code stringlengths 1 25.8M | language stringclasses 18 values | source stringclasses 4 values | repo stringclasses 78 values | path stringlengths 0 268 |
|---|---|---|---|---|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2014:
# Gabes Jean, naparuba@gmail.com
# Gerhard Lausser, Gerhard.Lausser@consol.de
# Gregory Starck, g.starck@gmail.com
# Hartmut Goebel, h.goebel@goebel-consult.de
#
# This file is part of Shinken.
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
"""
The objects package contains definition classes of the different objects
that can be declared in configuration files.
"""
from item import Item, Items
from timeperiod import Timeperiod, Timeperiods
from schedulingitem import SchedulingItem
from matchingitem import MatchingItem
from service import Service, Services
from command import Command, Commands
from resultmodulation import Resultmodulation, Resultmodulations
from escalation import Escalation, Escalations
from serviceescalation import Serviceescalation, Serviceescalations
from hostescalation import Hostescalation, Hostescalations
from host import Host, Hosts
from hostgroup import Hostgroup, Hostgroups
from realm import Realm, Realms
from contact import Contact, Contacts
from contactgroup import Contactgroup, Contactgroups
from notificationway import NotificationWay, NotificationWays
from servicegroup import Servicegroup, Servicegroups
from servicedependency import Servicedependency, Servicedependencies
from hostdependency import Hostdependency, Hostdependencies
from module import Module, Modules
from discoveryrule import Discoveryrule, Discoveryrules
from discoveryrun import Discoveryrun, Discoveryruns
from trigger import Trigger, Triggers
from businessimpactmodulation import Businessimpactmodulation, Businessimpactmodulations
from macromodulation import MacroModulation, MacroModulations
# from config import Config | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python3
import time, random, threading, random
salary = 999
def threadMethod(name):
print('Thread(%s:%s) Start' % (name, threading.current_thread().name))
for index in range(999999):
randomNumber = random.random()
global salary
salary = salary + randomNumber
salary = salary - randomNumber
def threadMethodLock(name, lock):
print('Thread(%s:%s) Start' % (name, threading.current_thread().name))
for index in range(999999):
randomNumber = random.random()
global salary
lock.acquire()
salary = salary + randomNumber
salary = salary - randomNumber
lock.release()
if __name__ == '__main__':
t1 = threading.Thread(target = threadMethod, name = 'threadMethod', args = ('threadMethod',))
t2 = threading.Thread(target = threadMethod, name = 'threadMethodCopy', args = ('threadMethodCopy',))
t1.start()
t2.start()
t1.join()
t2.join()
print(time.asctime(), salary)
lockk = threading.Lock()
salary = 999
t3 = threading.Thread(target = threadMethodLock, name = 'threadMethodLock', args = ('threadMethodLock',lockk))
t4 = threading.Thread(target = threadMethodLock, name = 'threadMethodLockCopy', args = ('threadMethodLockCopy',lockk))
t3.start()
t4.start()
t3.join()
t4.join()
print(time.asctime(), salary) | unknown | codeparrot/codeparrot-clean | ||
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing_extensions import Literal
from ..._models import BaseModel
__all__ = ["InputTokenCountResponse"]
class InputTokenCountResponse(BaseModel):
input_tokens: int
object: Literal["response.input_tokens"] | python | github | https://github.com/openai/openai-python | src/openai/types/responses/input_token_count_response.py |
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class R(models.Model):
is_default = models.BooleanField(default=False)
def __str__(self):
return "%s" % self.pk
def get_default_r():
return R.objects.get_or_create(is_default=True)[0].pk
class S(models.Model):
r = models.ForeignKey(R, models.CASCADE)
class T(models.Model):
s = models.ForeignKey(S, models.CASCADE)
class U(models.Model):
t = models.ForeignKey(T, models.CASCADE)
class RChild(R):
pass
class A(models.Model):
name = models.CharField(max_length=30)
auto = models.ForeignKey(R, models.CASCADE, related_name="auto_set")
auto_nullable = models.ForeignKey(R, models.CASCADE, null=True, related_name='auto_nullable_set')
setvalue = models.ForeignKey(R, models.SET(get_default_r), related_name='setvalue')
setnull = models.ForeignKey(R, models.SET_NULL, null=True, related_name='setnull_set')
setdefault = models.ForeignKey(R, models.SET_DEFAULT, default=get_default_r, related_name='setdefault_set')
setdefault_none = models.ForeignKey(
R, models.SET_DEFAULT,
default=None, null=True, related_name='setnull_nullable_set',
)
cascade = models.ForeignKey(R, models.CASCADE, related_name='cascade_set')
cascade_nullable = models.ForeignKey(R, models.CASCADE, null=True, related_name='cascade_nullable_set')
protect = models.ForeignKey(R, models.PROTECT, null=True)
donothing = models.ForeignKey(R, models.DO_NOTHING, null=True, related_name='donothing_set')
child = models.ForeignKey(RChild, models.CASCADE, related_name="child")
child_setnull = models.ForeignKey(RChild, models.SET_NULL, null=True, related_name="child_setnull")
# A OneToOneField is just a ForeignKey unique=True, so we don't duplicate
# all the tests; just one smoke test to ensure on_delete works for it as
# well.
o2o_setnull = models.ForeignKey(R, models.SET_NULL, null=True, related_name="o2o_nullable_set")
def create_a(name):
a = A(name=name)
for name in ('auto', 'auto_nullable', 'setvalue', 'setnull', 'setdefault',
'setdefault_none', 'cascade', 'cascade_nullable', 'protect',
'donothing', 'o2o_setnull'):
r = R.objects.create()
setattr(a, name, r)
a.child = RChild.objects.create()
a.child_setnull = RChild.objects.create()
a.save()
return a
class M(models.Model):
m2m = models.ManyToManyField(R, related_name="m_set")
m2m_through = models.ManyToManyField(R, through="MR", related_name="m_through_set")
m2m_through_null = models.ManyToManyField(R, through="MRNull", related_name="m_through_null_set")
class MR(models.Model):
m = models.ForeignKey(M, models.CASCADE)
r = models.ForeignKey(R, models.CASCADE)
class MRNull(models.Model):
m = models.ForeignKey(M, models.CASCADE)
r = models.ForeignKey(R, models.SET_NULL, null=True)
class Avatar(models.Model):
desc = models.TextField(null=True)
# This model is used to test a duplicate query regression (#25685)
class AvatarProxy(Avatar):
class Meta:
proxy = True
class User(models.Model):
avatar = models.ForeignKey(Avatar, models.CASCADE, null=True)
class HiddenUser(models.Model):
r = models.ForeignKey(R, models.CASCADE, related_name="+")
class HiddenUserProfile(models.Model):
user = models.ForeignKey(HiddenUser, models.CASCADE)
class M2MTo(models.Model):
pass
class M2MFrom(models.Model):
m2m = models.ManyToManyField(M2MTo)
class Parent(models.Model):
pass
class Child(Parent):
pass
class Base(models.Model):
pass
class RelToBase(models.Model):
base = models.ForeignKey(Base, models.DO_NOTHING) | unknown | codeparrot/codeparrot-clean | ||
"""OGGM tasks.
This module is simply a shortcut to the core functions
"""
from __future__ import absolute_import, division
# Entity tasks
from oggm.core.preprocessing.gis import define_glacier_region
from oggm.core.preprocessing.gis import glacier_masks
from oggm.core.preprocessing.centerlines import compute_centerlines
from oggm.core.preprocessing.centerlines import compute_downstream_lines
from oggm.core.preprocessing.centerlines import compute_downstream_bedshape
from oggm.core.preprocessing.geometry import catchment_area
from oggm.core.preprocessing.geometry import catchment_intersections
from oggm.core.preprocessing.geometry import initialize_flowlines
from oggm.core.preprocessing.geometry import catchment_width_geom
from oggm.core.preprocessing.geometry import catchment_width_correction
from oggm.core.preprocessing.climate import mu_candidates
from oggm.core.preprocessing.climate import process_cru_data
from oggm.core.preprocessing.climate import process_custom_climate_data
from oggm.core.preprocessing.climate import process_cesm_data
from oggm.core.preprocessing.climate import apparent_mb_from_linear_mb
from oggm.core.preprocessing.inversion import prepare_for_inversion
from oggm.core.preprocessing.inversion import volume_inversion
from oggm.core.preprocessing.inversion import filter_inversion_output
from oggm.core.preprocessing.inversion import distribute_thickness
from oggm.core.models.flowline import init_present_time_glacier
from oggm.core.models.flowline import random_glacier_evolution
from oggm.core.models.flowline import iterative_initial_glacier_search
# Global tasks
from oggm.core.preprocessing.climate import process_histalp_nonparallel
from oggm.core.preprocessing.climate import compute_ref_t_stars
from oggm.core.preprocessing.climate import distribute_t_stars
from oggm.core.preprocessing.climate import crossval_t_stars
from oggm.core.preprocessing.climate import quick_crossval_t_stars
from oggm.core.preprocessing.inversion import optimize_inversion_params | unknown | codeparrot/codeparrot-clean | ||
# Name: mapper_emodnet.py
# Purpose: Mapper for bathymetry data from EMODNet
# http://portal.emodnet-bathymetry.eu/
# Authors: Anton Korosov
# Licence: This file is part of NANSAT. You can redistribute it or modify
# under the terms of GNU General Public License, v.3
# http://www.gnu.org/licenses/gpl-3.0.html
import os
from dateutil.parser import parse
import numpy as np
from nansat.nsr import NSR
from nansat.vrt import VRT
from nansat.node import Node
from nansat.utils import gdal, ogr
from nansat.exceptions import WrongMapperError
class Mapper(VRT):
def __init__(self, inputFileName, gdalDataset, gdalMetadata, logLevel=30,
**kwargs):
# check if mapper fits
if not gdalMetadata:
raise WrongMapperError
if not os.path.splitext(inputFileName)[1] == '.mnt':
raise WrongMapperError
try:
mbNorthLatitude = float(gdalMetadata['NC_GLOBAL#mbNorthLatitude'])
mbSouthLatitude = float(gdalMetadata['NC_GLOBAL#mbSouthLatitude'])
mbEastLongitude = float(gdalMetadata['NC_GLOBAL#mbEastLongitude'])
mbWestLongitude = float(gdalMetadata['NC_GLOBAL#mbWestLongitude'])
mbProj4String = gdalMetadata['NC_GLOBAL#mbProj4String']
Number_lines = int(gdalMetadata['NC_GLOBAL#Number_lines'])
Number_columns = int(gdalMetadata['NC_GLOBAL#Number_columns'])
Element_x_size = float(gdalMetadata['NC_GLOBAL#Element_x_size'])
Element_y_size = float(gdalMetadata['NC_GLOBAL#Element_y_size'])
except:
raise WrongMapperError
# find subdataset with DEPTH
subDatasets = gdalDataset.GetSubDatasets()
dSourceFile = None
for subDataset in subDatasets:
if subDataset[0].endswith('.mnt":DEPTH'):
dSourceFile = subDataset[0]
if dSourceFile is None:
raise WrongMapperError
dSubDataset = gdal.Open(dSourceFile)
dMetadata = dSubDataset.GetMetadata()
try:
scale_factor = dMetadata['DEPTH#scale_factor']
add_offset = dMetadata['DEPTH#add_offset']
except:
raise WrongMapperError
geoTransform = [mbWestLongitude, Element_x_size, 0,
mbNorthLatitude, 0, -Element_y_size]
# create empty VRT dataset with geolocation only
self._init_from_dataset_params(Number_columns, Number_lines, geoTransform, NSR(mbProj4String).wkt, metadata=gdalMetadata)
metaDict = [{'src': {'SourceFilename': dSourceFile,
'SourceBand': 1,
'ScaleRatio' : scale_factor,
'ScaleOffset' : add_offset},
'dst': {'wkv': 'depth'}}]
# add bands with metadata and corresponding values to the empty VRT
self.create_bands(metaDict) | unknown | codeparrot/codeparrot-clean | ||
import { createCookie, isCookie } from "../cookies";
import type {
SessionStorage,
SessionIdStorageStrategy,
SessionData,
} from "../sessions";
import { warnOnceAboutSigningSessionCookie, createSession } from "../sessions";
interface CookieSessionStorageOptions {
/**
* The Cookie used to store the session data on the client, or options used
* to automatically create one.
*/
cookie?: SessionIdStorageStrategy["cookie"];
}
/**
* Creates and returns a SessionStorage object that stores all session data
* directly in the session cookie itself.
*
* This has the advantage that no database or other backend services are
* needed, and can help to simplify some load-balanced scenarios. However, it
* also has the limitation that serialized session data may not exceed the
* browser's maximum cookie size. Trade-offs!
*/
export function createCookieSessionStorage<
Data = SessionData,
FlashData = Data,
>({ cookie: cookieArg }: CookieSessionStorageOptions = {}): SessionStorage<
Data,
FlashData
> {
let cookie = isCookie(cookieArg)
? cookieArg
: createCookie(cookieArg?.name || "__session", cookieArg);
warnOnceAboutSigningSessionCookie(cookie);
return {
async getSession(cookieHeader, options) {
return createSession(
(cookieHeader && (await cookie.parse(cookieHeader, options))) || {},
);
},
async commitSession(session, options) {
let serializedCookie = await cookie.serialize(session.data, options);
if (serializedCookie.length > 4096) {
throw new Error(
"Cookie length will exceed browser maximum. Length: " +
serializedCookie.length,
);
}
return serializedCookie;
},
async destroySession(_session, options) {
return cookie.serialize("", {
...options,
maxAge: undefined,
expires: new Date(0),
});
},
};
} | typescript | github | https://github.com/remix-run/react-router | packages/react-router/lib/server-runtime/sessions/cookieStorage.ts |
"""
PostgreSQL database backend for Django.
Requires psycopg 2: http://initd.org/projects/psycopg2
"""
import sys
from django.db import utils
from django.db.backends import *
from django.db.backends.signals import connection_created
from django.db.backends.postgresql.operations import DatabaseOperations as PostgresqlDatabaseOperations
from django.db.backends.postgresql.client import DatabaseClient
from django.db.backends.postgresql.creation import DatabaseCreation
from django.db.backends.postgresql.version import get_version
from django.db.backends.postgresql_psycopg2.introspection import DatabaseIntrospection
from django.utils.safestring import SafeUnicode, SafeString
try:
import psycopg2 as Database
import psycopg2.extensions
except ImportError, e:
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e)
DatabaseError = Database.DatabaseError
IntegrityError = Database.IntegrityError
psycopg2.extensions.register_type(psycopg2.extensions.UNICODE)
psycopg2.extensions.register_adapter(SafeString, psycopg2.extensions.QuotedString)
psycopg2.extensions.register_adapter(SafeUnicode, psycopg2.extensions.QuotedString)
class CursorWrapper(object):
"""
A thin wrapper around psycopg2's normal cursor class so that we can catch
particular exception instances and reraise them with the right types.
"""
def __init__(self, cursor):
self.cursor = cursor
def execute(self, query, args=None):
try:
return self.cursor.execute(query, args)
except Database.IntegrityError, e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def executemany(self, query, args):
try:
return self.cursor.executemany(query, args)
except Database.IntegrityError, e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2]
except Database.DatabaseError, e:
raise utils.DatabaseError, utils.DatabaseError(*tuple(e)), sys.exc_info()[2]
def __getattr__(self, attr):
if attr in self.__dict__:
return self.__dict__[attr]
else:
return getattr(self.cursor, attr)
def __iter__(self):
return iter(self.cursor)
class DatabaseFeatures(BaseDatabaseFeatures):
needs_datetime_string_cast = False
can_return_id_from_insert = False
requires_rollback_on_dirty_transaction = True
has_real_datatype = True
can_defer_constraint_checks = True
class DatabaseOperations(PostgresqlDatabaseOperations):
def last_executed_query(self, cursor, sql, params):
# With psycopg2, cursor objects have a "query" attribute that is the
# exact query sent to the database. See docs here:
# http://www.initd.org/tracker/psycopg/wiki/psycopg2_documentation#postgresql-status-message-and-executed-query
return cursor.query
def return_insert_id(self):
return "RETURNING %s", ()
class DatabaseWrapper(BaseDatabaseWrapper):
vendor = 'postgresql'
operators = {
'exact': '= %s',
'iexact': '= UPPER(%s)',
'contains': 'LIKE %s',
'icontains': 'LIKE UPPER(%s)',
'regex': '~ %s',
'iregex': '~* %s',
'gt': '> %s',
'gte': '>= %s',
'lt': '< %s',
'lte': '<= %s',
'startswith': 'LIKE %s',
'endswith': 'LIKE %s',
'istartswith': 'LIKE UPPER(%s)',
'iendswith': 'LIKE UPPER(%s)',
}
def __init__(self, *args, **kwargs):
super(DatabaseWrapper, self).__init__(*args, **kwargs)
self.features = DatabaseFeatures(self)
autocommit = self.settings_dict["OPTIONS"].get('autocommit', False)
self.features.uses_autocommit = autocommit
self._set_isolation_level(int(not autocommit))
self.ops = DatabaseOperations(self)
self.client = DatabaseClient(self)
self.creation = DatabaseCreation(self)
self.introspection = DatabaseIntrospection(self)
self.validation = BaseDatabaseValidation(self)
def _cursor(self):
new_connection = False
set_tz = False
settings_dict = self.settings_dict
if self.connection is None:
new_connection = True
set_tz = settings_dict.get('TIME_ZONE')
if settings_dict['NAME'] == '':
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("You need to specify NAME in your Django settings file.")
conn_params = {
'database': settings_dict['NAME'],
}
conn_params.update(settings_dict['OPTIONS'])
if 'autocommit' in conn_params:
del conn_params['autocommit']
if settings_dict['USER']:
conn_params['user'] = settings_dict['USER']
if settings_dict['PASSWORD']:
conn_params['password'] = settings_dict['PASSWORD']
if settings_dict['HOST']:
conn_params['host'] = settings_dict['HOST']
if settings_dict['PORT']:
conn_params['port'] = settings_dict['PORT']
self.connection = Database.connect(**conn_params)
self.connection.set_client_encoding('UTF8')
self.connection.set_isolation_level(self.isolation_level)
connection_created.send(sender=self.__class__, connection=self)
cursor = self.connection.cursor()
cursor.tzinfo_factory = None
if new_connection:
if set_tz:
cursor.execute("SET TIME ZONE %s", [settings_dict['TIME_ZONE']])
if not hasattr(self, '_version'):
self.__class__._version = get_version(cursor)
if self._version[0:2] < (8, 0):
# No savepoint support for earlier version of PostgreSQL.
self.features.uses_savepoints = False
if self.features.uses_autocommit:
if self._version[0:2] < (8, 2):
# FIXME: Needs extra code to do reliable model insert
# handling, so we forbid it for now.
from django.core.exceptions import ImproperlyConfigured
raise ImproperlyConfigured("You cannot use autocommit=True with PostgreSQL prior to 8.2 at the moment.")
else:
# FIXME: Eventually we're enable this by default for
# versions that support it, but, right now, that's hard to
# do without breaking other things (#10509).
self.features.can_return_id_from_insert = True
return CursorWrapper(cursor)
def _enter_transaction_management(self, managed):
"""
Switch the isolation level when needing transaction support, so that
the same transaction is visible across all the queries.
"""
if self.features.uses_autocommit and managed and not self.isolation_level:
self._set_isolation_level(1)
def _leave_transaction_management(self, managed):
"""
If the normal operating mode is "autocommit", switch back to that when
leaving transaction management.
"""
if self.features.uses_autocommit and not managed and self.isolation_level:
self._set_isolation_level(0)
def _set_isolation_level(self, level):
"""
Do all the related feature configurations for changing isolation
levels. This doesn't touch the uses_autocommit feature, since that
controls the movement *between* isolation levels.
"""
assert level in (0, 1)
try:
if self.connection is not None:
self.connection.set_isolation_level(level)
finally:
self.isolation_level = level
self.features.uses_savepoints = bool(level)
def _commit(self):
if self.connection is not None:
try:
return self.connection.commit()
except Database.IntegrityError, e:
raise utils.IntegrityError, utils.IntegrityError(*tuple(e)), sys.exc_info()[2] | unknown | codeparrot/codeparrot-clean | ||
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from abc import ABCMeta
from pyspark import SparkContext
from pyspark.sql import DataFrame
from pyspark.ml.param import Params
from pyspark.ml.pipeline import Estimator, Transformer, Model
from pyspark.mllib.common import inherit_doc, _java2py, _py2java
def _jvm():
"""
Returns the JVM view associated with SparkContext. Must be called
after SparkContext is initialized.
"""
jvm = SparkContext._jvm
if jvm:
return jvm
else:
raise AttributeError("Cannot load _jvm from SparkContext. Is SparkContext initialized?")
@inherit_doc
class JavaWrapper(Params):
"""
Utility class to help create wrapper classes from Java/Scala
implementations of pipeline components.
"""
__metaclass__ = ABCMeta
#: The wrapped Java companion object. Subclasses should initialize
#: it properly. The param values in the Java object should be
#: synced with the Python wrapper in fit/transform/evaluate/copy.
_java_obj = None
@staticmethod
def _new_java_obj(java_class, *args):
"""
Construct a new Java object.
"""
sc = SparkContext._active_spark_context
java_obj = _jvm()
for name in java_class.split("."):
java_obj = getattr(java_obj, name)
java_args = [_py2java(sc, arg) for arg in args]
return java_obj(*java_args)
def _make_java_param_pair(self, param, value):
"""
Makes a Java parm pair.
"""
sc = SparkContext._active_spark_context
param = self._resolveParam(param)
java_param = self._java_obj.getParam(param.name)
java_value = _py2java(sc, value)
return java_param.w(java_value)
def _transfer_params_to_java(self):
"""
Transforms the embedded params to the companion Java object.
"""
paramMap = self.extractParamMap()
for param in self.params:
if param in paramMap:
pair = self._make_java_param_pair(param, paramMap[param])
self._java_obj.set(pair)
def _transfer_params_from_java(self):
"""
Transforms the embedded params from the companion Java object.
"""
sc = SparkContext._active_spark_context
for param in self.params:
if self._java_obj.hasParam(param.name):
java_param = self._java_obj.getParam(param.name)
if self._java_obj.isDefined(java_param):
value = _java2py(sc, self._java_obj.getOrDefault(java_param))
self._paramMap[param] = value
@staticmethod
def _empty_java_param_map():
"""
Returns an empty Java ParamMap reference.
"""
return _jvm().org.apache.spark.ml.param.ParamMap()
@inherit_doc
class JavaEstimator(Estimator, JavaWrapper):
"""
Base class for :py:class:`Estimator`s that wrap Java/Scala
implementations.
"""
__metaclass__ = ABCMeta
def _create_model(self, java_model):
"""
Creates a model from the input Java model reference.
"""
raise NotImplementedError()
def _fit_java(self, dataset):
"""
Fits a Java model to the input dataset.
:param dataset: input dataset, which is an instance of
:py:class:`pyspark.sql.DataFrame`
:param params: additional params (overwriting embedded values)
:return: fitted Java model
"""
self._transfer_params_to_java()
return self._java_obj.fit(dataset._jdf)
def _fit(self, dataset):
java_model = self._fit_java(dataset)
return self._create_model(java_model)
@inherit_doc
class JavaTransformer(Transformer, JavaWrapper):
"""
Base class for :py:class:`Transformer`s that wrap Java/Scala
implementations. Subclasses should ensure they have the transformer Java object
available as _java_obj.
"""
__metaclass__ = ABCMeta
def _transform(self, dataset):
self._transfer_params_to_java()
return DataFrame(self._java_obj.transform(dataset._jdf), dataset.sql_ctx)
@inherit_doc
class JavaModel(Model, JavaTransformer):
"""
Base class for :py:class:`Model`s that wrap Java/Scala
implementations. Subclasses should inherit this class before
param mix-ins, because this sets the UID from the Java model.
"""
__metaclass__ = ABCMeta
def __init__(self, java_model):
"""
Initialize this instance with a Java model object.
Subclasses should call this constructor, initialize params,
and then call _transformer_params_from_java.
"""
super(JavaModel, self).__init__()
self._java_obj = java_model
self.uid = java_model.uid()
def copy(self, extra=None):
"""
Creates a copy of this instance with the same uid and some
extra params. This implementation first calls Params.copy and
then make a copy of the companion Java model with extra params.
So both the Python wrapper and the Java model get copied.
:param extra: Extra parameters to copy to the new instance
:return: Copy of this instance
"""
if extra is None:
extra = dict()
that = super(JavaModel, self).copy(extra)
that._java_obj = self._java_obj.copy(self._empty_java_param_map())
that._transfer_params_to_java()
return that
def _call_java(self, name, *args):
m = getattr(self._java_obj, name)
sc = SparkContext._active_spark_context
java_args = [_py2java(sc, arg) for arg in args]
return _java2py(sc, m(*java_args)) | unknown | codeparrot/codeparrot-clean | ||
import { test } from '../../test';
export default test({
error: {
code: 'element_unclosed',
message: '`<script>` was left open',
position: [32, 32]
}
}); | javascript | github | https://github.com/sveltejs/svelte | packages/svelte/tests/compiler-errors/samples/script-unclosed/_config.js |
#!/usr/bin/env python
# coding: utf-8
from __future__ import (absolute_import, division,
print_function, unicode_literals)
"""
test_django-teryt
------------
Tests for `django-teryt` modules module.
"""
from django.utils import six
from django.test import TestCase
from django.db import models
from ..models import (RodzajMiejscowosci, JednostkaAdministracyjna,
Miejscowosc, Ulica)
from .factories import (RodzajMiejscowosciFactory,
JednostkaAdministracyjnaFactory,
MiejscowoscFactory, UlicaFactory)
class MixinTestObjectsManager(object):
def test_objects_model_manager(self):
self.assertIsInstance(JednostkaAdministracyjna.objects, models.Manager)
class TestRodzajMiejscowosci(TestCase, MixinTestObjectsManager):
def test_str(self):
rm = RodzajMiejscowosciFactory(id='96', nazwa='miasto')
self.assertEqual(six.text_type(rm), '96: miasto')
def test_set_val(self):
rm = RodzajMiejscowosci()
rm.set_val({'RM': '01',
'STAN_NA': '2013-02-28',
'NAZWA_RM': 'wieś'})
self.assertEqual(rm.nazwa, 'wieś')
self.assertEqual(rm.id, '01')
self.assertEqual(rm.stan_na, '2013-02-28')
class TestJednostkaAdministracyjna(TestCase, MixinTestObjectsManager):
def setUp(self):
self.rm_miasto = RodzajMiejscowosciFactory(
id='96',
nazwa='miasto')
self.gmina = JednostkaAdministracyjnaFactory(
id='0201011',
nazwa='Bolesławiec',
nazwa_dod='gmina miejska')
self.gmina_nowogrodziec = JednostkaAdministracyjnaFactory(
id='0201044',
nazwa='Nowogrodziec',
nazwa_dod='miasto')
self.powiat = JednostkaAdministracyjnaFactory(
id='0201',
nazwa='bolesławiecki',
nazwa_dod='powiat')
self.wojewodztwo = JednostkaAdministracyjnaFactory(
id='02',
nazwa='DOLNOŚLĄSKIE',
nazwa_dod='wojewdztwo')
self.boleslawiec = MiejscowoscFactory(
symbol='0935989',
jednostka=self.gmina,
miejscowosc_nadrzedna=None,
nazwa='Bolesławiec',
rodzaj_miejscowosci=self.rm_miasto)
self.nowogrodziec = MiejscowoscFactory(
symbol='0936262',
jednostka=self.gmina_nowogrodziec,
miejscowosc_nadrzedna=None,
nazwa='Nowogrodziec',
rodzaj_miejscowosci=self.rm_miasto)
def test_str(self):
self.assertEqual(six.text_type(self.gmina), '0201011: Bolesławiec')
def test_set_val(self):
gmina = JednostkaAdministracyjna()
gmina.set_val({
'GMI': '01',
'POW': '01',
'STAN_NA': '2013-01-01',
'NAZDOD': 'gmina miejska',
'RODZ': '1',
'NAZWA': 'Bolesławiec',
'WOJ': '02'
})
wojewodztwo = JednostkaAdministracyjna()
wojewodztwo.set_val({
'GMI': None,
'POW': None,
'STAN_NA': '2013-01-01',
'NAZDOD': 'województwo',
'RODZ': None,
'NAZWA': u'DOLNOŚLĄSKIE',
'WOJ': '02'})
# Common
self.assertEqual(gmina.stan_na, '2013-01-01')
self.assertEqual(gmina.aktywny, False)
# JednostkaAdministracyjna - gmina
self.assertEqual(gmina.id, '0201011')
self.assertEqual(gmina.nazwa, 'Bolesławiec')
self.assertEqual(gmina.nazwa_dod, 'gmina miejska')
self.assertEqual(gmina.typ, 'GMI')
# JednostkaAdministracyjna - województwo
self.assertEqual(wojewodztwo.id, '02')
self.assertEqual(wojewodztwo.nazwa, 'dolnośląskie')
self.assertEqual(wojewodztwo.nazwa_dod, 'województwo')
self.assertEqual(wojewodztwo.typ, 'WOJ')
def test_parents(self):
self.assertEqual(self.gmina.powiat(), self.powiat)
self.assertEqual(self.gmina.wojewodztwo(), self.wojewodztwo)
self.assertEqual(self.powiat.wojewodztwo(), self.wojewodztwo)
def test_managers_wojewodztwa(self):
self.assertIsInstance(JednostkaAdministracyjna.wojewodztwa,
models.Manager)
self.assertEqual(JednostkaAdministracyjna.wojewodztwa.count(), 1)
JednostkaAdministracyjna.wojewodztwa.get(id='02')
def test_managers_powiaty(self):
self.assertIsInstance(JednostkaAdministracyjna.powiaty, models.Manager)
self.assertEqual(JednostkaAdministracyjna.powiaty.count(), 1)
JednostkaAdministracyjna.powiaty.get(id='0201')
def test_managers_gminy(self):
self.assertIsInstance(JednostkaAdministracyjna.gminy, models.Manager)
self.assertEqual(JednostkaAdministracyjna.gminy.count(), 2)
JednostkaAdministracyjna.gminy.get(id='0201011')
def test_miejscowosci(self):
self.assertEqual(self.gmina.miejscowosci().count(), 1)
self.assertEqual(self.powiat.miejscowosci().count(), 2)
self.assertEqual(self.wojewodztwo.miejscowosci().count(), 2)
self.gmina.miejscowosci().get(symbol='0935989')
class TestMiejscowosc(TestCase, MixinTestObjectsManager):
def setUp(self):
self.miejscowosc = MiejscowoscFactory(
symbol='0861110',
miejscowosc_nadrzedna=None,
nazwa='Strzygowska Kolonia',
rodzaj_miejscowosci__id='02',
rodzaj_miejscowosci__nazwa='kolonia')
self.warszawa = MiejscowoscFactory(
symbol='0918123',
miejscowosc_nadrzedna=None,
nazwa='Warszawa',
rodzaj_miejscowosci__id='96',
rodzaj_miejscowosci__nazwa='miasto')
self.wies = MiejscowoscFactory(
symbol='0005546',
miejscowosc_nadrzedna=None,
nazwa='Wolica',
rodzaj_miejscowosci__id='01',
rodzaj_miejscowosci__nazwa='wieś')
def test_managers_miasta(self):
self.assertIsInstance(Miejscowosc.miasta, models.Manager)
self.assertEqual(Miejscowosc.miasta.count(), 1)
Miejscowosc.miasta.get(symbol='0918123')
def test_managers_wsie(self):
self.assertIsInstance(Miejscowosc.wsie, models.Manager)
self.assertEqual(Miejscowosc.wsie.count(), 1)
Miejscowosc.wsie.get(symbol='0005546')
def test_str(self):
self.assertEqual(six.text_type(self.miejscowosc),
'0861110: Strzygowska Kolonia')
def test_set_val(self):
m_dict = {
'GMI': '06',
'RODZ_GMI': '5',
'POW': '18',
'STAN_NA': '2013-03-06',
'SYM': '0861110',
'NAZWA': 'Strzygowska Kolonia',
'WOJ': '04',
'RM': '02',
'SYMPOD': '0861110',
'MZ': '1'
}
miejscowosc = Miejscowosc()
miejscowosc.set_val(m_dict)
# Common
self.assertEqual(miejscowosc.stan_na, '2013-03-06')
self.assertEqual(miejscowosc.aktywny, False)
# Miejscowosc
self.assertIsNone(miejscowosc.miejscowosc_nadrzedna)
self.assertEqual(miejscowosc.symbol, '0861110')
self.assertEqual(miejscowosc.jednostka_id, '0418065')
self.assertEqual(miejscowosc.nazwa, 'Strzygowska Kolonia')
# RodzajMiejscowosci instance made in setUp()
self.assertEqual(miejscowosc.rodzaj_miejscowosci.nazwa, 'kolonia')
m_dict['SYMPOD'] = '1234567'
miejscowosc2 = Miejscowosc()
miejscowosc2.set_val(m_dict)
self.assertEqual(miejscowosc2.miejscowosc_nadrzedna_id, '1234567')
class TestUlica(TestCase, MixinTestObjectsManager):
def setUp(self):
self.ulica1 = UlicaFactory(
miejscowosc__miejscowosc_nadrzedna=None
)
self.ulica2 = UlicaFactory(
cecha='pl.',
nazwa_1='Hoffa',
nazwa_2='Bogumiła',
miejscowosc__miejscowosc_nadrzedna=None
)
def test_str(self):
self.assertEqual(six.text_type(self.ulica1), 'ul. {} ({})'.format(
self.ulica1.nazwa_1, self.ulica1.miejscowosc.nazwa))
self.assertEqual(six.text_type(self.ulica2),
'pl. Bogumiła Hoffa ({})'.format(
self.ulica2.miejscowosc.nazwa))
def test_set_val(self):
m_dict = {
'GMI': '03',
'RODZ_GMI': '2',
'NAZWA_1': 'Cicha',
'NAZWA_2': None,
'POW': '03',
'STAN_NA': '2013-12-16',
'SYM': '0185962',
'CECHA': 'ul.',
'WOJ': '08',
'SYM_UL': '02974'
}
ulica = Ulica()
ulica.set_val(m_dict)
# Common
self.assertEqual(ulica.stan_na, '2013-12-16')
self.assertEqual(ulica.aktywny, False)
# Ulica
self.assertEqual(ulica.id, '018596202974')
self.assertEqual(ulica.miejscowosc_id, '0185962')
self.assertEqual(ulica.symbol_ulicy, '02974')
self.assertEqual(ulica.cecha, 'ul.')
self.assertEqual(ulica.nazwa_1, 'Cicha')
self.assertIsNone(ulica.nazwa_2) | unknown | codeparrot/codeparrot-clean | ||
import sys
from yaku.scheduler \
import \
run_tasks
from yaku.context \
import \
get_bld, get_cfg
from yaku.conftests.fconftests \
import \
check_fcompiler, check_fortran_verbose_flag, \
check_fortran_runtime_flags, check_fortran_dummy_main, \
check_fortran_mangling
def configure(ctx):
ctx.use_tools(["ctasks", "cxxtasks"])
ctx.load_tool("fortran")
ctx.builders["fortran"].configure(candidates=["gfortran"])
check_fcompiler(ctx)
check_fortran_verbose_flag(ctx)
check_fortran_runtime_flags(ctx)
check_fortran_dummy_main(ctx)
check_fortran_mangling(ctx)
def build(ctx):
builder = ctx.builders["fortran"]
builder.program("fbar", ["src/bar.f"])
builder = ctx.builders["ctasks"]
builder.program("cbar", ["src/bar.c"])
builder = ctx.builders["cxxtasks"]
builder.program("cxxbar", ["src/bar.cxx"])
if __name__ == "__main__":
ctx = get_cfg()
configure(ctx)
ctx.store()
ctx = get_bld()
build(ctx)
run_tasks(ctx)
ctx.store() | unknown | codeparrot/codeparrot-clean | ||
# Copyright (c) 2011-2021, Manfred Moitzi
# License: MIT License
from collections import namedtuple
from enum import Enum
from typing import (
Optional,
Dict,
List,
Tuple,
TYPE_CHECKING,
Iterable,
Callable,
Any,
Union,
)
from .const import DXFAttributeError, DXF12
import copy
if TYPE_CHECKING:
from ezdxf.eztypes import DXFEntity, TagValue
DefSubclass = namedtuple("DefSubclass", "name attribs")
VIRTUAL_TAG = -666
class XType(Enum):
"""Extended Attribute Types"""
point2d = 1 # 2D points only
point3d = 2 # 3D points only
any_point = 3 # 2D or 3D points
callback = 4 # callback attribute
def group_code_mapping(
subclass: DefSubclass, *, ignore: Iterable[int] = None
) -> Dict[int, Union[str, List[str]]]:
# Unique group codes are stored as group_code <int>: name <str>
# Duplicate group codes are stored as group_code <int>: [name1, name2, ...] <list>
# The order of appearance is important, therefore also callback attributes
# have to be included, but they should not be loaded into the DXF namespace.
mapping: Dict[int, Union[str, List[str]]] = dict()
for name, dxfattrib in subclass.attribs.items():
if dxfattrib.xtype == XType.callback:
# Mark callback attributes for special treatment as invalid
# Python name:
name = "*" + name
code = dxfattrib.code
existing_data: Union[None, str, List[str]] = mapping.get(code)
if existing_data is None:
mapping[code] = name
else:
if isinstance(existing_data, str):
existing_data = [existing_data]
mapping[code] = existing_data
assert isinstance(existing_data, list)
existing_data.append(name)
if ignore:
# Mark these tags as "*IGNORE" to be ignored,
# but they are not real callbacks! See POLYLINE for example!
for code in ignore:
mapping[code] = "*IGNORE"
return mapping
# Unique object as marker
RETURN_DEFAULT = object()
class DXFAttr:
"""Represents a DXF attribute for an DXF entity, accessible by the
DXF namespace :attr:`DXFEntity.dxf` like ``entity.dxf.color = 7``.
This definitions are immutable by design not by implementation.
Extended Attribute Types
------------------------
- XType.point2d: 2D points only
- XType.point3d: 3D point only
- XType.any_point: mixed 2D/3D point
- XType.callback: Calls get_value(entity) to get the value of DXF
attribute 'name', and calls set_value(entity, value) to set value
of DXF attribute 'name'.
See example definition: ezdxf.entities.dxfgfx.acdb_entity.
"""
def __init__(
self,
code: int,
xtype: XType = None,
default=None,
optional: bool = False,
dxfversion: str = DXF12,
getter: str = "",
setter: str = "",
alias: str = "",
validator: Optional[Callable[[Any], bool]] = None,
fixer: Optional[Callable[[Any], Any]] = None,
):
# Attribute name set by DXFAttributes.__init__()
self.name: str = ""
# DXF group code
self.code: int = code
# Extended attribute type:
self.xtype: Optional[XType] = xtype
# DXF default value
self.default: TagValue = default
# If optional is True, this attribute will be exported to DXF files
# only if the given value differs from default value.
self.optional: bool = optional
# This attribute is valid for all DXF versions starting from the
# specified DXF version, default is DXF12 = 'AC1009'
self.dxfversion: str = dxfversion
# DXF entity getter method name for callback attributes
self.getter: str = getter
# DXF entity setter method name for callback attributes
self.setter: str = setter
# Alternative name for this attribute
self.alias: str = alias
# Returns True if given value is valid - the validator should be as
# fast as possible!
self.validator: Optional[Callable[[Any], bool]] = validator
# Returns a fixed value for invalid attributes, the fixer is called
# only if the validator returns False.
if fixer is RETURN_DEFAULT:
fixer = self._return_default
self.fixer: Optional[Callable[[Any], Any]] = fixer
def _return_default(self, x: Any) -> Any:
return self.default
def __str__(self) -> str:
return f"({self.name}, {self.code})"
def __repr__(self) -> str:
return "DXFAttr" + self.__str__()
def get_callback_value(self, entity: "DXFEntity") -> "TagValue":
"""
Executes a callback function in 'entity' to get a DXF value.
Callback function is defined by self.getter as string.
Args:
entity: DXF entity
Raises:
AttributeError: getter method does not exist
TypeError: getter is None
Returns:
DXF attribute value
"""
try:
return getattr(entity, self.getter)()
except AttributeError:
raise DXFAttributeError(
f"DXF attribute {self.name}: invalid getter {self.getter}."
)
except TypeError:
raise DXFAttributeError(f"DXF attribute {self.name} has no getter.")
def set_callback_value(
self, entity: "DXFEntity", value: "TagValue"
) -> None:
"""Executes a callback function in 'entity' to set a DXF value.
Callback function is defined by self.setter as string.
Args:
entity: DXF entity
value: DXF attribute value
Raises:
AttributeError: setter method does not exist
TypeError: setter is None
"""
try:
getattr(entity, self.setter)(value)
except AttributeError:
raise DXFAttributeError(
f"DXF attribute {self.name}: invalid setter {self.setter}."
)
except TypeError:
raise DXFAttributeError(f"DXF attribute {self.name} has no setter.")
def is_valid_value(self, value: Any) -> bool:
if self.validator:
return self.validator(value)
else:
return True
class DXFAttributes:
__slots__ = ("_attribs",)
def __init__(self, *subclassdefs: DefSubclass):
self._attribs: Dict[str, DXFAttr] = dict()
for subclass in subclassdefs:
for name, dxfattrib in subclass.attribs.items():
dxfattrib.name = name
self._attribs[name] = dxfattrib
if dxfattrib.alias:
alias = copy.copy(dxfattrib)
alias.name = dxfattrib.alias
alias.alias = dxfattrib.name
self._attribs[dxfattrib.alias] = alias
def __contains__(self, name: str) -> bool:
return name in self._attribs
def get(self, key: str) -> Optional[DXFAttr]:
return self._attribs.get(key)
def build_group_code_items(
self, func=lambda x: True
) -> Iterable[Tuple[int, str]]:
for name, attrib in self._attribs.items():
# code < 0 is internal tag
if attrib.code > 0 and func(name):
yield attrib.code, name | unknown | codeparrot/codeparrot-clean | ||
# Contributing to Vapor
👋 Welcome to the Vapor team!
## Testing
Once in Xcode, select the `vapor-Package` scheme and use `CMD+U` to run the tests.
You can use the `Development` executables for testing out your code.
Don't forget to add tests for your new features.
If you are fixing a single GitHub issue in particular, you can add a test named `testGH<issue number>` to ensure
that your fix is working. This will also help prevent regression.
## API Documentation
Make sure that any new public API is covered by API documentation and update any existing documentation where relevant. See [Formatting Quick Help](https://developer.apple.com/library/archive/documentation/Xcode/Reference/xcode_markup_formatting_ref/SymbolDocumentation.html#//apple_ref/doc/uid/TP40016497-CH51-SW1) and [Swift Documentation](https://nshipster.com/swift-documentation/) for more information.
## Style Guide
When contributing code to Vapor, please try to follow existing style for consistency.
### Xcode Formatting
Avoid using "Xcode style" indentation where possible. This can be difficult to recreate in other editors.
❌
```swift
func foo(bar: String,
baz: Int) {
...
}
```
Use normal indentation instead.
✅
```swift
func foo(
bar: String,
baz: Int
) {
...
}
```
### Explicit self
When accessing member properties and methods, use explicit `self`.
```swift
struct Foo {
var bar: Int
func baz() {
// ❌
print(bar)
// ✅
print(self.bar)
}
}
```
This makes it easier to tell whether a local variable is being used or not, especially when reading code without syntax highlighting.
## SemVer
Vapor follows [SemVer](https://semver.org). This means that any changes to the source code that can cause
existing code to stop compiling _must_ wait until the next major version to be included.
Code that is only additive and will not break any existing code can be included in the next minor release.
## Releases
All vapor/* packages use automated releases. When a PR is merged, the Vapor bot will check for certain PR labels and ship a new release right away. This ensures users get access to new features as soon as possible and helps to reduce human error.
The release will use the PR's title and body directly. It will also include a note about who authored the release and who merged it.
### Release title
The release title should be concise description. For example:
- ✅ HTTP streaming improvements
- ✅ Add case-insensitive routing
- ✅ Fix `routes` command symbol usage
The release titles should use sentence capitalization and not be too verbose. They should also use present tense.
- ❌ Fix `routes` Command Symbol Usage
- ❌ Add new method on RouteBuilder called `caseInsensitive` which can be used to enable case-insensitive routing
- ❌ Fixed `routes` command symbol usage
### Release body
The release body (or description) should contain more in-depth information about the change and code examples if possible.
✅
````md
Allows configuring case-insensitive routing (#2354, fixes #1928).
```swift
// Enables case-insensitive routing.
// Defaults to false.
app.routes.caseInsensitive = true
```
````
The release body should include links to any associated PRs and issues. Issues that are fixed by this change should be prefixed with `fixes` so that they are closed automatically. The first line of the release body should be a concise description of the change. This can be followed by a more detailed explanation and code examples.
Releases with a large number of changes can separated using bullets. Special comments or notes can be added using quote blocks `>`.
✅
```md
Improves HTTP request and response streaming (#2404).
- Streaming request body skipping will only happen if the entire response has been sent before the user _starts_ reading the request body (fixes #2393).
> Note: Previously, streaming request bodies would be drained automatically by Vapor as soon as the response head was sent. This made it impossible to implement realtime streaming, like an echo server. With these changes, you have much more control over streaming HTTP while still preventing hanging if the request body is ignored entirely.
- Response body stream now supports omitting the `count` parameter (fixes #2393).
> Note: Previously streaming bodies required a count and would always set the `content-length` header. Now, setting a count of `-1` indicates a stream with indeterminate length. `-1` will be used if the stream count is omitted. This results in `transfer-encoding: chunked` being used automatically.
```
Release bodies should be in present tense third person. They should mention only information relevant to release notes. Any additional information or questions can be included in PR comments.
❌
```md
I've implemented two fixes to HTTP request streaming. I'm wondering if I need to implement three?
Here's what I've done so far:
...
```
The following PR labels are supported by Vapor's release bot.
- `semver-patch`: Bumps the patch version. 0.0.x
- `semver-minor`: Bumps the minor version: 0.x.0
- `semver-major`: Bumps the major version: x.0.0 (rarely used)
- `release`: Advances the pre-release identifier (alpha -> beta -> rc)
When Vapor's release bot makes a release, it will automatically notify the `#release` channel in Vapor's team chat and include a link to the release on the merged PR.
## Maintainers
Each repo under the Vapor organization has at least one [volunteer maintainer.](maintainers.md) [vapor/vapor's](https://github.com/vapor/vapor) current list of maintainers is:
- [@MrLotU](https://github.com/MrLotU)
- [@Joannis](https://github.com/Joannis)
- [@0xTim](https://github.com/0xtim)
- [@gwynne](https://github.com/gwynne)
- [@siemensikkema](https://github.com/siemensikkema)
## Extras
Here are some bash functions to help you test Swift on Linux easily from macOS (you must have Docker installed).
### Swift Linux
```bash
# Starts docker-machine and exports env variables.
_docker_start() {
docker-machine start default
eval "$(docker-machine env default)"
}
alias docker-start='_docker_start'
# Executes /usr/bin/swift in a Swift 4.1 docker container
_swift_linux() {
_docker_start
docker run -it -v $PWD:/root/code -w /root/code norionomura/swift:swift-4.1-branch /usr/bin/swift $1
}
alias swift-linux='_swift_linux'
```
You can add these methods to your `~/.bash_profile`. Just run `source ~/.bash_profile` after or restart your terminal.
Once added, you can run the following to test Swift projects on both macOS and Linux.
```sh
swift test
swift-linux test
```
### Clean SPM
Add the following code to your bash profile to make cleaning SPM temporary files easy.
```bash
# Cleans out all temporary SPM files
_spm_clean() {
rm Package.resolved
rm -rf .build
rm -rf *.xcodeproj
rm -rf Packages
}
alias spm-clean='_spm_clean'
```
Once added, you can run `spm-clean`.
```sh
spm-clean
```
----------
Join us on Discord if you have any questions: [http://vapor.team](http://vapor.team).
— Thanks! 🙌 | unknown | github | https://github.com/vapor/vapor | .github/contributing.md |
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of logilab-common.
#
# logilab-common is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option) any
# later version.
#
# logilab-common is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with logilab-common. If not, see <http://www.gnu.org/licenses/>.
"""Add an abstraction level to transparently import optik classes from optparse
(python >= 2.3) or the optik package.
It also defines three new types for optik/optparse command line parser :
* regexp
argument of this type will be converted using re.compile
* csv
argument of this type will be converted using split(',')
* yn
argument of this type will be true if 'y' or 'yes', false if 'n' or 'no'
* named
argument of this type are in the form <NAME>=<VALUE> or <NAME>:<VALUE>
* password
argument of this type wont be converted but this is used by other tools
such as interactive prompt for configuration to double check value and
use an invisible field
* multiple_choice
same as default "choice" type but multiple choices allowed
* file
argument of this type wont be converted but checked that the given file exists
* color
argument of this type wont be converted but checked its either a
named color or a color specified using hexadecimal notation (preceded by a #)
* time
argument of this type will be converted to a float value in seconds
according to time units (ms, s, min, h, d)
* bytes
argument of this type will be converted to a float value in bytes
according to byte units (b, kb, mb, gb, tb)
"""
__docformat__ = "restructuredtext en"
import re
import sys
import time
from copy import copy
from os.path import exists
# python >= 2.3
from optparse import OptionParser as BaseParser, Option as BaseOption, \
OptionGroup, OptionContainer, OptionValueError, OptionError, \
Values, HelpFormatter, NO_DEFAULT, SUPPRESS_HELP
try:
from mx import DateTime
HAS_MX_DATETIME = True
except ImportError:
HAS_MX_DATETIME = False
OPTPARSE_FORMAT_DEFAULT = sys.version_info >= (2, 4)
from logilab.common.textutils import splitstrip
def check_regexp(option, opt, value):
"""check a regexp value by trying to compile it
return the compiled regexp
"""
if hasattr(value, 'pattern'):
return value
try:
return re.compile(value)
except ValueError:
raise OptionValueError(
"option %s: invalid regexp value: %r" % (opt, value))
def check_csv(option, opt, value):
"""check a csv value by trying to split it
return the list of separated values
"""
if isinstance(value, (list, tuple)):
return value
try:
return splitstrip(value)
except ValueError:
raise OptionValueError(
"option %s: invalid csv value: %r" % (opt, value))
def check_yn(option, opt, value):
"""check a yn value
return true for yes and false for no
"""
if isinstance(value, int):
return bool(value)
if value in ('y', 'yes'):
return True
if value in ('n', 'no'):
return False
msg = "option %s: invalid yn value %r, should be in (y, yes, n, no)"
raise OptionValueError(msg % (opt, value))
def check_named(option, opt, value):
"""check a named value
return a dictionary containing (name, value) associations
"""
if isinstance(value, dict):
return value
values = []
for value in check_csv(option, opt, value):
if value.find('=') != -1:
values.append(value.split('=', 1))
elif value.find(':') != -1:
values.append(value.split(':', 1))
if values:
return dict(values)
msg = "option %s: invalid named value %r, should be <NAME>=<VALUE> or \
<NAME>:<VALUE>"
raise OptionValueError(msg % (opt, value))
def check_password(option, opt, value):
"""check a password value (can't be empty)
"""
# no actual checking, monkey patch if you want more
return value
def check_file(option, opt, value):
"""check a file value
return the filepath
"""
if exists(value):
return value
msg = "option %s: file %r does not exist"
raise OptionValueError(msg % (opt, value))
# XXX use python datetime
def check_date(option, opt, value):
"""check a file value
return the filepath
"""
try:
return DateTime.strptime(value, "%Y/%m/%d")
except DateTime.Error :
raise OptionValueError(
"expected format of %s is yyyy/mm/dd" % opt)
def check_color(option, opt, value):
"""check a color value and returns it
/!\ does *not* check color labels (like 'red', 'green'), only
checks hexadecimal forms
"""
# Case (1) : color label, we trust the end-user
if re.match('[a-z0-9 ]+$', value, re.I):
return value
# Case (2) : only accepts hexadecimal forms
if re.match('#[a-f0-9]{6}', value, re.I):
return value
# Else : not a color label neither a valid hexadecimal form => error
msg = "option %s: invalid color : %r, should be either hexadecimal \
value or predefined color"
raise OptionValueError(msg % (opt, value))
def check_time(option, opt, value):
from logilab.common.textutils import TIME_UNITS, apply_units
if isinstance(value, (int, long, float)):
return value
return apply_units(value, TIME_UNITS)
def check_bytes(option, opt, value):
from logilab.common.textutils import BYTE_UNITS, apply_units
if hasattr(value, '__int__'):
return value
return apply_units(value, BYTE_UNITS)
import types
class Option(BaseOption):
"""override optik.Option to add some new option types
"""
TYPES = BaseOption.TYPES + ('regexp', 'csv', 'yn', 'named', 'password',
'multiple_choice', 'file', 'color',
'time', 'bytes')
ATTRS = BaseOption.ATTRS + ['hide', 'level']
TYPE_CHECKER = copy(BaseOption.TYPE_CHECKER)
TYPE_CHECKER['regexp'] = check_regexp
TYPE_CHECKER['csv'] = check_csv
TYPE_CHECKER['yn'] = check_yn
TYPE_CHECKER['named'] = check_named
TYPE_CHECKER['multiple_choice'] = check_csv
TYPE_CHECKER['file'] = check_file
TYPE_CHECKER['color'] = check_color
TYPE_CHECKER['password'] = check_password
TYPE_CHECKER['time'] = check_time
TYPE_CHECKER['bytes'] = check_bytes
if HAS_MX_DATETIME:
TYPES += ('date',)
TYPE_CHECKER['date'] = check_date
def __init__(self, *opts, **attrs):
BaseOption.__init__(self, *opts, **attrs)
if hasattr(self, "hide") and self.hide:
self.help = SUPPRESS_HELP
def _check_choice(self):
"""FIXME: need to override this due to optik misdesign"""
if self.type in ("choice", "multiple_choice"):
if self.choices is None:
raise OptionError(
"must supply a list of choices for type 'choice'", self)
elif type(self.choices) not in (types.TupleType, types.ListType):
raise OptionError(
"choices must be a list of strings ('%s' supplied)"
% str(type(self.choices)).split("'")[1], self)
elif self.choices is not None:
raise OptionError(
"must not supply choices for type %r" % self.type, self)
BaseOption.CHECK_METHODS[2] = _check_choice
def process(self, opt, value, values, parser):
# First, convert the value(s) to the right type. Howl if any
# value(s) are bogus.
try:
value = self.convert_value(opt, value)
except AttributeError: # py < 2.4
value = self.check_value(opt, value)
if self.type == 'named':
existant = getattr(values, self.dest)
if existant:
existant.update(value)
value = existant
# And then take whatever action is expected of us.
# This is a separate method to make life easier for
# subclasses to add new actions.
return self.take_action(
self.action, self.dest, opt, value, values, parser)
class OptionParser(BaseParser):
"""override optik.OptionParser to use our Option class
"""
def __init__(self, option_class=Option, *args, **kwargs):
BaseParser.__init__(self, option_class=Option, *args, **kwargs)
def format_option_help(self, formatter=None):
if formatter is None:
formatter = self.formatter
outputlevel = getattr(formatter, 'output_level', 0)
formatter.store_option_strings(self)
result = []
result.append(formatter.format_heading("Options"))
formatter.indent()
if self.option_list:
result.append(OptionContainer.format_option_help(self, formatter))
result.append("\n")
for group in self.option_groups:
if group.level <= outputlevel and (
group.description or level_options(group, outputlevel)):
result.append(group.format_help(formatter))
result.append("\n")
formatter.dedent()
# Drop the last "\n", or the header if no options or option groups:
return "".join(result[:-1])
OptionGroup.level = 0
def level_options(group, outputlevel):
return [option for option in group.option_list
if (getattr(option, 'level', 0) or 0) <= outputlevel
and not option.help is SUPPRESS_HELP]
def format_option_help(self, formatter):
result = []
outputlevel = getattr(formatter, 'output_level', 0) or 0
for option in level_options(self, outputlevel):
result.append(formatter.format_option(option))
return "".join(result)
OptionContainer.format_option_help = format_option_help
class ManHelpFormatter(HelpFormatter):
"""Format help using man pages ROFF format"""
def __init__ (self,
indent_increment=0,
max_help_position=24,
width=79,
short_first=0):
HelpFormatter.__init__ (
self, indent_increment, max_help_position, width, short_first)
def format_heading(self, heading):
return '.SH %s\n' % heading.upper()
def format_description(self, description):
return description
def format_option(self, option):
try:
optstring = option.option_strings
except AttributeError:
optstring = self.format_option_strings(option)
if option.help:
help_text = self.expand_default(option)
help = ' '.join([l.strip() for l in help_text.splitlines()])
else:
help = ''
return '''.IP "%s"
%s
''' % (optstring, help)
def format_head(self, optparser, pkginfo, section=1):
long_desc = ""
try:
pgm = optparser._get_prog_name()
except AttributeError:
# py >= 2.4.X (dunno which X exactly, at least 2)
pgm = optparser.get_prog_name()
short_desc = self.format_short_description(pgm, pkginfo.description)
if hasattr(pkginfo, "long_desc"):
long_desc = self.format_long_description(pgm, pkginfo.long_desc)
return '%s\n%s\n%s\n%s' % (self.format_title(pgm, section),
short_desc, self.format_synopsis(pgm),
long_desc)
def format_title(self, pgm, section):
date = '-'.join([str(num) for num in time.localtime()[:3]])
return '.TH %s %s "%s" %s' % (pgm, section, date, pgm)
def format_short_description(self, pgm, short_desc):
return '''.SH NAME
.B %s
\- %s
''' % (pgm, short_desc.strip())
def format_synopsis(self, pgm):
return '''.SH SYNOPSIS
.B %s
[
.I OPTIONS
] [
.I <arguments>
]
''' % pgm
def format_long_description(self, pgm, long_desc):
long_desc = '\n'.join([line.lstrip()
for line in long_desc.splitlines()])
long_desc = long_desc.replace('\n.\n', '\n\n')
if long_desc.lower().startswith(pgm):
long_desc = long_desc[len(pgm):]
return '''.SH DESCRIPTION
.B %s
%s
''' % (pgm, long_desc.strip())
def format_tail(self, pkginfo):
tail = '''.SH SEE ALSO
/usr/share/doc/pythonX.Y-%s/
.SH BUGS
Please report bugs on the project\'s mailing list:
%s
.SH AUTHOR
%s <%s>
''' % (getattr(pkginfo, 'debian_name', pkginfo.modname),
pkginfo.mailinglist, pkginfo.author, pkginfo.author_email)
if hasattr(pkginfo, "copyright"):
tail += '''
.SH COPYRIGHT
%s
''' % pkginfo.copyright
return tail
def generate_manpage(optparser, pkginfo, section=1, stream=sys.stdout, level=0):
"""generate a man page from an optik parser"""
formatter = ManHelpFormatter()
formatter.output_level = level
formatter.parser = optparser
print >> stream, formatter.format_head(optparser, pkginfo, section)
print >> stream, optparser.format_option_help(formatter)
print >> stream, formatter.format_tail(pkginfo)
__all__ = ('OptionParser', 'Option', 'OptionGroup', 'OptionValueError',
'Values') | unknown | codeparrot/codeparrot-clean | ||
"""
Outline Tab Serializers.
"""
from django.utils.translation import ngettext
from rest_framework import serializers
from lms.djangoapps.course_home_api.dates.v1.serializers import DateSummarySerializer
from lms.djangoapps.course_home_api.progress.v1.serializers import CertificateDataSerializer
from lms.djangoapps.course_home_api.mixins import DatesBannerSerializerMixin, VerifiedModeSerializerMixin
class CourseBlockSerializer(serializers.Serializer):
"""
Serializer for Course Block Objects
"""
blocks = serializers.SerializerMethodField()
def get_blocks(self, block):
block_key = block['id']
block_type = block['type']
children = block.get('children', []) if block_type != 'sequential' else [] # Don't descend past sequential
description = block.get('format')
display_name = block['display_name']
enable_links = self.context.get('enable_links')
graded = block.get('graded')
icon = None
num_graded_problems = block.get('num_graded_problems', 0)
scored = block.get('scored')
if num_graded_problems and block_type == 'sequential':
questions = ngettext('({number} Question)', '({number} Questions)', num_graded_problems)
display_name += ' ' + questions.format(number=num_graded_problems)
if graded and scored:
icon = 'fa-pencil-square-o'
if 'special_exam_info' in block:
description = block['special_exam_info'].get('short_description')
icon = block['special_exam_info'].get('suggested_icon', 'fa-pencil-square-o')
serialized = {
block_key: {
'children': [child['id'] for child in children],
'complete': block.get('complete', False),
'description': description,
'display_name': display_name,
'due': block.get('due'),
'effort_activities': block.get('effort_activities'),
'effort_time': block.get('effort_time'),
'icon': icon,
'id': block_key,
'lms_web_url': block['lms_web_url'] if enable_links else None,
'legacy_web_url': block['legacy_web_url'] if enable_links else None,
'resume_block': block.get('resume_block', False),
'type': block_type,
'has_scheduled_content': block.get('has_scheduled_content'),
},
}
for child in children:
serialized.update(self.get_blocks(child))
return serialized
class CourseGoalsSerializer(serializers.Serializer):
"""
Serializer for Course Goal data
"""
goal_options = serializers.ListField()
selected_goal = serializers.DictField()
class CourseToolSerializer(serializers.Serializer):
"""
Serializer for Course Tool Objects
"""
analytics_id = serializers.CharField()
title = serializers.CharField()
url = serializers.SerializerMethodField()
def get_url(self, tool):
course_overview = self.context.get('course_overview')
url = tool.url(course_overview.id)
request = self.context.get('request')
return request.build_absolute_uri(url)
class DatesWidgetSerializer(serializers.Serializer):
"""
Serializer for Dates Widget data
"""
course_date_blocks = DateSummarySerializer(many=True)
dates_tab_link = serializers.CharField()
user_timezone = serializers.CharField()
class EnrollAlertSerializer(serializers.Serializer):
"""
Serializer for enroll alert information
"""
can_enroll = serializers.BooleanField()
extra_text = serializers.CharField()
class ResumeCourseSerializer(serializers.Serializer):
"""
Serializer for resume course data
"""
has_visited_course = serializers.BooleanField()
url = serializers.URLField()
class OutlineTabSerializer(DatesBannerSerializerMixin, VerifiedModeSerializerMixin, serializers.Serializer):
"""
Serializer for the Outline Tab
"""
access_expiration = serializers.DictField()
cert_data = CertificateDataSerializer()
course_blocks = CourseBlockSerializer()
course_goals = CourseGoalsSerializer()
course_tools = CourseToolSerializer(many=True)
dates_widget = DatesWidgetSerializer()
enroll_alert = EnrollAlertSerializer()
handouts_html = serializers.CharField()
has_ended = serializers.BooleanField()
offer = serializers.DictField()
resume_course = ResumeCourseSerializer()
welcome_message_html = serializers.CharField() | unknown | codeparrot/codeparrot-clean | ||
# -*- coding: utf-8 -*-
import os
import re
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
from pip.req import parse_requirements
TEST_REQUIRES = [
'pytest',
'responses',
]
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = [
'--verbose'
]
self.test_suite = True
def run_tests(self):
import pytest
errcode = pytest.main(self.test_args)
sys.exit(errcode)
def find_version(fname):
"""Attempts to find the version number in the file names fname.
Raises RuntimeError if not found.
"""
version = ''
with open(fname, 'r') as fp:
reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]')
for line in fp:
m = reg.match(line)
if m:
version = m.group(1)
break
if not version:
raise RuntimeError('Cannot find version information')
return version
__version__ = find_version('betfair/__init__.py')
def read(fname):
with open(fname) as fp:
content = fp.read()
return content
setup(
name='betfair.py',
version=__version__,
description='Python client for the Betfair API '
'(https://api.developer.betfair.com/)',
long_description=open('README.rst').read(),
author='Joshua Carp',
author_email='jm.carp@gmail.com',
url='https://github.com/jmcarp/betfair.py',
packages=find_packages(exclude=('test*', )),
package_dir={'betfair': 'betfair'},
include_package_data=True,
install_requires=[
str(requirement.req)
for requirement in parse_requirements('requirements.txt')
],
license=read('LICENSE'),
zip_safe=False,
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
test_suite='tests',
tests_require=TEST_REQUIRES,
cmdclass={'test': PyTest}
) | unknown | codeparrot/codeparrot-clean | ||
""" Python Character Mapping Codec generated from 'CP862.TXT' with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_map)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x05d0, # HEBREW LETTER ALEF
0x0081: 0x05d1, # HEBREW LETTER BET
0x0082: 0x05d2, # HEBREW LETTER GIMEL
0x0083: 0x05d3, # HEBREW LETTER DALET
0x0084: 0x05d4, # HEBREW LETTER HE
0x0085: 0x05d5, # HEBREW LETTER VAV
0x0086: 0x05d6, # HEBREW LETTER ZAYIN
0x0087: 0x05d7, # HEBREW LETTER HET
0x0088: 0x05d8, # HEBREW LETTER TET
0x0089: 0x05d9, # HEBREW LETTER YOD
0x008a: 0x05da, # HEBREW LETTER FINAL KAF
0x008b: 0x05db, # HEBREW LETTER KAF
0x008c: 0x05dc, # HEBREW LETTER LAMED
0x008d: 0x05dd, # HEBREW LETTER FINAL MEM
0x008e: 0x05de, # HEBREW LETTER MEM
0x008f: 0x05df, # HEBREW LETTER FINAL NUN
0x0090: 0x05e0, # HEBREW LETTER NUN
0x0091: 0x05e1, # HEBREW LETTER SAMEKH
0x0092: 0x05e2, # HEBREW LETTER AYIN
0x0093: 0x05e3, # HEBREW LETTER FINAL PE
0x0094: 0x05e4, # HEBREW LETTER PE
0x0095: 0x05e5, # HEBREW LETTER FINAL TSADI
0x0096: 0x05e6, # HEBREW LETTER TSADI
0x0097: 0x05e7, # HEBREW LETTER QOF
0x0098: 0x05e8, # HEBREW LETTER RESH
0x0099: 0x05e9, # HEBREW LETTER SHIN
0x009a: 0x05ea, # HEBREW LETTER TAV
0x009b: 0x00a2, # CENT SIGN
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00a5, # YEN SIGN
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00f1, # LATIN SMALL LETTER N WITH TILDE
0x00a5: 0x00d1, # LATIN CAPITAL LETTER N WITH TILDE
0x00a6: 0x00aa, # FEMININE ORDINAL INDICATOR
0x00a7: 0x00ba, # MASCULINE ORDINAL INDICATOR
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S (GERMAN)
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Encoding Map
encoding_map = codecs.make_encoding_map(decoding_map) | unknown | codeparrot/codeparrot-clean | ||
//// [tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts] ////
//// [awaitUsingDeclarations.1.ts]
await using d1 = { async [Symbol.asyncDispose]() {} };
async function af() {
await using d3 = { async [Symbol.asyncDispose]() {} };
await null;
}
async function * ag() {
await using d5 = { async [Symbol.asyncDispose]() {} };
yield;
await null;
}
const a = async () => {
await using d6 = { async [Symbol.asyncDispose]() {} };
};
class C1 {
a = async () => {
await using d7 = { async [Symbol.asyncDispose]() {} };
};
async am() {
await using d13 = { async [Symbol.asyncDispose]() {} };
await null;
}
async * ag() {
await using d15 = { async [Symbol.asyncDispose]() {} };
yield;
await null;
}
}
{
await using d19 = { async [Symbol.asyncDispose]() {} };
}
switch (Math.random()) {
case 0: {
await using d20 = { async [Symbol.asyncDispose]() {} };
break;
}
case 1: {
await using d21 = { async [Symbol.asyncDispose]() {} };
break;
}
default: {
await using d22 = { async [Symbol.asyncDispose]() {} };
}
}
if (true)
switch (0) {
case 0: {
await using d23 = { async [Symbol.asyncDispose]() {} };
break;
}
default: {
await using d24 = { async [Symbol.asyncDispose]() {} };
}
}
try {
await using d25 = { async [Symbol.asyncDispose]() {} };
}
catch {
await using d26 = { async [Symbol.asyncDispose]() {} };
}
finally {
await using d27 = { async [Symbol.asyncDispose]() {} };
}
if (true) {
await using d28 = { async [Symbol.asyncDispose]() {} };
}
else {
await using d29 = { async [Symbol.asyncDispose]() {} };
}
while (true) {
await using d30 = { async [Symbol.asyncDispose]() {} };
break;
}
do {
await using d31 = { async [Symbol.asyncDispose]() {} };
break;
}
while (true);
for (;;) {
await using d32 = { async [Symbol.asyncDispose]() {} };
break;
}
for (const x in {}) {
await using d33 = { async [Symbol.asyncDispose]() {} };
}
for (const x of []) {
await using d34 = { async [Symbol.asyncDispose]() {} };
}
export {};
//// [awaitUsingDeclarations.1.js]
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
if (value !== null && value !== void 0) {
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
var dispose, inner;
if (async) {
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
dispose = value[Symbol.asyncDispose];
}
if (dispose === void 0) {
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
dispose = value[Symbol.dispose];
if (async) inner = dispose;
}
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
env.stack.push({ value: value, dispose: dispose, async: async });
}
else if (async) {
env.stack.push({ async: true });
}
return value;
};
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
return function (env) {
function fail(e) {
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
env.hasError = true;
}
var r, s = 0;
function next() {
while (r = env.stack.pop()) {
try {
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
if (r.dispose) {
var result = r.dispose.call(r.value);
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
}
else s |= 1;
}
catch (e) {
fail(e);
}
}
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
if (env.hasError) throw env.error;
}
return next();
};
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
});
var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
};
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
function af() {
return __awaiter(this, void 0, void 0, function () {
var env_18, d3, e_18, result_18;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
env_18 = { stack: [], error: void 0, hasError: false };
_b.label = 1;
case 1:
_b.trys.push([1, 3, 4, 7]);
d3 = __addDisposableResource(env_18, (_a = {}, _a[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _a), true);
return [4 /*yield*/, null];
case 2:
_b.sent();
return [3 /*break*/, 7];
case 3:
e_18 = _b.sent();
env_18.error = e_18;
env_18.hasError = true;
return [3 /*break*/, 7];
case 4:
result_18 = __disposeResources(env_18);
if (!result_18) return [3 /*break*/, 6];
return [4 /*yield*/, result_18];
case 5:
_b.sent();
_b.label = 6;
case 6: return [7 /*endfinally*/];
case 7: return [2 /*return*/];
}
});
});
}
function ag() {
return __asyncGenerator(this, arguments, function ag_1() {
var env_19, d5, e_19, result_19;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
env_19 = { stack: [], error: void 0, hasError: false };
_b.label = 1;
case 1:
_b.trys.push([1, 5, 6, 9]);
d5 = __addDisposableResource(env_19, (_a = {}, _a[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _a), true);
return [4 /*yield*/, __await(void 0)];
case 2: return [4 /*yield*/, _b.sent()];
case 3:
_b.sent();
return [4 /*yield*/, __await(null)];
case 4:
_b.sent();
return [3 /*break*/, 9];
case 5:
e_19 = _b.sent();
env_19.error = e_19;
env_19.hasError = true;
return [3 /*break*/, 9];
case 6:
result_19 = __disposeResources(env_19);
if (!result_19) return [3 /*break*/, 8];
return [4 /*yield*/, __await(result_19)];
case 7:
_b.sent();
_b.label = 8;
case 8: return [7 /*endfinally*/];
case 9: return [2 /*return*/];
}
});
});
}
var d1, a, C1;
var env_1 = { stack: [], error: void 0, hasError: false };
try {
d1 = __addDisposableResource(env_1, (_a = {}, _a[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _a), true);
a = function () { return __awaiter(void 0, void 0, void 0, function () {
var env_20, d6, e_20, result_20;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
env_20 = { stack: [], error: void 0, hasError: false };
_b.label = 1;
case 1:
_b.trys.push([1, 2, 3, 6]);
d6 = __addDisposableResource(env_20, (_a = {}, _a[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _a), true);
return [3 /*break*/, 6];
case 2:
e_20 = _b.sent();
env_20.error = e_20;
env_20.hasError = true;
return [3 /*break*/, 6];
case 3:
result_20 = __disposeResources(env_20);
if (!result_20) return [3 /*break*/, 5];
return [4 /*yield*/, result_20];
case 4:
_b.sent();
_b.label = 5;
case 5: return [7 /*endfinally*/];
case 6: return [2 /*return*/];
}
});
}); };
C1 = /** @class */ (function () {
function C1() {
var _this = this;
this.a = function () { return __awaiter(_this, void 0, void 0, function () {
var env_21, d7, e_21, result_21;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
env_21 = { stack: [], error: void 0, hasError: false };
_b.label = 1;
case 1:
_b.trys.push([1, 2, 3, 6]);
d7 = __addDisposableResource(env_21, (_a = {}, _a[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _a), true);
return [3 /*break*/, 6];
case 2:
e_21 = _b.sent();
env_21.error = e_21;
env_21.hasError = true;
return [3 /*break*/, 6];
case 3:
result_21 = __disposeResources(env_21);
if (!result_21) return [3 /*break*/, 5];
return [4 /*yield*/, result_21];
case 4:
_b.sent();
_b.label = 5;
case 5: return [7 /*endfinally*/];
case 6: return [2 /*return*/];
}
});
}); };
}
C1.prototype.am = function () {
return __awaiter(this, void 0, void 0, function () {
var env_22, d13, e_22, result_22;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
env_22 = { stack: [], error: void 0, hasError: false };
_b.label = 1;
case 1:
_b.trys.push([1, 3, 4, 7]);
d13 = __addDisposableResource(env_22, (_a = {}, _a[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _a), true);
return [4 /*yield*/, null];
case 2:
_b.sent();
return [3 /*break*/, 7];
case 3:
e_22 = _b.sent();
env_22.error = e_22;
env_22.hasError = true;
return [3 /*break*/, 7];
case 4:
result_22 = __disposeResources(env_22);
if (!result_22) return [3 /*break*/, 6];
return [4 /*yield*/, result_22];
case 5:
_b.sent();
_b.label = 6;
case 6: return [7 /*endfinally*/];
case 7: return [2 /*return*/];
}
});
});
};
C1.prototype.ag = function () {
return __asyncGenerator(this, arguments, function ag_2() {
var env_23, d15, e_23, result_23;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
env_23 = { stack: [], error: void 0, hasError: false };
_b.label = 1;
case 1:
_b.trys.push([1, 5, 6, 9]);
d15 = __addDisposableResource(env_23, (_a = {}, _a[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _a), true);
return [4 /*yield*/, __await(void 0)];
case 2: return [4 /*yield*/, _b.sent()];
case 3:
_b.sent();
return [4 /*yield*/, __await(null)];
case 4:
_b.sent();
return [3 /*break*/, 9];
case 5:
e_23 = _b.sent();
env_23.error = e_23;
env_23.hasError = true;
return [3 /*break*/, 9];
case 6:
result_23 = __disposeResources(env_23);
if (!result_23) return [3 /*break*/, 8];
return [4 /*yield*/, __await(result_23)];
case 7:
_b.sent();
_b.label = 8;
case 8: return [7 /*endfinally*/];
case 9: return [2 /*return*/];
}
});
});
};
return C1;
}());
{
var env_2 = { stack: [], error: void 0, hasError: false };
try {
var d19 = __addDisposableResource(env_2, (_b = {}, _b[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _b), true);
}
catch (e_1) {
env_2.error = e_1;
env_2.hasError = true;
}
finally {
var result_1 = __disposeResources(env_2);
if (result_1)
await result_1;
}
}
switch (Math.random()) {
case 0: {
var env_3 = { stack: [], error: void 0, hasError: false };
try {
var d20 = __addDisposableResource(env_3, (_c = {}, _c[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _c), true);
break;
}
catch (e_2) {
env_3.error = e_2;
env_3.hasError = true;
}
finally {
var result_2 = __disposeResources(env_3);
if (result_2)
await result_2;
}
}
case 1: {
var env_4 = { stack: [], error: void 0, hasError: false };
try {
var d21 = __addDisposableResource(env_4, (_d = {}, _d[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _d), true);
break;
}
catch (e_3) {
env_4.error = e_3;
env_4.hasError = true;
}
finally {
var result_3 = __disposeResources(env_4);
if (result_3)
await result_3;
}
}
default: {
var env_5 = { stack: [], error: void 0, hasError: false };
try {
var d22 = __addDisposableResource(env_5, (_e = {}, _e[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _e), true);
}
catch (e_4) {
env_5.error = e_4;
env_5.hasError = true;
}
finally {
var result_4 = __disposeResources(env_5);
if (result_4)
await result_4;
}
}
}
if (true)
switch (0) {
case 0: {
var env_6 = { stack: [], error: void 0, hasError: false };
try {
var d23 = __addDisposableResource(env_6, (_f = {}, _f[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _f), true);
break;
}
catch (e_5) {
env_6.error = e_5;
env_6.hasError = true;
}
finally {
var result_5 = __disposeResources(env_6);
if (result_5)
await result_5;
}
}
default: {
var env_7 = { stack: [], error: void 0, hasError: false };
try {
var d24 = __addDisposableResource(env_7, (_g = {}, _g[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _g), true);
}
catch (e_6) {
env_7.error = e_6;
env_7.hasError = true;
}
finally {
var result_6 = __disposeResources(env_7);
if (result_6)
await result_6;
}
}
}
try {
var env_8 = { stack: [], error: void 0, hasError: false };
try {
var d25 = __addDisposableResource(env_8, (_h = {}, _h[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _h), true);
}
catch (e_7) {
env_8.error = e_7;
env_8.hasError = true;
}
finally {
var result_7 = __disposeResources(env_8);
if (result_7)
await result_7;
}
}
catch (_t) {
var env_9 = { stack: [], error: void 0, hasError: false };
try {
var d26 = __addDisposableResource(env_9, (_j = {}, _j[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _j), true);
}
catch (e_8) {
env_9.error = e_8;
env_9.hasError = true;
}
finally {
var result_8 = __disposeResources(env_9);
if (result_8)
await result_8;
}
}
finally {
var env_10 = { stack: [], error: void 0, hasError: false };
try {
var d27 = __addDisposableResource(env_10, (_k = {}, _k[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _k), true);
}
catch (e_9) {
env_10.error = e_9;
env_10.hasError = true;
}
finally {
var result_9 = __disposeResources(env_10);
if (result_9)
await result_9;
}
}
if (true) {
var env_11 = { stack: [], error: void 0, hasError: false };
try {
var d28 = __addDisposableResource(env_11, (_l = {}, _l[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _l), true);
}
catch (e_10) {
env_11.error = e_10;
env_11.hasError = true;
}
finally {
var result_10 = __disposeResources(env_11);
if (result_10)
await result_10;
}
}
else {
var env_12 = { stack: [], error: void 0, hasError: false };
try {
var d29 = __addDisposableResource(env_12, (_m = {}, _m[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _m), true);
}
catch (e_11) {
env_12.error = e_11;
env_12.hasError = true;
}
finally {
var result_11 = __disposeResources(env_12);
if (result_11)
await result_11;
}
}
while (true) {
var env_13 = { stack: [], error: void 0, hasError: false };
try {
var d30 = __addDisposableResource(env_13, (_o = {}, _o[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _o), true);
break;
}
catch (e_12) {
env_13.error = e_12;
env_13.hasError = true;
}
finally {
var result_12 = __disposeResources(env_13);
if (result_12)
await result_12;
}
}
do {
var env_14 = { stack: [], error: void 0, hasError: false };
try {
var d31 = __addDisposableResource(env_14, (_p = {}, _p[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _p), true);
break;
}
catch (e_13) {
env_14.error = e_13;
env_14.hasError = true;
}
finally {
var result_13 = __disposeResources(env_14);
if (result_13)
await result_13;
}
} while (true);
for (;;) {
var env_15 = { stack: [], error: void 0, hasError: false };
try {
var d32 = __addDisposableResource(env_15, (_q = {}, _q[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _q), true);
break;
}
catch (e_14) {
env_15.error = e_14;
env_15.hasError = true;
}
finally {
var result_14 = __disposeResources(env_15);
if (result_14)
await result_14;
}
}
for (var x in {}) {
var env_16 = { stack: [], error: void 0, hasError: false };
try {
var d33 = __addDisposableResource(env_16, (_r = {}, _r[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _r), true);
}
catch (e_15) {
env_16.error = e_15;
env_16.hasError = true;
}
finally {
var result_15 = __disposeResources(env_16);
if (result_15)
await result_15;
}
}
for (var _i = 0, _u = []; _i < _u.length; _i++) {
var x = _u[_i];
var env_17 = { stack: [], error: void 0, hasError: false };
try {
var d34 = __addDisposableResource(env_17, (_s = {}, _s[Symbol.asyncDispose] = function () {
return __awaiter(this, void 0, void 0, function () { return __generator(this, function (_a) {
return [2 /*return*/];
}); });
}, _s), true);
}
catch (e_16) {
env_17.error = e_16;
env_17.hasError = true;
}
finally {
var result_16 = __disposeResources(env_17);
if (result_16)
await result_16;
}
}
}
catch (e_17) {
env_1.error = e_17;
env_1.hasError = true;
}
finally {
var result_17 = __disposeResources(env_1);
if (result_17)
await result_17;
}
export {}; | javascript | github | https://github.com/microsoft/TypeScript | tests/baselines/reference/awaitUsingDeclarations.1(target=es5).js |
"""Test correct operation of the print function.
"""
# In 2.6, this gives us the behavior we want. In 3.0, it has
# no function, but it still must parse correctly.
from __future__ import print_function
import unittest
from test import test_support
from StringIO import StringIO
NotDefined = object()
# A dispatch table all 8 combinations of providing
# sep, end, and file
# I use this machinery so that I'm not just passing default
# values to print, I'm either passing or not passing in the
# arguments
dispatch = {
(False, False, False):
lambda args, sep, end, file: print(*args),
(False, False, True):
lambda args, sep, end, file: print(file=file, *args),
(False, True, False):
lambda args, sep, end, file: print(end=end, *args),
(False, True, True):
lambda args, sep, end, file: print(end=end, file=file, *args),
(True, False, False):
lambda args, sep, end, file: print(sep=sep, *args),
(True, False, True):
lambda args, sep, end, file: print(sep=sep, file=file, *args),
(True, True, False):
lambda args, sep, end, file: print(sep=sep, end=end, *args),
(True, True, True):
lambda args, sep, end, file: print(sep=sep, end=end, file=file, *args),
}
# Class used to test __str__ and print
class ClassWith__str__:
def __init__(self, x):
self.x = x
def __str__(self):
return self.x
class TestPrint(unittest.TestCase):
def check(self, expected, args,
sep=NotDefined, end=NotDefined, file=NotDefined):
# Capture sys.stdout in a StringIO. Call print with args,
# and with sep, end, and file, if they're defined. Result
# must match expected.
# Look up the actual function to call, based on if sep, end, and file
# are defined
fn = dispatch[(sep is not NotDefined,
end is not NotDefined,
file is not NotDefined)]
with test_support.captured_stdout() as t:
fn(args, sep, end, file)
self.assertEqual(t.getvalue(), expected)
def test_print(self):
def x(expected, args, sep=NotDefined, end=NotDefined):
# Run the test 2 ways: not using file, and using
# file directed to a StringIO
self.check(expected, args, sep=sep, end=end)
# When writing to a file, stdout is expected to be empty
o = StringIO()
self.check('', args, sep=sep, end=end, file=o)
# And o will contain the expected output
self.assertEqual(o.getvalue(), expected)
x('\n', ())
x('a\n', ('a',))
x('None\n', (None,))
x('1 2\n', (1, 2))
x('1 2\n', (1, ' ', 2))
x('1*2\n', (1, 2), sep='*')
x('1 s', (1, 's'), end='')
x('a\nb\n', ('a', 'b'), sep='\n')
x('1.01', (1.0, 1), sep='', end='')
x('1*a*1.3+', (1, 'a', 1.3), sep='*', end='+')
x('a\n\nb\n', ('a\n', 'b'), sep='\n')
x('\0+ +\0\n', ('\0', ' ', '\0'), sep='+')
x('a\n b\n', ('a\n', 'b'))
x('a\n b\n', ('a\n', 'b'), sep=None)
x('a\n b\n', ('a\n', 'b'), end=None)
x('a\n b\n', ('a\n', 'b'), sep=None, end=None)
x('*\n', (ClassWith__str__('*'),))
x('abc 1\n', (ClassWith__str__('abc'), 1))
# 2.x unicode tests
x(u'1 2\n', ('1', u'2'))
x(u'u\1234\n', (u'u\1234',))
x(u' abc 1\n', (' ', ClassWith__str__(u'abc'), 1))
# errors
self.assertRaises(TypeError, print, '', sep=3)
self.assertRaises(TypeError, print, '', end=3)
self.assertRaises(AttributeError, print, '', file='')
def test_mixed_args(self):
# If an unicode arg is passed, sep and end should be unicode, too.
class Recorder(object):
def __init__(self, must_be_unicode):
self.buf = []
self.force_unicode = must_be_unicode
def write(self, what):
if self.force_unicode and not isinstance(what, unicode):
raise AssertionError("{0!r} is not unicode".format(what))
self.buf.append(what)
buf = Recorder(True)
print(u'hi', file=buf)
self.assertEqual(u''.join(buf.buf), 'hi\n')
del buf.buf[:]
print(u'hi', u'nothing', file=buf)
self.assertEqual(u''.join(buf.buf), 'hi nothing\n')
buf = Recorder(False)
print('hi', 'bye', end=u'\n', file=buf)
self.assertIsInstance(buf.buf[1], unicode)
self.assertIsInstance(buf.buf[3], unicode)
del buf.buf[:]
print(sep=u'x', file=buf)
self.assertIsInstance(buf.buf[-1], unicode)
def test_main():
test_support.run_unittest(TestPrint)
if __name__ == "__main__":
test_main() | unknown | codeparrot/codeparrot-clean | ||
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Common codegen classes.
import operator
import re
import string
import textwrap
import functools
from WebIDL import (
BuiltinTypes,
IDLBuiltinType,
IDLNullValue,
IDLType,
IDLInterfaceMember,
IDLUndefinedValue,
)
from Configuration import getTypesFromDescriptor, getTypesFromDictionary, getTypesFromCallback
AUTOGENERATED_WARNING_COMMENT = \
"/* THIS FILE IS AUTOGENERATED - DO NOT EDIT */\n\n"
FINALIZE_HOOK_NAME = '_finalize'
TRACE_HOOK_NAME = '_trace'
CONSTRUCT_HOOK_NAME = '_constructor'
HASINSTANCE_HOOK_NAME = '_hasInstance'
def replaceFileIfChanged(filename, newContents):
"""
Read a copy of the old file, so that we don't touch it if it hasn't changed.
Returns True if the file was updated, false otherwise.
"""
# XXXjdm This doesn't play well with make right now.
# Force the file to always be updated, or else changing CodegenRust.py
# will cause many autogenerated bindings to be regenerated perpetually
# until the result is actually different.
# oldFileContents = ""
# try:
# with open(filename, 'rb') as oldFile:
# oldFileContents = ''.join(oldFile.readlines())
# except:
# pass
# if newContents == oldFileContents:
# return False
with open(filename, 'wb') as f:
f.write(newContents)
return True
def toStringBool(arg):
return str(not not arg).lower()
def toBindingNamespace(arg):
return re.sub("((_workers)?$)", "Binding\\1", arg)
def stripTrailingWhitespace(text):
tail = '\n' if text.endswith('\n') else ''
lines = text.splitlines()
for i in range(len(lines)):
lines[i] = lines[i].rstrip()
return '\n'.join(lines) + tail
def MakeNativeName(name):
return name[0].upper() + name[1:]
builtinNames = {
IDLType.Tags.bool: 'bool',
IDLType.Tags.int8: 'i8',
IDLType.Tags.int16: 'i16',
IDLType.Tags.int32: 'i32',
IDLType.Tags.int64: 'i64',
IDLType.Tags.uint8: 'u8',
IDLType.Tags.uint16: 'u16',
IDLType.Tags.uint32: 'u32',
IDLType.Tags.uint64: 'u64',
IDLType.Tags.unrestricted_float: 'f32',
IDLType.Tags.float: 'Finite<f32>',
IDLType.Tags.unrestricted_double: 'f64',
IDLType.Tags.double: 'Finite<f64>'
}
numericTags = [
IDLType.Tags.int8, IDLType.Tags.uint8,
IDLType.Tags.int16, IDLType.Tags.uint16,
IDLType.Tags.int32, IDLType.Tags.uint32,
IDLType.Tags.int64, IDLType.Tags.uint64,
IDLType.Tags.unrestricted_float,
IDLType.Tags.unrestricted_double
]
class CastableObjectUnwrapper():
"""
A class for unwrapping an object named by the "source" argument
based on the passed-in descriptor. Stringifies to a Rust expression of
the appropriate type.
codeOnFailure is the code to run if unwrapping fails.
"""
def __init__(self, descriptor, source, codeOnFailure, handletype):
self.substitution = {
"source": source,
"codeOnFailure": CGIndenter(CGGeneric(codeOnFailure), 8).define(),
"handletype": handletype,
}
def __str__(self):
return string.Template("""\
match native_from_handle${handletype}(${source}) {
Ok(val) => val,
Err(()) => {
${codeOnFailure}
}
}""").substitute(self.substitution)
# We'll want to insert the indent at the beginnings of lines, but we
# don't want to indent empty lines. So only indent lines that have a
# non-newline character on them.
lineStartDetector = re.compile("^(?=[^\n#])", re.MULTILINE)
def indent(s, indentLevel=2):
"""
Indent C++ code.
Weird secret feature: this doesn't indent lines that start with # (such as
#include lines or #ifdef/#endif).
"""
if s == "":
return s
return re.sub(lineStartDetector, indentLevel * " ", s)
# dedent() and fill() are often called on the same string multiple
# times. We want to memoize their return values so we don't keep
# recomputing them all the time.
def memoize(fn):
"""
Decorator to memoize a function of one argument. The cache just
grows without bound.
"""
cache = {}
@functools.wraps(fn)
def wrapper(arg):
retval = cache.get(arg)
if retval is None:
retval = cache[arg] = fn(arg)
return retval
return wrapper
@memoize
def dedent(s):
"""
Remove all leading whitespace from s, and remove a blank line
at the beginning.
"""
if s.startswith('\n'):
s = s[1:]
return textwrap.dedent(s)
# This works by transforming the fill()-template to an equivalent
# string.Template.
fill_multiline_substitution_re = re.compile(r"( *)\$\*{(\w+)}(\n)?")
@memoize
def compile_fill_template(template):
"""
Helper function for fill(). Given the template string passed to fill(),
do the reusable part of template processing and return a pair (t,
argModList) that can be used every time fill() is called with that
template argument.
argsModList is list of tuples that represent modifications to be
made to args. Each modification has, in order: i) the arg name,
ii) the modified name, iii) the indent depth.
"""
t = dedent(template)
assert t.endswith("\n") or "\n" not in t
argModList = []
def replace(match):
"""
Replaces a line like ' $*{xyz}\n' with '${xyz_n}',
where n is the indent depth, and add a corresponding entry to
argModList.
Note that this needs to close over argModList, so it has to be
defined inside compile_fill_template().
"""
indentation, name, nl = match.groups()
depth = len(indentation)
# Check that $*{xyz} appears by itself on a line.
prev = match.string[:match.start()]
if (prev and not prev.endswith("\n")) or nl is None:
raise ValueError("Invalid fill() template: $*{%s} must appear by itself on a line" % name)
# Now replace this whole line of template with the indented equivalent.
modified_name = name + "_" + str(depth)
argModList.append((name, modified_name, depth))
return "${" + modified_name + "}"
t = re.sub(fill_multiline_substitution_re, replace, t)
return (string.Template(t), argModList)
def fill(template, **args):
"""
Convenience function for filling in a multiline template.
`fill(template, name1=v1, name2=v2)` is a lot like
`string.Template(template).substitute({"name1": v1, "name2": v2})`.
However, it's shorter, and has a few nice features:
* If `template` is indented, fill() automatically dedents it!
This makes code using fill() with Python's multiline strings
much nicer to look at.
* If `template` starts with a blank line, fill() strips it off.
(Again, convenient with multiline strings.)
* fill() recognizes a special kind of substitution
of the form `$*{name}`.
Use this to paste in, and automatically indent, multiple lines.
(Mnemonic: The `*` is for "multiple lines").
A `$*` substitution must appear by itself on a line, with optional
preceding indentation (spaces only). The whole line is replaced by the
corresponding keyword argument, indented appropriately. If the
argument is an empty string, no output is generated, not even a blank
line.
"""
t, argModList = compile_fill_template(template)
# Now apply argModList to args
for (name, modified_name, depth) in argModList:
if not (args[name] == "" or args[name].endswith("\n")):
raise ValueError("Argument %s with value %r is missing a newline" % (name, args[name]))
args[modified_name] = indent(args[name], depth)
return t.substitute(args)
class CGThing():
"""
Abstract base class for things that spit out code.
"""
def __init__(self):
pass # Nothing for now
def define(self):
"""Produce code for a Rust file."""
raise NotImplementedError # Override me!
class CGNativePropertyHooks(CGThing):
"""
Generate a NativePropertyHooks for a given descriptor
"""
def __init__(self, descriptor, properties):
CGThing.__init__(self)
self.descriptor = descriptor
self.properties = properties
def define(self):
parent = self.descriptor.interface.parent
if parent:
parentHooks = ("Some(&::dom::bindings::codegen::Bindings::%sBinding::sNativePropertyHooks)"
% parent.identifier.name)
else:
parentHooks = "None"
substitutions = {
"parentHooks": parentHooks
}
return string.Template(
"pub static sNativePropertyHooks: NativePropertyHooks = NativePropertyHooks {\n"
" native_properties: &sNativeProperties,\n"
" proto_hooks: ${parentHooks},\n"
"};\n").substitute(substitutions)
class CGMethodCall(CGThing):
"""
A class to generate selection of a method signature from a set of
signatures and generation of a call to that signature.
"""
def __init__(self, argsPre, nativeMethodName, static, descriptor, method):
CGThing.__init__(self)
methodName = '\\"%s.%s\\"' % (descriptor.interface.identifier.name, method.identifier.name)
def requiredArgCount(signature):
arguments = signature[1]
if len(arguments) == 0:
return 0
requiredArgs = len(arguments)
while requiredArgs and arguments[requiredArgs - 1].optional:
requiredArgs -= 1
return requiredArgs
signatures = method.signatures()
def getPerSignatureCall(signature, argConversionStartsAt=0):
signatureIndex = signatures.index(signature)
return CGPerSignatureCall(signature[0], argsPre, signature[1],
nativeMethodName + '_' * signatureIndex,
static, descriptor,
method, argConversionStartsAt)
if len(signatures) == 1:
# Special case: we can just do a per-signature method call
# here for our one signature and not worry about switching
# on anything.
signature = signatures[0]
self.cgRoot = CGList([getPerSignatureCall(signature)])
requiredArgs = requiredArgCount(signature)
if requiredArgs > 0:
code = (
"if argc < %d {\n"
" throw_type_error(cx, \"Not enough arguments to %s.\");\n"
" return 0;\n"
"}" % (requiredArgs, methodName))
self.cgRoot.prepend(
CGWrapper(CGGeneric(code), pre="\n", post="\n"))
return
# Need to find the right overload
maxArgCount = method.maxArgCount
allowedArgCounts = method.allowedArgCounts
argCountCases = []
for argCount in allowedArgCounts:
possibleSignatures = method.signaturesForArgCount(argCount)
if len(possibleSignatures) == 1:
# easy case!
signature = possibleSignatures[0]
argCountCases.append(CGCase(str(argCount), getPerSignatureCall(signature)))
continue
distinguishingIndex = method.distinguishingIndexForArgCount(argCount)
# We can't handle unions at the distinguishing index.
for (returnType, args) in possibleSignatures:
if args[distinguishingIndex].type.isUnion():
raise TypeError("No support for unions as distinguishing "
"arguments yet: %s",
args[distinguishingIndex].location)
# Convert all our arguments up to the distinguishing index.
# Doesn't matter which of the possible signatures we use, since
# they all have the same types up to that point; just use
# possibleSignatures[0]
caseBody = [
CGArgumentConverter(possibleSignatures[0][1][i],
i, "args", "argc", descriptor)
for i in range(0, distinguishingIndex)]
# Select the right overload from our set.
distinguishingArg = "args.get(%d)" % distinguishingIndex
def pickFirstSignature(condition, filterLambda):
sigs = filter(filterLambda, possibleSignatures)
assert len(sigs) < 2
if len(sigs) > 0:
call = getPerSignatureCall(sigs[0], distinguishingIndex)
if condition is None:
caseBody.append(call)
else:
caseBody.append(CGGeneric("if " + condition + " {"))
caseBody.append(CGIndenter(call))
caseBody.append(CGGeneric("}"))
return True
return False
# First check for null or undefined
pickFirstSignature("%s.isNullOrUndefined()" % distinguishingArg,
lambda s: (s[1][distinguishingIndex].type.nullable() or
s[1][distinguishingIndex].type.isDictionary()))
# Now check for distinguishingArg being an object that implements a
# non-callback interface. That includes typed arrays and
# arraybuffers.
interfacesSigs = [
s for s in possibleSignatures
if (s[1][distinguishingIndex].type.isObject() or
s[1][distinguishingIndex].type.isNonCallbackInterface())]
# There might be more than one of these; we need to check
# which ones we unwrap to.
if len(interfacesSigs) > 0:
# The spec says that we should check for "platform objects
# implementing an interface", but it's enough to guard on these
# being an object. The code for unwrapping non-callback
# interfaces and typed arrays will just bail out and move on to
# the next overload if the object fails to unwrap correctly. We
# could even not do the isObject() check up front here, but in
# cases where we have multiple object overloads it makes sense
# to do it only once instead of for each overload. That will
# also allow the unwrapping test to skip having to do codegen
# for the null-or-undefined case, which we already handled
# above.
caseBody.append(CGGeneric("if %s.get().is_object() {" %
(distinguishingArg)))
for idx, sig in enumerate(interfacesSigs):
caseBody.append(CGIndenter(CGGeneric("loop {")))
type = sig[1][distinguishingIndex].type
# The argument at index distinguishingIndex can't possibly
# be unset here, because we've already checked that argc is
# large enough that we can examine this argument.
info = getJSToNativeConversionInfo(
type, descriptor, failureCode="break;", isDefinitelyObject=True)
template = info.template
declType = info.declType
needsRooting = info.needsRooting
testCode = instantiateJSToNativeConversionTemplate(
template,
{"val": distinguishingArg},
declType,
"arg%d" % distinguishingIndex,
needsRooting)
# Indent by 4, since we need to indent further than our "do" statement
caseBody.append(CGIndenter(testCode, 4))
# If we got this far, we know we unwrapped to the right
# interface, so just do the call. Start conversion with
# distinguishingIndex + 1, since we already converted
# distinguishingIndex.
caseBody.append(CGIndenter(
getPerSignatureCall(sig, distinguishingIndex + 1), 4))
caseBody.append(CGIndenter(CGGeneric("}")))
caseBody.append(CGGeneric("}"))
# XXXbz Now we're supposed to check for distinguishingArg being
# an array or a platform object that supports indexed
# properties... skip that last for now. It's a bit of a pain.
pickFirstSignature("%s.get().isObject() && IsArrayLike(cx, &%s.get().toObject())" %
(distinguishingArg, distinguishingArg),
lambda s:
(s[1][distinguishingIndex].type.isArray() or
s[1][distinguishingIndex].type.isSequence() or
s[1][distinguishingIndex].type.isObject()))
# Check for Date objects
# XXXbz Do we need to worry about security wrappers around the Date?
pickFirstSignature("%s.get().isObject() && JS_ObjectIsDate(cx, &%s.get().toObject())" %
(distinguishingArg, distinguishingArg),
lambda s: (s[1][distinguishingIndex].type.isDate() or
s[1][distinguishingIndex].type.isObject()))
# Check for vanilla JS objects
# XXXbz Do we need to worry about security wrappers?
pickFirstSignature("%s.get().is_object() && !is_platform_object(%s.get().to_object())" %
(distinguishingArg, distinguishingArg),
lambda s: (s[1][distinguishingIndex].type.isCallback() or
s[1][distinguishingIndex].type.isCallbackInterface() or
s[1][distinguishingIndex].type.isDictionary() or
s[1][distinguishingIndex].type.isObject()))
# The remaining cases are mutually exclusive. The
# pickFirstSignature calls are what change caseBody
# Check for strings or enums
if pickFirstSignature(None,
lambda s: (s[1][distinguishingIndex].type.isString() or
s[1][distinguishingIndex].type.isEnum())):
pass
# Check for primitives
elif pickFirstSignature(None,
lambda s: s[1][distinguishingIndex].type.isPrimitive()):
pass
# Check for "any"
elif pickFirstSignature(None,
lambda s: s[1][distinguishingIndex].type.isAny()):
pass
else:
# Just throw; we have no idea what we're supposed to
# do with this.
caseBody.append(CGGeneric("return Throw(cx, NS_ERROR_XPC_BAD_CONVERT_JS);"))
argCountCases.append(CGCase(str(argCount),
CGList(caseBody, "\n")))
overloadCGThings = []
overloadCGThings.append(
CGGeneric("let argcount = cmp::min(argc, %d);" %
maxArgCount))
overloadCGThings.append(
CGSwitch("argcount",
argCountCases,
CGGeneric("throw_type_error(cx, \"Not enough arguments to %s.\");\n"
"return 0;" % methodName)))
# XXXjdm Avoid unreachable statement warnings
# overloadCGThings.append(
# CGGeneric('panic!("We have an always-returning default case");\n'
# 'return 0;'))
self.cgRoot = CGWrapper(CGList(overloadCGThings, "\n"),
pre="\n")
def define(self):
return self.cgRoot.define()
def dictionaryHasSequenceMember(dictionary):
return (any(typeIsSequenceOrHasSequenceMember(m.type) for m in
dictionary.members) or
(dictionary.parent and
dictionaryHasSequenceMember(dictionary.parent)))
def typeIsSequenceOrHasSequenceMember(type):
if type.nullable():
type = type.inner
if type.isSequence():
return True
if type.isArray():
elementType = type.inner
return typeIsSequenceOrHasSequenceMember(elementType)
if type.isDictionary():
return dictionaryHasSequenceMember(type.inner)
if type.isUnion():
return any(typeIsSequenceOrHasSequenceMember(m.type) for m in
type.flatMemberTypes)
return False
def typeNeedsRooting(type, descriptorProvider):
return (type.isGeckoInterface() and
descriptorProvider.getDescriptor(type.unroll().inner.identifier.name).needsRooting)
def union_native_type(t):
name = t.unroll().name
return 'UnionTypes::%s' % name
class JSToNativeConversionInfo():
"""
An object representing information about a JS-to-native conversion.
"""
def __init__(self, template, default=None, declType=None,
needsRooting=False):
"""
template: A string representing the conversion code. This will have
template substitution performed on it as follows:
${val} is a handle to the JS::Value in question
default: A string or None representing rust code for default value(if any).
declType: A CGThing representing the native C++ type we're converting
to. This is allowed to be None if the conversion code is
supposed to be used as-is.
needsRooting: A boolean indicating whether the caller has to root
the result
"""
assert isinstance(template, str)
assert declType is None or isinstance(declType, CGThing)
self.template = template
self.default = default
self.declType = declType
self.needsRooting = needsRooting
def getJSToNativeConversionInfo(type, descriptorProvider, failureCode=None,
isDefinitelyObject=False,
isMember=False,
isArgument=False,
invalidEnumValueFatal=True,
defaultValue=None,
treatNullAs="Default",
isEnforceRange=False,
isClamp=False,
exceptionCode=None,
allowTreatNonObjectAsNull=False,
isCallbackReturnValue=False,
sourceDescription="value"):
"""
Get a template for converting a JS value to a native object based on the
given type and descriptor. If failureCode is given, then we're actually
testing whether we can convert the argument to the desired type. That
means that failures to convert due to the JS value being the wrong type of
value need to use failureCode instead of throwing exceptions. Failures to
convert that are due to JS exceptions (from toString or valueOf methods) or
out of memory conditions need to throw exceptions no matter what
failureCode is.
If isDefinitelyObject is True, that means we know the value
isObject() and we have no need to recheck that.
if isMember is True, we're being converted from a property of some
JS object, not from an actual method argument, so we can't rely on
our jsval being rooted or outliving us in any way. Any caller
passing true needs to ensure that it is handled correctly in
typeIsSequenceOrHasSequenceMember.
invalidEnumValueFatal controls whether an invalid enum value conversion
attempt will throw (if true) or simply return without doing anything (if
false).
If defaultValue is not None, it's the IDL default value for this conversion
If isEnforceRange is true, we're converting an integer and throwing if the
value is out of range.
If isClamp is true, we're converting an integer and clamping if the
value is out of range.
If allowTreatNonObjectAsNull is true, then [TreatNonObjectAsNull]
extended attributes on nullable callback functions will be honored.
The return value from this function is an object of JSToNativeConversionInfo consisting of four things:
1) A string representing the conversion code. This will have template
substitution performed on it as follows:
${val} replaced by an expression for the JS::Value in question
2) A string or None representing Rust code for the default value (if any).
3) A CGThing representing the native C++ type we're converting to
(declType). This is allowed to be None if the conversion code is
supposed to be used as-is.
4) A boolean indicating whether the caller has to root the result.
"""
# We should not have a defaultValue if we know we're an object
assert(not isDefinitelyObject or defaultValue is None)
# If exceptionCode is not set, we'll just rethrow the exception we got.
# Note that we can't just set failureCode to exceptionCode, because setting
# failureCode will prevent pending exceptions from being set in cases when
# they really should be!
if exceptionCode is None:
exceptionCode = "return JSFalse;"
needsRooting = typeNeedsRooting(type, descriptorProvider)
def handleOptional(template, declType, default):
assert (defaultValue is None) == (default is None)
return JSToNativeConversionInfo(template, default, declType, needsRooting=needsRooting)
# Unfortunately, .capitalize() on a string will lowercase things inside the
# string, which we do not want.
def firstCap(string):
return string[0].upper() + string[1:]
# Helper functions for dealing with failures due to the JS value being the
# wrong type of value.
def onFailureNotAnObject(failureCode):
return CGWrapper(
CGGeneric(
failureCode or
('throw_type_error(cx, "%s is not an object.");\n'
'%s' % (firstCap(sourceDescription), exceptionCode))),
post="\n")
def onFailureNotCallable(failureCode):
return CGWrapper(
CGGeneric(
failureCode or
('throw_type_error(cx, \"%s is not callable.\");\n'
'%s' % (firstCap(sourceDescription), exceptionCode))))
# A helper function for handling null default values. Checks that the
# default value, if it exists, is null.
def handleDefaultNull(nullValue):
if defaultValue is None:
return None
if not isinstance(defaultValue, IDLNullValue):
raise TypeError("Can't handle non-null default value here")
assert type.nullable() or type.isDictionary()
return nullValue
# A helper function for wrapping up the template body for
# possibly-nullable objecty stuff
def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type,
failureCode=None):
if not isDefinitelyObject:
# Handle the non-object cases by wrapping up the whole
# thing in an if cascade.
templateBody = (
"if ${val}.get().is_object() {\n" +
CGIndenter(CGGeneric(templateBody)).define() + "\n")
if type.nullable():
templateBody += (
"} else if ${val}.get().is_null_or_undefined() {\n"
" %s\n") % nullValue
templateBody += (
"} else {\n" +
CGIndenter(onFailureNotAnObject(failureCode)).define() +
"}")
return templateBody
assert not (isEnforceRange and isClamp) # These are mutually exclusive
if type.isArray():
raise TypeError("Can't handle array arguments yet")
if type.isSequence():
raise TypeError("Can't handle sequence arguments yet")
if type.isUnion():
declType = CGGeneric(union_native_type(type))
if type.nullable():
declType = CGWrapper(declType, pre="Option<", post=" >")
templateBody = ("match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n"
" Ok(value) => value,\n"
" Err(()) => { %s },\n"
"}" % exceptionCode)
return handleOptional(templateBody, declType, handleDefaultNull("None"))
if type.isGeckoInterface():
assert not isEnforceRange and not isClamp
descriptor = descriptorProvider.getDescriptor(
type.unroll().inner.identifier.name)
if descriptor.interface.isCallback():
name = descriptor.nativeType
declType = CGWrapper(CGGeneric(name), pre="Rc<", post=">")
template = "%s::new(${val}.get().to_object())" % name
if type.nullable():
declType = CGWrapper(declType, pre="Option<", post=">")
template = wrapObjectTemplate("Some(%s)" % template, "None",
isDefinitelyObject, type,
failureCode)
return handleOptional(template, declType, handleDefaultNull("None"))
if isMember:
descriptorType = descriptor.memberType
elif isArgument:
descriptorType = descriptor.argumentType
else:
descriptorType = descriptor.nativeType
templateBody = ""
if descriptor.interface.isConsequential():
raise TypeError("Consequential interface %s being used as an "
"argument" % descriptor.interface.identifier.name)
if failureCode is None:
substitutions = {
"sourceDescription": sourceDescription,
"interface": descriptor.interface.identifier.name,
"exceptionCode": exceptionCode,
}
unwrapFailureCode = string.Template(
'throw_type_error(cx, "${sourceDescription} does not '
'implement interface ${interface}.");\n'
'${exceptionCode}').substitute(substitutions)
else:
unwrapFailureCode = failureCode
templateBody = str(
CastableObjectUnwrapper(descriptor, "${val}", unwrapFailureCode, "value"))
declType = CGGeneric(descriptorType)
if type.nullable():
templateBody = "Some(%s)" % templateBody
declType = CGWrapper(declType, pre="Option<", post=">")
templateBody = wrapObjectTemplate(templateBody, "None",
isDefinitelyObject, type, failureCode)
return handleOptional(templateBody, declType, handleDefaultNull("None"))
if type.isSpiderMonkeyInterface():
raise TypeError("Can't handle SpiderMonkey interface arguments yet")
if type.isDOMString():
assert not isEnforceRange and not isClamp
treatAs = {
"Default": "StringificationBehavior::Default",
"EmptyString": "StringificationBehavior::Empty",
}
if treatNullAs not in treatAs:
raise TypeError("We don't support [TreatNullAs=%s]" % treatNullAs)
if type.nullable():
# Note: the actual behavior passed here doesn't matter for nullable
# strings.
nullBehavior = "StringificationBehavior::Default"
else:
nullBehavior = treatAs[treatNullAs]
conversionCode = (
"match FromJSValConvertible::from_jsval(cx, ${val}, %s) {\n"
" Ok(strval) => strval,\n"
" Err(_) => { %s },\n"
"}" % (nullBehavior, exceptionCode))
if defaultValue is None:
default = None
elif isinstance(defaultValue, IDLNullValue):
assert type.nullable()
default = "None"
else:
assert defaultValue.type.tag() == IDLType.Tags.domstring
default = '"%s".to_owned()' % defaultValue.value
if type.nullable():
default = "Some(%s)" % default
declType = "DOMString"
if type.nullable():
declType = "Option<%s>" % declType
return handleOptional(conversionCode, CGGeneric(declType), default)
if type.isUSVString():
assert not isEnforceRange and not isClamp
conversionCode = (
"match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n"
" Ok(strval) => strval,\n"
" Err(_) => { %s },\n"
"}" % exceptionCode)
if defaultValue is None:
default = None
elif isinstance(defaultValue, IDLNullValue):
assert type.nullable()
default = "None"
else:
assert defaultValue.type.tag() in (IDLType.Tags.domstring, IDLType.Tags.usvstring)
default = 'USVString("%s".to_owned())' % defaultValue.value
if type.nullable():
default = "Some(%s)" % default
declType = "USVString"
if type.nullable():
declType = "Option<%s>" % declType
return handleOptional(conversionCode, CGGeneric(declType), default)
if type.isByteString():
assert not isEnforceRange and not isClamp
conversionCode = (
"match FromJSValConvertible::from_jsval(cx, ${val}, ()) {\n"
" Ok(strval) => strval,\n"
" Err(_) => { %s },\n"
"}" % exceptionCode)
declType = CGGeneric("ByteString")
if type.nullable():
declType = CGWrapper(declType, pre="Option<", post=">")
return handleOptional(conversionCode, declType, handleDefaultNull("None"))
if type.isEnum():
assert not isEnforceRange and not isClamp
if type.nullable():
raise TypeError("We don't support nullable enumerated arguments "
"yet")
enum = type.inner.identifier.name
if invalidEnumValueFatal:
handleInvalidEnumValueCode = exceptionCode
else:
handleInvalidEnumValueCode = "return 1;"
template = (
"match find_enum_string_index(cx, ${val}, %(values)s) {\n"
" Err(_) => { %(exceptionCode)s },\n"
" Ok(None) => { %(handleInvalidEnumValueCode)s },\n"
" Ok(Some(index)) => {\n"
" //XXXjdm need some range checks up in here.\n"
" unsafe { mem::transmute(index) }\n"
" },\n"
"}" % {"values": enum + "Values::strings",
"exceptionCode": exceptionCode,
"handleInvalidEnumValueCode": handleInvalidEnumValueCode})
if defaultValue is not None:
assert(defaultValue.type.tag() == IDLType.Tags.domstring)
default = "%s::%s" % (enum, getEnumValueName(defaultValue.value))
else:
default = None
return handleOptional(template, CGGeneric(enum), default)
if type.isCallback():
assert not isEnforceRange and not isClamp
assert not type.treatNonCallableAsNull()
assert not type.treatNonObjectAsNull() or type.nullable()
assert not type.treatNonObjectAsNull() or not type.treatNonCallableAsNull()
callback = type.unroll().callback
declType = CGGeneric('%s::%s' % (callback.module(), callback.identifier.name))
finalDeclType = CGTemplatedType("Rc", declType)
conversion = CGCallbackTempRoot(declType.define())
if type.nullable():
declType = CGTemplatedType("Option", declType)
finalDeclType = CGTemplatedType("Option", finalDeclType)
conversion = CGWrapper(conversion, pre="Some(", post=")")
if allowTreatNonObjectAsNull and type.treatNonObjectAsNull():
if not isDefinitelyObject:
haveObject = "${val}.get().is_object()"
template = CGIfElseWrapper(haveObject,
conversion,
CGGeneric("None")).define()
else:
template = conversion
else:
template = CGIfElseWrapper("IsCallable(${val}.get().to_object()) != 0",
conversion,
onFailureNotCallable(failureCode)).define()
template = wrapObjectTemplate(
template,
"None",
isDefinitelyObject,
type,
failureCode)
if defaultValue is not None:
assert allowTreatNonObjectAsNull
assert type.treatNonObjectAsNull()
assert type.nullable()
assert isinstance(defaultValue, IDLNullValue)
default = "None"
else:
default = None
return JSToNativeConversionInfo(template, default, finalDeclType, needsRooting=needsRooting)
if type.isAny():
assert not isEnforceRange and not isClamp
declType = ""
default = ""
if isMember == "Dictionary":
# TODO: Need to properly root dictionaries
# https://github.com/servo/servo/issues/6381
declType = CGGeneric("JSVal")
if defaultValue is None:
default = None
elif isinstance(defaultValue, IDLNullValue):
default = "NullValue()"
elif isinstance(defaultValue, IDLUndefinedValue):
default = "UndefinedValue()"
else:
raise TypeError("Can't handle non-null, non-undefined default value here")
else:
declType = CGGeneric("HandleValue")
if defaultValue is None:
default = None
elif isinstance(defaultValue, IDLNullValue):
default = "HandleValue::null()"
elif isinstance(defaultValue, IDLUndefinedValue):
default = "HandleValue::undefined()"
else:
raise TypeError("Can't handle non-null, non-undefined default value here")
return handleOptional("${val}", declType, default)
if type.isObject():
assert not isEnforceRange and not isClamp
# TODO: Need to root somehow
# https://github.com/servo/servo/issues/6382
declType = CGGeneric("*mut JSObject")
templateBody = wrapObjectTemplate("${val}.get().to_object()",
"ptr::null_mut()",
isDefinitelyObject, type, failureCode)
return handleOptional(templateBody, declType,
handleDefaultNull("ptr::null_mut()"))
if type.isDictionary():
if failureCode is not None:
raise TypeError("Can't handle dictionaries when failureCode is not None")
# There are no nullable dictionaries
assert not type.nullable()
typeName = CGDictionary.makeDictionaryName(type.inner)
declType = CGGeneric(typeName)
template = ("match %s::new(cx, ${val}) {\n"
" Ok(dictionary) => dictionary,\n"
" Err(_) => return 0,\n"
"}" % typeName)
return handleOptional(template, declType, handleDefaultNull("%s::empty(cx)" % typeName))
if type.isVoid():
# This one only happens for return values, and its easy: Just
# ignore the jsval.
return JSToNativeConversionInfo("", None, None, needsRooting=False)
if not type.isPrimitive():
raise TypeError("Need conversion for argument type '%s'" % str(type))
if type.isInteger():
if isEnforceRange:
conversionBehavior = "ConversionBehavior::EnforceRange"
elif isClamp:
conversionBehavior = "ConversionBehavior::Clamp"
else:
conversionBehavior = "ConversionBehavior::Default"
else:
assert not isEnforceRange and not isClamp
conversionBehavior = "()"
if failureCode is None:
failureCode = 'return 0'
declType = CGGeneric(builtinNames[type.tag()])
if type.nullable():
declType = CGWrapper(declType, pre="Option<", post=">")
template = (
"match FromJSValConvertible::from_jsval(cx, ${val}, %s) {\n"
" Ok(v) => v,\n"
" Err(_) => { %s }\n"
"}" % (conversionBehavior, exceptionCode))
if defaultValue is not None:
if isinstance(defaultValue, IDLNullValue):
assert type.nullable()
defaultStr = "None"
else:
tag = defaultValue.type.tag()
if tag in [IDLType.Tags.float, IDLType.Tags.double]:
defaultStr = "Finite::wrap(%s)" % defaultValue.value
elif tag in numericTags:
defaultStr = str(defaultValue.value)
else:
assert(tag == IDLType.Tags.bool)
defaultStr = toStringBool(defaultValue.value)
if type.nullable():
defaultStr = "Some(%s)" % defaultStr
else:
defaultStr = None
return handleOptional(template, declType, defaultStr)
def instantiateJSToNativeConversionTemplate(templateBody, replacements,
declType, declName, needsRooting):
"""
Take the templateBody and declType as returned by
getJSToNativeConversionInfo, a set of replacements as required by the
strings in such a templateBody, and a declName, and generate code to
convert into a stack Rust binding with that name.
"""
result = CGList([], "\n")
conversion = CGGeneric(string.Template(templateBody).substitute(replacements))
if declType is not None:
newDecl = [
CGGeneric("let "),
CGGeneric(declName),
CGGeneric(": "),
declType,
CGGeneric(" = "),
conversion,
CGGeneric(";"),
]
result.append(CGList(newDecl))
else:
result.append(conversion)
# Add an empty CGGeneric to get an extra newline after the argument
# conversion.
result.append(CGGeneric(""))
return result
def convertConstIDLValueToJSVal(value):
if isinstance(value, IDLNullValue):
return "NullVal"
tag = value.type.tag()
if tag in [IDLType.Tags.int8, IDLType.Tags.uint8, IDLType.Tags.int16,
IDLType.Tags.uint16, IDLType.Tags.int32]:
return "IntVal(%s)" % (value.value)
if tag == IDLType.Tags.uint32:
return "UintVal(%s)" % (value.value)
if tag in [IDLType.Tags.int64, IDLType.Tags.uint64]:
return "DoubleVal(%s)" % (value.value)
if tag == IDLType.Tags.bool:
return "BoolVal(true)" if value.value else "BoolVal(false)"
if tag in [IDLType.Tags.unrestricted_float, IDLType.Tags.float,
IDLType.Tags.unrestricted_double, IDLType.Tags.double]:
return "DoubleVal(%s)" % (value.value)
raise TypeError("Const value of unhandled type: " + value.type)
class CGArgumentConverter(CGThing):
"""
A class that takes an IDL argument object, its index in the
argument list, and the argv and argc strings and generates code to
unwrap the argument to the right native type.
"""
def __init__(self, argument, index, args, argc, descriptorProvider,
invalidEnumValueFatal=True):
CGThing.__init__(self)
assert(not argument.defaultValue or argument.optional)
replacer = {
"index": index,
"argc": argc,
"args": args
}
condition = string.Template("${index} < ${argc}").substitute(replacer)
replacementVariables = {
"val": string.Template("${args}.get(${index})").substitute(replacer),
}
info = getJSToNativeConversionInfo(
argument.type,
descriptorProvider,
invalidEnumValueFatal=invalidEnumValueFatal,
defaultValue=argument.defaultValue,
treatNullAs=argument.treatNullAs,
isEnforceRange=argument.enforceRange,
isClamp=argument.clamp,
isMember="Variadic" if argument.variadic else False,
allowTreatNonObjectAsNull=argument.allowTreatNonCallableAsNull())
template = info.template
default = info.default
declType = info.declType
needsRooting = info.needsRooting
if not argument.variadic:
if argument.optional:
if argument.defaultValue:
assert default
template = CGIfElseWrapper(condition,
CGGeneric(template),
CGGeneric(default)).define()
else:
assert not default
declType = CGWrapper(declType, pre="Option<", post=">")
template = CGIfElseWrapper(condition,
CGGeneric("Some(%s)" % template),
CGGeneric("None")).define()
else:
assert not default
self.converter = instantiateJSToNativeConversionTemplate(
template, replacementVariables, declType, "arg%d" % index,
needsRooting)
else:
assert argument.optional
variadicConversion = {
"val": string.Template("${args}.get(variadicArg)").substitute(replacer),
}
innerConverter = instantiateJSToNativeConversionTemplate(
template, variadicConversion, declType, "slot",
needsRooting)
seqType = CGTemplatedType("Vec", declType)
variadicConversion = string.Template(
"let mut vector: ${seqType} = Vec::with_capacity((${argc} - ${index}) as usize);\n"
"for variadicArg in ${index}..${argc} {\n"
"${inner}\n"
" vector.push(slot);\n"
"}\n"
"vector"
).substitute({
"index": index,
"argc": argc,
"seqType": seqType.define(),
"inner": CGIndenter(innerConverter, 4).define(),
})
variadicConversion = CGIfElseWrapper(condition,
CGGeneric(variadicConversion),
CGGeneric("Vec::new()")).define()
self.converter = instantiateJSToNativeConversionTemplate(
variadicConversion, replacementVariables, seqType, "arg%d" % index,
False)
def define(self):
return self.converter.define()
def wrapForType(jsvalRef, result='result', successCode='return 1;', pre=''):
"""
Reflect a Rust value into JS.
* 'jsvalRef': a MutableHandleValue in which to store the result
of the conversion;
* 'result': the name of the variable in which the Rust value is stored;
* 'successCode': the code to run once we have done the conversion.
* 'pre': code to run before the conversion if rooting is necessary
"""
wrap = "%s\n(%s).to_jsval(cx, %s);" % (pre, result, jsvalRef)
if successCode:
wrap += "\n%s" % successCode
return wrap
def typeNeedsCx(type, retVal=False):
if type is None:
return False
if type.nullable():
type = type.inner
if type.isSequence() or type.isArray():
type = type.inner
if type.isUnion():
return any(typeNeedsCx(t) for t in type.unroll().flatMemberTypes)
if retVal and type.isSpiderMonkeyInterface():
return True
return type.isAny() or type.isObject()
# Returns a CGThing containing the type of the return value.
def getRetvalDeclarationForType(returnType, descriptorProvider):
if returnType is None or returnType.isVoid():
# Nothing to declare
return CGGeneric("()")
if returnType.isPrimitive() and returnType.tag() in builtinNames:
result = CGGeneric(builtinNames[returnType.tag()])
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
if returnType.isDOMString():
result = CGGeneric("DOMString")
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
if returnType.isUSVString():
result = CGGeneric("USVString")
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
if returnType.isByteString():
result = CGGeneric("ByteString")
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
if returnType.isEnum():
result = CGGeneric(returnType.unroll().inner.identifier.name)
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
if returnType.isGeckoInterface():
descriptor = descriptorProvider.getDescriptor(
returnType.unroll().inner.identifier.name)
result = CGGeneric(descriptor.returnType)
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
if returnType.isCallback():
callback = returnType.unroll().callback
result = CGGeneric('Rc<%s::%s>' % (callback.module(), callback.identifier.name))
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
if returnType.isUnion():
result = CGGeneric(union_native_type(returnType))
if returnType.nullable():
result = CGWrapper(result, pre="Option<", post=">")
return result
# TODO: Return the value through a MutableHandleValue outparam
# https://github.com/servo/servo/issues/6307
if returnType.isAny():
return CGGeneric("JSVal")
if returnType.isObject() or returnType.isSpiderMonkeyInterface():
return CGGeneric("*mut JSObject")
if returnType.isSequence():
raise TypeError("We don't support sequence return values")
if returnType.isDictionary():
nullable = returnType.nullable()
dictName = returnType.inner.name if nullable else returnType.name
result = CGGeneric(dictName)
if typeNeedsRooting(returnType, descriptorProvider):
raise TypeError("We don't support rootable dictionaries return values")
if nullable:
result = CGWrapper(result, pre="Option<", post=">")
return result
raise TypeError("Don't know how to declare return value for %s" %
returnType)
class PropertyDefiner:
"""
A common superclass for defining things on prototype objects.
Subclasses should implement generateArray to generate the actual arrays of
things we're defining. They should also set self.regular to the list of
things exposed to web pages.
"""
def __init__(self, descriptor, name):
self.descriptor = descriptor
self.name = name
def variableName(self):
return "s" + self.name
def length(self):
return len(self.regular)
def __str__(self):
# We only need to generate id arrays for things that will end
# up used via ResolveProperty or EnumerateProperties.
return self.generateArray(self.regular, self.variableName())
def generatePrefableArray(self, array, name, specTemplate, specTerminator,
specType, getDataTuple):
"""
This method generates our various arrays.
array is an array of interface members as passed to generateArray
name is the name as passed to generateArray
specTemplate is a template for each entry of the spec array
specTerminator is a terminator for the spec array (inserted at the end
of the array), or None
specType is the actual typename of our spec
getDataTuple is a callback function that takes an array entry and
returns a tuple suitable for substitution into specTemplate.
"""
assert(len(array) is not 0)
specs = []
for member in array:
specs.append(specTemplate % getDataTuple(member))
if specTerminator:
specs.append(specTerminator)
return (("const %s: &'static [%s] = &[\n" +
",\n".join(specs) + "\n" +
"];\n") % (name, specType))
# The length of a method is the minimum of the lengths of the
# argument lists of all its overloads.
def methodLength(method):
signatures = method.signatures()
return min(
len([arg for arg in arguments if not arg.optional and not arg.variadic])
for (_, arguments) in signatures)
class MethodDefiner(PropertyDefiner):
"""
A class for defining methods on a prototype object.
"""
def __init__(self, descriptor, name, static):
PropertyDefiner.__init__(self, descriptor, name)
# FIXME https://bugzilla.mozilla.org/show_bug.cgi?id=772822
# We should be able to check for special operations without an
# identifier. For now we check if the name starts with __
# Ignore non-static methods for callback interfaces
if not descriptor.interface.isCallback() or static:
methods = [m for m in descriptor.interface.members if
m.isMethod() and m.isStatic() == static and
not m.isIdentifierLess()]
else:
methods = []
self.regular = [{"name": m.identifier.name,
"methodInfo": not m.isStatic(),
"length": methodLength(m),
"flags": "JSPROP_ENUMERATE"} for m in methods]
# FIXME Check for an existing iterator on the interface first.
if any(m.isGetter() and m.isIndexed() for m in methods):
self.regular.append({"name": '@@iterator',
"methodInfo": False,
"selfHostedName": "ArrayValues",
"length": 0,
"flags": "JSPROP_ENUMERATE"})
if not static:
stringifier = descriptor.operations['Stringifier']
if stringifier:
self.regular.append({
"name": "toString",
"nativeName": stringifier.identifier.name,
"length": 0,
"flags": "JSPROP_ENUMERATE"
})
def generateArray(self, array, name):
if len(array) == 0:
return ""
def specData(m):
# TODO: Use something like JS_FNSPEC
# https://github.com/servo/servo/issues/6391
if "selfHostedName" in m:
selfHostedName = '%s as *const u8 as *const i8' % str_to_const_array(m["selfHostedName"])
assert not m.get("methodInfo", True)
accessor = "None"
jitinfo = "0 as *const JSJitInfo"
else:
selfHostedName = "0 as *const i8"
if m.get("methodInfo", True):
identifier = m.get("nativeName", m["name"])
jitinfo = "&%s_methodinfo" % identifier
accessor = "Some(generic_method)"
else:
jitinfo = "0 as *const JSJitInfo"
accessor = 'Some(%s)' % m.get("nativeName", m["name"])
if m["name"].startswith("@@"):
return ('(SymbolCode::%s as i32 + 1)'
% m["name"][2:], accessor, jitinfo, m["length"], m["flags"], selfHostedName)
return (str_to_const_array(m["name"]), accessor, jitinfo, m["length"], m["flags"], selfHostedName)
return self.generatePrefableArray(
array, name,
' JSFunctionSpec {\n'
' name: %s as *const u8 as *const libc::c_char,\n'
' call: JSNativeWrapper {op: %s, info: %s},\n'
' nargs: %s,\n'
' flags: %s as u16,\n'
' selfHostedName: %s\n'
' }',
' JSFunctionSpec {\n'
' name: 0 as *const libc::c_char,\n'
' call: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo },\n'
' nargs: 0,\n'
' flags: 0,\n'
' selfHostedName: 0 as *const i8\n'
' }',
'JSFunctionSpec',
specData)
class AttrDefiner(PropertyDefiner):
def __init__(self, descriptor, name, static):
PropertyDefiner.__init__(self, descriptor, name)
self.name = name
self.regular = [
m
for m in descriptor.interface.members
if m.isAttr() and m.isStatic() == static
]
self.static = static
def generateArray(self, array, name):
if len(array) == 0:
return ""
def flags(attr):
return "JSPROP_SHARED | JSPROP_ENUMERATE"
def getter(attr):
if self.static:
accessor = 'get_' + attr.identifier.name
jitinfo = "0 as *const JSJitInfo"
else:
if attr.hasLenientThis():
accessor = "generic_lenient_getter"
else:
accessor = "generic_getter"
jitinfo = "&%s_getterinfo" % attr.identifier.name
return ("JSNativeWrapper { op: Some(%(native)s), info: %(info)s }"
% {"info": jitinfo,
"native": accessor})
def setter(attr):
if attr.readonly and not attr.getExtendedAttribute("PutForwards"):
return "JSNativeWrapper { op: None, info: 0 as *const JSJitInfo }"
if self.static:
accessor = 'set_' + attr.identifier.name
jitinfo = "0 as *const JSJitInfo"
else:
if attr.hasLenientThis():
accessor = "generic_lenient_setter"
else:
accessor = "generic_setter"
jitinfo = "&%s_setterinfo" % attr.identifier.name
return ("JSNativeWrapper { op: Some(%(native)s), info: %(info)s }"
% {"info": jitinfo,
"native": accessor})
def specData(attr):
return (str_to_const_array(attr.identifier.name), flags(attr), getter(attr),
setter(attr))
return self.generatePrefableArray(
array, name,
' JSPropertySpec {\n'
' name: %s as *const u8 as *const libc::c_char,\n'
' flags: ((%s) & 0xFF) as u8,\n'
' getter: %s,\n'
' setter: %s\n'
' }',
' JSPropertySpec {\n'
' name: 0 as *const libc::c_char,\n'
' flags: 0,\n'
' getter: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo },\n'
' setter: JSNativeWrapper { op: None, info: 0 as *const JSJitInfo }\n'
' }',
'JSPropertySpec',
specData)
class ConstDefiner(PropertyDefiner):
"""
A class for definining constants on the interface object
"""
def __init__(self, descriptor, name):
PropertyDefiner.__init__(self, descriptor, name)
self.name = name
self.regular = [m for m in descriptor.interface.members if m.isConst()]
def generateArray(self, array, name):
if len(array) == 0:
return ""
def specData(const):
return (str_to_const_array(const.identifier.name),
convertConstIDLValueToJSVal(const.value))
return self.generatePrefableArray(
array, name,
' ConstantSpec { name: %s, value: %s }',
None,
'ConstantSpec',
specData)
# We'll want to insert the indent at the beginnings of lines, but we
# don't want to indent empty lines. So only indent lines that have a
# non-newline character on them.
lineStartDetector = re.compile("^(?=[^\n])", re.MULTILINE)
class CGIndenter(CGThing):
"""
A class that takes another CGThing and generates code that indents that
CGThing by some number of spaces. The default indent is two spaces.
"""
def __init__(self, child, indentLevel=4):
CGThing.__init__(self)
self.child = child
self.indent = " " * indentLevel
def define(self):
defn = self.child.define()
if defn != "":
return re.sub(lineStartDetector, self.indent, defn)
else:
return defn
class CGWrapper(CGThing):
"""
Generic CGThing that wraps other CGThings with pre and post text.
"""
def __init__(self, child, pre="", post="", reindent=False):
CGThing.__init__(self)
self.child = child
self.pre = pre
self.post = post
self.reindent = reindent
def define(self):
defn = self.child.define()
if self.reindent:
# We don't use lineStartDetector because we don't want to
# insert whitespace at the beginning of our _first_ line.
defn = stripTrailingWhitespace(
defn.replace("\n", "\n" + (" " * len(self.pre))))
return self.pre + defn + self.post
class CGImports(CGWrapper):
"""
Generates the appropriate import/use statements.
"""
def __init__(self, child, descriptors, callbacks, imports, ignored_warnings=None):
"""
Adds a set of imports.
"""
if ignored_warnings is None:
ignored_warnings = [
# Allow unreachable_code because we use 'break' in a way that
# sometimes produces two 'break's in a row. See for example
# CallbackMember.getArgConversions.
'unreachable_code',
'non_camel_case_types',
'non_upper_case_globals',
'unused_parens',
'unused_imports',
'unused_variables',
'unused_unsafe',
'unused_mut',
'unused_assignments',
'dead_code',
]
def componentTypes(type):
if type.nullable():
type = type.unroll()
if type.isUnion():
return type.flatMemberTypes
return [type]
def isImportable(type):
if not type.isType():
assert type.isInterface()
return not type.isCallback()
return type.isNonCallbackInterface() and not type.builtin
def relatedTypesForSignatures(method):
types = []
for (returnType, arguments) in method.signatures():
types += componentTypes(returnType)
for arg in arguments:
types += componentTypes(arg.type)
return types
def getIdentifier(t):
if t.isType():
return t.inner.identifier
assert t.isInterface()
return t.identifier
types = []
for d in descriptors:
types += [d.interface]
members = d.interface.members + d.interface.namedConstructors
constructor = d.interface.ctor()
if constructor:
members += [constructor]
if d.proxy:
members += [o for o in d.operations.values() if o]
for m in members:
if m.isMethod():
types += relatedTypesForSignatures(m)
elif m.isAttr():
types += componentTypes(m.type)
for c in callbacks:
types += relatedTypesForSignatures(c)
imports += ['dom::types::%s' % getIdentifier(t).name for t in types if isImportable(t)]
statements = []
if len(ignored_warnings) > 0:
statements.append('#![allow(%s)]' % ','.join(ignored_warnings))
statements.extend('use %s;' % i for i in sorted(set(imports)))
CGWrapper.__init__(self, child,
pre='\n'.join(statements) + '\n\n')
class CGIfWrapper(CGWrapper):
def __init__(self, child, condition):
pre = CGWrapper(CGGeneric(condition), pre="if ", post=" {\n",
reindent=True)
CGWrapper.__init__(self, CGIndenter(child), pre=pre.define(),
post="\n}")
class CGTemplatedType(CGWrapper):
def __init__(self, templateName, child):
CGWrapper.__init__(self, child, pre=templateName + "<", post=">")
class CGNamespace(CGWrapper):
def __init__(self, namespace, child, public=False):
pre = "%smod %s {\n" % ("pub " if public else "", namespace)
post = "} // mod %s" % namespace
CGWrapper.__init__(self, child, pre=pre, post=post)
@staticmethod
def build(namespaces, child, public=False):
"""
Static helper method to build multiple wrapped namespaces.
"""
if not namespaces:
return child
inner = CGNamespace.build(namespaces[1:], child, public=public)
return CGNamespace(namespaces[0], inner, public=public)
def DOMClass(descriptor):
protoList = ['PrototypeList::ID::' + proto for proto in descriptor.prototypeChain]
# Pad out the list to the right length with ID::Count so we
# guarantee that all the lists are the same length. id::Count
# is never the ID of any prototype, so it's safe to use as
# padding.
protoList.extend(['PrototypeList::ID::Count'] * (descriptor.config.maxProtoChainLength - len(protoList)))
prototypeChainString = ', '.join(protoList)
return """\
DOMClass {
interface_chain: [ %s ],
native_hooks: &sNativePropertyHooks,
}""" % prototypeChainString
class CGDOMJSClass(CGThing):
"""
Generate a DOMJSClass for a given descriptor
"""
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def define(self):
traceHook = 'Some(%s)' % TRACE_HOOK_NAME
if self.descriptor.isGlobal():
traceHook = "Some(js::jsapi::_Z24JS_GlobalObjectTraceHookP8JSTracerP8JSObject)"
flags = "JSCLASS_IS_GLOBAL | JSCLASS_DOM_GLOBAL"
slots = "JSCLASS_GLOBAL_SLOT_COUNT + 1"
else:
flags = "0"
slots = "1"
return """\
static Class: DOMJSClass = DOMJSClass {
base: js::jsapi::Class {
name: %s as *const u8 as *const libc::c_char,
flags: JSCLASS_IS_DOMJSCLASS | JSCLASS_IMPLEMENTS_BARRIERS | %s |
(((%s) & JSCLASS_RESERVED_SLOTS_MASK) <<
JSCLASS_RESERVED_SLOTS_SHIFT), //JSCLASS_HAS_RESERVED_SLOTS(%s),
addProperty: None,
delProperty: None,
getProperty: None,
setProperty: None,
enumerate: None,
resolve: None,
convert: None,
finalize: Some(%s),
call: None,
hasInstance: None,
construct: None,
trace: %s,
spec: js::jsapi::ClassSpec {
createConstructor: None,
createPrototype: None,
constructorFunctions: 0 as *const js::jsapi::JSFunctionSpec,
constructorProperties: 0 as *const js::jsapi::JSPropertySpec,
prototypeFunctions: 0 as *const js::jsapi::JSFunctionSpec,
prototypeProperties: 0 as *const js::jsapi::JSPropertySpec,
finishInit: None,
flags: 0,
},
ext: js::jsapi::ClassExtension {
outerObject: %s,
innerObject: None,
isWrappedNative: 0,
weakmapKeyDelegateOp: None,
objectMovedOp: None,
},
ops: js::jsapi::ObjectOps {
lookupProperty: None,
defineProperty: None,
hasProperty: None,
getProperty: None,
setProperty: None,
getOwnPropertyDescriptor: None,
deleteProperty: None,
watch: None,
unwatch: None,
getElements: None,
enumerate: None,
thisObject: %s,
},
},
dom_class: %s
};""" % (str_to_const_array(self.descriptor.interface.identifier.name),
flags, slots, slots,
FINALIZE_HOOK_NAME, traceHook,
self.descriptor.outerObjectHook,
self.descriptor.outerObjectHook,
CGGeneric(DOMClass(self.descriptor)).define())
def str_to_const_array(s):
return "b\"%s\\0\"" % s
class CGPrototypeJSClass(CGThing):
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def define(self):
return """\
static PrototypeClass: JSClass = JSClass {
name: %s as *const u8 as *const libc::c_char,
flags: (1 & JSCLASS_RESERVED_SLOTS_MASK) << JSCLASS_RESERVED_SLOTS_SHIFT, //JSCLASS_HAS_RESERVED_SLOTS(1)
addProperty: None,
delProperty: None,
getProperty: None,
setProperty: None,
enumerate: None,
resolve: None,
convert: None,
finalize: None,
call: None,
hasInstance: None,
construct: None,
trace: None,
reserved: [0 as *mut libc::c_void; 25]
};
""" % str_to_const_array(self.descriptor.interface.identifier.name + "Prototype")
class CGInterfaceObjectJSClass(CGThing):
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def define(self):
if True:
return ""
ctorname = "0 as *const u8" if not self.descriptor.interface.ctor() else CONSTRUCT_HOOK_NAME
hasinstance = HASINSTANCE_HOOK_NAME
return """\
const InterfaceObjectClass: JSClass = {
%s, 0,
JS_PropertyStub,
JS_PropertyStub,
JS_PropertyStub,
JS_StrictPropertyStub,
JS_EnumerateStub,
JS_ResolveStub,
JS_ConvertStub,
0 as *const u8,
0 as *const u8,
%s,
%s,
%s,
0 as *const u8,
JSCLASS_NO_INTERNAL_MEMBERS
};
""" % (str_to_const_array("Function"), ctorname, hasinstance, ctorname)
class CGList(CGThing):
"""
Generate code for a list of GCThings. Just concatenates them together, with
an optional joiner string. "\n" is a common joiner.
"""
def __init__(self, children, joiner=""):
CGThing.__init__(self)
self.children = children
self.joiner = joiner
def append(self, child):
self.children.append(child)
def prepend(self, child):
self.children.insert(0, child)
def join(self, generator):
return self.joiner.join(filter(lambda s: len(s) > 0, (child for child in generator)))
def define(self):
return self.join(child.define() for child in self.children if child is not None)
class CGIfElseWrapper(CGList):
def __init__(self, condition, ifTrue, ifFalse):
kids = [CGIfWrapper(ifTrue, condition),
CGWrapper(CGIndenter(ifFalse), pre=" else {\n", post="\n}")]
CGList.__init__(self, kids)
class CGGeneric(CGThing):
"""
A class that spits out a fixed string into the codegen. Can spit out a
separate string for the declaration too.
"""
def __init__(self, text):
self.text = text
def define(self):
return self.text
class CGCallbackTempRoot(CGGeneric):
def __init__(self, name):
CGGeneric.__init__(self, "%s::new(${val}.get().to_object())" % name)
def getAllTypes(descriptors, dictionaries, callbacks):
"""
Generate all the types we're dealing with. For each type, a tuple
containing type, descriptor, dictionary is yielded. The
descriptor and dictionary can be None if the type does not come
from a descriptor or dictionary; they will never both be non-None.
"""
for d in descriptors:
for t in getTypesFromDescriptor(d):
yield (t, d, None)
for dictionary in dictionaries:
for t in getTypesFromDictionary(dictionary):
yield (t, None, dictionary)
for callback in callbacks:
for t in getTypesFromCallback(callback):
yield (t, None, None)
def SortedTuples(l):
"""
Sort a list of tuples based on the first item in the tuple
"""
return sorted(l, key=operator.itemgetter(0))
def SortedDictValues(d):
"""
Returns a list of values from the dict sorted by key.
"""
# Create a list of tuples containing key and value, sorted on key.
d = SortedTuples(d.items())
# We're only interested in the values.
return (i[1] for i in d)
def UnionTypes(descriptors, dictionaries, callbacks, config):
"""
Returns a CGList containing CGUnionStructs for every union.
"""
imports = [
'dom::bindings::codegen::PrototypeList',
'dom::bindings::conversions::FromJSValConvertible',
'dom::bindings::conversions::ToJSValConvertible',
'dom::bindings::conversions::ConversionBehavior',
'dom::bindings::conversions::native_from_handlevalue',
'dom::bindings::conversions::StringificationBehavior',
'dom::bindings::error::throw_not_in_union',
'dom::bindings::js::Root',
'dom::types::*',
'js::jsapi::JSContext',
'js::jsapi::{HandleValue, MutableHandleValue}',
'js::jsval::JSVal',
'util::str::DOMString',
]
# Now find all the things we'll need as arguments and return values because
# we need to wrap or unwrap them.
unionStructs = dict()
for (t, descriptor, dictionary) in getAllTypes(descriptors, dictionaries, callbacks):
assert not descriptor or not dictionary
t = t.unroll()
if not t.isUnion():
continue
name = str(t)
if name not in unionStructs:
provider = descriptor or config.getDescriptorProvider()
unionStructs[name] = CGList([
CGUnionStruct(t, provider),
CGUnionConversionStruct(t, provider)
])
return CGImports(CGList(SortedDictValues(unionStructs), "\n\n"), [], [], imports, ignored_warnings=[])
class Argument():
"""
A class for outputting the type and name of an argument
"""
def __init__(self, argType, name, default=None, mutable=False):
self.argType = argType
self.name = name
self.default = default
self.mutable = mutable
def declare(self):
string = ('mut ' if self.mutable else '') + self.name + ((': ' + self.argType) if self.argType else '')
# XXXjdm Support default arguments somehow :/
# if self.default is not None:
# string += " = " + self.default
return string
def define(self):
return self.argType + ' ' + self.name
class CGAbstractMethod(CGThing):
"""
An abstract class for generating code for a method. Subclasses
should override definition_body to create the actual code.
descriptor is the descriptor for the interface the method is associated with
name is the name of the method as a string
returnType is the IDLType of the return value
args is a list of Argument objects
inline should be True to generate an inline method, whose body is
part of the declaration.
alwaysInline should be True to generate an inline method annotated with
MOZ_ALWAYS_INLINE.
If templateArgs is not None it should be a list of strings containing
template arguments, and the function will be templatized using those
arguments.
"""
def __init__(self, descriptor, name, returnType, args, inline=False,
alwaysInline=False, extern=False, pub=False, templateArgs=None,
unsafe=True):
CGThing.__init__(self)
self.descriptor = descriptor
self.name = name
self.returnType = returnType
self.args = args
self.alwaysInline = alwaysInline
self.extern = extern
self.templateArgs = templateArgs
self.pub = pub
self.unsafe = unsafe
def _argstring(self):
return ', '.join([a.declare() for a in self.args])
def _template(self):
if self.templateArgs is None:
return ''
return '<%s>\n' % ', '.join(self.templateArgs)
def _decorators(self):
decorators = []
if self.alwaysInline:
decorators.append('#[inline]')
if self.extern:
decorators.append('unsafe')
decorators.append('extern')
if self.pub:
decorators.append('pub')
if not decorators:
return ''
return ' '.join(decorators) + ' '
def _returnType(self):
return (" -> %s" % self.returnType) if self.returnType != "void" else ""
def define(self):
body = self.definition_body()
# Method will already be marked `unsafe` if `self.extern == True`
if self.unsafe and not self.extern:
body = CGWrapper(CGIndenter(body), pre="unsafe {\n", post="\n}")
return CGWrapper(CGIndenter(body),
pre=self.definition_prologue(),
post=self.definition_epilogue()).define()
def definition_prologue(self):
return "%sfn %s%s(%s)%s {\n" % (self._decorators(), self.name, self._template(),
self._argstring(), self._returnType())
def definition_epilogue(self):
return "\n}\n"
def definition_body(self):
raise NotImplementedError # Override me!
def CreateBindingJSObject(descriptor, parent=None):
create = "let mut raw = Box::into_raw(object);\nlet _rt = RootedTraceable::new(&*raw);\n"
if descriptor.proxy:
assert not descriptor.isGlobal()
create += """
let handler = RegisterBindings::proxy_handlers[PrototypeList::Proxies::%s as usize];
let private = RootedValue::new(cx, PrivateValue(raw as *const libc::c_void));
let obj = {
let _ac = JSAutoCompartment::new(cx, proto.ptr);
NewProxyObject(cx, handler,
private.handle(),
proto.ptr, %s.get(),
ptr::null_mut(), ptr::null_mut())
};
assert!(!obj.is_null());
let obj = RootedObject::new(cx, obj);\
""" % (descriptor.name, parent)
else:
if descriptor.isGlobal():
create += ("let obj = RootedObject::new(\n"
" cx,\n"
" create_dom_global(\n"
" cx,\n"
" &Class.base as *const js::jsapi::Class as *const JSClass,\n"
" Some(%s))\n"
");\n" % TRACE_HOOK_NAME)
else:
create += ("let obj = {\n"
" let _ac = JSAutoCompartment::new(cx, proto.ptr);\n"
" JS_NewObjectWithGivenProto(\n"
" cx, &Class.base as *const js::jsapi::Class as *const JSClass, proto.handle())\n"
"};\n"
"let obj = RootedObject::new(cx, obj);\n")
create += """\
assert!(!obj.ptr.is_null());
JS_SetReservedSlot(obj.ptr, DOM_OBJECT_SLOT,
PrivateValue(raw as *const libc::c_void));"""
return create
class CGWrapMethod(CGAbstractMethod):
"""
Class that generates the FooBinding::Wrap function for non-callback
interfaces.
"""
def __init__(self, descriptor):
assert not descriptor.interface.isCallback()
if not descriptor.isGlobal():
args = [Argument('*mut JSContext', 'cx'), Argument('GlobalRef', 'scope'),
Argument("Box<%s>" % descriptor.concreteType, 'object', mutable=True)]
else:
args = [Argument('*mut JSContext', 'cx'),
Argument("Box<%s>" % descriptor.concreteType, 'object', mutable=True)]
retval = 'Root<%s>' % descriptor.concreteType
CGAbstractMethod.__init__(self, descriptor, 'Wrap', retval, args, pub=True)
def definition_body(self):
if not self.descriptor.isGlobal():
return CGGeneric("""\
let _ar = JSAutoRequest::new(cx);
let scope = scope.reflector().get_jsobject();
assert!(!scope.get().is_null());
assert!(((*JS_GetClass(scope.get())).flags & JSCLASS_IS_GLOBAL) != 0);
let mut proto = RootedObject::new(cx, ptr::null_mut());
{
let _ac = JSAutoCompartment::new(cx, scope.get());
GetProtoObject(cx, scope, scope, proto.handle_mut())
}
assert!(!proto.ptr.is_null());
%s
(*raw).init_reflector(obj.ptr);
Root::from_ref(&*raw)""" % CreateBindingJSObject(self.descriptor, "scope"))
else:
return CGGeneric("""\
let _ar = JSAutoRequest::new(cx);
%s
let _ac = JSAutoCompartment::new(cx, obj.ptr);
let mut proto = RootedObject::new(cx, ptr::null_mut());
GetProtoObject(cx, obj.handle(), obj.handle(), proto.handle_mut());
JS_SetPrototype(cx, obj.handle(), proto.handle());
(*raw).init_reflector(obj.ptr);
let ret = Root::from_ref(&*raw);
RegisterBindings::Register(cx, obj.handle());
ret""" % CreateBindingJSObject(self.descriptor))
class CGIDLInterface(CGThing):
"""
Class for codegen of an implementation of the IDLInterface trait.
"""
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def define(self):
replacer = {
'type': self.descriptor.name,
'depth': self.descriptor.interface.inheritanceDepth(),
}
return string.Template("""\
impl IDLInterface for ${type} {
fn get_prototype_id() -> PrototypeList::ID {
PrototypeList::ID::${type}
}
fn get_prototype_depth() -> usize {
${depth}
}
}
""").substitute(replacer)
class CGAbstractExternMethod(CGAbstractMethod):
"""
Abstract base class for codegen of implementation-only (no
declaration) static methods.
"""
def __init__(self, descriptor, name, returnType, args):
CGAbstractMethod.__init__(self, descriptor, name, returnType, args,
inline=False, extern=True)
class PropertyArrays():
def __init__(self, descriptor):
self.static_methods = MethodDefiner(descriptor, "StaticMethods",
static=True)
self.static_attrs = AttrDefiner(descriptor, "StaticAttributes",
static=True)
self.methods = MethodDefiner(descriptor, "Methods", static=False)
self.attrs = AttrDefiner(descriptor, "Attributes", static=False)
self.consts = ConstDefiner(descriptor, "Constants")
pass
@staticmethod
def arrayNames():
return ["static_methods", "static_attrs", "methods", "attrs", "consts"]
def variableNames(self):
names = {}
for array in self.arrayNames():
names[array] = getattr(self, array).variableName()
return names
def __str__(self):
define = ""
for array in self.arrayNames():
define += str(getattr(self, array))
return define
class CGNativeProperties(CGThing):
def __init__(self, descriptor, properties):
CGThing.__init__(self)
self.properties = properties
def define(self):
def getField(array):
propertyArray = getattr(self.properties, array)
if propertyArray.length() > 0:
value = "Some(%s)" % propertyArray.variableName()
else:
value = "None"
return CGGeneric(string.Template('${name}: ${value},').substitute({
'name': array,
'value': value,
}))
nativeProps = CGList([getField(array) for array in self.properties.arrayNames()], '\n')
return CGWrapper(CGIndenter(nativeProps),
pre="static sNativeProperties: NativeProperties = NativeProperties {\n",
post="\n};\n").define()
class CGCreateInterfaceObjectsMethod(CGAbstractMethod):
"""
Generate the CreateInterfaceObjects method for an interface descriptor.
properties should be a PropertyArrays instance.
"""
def __init__(self, descriptor, properties):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'global'),
Argument('HandleObject', 'receiver'),
Argument('MutableHandleObject', 'rval')]
CGAbstractMethod.__init__(self, descriptor, 'CreateInterfaceObjects', 'void', args)
self.properties = properties
def definition_body(self):
protoChain = self.descriptor.prototypeChain
if len(protoChain) == 1:
getParentProto = "parent_proto.ptr = JS_GetObjectPrototype(cx, global)"
else:
parentProtoName = self.descriptor.prototypeChain[-2]
getParentProto = ("%s::GetProtoObject(cx, global, receiver, parent_proto.handle_mut())" %
toBindingNamespace(parentProtoName))
getParentProto = ("let mut parent_proto = RootedObject::new(cx, ptr::null_mut());\n"
"%s;\n"
"assert!(!parent_proto.ptr.is_null());\n") % getParentProto
if self.descriptor.interface.isCallback():
protoClass = "None"
else:
protoClass = "Some(&PrototypeClass)"
if self.descriptor.concrete:
if self.descriptor.proxy:
domClass = "&Class"
else:
domClass = "&Class.dom_class"
else:
domClass = "ptr::null()"
if self.descriptor.interface.hasInterfaceObject():
if self.descriptor.interface.ctor():
constructHook = CONSTRUCT_HOOK_NAME
constructArgs = methodLength(self.descriptor.interface.ctor())
else:
constructHook = "throwing_constructor"
constructArgs = 0
constructor = 'Some((%s as NonNullJSNative, "%s", %d))' % (
constructHook, self.descriptor.interface.identifier.name,
constructArgs)
else:
constructor = 'None'
call = """\
do_create_interface_objects(cx, receiver, parent_proto.handle(),
%s, %s,
&named_constructors,
%s,
&sNativeProperties, rval);""" % (protoClass, constructor, domClass)
createArray = """\
let named_constructors: [(NonNullJSNative, &'static str, u32); %d] = [
""" % len(self.descriptor.interface.namedConstructors)
for ctor in self.descriptor.interface.namedConstructors:
constructHook = CONSTRUCT_HOOK_NAME + "_" + ctor.identifier.name
constructArgs = methodLength(ctor)
constructor = '(%s as NonNullJSNative, "%s", %d)' % (
constructHook, ctor.identifier.name, constructArgs)
createArray += constructor
createArray += ","
createArray += "];"
return CGList([
CGGeneric(getParentProto),
CGGeneric(createArray),
CGGeneric(call % self.properties.variableNames())
], "\n")
class CGGetPerInterfaceObject(CGAbstractMethod):
"""
A method for getting a per-interface object (a prototype object or interface
constructor object).
"""
def __init__(self, descriptor, name, idPrefix="", pub=False):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'global'),
Argument('HandleObject', 'receiver'),
Argument('MutableHandleObject', 'rval')]
CGAbstractMethod.__init__(self, descriptor, name,
'void', args, pub=pub)
self.id = idPrefix + "ID::" + self.descriptor.name
def definition_body(self):
return CGGeneric("""
/* global and receiver are usually the same, but they can be different
too. For example a sandbox often has an xray wrapper for a window as the
prototype of the sandbox's global. In that case receiver is the xray
wrapper and global is the sandbox's global.
*/
assert!(((*JS_GetClass(global.get())).flags & JSCLASS_DOM_GLOBAL) != 0);
/* Check to see whether the interface objects are already installed */
let proto_or_iface_array = get_proto_or_iface_array(global.get());
rval.set((*proto_or_iface_array)[%s as usize]);
if !rval.get().is_null() {
return;
}
CreateInterfaceObjects(cx, global, receiver, rval);
assert!(!rval.get().is_null());
(*proto_or_iface_array)[%s as usize] = rval.get();
if <*mut JSObject>::needs_post_barrier(rval.get()) {
<*mut JSObject>::post_barrier((*proto_or_iface_array).as_mut_ptr().offset(%s as isize))
}
""" % (self.id, self.id, self.id))
class CGGetProtoObjectMethod(CGGetPerInterfaceObject):
"""
A method for getting the interface prototype object.
"""
def __init__(self, descriptor):
CGGetPerInterfaceObject.__init__(self, descriptor, "GetProtoObject",
"PrototypeList::", pub=True)
def definition_body(self):
return CGList([
CGGeneric("""\
/* Get the interface prototype object for this class. This will create the
object as needed. */"""),
CGGetPerInterfaceObject.definition_body(self),
])
class CGGetConstructorObjectMethod(CGGetPerInterfaceObject):
"""
A method for getting the interface constructor object.
"""
def __init__(self, descriptor):
CGGetPerInterfaceObject.__init__(self, descriptor, "GetConstructorObject",
"constructors::")
def definition_body(self):
return CGList([
CGGeneric("""\
/* Get the interface object for this class. This will create the object as
needed. */"""),
CGGetPerInterfaceObject.definition_body(self),
])
class CGDefineProxyHandler(CGAbstractMethod):
"""
A method to create and cache the proxy trap for a given interface.
"""
def __init__(self, descriptor):
assert descriptor.proxy
CGAbstractMethod.__init__(self, descriptor, 'DefineProxyHandler', '*const libc::c_void', [], pub=True)
def define(self):
return CGAbstractMethod.define(self)
def definition_body(self):
customDefineProperty = 'proxyhandler::define_property'
if self.descriptor.operations['IndexedSetter'] or self.descriptor.operations['NamedSetter']:
customDefineProperty = 'defineProperty'
customDelete = 'proxyhandler::delete'
if self.descriptor.operations['NamedDeleter']:
customDelete = 'delete'
body = """\
let traps = ProxyTraps {
enter: None,
getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor),
defineProperty: Some(%s),
ownPropertyKeys: Some(own_property_keys),
delete_: Some(%s),
enumerate: None,
preventExtensions: Some(proxyhandler::prevent_extensions),
isExtensible: Some(proxyhandler::is_extensible),
has: None,
get: Some(get),
set: None,
call: None,
construct: None,
getPropertyDescriptor: Some(get_property_descriptor),
hasOwn: Some(hasOwn),
getOwnEnumerablePropertyKeys: None,
nativeCall: None,
hasInstance: None,
objectClassIs: None,
className: Some(className),
fun_toString: None,
boxedValue_unbox: None,
defaultValue: None,
trace: Some(%s),
finalize: Some(%s),
objectMoved: None,
isCallable: None,
isConstructor: None,
};
CreateProxyHandler(&traps, &Class as *const _ as *const _)\
""" % (customDefineProperty, customDelete, TRACE_HOOK_NAME, FINALIZE_HOOK_NAME)
return CGGeneric(body)
class CGDefineDOMInterfaceMethod(CGAbstractMethod):
"""
A method for resolve hooks to try to lazily define the interface object for
a given interface.
"""
def __init__(self, descriptor):
assert descriptor.interface.hasInterfaceObject()
args = [
Argument('*mut JSContext', 'cx'),
Argument('HandleObject', 'global'),
]
CGAbstractMethod.__init__(self, descriptor, 'DefineDOMInterface', 'void', args, pub=True)
def define(self):
return CGAbstractMethod.define(self)
def definition_body(self):
if self.descriptor.interface.isCallback():
code = """\
let mut obj = RootedObject::new(cx, ptr::null_mut());
CreateInterfaceObjects(cx, global, global, obj.handle_mut());
"""
else:
code = """\
let mut proto = RootedObject::new(cx, ptr::null_mut());
GetProtoObject(cx, global, global, proto.handle_mut());
assert!(!proto.ptr.is_null());
"""
return CGGeneric("assert!(!global.get().is_null());\n" + code)
def needCx(returnType, arguments, considerTypes):
return (considerTypes and
(typeNeedsCx(returnType, True) or
any(typeNeedsCx(a.type) for a in arguments)))
class CGCallGenerator(CGThing):
"""
A class to generate an actual call to a C++ object. Assumes that the C++
object is stored in a variable whose name is given by the |object| argument.
errorResult should be a string for the value to return in case of an
exception from the native code, or None if no error reporting is needed.
"""
def __init__(self, errorResult, arguments, argsPre, returnType,
extendedAttributes, descriptorProvider, nativeMethodName,
static, object="this"):
CGThing.__init__(self)
assert errorResult is None or isinstance(errorResult, str)
isFallible = errorResult is not None
result = getRetvalDeclarationForType(returnType, descriptorProvider)
if isFallible:
result = CGWrapper(result, pre="Result<", post=", Error>")
args = CGList([CGGeneric(arg) for arg in argsPre], ", ")
for (a, name) in arguments:
# XXXjdm Perhaps we should pass all nontrivial types by borrowed pointer
if a.type.isDictionary():
name = "&" + name
args.append(CGGeneric(name))
needsCx = needCx(returnType, (a for (a, _) in arguments), True)
if "cx" not in argsPre and needsCx:
args.prepend(CGGeneric("cx"))
# Build up our actual call
self.cgRoot = CGList([], "\n")
call = CGGeneric(nativeMethodName)
if static:
call = CGWrapper(call, pre="%s::" % descriptorProvider.interface.identifier.name)
else:
call = CGWrapper(call, pre="%s." % object)
call = CGList([call, CGWrapper(args, pre="(", post=")")])
self.cgRoot.append(CGList([
CGGeneric("let result: "),
result,
CGGeneric(" = "),
call,
CGGeneric(";"),
]))
if isFallible:
if static:
glob = ""
else:
glob = " let global = global_object_for_js_object(this.reflector().get_jsobject().get());\n"
self.cgRoot.append(CGGeneric(
"let result = match result {\n"
" Ok(result) => result,\n"
" Err(e) => {\n"
"%s"
" throw_dom_exception(cx, global.r(), e);\n"
" return%s;\n"
" },\n"
"};" % (glob, errorResult)))
def define(self):
return self.cgRoot.define()
class CGPerSignatureCall(CGThing):
"""
This class handles the guts of generating code for a particular
call signature. A call signature consists of four things:
1) A return type, which can be None to indicate that there is no
actual return value (e.g. this is an attribute setter) or an
IDLType if there's an IDL type involved (including |void|).
2) An argument list, which is allowed to be empty.
3) A name of a native method to call.
4) Whether or not this method is static.
We also need to know whether this is a method or a getter/setter
to do error reporting correctly.
The idlNode parameter can be either a method or an attr. We can query
|idlNode.identifier| in both cases, so we can be agnostic between the two.
"""
# XXXbz For now each entry in the argument list is either an
# IDLArgument or a FakeArgument, but longer-term we may want to
# have ways of flagging things like JSContext* or optional_argc in
# there.
def __init__(self, returnType, argsPre, arguments, nativeMethodName, static,
descriptor, idlNode, argConversionStartsAt=0,
getter=False, setter=False):
CGThing.__init__(self)
self.returnType = returnType
self.descriptor = descriptor
self.idlNode = idlNode
self.extendedAttributes = descriptor.getExtendedAttributes(idlNode,
getter=getter,
setter=setter)
self.argsPre = argsPre
self.arguments = arguments
self.argCount = len(arguments)
cgThings = []
cgThings.extend([CGArgumentConverter(arguments[i], i, self.getArgs(),
self.getArgc(), self.descriptor,
invalidEnumValueFatal=not setter) for
i in range(argConversionStartsAt, self.argCount)])
errorResult = None
if self.isFallible():
errorResult = " JSFalse"
cgThings.append(CGCallGenerator(
errorResult,
self.getArguments(), self.argsPre, returnType,
self.extendedAttributes, descriptor, nativeMethodName,
static))
self.cgRoot = CGList(cgThings, "\n")
def getArgs(self):
return "args" if self.argCount > 0 else ""
def getArgc(self):
return "argc"
def getArguments(self):
def process(arg, i):
argVal = "arg" + str(i)
if arg.type.isGeckoInterface() and not arg.type.unroll().inner.isCallback():
argVal += ".r()"
return argVal
return [(a, process(a, i)) for (i, a) in enumerate(self.arguments)]
def isFallible(self):
return 'infallible' not in self.extendedAttributes
def wrap_return_value(self):
return wrapForType('args.rval()')
def define(self):
return (self.cgRoot.define() + "\n" + self.wrap_return_value())
class CGSwitch(CGList):
"""
A class to generate code for a switch statement.
Takes three constructor arguments: an expression, a list of cases,
and an optional default.
Each case is a CGCase. The default is a CGThing for the body of
the default case, if any.
"""
def __init__(self, expression, cases, default=None):
CGList.__init__(self, [CGIndenter(c) for c in cases], "\n")
self.prepend(CGWrapper(CGGeneric(expression),
pre="match ", post=" {"))
if default is not None:
self.append(
CGIndenter(
CGWrapper(
CGIndenter(default),
pre="_ => {\n",
post="\n}"
)
)
)
self.append(CGGeneric("}"))
class CGCase(CGList):
"""
A class to generate code for a case statement.
Takes three constructor arguments: an expression, a CGThing for
the body (allowed to be None if there is no body), and an optional
argument (defaulting to False) for whether to fall through.
"""
def __init__(self, expression, body, fallThrough=False):
CGList.__init__(self, [], "\n")
self.append(CGWrapper(CGGeneric(expression), post=" => {"))
bodyList = CGList([body], "\n")
if fallThrough:
raise TypeError("fall through required but unsupported")
# bodyList.append(CGGeneric('panic!("fall through unsupported"); /* Fall through */'))
self.append(CGIndenter(bodyList))
self.append(CGGeneric("}"))
class CGGetterCall(CGPerSignatureCall):
"""
A class to generate a native object getter call for a particular IDL
getter.
"""
def __init__(self, argsPre, returnType, nativeMethodName, descriptor, attr):
CGPerSignatureCall.__init__(self, returnType, argsPre, [],
nativeMethodName, attr.isStatic(), descriptor,
attr, getter=True)
class FakeArgument():
"""
A class that quacks like an IDLArgument. This is used to make
setters look like method calls or for special operations.
"""
def __init__(self, type, interfaceMember, allowTreatNonObjectAsNull=False):
self.type = type
self.optional = False
self.variadic = False
self.defaultValue = None
self._allowTreatNonObjectAsNull = allowTreatNonObjectAsNull
self.treatNullAs = interfaceMember.treatNullAs
self.enforceRange = False
self.clamp = False
def allowTreatNonCallableAsNull(self):
return self._allowTreatNonObjectAsNull
class CGSetterCall(CGPerSignatureCall):
"""
A class to generate a native object setter call for a particular IDL
setter.
"""
def __init__(self, argsPre, argType, nativeMethodName, descriptor, attr):
CGPerSignatureCall.__init__(self, None, argsPre,
[FakeArgument(argType, attr, allowTreatNonObjectAsNull=True)],
nativeMethodName, attr.isStatic(), descriptor, attr,
setter=True)
def wrap_return_value(self):
# We have no return value
return "\nreturn 1;"
def getArgc(self):
return "1"
class CGAbstractStaticBindingMethod(CGAbstractMethod):
"""
Common class to generate the JSNatives for all our static methods, getters
and setters. This will generate the function declaration and unwrap the
global object. Subclasses are expected to override the generate_code
function to do the rest of the work. This function should return a
CGThing which is already properly indented.
"""
def __init__(self, descriptor, name):
args = [
Argument('*mut JSContext', 'cx'),
Argument('libc::c_uint', 'argc'),
Argument('*mut JSVal', 'vp'),
]
CGAbstractMethod.__init__(self, descriptor, name, "u8", args, extern=True)
def definition_body(self):
preamble = CGGeneric("""\
let global = global_object_for_js_object(JS_CALLEE(cx, vp).to_object());
""")
return CGList([preamble, self.generate_code()])
def generate_code(self):
raise NotImplementedError # Override me!
class CGSpecializedMethod(CGAbstractExternMethod):
"""
A class for generating the C++ code for a specialized method that the JIT
can call with lower overhead.
"""
def __init__(self, descriptor, method):
self.method = method
name = method.identifier.name
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', '_obj'),
Argument('*const %s' % descriptor.concreteType, 'this'),
Argument('*const JSJitMethodCallArgs', 'args')]
CGAbstractExternMethod.__init__(self, descriptor, name, 'u8', args)
def definition_body(self):
nativeName = CGSpecializedMethod.makeNativeName(self.descriptor,
self.method)
return CGWrapper(CGMethodCall([], nativeName, self.method.isStatic(),
self.descriptor, self.method),
pre="let this = &*this;\n"
"let args = &*args;\n"
"let argc = args.argc_;\n")
@staticmethod
def makeNativeName(descriptor, method):
name = method.identifier.name
return MakeNativeName(descriptor.binaryNameFor(name))
class CGStaticMethod(CGAbstractStaticBindingMethod):
"""
A class for generating the Rust code for an IDL static method.
"""
def __init__(self, descriptor, method):
self.method = method
name = method.identifier.name
CGAbstractStaticBindingMethod.__init__(self, descriptor, name)
def generate_code(self):
nativeName = CGSpecializedMethod.makeNativeName(self.descriptor,
self.method)
setupArgs = CGGeneric("let mut args = CallArgs::from_vp(vp, argc);\n")
call = CGMethodCall(["global.r()"], nativeName, True, self.descriptor, self.method)
return CGList([setupArgs, call])
class CGSpecializedGetter(CGAbstractExternMethod):
"""
A class for generating the code for a specialized attribute getter
that the JIT can call with lower overhead.
"""
def __init__(self, descriptor, attr):
self.attr = attr
name = 'get_' + attr.identifier.name
args = [Argument('*mut JSContext', 'cx'),
Argument('HandleObject', '_obj'),
Argument('*const %s' % descriptor.concreteType, 'this'),
Argument('JSJitGetterCallArgs', 'args')]
CGAbstractExternMethod.__init__(self, descriptor, name, "u8", args)
def definition_body(self):
nativeName = CGSpecializedGetter.makeNativeName(self.descriptor,
self.attr)
return CGWrapper(CGGetterCall([], self.attr.type, nativeName,
self.descriptor, self.attr),
pre="let this = &*this;\n")
@staticmethod
def makeNativeName(descriptor, attr):
name = attr.identifier.name
nativeName = MakeNativeName(descriptor.binaryNameFor(name))
infallible = ('infallible' in
descriptor.getExtendedAttributes(attr, getter=True))
if attr.type.nullable() or not infallible:
return "Get" + nativeName
return nativeName
class CGStaticGetter(CGAbstractStaticBindingMethod):
"""
A class for generating the C++ code for an IDL static attribute getter.
"""
def __init__(self, descriptor, attr):
self.attr = attr
name = 'get_' + attr.identifier.name
CGAbstractStaticBindingMethod.__init__(self, descriptor, name)
def generate_code(self):
nativeName = CGSpecializedGetter.makeNativeName(self.descriptor,
self.attr)
setupArgs = CGGeneric("let mut args = CallArgs::from_vp(vp, argc);\n")
call = CGGetterCall(["global.r()"], self.attr.type, nativeName, self.descriptor,
self.attr)
return CGList([setupArgs, call])
class CGSpecializedSetter(CGAbstractExternMethod):
"""
A class for generating the code for a specialized attribute setter
that the JIT can call with lower overhead.
"""
def __init__(self, descriptor, attr):
self.attr = attr
name = 'set_' + attr.identifier.name
args = [Argument('*mut JSContext', 'cx'),
Argument('HandleObject', 'obj'),
Argument('*const %s' % descriptor.concreteType, 'this'),
Argument('JSJitSetterCallArgs', 'args')]
CGAbstractExternMethod.__init__(self, descriptor, name, "u8", args)
def definition_body(self):
nativeName = CGSpecializedSetter.makeNativeName(self.descriptor,
self.attr)
return CGWrapper(CGSetterCall([], self.attr.type, nativeName,
self.descriptor, self.attr),
pre="let this = &*this;\n")
@staticmethod
def makeNativeName(descriptor, attr):
name = attr.identifier.name
return "Set" + MakeNativeName(descriptor.binaryNameFor(name))
class CGStaticSetter(CGAbstractStaticBindingMethod):
"""
A class for generating the C++ code for an IDL static attribute setter.
"""
def __init__(self, descriptor, attr):
self.attr = attr
name = 'set_' + attr.identifier.name
CGAbstractStaticBindingMethod.__init__(self, descriptor, name)
def generate_code(self):
nativeName = CGSpecializedSetter.makeNativeName(self.descriptor,
self.attr)
checkForArg = CGGeneric(
"let args = CallArgs::from_vp(vp, argc);\n"
"if (argc == 0) {\n"
" throw_type_error(cx, \"Not enough arguments to %s setter.\");\n"
" return 0;\n"
"}" % self.attr.identifier.name)
call = CGSetterCall(["global.r()"], self.attr.type, nativeName, self.descriptor,
self.attr)
return CGList([checkForArg, call])
class CGSpecializedForwardingSetter(CGSpecializedSetter):
"""
A class for generating the code for an IDL attribute forwarding setter.
"""
def __init__(self, descriptor, attr):
CGSpecializedSetter.__init__(self, descriptor, attr)
def definition_body(self):
attrName = self.attr.identifier.name
forwardToAttrName = self.attr.getExtendedAttribute("PutForwards")[0]
# JS_GetProperty and JS_SetProperty can only deal with ASCII
assert all(ord(c) < 128 for c in attrName)
assert all(ord(c) < 128 for c in forwardToAttrName)
return CGGeneric("""\
let mut v = RootedValue::new(cx, UndefinedValue());
if JS_GetProperty(cx, obj, %s as *const u8 as *const libc::c_char, v.handle_mut()) == 0 {
return JSFalse;
}
if !v.ptr.is_object() {
throw_type_error(cx, "Value.%s is not an object.");
return JSFalse;
}
let target_obj = RootedObject::new(cx, v.ptr.to_object());
JS_SetProperty(cx, target_obj.handle(), %s as *const u8 as *const libc::c_char, args.get(0))
""" % (str_to_const_array(attrName), attrName, str_to_const_array(forwardToAttrName)))
class CGMemberJITInfo(CGThing):
"""
A class for generating the JITInfo for a property that points to
our specialized getter and setter.
"""
def __init__(self, descriptor, member):
self.member = member
self.descriptor = descriptor
def defineJitInfo(self, infoName, opName, opType, infallible, movable,
aliasSet, alwaysInSlot, lazilyInSlot, slotIndex,
returnTypes, args):
"""
aliasSet is a JSJitInfo::AliasSet value, without the "JSJitInfo::" bit.
args is None if we don't want to output argTypes for some
reason (e.g. we have overloads or we're not a method) and
otherwise an iterable of the arguments for this method.
"""
assert(not movable or aliasSet != "AliasEverything") # Can't move write-aliasing things
assert(not alwaysInSlot or movable) # Things always in slots had better be movable
def jitInfoInitializer(isTypedMethod):
initializer = fill(
"""
JSJitInfo {
_bindgen_data_1_: ${opName} as *const ::libc::c_void,
protoID: PrototypeList::ID::${name} as u16,
depth: ${depth},
_bitfield_1: ((JSJitInfo_OpType::${opType} as u32) << 0) |
((JSJitInfo_AliasSet::${aliasSet} as u32) << 4) |
((JSValueType::${returnType} as u32) << 8) |
((${isInfallible} as u32) << 16) |
((${isMovable} as u32) << 17) |
((${isAlwaysInSlot} as u32) << 18) |
((${isLazilyCachedInSlot} as u32) << 19) |
((${isTypedMethod} as u32) << 20) |
((${slotIndex} as u32) << 21)
}
""",
opName=opName,
name=self.descriptor.name,
depth=self.descriptor.interface.inheritanceDepth(),
opType=opType,
aliasSet=aliasSet,
returnType=reduce(CGMemberJITInfo.getSingleReturnType, returnTypes,
""),
isInfallible=toStringBool(infallible),
isMovable=toStringBool(movable),
isAlwaysInSlot=toStringBool(alwaysInSlot),
isLazilyCachedInSlot=toStringBool(lazilyInSlot),
isTypedMethod=toStringBool(isTypedMethod),
slotIndex=slotIndex)
return initializer.rstrip()
return ("\n"
"const %s: JSJitInfo = %s;\n"
% (infoName, jitInfoInitializer(False)))
def define(self):
if self.member.isAttr():
getterinfo = ("%s_getterinfo" % self.member.identifier.name)
getter = ("get_%s" % self.member.identifier.name)
getterinfal = "infallible" in self.descriptor.getExtendedAttributes(self.member, getter=True)
movable = self.mayBeMovable() and getterinfal
aliasSet = self.aliasSet()
isAlwaysInSlot = self.member.getExtendedAttribute("StoreInSlot")
if self.member.slotIndex is not None:
assert isAlwaysInSlot or self.member.getExtendedAttribute("Cached")
isLazilyCachedInSlot = not isAlwaysInSlot
slotIndex = memberReservedSlot(self.member) # noqa:FIXME: memberReservedSlot is not defined
# We'll statically assert that this is not too big in
# CGUpdateMemberSlotsMethod, in the case when
# isAlwaysInSlot is true.
else:
isLazilyCachedInSlot = False
slotIndex = "0"
result = self.defineJitInfo(getterinfo, getter, "Getter",
getterinfal, movable, aliasSet,
isAlwaysInSlot, isLazilyCachedInSlot,
slotIndex,
[self.member.type], None)
if (not self.member.readonly or self.member.getExtendedAttribute("PutForwards")):
setterinfo = ("%s_setterinfo" % self.member.identifier.name)
setter = ("set_%s" % self.member.identifier.name)
# Setters are always fallible, since they have to do a typed unwrap.
result += self.defineJitInfo(setterinfo, setter, "Setter",
False, False, "AliasEverything",
False, False, "0",
[BuiltinTypes[IDLBuiltinType.Types.void]],
None)
return result
if self.member.isMethod():
methodinfo = ("%s_methodinfo" % self.member.identifier.name)
method = ("%s" % self.member.identifier.name)
# Methods are infallible if they are infallible, have no arguments
# to unwrap, and have a return type that's infallible to wrap up for
# return.
sigs = self.member.signatures()
if len(sigs) != 1:
# Don't handle overloading. If there's more than one signature,
# one of them must take arguments.
methodInfal = False
args = None
movable = False
else:
sig = sigs[0]
# For methods that affect nothing, it's OK to set movable to our
# notion of infallible on the C++ side, without considering
# argument conversions, since argument conversions that can
# reliably throw would be effectful anyway and the jit doesn't
# move effectful things.
hasInfallibleImpl = "infallible" in self.descriptor.getExtendedAttributes(self.member)
movable = self.mayBeMovable() and hasInfallibleImpl
# XXXbz can we move the smarts about fallibility due to arg
# conversions into the JIT, using our new args stuff?
if (len(sig[1]) != 0):
# We have arguments or our return-value boxing can fail
methodInfal = False
else:
methodInfal = hasInfallibleImpl
# For now, only bother to output args if we're side-effect-free.
if self.member.affects == "Nothing":
args = sig[1]
else:
args = None
aliasSet = self.aliasSet()
result = self.defineJitInfo(methodinfo, method, "Method",
methodInfal, movable, aliasSet,
False, False, "0",
[s[0] for s in sigs], args)
return result
raise TypeError("Illegal member type to CGPropertyJITInfo")
def mayBeMovable(self):
"""
Returns whether this attribute or method may be movable, just
based on Affects/DependsOn annotations.
"""
affects = self.member.affects
dependsOn = self.member.dependsOn
assert affects in IDLInterfaceMember.AffectsValues
assert dependsOn in IDLInterfaceMember.DependsOnValues
# Things that are DependsOn=DeviceState are not movable, because we
# don't want them coalesced with each other or loop-hoisted, since
# their return value can change even if nothing is going on from our
# point of view.
return (affects == "Nothing" and
(dependsOn != "Everything" and dependsOn != "DeviceState"))
def aliasSet(self):
"""Returns the alias set to store in the jitinfo. This may not be the
effective alias set the JIT uses, depending on whether we have enough
information about our args to allow the JIT to prove that effectful
argument conversions won't happen.
"""
dependsOn = self.member.dependsOn
assert dependsOn in IDLInterfaceMember.DependsOnValues
if dependsOn == "Nothing" or dependsOn == "DeviceState":
assert self.member.affects == "Nothing"
return "AliasNone"
if dependsOn == "DOMState":
assert self.member.affects == "Nothing"
return "AliasDOMSets"
return "AliasEverything"
@staticmethod
def getJSReturnTypeTag(t):
if t.nullable():
# Sometimes it might return null, sometimes not
return "JSVAL_TYPE_UNKNOWN"
if t.isVoid():
# No return, every time
return "JSVAL_TYPE_UNDEFINED"
if t.isArray():
# No idea yet
assert False
if t.isSequence():
return "JSVAL_TYPE_OBJECT"
if t.isMozMap():
return "JSVAL_TYPE_OBJECT"
if t.isGeckoInterface():
return "JSVAL_TYPE_OBJECT"
if t.isString():
return "JSVAL_TYPE_STRING"
if t.isEnum():
return "JSVAL_TYPE_STRING"
if t.isCallback():
return "JSVAL_TYPE_OBJECT"
if t.isAny():
# The whole point is to return various stuff
return "JSVAL_TYPE_UNKNOWN"
if t.isObject():
return "JSVAL_TYPE_OBJECT"
if t.isSpiderMonkeyInterface():
return "JSVAL_TYPE_OBJECT"
if t.isUnion():
u = t.unroll()
if u.hasNullableType:
# Might be null or not
return "JSVAL_TYPE_UNKNOWN"
return reduce(CGMemberJITInfo.getSingleReturnType,
u.flatMemberTypes, "")
if t.isDictionary():
return "JSVAL_TYPE_OBJECT"
if t.isDate():
return "JSVAL_TYPE_OBJECT"
if not t.isPrimitive():
raise TypeError("No idea what type " + str(t) + " is.")
tag = t.tag()
if tag == IDLType.Tags.bool:
return "JSVAL_TYPE_BOOLEAN"
if tag in [IDLType.Tags.int8, IDLType.Tags.uint8,
IDLType.Tags.int16, IDLType.Tags.uint16,
IDLType.Tags.int32]:
return "JSVAL_TYPE_INT32"
if tag in [IDLType.Tags.int64, IDLType.Tags.uint64,
IDLType.Tags.unrestricted_float, IDLType.Tags.float,
IDLType.Tags.unrestricted_double, IDLType.Tags.double]:
# These all use JS_NumberValue, which can return int or double.
# But TI treats "double" as meaning "int or double", so we're
# good to return JSVAL_TYPE_DOUBLE here.
return "JSVAL_TYPE_DOUBLE"
if tag != IDLType.Tags.uint32:
raise TypeError("No idea what type " + str(t) + " is.")
# uint32 is sometimes int and sometimes double.
return "JSVAL_TYPE_DOUBLE"
@staticmethod
def getSingleReturnType(existingType, t):
type = CGMemberJITInfo.getJSReturnTypeTag(t)
if existingType == "":
# First element of the list; just return its type
return type
if type == existingType:
return existingType
if ((type == "JSVAL_TYPE_DOUBLE" and
existingType == "JSVAL_TYPE_INT32") or
(existingType == "JSVAL_TYPE_DOUBLE" and
type == "JSVAL_TYPE_INT32")):
# Promote INT32 to DOUBLE as needed
return "JSVAL_TYPE_DOUBLE"
# Different types
return "JSVAL_TYPE_UNKNOWN"
def getEnumValueName(value):
# Some enum values can be empty strings. Others might have weird
# characters in them. Deal with the former by returning "_empty",
# deal with possible name collisions from that by throwing if the
# enum value is actually "_empty", and throw on any value
# containing non-ASCII chars for now. Replace all chars other than
# [0-9A-Za-z_] with '_'.
if re.match("[^\x20-\x7E]", value):
raise SyntaxError('Enum value "' + value + '" contains non-ASCII characters')
if re.match("^[0-9]", value):
raise SyntaxError('Enum value "' + value + '" starts with a digit')
value = re.sub(r'[^0-9A-Za-z_]', '_', value)
if re.match("^_[A-Z]|__", value):
raise SyntaxError('Enum value "' + value + '" is reserved by the C++ spec')
if value == "_empty":
raise SyntaxError('"_empty" is not an IDL enum value we support yet')
if value == "":
return "_empty"
return MakeNativeName(value)
class CGEnum(CGThing):
def __init__(self, enum):
CGThing.__init__(self)
decl = """\
#[repr(usize)]
#[derive(JSTraceable, PartialEq, Copy, Clone, HeapSizeOf)]
pub enum %s {
%s
}
""" % (enum.identifier.name, ",\n ".join(map(getEnumValueName, enum.values())))
inner = """\
use dom::bindings::conversions::ToJSValConvertible;
use js::jsapi::{JSContext, MutableHandleValue};
use js::jsval::JSVal;
pub const strings: &'static [&'static str] = &[
%s,
];
impl ToJSValConvertible for super::%s {
fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
strings[*self as usize].to_jsval(cx, rval);
}
}
""" % (",\n ".join(['"%s"' % val for val in enum.values()]), enum.identifier.name)
self.cgRoot = CGList([
CGGeneric(decl),
CGNamespace.build([enum.identifier.name + "Values"],
CGIndenter(CGGeneric(inner)), public=True),
])
def define(self):
return self.cgRoot.define()
def convertConstIDLValueToRust(value):
tag = value.type.tag()
if tag in [IDLType.Tags.int8, IDLType.Tags.uint8,
IDLType.Tags.int16, IDLType.Tags.uint16,
IDLType.Tags.int32, IDLType.Tags.uint32,
IDLType.Tags.int64, IDLType.Tags.uint64,
IDLType.Tags.unrestricted_float, IDLType.Tags.float,
IDLType.Tags.unrestricted_double, IDLType.Tags.double]:
return str(value.value)
if tag == IDLType.Tags.bool:
return toStringBool(value.value)
raise TypeError("Const value of unhandled type: " + value.type)
class CGConstant(CGThing):
def __init__(self, constants):
CGThing.__init__(self)
self.constants = constants
def define(self):
def stringDecl(const):
name = const.identifier.name
value = convertConstIDLValueToRust(const.value)
return CGGeneric("pub const %s: %s = %s;\n" % (name, builtinNames[const.value.type.tag()], value))
return CGIndenter(CGList(stringDecl(m) for m in self.constants)).define()
def getUnionTypeTemplateVars(type, descriptorProvider):
# For dictionaries and sequences we need to pass None as the failureCode
# for getJSToNativeConversionInfo.
# Also, for dictionaries we would need to handle conversion of
# null/undefined to the dictionary correctly.
if type.isDictionary() or type.isSequence():
raise TypeError("Can't handle dictionaries or sequences in unions")
if type.isGeckoInterface():
name = type.inner.identifier.name
typeName = descriptorProvider.getDescriptor(name).nativeType
elif type.isEnum():
name = type.inner.identifier.name
typeName = name
elif type.isArray() or type.isSequence():
name = str(type)
# XXXjdm dunno about typeName here
typeName = "/*" + type.name + "*/"
elif type.isDOMString():
name = type.name
typeName = "DOMString"
elif type.isPrimitive():
name = type.name
typeName = builtinNames[type.tag()]
else:
name = type.name
typeName = "/*" + type.name + "*/"
info = getJSToNativeConversionInfo(
type, descriptorProvider, failureCode="return Ok(None);",
exceptionCode='return Err(());',
isDefinitelyObject=True)
template = info.template
assert not type.isObject()
jsConversion = string.Template(template).substitute({
"val": "value",
})
jsConversion = CGWrapper(CGGeneric(jsConversion), pre="Ok(Some(", post="))")
return {
"name": name,
"typeName": typeName,
"jsConversion": jsConversion,
}
class CGUnionStruct(CGThing):
def __init__(self, type, descriptorProvider):
assert not type.nullable()
assert not type.hasNullableType
CGThing.__init__(self)
self.type = type
self.descriptorProvider = descriptorProvider
def define(self):
templateVars = map(lambda t: getUnionTypeTemplateVars(t, self.descriptorProvider),
self.type.flatMemberTypes)
enumValues = [
" e%s(%s)," % (v["name"], v["typeName"]) for v in templateVars
]
enumConversions = [
" %s::e%s(ref inner) => inner.to_jsval(cx, rval),"
% (self.type, v["name"]) for v in templateVars
]
return ("""\
pub enum %s {
%s
}
impl ToJSValConvertible for %s {
fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
match *self {
%s
}
}
}
""") % (self.type, "\n".join(enumValues), self.type, "\n".join(enumConversions))
class CGUnionConversionStruct(CGThing):
def __init__(self, type, descriptorProvider):
assert not type.nullable()
assert not type.hasNullableType
CGThing.__init__(self)
self.type = type
self.descriptorProvider = descriptorProvider
def from_jsval(self):
memberTypes = self.type.flatMemberTypes
names = []
conversions = []
interfaceMemberTypes = filter(lambda t: t.isNonCallbackInterface(), memberTypes)
if len(interfaceMemberTypes) > 0:
def get_name(memberType):
if self.type.isGeckoInterface():
return memberType.inner.identifier.name
return memberType.name
def get_match(name):
return (
"match %s::TryConvertTo%s(cx, value) {\n"
" Err(_) => return Err(()),\n"
" Ok(Some(value)) => return Ok(%s::e%s(value)),\n"
" Ok(None) => (),\n"
"}\n") % (self.type, name, self.type, name)
typeNames = [get_name(memberType) for memberType in interfaceMemberTypes]
interfaceObject = CGList(CGGeneric(get_match(typeName)) for typeName in typeNames)
names.extend(typeNames)
else:
interfaceObject = None
arrayObjectMemberTypes = filter(lambda t: t.isArray() or t.isSequence(), memberTypes)
if len(arrayObjectMemberTypes) > 0:
assert len(arrayObjectMemberTypes) == 1
raise TypeError("Can't handle arrays or sequences in unions.")
else:
arrayObject = None
dateObjectMemberTypes = filter(lambda t: t.isDate(), memberTypes)
if len(dateObjectMemberTypes) > 0:
assert len(dateObjectMemberTypes) == 1
raise TypeError("Can't handle dates in unions.")
else:
dateObject = None
callbackMemberTypes = filter(lambda t: t.isCallback() or t.isCallbackInterface(), memberTypes)
if len(callbackMemberTypes) > 0:
assert len(callbackMemberTypes) == 1
raise TypeError("Can't handle callbacks in unions.")
else:
callbackObject = None
dictionaryMemberTypes = filter(lambda t: t.isDictionary(), memberTypes)
if len(dictionaryMemberTypes) > 0:
raise TypeError("No support for unwrapping dictionaries as member "
"of a union")
else:
dictionaryObject = None
if callbackObject or dictionaryObject:
assert False, "Not currently supported"
else:
nonPlatformObject = None
objectMemberTypes = filter(lambda t: t.isObject(), memberTypes)
if len(objectMemberTypes) > 0:
raise TypeError("Can't handle objects in unions.")
else:
object = None
hasObjectTypes = interfaceObject or arrayObject or dateObject or nonPlatformObject or object
if hasObjectTypes:
assert interfaceObject
templateBody = CGList([interfaceObject], "\n")
conversions.append(CGIfWrapper(templateBody, "value.get().is_object()"))
otherMemberTypes = [
t for t in memberTypes if t.isPrimitive() or t.isString() or t.isEnum()
]
if len(otherMemberTypes) > 0:
assert len(otherMemberTypes) == 1
memberType = otherMemberTypes[0]
if memberType.isEnum():
name = memberType.inner.identifier.name
else:
name = memberType.name
match = (
"match %s::TryConvertTo%s(cx, value) {\n"
" Err(_) => return Err(()),\n"
" Ok(Some(value)) => return Ok(%s::e%s(value)),\n"
" Ok(None) => (),\n"
"}\n") % (self.type, name, self.type, name)
conversions.append(CGGeneric(match))
names.append(name)
conversions.append(CGGeneric(
"throw_not_in_union(cx, \"%s\");\n"
"Err(())" % ", ".join(names)))
method = CGWrapper(
CGIndenter(CGList(conversions, "\n\n")),
pre="fn from_jsval(cx: *mut JSContext,\n"
" value: HandleValue, _option: ()) -> Result<%s, ()> {\n" % self.type,
post="\n}")
return CGWrapper(
CGIndenter(CGList([
CGGeneric("type Config = ();"),
method,
], "\n")),
pre="impl FromJSValConvertible for %s {\n" % self.type,
post="\n}")
def try_method(self, t):
templateVars = getUnionTypeTemplateVars(t, self.descriptorProvider)
returnType = "Result<Option<%s>, ()>" % templateVars["typeName"]
jsConversion = templateVars["jsConversion"]
return CGWrapper(
CGIndenter(jsConversion, 4),
pre="fn TryConvertTo%s(cx: *mut JSContext, value: HandleValue) -> %s {\n" % (t.name, returnType),
post="\n}")
def define(self):
from_jsval = self.from_jsval()
methods = CGIndenter(CGList([
self.try_method(t) for t in self.type.flatMemberTypes
], "\n\n"))
return """
%s
impl %s {
%s
}
""" % (from_jsval.define(), self.type, methods.define())
class ClassItem:
""" Use with CGClass """
def __init__(self, name, visibility):
self.name = name
self.visibility = visibility
def declare(self, cgClass):
assert False
def define(self, cgClass):
assert False
class ClassBase(ClassItem):
def __init__(self, name, visibility='pub'):
ClassItem.__init__(self, name, visibility)
def declare(self, cgClass):
return '%s %s' % (self.visibility, self.name)
def define(self, cgClass):
# Only in the header
return ''
class ClassMethod(ClassItem):
def __init__(self, name, returnType, args, inline=False, static=False,
virtual=False, const=False, bodyInHeader=False,
templateArgs=None, visibility='public', body=None,
breakAfterReturnDecl="\n",
breakAfterSelf="\n", override=False):
"""
override indicates whether to flag the method as MOZ_OVERRIDE
"""
assert not override or virtual
assert not (override and static)
self.returnType = returnType
self.args = args
self.inline = False
self.static = static
self.virtual = virtual
self.const = const
self.bodyInHeader = True
self.templateArgs = templateArgs
self.body = body
self.breakAfterReturnDecl = breakAfterReturnDecl
self.breakAfterSelf = breakAfterSelf
self.override = override
ClassItem.__init__(self, name, visibility)
def getDecorators(self, declaring):
decorators = []
if self.inline:
decorators.append('inline')
if declaring:
if self.static:
decorators.append('static')
if self.virtual:
decorators.append('virtual')
if decorators:
return ' '.join(decorators) + ' '
return ''
def getBody(self):
# Override me or pass a string to constructor
assert self.body is not None
return self.body
def declare(self, cgClass):
templateClause = '<%s>' % ', '.join(self.templateArgs) \
if self.bodyInHeader and self.templateArgs else ''
args = ', '.join([a.declare() for a in self.args])
if self.bodyInHeader:
body = CGIndenter(CGGeneric(self.getBody())).define()
body = ' {\n' + body + '\n}'
else:
body = ';'
return string.Template(
"${decorators}%s"
"${visibility}fn ${name}${templateClause}(${args})${returnType}${const}${override}${body}%s" %
(self.breakAfterReturnDecl, self.breakAfterSelf)
).substitute({
'templateClause': templateClause,
'decorators': self.getDecorators(True),
'returnType': (" -> %s" % self.returnType) if self.returnType else "",
'name': self.name,
'const': ' const' if self.const else '',
'override': ' MOZ_OVERRIDE' if self.override else '',
'args': args,
'body': body,
'visibility': self.visibility + ' ' if self.visibility != 'priv' else ''
})
def define(self, cgClass):
pass
class ClassConstructor(ClassItem):
"""
Used for adding a constructor to a CGClass.
args is a list of Argument objects that are the arguments taken by the
constructor.
inline should be True if the constructor should be marked inline.
bodyInHeader should be True if the body should be placed in the class
declaration in the header.
visibility determines the visibility of the constructor (public,
protected, private), defaults to private.
explicit should be True if the constructor should be marked explicit.
baseConstructors is a list of strings containing calls to base constructors,
defaults to None.
body contains a string with the code for the constructor, defaults to empty.
"""
def __init__(self, args, inline=False, bodyInHeader=False,
visibility="priv", explicit=False, baseConstructors=None,
body=""):
self.args = args
self.inline = False
self.bodyInHeader = bodyInHeader
self.explicit = explicit
self.baseConstructors = baseConstructors or []
self.body = body
ClassItem.__init__(self, None, visibility)
def getDecorators(self, declaring):
decorators = []
if self.explicit:
decorators.append('explicit')
if self.inline and declaring:
decorators.append('inline')
if decorators:
return ' '.join(decorators) + ' '
return ''
def getInitializationList(self, cgClass):
items = [str(c) for c in self.baseConstructors]
for m in cgClass.members:
if not m.static:
initialize = m.body
if initialize:
items.append(m.name + "(" + initialize + ")")
if len(items) > 0:
return '\n : ' + ',\n '.join(items)
return ''
def getBody(self, cgClass):
initializers = [" parent: %s" % str(self.baseConstructors[0])]
return (self.body + (
"let mut ret = Rc::new(%s {\n"
"%s\n"
"});\n"
"// Note: callback cannot be moved after calling init.\n"
"match Rc::get_mut(&mut ret) {\n"
" Some(ref mut callback) => callback.parent.init(%s),\n"
" None => unreachable!(),\n"
"};\n"
"ret") % (cgClass.name, '\n'.join(initializers), self.args[0].name))
def declare(self, cgClass):
args = ', '.join([a.declare() for a in self.args])
body = ' ' + self.getBody(cgClass)
body = stripTrailingWhitespace(body.replace('\n', '\n '))
if len(body) > 0:
body += '\n'
body = ' {\n' + body + '}'
return string.Template("""\
pub fn ${decorators}new(${args}) -> Rc<${className}>${body}
""").substitute({'decorators': self.getDecorators(True),
'className': cgClass.getNameString(),
'args': args,
'body': body})
def define(self, cgClass):
if self.bodyInHeader:
return ''
args = ', '.join([a.define() for a in self.args])
body = ' ' + self.getBody()
body = '\n' + stripTrailingWhitespace(body.replace('\n', '\n '))
if len(body) > 0:
body += '\n'
return string.Template("""\
${decorators}
${className}::${className}(${args})${initializationList}
{${body}}
""").substitute({'decorators': self.getDecorators(False),
'className': cgClass.getNameString(),
'args': args,
'initializationList': self.getInitializationList(cgClass),
'body': body})
class ClassMember(ClassItem):
def __init__(self, name, type, visibility="priv", static=False,
body=None):
self.type = type
self.static = static
self.body = body
ClassItem.__init__(self, name, visibility)
def declare(self, cgClass):
return '%s %s: %s,\n' % (self.visibility, self.name, self.type)
def define(self, cgClass):
if not self.static:
return ''
if self.body:
body = " = " + self.body
else:
body = ""
return '%s %s::%s%s;\n' % (self.type, cgClass.getNameString(),
self.name, body)
class CGClass(CGThing):
def __init__(self, name, bases=[], members=[], constructors=[],
destructor=None, methods=[],
typedefs=[], enums=[], unions=[], templateArgs=[],
templateSpecialization=[],
disallowCopyConstruction=False, indent='',
decorators='',
extradeclarations=''):
CGThing.__init__(self)
self.name = name
self.bases = bases
self.members = members
self.constructors = constructors
# We store our single destructor in a list, since all of our
# code wants lists of members.
self.destructors = [destructor] if destructor else []
self.methods = methods
self.typedefs = typedefs
self.enums = enums
self.unions = unions
self.templateArgs = templateArgs
self.templateSpecialization = templateSpecialization
self.disallowCopyConstruction = disallowCopyConstruction
self.indent = indent
self.decorators = decorators
self.extradeclarations = extradeclarations
def getNameString(self):
className = self.name
if self.templateSpecialization:
className = className + \
'<%s>' % ', '.join([str(a) for a
in self.templateSpecialization])
return className
def define(self):
result = ''
if self.templateArgs:
templateArgs = [a.declare() for a in self.templateArgs]
templateArgs = templateArgs[len(self.templateSpecialization):]
result = result + self.indent + 'template <%s>\n' % ','.join([str(a) for a in templateArgs])
if self.templateSpecialization:
specialization = \
'<%s>' % ', '.join([str(a) for a in self.templateSpecialization])
else:
specialization = ''
myself = ''
if self.decorators != '':
myself += self.decorators + '\n'
myself += '%spub struct %s%s' % (self.indent, self.name, specialization)
result += myself
assert len(self.bases) == 1 # XXjdm Can we support multiple inheritance?
result += ' {\n'
if self.bases:
self.members = [ClassMember("parent", self.bases[0].name, "pub")] + self.members
result += CGIndenter(CGGeneric(self.extradeclarations),
len(self.indent)).define()
def declareMembers(cgClass, memberList):
result = ''
for member in memberList:
declaration = member.declare(cgClass)
declaration = CGIndenter(CGGeneric(declaration)).define()
result = result + declaration
return result
if self.disallowCopyConstruction:
class DisallowedCopyConstructor(object):
def __init__(self):
self.visibility = "private"
def declare(self, cgClass):
name = cgClass.getNameString()
return ("%s(const %s&) MOZ_DELETE;\n"
"void operator=(const %s) MOZ_DELETE;\n" % (name, name, name))
disallowedCopyConstructors = [DisallowedCopyConstructor()]
else:
disallowedCopyConstructors = []
order = [(self.enums, ''), (self.unions, ''),
(self.typedefs, ''), (self.members, '')]
for (memberList, separator) in order:
memberString = declareMembers(self, memberList)
if self.indent:
memberString = CGIndenter(CGGeneric(memberString),
len(self.indent)).define()
result = result + memberString
result += self.indent + '}\n\n'
result += 'impl %s {\n' % self.name
order = [(self.constructors + disallowedCopyConstructors, '\n'),
(self.destructors, '\n'), (self.methods, '\n)')]
for (memberList, separator) in order:
memberString = declareMembers(self, memberList)
if self.indent:
memberString = CGIndenter(CGGeneric(memberString),
len(self.indent)).define()
result = result + memberString
result += "}"
return result
class CGProxySpecialOperation(CGPerSignatureCall):
"""
Base class for classes for calling an indexed or named special operation
(don't use this directly, use the derived classes below).
"""
def __init__(self, descriptor, operation):
nativeName = MakeNativeName(descriptor.binaryNameFor(operation))
operation = descriptor.operations[operation]
assert len(operation.signatures()) == 1
signature = operation.signatures()[0]
(returnType, arguments) = signature
# We pass len(arguments) as the final argument so that the
# CGPerSignatureCall won't do any argument conversion of its own.
CGPerSignatureCall.__init__(self, returnType, "", arguments, nativeName,
False, descriptor, operation,
len(arguments))
if operation.isSetter() or operation.isCreator():
# arguments[0] is the index or name of the item that we're setting.
argument = arguments[1]
info = getJSToNativeConversionInfo(
argument.type, descriptor, treatNullAs=argument.treatNullAs,
exceptionCode="return JSFalse;")
template = info.template
declType = info.declType
needsRooting = info.needsRooting
templateValues = {
"val": "value.handle()",
}
self.cgRoot.prepend(instantiateJSToNativeConversionTemplate(
template, templateValues, declType, argument.identifier.name,
needsRooting))
self.cgRoot.prepend(CGGeneric("let value = RootedValue::new(cx, desc.get().value);"))
elif operation.isGetter():
self.cgRoot.prepend(CGGeneric("let mut found = false;"))
def getArguments(self):
def process(arg):
argVal = arg.identifier.name
if arg.type.isGeckoInterface() and not arg.type.unroll().inner.isCallback():
argVal += ".r()"
return argVal
args = [(a, process(a)) for a in self.arguments]
if self.idlNode.isGetter():
args.append((FakeArgument(BuiltinTypes[IDLBuiltinType.Types.boolean],
self.idlNode),
"&mut found"))
return args
def wrap_return_value(self):
if not self.idlNode.isGetter() or self.templateValues is None:
return ""
wrap = CGGeneric(wrapForType(**self.templateValues))
wrap = CGIfWrapper(wrap, "found")
return "\n" + wrap.define()
class CGProxyIndexedGetter(CGProxySpecialOperation):
"""
Class to generate a call to an indexed getter. If templateValues is not None
the returned value will be wrapped with wrapForType using templateValues.
"""
def __init__(self, descriptor, templateValues=None):
self.templateValues = templateValues
CGProxySpecialOperation.__init__(self, descriptor, 'IndexedGetter')
class CGProxyIndexedSetter(CGProxySpecialOperation):
"""
Class to generate a call to an indexed setter.
"""
def __init__(self, descriptor):
CGProxySpecialOperation.__init__(self, descriptor, 'IndexedSetter')
class CGProxyNamedOperation(CGProxySpecialOperation):
"""
Class to generate a call to a named operation.
"""
def __init__(self, descriptor, name):
CGProxySpecialOperation.__init__(self, descriptor, name)
def define(self):
# Our first argument is the id we're getting.
argName = self.arguments[0].identifier.name
return ("let %s = jsid_to_str(cx, id);\n"
"let this = UnwrapProxy(proxy);\n"
"let this = &*this;\n" % argName +
CGProxySpecialOperation.define(self))
class CGProxyNamedGetter(CGProxyNamedOperation):
"""
Class to generate a call to an named getter. If templateValues is not None
the returned value will be wrapped with wrapForType using templateValues.
"""
def __init__(self, descriptor, templateValues=None):
self.templateValues = templateValues
CGProxySpecialOperation.__init__(self, descriptor, 'NamedGetter')
class CGProxyNamedPresenceChecker(CGProxyNamedGetter):
"""
Class to generate a call that checks whether a named property exists.
For now, we just delegate to CGProxyNamedGetter
"""
def __init__(self, descriptor):
CGProxyNamedGetter.__init__(self, descriptor)
class CGProxyNamedSetter(CGProxyNamedOperation):
"""
Class to generate a call to a named setter.
"""
def __init__(self, descriptor):
CGProxySpecialOperation.__init__(self, descriptor, 'NamedSetter')
class CGProxyNamedDeleter(CGProxyNamedOperation):
"""
Class to generate a call to a named deleter.
"""
def __init__(self, descriptor):
CGProxySpecialOperation.__init__(self, descriptor, 'NamedDeleter')
class CGProxyUnwrap(CGAbstractMethod):
def __init__(self, descriptor):
args = [Argument('HandleObject', 'obj')]
CGAbstractMethod.__init__(self, descriptor, "UnwrapProxy",
'*const ' + descriptor.concreteType, args, alwaysInline=True)
def definition_body(self):
return CGGeneric("""\
/*if (xpc::WrapperFactory::IsXrayWrapper(obj)) {
obj = js::UnwrapObject(obj);
}*/
//MOZ_ASSERT(IsProxy(obj));
let box_ = GetProxyPrivate(*obj.ptr).to_private() as *const %s;
return box_;""" % self.descriptor.concreteType)
class CGDOMJSProxyHandler_getOwnPropertyDescriptor(CGAbstractExternMethod):
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'),
Argument('HandleId', 'id'),
Argument('MutableHandle<JSPropertyDescriptor>', 'desc')]
CGAbstractExternMethod.__init__(self, descriptor, "getOwnPropertyDescriptor",
"u8", args)
self.descriptor = descriptor
def getBody(self):
indexedGetter = self.descriptor.operations['IndexedGetter']
indexedSetter = self.descriptor.operations['IndexedSetter']
get = ""
if indexedGetter or indexedSetter:
get = "let index = get_array_index_from_id(cx, id);\n"
if indexedGetter:
readonly = toStringBool(self.descriptor.operations['IndexedSetter'] is None)
fillDescriptor = ("desc.get().value = result_root.ptr;\n"
"fill_property_descriptor(&mut *desc.ptr, *proxy.ptr, %s);\n"
"return JSTrue;" % readonly)
templateValues = {
'jsvalRef': 'result_root.handle_mut()',
'successCode': fillDescriptor,
'pre': 'let mut result_root = RootedValue::new(cx, UndefinedValue());'
}
get += ("if let Some(index) = index {\n" +
" let this = UnwrapProxy(proxy);\n" +
" let this = &*this;\n" +
CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define() + "\n" +
"}\n")
namedGetter = self.descriptor.operations['NamedGetter']
if namedGetter:
readonly = toStringBool(self.descriptor.operations['NamedSetter'] is None)
fillDescriptor = ("desc.get().value = result_root.ptr;\n"
"fill_property_descriptor(&mut *desc.ptr, *proxy.ptr, %s);\n"
"return JSTrue;" % readonly)
templateValues = {
'jsvalRef': 'result_root.handle_mut()',
'successCode': fillDescriptor,
'pre': 'let mut result_root = RootedValue::new(cx, UndefinedValue());'
}
# Once we start supporting OverrideBuiltins we need to make
# ResolveOwnProperty or EnumerateOwnProperties filter out named
# properties that shadow prototype properties.
namedGet = ("\n" +
"if RUST_JSID_IS_STRING(id) != 0 && !has_property_on_prototype(cx, proxy, id) {\n" +
CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() + "\n" +
"}\n")
else:
namedGet = ""
return get + """\
let expando = RootedObject::new(cx, get_expando_object(proxy));
//if (!xpc::WrapperFactory::IsXrayWrapper(proxy) && (expando = GetExpandoObject(proxy))) {
if !expando.ptr.is_null() {
if JS_GetPropertyDescriptorById(cx, expando.handle(), id, desc) == 0 {
return JSFalse;
}
if !desc.get().obj.is_null() {
// Pretend the property lives on the wrapper.
desc.get().obj = *proxy.ptr;
return JSTrue;
}
}
""" + namedGet + """\
desc.get().obj = ptr::null_mut();
return JSTrue;"""
def definition_body(self):
return CGGeneric(self.getBody())
# TODO(Issue 5876)
class CGDOMJSProxyHandler_defineProperty(CGAbstractExternMethod):
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'),
Argument('HandleId', 'id'),
Argument('Handle<JSPropertyDescriptor>', 'desc'),
Argument('*mut ObjectOpResult', 'opresult')]
CGAbstractExternMethod.__init__(self, descriptor, "defineProperty", "u8", args)
self.descriptor = descriptor
def getBody(self):
set = ""
indexedSetter = self.descriptor.operations['IndexedSetter']
if indexedSetter:
if not (self.descriptor.operations['IndexedCreator'] is indexedSetter):
raise TypeError("Can't handle creator that's different from the setter")
set += ("let index = get_array_index_from_id(cx, id);\n" +
"if let Some(index) = index {\n" +
" let this = UnwrapProxy(proxy);\n" +
" let this = &*this;\n" +
CGIndenter(CGProxyIndexedSetter(self.descriptor)).define() +
" return JSTrue;\n" +
"}\n")
elif self.descriptor.operations['IndexedGetter']:
set += ("if get_array_index_from_id(cx, id).is_some() {\n" +
" return JSFalse;\n" +
" //return ThrowErrorMessage(cx, MSG_NO_PROPERTY_SETTER, \"%s\");\n" +
"}\n") % self.descriptor.name
namedSetter = self.descriptor.operations['NamedSetter']
if namedSetter:
if not self.descriptor.operations['NamedCreator'] is namedSetter:
raise TypeError("Can't handle creator that's different from the setter")
set += ("if RUST_JSID_IS_STRING(id) != 0 {\n" +
CGIndenter(CGProxyNamedSetter(self.descriptor)).define() +
" (*opresult).code_ = 0; /* SpecialCodes::OkCode */\n" +
" return JSTrue;\n" +
"} else {\n" +
" return JSFalse;\n" +
"}\n")
else:
set += ("if RUST_JSID_IS_STRING(id) != 0 {\n" +
CGIndenter(CGProxyNamedGetter(self.descriptor)).define() +
" if (found) {\n"
# TODO(Issue 5876)
" //return js::IsInNonStrictPropertySet(cx)\n" +
" // ? opresult.succeed()\n" +
" // : ThrowErrorMessage(cx, MSG_NO_NAMED_SETTER, \"${name}\");\n" +
" (*opresult).code_ = 0; /* SpecialCodes::OkCode */\n" +
" return JSTrue;\n" +
" }\n" +
" (*opresult).code_ = 0; /* SpecialCodes::OkCode */\n" +
" return JSTrue;\n"
"}\n") % (self.descriptor.name, self.descriptor.name)
set += "return proxyhandler::define_property(%s);" % ", ".join(a.name for a in self.args)
return set
def definition_body(self):
return CGGeneric(self.getBody())
class CGDOMJSProxyHandler_delete(CGAbstractExternMethod):
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'),
Argument('HandleId', 'id'),
Argument('*mut ObjectOpResult', 'res')]
CGAbstractExternMethod.__init__(self, descriptor, "delete", "u8", args)
self.descriptor = descriptor
def getBody(self):
set = ""
if self.descriptor.operations['NamedDeleter']:
set += CGProxyNamedDeleter(self.descriptor).define()
set += "return proxyhandler::delete(%s) as u8;" % ", ".join(a.name for a in self.args)
return set
def definition_body(self):
return CGGeneric(self.getBody())
class CGDOMJSProxyHandler_ownPropertyKeys(CGAbstractExternMethod):
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'),
Argument('HandleObject', 'proxy'),
Argument('*mut AutoIdVector', 'props')]
CGAbstractExternMethod.__init__(self, descriptor, "own_property_keys", "u8", args)
self.descriptor = descriptor
def getBody(self):
body = dedent(
"""
let unwrapped_proxy = UnwrapProxy(proxy);
""")
if self.descriptor.operations['IndexedGetter']:
body += dedent(
"""
for i in 0..(*unwrapped_proxy).Length() {
let rooted_jsid = RootedId::new(cx, int_to_jsid(i as i32));
AppendToAutoIdVector(props, rooted_jsid.handle().get());
}
""")
if self.descriptor.operations['NamedGetter']:
body += dedent(
"""
for name in (*unwrapped_proxy).SupportedPropertyNames() {
let cstring = CString::new(name).unwrap();
let jsstring = JS_InternString(cx, cstring.as_ptr());
let mut rooted = RootedString::new(cx, jsstring);
let jsid = INTERNED_STRING_TO_JSID(cx, rooted.handle().get());
let rooted_jsid = RootedId::new(cx, jsid);
AppendToAutoIdVector(props, rooted_jsid.handle().get());
}
""")
body += dedent(
"""
let expando = get_expando_object(proxy);
if !expando.is_null() {
let rooted_expando = RootedObject::new(cx, expando);
GetPropertyKeys(cx, rooted_expando.handle(), JSITER_OWNONLY | JSITER_HIDDEN | JSITER_SYMBOLS, props);
}
return JSTrue;
""")
return body
def definition_body(self):
return CGGeneric(self.getBody())
class CGDOMJSProxyHandler_hasOwn(CGAbstractExternMethod):
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'),
Argument('HandleId', 'id'), Argument('*mut u8', 'bp')]
CGAbstractExternMethod.__init__(self, descriptor, "hasOwn", "u8", args)
self.descriptor = descriptor
def getBody(self):
indexedGetter = self.descriptor.operations['IndexedGetter']
if indexedGetter:
indexed = ("let index = get_array_index_from_id(cx, id);\n" +
"if let Some(index) = index {\n" +
" let this = UnwrapProxy(proxy);\n" +
" let this = &*this;\n" +
CGIndenter(CGProxyIndexedGetter(self.descriptor)).define() + "\n" +
" *bp = found as u8;\n" +
" return JSTrue;\n" +
"}\n\n")
else:
indexed = ""
namedGetter = self.descriptor.operations['NamedGetter']
if namedGetter:
named = ("if RUST_JSID_IS_STRING(id) != 0 && !has_property_on_prototype(cx, proxy, id) {\n" +
CGIndenter(CGProxyNamedGetter(self.descriptor)).define() + "\n" +
" *bp = found as u8;\n"
" return JSTrue;\n"
"}\n" +
"\n")
else:
named = ""
return indexed + """\
let expando = RootedObject::new(cx, get_expando_object(proxy));
if !expando.ptr.is_null() {
let mut b: u8 = 1;
let ok = JS_HasPropertyById(cx, expando.handle(), id, &mut b) != 0;
*bp = (b != 0) as u8;
if !ok || *bp != 0 {
return ok as u8;
}
}
""" + named + """\
*bp = JSFalse;
return JSTrue;"""
def definition_body(self):
return CGGeneric(self.getBody())
class CGDOMJSProxyHandler_get(CGAbstractExternMethod):
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', 'proxy'),
Argument('HandleObject', '_receiver'), Argument('HandleId', 'id'),
Argument('MutableHandleValue', 'vp')]
CGAbstractExternMethod.__init__(self, descriptor, "get", "u8", args)
self.descriptor = descriptor
def getBody(self):
getFromExpando = """\
let expando = RootedObject::new(cx, get_expando_object(proxy));
if !expando.ptr.is_null() {
let mut hasProp = 0;
if JS_HasPropertyById(cx, expando.handle(), id, &mut hasProp) == 0 {
return JSFalse;
}
if hasProp != 0 {
return (JS_GetPropertyById(cx, expando.handle(), id, vp) != 0) as u8;
}
}"""
templateValues = {
'jsvalRef': 'vp',
'successCode': 'return JSTrue;',
}
indexedGetter = self.descriptor.operations['IndexedGetter']
if indexedGetter:
getIndexedOrExpando = ("let index = get_array_index_from_id(cx, id);\n" +
"if let Some(index) = index {\n" +
" let this = UnwrapProxy(proxy);\n" +
" let this = &*this;\n" +
CGIndenter(CGProxyIndexedGetter(self.descriptor, templateValues)).define())
getIndexedOrExpando += """\
// Even if we don't have this index, we don't forward the
// get on to our expando object.
} else {
%s
}
""" % (stripTrailingWhitespace(getFromExpando.replace('\n', '\n ')))
else:
getIndexedOrExpando = getFromExpando + "\n"
namedGetter = self.descriptor.operations['NamedGetter']
if namedGetter:
getNamed = ("if (RUST_JSID_IS_STRING(id) != 0) {\n" +
CGIndenter(CGProxyNamedGetter(self.descriptor, templateValues)).define() +
"}\n")
else:
getNamed = ""
return """\
//MOZ_ASSERT(!xpc::WrapperFactory::IsXrayWrapper(proxy),
//"Should not have a XrayWrapper here");
%s
let mut found = false;
if !get_property_on_prototype(cx, proxy, id, &mut found, vp) {
return JSFalse;
}
if found {
return JSTrue;
}
%s
*vp.ptr = UndefinedValue();
return JSTrue;""" % (getIndexedOrExpando, getNamed)
def definition_body(self):
return CGGeneric(self.getBody())
class CGDOMJSProxyHandler_className(CGAbstractExternMethod):
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('HandleObject', '_proxy')]
CGAbstractExternMethod.__init__(self, descriptor, "className", "*const i8", args)
self.descriptor = descriptor
def getBody(self):
return '%s as *const u8 as *const i8' % str_to_const_array(self.descriptor.name)
def definition_body(self):
return CGGeneric(self.getBody())
class CGAbstractClassHook(CGAbstractExternMethod):
"""
Meant for implementing JSClass hooks, like Finalize or Trace. Does very raw
'this' unwrapping as it assumes that the unwrapped type is always known.
"""
def __init__(self, descriptor, name, returnType, args):
CGAbstractExternMethod.__init__(self, descriptor, name, returnType,
args)
def definition_body_prologue(self):
return CGGeneric("""\
let this: *const %s = native_from_reflector::<%s>(obj);
""" % (self.descriptor.concreteType, self.descriptor.concreteType))
def definition_body(self):
return CGList([
self.definition_body_prologue(),
self.generate_code(),
])
def generate_code(self):
raise NotImplementedError # Override me!
def finalizeHook(descriptor, hookName, context):
release = ""
if descriptor.isGlobal():
release += """\
finalize_global(obj);
"""
release += """\
let _ = Box::from_raw(this as *mut %s);
debug!("%s finalize: {:p}", this);\
""" % (descriptor.concreteType, descriptor.concreteType)
return release
class CGClassTraceHook(CGAbstractClassHook):
"""
A hook to trace through our native object; used for GC and CC
"""
def __init__(self, descriptor):
args = [Argument('*mut JSTracer', 'trc'), Argument('*mut JSObject', 'obj')]
CGAbstractClassHook.__init__(self, descriptor, TRACE_HOOK_NAME, 'void',
args)
self.traceGlobal = descriptor.isGlobal()
def generate_code(self):
body = [CGGeneric("if this.is_null() { return; } // GC during obj creation\n"
"(*this).trace(%s);" % self.args[0].name)]
if self.traceGlobal:
body += [CGGeneric("trace_global(trc, obj);")]
return CGList(body, "\n")
class CGClassConstructHook(CGAbstractExternMethod):
"""
JS-visible constructor for our objects
"""
def __init__(self, descriptor):
args = [Argument('*mut JSContext', 'cx'), Argument('u32', 'argc'), Argument('*mut JSVal', 'vp')]
CGAbstractExternMethod.__init__(self, descriptor, CONSTRUCT_HOOK_NAME,
'u8', args)
self._ctor = self.descriptor.interface.ctor()
def define(self):
if not self._ctor:
return ""
return CGAbstractExternMethod.define(self)
def definition_body(self):
preamble = CGGeneric("""\
let global = global_object_for_js_object(JS_CALLEE(cx, vp).to_object());
let args = CallArgs::from_vp(vp, argc);
""")
name = self._ctor.identifier.name
nativeName = MakeNativeName(self.descriptor.binaryNameFor(name))
callGenerator = CGMethodCall(["global.r()"], nativeName, True,
self.descriptor, self._ctor)
return CGList([preamble, callGenerator])
class CGClassNameConstructHook(CGAbstractExternMethod):
"""
JS-visible named constructor for our objects
"""
def __init__(self, descriptor, ctor):
args = [Argument('*mut JSContext', 'cx'), Argument('u32', 'argc'), Argument('*mut JSVal', 'vp')]
self._ctor = ctor
CGAbstractExternMethod.__init__(self, descriptor,
CONSTRUCT_HOOK_NAME + "_" +
self._ctor.identifier.name,
'u8', args)
def definition_body(self):
preamble = CGGeneric("""\
let global = global_object_for_js_object(JS_CALLEE(cx, vp).to_object());
let args = CallArgs::from_vp(vp, argc);
""")
name = self._ctor.identifier.name
nativeName = MakeNativeName(self.descriptor.binaryNameFor(name))
callGenerator = CGMethodCall(["global.r()"], nativeName, True,
self.descriptor, self._ctor)
return CGList([preamble, callGenerator])
class CGClassFinalizeHook(CGAbstractClassHook):
"""
A hook for finalize, used to release our native object.
"""
def __init__(self, descriptor):
args = [Argument('*mut FreeOp', '_fop'), Argument('*mut JSObject', 'obj')]
CGAbstractClassHook.__init__(self, descriptor, FINALIZE_HOOK_NAME,
'void', args)
def generate_code(self):
return CGGeneric(finalizeHook(self.descriptor, self.name, self.args[0].name))
class CGDOMJSProxyHandlerDOMClass(CGThing):
def __init__(self, descriptor):
CGThing.__init__(self)
self.descriptor = descriptor
def define(self):
return "static Class: DOMClass = " + DOMClass(self.descriptor) + ";\n"
class CGInterfaceTrait(CGThing):
def __init__(self, descriptor):
CGThing.__init__(self)
def attribute_arguments(needCx, argument=None):
if needCx:
yield "cx", "*mut JSContext"
if argument:
yield "value", argument_type(descriptor, argument)
def members():
for m in descriptor.interface.members:
if (m.isMethod() and not m.isStatic() and
(not m.isIdentifierLess() or m.isStringifier())):
name = CGSpecializedMethod.makeNativeName(descriptor, m)
infallible = 'infallible' in descriptor.getExtendedAttributes(m)
for idx, (rettype, arguments) in enumerate(m.signatures()):
arguments = method_arguments(descriptor, rettype, arguments)
rettype = return_type(descriptor, rettype, infallible)
yield name + ('_' * idx), arguments, rettype
elif m.isAttr() and not m.isStatic():
name = CGSpecializedGetter.makeNativeName(descriptor, m)
infallible = 'infallible' in descriptor.getExtendedAttributes(m, getter=True)
yield (name,
attribute_arguments(typeNeedsCx(m.type, True)),
return_type(descriptor, m.type, infallible))
if not m.readonly:
name = CGSpecializedSetter.makeNativeName(descriptor, m)
infallible = 'infallible' in descriptor.getExtendedAttributes(m, setter=True)
if infallible:
rettype = "()"
else:
rettype = "ErrorResult"
yield name, attribute_arguments(typeNeedsCx(m.type, False), m.type), rettype
if descriptor.proxy:
for name, operation in descriptor.operations.iteritems():
if not operation or operation.isStringifier():
continue
assert len(operation.signatures()) == 1
rettype, arguments = operation.signatures()[0]
infallible = 'infallible' in descriptor.getExtendedAttributes(operation)
if operation.isGetter():
arguments = method_arguments(descriptor, rettype, arguments, trailing=("found", "&mut bool"))
# If this interface 'supports named properties', then we
# should be able to access 'supported property names'
#
# WebIDL, Second Draft, section 3.2.4.5
# https://heycam.github.io/webidl/#idl-named-properties
if operation.isNamed():
yield "SupportedPropertyNames", [], "Vec<DOMString>"
else:
arguments = method_arguments(descriptor, rettype, arguments)
rettype = return_type(descriptor, rettype, infallible)
yield name, arguments, rettype
def fmt(arguments):
return "".join(", %s: %s" % argument for argument in arguments)
methods = [
CGGeneric("fn %s(&self%s) -> %s;\n" % (name, fmt(arguments), rettype))
for name, arguments, rettype in members()
]
if methods:
self.cgRoot = CGWrapper(CGIndenter(CGList(methods, "")),
pre="pub trait %sMethods {\n" % descriptor.interface.identifier.name,
post="}")
else:
self.cgRoot = CGGeneric("")
def define(self):
return self.cgRoot.define()
class CGDescriptor(CGThing):
def __init__(self, descriptor):
CGThing.__init__(self)
assert not descriptor.concrete or not descriptor.interface.isCallback()
cgThings = []
if not descriptor.interface.isCallback():
cgThings.append(CGGetProtoObjectMethod(descriptor))
if descriptor.interface.hasInterfaceObject():
# https://github.com/mozilla/servo/issues/2665
# cgThings.append(CGGetConstructorObjectMethod(descriptor))
pass
for m in descriptor.interface.members:
if (m.isMethod() and
(not m.isIdentifierLess() or m == descriptor.operations["Stringifier"])):
if m.isStatic():
assert descriptor.interface.hasInterfaceObject()
cgThings.append(CGStaticMethod(descriptor, m))
elif not descriptor.interface.isCallback():
cgThings.append(CGSpecializedMethod(descriptor, m))
cgThings.append(CGMemberJITInfo(descriptor, m))
elif m.isAttr():
if m.stringifier:
raise TypeError("Stringifier attributes not supported yet. "
"See bug 824857.\n"
"%s" % m.location)
if m.isStatic():
assert descriptor.interface.hasInterfaceObject()
cgThings.append(CGStaticGetter(descriptor, m))
elif not descriptor.interface.isCallback():
cgThings.append(CGSpecializedGetter(descriptor, m))
if not m.readonly:
if m.isStatic():
assert descriptor.interface.hasInterfaceObject()
cgThings.append(CGStaticSetter(descriptor, m))
elif not descriptor.interface.isCallback():
cgThings.append(CGSpecializedSetter(descriptor, m))
elif m.getExtendedAttribute("PutForwards"):
cgThings.append(CGSpecializedForwardingSetter(descriptor, m))
if (not m.isStatic() and not descriptor.interface.isCallback()):
cgThings.append(CGMemberJITInfo(descriptor, m))
if descriptor.concrete:
cgThings.append(CGClassFinalizeHook(descriptor))
cgThings.append(CGClassTraceHook(descriptor))
if descriptor.interface.hasInterfaceObject():
cgThings.append(CGClassConstructHook(descriptor))
for ctor in descriptor.interface.namedConstructors:
cgThings.append(CGClassNameConstructHook(descriptor, ctor))
cgThings.append(CGInterfaceObjectJSClass(descriptor))
if not descriptor.interface.isCallback():
cgThings.append(CGPrototypeJSClass(descriptor))
properties = PropertyArrays(descriptor)
cgThings.append(CGGeneric(str(properties)))
cgThings.append(CGNativeProperties(descriptor, properties))
cgThings.append(CGNativePropertyHooks(descriptor, properties))
cgThings.append(CGCreateInterfaceObjectsMethod(descriptor, properties))
cgThings.append(CGNamespace.build([descriptor.name + "Constants"],
CGConstant(m for m in descriptor.interface.members if m.isConst()),
public=True))
if descriptor.interface.hasInterfaceObject():
cgThings.append(CGDefineDOMInterfaceMethod(descriptor))
if descriptor.proxy:
cgThings.append(CGDefineProxyHandler(descriptor))
if descriptor.concrete:
if descriptor.proxy:
# cgThings.append(CGProxyIsProxy(descriptor))
cgThings.append(CGProxyUnwrap(descriptor))
cgThings.append(CGDOMJSProxyHandlerDOMClass(descriptor))
cgThings.append(CGDOMJSProxyHandler_ownPropertyKeys(descriptor))
cgThings.append(CGDOMJSProxyHandler_getOwnPropertyDescriptor(descriptor))
cgThings.append(CGDOMJSProxyHandler_className(descriptor))
cgThings.append(CGDOMJSProxyHandler_get(descriptor))
cgThings.append(CGDOMJSProxyHandler_hasOwn(descriptor))
if descriptor.operations['IndexedSetter'] or descriptor.operations['NamedSetter']:
cgThings.append(CGDOMJSProxyHandler_defineProperty(descriptor))
# We want to prevent indexed deleters from compiling at all.
assert not descriptor.operations['IndexedDeleter']
if descriptor.operations['NamedDeleter']:
cgThings.append(CGDOMJSProxyHandler_delete(descriptor))
# cgThings.append(CGDOMJSProxyHandler(descriptor))
# cgThings.append(CGIsMethod(descriptor))
pass
else:
cgThings.append(CGDOMJSClass(descriptor))
pass
cgThings.append(CGWrapMethod(descriptor))
if not descriptor.interface.isCallback():
cgThings.append(CGIDLInterface(descriptor))
cgThings.append(CGInterfaceTrait(descriptor))
cgThings = CGList(cgThings, "\n")
# self.cgRoot = CGWrapper(CGNamespace(toBindingNamespace(descriptor.name),
# cgThings),
# post='\n')
self.cgRoot = cgThings
def define(self):
return self.cgRoot.define()
class CGNonNamespacedEnum(CGThing):
def __init__(self, enumName, names, values, comment="", deriving="", repr=""):
if not values:
values = []
# Account for explicit enum values.
entries = []
for i in range(0, len(names)):
if len(values) > i and values[i] is not None:
entry = "%s = %s" % (names[i], values[i])
else:
entry = names[i]
entries.append(entry)
# Append a Count.
entries.append('Count = ' + str(len(entries)))
# Indent.
entries = [' ' + e for e in entries]
# Build the enum body.
enumstr = comment + 'pub enum %s {\n%s\n}\n' % (enumName, ',\n'.join(entries))
if repr:
enumstr = ('#[repr(%s)]\n' % repr) + enumstr
if deriving:
enumstr = ('#[derive(%s)]\n' % deriving) + enumstr
curr = CGGeneric(enumstr)
# Add some whitespace padding.
curr = CGWrapper(curr, pre='\n', post='\n')
# Add the typedef
# typedef = '\ntypedef %s::%s %s;\n\n' % (namespace, enumName, enumName)
# curr = CGList([curr, CGGeneric(typedef)])
# Save the result.
self.node = curr
def define(self):
return self.node.define()
class CGDictionary(CGThing):
def __init__(self, dictionary, descriptorProvider):
self.dictionary = dictionary
if all(CGDictionary(d, descriptorProvider).generatable for
d in CGDictionary.getDictionaryDependencies(dictionary)):
self.generatable = True
else:
self.generatable = False
# Nothing else to do here
return
self.memberInfo = [
(member,
getJSToNativeConversionInfo(member.type,
descriptorProvider,
isMember="Dictionary",
defaultValue=member.defaultValue,
exceptionCode="return Err(());"))
for member in dictionary.members]
def define(self):
if not self.generatable:
return ""
return self.struct() + "\n" + self.impl()
def struct(self):
d = self.dictionary
if d.parent:
inheritance = " pub parent: %s::%s,\n" % (self.makeModuleName(d.parent),
self.makeClassName(d.parent))
else:
inheritance = ""
memberDecls = [" pub %s: %s," %
(self.makeMemberName(m[0].identifier.name), self.getMemberType(m))
for m in self.memberInfo]
return (string.Template(
"#[no_move]\n" +
"pub struct ${selfName} {\n" +
"${inheritance}" +
"\n".join(memberDecls) + "\n" +
"}").substitute({"selfName": self.makeClassName(d),
"inheritance": inheritance}))
def impl(self):
d = self.dictionary
if d.parent:
initParent = "parent: try!(%s::%s::new(cx, val)),\n" % (
self.makeModuleName(d.parent),
self.makeClassName(d.parent))
else:
initParent = ""
def memberInit(memberInfo):
member, _ = memberInfo
name = self.makeMemberName(member.identifier.name)
conversion = self.getMemberConversion(memberInfo, member.type)
return CGGeneric("%s: %s,\n" % (name, conversion.define()))
def memberInsert(memberInfo):
member, _ = memberInfo
name = self.makeMemberName(member.identifier.name)
insertion = ("let mut %s = RootedValue::new(cx, UndefinedValue());\n"
"self.%s.to_jsval(cx, %s.handle_mut());\n"
"set_dictionary_property(cx, obj.handle(), \"%s\", %s.handle()).unwrap();"
% (name, name, name, name, name))
return CGGeneric("%s\n" % insertion)
memberInits = CGList([memberInit(m) for m in self.memberInfo])
memberInserts = CGList([memberInsert(m) for m in self.memberInfo])
return string.Template(
"impl ${selfName} {\n"
" pub fn empty(cx: *mut JSContext) -> ${selfName} {\n"
" ${selfName}::new(cx, HandleValue::null()).unwrap()\n"
" }\n"
" pub fn new(cx: *mut JSContext, val: HandleValue) -> Result<${selfName}, ()> {\n"
" let object = if val.get().is_null_or_undefined() {\n"
" RootedObject::new(cx, ptr::null_mut())\n"
" } else if val.get().is_object() {\n"
" RootedObject::new(cx, val.get().to_object())\n"
" } else {\n"
" throw_type_error(cx, \"Value not an object.\");\n"
" return Err(());\n"
" };\n"
" Ok(${selfName} {\n"
"${initParent}"
"${initMembers}"
" })\n"
" }\n"
"}\n"
"\n"
"impl ToJSValConvertible for ${selfName} {\n"
" fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {\n"
" let obj = unsafe { RootedObject::new(cx, JS_NewObject(cx, ptr::null())) };\n"
"${insertMembers}"
" rval.set(ObjectOrNullValue(obj.ptr))\n"
" }\n"
"}\n").substitute({
"selfName": self.makeClassName(d),
"initParent": CGIndenter(CGGeneric(initParent), indentLevel=12).define(),
"initMembers": CGIndenter(memberInits, indentLevel=12).define(),
"insertMembers": CGIndenter(memberInserts, indentLevel=8).define(),
})
@staticmethod
def makeDictionaryName(dictionary):
return dictionary.identifier.name
def makeClassName(self, dictionary):
return self.makeDictionaryName(dictionary)
@staticmethod
def makeModuleName(dictionary):
return dictionary.module()
def getMemberType(self, memberInfo):
member, info = memberInfo
declType = info.declType
if member.optional and not member.defaultValue:
declType = CGWrapper(info.declType, pre="Option<", post=">")
return declType.define()
def getMemberConversion(self, memberInfo, memberType):
def indent(s):
return CGIndenter(CGGeneric(s), 8).define()
member, info = memberInfo
templateBody = info.template
default = info.default
replacements = {"val": "rval.handle()"}
conversion = string.Template(templateBody).substitute(replacements)
if memberType.isAny():
conversion = "%s.get()" % conversion
assert (member.defaultValue is None) == (default is None)
if not member.optional:
assert default is None
default = ("throw_type_error(cx, \"Missing required member \\\"%s\\\".\");\n"
"return Err(());") % member.identifier.name
elif not default:
default = "None"
conversion = "Some(%s)" % conversion
conversion = (
"{\n"
"let mut rval = RootedValue::new(cx, UndefinedValue());\n"
"match try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n"
" true => {\n"
"%s\n"
" },\n"
" false => {\n"
"%s\n"
" },\n"
"}\n}") % (member.identifier.name, indent(conversion), indent(default))
return CGGeneric(conversion)
@staticmethod
def makeMemberName(name):
# Can't use Rust keywords as member names.
if name == "type":
return name + "_"
return name
@staticmethod
def getDictionaryDependencies(dictionary):
deps = set()
if dictionary.parent:
deps.add(dictionary.parent)
for member in dictionary.members:
if member.type.isDictionary():
deps.add(member.type.unroll().inner)
return deps
class CGRegisterProtos(CGAbstractMethod):
def __init__(self, config):
arguments = [
Argument('*mut JSContext', 'cx'),
Argument('HandleObject', 'global'),
]
CGAbstractMethod.__init__(self, None, 'Register', 'void', arguments,
unsafe=False, pub=True)
self.config = config
def definition_body(self):
return CGList([
CGGeneric("codegen::Bindings::%sBinding::DefineDOMInterface(cx, global);" % desc.name)
for desc in self.config.getDescriptors(hasInterfaceObject=True, register=True)
], "\n")
class CGRegisterProxyHandlersMethod(CGAbstractMethod):
def __init__(self, descriptors):
CGAbstractMethod.__init__(self, None, 'RegisterProxyHandlers', 'void', [],
unsafe=True, pub=True)
self.descriptors = descriptors
def definition_body(self):
return CGList([
CGGeneric("proxy_handlers[Proxies::%s as usize] = codegen::Bindings::%sBinding::DefineProxyHandler();"
% (desc.name, desc.name))
for desc in self.descriptors
], "\n")
class CGRegisterProxyHandlers(CGThing):
def __init__(self, config):
descriptors = config.getDescriptors(proxy=True)
length = len(descriptors)
self.root = CGList([
CGGeneric("pub static mut proxy_handlers: [*const libc::c_void; %d] = [0 as *const libc::c_void; %d];"
% (length, length)),
CGRegisterProxyHandlersMethod(descriptors),
], "\n")
def define(self):
return self.root.define()
class CGBindingRoot(CGThing):
"""
Root codegen class for binding generation. Instantiate the class, and call
declare or define to generate header or cpp code (respectively).
"""
def __init__(self, config, prefix, webIDLFile):
descriptors = config.getDescriptors(webIDLFile=webIDLFile,
hasInterfaceObject=True)
# We also want descriptors that have an interface prototype object
# (isCallback=False), but we don't want to include a second copy
# of descriptors that we also matched in the previous line
# (hence hasInterfaceObject=False).
descriptors.extend(config.getDescriptors(webIDLFile=webIDLFile,
hasInterfaceObject=False,
isCallback=False))
dictionaries = config.getDictionaries(webIDLFile=webIDLFile)
cgthings = []
mainCallbacks = config.getCallbacks(webIDLFile=webIDLFile)
callbackDescriptors = config.getDescriptors(webIDLFile=webIDLFile,
isCallback=True)
# Do codegen for all the enums
cgthings = [CGEnum(e) for e in config.getEnums(webIDLFile)]
cgthings.extend([CGDictionary(d, config.getDescriptorProvider())
for d in dictionaries])
# Do codegen for all the callbacks.
cgthings.extend(CGList([CGCallbackFunction(c, config.getDescriptorProvider()),
CGCallbackFunctionImpl(c)], "\n")
for c in mainCallbacks)
# Do codegen for all the descriptors
cgthings.extend([CGDescriptor(x) for x in descriptors])
# Do codegen for all the callback interfaces.
cgthings.extend(CGList([CGCallbackInterface(x),
CGCallbackFunctionImpl(x.interface)], "\n")
for x in callbackDescriptors)
# And make sure we have the right number of newlines at the end
curr = CGWrapper(CGList(cgthings, "\n\n"), post="\n\n")
# Wrap all of that in our namespaces.
# curr = CGNamespace.build(['dom'],
# CGWrapper(curr, pre="\n"))
# Add imports
curr = CGImports(curr, descriptors + callbackDescriptors, mainCallbacks, [
'js',
'js::JS_CALLEE',
'js::{JSCLASS_GLOBAL_SLOT_COUNT, JSCLASS_IS_DOMJSCLASS, JSCLASS_IMPLEMENTS_BARRIERS}',
'js::{JSCLASS_IS_GLOBAL, JSCLASS_RESERVED_SLOTS_SHIFT}',
'js::{JSCLASS_RESERVED_SLOTS_MASK}',
'js::{JSPROP_ENUMERATE, JSPROP_SHARED}',
'js::{JSITER_OWNONLY, JSITER_HIDDEN, JSITER_SYMBOLS}',
'js::jsapi::{JS_CallFunctionValue, JS_GetClass, JS_GetGlobalForObject}',
'js::jsapi::{JS_GetObjectPrototype, JS_GetProperty, JS_GetPropertyById}',
'js::jsapi::{JS_GetPropertyDescriptorById, JS_GetReservedSlot}',
'js::jsapi::{JS_HasProperty, JS_HasPropertyById, JS_IsExceptionPending}',
'js::jsapi::{JS_NewObjectWithGivenProto, JS_NewObject, IsCallable, JS_SetProperty, JS_SetPrototype}',
'js::jsapi::{JS_SetReservedSlot, JS_WrapValue, JSContext}',
'js::jsapi::{JSClass, FreeOp, JSFreeOp, JSFunctionSpec, jsid}',
'js::jsapi::{MutableHandleValue, MutableHandleObject, HandleObject, HandleValue, RootedObject}',
'js::jsapi::{RootedValue, JSNativeWrapper, JSNative, JSObject, JSPropertyDescriptor}',
'js::jsapi::{RootedId, JS_InternString, RootedString, INTERNED_STRING_TO_JSID}',
'js::jsapi::{JSPropertySpec}',
'js::jsapi::{JSString, JSTracer, JSJitInfo, JSJitInfo_OpType, JSJitInfo_AliasSet}',
'js::jsapi::{MutableHandle, Handle, HandleId, JSType, JSValueType}',
'js::jsapi::{SymbolCode, ObjectOpResult, HandleValueArray}',
'js::jsapi::{JSJitGetterCallArgs, JSJitSetterCallArgs, JSJitMethodCallArgs, CallArgs}',
'js::jsapi::{JSAutoCompartment, JSAutoRequest, JS_ComputeThis}',
'js::jsapi::{GetGlobalForObjectCrossCompartment, AutoIdVector, GetPropertyKeys}',
'js::jsval::JSVal',
'js::jsval::{ObjectValue, ObjectOrNullValue, PrivateValue}',
'js::jsval::{NullValue, UndefinedValue}',
'js::glue::{CallJitMethodOp, CallJitGetterOp, CallJitSetterOp, CreateProxyHandler}',
'js::glue::{GetProxyPrivate, NewProxyObject, ProxyTraps}',
'js::glue::{RUST_FUNCTION_VALUE_TO_JITINFO}',
'js::glue::{RUST_JS_NumberValue, RUST_JSID_IS_STRING, int_to_jsid}',
'js::glue::AppendToAutoIdVector',
'js::rust::GCMethods',
'js::{JSTrue, JSFalse}',
'dom::bindings',
'dom::bindings::global::GlobalRef',
'dom::bindings::global::global_object_for_js_object',
'dom::bindings::js::{JS, Root, RootedReference}',
'dom::bindings::js::{OptionalRootedReference}',
'dom::bindings::utils::{create_dom_global, do_create_interface_objects}',
'dom::bindings::utils::ConstantSpec',
'dom::bindings::utils::{DOMClass}',
'dom::bindings::utils::{DOMJSClass, JSCLASS_DOM_GLOBAL}',
'dom::bindings::utils::{find_enum_string_index, get_array_index_from_id}',
'dom::bindings::utils::{get_property_on_prototype, get_proto_or_iface_array}',
'dom::bindings::utils::{finalize_global, trace_global}',
'dom::bindings::utils::has_property_on_prototype',
'dom::bindings::utils::is_platform_object',
'dom::bindings::utils::{Reflectable}',
'dom::bindings::utils::throwing_constructor',
'dom::bindings::utils::get_dictionary_property',
'dom::bindings::utils::set_dictionary_property',
'dom::bindings::utils::{NativeProperties, NativePropertyHooks}',
'dom::bindings::utils::ConstantVal::{IntVal, UintVal}',
'dom::bindings::utils::NonNullJSNative',
'dom::bindings::utils::{generic_getter, generic_lenient_getter}',
'dom::bindings::utils::{generic_lenient_setter, generic_method}',
'dom::bindings::utils::generic_setter',
'dom::bindings::trace::{JSTraceable, RootedTraceable}',
'dom::bindings::callback::{CallbackContainer,CallbackInterface,CallbackFunction}',
'dom::bindings::callback::{CallSetup,ExceptionHandling}',
'dom::bindings::callback::wrap_call_this_object',
'dom::bindings::conversions::{FromJSValConvertible, ToJSValConvertible, ConversionBehavior}',
'dom::bindings::conversions::{native_from_reflector, native_from_handlevalue, native_from_handleobject}',
'dom::bindings::conversions::DOM_OBJECT_SLOT',
'dom::bindings::conversions::IDLInterface',
'dom::bindings::conversions::jsid_to_str',
'dom::bindings::conversions::StringificationBehavior',
'dom::bindings::codegen::{PrototypeList, RegisterBindings, UnionTypes}',
'dom::bindings::codegen::Bindings::*',
'dom::bindings::error::{Fallible, Error, ErrorResult}',
'dom::bindings::error::Error::JSFailed',
'dom::bindings::error::throw_dom_exception',
'dom::bindings::error::throw_type_error',
'dom::bindings::proxyhandler',
'dom::bindings::proxyhandler::{fill_property_descriptor, get_expando_object}',
'dom::bindings::proxyhandler::{get_property_descriptor}',
'dom::bindings::num::Finite',
'dom::bindings::str::ByteString',
'dom::bindings::str::USVString',
'libc',
'util::str::DOMString',
'std::borrow::ToOwned',
'std::cmp',
'std::mem',
'std::num',
'std::ptr',
'std::str',
'std::rc',
'std::rc::Rc',
'std::default::Default',
'std::ffi::CString',
])
# Add the auto-generated comment.
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
# Store the final result.
self.root = curr
def define(self):
return stripTrailingWhitespace(self.root.define())
def argument_type(descriptorProvider, ty, optional=False, defaultValue=None, variadic=False):
info = getJSToNativeConversionInfo(
ty, descriptorProvider, isArgument=True)
declType = info.declType
if variadic:
declType = CGWrapper(declType, pre="Vec<", post=">")
elif optional and not defaultValue:
declType = CGWrapper(declType, pre="Option<", post=">")
if ty.isDictionary():
declType = CGWrapper(declType, pre="&")
return declType.define()
def method_arguments(descriptorProvider, returnType, arguments, passJSBits=True, trailing=None):
if needCx(returnType, arguments, passJSBits):
yield "cx", "*mut JSContext"
for argument in arguments:
ty = argument_type(descriptorProvider, argument.type, argument.optional,
argument.defaultValue, argument.variadic)
yield CGDictionary.makeMemberName(argument.identifier.name), ty
if trailing:
yield trailing
def return_type(descriptorProvider, rettype, infallible):
result = getRetvalDeclarationForType(rettype, descriptorProvider)
if not infallible:
result = CGWrapper(result, pre="Fallible<", post=">")
return result.define()
class CGNativeMember(ClassMethod):
def __init__(self, descriptorProvider, member, name, signature, extendedAttrs,
breakAfter=True, passJSBitsAsNeeded=True, visibility="public"):
"""
If passJSBitsAsNeeded is false, we don't automatically pass in a
JSContext* or a JSObject* based on the return and argument types.
"""
self.descriptorProvider = descriptorProvider
self.member = member
self.extendedAttrs = extendedAttrs
self.passJSBitsAsNeeded = passJSBitsAsNeeded
breakAfterSelf = "\n" if breakAfter else ""
ClassMethod.__init__(self, name,
self.getReturnType(signature[0]),
self.getArgs(signature[0], signature[1]),
static=member.isStatic(),
# Mark our getters, which are attrs that
# have a non-void return type, as const.
const=(not member.isStatic() and member.isAttr() and
not signature[0].isVoid()),
breakAfterSelf=breakAfterSelf,
visibility=visibility)
def getReturnType(self, type):
infallible = 'infallible' in self.extendedAttrs
typeDecl = return_type(self.descriptorProvider, type, infallible)
return typeDecl
def getArgs(self, returnType, argList):
return [Argument(arg[1], arg[0]) for arg in method_arguments(self.descriptorProvider,
returnType,
argList,
self.passJSBitsAsNeeded)]
class CGCallback(CGClass):
def __init__(self, idlObject, descriptorProvider, baseName, methods,
getters=[], setters=[]):
self.baseName = baseName
self._deps = idlObject.getDeps()
name = idlObject.identifier.name
# For our public methods that needThisHandling we want most of the
# same args and the same return type as what CallbackMember
# generates. So we want to take advantage of all its
# CGNativeMember infrastructure, but that infrastructure can't deal
# with templates and most especially template arguments. So just
# cheat and have CallbackMember compute all those things for us.
realMethods = []
for method in methods:
if not method.needThisHandling:
realMethods.append(method)
else:
realMethods.extend(self.getMethodImpls(method))
CGClass.__init__(self, name,
bases=[ClassBase(baseName)],
constructors=self.getConstructors(),
methods=realMethods + getters + setters,
decorators="#[derive(JSTraceable, PartialEq)]")
def getConstructors(self):
return [ClassConstructor(
[Argument("*mut JSObject", "aCallback")],
bodyInHeader=True,
visibility="pub",
explicit=False,
baseConstructors=[
"%s::new()" % self.baseName
])]
def getMethodImpls(self, method):
assert method.needThisHandling
args = list(method.args)
# Strip out the JSContext*/JSObject* args
# that got added.
assert args[0].name == "cx" and args[0].argType == "*mut JSContext"
assert args[1].name == "aThisObj" and args[1].argType == "HandleObject"
args = args[2:]
# Record the names of all the arguments, so we can use them when we call
# the private method.
argnames = [arg.name for arg in args]
argnamesWithThis = ["s.get_context()", "thisObjJS.handle()"] + argnames
argnamesWithoutThis = ["s.get_context()", "thisObjJS.handle()"] + argnames
# Now that we've recorded the argnames for our call to our private
# method, insert our optional argument for deciding whether the
# CallSetup should re-throw exceptions on aRv.
args.append(Argument("ExceptionHandling", "aExceptionHandling",
"ReportExceptions"))
# And now insert our template argument.
argsWithoutThis = list(args)
args.insert(0, Argument("&T", "thisObj"))
# And the self argument
method.args.insert(0, Argument(None, "&self"))
args.insert(0, Argument(None, "&self"))
argsWithoutThis.insert(0, Argument(None, "&self"))
setupCall = ("let s = CallSetup::new(self, aExceptionHandling);\n"
"if s.get_context().is_null() {\n"
" return Err(JSFailed);\n"
"}\n")
bodyWithThis = string.Template(
setupCall +
"let mut thisObjJS = RootedObject::new(s.get_context(), ptr::null_mut());\n"
"wrap_call_this_object(s.get_context(), thisObj, thisObjJS.handle_mut());\n"
"if thisObjJS.ptr.is_null() {\n"
" return Err(JSFailed);\n"
"}\n"
"return ${methodName}(${callArgs});").substitute({
"callArgs": ", ".join(argnamesWithThis),
"methodName": 'self.' + method.name,
})
bodyWithoutThis = string.Template(
setupCall +
"let thisObjJS = RootedObject::new(s.get_context(), ptr::null_mut());"
"return ${methodName}(${callArgs});").substitute({
"callArgs": ", ".join(argnamesWithoutThis),
"methodName": 'self.' + method.name,
})
return [ClassMethod(method.name + '_', method.returnType, args,
bodyInHeader=True,
templateArgs=["T: Reflectable"],
body=bodyWithThis,
visibility='pub'),
ClassMethod(method.name + '__', method.returnType, argsWithoutThis,
bodyInHeader=True,
body=bodyWithoutThis,
visibility='pub'),
method]
def deps(self):
return self._deps
# We're always fallible
def callbackGetterName(attr, descriptor):
return "Get" + MakeNativeName(
descriptor.binaryNameFor(attr.identifier.name))
def callbackSetterName(attr, descriptor):
return "Set" + MakeNativeName(
descriptor.binaryNameFor(attr.identifier.name))
class CGCallbackFunction(CGCallback):
def __init__(self, callback, descriptorProvider):
CGCallback.__init__(self, callback, descriptorProvider,
"CallbackFunction",
methods=[CallCallback(callback, descriptorProvider)])
def getConstructors(self):
return CGCallback.getConstructors(self)
class CGCallbackFunctionImpl(CGGeneric):
def __init__(self, callback):
impl = string.Template("""\
impl CallbackContainer for ${type} {
fn new(callback: *mut JSObject) -> Rc<${type}> {
${type}::new(callback)
}
fn callback(&self) -> *mut JSObject {
self.parent.callback()
}
}
impl ToJSValConvertible for ${type} {
fn to_jsval(&self, cx: *mut JSContext, rval: MutableHandleValue) {
self.callback().to_jsval(cx, rval);
}
}\
""").substitute({"type": callback.identifier.name})
CGGeneric.__init__(self, impl)
class CGCallbackInterface(CGCallback):
def __init__(self, descriptor):
iface = descriptor.interface
attrs = [m for m in iface.members if m.isAttr() and not m.isStatic()]
getters = [CallbackGetter(a, descriptor) for a in attrs]
setters = [CallbackSetter(a, descriptor) for a in attrs
if not a.readonly]
methods = [m for m in iface.members
if m.isMethod() and not m.isStatic() and not m.isIdentifierLess()]
methods = [CallbackOperation(m, sig, descriptor) for m in methods
for sig in m.signatures()]
assert not iface.isJSImplemented() or not iface.ctor()
CGCallback.__init__(self, iface, descriptor, "CallbackInterface",
methods, getters=getters, setters=setters)
class FakeMember():
def __init__(self):
self.treatNullAs = "Default"
def isStatic(self):
return False
def isAttr(self):
return False
def isMethod(self):
return False
def getExtendedAttribute(self, name):
return None
class CallbackMember(CGNativeMember):
def __init__(self, sig, name, descriptorProvider, needThisHandling):
"""
needThisHandling is True if we need to be able to accept a specified
thisObj, False otherwise.
"""
self.retvalType = sig[0]
self.originalSig = sig
args = sig[1]
self.argCount = len(args)
if self.argCount > 0:
# Check for variadic arguments
lastArg = args[self.argCount - 1]
if lastArg.variadic:
self.argCountStr = (
"(%d - 1) + %s.len()" % (self.argCount,
lastArg.identifier.name))
else:
self.argCountStr = "%d" % self.argCount
self.needThisHandling = needThisHandling
# If needThisHandling, we generate ourselves as private and the caller
# will handle generating public versions that handle the "this" stuff.
visibility = "priv" if needThisHandling else "pub"
# We don't care, for callback codegen, whether our original member was
# a method or attribute or whatnot. Just always pass FakeMember()
# here.
CGNativeMember.__init__(self, descriptorProvider, FakeMember(),
name, (self.retvalType, args),
extendedAttrs={},
passJSBitsAsNeeded=False,
visibility=visibility)
# We have to do all the generation of our body now, because
# the caller relies on us throwing if we can't manage it.
self.exceptionCode = "return Err(JSFailed);"
self.body = self.getImpl()
def getImpl(self):
replacements = {
"declRval": self.getRvalDecl(),
"returnResult": self.getResultConversion(),
"convertArgs": self.getArgConversions(),
"doCall": self.getCall(),
"setupCall": self.getCallSetup(),
}
if self.argCount > 0:
replacements["argCount"] = self.argCountStr
replacements["argvDecl"] = string.Template(
"let mut argv = vec![UndefinedValue(); ${argCount}];\n"
).substitute(replacements)
else:
# Avoid weird 0-sized arrays
replacements["argvDecl"] = ""
# Newlines and semicolons are in the values
pre = string.Template(
"${setupCall}"
"${declRval}"
"${argvDecl}").substitute(replacements)
body = string.Template(
"${convertArgs}"
"${doCall}"
"${returnResult}").substitute(replacements)
return CGList([
CGGeneric(pre),
CGGeneric(body),
], "\n").define()
def getResultConversion(self):
replacements = {
"val": "rval.handle()",
}
info = getJSToNativeConversionInfo(
self.retvalType,
self.descriptorProvider,
exceptionCode=self.exceptionCode,
isCallbackReturnValue="Callback",
# XXXbz we should try to do better here
sourceDescription="return value")
template = info.template
declType = info.declType
needsRooting = info.needsRooting
convertType = instantiateJSToNativeConversionTemplate(
template, replacements, declType, "rvalDecl", needsRooting)
if self.retvalType is None or self.retvalType.isVoid():
retval = "()"
elif self.retvalType.isAny():
retval = "rvalDecl.get()"
else:
retval = "rvalDecl"
return "%s\nOk(%s)\n" % (convertType.define(), retval)
def getArgConversions(self):
# Just reget the arglist from self.originalSig, because our superclasses
# just have way to many members they like to clobber, so I can't find a
# safe member name to store it in.
argConversions = [self.getArgConversion(i, arg) for (i, arg)
in enumerate(self.originalSig[1])]
# Do them back to front, so our argc modifications will work
# correctly, because we examine trailing arguments first.
argConversions.reverse()
argConversions = [CGGeneric(c) for c in argConversions]
if self.argCount > 0:
argConversions.insert(0, self.getArgcDecl())
# And slap them together.
return CGList(argConversions, "\n\n").define() + "\n\n"
def getArgConversion(self, i, arg):
argval = arg.identifier.name
if arg.variadic:
argval = argval + "[idx].get()"
jsvalIndex = "%d + idx" % i
else:
jsvalIndex = "%d" % i
if arg.optional and not arg.defaultValue:
argval += ".clone().unwrap()"
conversion = wrapForType(
"argv_root.handle_mut()", result=argval,
successCode="argv[%s] = argv_root.ptr;" % jsvalIndex,
pre="let mut argv_root = RootedValue::new(cx, UndefinedValue());")
if arg.variadic:
conversion = string.Template(
"for idx in 0..${arg}.len() {\n" +
CGIndenter(CGGeneric(conversion)).define() + "\n"
"}"
).substitute({"arg": arg.identifier.name})
elif arg.optional and not arg.defaultValue:
conversion = (
CGIfWrapper(CGGeneric(conversion),
"%s.is_some()" % arg.identifier.name).define() +
" else if (argc == %d) {\n"
" // This is our current trailing argument; reduce argc\n"
" argc -= 1;\n"
"} else {\n"
" argv[%d] = UndefinedValue();\n"
"}" % (i + 1, i))
return conversion
def getArgs(self, returnType, argList):
args = CGNativeMember.getArgs(self, returnType, argList)
if not self.needThisHandling:
# Since we don't need this handling, we're the actual method that
# will be called, so we need an aRethrowExceptions argument.
args.append(Argument("ExceptionHandling", "aExceptionHandling",
"ReportExceptions"))
return args
# We want to allow the caller to pass in a "this" object, as
# well as a JSContext.
return [Argument("*mut JSContext", "cx"),
Argument("HandleObject", "aThisObj")] + args
def getCallSetup(self):
if self.needThisHandling:
# It's been done for us already
return ""
return (
"CallSetup s(CallbackPreserveColor(), aRv, aExceptionHandling);\n"
"JSContext* cx = s.get_context();\n"
"if (!cx) {\n"
" return Err(JSFailed);\n"
"}\n")
def getArgcDecl(self):
return CGGeneric("let mut argc = %s;" % self.argCountStr)
@staticmethod
def ensureASCIIName(idlObject):
type = "attribute" if idlObject.isAttr() else "operation"
if re.match("[^\x20-\x7E]", idlObject.identifier.name):
raise SyntaxError('Callback %s name "%s" contains non-ASCII '
"characters. We can't handle that. %s" %
(type, idlObject.identifier.name,
idlObject.location))
if re.match('"', idlObject.identifier.name):
raise SyntaxError("Callback %s name '%s' contains "
"double-quote character. We can't handle "
"that. %s" %
(type, idlObject.identifier.name,
idlObject.location))
class CallbackMethod(CallbackMember):
def __init__(self, sig, name, descriptorProvider, needThisHandling):
CallbackMember.__init__(self, sig, name, descriptorProvider,
needThisHandling)
def getRvalDecl(self):
return "let mut rval = RootedValue::new(cx, UndefinedValue());\n"
def getCall(self):
replacements = {
"thisObj": self.getThisObj(),
"getCallable": self.getCallableDecl()
}
if self.argCount > 0:
replacements["argv"] = "argv.as_ptr()"
replacements["argc"] = "argc"
else:
replacements["argv"] = "ptr::null_mut()"
replacements["argc"] = "0"
return string.Template(
"${getCallable}"
"let ok = unsafe {\n"
" let rootedThis = RootedObject::new(cx, ${thisObj});\n"
" JS_CallFunctionValue(\n"
" cx, rootedThis.handle(), callable.handle(),\n"
" &HandleValueArray {\n"
" length_: ${argc} as ::libc::size_t,\n"
" elements_: ${argv}\n"
" }, rval.handle_mut())\n"
"};\n"
"if ok == 0 {\n"
" return Err(JSFailed);\n"
"}\n").substitute(replacements)
class CallCallback(CallbackMethod):
def __init__(self, callback, descriptorProvider):
CallbackMethod.__init__(self, callback.signatures()[0], "Call",
descriptorProvider, needThisHandling=True)
def getThisObj(self):
return "aThisObj.get()"
def getCallableDecl(self):
return "let callable = RootedValue::new(cx, ObjectValue(unsafe {&*self.parent.callback()}));\n"
class CallbackOperationBase(CallbackMethod):
"""
Common class for implementing various callback operations.
"""
def __init__(self, signature, jsName, nativeName, descriptor, singleOperation):
self.singleOperation = singleOperation
self.methodName = jsName
CallbackMethod.__init__(self, signature, nativeName, descriptor, singleOperation)
def getThisObj(self):
if not self.singleOperation:
return "self.parent.callback()"
# This relies on getCallableDecl declaring a boolean
# isCallable in the case when we're a single-operation
# interface.
return "if isCallable { aThisObj.get() } else { self.parent.callback() }"
def getCallableDecl(self):
replacements = {
"methodName": self.methodName
}
getCallableFromProp = string.Template(
'RootedValue::new(cx, try!(self.parent.get_callable_property(cx, "${methodName}")))'
).substitute(replacements)
if not self.singleOperation:
return 'JS::Rooted<JS::Value> callable(cx);\n' + getCallableFromProp
return (
'let isCallable = unsafe { IsCallable(self.parent.callback()) != 0 };\n'
'let callable =\n' +
CGIndenter(
CGIfElseWrapper('isCallable',
CGGeneric('unsafe { RootedValue::new(cx, ObjectValue(&*self.parent.callback())) }'),
CGGeneric(getCallableFromProp))).define() + ';\n')
class CallbackOperation(CallbackOperationBase):
"""
Codegen actual WebIDL operations on callback interfaces.
"""
def __init__(self, method, signature, descriptor):
self.ensureASCIIName(method)
jsName = method.identifier.name
CallbackOperationBase.__init__(self, signature,
jsName,
MakeNativeName(descriptor.binaryNameFor(jsName)),
descriptor, descriptor.interface.isSingleOperationInterface())
class CallbackGetter(CallbackMember):
def __init__(self, attr, descriptor):
self.ensureASCIIName(attr)
self.attrName = attr.identifier.name
CallbackMember.__init__(self,
(attr.type, []),
callbackGetterName(attr),
descriptor,
needThisHandling=False)
def getRvalDecl(self):
return "JS::Rooted<JS::Value> rval(cx, JS::UndefinedValue());\n"
def getCall(self):
replacements = {
"attrName": self.attrName
}
return string.Template(
'if (!JS_GetProperty(cx, mCallback, "${attrName}", &rval)) {\n'
' return Err(JSFailed);\n'
'}\n').substitute(replacements)
class CallbackSetter(CallbackMember):
def __init__(self, attr, descriptor):
self.ensureASCIIName(attr)
self.attrName = attr.identifier.name
CallbackMember.__init__(self,
(BuiltinTypes[IDLBuiltinType.Types.void],
[FakeArgument(attr.type, attr)]),
callbackSetterName(attr),
descriptor,
needThisHandling=False)
def getRvalDecl(self):
# We don't need an rval
return ""
def getCall(self):
replacements = {
"attrName": self.attrName,
"argv": "argv.handleAt(0)",
}
return string.Template(
'MOZ_ASSERT(argv.length() == 1);\n'
'if (!JS_SetProperty(cx, mCallback, "${attrName}", ${argv})) {\n'
' return Err(JSFailed);\n'
'}\n').substitute(replacements)
def getArgcDecl(self):
return None
class GlobalGenRoots():
"""
Roots for global codegen.
To generate code, call the method associated with the target, and then
call the appropriate define/declare method.
"""
@staticmethod
def PrototypeList(config):
# Prototype ID enum.
protos = [d.name for d in config.getDescriptors(isCallback=False)]
proxies = [d.name for d in config.getDescriptors(proxy=True)]
return CGList([
CGGeneric(AUTOGENERATED_WARNING_COMMENT),
CGGeneric("pub const MAX_PROTO_CHAIN_LENGTH: usize = %d;\n\n" % config.maxProtoChainLength),
CGNonNamespacedEnum('ID', protos, [0], deriving="PartialEq, Copy, Clone", repr="u16"),
CGWrapper(CGIndenter(CGList([CGGeneric('"' + name + '"') for name in protos],
",\n"),
indentLevel=4),
pre="static INTERFACES: [&'static str; %d] = [\n" % len(protos),
post="\n];\n\n"),
CGGeneric("pub fn proto_id_to_name(proto_id: u16) -> &'static str {\n"
" debug_assert!(proto_id < ID::Count as u16);\n"
" INTERFACES[proto_id as usize]\n"
"}\n\n"),
CGNonNamespacedEnum('Proxies', proxies, [0], deriving="PartialEq, Copy, Clone"),
])
@staticmethod
def RegisterBindings(config):
# TODO - Generate the methods we want
code = CGList([
CGRegisterProtos(config),
CGRegisterProxyHandlers(config),
], "\n")
return CGImports(code, [], [], [
'dom::bindings::codegen',
'dom::bindings::codegen::PrototypeList::Proxies',
'js::jsapi::JSContext',
'js::jsapi::HandleObject',
'libc',
], ignored_warnings=[])
@staticmethod
def InterfaceTypes(config):
descriptors = [d.name for d in config.getDescriptors(register=True, isCallback=False)]
curr = CGList([CGGeneric("pub use dom::%s::%s;\n" % (name.lower(), name)) for name in descriptors])
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
return curr
@staticmethod
def Bindings(config):
descriptors = (set(d.name + "Binding" for d in config.getDescriptors(register=True)) |
set(d.module() for d in config.callbacks) |
set(d.module() for d in config.getDictionaries()))
curr = CGList([CGGeneric("pub mod %s;\n" % name) for name in sorted(descriptors)])
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
return curr
@staticmethod
def InheritTypes(config):
descriptors = config.getDescriptors(register=True, isCallback=False)
allprotos = [CGGeneric("use dom::types::*;\n"),
CGGeneric("use dom::bindings::js::{JS, LayoutJS, Root};\n"),
CGGeneric("use dom::bindings::trace::JSTraceable;\n"),
CGGeneric("use dom::bindings::utils::Reflectable;\n"),
CGGeneric("use js::jsapi::JSTracer;\n\n"),
CGGeneric("use std::mem;\n\n")]
for descriptor in descriptors:
name = descriptor.name
protos = [CGGeneric("""\
/// Types which are derived from `%(name)s` and can be freely converted
/// to `%(name)s`
pub trait %(name)sBase : Sized {}\n""" % {'name': name})]
for proto in descriptor.prototypeChain:
protos += [CGGeneric('impl %s for %s {}\n' % (proto + 'Base',
descriptor.concreteType))]
derived = [CGGeneric("""\
/// Types which `%(name)s` derives from
pub trait %(name)sDerived : Sized { fn %(method)s(&self) -> bool; }\n""" %
{'name': name, 'method': 'is_' + name.lower()})]
for protoName in descriptor.prototypeChain[1:-1]:
protoDescriptor = config.getDescriptor(protoName)
delegate = string.Template("""\
impl ${selfName} for ${baseName} {
#[inline]
fn ${fname}(&self) -> bool {
let base: &${parentName} = ${parentName}Cast::from_ref(self);
base.${fname}()
}
}
""").substitute({'fname': 'is_' + name.lower(),
'selfName': name + 'Derived',
'baseName': protoDescriptor.concreteType,
'parentName': protoDescriptor.prototypeChain[-2]})
derived += [CGGeneric(delegate)]
derived += [CGGeneric('\n')]
cast = [CGGeneric(string.Template("""\
pub struct ${name}Cast;
impl ${name}Cast {
#[inline]
/// Downcast an instance of a base class of `${name}` to an instance of
/// `${name}`, if it internally is an instance of `${name}`
pub fn to_ref<'a, T: ${toBound}+Reflectable>(base: &'a T) -> Option<&'a ${name}> {
match base.${checkFn}() {
true => Some(unsafe { mem::transmute(base) }),
false => None
}
}
#[inline]
#[allow(unrooted_must_root)]
pub fn to_layout_js<T: ${toBound}+Reflectable>(base: &LayoutJS<T>) -> Option<LayoutJS<${name}>> {
unsafe {
match (*base.unsafe_get()).${checkFn}() {
true => Some(mem::transmute_copy(base)),
false => None
}
}
}
#[inline]
pub fn to_root<T: ${toBound}+Reflectable>(base: Root<T>) -> Option<Root<${name}>> {
match base.r().${checkFn}() {
true => Some(unsafe { mem::transmute(base) }),
false => None
}
}
#[inline]
/// Upcast an instance of a derived class of `${name}` to `${name}`
pub fn from_ref<'a, T: ${fromBound}+Reflectable>(derived: &'a T) -> &'a ${name} {
unsafe { mem::transmute(derived) }
}
#[inline]
#[allow(unrooted_must_root)]
pub fn from_layout_js<T: ${fromBound}+Reflectable>(derived: &LayoutJS<T>) -> LayoutJS<${name}> {
unsafe { mem::transmute_copy(derived) }
}
#[inline]
pub fn from_root<T: ${fromBound}+Reflectable>(derived: Root<T>) -> Root<${name}> {
unsafe { mem::transmute(derived) }
}
}
""").substitute({'checkFn': 'is_' + name.lower(),
'name': name,
'fromBound': name + 'Base',
'toBound': name + 'Derived'}))]
allprotos += protos + derived + cast
curr = CGList(allprotos)
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
return curr
@staticmethod
def UnionTypes(config):
curr = UnionTypes(config.getDescriptors(),
config.getDictionaries(),
config.getCallbacks(),
config)
# Add the auto-generated comment.
curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT)
# Done.
return curr | unknown | codeparrot/codeparrot-clean | ||
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from typing import Optional
from typing_extensions import Literal
from ..._models import BaseModel
__all__ = ["ToolChoiceMcp"]
class ToolChoiceMcp(BaseModel):
"""
Use this option to force the model to call a specific tool on a remote MCP server.
"""
server_label: str
"""The label of the MCP server to use."""
type: Literal["mcp"]
"""For MCP tools, the type is always `mcp`."""
name: Optional[str] = None
"""The name of the tool to call on the server.""" | python | github | https://github.com/openai/openai-python | src/openai/types/responses/tool_choice_mcp.py |
#!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = '''
---
module: efs
short_description: create and maintain EFS file systems
description:
- Module allows create, search and destroy Amazon EFS file systems
version_added: "2.2"
requirements: [ boto3 ]
author:
- "Ryan Sydnor (@ryansydnor)"
- "Artem Kazakov (@akazakov)"
options:
encrypt:
description:
- A boolean value that, if true, creates an encrypted file system. This can not be modfied after the file
system is created.
required: false
default: false
choices: ['yes', 'no']
version_added: 2.5
kms_key_id:
description:
- The id of the AWS KMS CMK that will be used to protect the encrypted file system. This parameter is only
required if you want to use a non-default CMK. If this parameter is not specified, the default CMK for
Amazon EFS is used. The key id can be Key ID, Key ID ARN, Key Alias or Key Alias ARN.
required: false
version_added: 2.5
purge_tags:
description:
- If yes, existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. If the I(tags) parameter
is not set then tags will not be modified.
required: false
default: yes
choices: [ 'yes', 'no' ]
version_added: 2.5
state:
description:
- Allows to create, search and destroy Amazon EFS file system
required: false
default: 'present'
choices: ['present', 'absent']
name:
description:
- Creation Token of Amazon EFS file system. Required for create. Either name or ID required for delete.
required: false
default: None
id:
description:
- ID of Amazon EFS. Either name or ID required for delete.
required: false
default: None
performance_mode:
description:
- File system's performance mode to use. Only takes effect during creation.
required: false
default: 'general_purpose'
choices: ['general_purpose', 'max_io']
tags:
description:
- "List of tags of Amazon EFS. Should be defined as dictionary
In case of 'present' state with list of tags and existing EFS (matched by 'name'), tags of EFS will be replaced with provided data."
required: false
default: None
targets:
description:
- "List of mounted targets. It should be a list of dictionaries, every dictionary should include next attributes:
- subnet_id - Mandatory. The ID of the subnet to add the mount target in.
- ip_address - Optional. A valid IPv4 address within the address range of the specified subnet.
- security_groups - Optional. List of security group IDs, of the form 'sg-xxxxxxxx'. These must be for the same VPC as subnet specified
This data may be modified for existing EFS using state 'present' and new list of mount targets."
required: false
default: None
wait:
description:
- "In case of 'present' state should wait for EFS 'available' life cycle state (of course, if current state not 'deleting' or 'deleted')
In case of 'absent' state should wait for EFS 'deleted' life cycle state"
required: false
default: "no"
choices: ["yes", "no"]
wait_timeout:
description:
- How long the module should wait (in seconds) for desired state before returning. Zero means wait as long as necessary.
required: false
default: 0
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# EFS provisioning
- efs:
state: present
name: myTestEFS
tags:
name: myTestNameTag
purpose: file-storage
targets:
- subnet_id: subnet-748c5d03
security_groups: [ "sg-1a2b3c4d" ]
# Modifying EFS data
- efs:
state: present
name: myTestEFS
tags:
name: myAnotherTestTag
targets:
- subnet_id: subnet-7654fdca
security_groups: [ "sg-4c5d6f7a" ]
# Deleting EFS
- efs:
state: absent
name: myTestEFS
'''
RETURN = '''
creation_time:
description: timestamp of creation date
returned: always
type: string
sample: "2015-11-16 07:30:57-05:00"
creation_token:
description: EFS creation token
returned: always
type: string
sample: "console-88609e04-9a0e-4a2e-912c-feaa99509961"
file_system_id:
description: ID of the file system
returned: always
type: string
sample: "fs-xxxxxxxx"
life_cycle_state:
description: state of the EFS file system
returned: always
type: string
sample: "creating, available, deleting, deleted"
mount_point:
description: url of file system
returned: always
type: string
sample: ".fs-xxxxxxxx.efs.us-west-2.amazonaws.com:/"
mount_targets:
description: list of mount targets
returned: always
type: list
sample:
[
{
"file_system_id": "fs-a7ad440e",
"ip_address": "172.31.17.173",
"life_cycle_state": "available",
"mount_target_id": "fsmt-d8907871",
"network_interface_id": "eni-6e387e26",
"owner_id": "740748460359",
"security_groups": [
"sg-a30b22c6"
],
"subnet_id": "subnet-e265c895"
},
...
]
name:
description: name of the file system
returned: always
type: string
sample: "my-efs"
number_of_mount_targets:
description: the number of targets mounted
returned: always
type: int
sample: 3
owner_id:
description: AWS account ID of EFS owner
returned: always
type: string
sample: "XXXXXXXXXXXX"
size_in_bytes:
description: size of the file system in bytes as of a timestamp
returned: always
type: dict
sample:
{
"timestamp": "2015-12-21 13:59:59-05:00",
"value": 12288
}
performance_mode:
description: performance mode of the file system
returned: always
type: string
sample: "generalPurpose"
tags:
description: tags on the efs instance
returned: always
type: dict
sample:
{
"name": "my-efs",
"key": "Value"
}
'''
from time import sleep
from time import time as timestamp
import traceback
try:
from botocore.exceptions import ClientError, BotoCoreError
except ImportError as e:
pass # Taken care of by ec2.HAS_BOTO3
from ansible.module_utils._text import to_native
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import (HAS_BOTO3, boto3_conn, camel_dict_to_snake_dict,
ec2_argument_spec, get_aws_connection_info, ansible_dict_to_boto3_tag_list,
compare_aws_tags, boto3_tag_list_to_ansible_dict)
def _index_by_key(key, items):
return dict((item[key], item) for item in items)
class EFSConnection(object):
DEFAULT_WAIT_TIMEOUT_SECONDS = 0
STATE_CREATING = 'creating'
STATE_AVAILABLE = 'available'
STATE_DELETING = 'deleting'
STATE_DELETED = 'deleted'
def __init__(self, module, region, **aws_connect_params):
self.connection = boto3_conn(module, conn_type='client',
resource='efs', region=region,
**aws_connect_params)
self.module = module
self.region = region
self.wait = module.params.get('wait')
self.wait_timeout = module.params.get('wait_timeout')
def get_file_systems(self, **kwargs):
"""
Returns generator of file systems including all attributes of FS
"""
items = iterate_all(
'FileSystems',
self.connection.describe_file_systems,
**kwargs
)
for item in items:
item['Name'] = item['CreationToken']
item['CreationTime'] = str(item['CreationTime'])
"""
Suffix of network path to be used as NFS device for mount. More detail here:
http://docs.aws.amazon.com/efs/latest/ug/gs-step-three-connect-to-ec2-instance.html
"""
item['MountPoint'] = '.%s.efs.%s.amazonaws.com:/' % (item['FileSystemId'], self.region)
if 'Timestamp' in item['SizeInBytes']:
item['SizeInBytes']['Timestamp'] = str(item['SizeInBytes']['Timestamp'])
if item['LifeCycleState'] == self.STATE_AVAILABLE:
item['Tags'] = self.get_tags(FileSystemId=item['FileSystemId'])
item['MountTargets'] = list(self.get_mount_targets(FileSystemId=item['FileSystemId']))
else:
item['Tags'] = {}
item['MountTargets'] = []
yield item
def get_tags(self, **kwargs):
"""
Returns tag list for selected instance of EFS
"""
tags = self.connection.describe_tags(**kwargs)['Tags']
return tags
def get_mount_targets(self, **kwargs):
"""
Returns mount targets for selected instance of EFS
"""
targets = iterate_all(
'MountTargets',
self.connection.describe_mount_targets,
**kwargs
)
for target in targets:
if target['LifeCycleState'] == self.STATE_AVAILABLE:
target['SecurityGroups'] = list(self.get_security_groups(
MountTargetId=target['MountTargetId']
))
else:
target['SecurityGroups'] = []
yield target
def get_security_groups(self, **kwargs):
"""
Returns security groups for selected instance of EFS
"""
return iterate_all(
'SecurityGroups',
self.connection.describe_mount_target_security_groups,
**kwargs
)
def get_file_system_id(self, name):
"""
Returns ID of instance by instance name
"""
info = first_or_default(iterate_all(
'FileSystems',
self.connection.describe_file_systems,
CreationToken=name
))
return info and info['FileSystemId'] or None
def get_file_system_state(self, name, file_system_id=None):
"""
Returns state of filesystem by EFS id/name
"""
info = first_or_default(iterate_all(
'FileSystems',
self.connection.describe_file_systems,
CreationToken=name,
FileSystemId=file_system_id
))
return info and info['LifeCycleState'] or self.STATE_DELETED
def get_mount_targets_in_state(self, file_system_id, states=None):
"""
Returns states of mount targets of selected EFS with selected state(s) (optional)
"""
targets = iterate_all(
'MountTargets',
self.connection.describe_mount_targets,
FileSystemId=file_system_id
)
if states:
if not isinstance(states, list):
states = [states]
targets = filter(lambda target: target['LifeCycleState'] in states, targets)
return list(targets)
def create_file_system(self, name, performance_mode, encrypt, kms_key_id):
"""
Creates new filesystem with selected name
"""
changed = False
state = self.get_file_system_state(name)
params = {}
params['CreationToken'] = name
params['PerformanceMode'] = performance_mode
if encrypt:
params['Encrypted'] = encrypt
if kms_key_id is not None:
params['KmsKeyId'] = kms_key_id
if state in [self.STATE_DELETING, self.STATE_DELETED]:
wait_for(
lambda: self.get_file_system_state(name),
self.STATE_DELETED
)
try:
self.connection.create_file_system(**params)
changed = True
except ClientError as e:
self.module.fail_json(msg="Unable to create file system: {0}".format(to_native(e)),
exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
except BotoCoreError as e:
self.module.fail_json(msg="Unable to create file system: {0}".format(to_native(e)),
exception=traceback.format_exc())
# we always wait for the state to be available when creating.
# if we try to take any actions on the file system before it's available
# we'll throw errors
wait_for(
lambda: self.get_file_system_state(name),
self.STATE_AVAILABLE,
self.wait_timeout
)
return changed
def converge_file_system(self, name, tags, purge_tags, targets):
"""
Change attributes (mount targets and tags) of filesystem by name
"""
result = False
fs_id = self.get_file_system_id(name)
if tags is not None:
tags_need_modify, tags_to_delete = compare_aws_tags(boto3_tag_list_to_ansible_dict(self.get_tags(FileSystemId=fs_id)), tags, purge_tags)
if tags_to_delete:
try:
self.connection.delete_tags(
FileSystemId=fs_id,
TagKeys=tags_to_delete
)
except ClientError as e:
self.module.fail_json(msg="Unable to delete tags: {0}".format(to_native(e)),
exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
except BotoCoreError as e:
self.module.fail_json(msg="Unable to delete tags: {0}".format(to_native(e)),
exception=traceback.format_exc())
result = True
if tags_need_modify:
try:
self.connection.create_tags(
FileSystemId=fs_id,
Tags=ansible_dict_to_boto3_tag_list(tags_need_modify)
)
except ClientError as e:
self.module.fail_json(msg="Unable to create tags: {0}".format(to_native(e)),
exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
except BotoCoreError as e:
self.module.fail_json(msg="Unable to create tags: {0}".format(to_native(e)),
exception=traceback.format_exc())
result = True
if targets is not None:
incomplete_states = [self.STATE_CREATING, self.STATE_DELETING]
wait_for(
lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)),
0
)
current_targets = _index_by_key('SubnetId', self.get_mount_targets(FileSystemId=fs_id))
targets = _index_by_key('SubnetId', targets)
targets_to_create, intersection, targets_to_delete = dict_diff(current_targets,
targets, True)
# To modify mount target it should be deleted and created again
changed = [sid for sid in intersection if not targets_equal(['SubnetId', 'IpAddress', 'NetworkInterfaceId'],
current_targets[sid], targets[sid])]
targets_to_delete = list(targets_to_delete) + changed
targets_to_create = list(targets_to_create) + changed
if targets_to_delete:
for sid in targets_to_delete:
self.connection.delete_mount_target(
MountTargetId=current_targets[sid]['MountTargetId']
)
wait_for(
lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)),
0
)
result = True
if targets_to_create:
for sid in targets_to_create:
self.connection.create_mount_target(
FileSystemId=fs_id,
**targets[sid]
)
wait_for(
lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)),
0,
self.wait_timeout
)
result = True
# If no security groups were passed into the module, then do not change it.
security_groups_to_update = [sid for sid in intersection if
'SecurityGroups' in targets[sid] and
current_targets[sid]['SecurityGroups'] != targets[sid]['SecurityGroups']]
if security_groups_to_update:
for sid in security_groups_to_update:
self.connection.modify_mount_target_security_groups(
MountTargetId=current_targets[sid]['MountTargetId'],
SecurityGroups=targets[sid].get('SecurityGroups', None)
)
result = True
return result
def delete_file_system(self, name, file_system_id=None):
"""
Removes EFS instance by id/name
"""
result = False
state = self.get_file_system_state(name, file_system_id)
if state in [self.STATE_CREATING, self.STATE_AVAILABLE]:
wait_for(
lambda: self.get_file_system_state(name),
self.STATE_AVAILABLE
)
if not file_system_id:
file_system_id = self.get_file_system_id(name)
self.delete_mount_targets(file_system_id)
self.connection.delete_file_system(FileSystemId=file_system_id)
result = True
if self.wait:
wait_for(
lambda: self.get_file_system_state(name),
self.STATE_DELETED,
self.wait_timeout
)
return result
def delete_mount_targets(self, file_system_id):
"""
Removes mount targets by EFS id
"""
wait_for(
lambda: len(self.get_mount_targets_in_state(file_system_id, self.STATE_CREATING)),
0
)
targets = self.get_mount_targets_in_state(file_system_id, self.STATE_AVAILABLE)
for target in targets:
self.connection.delete_mount_target(MountTargetId=target['MountTargetId'])
wait_for(
lambda: len(self.get_mount_targets_in_state(file_system_id, self.STATE_DELETING)),
0
)
return len(targets) > 0
def iterate_all(attr, map_method, **kwargs):
"""
Method creates iterator from result set
"""
args = dict((key, value) for (key, value) in kwargs.items() if value is not None)
wait = 1
while True:
try:
data = map_method(**args)
for elm in data[attr]:
yield elm
if 'NextMarker' in data:
args['Marker'] = data['Nextmarker']
continue
break
except ClientError as e:
if e.response['Error']['Code'] == "ThrottlingException" and wait < 600:
sleep(wait)
wait = wait * 2
continue
else:
raise
def targets_equal(keys, a, b):
"""
Method compare two mount targets by specified attributes
"""
for key in keys:
if key in b and a[key] != b[key]:
return False
return True
def dict_diff(dict1, dict2, by_key=False):
"""
Helper method to calculate difference of two dictionaries
"""
keys1 = set(dict1.keys() if by_key else dict1.items())
keys2 = set(dict2.keys() if by_key else dict2.items())
intersection = keys1 & keys2
return keys2 ^ intersection, intersection, keys1 ^ intersection
def first_or_default(items, default=None):
"""
Helper method to fetch first element of list (if exists)
"""
for item in items:
return item
return default
def wait_for(callback, value, timeout=EFSConnection.DEFAULT_WAIT_TIMEOUT_SECONDS):
"""
Helper method to wait for desired value returned by callback method
"""
wait_start = timestamp()
while True:
if callback() != value:
if timeout != 0 and (timestamp() - wait_start > timeout):
raise RuntimeError('Wait timeout exceeded (' + str(timeout) + ' sec)')
else:
sleep(5)
continue
break
def main():
"""
Module action handler
"""
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
encrypt=dict(required=False, type="bool", default=False),
state=dict(required=False, type='str', choices=["present", "absent"], default="present"),
kms_key_id=dict(required=False, type='str', default=None),
purge_tags=dict(default=True, type='bool'),
id=dict(required=False, type='str', default=None),
name=dict(required=False, type='str', default=None),
tags=dict(required=False, type="dict", default={}),
targets=dict(required=False, type="list", default=[]),
performance_mode=dict(required=False, type='str', choices=["general_purpose", "max_io"], default="general_purpose"),
wait=dict(required=False, type="bool", default=False),
wait_timeout=dict(required=False, type="int", default=0)
))
module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO3:
module.fail_json(msg='boto3 required for this module')
region, _, aws_connect_params = get_aws_connection_info(module, boto3=True)
connection = EFSConnection(module, region, **aws_connect_params)
name = module.params.get('name')
fs_id = module.params.get('id')
tags = module.params.get('tags')
target_translations = {
'ip_address': 'IpAddress',
'security_groups': 'SecurityGroups',
'subnet_id': 'SubnetId'
}
targets = [dict((target_translations[key], value) for (key, value) in x.items()) for x in module.params.get('targets')]
performance_mode_translations = {
'general_purpose': 'generalPurpose',
'max_io': 'maxIO'
}
encrypt = module.params.get('encrypt')
kms_key_id = module.params.get('kms_key_id')
performance_mode = performance_mode_translations[module.params.get('performance_mode')]
purge_tags = module.params.get('purge_tags')
changed = False
state = str(module.params.get('state')).lower()
if state == 'present':
if not name:
module.fail_json(msg='Name parameter is required for create')
changed = connection.create_file_system(name, performance_mode, encrypt, kms_key_id)
changed = connection.converge_file_system(name=name, tags=tags, purge_tags=purge_tags, targets=targets) or changed
result = first_or_default(connection.get_file_systems(CreationToken=name))
elif state == 'absent':
if not name and not fs_id:
module.fail_json(msg='Either name or id parameter is required for delete')
changed = connection.delete_file_system(name, fs_id)
result = None
if result:
result = camel_dict_to_snake_dict(result)
module.exit_json(changed=changed, efs=result)
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
#pragma once
#include <c10/core/Allocator.h>
#include <c10/core/AllocatorConfig.h>
#include <c10/core/Stream.h>
#include <c10/core/thread_pool.h>
#include <c10/util/flat_hash_map.h>
#include <c10/util/llvmMathExtras.h>
#include <iostream>
#include <optional>
#include <deque>
#include <vector>
#include <mutex>
#include <shared_mutex>
C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wunused-parameter")
namespace at {
using c10::CachingAllocator::Stat;
using c10::CachingAllocator::DurationStat;
/**
* HostBlock is typically a fundamental memory block used in pinned memory. It
* is likely related to Event and Stream of device runtime. It is probably a
* base struct or interface that can be inherited and extended by each backend.
*/
template <typename S>
struct HostBlock {
// constructor for search key
HostBlock(size_t size) : size_(size) {}
HostBlock(size_t size, void* ptr) : size_(size), ptr_(ptr) {}
std::mutex mutex_;
size_t size_{0}; // block size in bytes
void* ptr_{nullptr}; // memory address
bool allocated_{false}; // in-use flag
size_t event_count_{0}; // number of related events
ska::flat_hash_set<S> streams_; // streams on which the block was used
c10::MempoolId_t owning_pool_{0,0}; // never changes after construction, so we don't need a mutex to guard this
bool was_allocated_during_stream_capture_;
};
template <typename B>
struct alignas(hardware_destructive_interference_size) FreeBlockList {
std::mutex mutex_;
std::deque<B*> list_;
};
namespace {
// Max cached block sizes: (1 << MAX_SIZE_INDEX) bytes
// NOLINTNEXTLINE(misc-definitions-in-headers)
constexpr size_t MAX_SIZE_INDEX = 64;
}
// A large reserved pinned memory segment that is created in advance which is used
// to allocate small pinned memory requests to avoid calling into expensive APIs.
// We never free this memory and move up the pointer as we allocate new blocks
// and when blocks are freed, they are cached in the free lists.
struct PinnedReserveSegment {
PinnedReserveSegment(void *start, size_t size) : start_(start), size_(size),
current_ptr_(start_), initialized_(true) {}
PinnedReserveSegment() : start_(nullptr), size_(0), current_ptr_(nullptr), initialized_(false) {}
bool initialized() {
return initialized_;
}
void* allocate(size_t bytes) {
std::lock_guard<std::mutex> guard(mutex_);
// Round up the requested size to 4KB boundary for all including the small ones.
size_t rounded_bytes = (bytes + 4096 - 1) & ~(4096 - 1);
if (((uint8_t*)current_ptr_ + rounded_bytes) > ((uint8_t*)start_ + size_)) {
return nullptr;
}
void* ptr = current_ptr_;
current_ptr_ = (uint8_t*)current_ptr_ + rounded_bytes;
return ptr;
}
bool owns(void* ptr) {
return ptr >= start_ && ptr < (uint8_t*)start_ + size_;
}
std::mutex mutex_;
void* start_;
size_t size_;
void* current_ptr_;
bool initialized_;
};
// Struct containing memory allocator summary statistics for host.
struct TORCH_API HostStats {
// COUNT: total allocations (active)
Stat active_requests;
// SUM: bytes allocated/reserved by this memory allocator. (active)
Stat active_bytes;
// COUNT: total allocations (active + free)
Stat allocations;
// SUM: bytes allocated/reserved by this memory allocator. This accounts
// for both free and in-use blocks.
Stat allocated_bytes;
// SUM: time spent in cudaHostAlloc/cudaHostRegister in microseconds
DurationStat host_alloc_time;
// SUM: time spent in cudaHostFree/cudaHostUnregister in microseconds
DurationStat host_free_time;
// COUNT: number of times cudaHostAlloc/cudaHostRegister was called because
// the request could not be satisfied from existing free blocks.
int64_t num_host_alloc = 0; // This is derived from segment or timing
// COUNT: number of times cudaHostFree/cudaHostUnregister was called.
int64_t num_host_free = 0; // This is derived from segment or timing
// Count of cudaHostAlloc/cudaHostRegister per bucket
std::vector<int64_t> bucket_allocation = std::vector<int64_t>(MAX_SIZE_INDEX);
};
// Struct containing memory allocator summary statistics for host, as they
// are staged for reporting. This is a temporary struct that is used to
// avoid locking the allocator while collecting stats.
struct alignas(hardware_destructive_interference_size) HostStatsStaged {
std::mutex timing_mutex_;
// COUNT: total allocations (active + free)
// LOCK: access to this stat is protected by the allocator's blocks_mutex_
Stat allocations;
// SUM: bytes allocated/reserved by this memory allocator. This accounts
// for both free and in-use blocks.
Stat allocated_bytes;
// COUNT: number of allocations per bucket (active)
// LOCK: access to this stat is protected by the per bucket free_list_[index].mutex_
std::vector<Stat> active_bucket_stats = std::vector<Stat>(MAX_SIZE_INDEX);
// SUM: bytes of allocation per bucket (active)
// LOCK: access to this stat is protected by the per bucket free_list_[index].mutex_
std::vector<Stat> active_bytes_bucket_stats = std::vector<Stat>(MAX_SIZE_INDEX);
// COUNT: number of allocations per bucket (active + free)
// LOCK: access to this stat is protected by the per bucket free_list_[index].mutex_
std::vector<Stat> allocation_bucket_stats = std::vector<Stat>(MAX_SIZE_INDEX);
// SUM: bytes of allocation per bucket (active + free)
// LOCK: access to this stat is protected by the per bucket free_list_[index].mutex_
std::vector<Stat> allocated_bytes_bucket_stats = std::vector<Stat>(MAX_SIZE_INDEX);
// SUM: time spent in cudaHostAlloc/cudaHostRegister
// LOCK: access to this stat is protected by the timing_mutex_
DurationStat host_alloc_time;
// SUM: time spent in cudaHostFree/cudaHostUnregister
// LOCK: access to this stat is protected by the timing_mutex_
DurationStat host_free_time;
};
/**
* Note [HostAllocator design]
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* We have three key data structures - the free list which stores blocks that
* are not currently used, the block list which stores all blocks that have been
* allocated, and the event queue which stores runtime events and their
* corresponding blocks.
*
* Each of these are protected by a separate mutex. The key design principles
* are to 1) only hold each mutex for the minimal amount of time possible, 2)
* never do any possible expensive operations (such as CUDA runtime API calls)
* while holding the lock.
*
* There are four public methods: allocate, free, record_event and empty_cache.
* 1) In the allocate path, we first check to see if we can service our
* request from this free list, and otherwise we create a new block with
* allocate_host_memory.
* 2) In the free path, we insert events (if required) into the event queue,
* and if possible insert our block back into the free list. In allocate, we
* first eagerly query events until we find one that is not ready, and insert
* the corresponding block onto the free list if all the events recorded for a
* block are ready.
* 3) In the record_event path, we simply insert the given stream into the set
* of streams tracked by the specified block. This set of streams is then
* consumed in the free path.
* 4) In the empty_cache path, we flush any available blocks into the free
* list. Remove all element of free list, then remove them from block list and
* release the associated pinned memory allocation via free_block.
*
* We generalize the caching host allocator into two parts: interface and
* implementation. For any new backend looking to integrate with host allocator
* and reuse caching mechanism, these two parts are necessary to be specialized.
*
* For the implementation, we provide a CachingHostAllocatorImpl struct
* to abstract the caching mechanism. Any backend needs to provide a customized
* implementation by specializing its own public functions and the related
* runtime functions. Its template parameter S represents runtime Stream, E
* denotes runtime Event, B indicates the fundamental memory block.
*
* For the interface, we provide a CachingHostAllocatorInterface struct as an
* interface. Any backend needs to derive its own host allocator from this
* interface. Its template parameter T refers to an implementation that
* inherited from CachingHostAllocatorImpl.
*
* So this design can share the caching mechanism across each backend, and
* provide flexibility to each backend. A backend can choose to follow this
* implementation or reuse them by extending and overriding them as necessary.
* Taking CUDA as an example, it specializes runtime related functions to reuse
* the caching mechanism. Additionally, it extends the allocator's functionality
* by adding the allocWithCudaHostRegister function to support page-locking the
* memory range used by CUDA. Of course, you can also refer to
* XPUCachingHostAllocator, which is a host caching allocator supported on XPU
* backend, to implement a basic host caching allocator.
*
* Some of the invariants here are less strict than they could be - for example,
* we do not enforce that free(Block* block) => block->event_count == 0. This is
* for compatibility reasons, and we can explore enforcing these in subsequent
* versions.
*
* Note that this caching host allocator does not split larger allocations into
* smaller blocks, unlike the caching device allocator.
*
* In order to gather statistics about caching host allocator while minimally
* impacting performance, we use a HostStatsStaged struct to stage the stats
* before reporting them. This is done to avoid adding new locks to the allocator.
* Collecting stats is carefully done under existing locks, and then the staged
* stats are converted to the final stats when getStats is called. At that time
* we hold the same locks as empty_cache, to ensure the fidelity of the stats.
*/
// Generic per-pool structures for the host caching allocator. These are
// templated so they can reference the allocator's template parameters B and E.
template <typename S_, typename E_, typename B_>
struct HostBlockPool {
HostBlockPool() = default;
HostBlockPool(const HostBlockPool&) = delete;
HostBlockPool& operator=(const HostBlockPool&) = delete;
alignas(hardware_destructive_interference_size) std::mutex blocks_mutex_;
ska::flat_hash_set<B_*> blocks_; // all blocks in this pool
ska::flat_hash_map<void*, B_*> ptr_to_block_;
// Per-size free lists guarded by their own mutexes.
alignas(hardware_destructive_interference_size) std::vector<FreeBlockList<B_>> free_list_ =
std::vector<FreeBlockList<B_>>(MAX_SIZE_INDEX);
// Events pending for blocks in this pool.
alignas(hardware_destructive_interference_size) std::mutex events_mutex_;
std::deque<std::pair<E_, B_*>> events_;
};
// The HostBlockPool owned by one HostPrivatePool cannot share blocks
// with any other HostPrivatePool. This invariant is necessary to
// implement cuda graph capture correctly, which depends upon virtual
// addresses staying alive for the duration of a graph's existence.
template <typename S_, typename E_, typename B_>
struct HostPrivatePool {
explicit HostPrivatePool(c10::MempoolId_t id_) : id(id_) {}
HostPrivatePool(const HostPrivatePool&) = delete;
HostPrivatePool& operator=(const HostPrivatePool&) = delete;
c10::MempoolId_t id;
int use_count{1};
HostBlockPool<S_, E_, B_> blocks;
};
template <
typename S,
typename E,
typename B = HostBlock<S>>
struct CachingHostAllocatorImpl {
using BlockPool = HostBlockPool<S, E, B>;
using PrivatePool = HostPrivatePool<S, E, B>;
virtual ~CachingHostAllocatorImpl() {
if (active_) {
active_ = false;
getBackgroundThreadPool()->waitWorkComplete();
}
}
// return data_ptr and block pair.
virtual std::pair<void*, void*> allocate(size_t size) {
if (size == 0) {
return {nullptr, nullptr};
}
auto&& [mempool_id, pool] = get_allocation_pool_for_current_stream();
// If we are using background threads, we can process events in the
// background.
// In the case of a non-default pool, we never use the background
// thread. Since allocations happen only during stream capture
// time and there are no events to process anyway, speeding up
// event processing with a helper thread is not helpful.
if (!(pinned_use_background_threads() &&
mempool_id.first == 0 && mempool_id.second == 0)) {
process_events(pool);
}
// Round up the allocation to the nearest power of two to improve reuse.
// These power of two sizes are also used to index into the free list.
size_t roundSize = c10::llvm::PowerOf2Ceil(size);
// First, try to allocate from the free list of the chosen pool
auto* block = get_free_block(roundSize, pool);
if (block) {
block->was_allocated_during_stream_capture_ = current_stream_is_capturing_fast_path();
return {block->ptr_, reinterpret_cast<void*>(block)};
}
// Check in the recently freed blocks with pending events to see if we
// can reuse them. Call get_free_block again after processing events
if (pinned_use_background_threads()) {
// Launch the background thread and process events in a loop.
static bool background_thread_flag [[maybe_unused]] = [this] {
active_ = true;
getBackgroundThreadPool()->run([&]() {
while (active_) {
// Background thread conservatively processes default pool
// events only. Private pools never use a background
// thread because cuda stream capture does not benefit
// from asynchronous event processing.
process_events(default_pool_);
std::this_thread::sleep_for(std::chrono::microseconds(100));
}
});
return true;
}();
}
// Slow path: if we can't allocate from the cached free list, we need
// to create a new block.
void* ptr = nullptr;
allocate_host_memory(roundSize, &ptr);
// Then, create a new block.
block = new B(roundSize, ptr);
block->allocated_ = true;
block->owning_pool_ = mempool_id;
block->was_allocated_during_stream_capture_ = current_stream_is_capturing_fast_path();
add_allocated_block(block, pool);
return {block->ptr_, reinterpret_cast<void*>(block)};
}
virtual void free(void* ctx) {
if (!ctx) {
return;
}
// Note: we can assume that free is correctly paired with alloc, and thus we
// do not need to look up the ctx in blocks_.
auto* block = reinterpret_cast<B*>(ctx);
std::optional<std::vector<E>> events;
ska::flat_hash_set<S> streams;
bool allocated_during_capture = false;
{
std::lock_guard<std::mutex> g(block->mutex_);
block->allocated_ = false;
allocated_during_capture = block->was_allocated_during_stream_capture_;
if (block->streams_.empty()) {
TORCH_INTERNAL_ASSERT(block->event_count_ == 0);
} else {
events = std::vector<E>();
events->reserve(block->streams_.size());
block->event_count_ += block->streams_.size();
// Move out streams to avoid holding the mutex during event recording
streams = std::move(block->streams_);
block->streams_.clear();
}
}
// cudaEventRecord() does not work for indicating when a block can
// be reused while stream capture is happening, since no actual
// GPU work happens during stream capture.
if (!allocated_during_capture) {
// Event recording must be done outside the mutex to avoid potential
// deadlocks (e.g., when Python GIL is involved)
for (auto stream : streams) {
record_stream(events, stream);
}
}
if (!events.has_value()) {
auto& pool = pool_from_block(block);
auto index = size_index(block->size_);
std::lock_guard<std::mutex> g(pool.free_list_[index].mutex_);
pool.free_list_[index].list_.push_back(block);
} else if (allocated_during_capture) {
// pass: No events are ever recorded during stream capture.
// If the block was ever used, block->event_count_ will be above
// 0 and thus can never be recycled by
// process_events_for_specific_size. Thus, this block will never
// be returned again. "Leaking" memory like this is intentional
// to avoid subtle cuda graph problems described here:
// https://github.com/pytorch/pytorch/pull/161583#issuecomment-3229885771
// Otherwise, if the block was never used, block->event_count_
// will be 0 and thus process_events_for_specific_size can
// return this block.
} else {
// restore these events that record by used streams.
auto& pool = pool_from_block(block);
std::lock_guard<std::mutex> g(pool.events_mutex_);
for (auto&& event : *events) {
pool.events_.emplace_front(std::move(event), block);
}
}
}
virtual bool record_event(void* ptr, void* ctx, c10::Stream s) {
B *block = nullptr;
if (block_exists(ctx)) {
block = reinterpret_cast<B*>(ctx);
} else {
block = get_block_from_ptr(ptr);
}
if (block == nullptr) {
return false;
}
S stream = S(s);
std::lock_guard<std::mutex> gb(block->mutex_);
TORCH_INTERNAL_ASSERT(block->allocated_);
block->streams_.insert(stream);
return true;
}
void free_from_pool(BlockPool &pool) {
for (size_t i = 0; i < pool.free_list_.size(); ++i) {
std::lock(pool.free_list_[i].mutex_, pool.blocks_mutex_);
std::lock_guard<std::mutex> gf(pool.free_list_[i].mutex_, std::adopt_lock);
std::lock_guard<std::mutex> gb(pool.blocks_mutex_, std::adopt_lock);
std::vector<B*> blocks_to_remove(pool.free_list_[i].list_.begin(),
pool.free_list_[i].list_.end());
pool.free_list_[i].list_.clear();
for (auto* block : blocks_to_remove) {
pool.blocks_.erase(block);
pool.ptr_to_block_.erase(block->ptr_);
auto index = size_index(block->size_);
free_block(block);
stats_.allocations.decrease(1);
stats_.allocated_bytes.decrease(block->size_);
stats_.allocation_bucket_stats[index].decrease(1);
stats_.allocated_bytes_bucket_stats[index].decrease(block->size_);
delete block;
}
}
}
// TODO: Make this take a pool id like in CUDACachingAllocator
virtual void empty_cache() {
process_events(default_pool_);
free_from_pool(default_pool_);
{
std::unique_lock<std::shared_mutex> lg(instance_mutex_);
for (auto it = graph_pools_freeable_.begin(); it != graph_pools_freeable_.end();) {
process_events(it->second->blocks);
free_from_pool(it->second->blocks);
if (it->second->blocks.blocks_.empty()) {
auto erase_count = graph_pools_.erase(it->first);
TORCH_INTERNAL_ASSERT(erase_count == 1);
it = graph_pools_freeable_.erase(it);
} else {
++it;
}
}
}
}
inline size_t size_index(size_t size) {
return c10::llvm::Log2_64_Ceil(size);
}
virtual bool pinned_use_background_threads() {
return c10::CachingAllocator::AcceleratorAllocatorConfig::
pinned_use_background_threads();
}
virtual void copy_data(void* dest [[maybe_unused]], const void* src [[maybe_unused]], std::size_t count [[maybe_unused]]) const {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for copy_data");
}
HostStats getStats() {
HostStats stats;
// To keep getStats lightweight we do *not* flush any available blocks
// into the free_list. This may skew the stats a bit.
auto add_bucket_stats = [](Stat& accumulator, const Stat& other) {
accumulator.allocated += other.allocated;
accumulator.current += other.current;
accumulator.freed += other.freed;
// Since peaks are measured per bucket independently, we add them up
// to estimate the total peak. This is not strictly correct, but it is
// the best approximation we can get after the fact.
accumulator.peak += other.peak;
};
// Accurate reading of memory stats requires concurrently holding both the
// free list mutexes and the blocks mutex. Previously, this was only done in
// empty_cache function.
for (size_t i = 0; i < default_pool_.free_list_.size(); ++i) {
std::lock(
default_pool_.free_list_[i].mutex_, default_pool_.blocks_mutex_);
std::lock_guard<std::mutex> gf(
default_pool_.free_list_[i].mutex_, std::adopt_lock);
std::lock_guard<std::mutex> gb(
default_pool_.blocks_mutex_, std::adopt_lock);
// We collect the slow-path stats only once, since they are not collected
// per bucket (we pick index 0 arbitrarily). These are also all the host
// allocations, not taking into account caching and free lists.
if (i == 0) {
stats.allocations = stats_.allocations;
stats.allocated_bytes = stats_.allocated_bytes;
stats.num_host_alloc = stats.allocations.allocated;
stats.num_host_free = stats.allocations.freed;
}
// Bucket stats need to be merged with the slow-path stats. We do this in
// a best effort manner, since we can't really replay the cached events per bucket.
add_bucket_stats(stats.active_requests, stats_.active_bucket_stats[i]);
add_bucket_stats(stats.active_bytes, stats_.active_bytes_bucket_stats[i]);
stats.bucket_allocation[i] = stats_.allocation_bucket_stats[i].allocated;
}
// Get the timing stats
{
std::lock_guard<std::mutex> g(stats_.timing_mutex_);
stats.host_alloc_time = stats_.host_alloc_time;
stats.host_free_time = stats_.host_free_time;
}
return stats;
}
void resetAccumulatedStats() {
// Resetting accumulated memory stats requires concurrently holding both the
// free list mutexes and the blocks mutex. Previously, this was only done in
// empty_cache function.
for (size_t i = 0; i < default_pool_.free_list_.size(); ++i) {
std::lock(
default_pool_.free_list_[i].mutex_, default_pool_.blocks_mutex_);
std::lock_guard<std::mutex> gf(
default_pool_.free_list_[i].mutex_, std::adopt_lock);
std::lock_guard<std::mutex> gb(
default_pool_.blocks_mutex_, std::adopt_lock);
if (i == 0) {
stats_.allocations.reset_accumulated();
stats_.allocated_bytes.reset_accumulated();
}
stats_.active_bucket_stats[i].reset_accumulated();
stats_.active_bytes_bucket_stats[i].reset_accumulated();
stats_.allocation_bucket_stats[i].reset_accumulated();
stats_.allocated_bytes_bucket_stats[i].reset_accumulated();
}
// Also reset timing stats
{
std::lock_guard<std::mutex> g(stats_.timing_mutex_);
stats_.host_alloc_time.reset_accumulated();
stats_.host_free_time.reset_accumulated();
}
}
void resetPeakStats() {
// Resetting peak memory stats requires concurrently holding both the
// free list mutexes and the blocks mutex. Previously, this was only done in
// empty_cache function.
for (size_t i = 0; i < default_pool_.free_list_.size(); ++i) {
std::lock(
default_pool_.free_list_[i].mutex_, default_pool_.blocks_mutex_);
std::lock_guard<std::mutex> gf(
default_pool_.free_list_[i].mutex_, std::adopt_lock);
std::lock_guard<std::mutex> gb(
default_pool_.blocks_mutex_, std::adopt_lock);
if (i == 0) {
stats_.allocations.reset_peak();
stats_.allocated_bytes.reset_peak();
}
stats_.active_bucket_stats[i].reset_peak();
stats_.active_bytes_bucket_stats[i].reset_peak();
stats_.allocation_bucket_stats[i].reset_peak();
stats_.allocated_bytes_bucket_stats[i].reset_peak();
}
// Also reset timing stats
{
std::lock_guard<std::mutex> g(stats_.timing_mutex_);
stats_.host_alloc_time.reset_peak();
stats_.host_free_time.reset_peak();
}
}
private:
virtual void add_allocated_block(B* block, BlockPool& pool) {
std::lock_guard<std::mutex> g(pool.blocks_mutex_);
pool.blocks_.insert(block);
stats_.allocations.increase(1);
stats_.allocated_bytes.increase(block->size_);
pool.ptr_to_block_.insert({block->ptr_, block});
// Unfortunately, we have to, on the slow path, quickly
// lock the bucket to record the allocation. This should
// be a rare event once the cache is warmed up.
auto size = block->size_;
auto index = size_index(size);
{
std::lock_guard<std::mutex> g(pool.free_list_[index].mutex_);
stats_.allocation_bucket_stats[index].increase(1);
stats_.allocated_bytes_bucket_stats[index].increase(size);
stats_.active_bucket_stats[index].increase(1);
stats_.active_bytes_bucket_stats[index].increase(size);
}
}
virtual B* get_free_block(size_t size, BlockPool& pool) {
auto index = size_index(size);
std::lock_guard<std::mutex> g(pool.free_list_[index].mutex_);
if (!pool.free_list_[index].list_.empty()) {
B* block = pool.free_list_[index].list_.back();
pool.free_list_[index].list_.pop_back();
block->allocated_ = true;
stats_.active_bucket_stats[index].increase(1);
stats_.active_bytes_bucket_stats[index].increase(size);
return block;
}
return nullptr;
}
virtual void process_events(BlockPool& pool) {
// process all events in the given pool until the last unready event.
process_events_for_specific_size(-1, pool);
}
// If size is -1, process all events from backwards until the last unready
// event. Otherwise, process events for a specific size and on first ready block
// is found, add it to the free list and return.
virtual void process_events_for_specific_size(int64_t size, BlockPool& pool) {
size_t event_count = 0;
size_t max_events = 0;
{
std::lock_guard<std::mutex> g(pool.events_mutex_);
max_events = pool.events_.size();
}
while (true) {
// Avoid calling cudaEventDestroy while holding a mutex, so move
// intermediate events out of the lock into this object.
// process the last event
std::optional<std::pair<E, B*>> processed;
{
std::lock_guard<std::mutex> g(pool.events_mutex_);
if (!pool.events_.empty()) {
processed = std::move(pool.events_.back());
pool.events_.pop_back();
}
}
if (!processed) {
return;
}
if (size != -1) {
if (event_count++ > max_events) {
{
std::lock_guard<std::mutex> g(pool.events_mutex_);
pool.events_.push_front(std::move(*processed));
}
return;
}
if (size != (int64_t)processed->second->size_) {
// if we are processing a specific size, and the size of the block
// doesn't match, we can't use it.
{
std::lock_guard<std::mutex> g(pool.events_mutex_);
pool.events_.push_front(std::move(*processed));
}
continue;
}
}
// otherwise, query the event
{
// now, see if we can handle this element
auto& event = processed->first;
if (!query_event(event)) {
// push the event onto the back if it's not ready.
{
std::lock_guard<std::mutex> g(pool.events_mutex_);
if (size == -1) {
pool.events_.push_back(std::move(*processed));
return;
} else {
pool.events_.push_front(std::move(*processed));
continue;
}
}
}
}
// Process the events.
TORCH_INTERNAL_ASSERT(processed);
auto* block = processed->second;
bool available = false;
{
std::lock_guard<std::mutex> g(block->mutex_);
TORCH_INTERNAL_ASSERT(!block->allocated_);
block->event_count_--;
if (block->event_count_ == 0) {
available = true;
}
}
if (available) {
auto index = size_index(block->size_);
std::lock_guard<std::mutex> g(pool.free_list_[index].mutex_);
pool.free_list_[index].list_.push_back(block);
stats_.active_bucket_stats[index].decrease(1);
stats_.active_bytes_bucket_stats[index].decrease(size);
if (size != -1) {
return;
}
}
}
}
TaskThreadPool* getBackgroundThreadPool() {
static TaskThreadPool* pool = new TaskThreadPool(1);
return pool;
}
public:
void begin_allocate_to_pool(
c10::MempoolId_t pool_id,
std::function<bool(c10::Stream)> filter) {
std::unique_lock<std::shared_mutex> lg(instance_mutex_);
create_or_incref_pool_under_lock(pool_id);
for (auto it2 = captures_underway_.begin(); it2 != captures_underway_.end();
++it2) {
TORCH_CHECK(
it2->first != pool_id,
"beginAllocateToPool: already recording to mempool_id");
}
captures_underway_.emplace_back(pool_id, std::move(filter));
captures_underway_empty_.store(false, std::memory_order_relaxed);
}
void end_allocate_to_pool(c10::MempoolId_t pool_id) {
std::unique_lock<std::shared_mutex> lg(instance_mutex_);
for (auto it = captures_underway_.begin(); it != captures_underway_.end();
++it) {
if (it->first == pool_id) {
captures_underway_.erase(it);
captures_underway_empty_.store(captures_underway_.empty(), std::memory_order_relaxed);
return;
}
}
TORCH_CHECK(false, "endAllocatePool: not currently recording to mempool_id");
}
void create_or_incref_pool_under_lock(c10::MempoolId_t pool_id) {
auto it = graph_pools_.find(pool_id);
if (it == graph_pools_.end()) {
graph_pools_.emplace(pool_id, std::make_unique<PrivatePool>(pool_id));
} else {
TORCH_INTERNAL_ASSERT(it->second->use_count > 0);
it->second->use_count++;
}
}
void release_pool(c10::MempoolId_t pool_id) {
std::unique_lock<std::shared_mutex> lg(instance_mutex_);
auto* pp = graph_pools_.at(pool_id).get();
TORCH_INTERNAL_ASSERT(pp != nullptr);
auto uc = --(pp->use_count);
TORCH_INTERNAL_ASSERT(uc >= 0);
if (uc == 0) {
bool inserted = graph_pools_freeable_.insert({pool_id, pp}).second;
TORCH_INTERNAL_ASSERT(inserted);
}
}
private:
std::tuple<c10::MempoolId_t, BlockPool&> get_allocation_pool_for_current_stream() {
if (C10_LIKELY(captures_underway_empty_.load(std::memory_order_relaxed))) {
return {c10::MempoolId_t{0, 0}, default_pool_};
}
std::shared_lock<std::shared_mutex> lg(instance_mutex_);
S stream = get_current_stream();
for (auto& entry : captures_underway_) {
if (entry.second(stream)) {
auto it = graph_pools_.find(entry.first);
TORCH_INTERNAL_ASSERT(it != graph_pools_.end());
auto id = entry.first;
if (C10_UNLIKELY(!stream_is_capturing(stream))) {
TORCH_WARN_ONCE("CachingHostAllocator is allocating to private pool (",
id.first, ",", id.second,
") but the current stream is not capturing. Private "
"pools have been tested only during graph capture. "
"See https://github.com/pytorch/pytorch/pull/167507#discussion_r2561698011");
}
return {id, it->second->blocks};
}
}
return {c10::MempoolId_t{0, 0}, default_pool_};
}
// Helper: return the pool containing a block, based on its owning_pool_.
BlockPool& pool_from_block(B* block) {
auto id = block->owning_pool_;
if (id == c10::MempoolId_t{0, 0}) {
return default_pool_;
}
std::shared_lock<std::shared_mutex> lg(instance_mutex_);
auto it = graph_pools_.find(id);
TORCH_INTERNAL_ASSERT(it != graph_pools_.end());
return it->second->blocks;
}
B* get_block_from_ptr(void *ptr) {
std::shared_lock<std::shared_mutex> lk(instance_mutex_);
{
std::lock_guard<std::mutex> lk(default_pool_.blocks_mutex_);
if (default_pool_.ptr_to_block_.count(ptr)) {
return default_pool_.ptr_to_block_.at(ptr);
}
}
if (C10_LIKELY(graph_pools_.empty())) {
return nullptr;
} else {
for (auto &&[_, private_pool]: graph_pools_) {
BlockPool& pool = private_pool->blocks;
std::lock_guard<std::mutex> lk(pool.blocks_mutex_);
if (pool.ptr_to_block_.count(ptr)) {
return pool.ptr_to_block_.at(ptr);
}
}
return nullptr;
}
}
bool block_exists(void *block_) {
B *block = reinterpret_cast<B*>(block_);
std::shared_lock<std::shared_mutex> lk(instance_mutex_);
{
std::lock_guard<std::mutex> lk(default_pool_.blocks_mutex_);
if (default_pool_.blocks_.count(block)) {
return true;
}
}
if (C10_LIKELY(graph_pools_.empty())) {
return false;
} else {
for (auto &&[_, private_pool]: graph_pools_) {
BlockPool& pool = private_pool->blocks;
std::lock_guard<std::mutex> lk(pool.blocks_mutex_);
if (pool.blocks_.count(block)) {
return true;
}
}
return false;
}
}
protected:
// We want to keep the non stream capture case as fast as possible,
// since memory allocation is often in the critical path in non
// stream capture code. This function will skip the overhead of
// locking on instance_mutex_, two virtual function calls, and a
// call into the CUDA API in order to prevent overheads whenever
// possible.
bool current_stream_is_capturing_fast_path() const {
// Stream capture can allocate only to private pools. If there
// are no private pools for which capture is currently underway,
// then by modus tollens the current stream is not capturing.
if (C10_LIKELY(captures_underway_empty_.load(std::memory_order_relaxed))) {
return false;
}
return stream_is_capturing(get_current_stream());
}
private:
/* These following functions are runtime-related. */
// Allocate page-locked memory on the host.
virtual void allocate_host_memory(size_t size, void** ptr) {
TORCH_CHECK_NOT_IMPLEMENTED(
false, "Not implemented for allocate_host_memory");
}
// Free block and release the pointer contained in block.
virtual void free_block(B* block) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for free_block");
}
// Record an event on stream and store event into events.
virtual void record_stream(std::optional<std::vector<E>>& events, S stream) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for record_stream");
}
// Query event if it is completed.
virtual bool query_event(E& event) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for query_event");
}
virtual S get_current_stream() const {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for get_current_stream");
}
virtual bool stream_is_capturing(S s) const {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for stream_is_capturing");
}
// instance variables
// instance_mutex_ protects graphs_pools_, graph_pools_freeable_,
// and captures_underway_, as well as the use_count field of
// PrivatePools in graph_pools_ and graph_pools_freeable_. We use a
// shared mutex because we want to allow for multiple private pools
// to be allocated to concurrently. Does not protect default_pool_,
// which has its own mutex.
alignas(hardware_destructive_interference_size) mutable std::shared_mutex instance_mutex_;
// We manually maintain the invariant that captures_underway_empty_
// == captures_underway_.empty() outside of zones guarded by
// instance_mutex_. This trick allows for us to check whether any
// captures are currently underway without ever taking a lock on
// instance_mutex_ (which guards captures_underway_), which is much
// more expensive than a relaxed memory load on this atomic. Read
// more here:
// https://github.com/pytorch/pytorch/pull/167507#discussion_r2586418965
// It is important to use only "relaxed" loads and stores.
std::atomic<bool> captures_underway_empty_{true};
// Private pools for captures
ska::flat_hash_map<c10::MempoolId_t, std::unique_ptr<PrivatePool>, c10::MempoolIdHash>
graph_pools_;
ska::flat_hash_map<c10::MempoolId_t, PrivatePool*, c10::MempoolIdHash>
graph_pools_freeable_;
// Track active capture contexts requesting allocations to specific pools
std::vector<
std::pair<c10::MempoolId_t, std::function<bool(c10::Stream)>>> captures_underway_;
// corresponds to c10::MempoolId_t{0,0}
BlockPool default_pool_;
// Indicates whether the event-processing thread pool is active.
// Set to false in the destructor to signal background threads to stop.
std::atomic<bool> active_{false};
protected:
alignas(hardware_destructive_interference_size) HostStatsStaged stats_;
};
struct TORCH_API HostAllocator : public at::Allocator {
// Associates the pinned memory allocation with a stream to track
// dependencies. This ensures the memory won't be reused until the stream's
// operations complete
virtual bool record_event(void* ptr, void* ctx, c10::Stream stream) = 0;
// Frees all cached pinned memory and returns it to the system, clearing the
// allocator's internal cache
virtual void empty_cache() = 0;
// Returns comprehensive statistics about the allocator's memory usage,
// allocation patterns, and timing metrics
virtual HostStats get_stats() = 0;
// Resets the cumulative allocation statistics
virtual void reset_accumulated_stats() = 0;
// Resets the peak memory usage metrics
virtual void reset_peak_stats() = 0;
virtual void begin_allocate_to_pool(
c10::MempoolId_t pool_id,
std::function<bool(c10::Stream)> filter) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for begin_allocate_to_pool");
}
virtual void end_allocate_to_pool(c10::MempoolId_t pool_id) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for end_allocate_to_pool");
}
virtual void release_pool(c10::MempoolId_t pool_id) {
TORCH_CHECK_NOT_IMPLEMENTED(false, "Not implemented for release_pool");
}
};
template <typename T, c10::DeleterFnPtr deleteFunc>
struct CachingHostAllocatorInterface : public HostAllocator {
CachingHostAllocatorInterface() : impl_(std::make_unique<T>()) {}
at::DataPtr allocate(size_t size) override {
auto ptr_and_ctx = impl_->allocate(size);
return {
ptr_and_ctx.first,
ptr_and_ctx.second,
deleteFunc, // Use the template parameter deleter function
at::DeviceType::CPU};
}
void free(void* ctx) {
impl_->free(ctx);
}
bool record_event(void* ptr, void* ctx, c10::Stream stream) override {
return impl_->record_event(ptr, ctx, stream);
}
void empty_cache() override {
impl_->empty_cache();
}
void copy_data(void* dest, const void* src, std::size_t count)
const override {
impl_->copy_data(dest, src, count);
}
HostStats get_stats() override {
return impl_->getStats();
}
void reset_accumulated_stats() override {
impl_->resetAccumulatedStats();
}
void reset_peak_stats() override {
impl_->resetPeakStats();
}
void begin_allocate_to_pool(
c10::MempoolId_t pool_id,
std::function<bool(c10::Stream)> filter) override {
impl_->begin_allocate_to_pool(pool_id, std::move(filter));
}
void end_allocate_to_pool(c10::MempoolId_t pool_id) override {
impl_->end_allocate_to_pool(pool_id);
}
void release_pool(c10::MempoolId_t pool_id) override {
impl_->release_pool(pool_id);
}
std::unique_ptr<T> impl_;
};
#define DECLARE_HOST_ALLOCATOR(name, impl, deleter, instance) \
void deleter(void* ptr); \
struct name final \
: public at::CachingHostAllocatorInterface<impl, deleter> {}; \
static name instance; \
void deleter(void* ptr) { \
instance.free(ptr); \
}
/**
* Set the host allocator for DeviceType `device_type`. This allocator manages
* pinned memory on the host that can be accessed efficiently by the specified
* device type. Note that this function is not thread-safe.
*/
TORCH_API void setHostAllocator(
at::DeviceType device_type,
at::HostAllocator* allocator,
uint8_t priority = 0);
TORCH_API at::HostAllocator* getHostAllocator(at::DeviceType device_type);
template <DeviceType device_type>
struct HostAllocatorRegistry {
explicit HostAllocatorRegistry(HostAllocator* allocator) {
at::setHostAllocator(device_type, allocator);
}
};
#define REGISTER_HOST_ALLOCATOR(device_type, allocator) \
namespace { \
static at::HostAllocatorRegistry<device_type> \
g_host_allocator_registry_instance(allocator); \
}
} // namespace at
C10_DIAGNOSTIC_POP() | c | github | https://github.com/pytorch/pytorch | aten/src/ATen/core/CachingHostAllocator.h |
'''
Created on 25.10.2010
@author: michi
'''
from ems.converter.tag import Tag,AttributeException
class ForEach(Tag):
'''
classdocs
'''
def interpret(self,xmlDict,inputReader,outputWriter):
if xmlDict['attributes'].has_key('select'):
select = xmlDict['attributes']['select']
result = self._select(select, inputReader, outputWriter)
hasAssignAttribute = False
assignDataTo = []
if xmlDict['attributes'].has_key('as'):
assignString = xmlDict['attributes']['as']
if assignString:
hasAssignAttribute = True
if assignString.find(':'):
assignDataTo = assignString.split(':')
else:
assignDataTo = [assignString]
if hasattr(result, '__iter__'):
for data in result:
if hasAssignAttribute:
if len(assignDataTo) == 1:
self.converter.setVar(assignDataTo[0],data)
if len(assignDataTo) == 2:
self.converter.setVar(assignDataTo[0],data)
self.converter.setVar(assignDataTo[1],result[data])
for child in xmlDict['children']:
self.converter.interpretTag(child,inputReader,outputWriter)
else:
raise AttributeException("The tag for-each needs a select attribute")
def __str__(self):
return "for-each" | unknown | codeparrot/codeparrot-clean | ||
---
---
@import "jekyll-theme-primer";
@import "main"; | unknown | github | https://github.com/google/googletest | docs/assets/css/style.scss |
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package stackeval
import (
"context"
"fmt"
"time"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/zclconf/go-cty/cty"
"github.com/hashicorp/terraform/internal/instances"
"github.com/hashicorp/terraform/internal/lang"
"github.com/hashicorp/terraform/internal/promising"
"github.com/hashicorp/terraform/internal/providers"
"github.com/hashicorp/terraform/internal/stacks/stackaddrs"
"github.com/hashicorp/terraform/internal/stacks/stackplan"
"github.com/hashicorp/terraform/internal/stacks/stackruntime/internal/stackeval/stubs"
"github.com/hashicorp/terraform/internal/stacks/stackstate"
"github.com/hashicorp/terraform/internal/tfdiags"
"github.com/hashicorp/terraform/version"
)
// ProviderInstance represents one instance of a provider.
//
// A provider configuration block with the for_each argument appears as a
// single [ProviderConfig], then one [Provider] for each stack config instance
// the provider belongs to, and then one [ProviderInstance] for each
// element of for_each for each [Provider].
type ProviderInstance struct {
provider *Provider
addr stackaddrs.AbsProviderConfigInstance
repetition instances.RepetitionData
main *Main
providerArgs perEvalPhase[promising.Once[withDiagnostics[cty.Value]]]
client perEvalPhase[promising.Once[withDiagnostics[providers.Interface]]]
}
var _ ExpressionScope = (*ProviderInstance)(nil)
func newProviderInstance(provider *Provider, addr stackaddrs.AbsProviderConfigInstance, repetition instances.RepetitionData) *ProviderInstance {
return &ProviderInstance{
provider: provider,
addr: addr,
main: provider.main,
repetition: repetition,
}
}
func (p *ProviderInstance) RepetitionData() instances.RepetitionData {
return p.repetition
}
func (p *ProviderInstance) ProviderType() *ProviderType {
return p.main.ProviderType(p.addr.Item.ProviderConfig.Provider)
}
func (p *ProviderInstance) ProviderArgsDecoderSpec(ctx context.Context) (hcldec.Spec, error) {
return p.provider.config.ProviderArgsDecoderSpec(ctx)
}
// ProviderArgs returns an object value representing the provider configuration
// for this instance, or an unknown value of the correct type if the
// configuration is invalid. If a provider error occurs, it returns
// [cty.DynamicVal].
func (p *ProviderInstance) ProviderArgs(ctx context.Context, phase EvalPhase) cty.Value {
v, _ := p.CheckProviderArgs(ctx, phase)
return v
}
func (p *ProviderInstance) CheckProviderArgs(ctx context.Context, phase EvalPhase) (cty.Value, tfdiags.Diagnostics) {
return doOnceWithDiags(
ctx, p.tracingName(), p.providerArgs.For(phase),
func(ctx context.Context) (cty.Value, tfdiags.Diagnostics) {
var diags tfdiags.Diagnostics
providerType := p.ProviderType()
decl := p.provider.config.config
spec, err := p.ProviderArgsDecoderSpec(ctx)
if err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Failed to read provider schema",
Detail: fmt.Sprintf(
"Error while reading the schema for %q: %s.",
providerType.Addr(), err,
),
Subject: decl.DeclRange.ToHCL().Ptr(),
})
return cty.DynamicVal, diags
}
var configVal cty.Value
var moreDiags tfdiags.Diagnostics
configBody := decl.Config
if configBody == nil {
configBody = hcl.EmptyBody()
}
configVal, moreDiags = EvalBody(ctx, configBody, spec, phase, p)
diags = diags.Append(moreDiags)
if moreDiags.HasErrors() {
return cty.UnknownVal(hcldec.ImpliedType(spec)), diags
}
unconfClient, err := providerType.UnconfiguredClient()
if err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Failed to start provider plugin",
Detail: fmt.Sprintf(
"Error while instantiating %q: %s.",
providerType.Addr(), err,
),
Subject: decl.DeclRange.ToHCL().Ptr(),
})
return cty.DynamicVal, diags
}
// We unmark the config before making the RPC call, but will still
// return the original possibly-marked config if successful.
unmarkedConfigVal, _ := configVal.UnmarkDeep()
validateResp := unconfClient.ValidateProviderConfig(providers.ValidateProviderConfigRequest{
Config: unmarkedConfigVal,
})
diags = diags.Append(validateResp.Diagnostics)
if validateResp.Diagnostics.HasErrors() {
return cty.DynamicVal, diags
}
return configVal, diags
},
)
}
// Client returns a client object for the provider instance, already configured
// per the provider configuration arguments and ready to use.
//
// If the configured arguments are invalid then this might return a stub
// provider client that implements all methods either as silent no-ops or as
// returning error diagnostics, so callers can just treat the returned client
// as always valid.
//
// Callers must call Close on the returned client once they have finished using
// the client.
func (p *ProviderInstance) Client(ctx context.Context, phase EvalPhase) providers.Interface {
ret, _ := p.CheckClient(ctx, phase)
return ret
}
func (p *ProviderInstance) CheckClient(ctx context.Context, phase EvalPhase) (providers.Interface, tfdiags.Diagnostics) {
return doOnceWithDiags(
ctx, p.tracingName()+" plugin client", p.client.For(phase),
func(ctx context.Context) (providers.Interface, tfdiags.Diagnostics) {
var diags tfdiags.Diagnostics
if p.repetition.EachKey != cty.NilVal && !p.repetition.EachKey.IsKnown() {
// We should have triggered and returned a stub.UnknownProvider
// in this case, so there's a bug somewhere in Terraform if
// this happens.
panic("provider instance with unknown for_each key")
}
if p.repetition.CountIndex != cty.NilVal && !p.repetition.CountIndex.IsKnown() {
// Providers don't even support the count index argument, so
// something crazy is happening if we get here.
panic("provider instance with unknown count index")
}
providerType := p.ProviderType()
decl := p.provider.config.config
client, err := p.main.ProviderFactories().NewUnconfiguredClient(providerType.Addr())
if err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Failed to start provider plugin",
Detail: fmt.Sprintf(
"Could not create an instance of %s for %s: %s.",
providerType.Addr(), p.addr, err,
),
Subject: decl.DeclRange.ToHCL().Ptr(),
})
return stubs.ErroredProvider(), diags
}
// If the context we recieved gets cancelled then we want providers
// to try to cancel any operations they have in progress, so we'll
// watch for that in a separate goroutine. This extra context
// is here just so we can avoid leaking this goroutine if the
// parent doesn't get cancelled.
providerCtx, localCancel := context.WithCancel(ctx)
go func() {
<-providerCtx.Done()
if ctx.Err() == context.Canceled {
// Not all providers respond to this, but some will quickly
// abort operations currently in progress and return a
// cancellation error, thus allowing us to halt more quickly
// when interrupted.
client.Stop()
}
}()
// If this provider is implemented as a separate plugin then we
// must terminate its child process once evaluation is complete.
p.main.RegisterCleanup(func(ctx context.Context) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
localCancel() // make sure our cancel-monitoring goroutine terminates
err := client.Close()
if err != nil {
diags = diags.Append(&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Failed to terminate provider plugin",
Detail: fmt.Sprintf(
"Error closing the instance of %s for %s: %s.",
providerType.Addr(), p.addr, err,
),
Subject: decl.DeclRange.ToHCL().Ptr(),
})
}
return diags
})
// TODO: Some providers will malfunction if the caller doesn't
// fetch their schema at least once before use. That's not something
// the provider protocol promises but it's an implementation
// detail that a certain generation of providers relied on
// nonetheless. We'll probably need to check whether the provider
// supports the "I don't need you to fetch my schema" capability
// and, if not, do a redundant re-fetch of the schema in here
// somewhere. Refer to the corresponding behavior in the
// "terraform" package for non-Stacks usage and try to mimick
// what it does in as lightweight a way as possible.
// We unmark the config before making the RPC call, as marks cannot
// be serialized.
unmarkedArgs, _ := p.ProviderArgs(ctx, phase).UnmarkDeep()
if unmarkedArgs == cty.NilVal {
// Then we had an error previously, so we'll rely on that error
// being exposed elsewhere.
return stubs.ErroredProvider(), diags
}
resp := client.ConfigureProvider(providers.ConfigureProviderRequest{
TerraformVersion: version.SemVer.String(),
Config: unmarkedArgs,
ClientCapabilities: ClientCapabilities(),
})
diags = diags.Append(resp.Diagnostics)
if resp.Diagnostics.HasErrors() {
// If the provider didn't configure successfully then it won't
// meet the expectations of our callers and so we'll return a
// stub instead. (The real provider stays running until it
// gets cleaned up by the cleanup function above, despite being
// inaccessible to the caller.)
return stubs.ErroredProvider(), diags
}
return unconfigurableProvider{
Interface: client,
}, diags
},
)
}
// ResolveExpressionReference implements ExpressionScope for expressions other
// than the for_each argument inside a provider block, which get evaluated
// once per provider instance.
func (p *ProviderInstance) ResolveExpressionReference(ctx context.Context, ref stackaddrs.Reference) (Referenceable, tfdiags.Diagnostics) {
return p.provider.stack.resolveExpressionReference(ctx, ref, nil, p.repetition)
}
// ExternalFunctions implements ExpressionScope.
func (p *ProviderInstance) ExternalFunctions(ctx context.Context) (lang.ExternalFuncs, tfdiags.Diagnostics) {
return p.main.ProviderFunctions(ctx, p.provider.config.stack)
}
// PlanTimestamp implements ExpressionScope, providing the timestamp at which
// the current plan is being run.
func (p *ProviderInstance) PlanTimestamp() time.Time {
return p.main.PlanTimestamp()
}
func (p *ProviderInstance) checkValid(ctx context.Context, phase EvalPhase) tfdiags.Diagnostics {
var diags tfdiags.Diagnostics
_, moreDiags := p.CheckProviderArgs(ctx, phase)
diags = diags.Append(moreDiags)
// NOTE: CheckClient starts and configures the provider as a side-effect.
// If this is a plugin-based provider then the plugin process will stay
// running for the remainder of the specified evaluation phase.
_, moreDiags = p.CheckClient(ctx, phase)
diags = diags.Append(moreDiags)
return diags
}
// PlanChanges implements Plannable.
func (p *ProviderInstance) PlanChanges(ctx context.Context) ([]stackplan.PlannedChange, tfdiags.Diagnostics) {
return nil, p.checkValid(ctx, PlanPhase)
}
// CheckApply implements Applyable.
func (p *ProviderInstance) CheckApply(ctx context.Context) ([]stackstate.AppliedChange, tfdiags.Diagnostics) {
return nil, p.checkValid(ctx, ApplyPhase)
}
// tracingName implements Plannable.
func (p *ProviderInstance) tracingName() string {
return p.addr.String()
} | go | github | https://github.com/hashicorp/terraform | internal/stacks/stackruntime/internal/stackeval/provider_instance.go |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import gettext
import os
from datetime import datetime, timedelta
from importlib import import_module
from unittest import skipIf
from django import forms
from django.conf import settings
from django.contrib import admin
from django.contrib.admin import widgets
from django.contrib.admin.tests import AdminSeleniumWebDriverTestCase
from django.contrib.auth.models import User
from django.core.files.storage import default_storage
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.urlresolvers import reverse
from django.db.models import CharField, DateField
from django.test import SimpleTestCase, TestCase, override_settings
from django.utils import six, translation
from . import models
from .widgetadmin import site as widget_admin_site
try:
import pytz
except ImportError:
pytz = None
class TestDataMixin(object):
@classmethod
def setUpTestData(cls):
cls.u1 = User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime(2007, 5, 30, 13, 20, 10)
)
cls.u2 = User.objects.create(
pk=101, username='testser', first_name='Add', last_name='User', email='auser@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=False,
is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime(2007, 5, 30, 13, 20, 10)
)
models.Car.objects.create(id=1, owner=cls.u1, make='Volkswagon', model='Passat')
models.Car.objects.create(id=2, owner=cls.u2, make='BMW', model='M3')
class SeleniumDataMixin(object):
def setUp(self):
self.u1 = User.objects.create(
pk=100, username='super', first_name='Super', last_name='User', email='super@example.com',
password='sha1$995a3$6011485ea3834267d719b4c801409b8b1ddd0158', is_active=True, is_superuser=True,
is_staff=True, last_login=datetime(2007, 5, 30, 13, 20, 10),
date_joined=datetime(2007, 5, 30, 13, 20, 10)
)
class AdminFormfieldForDBFieldTests(SimpleTestCase):
"""
Tests for correct behavior of ModelAdmin.formfield_for_dbfield
"""
def assertFormfield(self, model, fieldname, widgetclass, **admin_overrides):
"""
Helper to call formfield_for_dbfield for a given model and field name
and verify that the returned formfield is appropriate.
"""
# Override any settings on the model admin
class MyModelAdmin(admin.ModelAdmin):
pass
for k in admin_overrides:
setattr(MyModelAdmin, k, admin_overrides[k])
# Construct the admin, and ask it for a formfield
ma = MyModelAdmin(model, admin.site)
ff = ma.formfield_for_dbfield(model._meta.get_field(fieldname), request=None)
# "unwrap" the widget wrapper, if needed
if isinstance(ff.widget, widgets.RelatedFieldWidgetWrapper):
widget = ff.widget.widget
else:
widget = ff.widget
# Check that we got a field of the right type
self.assertTrue(
isinstance(widget, widgetclass),
"Wrong widget for %s.%s: expected %s, got %s" % (
model.__class__.__name__,
fieldname,
widgetclass,
type(widget),
)
)
# Return the formfield so that other tests can continue
return ff
def test_DateField(self):
self.assertFormfield(models.Event, 'start_date', widgets.AdminDateWidget)
def test_DateTimeField(self):
self.assertFormfield(models.Member, 'birthdate', widgets.AdminSplitDateTime)
def test_TimeField(self):
self.assertFormfield(models.Event, 'start_time', widgets.AdminTimeWidget)
def test_TextField(self):
self.assertFormfield(models.Event, 'description', widgets.AdminTextareaWidget)
def test_URLField(self):
self.assertFormfield(models.Event, 'link', widgets.AdminURLFieldWidget)
def test_IntegerField(self):
self.assertFormfield(models.Event, 'min_age', widgets.AdminIntegerFieldWidget)
def test_CharField(self):
self.assertFormfield(models.Member, 'name', widgets.AdminTextInputWidget)
def test_EmailField(self):
self.assertFormfield(models.Member, 'email', widgets.AdminEmailInputWidget)
def test_FileField(self):
self.assertFormfield(models.Album, 'cover_art', widgets.AdminFileWidget)
def test_ForeignKey(self):
self.assertFormfield(models.Event, 'main_band', forms.Select)
def test_raw_id_ForeignKey(self):
self.assertFormfield(models.Event, 'main_band', widgets.ForeignKeyRawIdWidget,
raw_id_fields=['main_band'])
def test_radio_fields_ForeignKey(self):
ff = self.assertFormfield(models.Event, 'main_band', widgets.AdminRadioSelect,
radio_fields={'main_band': admin.VERTICAL})
self.assertEqual(ff.empty_label, None)
def test_many_to_many(self):
self.assertFormfield(models.Band, 'members', forms.SelectMultiple)
def test_raw_id_many_to_many(self):
self.assertFormfield(models.Band, 'members', widgets.ManyToManyRawIdWidget,
raw_id_fields=['members'])
def test_filtered_many_to_many(self):
self.assertFormfield(models.Band, 'members', widgets.FilteredSelectMultiple,
filter_vertical=['members'])
def test_formfield_overrides(self):
self.assertFormfield(models.Event, 'start_date', forms.TextInput,
formfield_overrides={DateField: {'widget': forms.TextInput}})
def test_formfield_overrides_widget_instances(self):
"""
Test that widget instances in formfield_overrides are not shared between
different fields. (#19423)
"""
class BandAdmin(admin.ModelAdmin):
formfield_overrides = {
CharField: {'widget': forms.TextInput(attrs={'size': '10'})}
}
ma = BandAdmin(models.Band, admin.site)
f1 = ma.formfield_for_dbfield(models.Band._meta.get_field('name'), request=None)
f2 = ma.formfield_for_dbfield(models.Band._meta.get_field('style'), request=None)
self.assertNotEqual(f1.widget, f2.widget)
self.assertEqual(f1.widget.attrs['maxlength'], '100')
self.assertEqual(f2.widget.attrs['maxlength'], '20')
self.assertEqual(f2.widget.attrs['size'], '10')
def test_field_with_choices(self):
self.assertFormfield(models.Member, 'gender', forms.Select)
def test_choices_with_radio_fields(self):
self.assertFormfield(models.Member, 'gender', widgets.AdminRadioSelect,
radio_fields={'gender': admin.VERTICAL})
def test_inheritance(self):
self.assertFormfield(models.Album, 'backside_art', widgets.AdminFileWidget)
def test_m2m_widgets(self):
"""m2m fields help text as it applies to admin app (#9321)."""
class AdvisorAdmin(admin.ModelAdmin):
filter_vertical = ['companies']
self.assertFormfield(models.Advisor, 'companies', widgets.FilteredSelectMultiple,
filter_vertical=['companies'])
ma = AdvisorAdmin(models.Advisor, admin.site)
f = ma.formfield_for_dbfield(models.Advisor._meta.get_field('companies'), request=None)
self.assertEqual(
six.text_type(f.help_text),
'Hold down "Control", or "Command" on a Mac, to select more than one.'
)
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminFormfieldForDBFieldWithRequestTests(TestDataMixin, TestCase):
def test_filter_choices_by_request_user(self):
"""
Ensure the user can only see their own cars in the foreign key dropdown.
"""
self.client.login(username="super", password="secret")
response = self.client.get(reverse('admin:admin_widgets_cartire_add'))
self.assertNotContains(response, "BMW M3")
self.assertContains(response, "Volkswagon Passat")
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminForeignKeyWidgetChangeList(TestDataMixin, TestCase):
def setUp(self):
self.client.login(username="super", password="secret")
def test_changelist_ForeignKey(self):
response = self.client.get(reverse('admin:admin_widgets_car_changelist'))
self.assertContains(response, '/auth/user/add/')
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminForeignKeyRawIdWidget(TestDataMixin, TestCase):
def setUp(self):
self.client.login(username="super", password="secret")
def test_nonexistent_target_id(self):
band = models.Band.objects.create(name='Bogey Blues')
pk = band.pk
band.delete()
post_data = {
"main_band": '%s' % pk,
}
# Try posting with a non-existent pk in a raw id field: this
# should result in an error message, not a server exception.
response = self.client.post(reverse('admin:admin_widgets_event_add'), post_data)
self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')
def test_invalid_target_id(self):
for test_str in ('Iñtërnâtiônàlizætiøn', "1234'", -1234):
# This should result in an error message, not a server exception.
response = self.client.post(reverse('admin:admin_widgets_event_add'),
{"main_band": test_str})
self.assertContains(response,
'Select a valid choice. That choice is not one of the available choices.')
def test_url_params_from_lookup_dict_any_iterable(self):
lookup1 = widgets.url_params_from_lookup_dict({'color__in': ('red', 'blue')})
lookup2 = widgets.url_params_from_lookup_dict({'color__in': ['red', 'blue']})
self.assertEqual(lookup1, {'color__in': 'red,blue'})
self.assertEqual(lookup1, lookup2)
def test_url_params_from_lookup_dict_callable(self):
def my_callable():
return 'works'
lookup1 = widgets.url_params_from_lookup_dict({'myfield': my_callable})
lookup2 = widgets.url_params_from_lookup_dict({'myfield': my_callable()})
self.assertEqual(lookup1, lookup2)
class FilteredSelectMultipleWidgetTest(SimpleTestCase):
def test_render(self):
# Backslash in verbose_name to ensure it is JavaScript escaped.
w = widgets.FilteredSelectMultiple('test\\', False)
self.assertHTMLEqual(
w.render('test', 'test'),
'<select multiple="multiple" name="test" class="selectfilter">\n</select>'
'<script type="text/javascript">addEvent(window, "load", function(e) '
'{SelectFilter.init("id_test", "test\\u005C", 0); });</script>\n'
)
def test_stacked_render(self):
# Backslash in verbose_name to ensure it is JavaScript escaped.
w = widgets.FilteredSelectMultiple('test\\', True)
self.assertHTMLEqual(
w.render('test', 'test'),
'<select multiple="multiple" name="test" class="selectfilterstacked">\n</select>'
'<script type="text/javascript">addEvent(window, "load", function(e) '
'{SelectFilter.init("id_test", "test\\u005C", 1); });</script>\n'
)
class AdminDateWidgetTest(SimpleTestCase):
def test_attrs(self):
"""
Ensure that user-supplied attrs are used.
Refs #12073.
"""
w = widgets.AdminDateWidget()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="2007-12-01" type="text" class="vDateField" name="test" size="10" />',
)
# pass attrs to widget
w = widgets.AdminDateWidget(attrs={'size': 20, 'class': 'myDateField'})
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="2007-12-01" type="text" class="myDateField" name="test" size="20" />',
)
class AdminTimeWidgetTest(SimpleTestCase):
def test_attrs(self):
"""
Ensure that user-supplied attrs are used.
Refs #12073.
"""
w = widgets.AdminTimeWidget()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="09:30:00" type="text" class="vTimeField" name="test" size="8" />',
)
# pass attrs to widget
w = widgets.AdminTimeWidget(attrs={'size': 20, 'class': 'myTimeField'})
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<input value="09:30:00" type="text" class="myTimeField" name="test" size="20" />',
)
class AdminSplitDateTimeWidgetTest(SimpleTestCase):
def test_render(self):
w = widgets.AdminSplitDateTime()
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<p class="datetime">'
'Date: <input value="2007-12-01" type="text" class="vDateField" '
'name="test_0" size="10" /><br />'
'Time: <input value="09:30:00" type="text" class="vTimeField" '
'name="test_1" size="8" /></p>'
)
def test_localization(self):
w = widgets.AdminSplitDateTime()
with self.settings(USE_L10N=True), translation.override('de-at'):
w.is_localized = True
self.assertHTMLEqual(
w.render('test', datetime(2007, 12, 1, 9, 30)),
'<p class="datetime">'
'Datum: <input value="01.12.2007" type="text" '
'class="vDateField" name="test_0"size="10" /><br />'
'Zeit: <input value="09:30:00" type="text" class="vTimeField" '
'name="test_1" size="8" /></p>'
)
class AdminURLWidgetTest(SimpleTestCase):
def test_render(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual(
w.render('test', ''),
'<input class="vURLField" name="test" type="url" />'
)
self.assertHTMLEqual(
w.render('test', 'http://example.com'),
'<p class="url">Currently:<a href="http://example.com">'
'http://example.com</a><br />'
'Change:<input class="vURLField" name="test" type="url" '
'value="http://example.com" /></p>'
)
def test_render_idn(self):
w = widgets.AdminURLFieldWidget()
self.assertHTMLEqual(
w.render('test', 'http://example-äüö.com'),
'<p class="url">Currently: <a href="http://xn--example--7za4pnc.com">'
'http://example-äüö.com</a><br />'
'Change:<input class="vURLField" name="test" type="url" '
'value="http://example-äüö.com" /></p>'
)
def test_render_quoting(self):
# WARNING: Don't use assertHTMLEqual in that testcase!
# assertHTMLEqual will get rid of some escapes which are tested here!
w = widgets.AdminURLFieldWidget()
self.assertEqual(
w.render('test', 'http://example.com/<sometag>some text</sometag>'),
'<p class="url">Currently: '
'<a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">'
'http://example.com/<sometag>some text</sometag></a><br />'
'Change: <input class="vURLField" name="test" type="url" '
'value="http://example.com/<sometag>some text</sometag>" /></p>'
)
self.assertEqual(
w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>'),
'<p class="url">Currently: '
'<a href="http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E">'
'http://example-äüö.com/<sometag>some text</sometag></a><br />'
'Change: <input class="vURLField" name="test" type="url" '
'value="http://example-äüö.com/<sometag>some text</sometag>" /></p>'
)
self.assertEqual(
w.render('test', 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"'),
'<p class="url">Currently: '
'<a href="http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22">'
'http://www.example.com/%C3%A4"><script>'
'alert("XSS!")</script>"</a><br />'
'Change: <input class="vURLField" name="test" type="url" '
'value="http://www.example.com/%C3%A4"><script>'
'alert("XSS!")</script>"" /></p>'
)
@override_settings(
PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls',
)
class AdminFileWidgetTests(TestDataMixin, TestCase):
@classmethod
def setUpTestData(cls):
super(AdminFileWidgetTests, cls).setUpTestData()
band = models.Band.objects.create(name='Linkin Park')
cls.album = band.album_set.create(
name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
)
def test_render(self):
w = widgets.AdminFileWidget()
self.assertHTMLEqual(
w.render('test', self.album.cover_art),
'<p class="file-upload">Currently: <a href="%(STORAGE_URL)salbums/'
'hybrid_theory.jpg">albums\hybrid_theory.jpg</a> '
'<span class="clearable-file-input">'
'<input type="checkbox" name="test-clear" id="test-clear_id" /> '
'<label for="test-clear_id">Clear</label></span><br />'
'Change: <input type="file" name="test" /></p>' % {
'STORAGE_URL': default_storage.url(''),
},
)
self.assertHTMLEqual(
w.render('test', SimpleUploadedFile('test', b'content')),
'<input type="file" name="test" />',
)
def test_readonly_fields(self):
"""
File widgets should render as a link when they're marked "read only."
"""
self.client.login(username="super", password="secret")
response = self.client.get(reverse('admin:admin_widgets_album_change', args=(self.album.id,)))
self.assertContains(
response,
'<p><a href="%(STORAGE_URL)salbums/hybrid_theory.jpg">'
'albums\hybrid_theory.jpg</a></p>' % {'STORAGE_URL': default_storage.url('')},
html=True,
)
self.assertNotContains(
response,
'<input type="file" name="cover_art" id="id_cover_art" />',
html=True,
)
response = self.client.get(reverse('admin:admin_widgets_album_add'))
self.assertContains(
response,
'<p></p>',
html=True,
)
@override_settings(ROOT_URLCONF='admin_widgets.urls')
class ForeignKeyRawIdWidgetTest(TestCase):
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
band.album_set.create(
name='Hybrid Theory', cover_art=r'albums\hybrid_theory.jpg'
)
rel = models.Album._meta.get_field('band').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', band.pk, attrs={}),
'<input type="text" name="test" value="%(bandpk)s" '
'class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/band/?_to_field=id" class="related-lookup" '
'id="lookup_id_test" title="Lookup"></a> <strong>Linkin Park</strong>'
% {'bandpk': band.pk}
)
def test_relations_to_non_primary_key(self):
# Check that ForeignKeyRawIdWidget works with fields which aren't
# related to the model's primary key.
apple = models.Inventory.objects.create(barcode=86, name='Apple')
models.Inventory.objects.create(barcode=22, name='Pear')
core = models.Inventory.objects.create(
barcode=87, name='Core', parent=apple
)
rel = models.Inventory._meta.get_field('parent').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', core.parent_id, attrs={}),
'<input type="text" name="test" value="86" '
'class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/inventory/?_to_field=barcode" '
'class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
' <strong>Apple</strong>'
)
def test_fk_related_model_not_in_admin(self):
# FK to a model not registered with admin site. Raw ID widget should
# have no magnifying glass link. See #16542
big_honeycomb = models.Honeycomb.objects.create(location='Old tree')
big_honeycomb.bee_set.create()
rel = models.Bee._meta.get_field('honeycomb').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('honeycomb_widget', big_honeycomb.pk, attrs={}),
'<input type="text" name="honeycomb_widget" value="%(hcombpk)s" />'
' <strong>Honeycomb object</strong>'
% {'hcombpk': big_honeycomb.pk}
)
def test_fk_to_self_model_not_in_admin(self):
# FK to self, not registered with admin site. Raw ID widget should have
# no magnifying glass link. See #16542
subject1 = models.Individual.objects.create(name='Subject #1')
models.Individual.objects.create(name='Child', parent=subject1)
rel = models.Individual._meta.get_field('parent').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('individual_widget', subject1.pk, attrs={}),
'<input type="text" name="individual_widget" value="%(subj1pk)s" />'
' <strong>Individual object</strong>'
% {'subj1pk': subject1.pk}
)
def test_proper_manager_for_label_lookup(self):
# see #9258
rel = models.Inventory._meta.get_field('parent').remote_field
w = widgets.ForeignKeyRawIdWidget(rel, widget_admin_site)
hidden = models.Inventory.objects.create(
barcode=93, name='Hidden', hidden=True
)
child_of_hidden = models.Inventory.objects.create(
barcode=94, name='Child of hidden', parent=hidden
)
self.assertHTMLEqual(
w.render('test', child_of_hidden.parent_id, attrs={}),
'<input type="text" name="test" value="93" class="vForeignKeyRawIdAdminField" />'
'<a href="/admin_widgets/inventory/?_to_field=barcode" '
'class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
' <strong>Hidden</strong>'
)
@override_settings(ROOT_URLCONF='admin_widgets.urls')
class ManyToManyRawIdWidgetTest(TestCase):
def test_render(self):
band = models.Band.objects.create(name='Linkin Park')
m1 = models.Member.objects.create(name='Chester')
m2 = models.Member.objects.create(name='Mike')
band.members.add(m1, m2)
rel = models.Band._meta.get_field('members').remote_field
w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('test', [m1.pk, m2.pk], attrs={}), (
'<input type="text" name="test" value="%(m1pk)s,%(m2pk)s" class="vManyToManyRawIdAdminField" />'
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
) % dict(m1pk=m1.pk, m2pk=m2.pk)
)
self.assertHTMLEqual(
w.render('test', [m1.pk]), (
'<input type="text" name="test" value="%(m1pk)s" class="vManyToManyRawIdAdminField">'
'<a href="/admin_widgets/member/" class="related-lookup" id="lookup_id_test" title="Lookup"></a>'
) % dict(m1pk=m1.pk)
)
def test_m2m_related_model_not_in_admin(self):
# M2M relationship with model not registered with admin site. Raw ID
# widget should have no magnifying glass link. See #16542
consultor1 = models.Advisor.objects.create(name='Rockstar Techie')
c1 = models.Company.objects.create(name='Doodle')
c2 = models.Company.objects.create(name='Pear')
consultor1.companies.add(c1, c2)
rel = models.Advisor._meta.get_field('companies').remote_field
w = widgets.ManyToManyRawIdWidget(rel, widget_admin_site)
self.assertHTMLEqual(
w.render('company_widget1', [c1.pk, c2.pk], attrs={}),
'<input type="text" name="company_widget1" value="%(c1pk)s,%(c2pk)s" />' % {'c1pk': c1.pk, 'c2pk': c2.pk}
)
self.assertHTMLEqual(
w.render('company_widget2', [c1.pk]),
'<input type="text" name="company_widget2" value="%(c1pk)s" />' % {'c1pk': c1.pk}
)
class RelatedFieldWidgetWrapperTests(SimpleTestCase):
def test_no_can_add_related(self):
rel = models.Individual._meta.get_field('parent').remote_field
w = widgets.AdminRadioSelect()
# Used to fail with a name error.
w = widgets.RelatedFieldWidgetWrapper(w, rel, widget_admin_site)
self.assertFalse(w.can_add_related)
def test_select_multiple_widget_cant_change_delete_related(self):
rel = models.Individual._meta.get_field('parent').remote_field
widget = forms.SelectMultiple()
wrapper = widgets.RelatedFieldWidgetWrapper(
widget, rel, widget_admin_site,
can_add_related=True,
can_change_related=True,
can_delete_related=True,
)
self.assertTrue(wrapper.can_add_related)
self.assertFalse(wrapper.can_change_related)
self.assertFalse(wrapper.can_delete_related)
def test_on_delete_cascade_rel_cant_delete_related(self):
rel = models.Individual._meta.get_field('soulmate').remote_field
widget = forms.Select()
wrapper = widgets.RelatedFieldWidgetWrapper(
widget, rel, widget_admin_site,
can_add_related=True,
can_change_related=True,
can_delete_related=True,
)
self.assertTrue(wrapper.can_add_related)
self.assertTrue(wrapper.can_change_related)
self.assertFalse(wrapper.can_delete_related)
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class DateTimePickerSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_show_hide_date_time_picker_widgets(self):
"""
Ensure that pressing the ESC key closes the date and time picker
widgets.
Refs #17064.
"""
from selenium.webdriver.common.keys import Keys
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
# First, with the date picker widget ---------------------------------
# Check that the date picker is hidden
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'none')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# Check that the date picker is visible
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'block')
# Press the ESC key
self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE])
# Check that the date picker is hidden again
self.assertEqual(
self.get_css_value('#calendarbox0', 'display'), 'none')
# Then, with the time picker widget ----------------------------------
# Check that the time picker is hidden
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'none')
# Click the time icon
self.selenium.find_element_by_id('clocklink0').click()
# Check that the time picker is visible
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'block')
self.assertEqual(
[
x.text for x in
self.selenium.find_elements_by_xpath("//ul[@class='timelist']/li/a")
],
['Now', 'Midnight', '6 a.m.', 'Noon', '6 p.m.']
)
# Press the ESC key
self.selenium.find_element_by_tag_name('body').send_keys([Keys.ESCAPE])
# Check that the time picker is hidden again
self.assertEqual(
self.get_css_value('#clockbox0', 'display'), 'none')
def test_calendar_nonday_class(self):
"""
Ensure cells that are not days of the month have the `nonday` CSS class.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
# fill in the birth date.
self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# make sure the first and last 6 cells have class nonday
for td in tds[:6] + tds[-6:]:
self.assertEqual(td.get_attribute('class'), 'nonday')
def test_calendar_selected_class(self):
"""
Ensure cell for the day in the input has the `selected` CSS class.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
# fill in the birth date.
self.selenium.find_element_by_id('id_birthdate_0').send_keys('2013-06-01')
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# verify the selected cell
selected = tds[6]
self.assertEqual(selected.get_attribute('class'), 'selected')
self.assertEqual(selected.text, '1')
def test_calendar_no_selected_class(self):
"""
Ensure no cells are given the selected class when the field is empty.
Refs #4574.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Open a page that has a date and time picker widgets
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
# Click the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# get all the tds within the calendar
calendar0 = self.selenium.find_element_by_id('calendarin0')
tds = calendar0.find_elements_by_tag_name('td')
# verify there are no cells with the selected class
selected = [td for td in tds if td.get_attribute('class') == 'selected']
self.assertEqual(len(selected), 0)
def test_calendar_show_date_from_input(self):
"""
Ensure that the calendar show the date from the input field for every
locale supported by django.
"""
self.admin_login(username='super', password='secret', login_url='/')
# Enter test data
member = models.Member.objects.create(name='Bob', birthdate=datetime(1984, 5, 15), gender='M')
# Get month names translations for every locales
month_string = 'January February March April May June July August September October November December'
path = os.path.join(os.path.dirname(import_module('django.contrib.admin').__file__), 'locale')
for language_code, language_name in settings.LANGUAGES:
try:
catalog = gettext.translation('djangojs', path, [language_code])
except IOError:
continue
if month_string in catalog._catalog:
month_names = catalog._catalog[month_string]
else:
month_names = month_string
# Get the expected caption
may_translation = month_names.split(' ')[4]
expected_caption = '{0:s} {1:d}'.format(may_translation.upper(), 1984)
# Test with every locale
with override_settings(LANGUAGE_CODE=language_code, USE_L10N=True):
# Open a page that has a date picker widget
self.selenium.get('{}{}'.format(self.live_server_url,
reverse('admin:admin_widgets_member_change', args=(member.pk,))))
# Click on the calendar icon
self.selenium.find_element_by_id('calendarlink0').click()
# Make sure that the right month and year are displayed
self.wait_for_text('#calendarin0 caption', expected_caption)
class DateTimePickerSeleniumChromeTests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerSeleniumIETests(DateTimePickerSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@skipIf(pytz is None, "this test requires pytz")
@override_settings(TIME_ZONE='Asia/Singapore')
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class DateTimePickerShortcutsSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_date_time_picker_shortcuts(self):
"""
Ensure that date/time/datetime picker shortcuts work in the current time zone.
Refs #20663.
This test case is fairly tricky, it relies on selenium still running the browser
in the default time zone "America/Chicago" despite `override_settings` changing
the time zone to "Asia/Singapore".
"""
self.admin_login(username='super', password='secret', login_url='/')
error_margin = timedelta(seconds=10)
# If we are neighbouring a DST, we add an hour of error margin.
tz = pytz.timezone('America/Chicago')
utc_now = datetime.now(pytz.utc)
tz_yesterday = (utc_now - timedelta(days=1)).astimezone(tz).tzname()
tz_tomorrow = (utc_now + timedelta(days=1)).astimezone(tz).tzname()
if tz_yesterday != tz_tomorrow:
error_margin += timedelta(hours=1)
now = datetime.now()
self.selenium.get('%s%s' % (self.live_server_url,
reverse('admin:admin_widgets_member_add')))
self.selenium.find_element_by_id('id_name').send_keys('test')
# Click on the "today" and "now" shortcuts.
shortcuts = self.selenium.find_elements_by_css_selector(
'.field-birthdate .datetimeshortcuts')
for shortcut in shortcuts:
shortcut.find_element_by_tag_name('a').click()
# Check that there is a time zone mismatch warning.
# Warning: This would effectively fail if the TIME_ZONE defined in the
# settings has the same UTC offset as "Asia/Singapore" because the
# mismatch warning would be rightfully missing from the page.
self.selenium.find_elements_by_css_selector(
'.field-birthdate .timezonewarning')
# Submit the form.
self.selenium.find_element_by_tag_name('form').submit()
self.wait_page_loaded()
# Make sure that "now" in javascript is within 10 seconds
# from "now" on the server side.
member = models.Member.objects.get(name='test')
self.assertGreater(member.birthdate, now - error_margin)
self.assertLess(member.birthdate, now + error_margin)
class DateTimePickerShortcutsSeleniumChromeTests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerShortcutsSeleniumIETests(DateTimePickerShortcutsSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
# The above tests run with Asia/Singapore which are on the positive side of
# UTC. Here we test with a timezone on the negative side.
@override_settings(TIME_ZONE='US/Eastern')
class DateTimePickerAltTimezoneSeleniumFirefoxTests(DateTimePickerShortcutsSeleniumFirefoxTests):
pass
class DateTimePickerAltTimezoneSeleniumChromeTests(DateTimePickerAltTimezoneSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class DateTimePickerAltTimezoneSeleniumIETests(DateTimePickerAltTimezoneSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class HorizontalVerticalFilterSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def setUp(self):
super(HorizontalVerticalFilterSeleniumFirefoxTests, self).setUp()
self.lisa = models.Student.objects.create(name='Lisa')
self.john = models.Student.objects.create(name='John')
self.bob = models.Student.objects.create(name='Bob')
self.peter = models.Student.objects.create(name='Peter')
self.jenny = models.Student.objects.create(name='Jenny')
self.jason = models.Student.objects.create(name='Jason')
self.cliff = models.Student.objects.create(name='Cliff')
self.arthur = models.Student.objects.create(name='Arthur')
self.school = models.School.objects.create(name='School of Awesome')
def assertActiveButtons(self, mode, field_name, choose, remove,
choose_all=None, remove_all=None):
choose_link = '#id_%s_add_link' % field_name
choose_all_link = '#id_%s_add_all_link' % field_name
remove_link = '#id_%s_remove_link' % field_name
remove_all_link = '#id_%s_remove_all_link' % field_name
self.assertEqual(self.has_css_class(choose_link, 'active'), choose)
self.assertEqual(self.has_css_class(remove_link, 'active'), remove)
if mode == 'horizontal':
self.assertEqual(self.has_css_class(choose_all_link, 'active'), choose_all)
self.assertEqual(self.has_css_class(remove_all_link, 'active'), remove_all)
def execute_basic_operations(self, mode, field_name):
from_box = '#id_%s_from' % field_name
to_box = '#id_%s_to' % field_name
choose_link = 'id_%s_add_link' % field_name
choose_all_link = 'id_%s_add_all_link' % field_name
remove_link = 'id_%s_remove_link' % field_name
remove_all_link = 'id_%s_remove_all_link' % field_name
# Initial positions ---------------------------------------------------
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id)])
self.assertActiveButtons(mode, field_name, False, False, True, True)
# Click 'Choose all' --------------------------------------------------
if mode == 'horizontal':
self.selenium.find_element_by_id(choose_all_link).click()
elif mode == 'vertical':
# There 's no 'Choose all' button in vertical mode, so individually
# select all options and click 'Choose'.
for option in self.selenium.find_elements_by_css_selector(from_box + ' > option'):
option.click()
self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box, [])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id),
str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertActiveButtons(mode, field_name, False, False, False, True)
# Click 'Remove all' --------------------------------------------------
if mode == 'horizontal':
self.selenium.find_element_by_id(remove_all_link).click()
elif mode == 'vertical':
# There 's no 'Remove all' button in vertical mode, so individually
# select all options and click 'Remove'.
for option in self.selenium.find_elements_by_css_selector(to_box + ' > option'):
option.click()
self.selenium.find_element_by_id(remove_link).click()
self.assertSelectOptions(from_box,
[str(self.lisa.id), str(self.peter.id),
str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
self.assertSelectOptions(to_box, [])
self.assertActiveButtons(mode, field_name, False, False, True, False)
# Choose some options ------------------------------------------------
from_lisa_select_option = self.get_select_option(from_box, str(self.lisa.id))
# Check the title attribute is there for tool tips: ticket #20821
self.assertEqual(from_lisa_select_option.get_attribute('title'), from_lisa_select_option.get_attribute('text'))
from_lisa_select_option.click()
self.get_select_option(from_box, str(self.jason.id)).click()
self.get_select_option(from_box, str(self.bob.id)).click()
self.get_select_option(from_box, str(self.john.id)).click()
self.assertActiveButtons(mode, field_name, True, False, True, False)
self.selenium.find_element_by_id(choose_link).click()
self.assertActiveButtons(mode, field_name, False, False, True, True)
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.arthur.id),
str(self.cliff.id), str(self.jenny.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.bob.id),
str(self.jason.id), str(self.john.id)])
# Check the tooltip is still there after moving: ticket #20821
to_lisa_select_option = self.get_select_option(to_box, str(self.lisa.id))
self.assertEqual(to_lisa_select_option.get_attribute('title'), to_lisa_select_option.get_attribute('text'))
# Remove some options -------------------------------------------------
self.get_select_option(to_box, str(self.lisa.id)).click()
self.get_select_option(to_box, str(self.bob.id)).click()
self.assertActiveButtons(mode, field_name, False, True, True, True)
self.selenium.find_element_by_id(remove_link).click()
self.assertActiveButtons(mode, field_name, False, False, True, True)
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.arthur.id),
str(self.cliff.id), str(self.jenny.id),
str(self.lisa.id), str(self.bob.id)])
self.assertSelectOptions(to_box,
[str(self.jason.id), str(self.john.id)])
# Choose some more options --------------------------------------------
self.get_select_option(from_box, str(self.arthur.id)).click()
self.get_select_option(from_box, str(self.cliff.id)).click()
self.selenium.find_element_by_id(choose_link).click()
self.assertSelectOptions(from_box,
[str(self.peter.id), str(self.jenny.id),
str(self.lisa.id), str(self.bob.id)])
self.assertSelectOptions(to_box,
[str(self.jason.id), str(self.john.id),
str(self.arthur.id), str(self.cliff.id)])
def test_basic(self):
self.school.students = [self.lisa, self.peter]
self.school.alumni = [self.lisa, self.peter]
self.school.save()
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get('%s%s' % (
self.live_server_url, reverse('admin:admin_widgets_school_change', args=(self.school.id,))))
self.wait_page_loaded()
self.execute_basic_operations('vertical', 'students')
self.execute_basic_operations('horizontal', 'alumni')
# Save and check that everything is properly stored in the database ---
self.selenium.find_element_by_xpath('//input[@value="Save"]').click()
self.wait_page_loaded()
self.school = models.School.objects.get(id=self.school.id) # Reload from database
self.assertEqual(list(self.school.students.all()),
[self.arthur, self.cliff, self.jason, self.john])
self.assertEqual(list(self.school.alumni.all()),
[self.arthur, self.cliff, self.jason, self.john])
def test_filter(self):
"""
Ensure that typing in the search box filters out options displayed in
the 'from' box.
"""
from selenium.webdriver.common.keys import Keys
self.school.students = [self.lisa, self.peter]
self.school.alumni = [self.lisa, self.peter]
self.school.save()
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_school_change', args=(self.school.id,))))
for field_name in ['students', 'alumni']:
from_box = '#id_%s_from' % field_name
to_box = '#id_%s_to' % field_name
choose_link = '#id_%s_add_link' % field_name
remove_link = '#id_%s_remove_link' % field_name
input = self.selenium.find_element_by_css_selector('#id_%s_input' % field_name)
# Initial values
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
# Typing in some characters filters out non-matching options
input.send_keys('a')
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
input.send_keys('R')
self.assertSelectOptions(from_box, [str(self.arthur.id)])
# Clearing the text box makes the other options reappear
input.send_keys([Keys.BACK_SPACE])
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE])
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jason.id),
str(self.jenny.id), str(self.john.id)])
# -----------------------------------------------------------------
# Check that choosing a filtered option sends it properly to the
# 'to' box.
input.send_keys('a')
self.assertSelectOptions(from_box, [str(self.arthur.id), str(self.jason.id)])
self.get_select_option(from_box, str(self.jason.id)).click()
self.selenium.find_element_by_css_selector(choose_link).click()
self.assertSelectOptions(from_box, [str(self.arthur.id)])
self.assertSelectOptions(to_box,
[str(self.lisa.id), str(self.peter.id),
str(self.jason.id)])
self.get_select_option(to_box, str(self.lisa.id)).click()
self.selenium.find_element_by_css_selector(remove_link).click()
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.lisa.id)])
self.assertSelectOptions(to_box,
[str(self.peter.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE]) # Clear text box
self.assertSelectOptions(from_box,
[str(self.arthur.id), str(self.bob.id),
str(self.cliff.id), str(self.jenny.id),
str(self.john.id), str(self.lisa.id)])
self.assertSelectOptions(to_box,
[str(self.peter.id), str(self.jason.id)])
# -----------------------------------------------------------------
# Check that pressing enter on a filtered option sends it properly
# to the 'to' box.
self.get_select_option(to_box, str(self.jason.id)).click()
self.selenium.find_element_by_css_selector(remove_link).click()
input.send_keys('ja')
self.assertSelectOptions(from_box, [str(self.jason.id)])
input.send_keys([Keys.ENTER])
self.assertSelectOptions(to_box, [str(self.peter.id), str(self.jason.id)])
input.send_keys([Keys.BACK_SPACE, Keys.BACK_SPACE])
# Save and check that everything is properly stored in the database ---
self.selenium.find_element_by_xpath('//input[@value="Save"]').click()
self.wait_page_loaded()
self.school = models.School.objects.get(id=self.school.id) # Reload from database
self.assertEqual(list(self.school.students.all()),
[self.jason, self.peter])
self.assertEqual(list(self.school.alumni.all()),
[self.jason, self.peter])
class HorizontalVerticalFilterSeleniumChromeTests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class HorizontalVerticalFilterSeleniumIETests(HorizontalVerticalFilterSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class AdminRawIdWidgetSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def setUp(self):
super(AdminRawIdWidgetSeleniumFirefoxTests, self).setUp()
models.Band.objects.create(id=42, name='Bogey Blues')
models.Band.objects.create(id=98, name='Green Potatoes')
def test_ForeignKey(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_event_add')))
main_window = self.selenium.current_window_handle
# No value has been selected yet
self.assertEqual(
self.selenium.find_element_by_id('id_main_band').get_attribute('value'),
'')
# Open the popup window and click on a band
self.selenium.find_element_by_id('lookup_id_main_band').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_main_band')
link = self.selenium.find_element_by_link_text('Bogey Blues')
self.assertIn('/band/42/', link.get_attribute('href'))
link.click()
# The field now contains the selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_main_band', '42')
# Reopen the popup window and click on another band
self.selenium.find_element_by_id('lookup_id_main_band').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_main_band')
link = self.selenium.find_element_by_link_text('Green Potatoes')
self.assertIn('/band/98/', link.get_attribute('href'))
link.click()
# The field now contains the other selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_main_band', '98')
def test_many_to_many(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get(
'%s%s' % (self.live_server_url, reverse('admin:admin_widgets_event_add')))
main_window = self.selenium.current_window_handle
# No value has been selected yet
self.assertEqual(
self.selenium.find_element_by_id('id_supporting_bands').get_attribute('value'),
'')
# Open the popup window and click on a band
self.selenium.find_element_by_id('lookup_id_supporting_bands').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_supporting_bands')
link = self.selenium.find_element_by_link_text('Bogey Blues')
self.assertIn('/band/42/', link.get_attribute('href'))
link.click()
# The field now contains the selected band's id
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_supporting_bands', '42')
# Reopen the popup window and click on another band
self.selenium.find_element_by_id('lookup_id_supporting_bands').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_supporting_bands')
link = self.selenium.find_element_by_link_text('Green Potatoes')
self.assertIn('/band/98/', link.get_attribute('href'))
link.click()
# The field now contains the two selected bands' ids
self.selenium.switch_to.window(main_window)
self.wait_for_value('#id_supporting_bands', '42,98')
class AdminRawIdWidgetSeleniumChromeTests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class AdminRawIdWidgetSeleniumIETests(AdminRawIdWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver'
@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
ROOT_URLCONF='admin_widgets.urls')
class RelatedFieldWidgetSeleniumFirefoxTests(SeleniumDataMixin, AdminSeleniumWebDriverTestCase):
available_apps = ['admin_widgets'] + AdminSeleniumWebDriverTestCase.available_apps
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
def test_ForeignKey_using_to_field(self):
self.admin_login(username='super', password='secret', login_url='/')
self.selenium.get('%s%s' % (
self.live_server_url,
reverse('admin:admin_widgets_profile_add')))
main_window = self.selenium.current_window_handle
# Click the Add User button to add new
self.selenium.find_element_by_id('add_id_user').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_user')
password_field = self.selenium.find_element_by_id('id_password')
password_field.send_keys('password')
username_field = self.selenium.find_element_by_id('id_username')
username_value = 'newuser'
username_field.send_keys(username_value)
save_button_css_selector = '.submit-row > input[type=submit]'
self.selenium.find_element_by_css_selector(save_button_css_selector).click()
self.selenium.switch_to.window(main_window)
# The field now contains the new user
self.wait_for('#id_user option[value="newuser"]')
# Click the Change User button to change it
self.selenium.find_element_by_id('change_id_user').click()
self.wait_for_popup()
self.selenium.switch_to.window('id_user')
username_field = self.selenium.find_element_by_id('id_username')
username_value = 'changednewuser'
username_field.clear()
username_field.send_keys(username_value)
save_button_css_selector = '.submit-row > input[type=submit]'
self.selenium.find_element_by_css_selector(save_button_css_selector).click()
self.selenium.switch_to.window(main_window)
# Wait up to 2 seconds for the new option to show up after clicking save in the popup.
self.selenium.implicitly_wait(2)
self.selenium.find_element_by_css_selector('#id_user option[value=changednewuser]')
self.selenium.implicitly_wait(0)
# Go ahead and submit the form to make sure it works
self.selenium.find_element_by_css_selector(save_button_css_selector).click()
self.wait_for_text('li.success', 'The profile "changednewuser" was added successfully.')
profiles = models.Profile.objects.all()
self.assertEqual(len(profiles), 1)
self.assertEqual(profiles[0].user.username, username_value)
class RelatedFieldWidgetSeleniumChromeTests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.chrome.webdriver.WebDriver'
class RelatedFieldWidgetSeleniumIETests(RelatedFieldWidgetSeleniumFirefoxTests):
webdriver_class = 'selenium.webdriver.ie.webdriver.WebDriver' | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2007 Google Inc.
# Licensed to PSF under a Contributor Agreement.
"""Unittest for ipaddress module."""
import unittest
import re
import contextlib
import operator
import ipaddress
class BaseTestCase(unittest.TestCase):
# One big change in ipaddress over the original ipaddr module is
# error reporting that tries to assume users *don't know the rules*
# for what constitutes an RFC compliant IP address
# Ensuring these errors are emitted correctly in all relevant cases
# meant moving to a more systematic test structure that allows the
# test structure to map more directly to the module structure
# Note that if the constructors are refactored so that addresses with
# multiple problems get classified differently, that's OK - just
# move the affected examples to the newly appropriate test case.
# There is some duplication between the original relatively ad hoc
# test suite and the new systematic tests. While some redundancy in
# testing is considered preferable to accidentally deleting a valid
# test, the original test suite will likely be reduced over time as
# redundant tests are identified.
@property
def factory(self):
raise NotImplementedError
@contextlib.contextmanager
def assertCleanError(self, exc_type, details, *args):
"""
Ensure exception does not display a context by default
Wraps unittest.TestCase.assertRaisesRegex
"""
if args:
details = details % args
cm = self.assertRaisesRegex(exc_type, details)
with cm as exc:
yield exc
# Ensure we produce clean tracebacks on failure
if exc.exception.__context__ is not None:
self.assertTrue(exc.exception.__suppress_context__)
def assertAddressError(self, details, *args):
"""Ensure a clean AddressValueError"""
return self.assertCleanError(ipaddress.AddressValueError,
details, *args)
def assertNetmaskError(self, details, *args):
"""Ensure a clean NetmaskValueError"""
return self.assertCleanError(ipaddress.NetmaskValueError,
details, *args)
def assertInstancesEqual(self, lhs, rhs):
"""Check constructor arguments produce equivalent instances"""
self.assertEqual(self.factory(lhs), self.factory(rhs))
class CommonTestMixin:
def test_empty_address(self):
with self.assertAddressError("Address cannot be empty"):
self.factory("")
def test_floats_rejected(self):
with self.assertAddressError(re.escape(repr("1.0"))):
self.factory(1.0)
def test_not_an_index_issue15559(self):
# Implementing __index__ makes for a very nasty interaction with the
# bytes constructor. Thus, we disallow implicit use as an integer
self.assertRaises(TypeError, operator.index, self.factory(1))
self.assertRaises(TypeError, hex, self.factory(1))
self.assertRaises(TypeError, bytes, self.factory(1))
class CommonTestMixin_v4(CommonTestMixin):
def test_leading_zeros(self):
self.assertInstancesEqual("000.000.000.000", "0.0.0.0")
self.assertInstancesEqual("192.168.000.001", "192.168.0.1")
def test_int(self):
self.assertInstancesEqual(0, "0.0.0.0")
self.assertInstancesEqual(3232235521, "192.168.0.1")
def test_packed(self):
self.assertInstancesEqual(bytes.fromhex("00000000"), "0.0.0.0")
self.assertInstancesEqual(bytes.fromhex("c0a80001"), "192.168.0.1")
def test_negative_ints_rejected(self):
msg = "-1 (< 0) is not permitted as an IPv4 address"
with self.assertAddressError(re.escape(msg)):
self.factory(-1)
def test_large_ints_rejected(self):
msg = "%d (>= 2**32) is not permitted as an IPv4 address"
with self.assertAddressError(re.escape(msg % 2**32)):
self.factory(2**32)
def test_bad_packed_length(self):
def assertBadLength(length):
addr = bytes(length)
msg = "%r (len %d != 4) is not permitted as an IPv4 address"
with self.assertAddressError(re.escape(msg % (addr, length))):
self.factory(addr)
assertBadLength(3)
assertBadLength(5)
class CommonTestMixin_v6(CommonTestMixin):
def test_leading_zeros(self):
self.assertInstancesEqual("0000::0000", "::")
self.assertInstancesEqual("000::c0a8:0001", "::c0a8:1")
def test_int(self):
self.assertInstancesEqual(0, "::")
self.assertInstancesEqual(3232235521, "::c0a8:1")
def test_packed(self):
addr = bytes(12) + bytes.fromhex("00000000")
self.assertInstancesEqual(addr, "::")
addr = bytes(12) + bytes.fromhex("c0a80001")
self.assertInstancesEqual(addr, "::c0a8:1")
addr = bytes.fromhex("c0a80001") + bytes(12)
self.assertInstancesEqual(addr, "c0a8:1::")
def test_negative_ints_rejected(self):
msg = "-1 (< 0) is not permitted as an IPv6 address"
with self.assertAddressError(re.escape(msg)):
self.factory(-1)
def test_large_ints_rejected(self):
msg = "%d (>= 2**128) is not permitted as an IPv6 address"
with self.assertAddressError(re.escape(msg % 2**128)):
self.factory(2**128)
def test_bad_packed_length(self):
def assertBadLength(length):
addr = bytes(length)
msg = "%r (len %d != 16) is not permitted as an IPv6 address"
with self.assertAddressError(re.escape(msg % (addr, length))):
self.factory(addr)
self.factory(addr)
assertBadLength(15)
assertBadLength(17)
class AddressTestCase_v4(BaseTestCase, CommonTestMixin_v4):
factory = ipaddress.IPv4Address
def test_network_passed_as_address(self):
addr = "127.0.0.1/24"
with self.assertAddressError("Unexpected '/' in %r", addr):
ipaddress.IPv4Address(addr)
def test_bad_address_split(self):
def assertBadSplit(addr):
with self.assertAddressError("Expected 4 octets in %r", addr):
ipaddress.IPv4Address(addr)
assertBadSplit("127.0.1")
assertBadSplit("42.42.42.42.42")
assertBadSplit("42.42.42")
assertBadSplit("42.42")
assertBadSplit("42")
assertBadSplit("42..42.42.42")
assertBadSplit("42.42.42.42.")
assertBadSplit("42.42.42.42...")
assertBadSplit(".42.42.42.42")
assertBadSplit("...42.42.42.42")
assertBadSplit("016.016.016")
assertBadSplit("016.016")
assertBadSplit("016")
assertBadSplit("000")
assertBadSplit("0x0a.0x0a.0x0a")
assertBadSplit("0x0a.0x0a")
assertBadSplit("0x0a")
assertBadSplit(".")
assertBadSplit("bogus")
assertBadSplit("bogus.com")
assertBadSplit("1000")
assertBadSplit("1000000000000000")
assertBadSplit("192.168.0.1.com")
def test_empty_octet(self):
def assertBadOctet(addr):
with self.assertAddressError("Empty octet not permitted in %r",
addr):
ipaddress.IPv4Address(addr)
assertBadOctet("42..42.42")
assertBadOctet("...")
def test_invalid_characters(self):
def assertBadOctet(addr, octet):
msg = "Only decimal digits permitted in %r in %r" % (octet, addr)
with self.assertAddressError(re.escape(msg)):
ipaddress.IPv4Address(addr)
assertBadOctet("0x0a.0x0a.0x0a.0x0a", "0x0a")
assertBadOctet("0xa.0x0a.0x0a.0x0a", "0xa")
assertBadOctet("42.42.42.-0", "-0")
assertBadOctet("42.42.42.+0", "+0")
assertBadOctet("42.42.42.-42", "-42")
assertBadOctet("+1.+2.+3.4", "+1")
assertBadOctet("1.2.3.4e0", "4e0")
assertBadOctet("1.2.3.4::", "4::")
assertBadOctet("1.a.2.3", "a")
def test_octal_decimal_ambiguity(self):
def assertBadOctet(addr, octet):
msg = "Ambiguous (octal/decimal) value in %r not permitted in %r"
with self.assertAddressError(re.escape(msg % (octet, addr))):
ipaddress.IPv4Address(addr)
assertBadOctet("016.016.016.016", "016")
assertBadOctet("001.000.008.016", "008")
def test_octet_length(self):
def assertBadOctet(addr, octet):
msg = "At most 3 characters permitted in %r in %r"
with self.assertAddressError(re.escape(msg % (octet, addr))):
ipaddress.IPv4Address(addr)
assertBadOctet("0000.000.000.000", "0000")
assertBadOctet("12345.67899.-54321.-98765", "12345")
def test_octet_limit(self):
def assertBadOctet(addr, octet):
msg = "Octet %d (> 255) not permitted in %r" % (octet, addr)
with self.assertAddressError(re.escape(msg)):
ipaddress.IPv4Address(addr)
assertBadOctet("257.0.0.0", 257)
assertBadOctet("192.168.0.999", 999)
class AddressTestCase_v6(BaseTestCase, CommonTestMixin_v6):
factory = ipaddress.IPv6Address
def test_network_passed_as_address(self):
addr = "::1/24"
with self.assertAddressError("Unexpected '/' in %r", addr):
ipaddress.IPv6Address(addr)
def test_bad_address_split_v6_not_enough_parts(self):
def assertBadSplit(addr):
msg = "At least 3 parts expected in %r"
with self.assertAddressError(msg, addr):
ipaddress.IPv6Address(addr)
assertBadSplit(":")
assertBadSplit(":1")
assertBadSplit("FEDC:9878")
def test_bad_address_split_v6_too_many_colons(self):
def assertBadSplit(addr):
msg = "At most 8 colons permitted in %r"
with self.assertAddressError(msg, addr):
ipaddress.IPv6Address(addr)
assertBadSplit("9:8:7:6:5:4:3::2:1")
assertBadSplit("10:9:8:7:6:5:4:3:2:1")
assertBadSplit("::8:7:6:5:4:3:2:1")
assertBadSplit("8:7:6:5:4:3:2:1::")
# A trailing IPv4 address is two parts
assertBadSplit("10:9:8:7:6:5:4:3:42.42.42.42")
def test_bad_address_split_v6_too_many_parts(self):
def assertBadSplit(addr):
msg = "Exactly 8 parts expected without '::' in %r"
with self.assertAddressError(msg, addr):
ipaddress.IPv6Address(addr)
assertBadSplit("3ffe:0:0:0:0:0:0:0:1")
assertBadSplit("9:8:7:6:5:4:3:2:1")
assertBadSplit("7:6:5:4:3:2:1")
# A trailing IPv4 address is two parts
assertBadSplit("9:8:7:6:5:4:3:42.42.42.42")
assertBadSplit("7:6:5:4:3:42.42.42.42")
def test_bad_address_split_v6_too_many_parts_with_double_colon(self):
def assertBadSplit(addr):
msg = "Expected at most 7 other parts with '::' in %r"
with self.assertAddressError(msg, addr):
ipaddress.IPv6Address(addr)
assertBadSplit("1:2:3:4::5:6:7:8")
def test_bad_address_split_v6_repeated_double_colon(self):
def assertBadSplit(addr):
msg = "At most one '::' permitted in %r"
with self.assertAddressError(msg, addr):
ipaddress.IPv6Address(addr)
assertBadSplit("3ffe::1::1")
assertBadSplit("1::2::3::4:5")
assertBadSplit("2001::db:::1")
assertBadSplit("3ffe::1::")
assertBadSplit("::3ffe::1")
assertBadSplit(":3ffe::1::1")
assertBadSplit("3ffe::1::1:")
assertBadSplit(":3ffe::1::1:")
assertBadSplit(":::")
assertBadSplit('2001:db8:::1')
def test_bad_address_split_v6_leading_colon(self):
def assertBadSplit(addr):
msg = "Leading ':' only permitted as part of '::' in %r"
with self.assertAddressError(msg, addr):
ipaddress.IPv6Address(addr)
assertBadSplit(":2001:db8::1")
assertBadSplit(":1:2:3:4:5:6:7")
assertBadSplit(":1:2:3:4:5:6:")
assertBadSplit(":6:5:4:3:2:1::")
def test_bad_address_split_v6_trailing_colon(self):
def assertBadSplit(addr):
msg = "Trailing ':' only permitted as part of '::' in %r"
with self.assertAddressError(msg, addr):
ipaddress.IPv6Address(addr)
assertBadSplit("2001:db8::1:")
assertBadSplit("1:2:3:4:5:6:7:")
assertBadSplit("::1.2.3.4:")
assertBadSplit("::7:6:5:4:3:2:")
def test_bad_v4_part_in(self):
def assertBadAddressPart(addr, v4_error):
with self.assertAddressError("%s in %r", v4_error, addr):
ipaddress.IPv6Address(addr)
assertBadAddressPart("3ffe::1.net", "Expected 4 octets in '1.net'")
assertBadAddressPart("3ffe::127.0.1",
"Expected 4 octets in '127.0.1'")
assertBadAddressPart("::1.2.3",
"Expected 4 octets in '1.2.3'")
assertBadAddressPart("::1.2.3.4.5",
"Expected 4 octets in '1.2.3.4.5'")
assertBadAddressPart("3ffe::1.1.1.net",
"Only decimal digits permitted in 'net' "
"in '1.1.1.net'")
def test_invalid_characters(self):
def assertBadPart(addr, part):
msg = "Only hex digits permitted in %r in %r" % (part, addr)
with self.assertAddressError(re.escape(msg)):
ipaddress.IPv6Address(addr)
assertBadPart("3ffe::goog", "goog")
assertBadPart("3ffe::-0", "-0")
assertBadPart("3ffe::+0", "+0")
assertBadPart("3ffe::-1", "-1")
assertBadPart("1.2.3.4::", "1.2.3.4")
assertBadPart('1234:axy::b', "axy")
def test_part_length(self):
def assertBadPart(addr, part):
msg = "At most 4 characters permitted in %r in %r"
with self.assertAddressError(msg, part, addr):
ipaddress.IPv6Address(addr)
assertBadPart("::00000", "00000")
assertBadPart("3ffe::10000", "10000")
assertBadPart("02001:db8::", "02001")
assertBadPart('2001:888888::1', "888888")
class NetmaskTestMixin_v4(CommonTestMixin_v4):
"""Input validation on interfaces and networks is very similar"""
def test_split_netmask(self):
addr = "1.2.3.4/32/24"
with self.assertAddressError("Only one '/' permitted in %r" % addr):
self.factory(addr)
def test_address_errors(self):
def assertBadAddress(addr, details):
with self.assertAddressError(details):
self.factory(addr)
assertBadAddress("/", "Address cannot be empty")
assertBadAddress("/8", "Address cannot be empty")
assertBadAddress("bogus", "Expected 4 octets")
assertBadAddress("google.com", "Expected 4 octets")
assertBadAddress("10/8", "Expected 4 octets")
assertBadAddress("::1.2.3.4", "Only decimal digits")
assertBadAddress("1.2.3.256", re.escape("256 (> 255)"))
def test_netmask_errors(self):
def assertBadNetmask(addr, netmask):
msg = "%r is not a valid netmask"
with self.assertNetmaskError(msg % netmask):
self.factory("%s/%s" % (addr, netmask))
assertBadNetmask("1.2.3.4", "")
assertBadNetmask("1.2.3.4", "33")
assertBadNetmask("1.2.3.4", "254.254.255.256")
assertBadNetmask("1.1.1.1", "254.xyz.2.3")
assertBadNetmask("1.1.1.1", "240.255.0.0")
assertBadNetmask("1.1.1.1", "pudding")
class InterfaceTestCase_v4(BaseTestCase, NetmaskTestMixin_v4):
factory = ipaddress.IPv4Interface
class NetworkTestCase_v4(BaseTestCase, NetmaskTestMixin_v4):
factory = ipaddress.IPv4Network
class NetmaskTestMixin_v6(CommonTestMixin_v6):
"""Input validation on interfaces and networks is very similar"""
def test_split_netmask(self):
addr = "cafe:cafe::/128/190"
with self.assertAddressError("Only one '/' permitted in %r" % addr):
self.factory(addr)
def test_address_errors(self):
def assertBadAddress(addr, details):
with self.assertAddressError(details):
self.factory(addr)
assertBadAddress("/", "Address cannot be empty")
assertBadAddress("/8", "Address cannot be empty")
assertBadAddress("google.com", "At least 3 parts")
assertBadAddress("1.2.3.4", "At least 3 parts")
assertBadAddress("10/8", "At least 3 parts")
assertBadAddress("1234:axy::b", "Only hex digits")
def test_netmask_errors(self):
def assertBadNetmask(addr, netmask):
msg = "%r is not a valid netmask"
with self.assertNetmaskError(msg % netmask):
self.factory("%s/%s" % (addr, netmask))
assertBadNetmask("::1", "")
assertBadNetmask("::1", "::1")
assertBadNetmask("::1", "1::")
assertBadNetmask("::1", "129")
assertBadNetmask("::1", "pudding")
class InterfaceTestCase_v6(BaseTestCase, NetmaskTestMixin_v6):
factory = ipaddress.IPv6Interface
class NetworkTestCase_v6(BaseTestCase, NetmaskTestMixin_v6):
factory = ipaddress.IPv6Network
class FactoryFunctionErrors(BaseTestCase):
def assertFactoryError(self, factory, kind):
"""Ensure a clean ValueError with the expected message"""
addr = "camelot"
msg = '%r does not appear to be an IPv4 or IPv6 %s'
with self.assertCleanError(ValueError, msg, addr, kind):
factory(addr)
def test_ip_address(self):
self.assertFactoryError(ipaddress.ip_address, "address")
def test_ip_interface(self):
self.assertFactoryError(ipaddress.ip_interface, "interface")
def test_ip_network(self):
self.assertFactoryError(ipaddress.ip_network, "network")
class ComparisonTests(unittest.TestCase):
v4addr = ipaddress.IPv4Address(1)
v4net = ipaddress.IPv4Network(1)
v4intf = ipaddress.IPv4Interface(1)
v6addr = ipaddress.IPv6Address(1)
v6net = ipaddress.IPv6Network(1)
v6intf = ipaddress.IPv6Interface(1)
v4_addresses = [v4addr, v4intf]
v4_objects = v4_addresses + [v4net]
v6_addresses = [v6addr, v6intf]
v6_objects = v6_addresses + [v6net]
objects = v4_objects + v6_objects
def test_foreign_type_equality(self):
# __eq__ should never raise TypeError directly
other = object()
for obj in self.objects:
self.assertNotEqual(obj, other)
self.assertFalse(obj == other)
self.assertEqual(obj.__eq__(other), NotImplemented)
self.assertEqual(obj.__ne__(other), NotImplemented)
def test_mixed_type_equality(self):
# Ensure none of the internal objects accidentally
# expose the right set of attributes to become "equal"
for lhs in self.objects:
for rhs in self.objects:
if lhs is rhs:
continue
self.assertNotEqual(lhs, rhs)
def test_containment(self):
for obj in self.v4_addresses:
self.assertIn(obj, self.v4net)
for obj in self.v6_addresses:
self.assertIn(obj, self.v6net)
for obj in self.v4_objects + [self.v6net]:
self.assertNotIn(obj, self.v6net)
for obj in self.v6_objects + [self.v4net]:
self.assertNotIn(obj, self.v4net)
def test_mixed_type_ordering(self):
for lhs in self.objects:
for rhs in self.objects:
if isinstance(lhs, type(rhs)) or isinstance(rhs, type(lhs)):
continue
self.assertRaises(TypeError, lambda: lhs < rhs)
self.assertRaises(TypeError, lambda: lhs > rhs)
self.assertRaises(TypeError, lambda: lhs <= rhs)
self.assertRaises(TypeError, lambda: lhs >= rhs)
def test_mixed_type_key(self):
# with get_mixed_type_key, you can sort addresses and network.
v4_ordered = [self.v4addr, self.v4net, self.v4intf]
v6_ordered = [self.v6addr, self.v6net, self.v6intf]
self.assertEqual(v4_ordered,
sorted(self.v4_objects,
key=ipaddress.get_mixed_type_key))
self.assertEqual(v6_ordered,
sorted(self.v6_objects,
key=ipaddress.get_mixed_type_key))
self.assertEqual(v4_ordered + v6_ordered,
sorted(self.objects,
key=ipaddress.get_mixed_type_key))
self.assertEqual(NotImplemented, ipaddress.get_mixed_type_key(object))
def test_incompatible_versions(self):
# These should always raise TypeError
v4addr = ipaddress.ip_address('1.1.1.1')
v4net = ipaddress.ip_network('1.1.1.1')
v6addr = ipaddress.ip_address('::1')
v6net = ipaddress.ip_address('::1')
self.assertRaises(TypeError, v4addr.__lt__, v6addr)
self.assertRaises(TypeError, v4addr.__gt__, v6addr)
self.assertRaises(TypeError, v4net.__lt__, v6net)
self.assertRaises(TypeError, v4net.__gt__, v6net)
self.assertRaises(TypeError, v6addr.__lt__, v4addr)
self.assertRaises(TypeError, v6addr.__gt__, v4addr)
self.assertRaises(TypeError, v6net.__lt__, v4net)
self.assertRaises(TypeError, v6net.__gt__, v4net)
class IpaddrUnitTest(unittest.TestCase):
def setUp(self):
self.ipv4_address = ipaddress.IPv4Address('1.2.3.4')
self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24')
self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24')
#self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255')
self.ipv6_address = ipaddress.IPv6Interface(
'2001:658:22a:cafe:200:0:0:1')
self.ipv6_interface = ipaddress.IPv6Interface(
'2001:658:22a:cafe:200:0:0:1/64')
self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64')
def testRepr(self):
self.assertEqual("IPv4Interface('1.2.3.4/32')",
repr(ipaddress.IPv4Interface('1.2.3.4')))
self.assertEqual("IPv6Interface('::1/128')",
repr(ipaddress.IPv6Interface('::1')))
# issue57
def testAddressIntMath(self):
self.assertEqual(ipaddress.IPv4Address('1.1.1.1') + 255,
ipaddress.IPv4Address('1.1.2.0'))
self.assertEqual(ipaddress.IPv4Address('1.1.1.1') - 256,
ipaddress.IPv4Address('1.1.0.1'))
self.assertEqual(ipaddress.IPv6Address('::1') + (2**16 - 2),
ipaddress.IPv6Address('::ffff'))
self.assertEqual(ipaddress.IPv6Address('::ffff') - (2**16 - 2),
ipaddress.IPv6Address('::1'))
def testInvalidIntToBytes(self):
self.assertRaises(ValueError, ipaddress.v4_int_to_packed, -1)
self.assertRaises(ValueError, ipaddress.v4_int_to_packed,
2 ** ipaddress.IPV4LENGTH)
self.assertRaises(ValueError, ipaddress.v6_int_to_packed, -1)
self.assertRaises(ValueError, ipaddress.v6_int_to_packed,
2 ** ipaddress.IPV6LENGTH)
def testInternals(self):
first, last = ipaddress._find_address_range([
ipaddress.IPv4Address('10.10.10.10'),
ipaddress.IPv4Address('10.10.10.12')])
self.assertEqual(first, last)
self.assertEqual(128, ipaddress._count_righthand_zero_bits(0, 128))
self.assertEqual("IPv4Network('1.2.3.0/24')", repr(self.ipv4_network))
def testMissingAddressVersion(self):
class Broken(ipaddress._BaseAddress):
pass
broken = Broken('127.0.0.1')
with self.assertRaisesRegex(NotImplementedError, "Broken.*version"):
broken.version
def testMissingNetworkVersion(self):
class Broken(ipaddress._BaseNetwork):
pass
broken = Broken('127.0.0.1')
with self.assertRaisesRegex(NotImplementedError, "Broken.*version"):
broken.version
def testMissingAddressClass(self):
class Broken(ipaddress._BaseNetwork):
pass
broken = Broken('127.0.0.1')
with self.assertRaisesRegex(NotImplementedError, "Broken.*address"):
broken._address_class
def testGetNetwork(self):
self.assertEqual(int(self.ipv4_network.network_address), 16909056)
self.assertEqual(str(self.ipv4_network.network_address), '1.2.3.0')
self.assertEqual(int(self.ipv6_network.network_address),
42540616829182469433403647294022090752)
self.assertEqual(str(self.ipv6_network.network_address),
'2001:658:22a:cafe::')
self.assertEqual(str(self.ipv6_network.hostmask),
'::ffff:ffff:ffff:ffff')
def testIpFromInt(self):
self.assertEqual(self.ipv4_interface._ip,
ipaddress.IPv4Interface(16909060)._ip)
ipv4 = ipaddress.ip_network('1.2.3.4')
ipv6 = ipaddress.ip_network('2001:658:22a:cafe:200:0:0:1')
self.assertEqual(ipv4, ipaddress.ip_network(int(ipv4.network_address)))
self.assertEqual(ipv6, ipaddress.ip_network(int(ipv6.network_address)))
v6_int = 42540616829182469433547762482097946625
self.assertEqual(self.ipv6_interface._ip,
ipaddress.IPv6Interface(v6_int)._ip)
self.assertEqual(ipaddress.ip_network(self.ipv4_address._ip).version,
4)
self.assertEqual(ipaddress.ip_network(self.ipv6_address._ip).version,
6)
def testIpFromPacked(self):
address = ipaddress.ip_address
self.assertEqual(self.ipv4_interface._ip,
ipaddress.ip_interface(b'\x01\x02\x03\x04')._ip)
self.assertEqual(address('255.254.253.252'),
address(b'\xff\xfe\xfd\xfc'))
self.assertEqual(self.ipv6_interface.ip,
ipaddress.ip_interface(
b'\x20\x01\x06\x58\x02\x2a\xca\xfe'
b'\x02\x00\x00\x00\x00\x00\x00\x01').ip)
self.assertEqual(address('ffff:2:3:4:ffff::'),
address(b'\xff\xff\x00\x02\x00\x03\x00\x04' +
b'\xff\xff' + b'\x00' * 6))
self.assertEqual(address('::'),
address(b'\x00' * 16))
def testGetIp(self):
self.assertEqual(int(self.ipv4_interface.ip), 16909060)
self.assertEqual(str(self.ipv4_interface.ip), '1.2.3.4')
self.assertEqual(int(self.ipv6_interface.ip),
42540616829182469433547762482097946625)
self.assertEqual(str(self.ipv6_interface.ip),
'2001:658:22a:cafe:200::1')
def testGetNetmask(self):
self.assertEqual(int(self.ipv4_network.netmask), 4294967040)
self.assertEqual(str(self.ipv4_network.netmask), '255.255.255.0')
self.assertEqual(int(self.ipv6_network.netmask),
340282366920938463444927863358058659840)
self.assertEqual(self.ipv6_network.prefixlen, 64)
def testZeroNetmask(self):
ipv4_zero_netmask = ipaddress.IPv4Interface('1.2.3.4/0')
self.assertEqual(int(ipv4_zero_netmask.network.netmask), 0)
self.assertTrue(ipv4_zero_netmask.network._is_valid_netmask(
str(0)))
self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0'))
self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0.0.0.0'))
self.assertFalse(ipv4_zero_netmask._is_valid_netmask('invalid'))
ipv6_zero_netmask = ipaddress.IPv6Interface('::1/0')
self.assertEqual(int(ipv6_zero_netmask.network.netmask), 0)
self.assertTrue(ipv6_zero_netmask.network._is_valid_netmask(
str(0)))
def testIPv4NetAndHostmasks(self):
net = self.ipv4_network
self.assertFalse(net._is_valid_netmask('invalid'))
self.assertTrue(net._is_valid_netmask('128.128.128.128'))
self.assertFalse(net._is_valid_netmask('128.128.128.127'))
self.assertFalse(net._is_valid_netmask('128.128.128.255'))
self.assertTrue(net._is_valid_netmask('255.128.128.128'))
self.assertFalse(net._is_hostmask('invalid'))
self.assertTrue(net._is_hostmask('128.255.255.255'))
self.assertFalse(net._is_hostmask('255.255.255.255'))
self.assertFalse(net._is_hostmask('1.2.3.4'))
net = ipaddress.IPv4Network('127.0.0.0/0.0.0.255')
self.assertEqual(24, net.prefixlen)
def testGetBroadcast(self):
self.assertEqual(int(self.ipv4_network.broadcast_address), 16909311)
self.assertEqual(str(self.ipv4_network.broadcast_address), '1.2.3.255')
self.assertEqual(int(self.ipv6_network.broadcast_address),
42540616829182469451850391367731642367)
self.assertEqual(str(self.ipv6_network.broadcast_address),
'2001:658:22a:cafe:ffff:ffff:ffff:ffff')
def testGetPrefixlen(self):
self.assertEqual(self.ipv4_interface.network.prefixlen, 24)
self.assertEqual(self.ipv6_interface.network.prefixlen, 64)
def testGetSupernet(self):
self.assertEqual(self.ipv4_network.supernet().prefixlen, 23)
self.assertEqual(str(self.ipv4_network.supernet().network_address),
'1.2.2.0')
self.assertEqual(
ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(),
ipaddress.IPv4Network('0.0.0.0/0'))
self.assertEqual(self.ipv6_network.supernet().prefixlen, 63)
self.assertEqual(str(self.ipv6_network.supernet().network_address),
'2001:658:22a:cafe::')
self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(),
ipaddress.IPv6Network('::0/0'))
def testGetSupernet3(self):
self.assertEqual(self.ipv4_network.supernet(3).prefixlen, 21)
self.assertEqual(str(self.ipv4_network.supernet(3).network_address),
'1.2.0.0')
self.assertEqual(self.ipv6_network.supernet(3).prefixlen, 61)
self.assertEqual(str(self.ipv6_network.supernet(3).network_address),
'2001:658:22a:caf8::')
def testGetSupernet4(self):
self.assertRaises(ValueError, self.ipv4_network.supernet,
prefixlen_diff=2, new_prefix=1)
self.assertRaises(ValueError, self.ipv4_network.supernet,
new_prefix=25)
self.assertEqual(self.ipv4_network.supernet(prefixlen_diff=2),
self.ipv4_network.supernet(new_prefix=22))
self.assertRaises(ValueError, self.ipv6_network.supernet,
prefixlen_diff=2, new_prefix=1)
self.assertRaises(ValueError, self.ipv6_network.supernet,
new_prefix=65)
self.assertEqual(self.ipv6_network.supernet(prefixlen_diff=2),
self.ipv6_network.supernet(new_prefix=62))
def testHosts(self):
hosts = list(self.ipv4_network.hosts())
self.assertEqual(254, len(hosts))
self.assertEqual(ipaddress.IPv4Address('1.2.3.1'), hosts[0])
self.assertEqual(ipaddress.IPv4Address('1.2.3.254'), hosts[-1])
# special case where only 1 bit is left for address
self.assertEqual([ipaddress.IPv4Address('2.0.0.0'),
ipaddress.IPv4Address('2.0.0.1')],
list(ipaddress.ip_network('2.0.0.0/31').hosts()))
def testFancySubnetting(self):
self.assertEqual(sorted(self.ipv4_network.subnets(prefixlen_diff=3)),
sorted(self.ipv4_network.subnets(new_prefix=27)))
self.assertRaises(ValueError, list,
self.ipv4_network.subnets(new_prefix=23))
self.assertRaises(ValueError, list,
self.ipv4_network.subnets(prefixlen_diff=3,
new_prefix=27))
self.assertEqual(sorted(self.ipv6_network.subnets(prefixlen_diff=4)),
sorted(self.ipv6_network.subnets(new_prefix=68)))
self.assertRaises(ValueError, list,
self.ipv6_network.subnets(new_prefix=63))
self.assertRaises(ValueError, list,
self.ipv6_network.subnets(prefixlen_diff=4,
new_prefix=68))
def testGetSubnets(self):
self.assertEqual(list(self.ipv4_network.subnets())[0].prefixlen, 25)
self.assertEqual(str(list(
self.ipv4_network.subnets())[0].network_address),
'1.2.3.0')
self.assertEqual(str(list(
self.ipv4_network.subnets())[1].network_address),
'1.2.3.128')
self.assertEqual(list(self.ipv6_network.subnets())[0].prefixlen, 65)
def testGetSubnetForSingle32(self):
ip = ipaddress.IPv4Network('1.2.3.4/32')
subnets1 = [str(x) for x in ip.subnets()]
subnets2 = [str(x) for x in ip.subnets(2)]
self.assertEqual(subnets1, ['1.2.3.4/32'])
self.assertEqual(subnets1, subnets2)
def testGetSubnetForSingle128(self):
ip = ipaddress.IPv6Network('::1/128')
subnets1 = [str(x) for x in ip.subnets()]
subnets2 = [str(x) for x in ip.subnets(2)]
self.assertEqual(subnets1, ['::1/128'])
self.assertEqual(subnets1, subnets2)
def testSubnet2(self):
ips = [str(x) for x in self.ipv4_network.subnets(2)]
self.assertEqual(
ips,
['1.2.3.0/26', '1.2.3.64/26', '1.2.3.128/26', '1.2.3.192/26'])
ipsv6 = [str(x) for x in self.ipv6_network.subnets(2)]
self.assertEqual(
ipsv6,
['2001:658:22a:cafe::/66',
'2001:658:22a:cafe:4000::/66',
'2001:658:22a:cafe:8000::/66',
'2001:658:22a:cafe:c000::/66'])
def testSubnetFailsForLargeCidrDiff(self):
self.assertRaises(ValueError, list,
self.ipv4_interface.network.subnets(9))
self.assertRaises(ValueError, list,
self.ipv4_network.subnets(9))
self.assertRaises(ValueError, list,
self.ipv6_interface.network.subnets(65))
self.assertRaises(ValueError, list,
self.ipv6_network.subnets(65))
def testSupernetFailsForLargeCidrDiff(self):
self.assertRaises(ValueError,
self.ipv4_interface.network.supernet, 25)
self.assertRaises(ValueError,
self.ipv6_interface.network.supernet, 65)
def testSubnetFailsForNegativeCidrDiff(self):
self.assertRaises(ValueError, list,
self.ipv4_interface.network.subnets(-1))
self.assertRaises(ValueError, list,
self.ipv4_network.subnets(-1))
self.assertRaises(ValueError, list,
self.ipv6_interface.network.subnets(-1))
self.assertRaises(ValueError, list,
self.ipv6_network.subnets(-1))
def testGetNum_Addresses(self):
self.assertEqual(self.ipv4_network.num_addresses, 256)
self.assertEqual(list(self.ipv4_network.subnets())[0].num_addresses,
128)
self.assertEqual(self.ipv4_network.supernet().num_addresses, 512)
self.assertEqual(self.ipv6_network.num_addresses, 18446744073709551616)
self.assertEqual(list(self.ipv6_network.subnets())[0].num_addresses,
9223372036854775808)
self.assertEqual(self.ipv6_network.supernet().num_addresses,
36893488147419103232)
def testContains(self):
self.assertTrue(ipaddress.IPv4Interface('1.2.3.128/25') in
self.ipv4_network)
self.assertFalse(ipaddress.IPv4Interface('1.2.4.1/24') in
self.ipv4_network)
# We can test addresses and string as well.
addr1 = ipaddress.IPv4Address('1.2.3.37')
self.assertTrue(addr1 in self.ipv4_network)
# issue 61, bad network comparison on like-ip'd network objects
# with identical broadcast addresses.
self.assertFalse(ipaddress.IPv4Network('1.1.0.0/16').__contains__(
ipaddress.IPv4Network('1.0.0.0/15')))
def testNth(self):
self.assertEqual(str(self.ipv4_network[5]), '1.2.3.5')
self.assertRaises(IndexError, self.ipv4_network.__getitem__, 256)
self.assertEqual(str(self.ipv6_network[5]),
'2001:658:22a:cafe::5')
def testGetitem(self):
# http://code.google.com/p/ipaddr-py/issues/detail?id=15
addr = ipaddress.IPv4Network('172.31.255.128/255.255.255.240')
self.assertEqual(28, addr.prefixlen)
addr_list = list(addr)
self.assertEqual('172.31.255.128', str(addr_list[0]))
self.assertEqual('172.31.255.128', str(addr[0]))
self.assertEqual('172.31.255.143', str(addr_list[-1]))
self.assertEqual('172.31.255.143', str(addr[-1]))
self.assertEqual(addr_list[-1], addr[-1])
def testEqual(self):
self.assertTrue(self.ipv4_interface ==
ipaddress.IPv4Interface('1.2.3.4/24'))
self.assertFalse(self.ipv4_interface ==
ipaddress.IPv4Interface('1.2.3.4/23'))
self.assertFalse(self.ipv4_interface ==
ipaddress.IPv6Interface('::1.2.3.4/24'))
self.assertFalse(self.ipv4_interface == '')
self.assertFalse(self.ipv4_interface == [])
self.assertFalse(self.ipv4_interface == 2)
self.assertTrue(self.ipv6_interface ==
ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
self.assertFalse(self.ipv6_interface ==
ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
self.assertFalse(self.ipv6_interface ==
ipaddress.IPv4Interface('1.2.3.4/23'))
self.assertFalse(self.ipv6_interface == '')
self.assertFalse(self.ipv6_interface == [])
self.assertFalse(self.ipv6_interface == 2)
def testNotEqual(self):
self.assertFalse(self.ipv4_interface !=
ipaddress.IPv4Interface('1.2.3.4/24'))
self.assertTrue(self.ipv4_interface !=
ipaddress.IPv4Interface('1.2.3.4/23'))
self.assertTrue(self.ipv4_interface !=
ipaddress.IPv6Interface('::1.2.3.4/24'))
self.assertTrue(self.ipv4_interface != '')
self.assertTrue(self.ipv4_interface != [])
self.assertTrue(self.ipv4_interface != 2)
self.assertTrue(self.ipv4_address !=
ipaddress.IPv4Address('1.2.3.5'))
self.assertTrue(self.ipv4_address != '')
self.assertTrue(self.ipv4_address != [])
self.assertTrue(self.ipv4_address != 2)
self.assertFalse(self.ipv6_interface !=
ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
self.assertTrue(self.ipv6_interface !=
ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
self.assertTrue(self.ipv6_interface !=
ipaddress.IPv4Interface('1.2.3.4/23'))
self.assertTrue(self.ipv6_interface != '')
self.assertTrue(self.ipv6_interface != [])
self.assertTrue(self.ipv6_interface != 2)
self.assertTrue(self.ipv6_address !=
ipaddress.IPv4Address('1.2.3.4'))
self.assertTrue(self.ipv6_address != '')
self.assertTrue(self.ipv6_address != [])
self.assertTrue(self.ipv6_address != 2)
def testSlash32Constructor(self):
self.assertEqual(str(ipaddress.IPv4Interface(
'1.2.3.4/255.255.255.255')), '1.2.3.4/32')
def testSlash128Constructor(self):
self.assertEqual(str(ipaddress.IPv6Interface('::1/128')),
'::1/128')
def testSlash0Constructor(self):
self.assertEqual(str(ipaddress.IPv4Interface('1.2.3.4/0.0.0.0')),
'1.2.3.4/0')
def testCollapsing(self):
# test only IP addresses including some duplicates
ip1 = ipaddress.IPv4Address('1.1.1.0')
ip2 = ipaddress.IPv4Address('1.1.1.1')
ip3 = ipaddress.IPv4Address('1.1.1.2')
ip4 = ipaddress.IPv4Address('1.1.1.3')
ip5 = ipaddress.IPv4Address('1.1.1.4')
ip6 = ipaddress.IPv4Address('1.1.1.0')
# check that addreses are subsumed properly.
collapsed = ipaddress.collapse_addresses(
[ip1, ip2, ip3, ip4, ip5, ip6])
self.assertEqual(list(collapsed),
[ipaddress.IPv4Network('1.1.1.0/30'),
ipaddress.IPv4Network('1.1.1.4/32')])
# test a mix of IP addresses and networks including some duplicates
ip1 = ipaddress.IPv4Address('1.1.1.0')
ip2 = ipaddress.IPv4Address('1.1.1.1')
ip3 = ipaddress.IPv4Address('1.1.1.2')
ip4 = ipaddress.IPv4Address('1.1.1.3')
#ip5 = ipaddress.IPv4Interface('1.1.1.4/30')
#ip6 = ipaddress.IPv4Interface('1.1.1.4/30')
# check that addreses are subsumed properly.
collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3, ip4])
self.assertEqual(list(collapsed),
[ipaddress.IPv4Network('1.1.1.0/30')])
# test only IP networks
ip1 = ipaddress.IPv4Network('1.1.0.0/24')
ip2 = ipaddress.IPv4Network('1.1.1.0/24')
ip3 = ipaddress.IPv4Network('1.1.2.0/24')
ip4 = ipaddress.IPv4Network('1.1.3.0/24')
ip5 = ipaddress.IPv4Network('1.1.4.0/24')
# stored in no particular order b/c we want CollapseAddr to call
# [].sort
ip6 = ipaddress.IPv4Network('1.1.0.0/22')
# check that addreses are subsumed properly.
collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3, ip4, ip5,
ip6])
self.assertEqual(list(collapsed),
[ipaddress.IPv4Network('1.1.0.0/22'),
ipaddress.IPv4Network('1.1.4.0/24')])
# test that two addresses are supernet'ed properly
collapsed = ipaddress.collapse_addresses([ip1, ip2])
self.assertEqual(list(collapsed),
[ipaddress.IPv4Network('1.1.0.0/23')])
# test same IP networks
ip_same1 = ip_same2 = ipaddress.IPv4Network('1.1.1.1/32')
self.assertEqual(list(ipaddress.collapse_addresses(
[ip_same1, ip_same2])),
[ip_same1])
# test same IP addresses
ip_same1 = ip_same2 = ipaddress.IPv4Address('1.1.1.1')
self.assertEqual(list(ipaddress.collapse_addresses(
[ip_same1, ip_same2])),
[ipaddress.ip_network('1.1.1.1/32')])
ip1 = ipaddress.IPv6Network('2001::/100')
ip2 = ipaddress.IPv6Network('2001::/120')
ip3 = ipaddress.IPv6Network('2001::/96')
# test that ipv6 addresses are subsumed properly.
collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3])
self.assertEqual(list(collapsed), [ip3])
# the toejam test
addr_tuples = [
(ipaddress.ip_address('1.1.1.1'),
ipaddress.ip_address('::1')),
(ipaddress.IPv4Network('1.1.0.0/24'),
ipaddress.IPv6Network('2001::/120')),
(ipaddress.IPv4Network('1.1.0.0/32'),
ipaddress.IPv6Network('2001::/128')),
]
for ip1, ip2 in addr_tuples:
self.assertRaises(TypeError, ipaddress.collapse_addresses,
[ip1, ip2])
def testSummarizing(self):
#ip = ipaddress.ip_address
#ipnet = ipaddress.ip_network
summarize = ipaddress.summarize_address_range
ip1 = ipaddress.ip_address('1.1.1.0')
ip2 = ipaddress.ip_address('1.1.1.255')
# summarize works only for IPv4 & IPv6
class IPv7Address(ipaddress.IPv6Address):
@property
def version(self):
return 7
ip_invalid1 = IPv7Address('::1')
ip_invalid2 = IPv7Address('::1')
self.assertRaises(ValueError, list,
summarize(ip_invalid1, ip_invalid2))
# test that a summary over ip4 & ip6 fails
self.assertRaises(TypeError, list,
summarize(ip1, ipaddress.IPv6Address('::1')))
# test a /24 is summarized properly
self.assertEqual(list(summarize(ip1, ip2))[0],
ipaddress.ip_network('1.1.1.0/24'))
# test an IPv4 range that isn't on a network byte boundary
ip2 = ipaddress.ip_address('1.1.1.8')
self.assertEqual(list(summarize(ip1, ip2)),
[ipaddress.ip_network('1.1.1.0/29'),
ipaddress.ip_network('1.1.1.8')])
# all!
ip1 = ipaddress.IPv4Address(0)
ip2 = ipaddress.IPv4Address(ipaddress.IPv4Address._ALL_ONES)
self.assertEqual([ipaddress.IPv4Network('0.0.0.0/0')],
list(summarize(ip1, ip2)))
ip1 = ipaddress.ip_address('1::')
ip2 = ipaddress.ip_address('1:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
# test a IPv6 is sumamrized properly
self.assertEqual(list(summarize(ip1, ip2))[0],
ipaddress.ip_network('1::/16'))
# test an IPv6 range that isn't on a network byte boundary
ip2 = ipaddress.ip_address('2::')
self.assertEqual(list(summarize(ip1, ip2)),
[ipaddress.ip_network('1::/16'),
ipaddress.ip_network('2::/128')])
# test exception raised when first is greater than last
self.assertRaises(ValueError, list,
summarize(ipaddress.ip_address('1.1.1.0'),
ipaddress.ip_address('1.1.0.0')))
# test exception raised when first and last aren't IP addresses
self.assertRaises(TypeError, list,
summarize(ipaddress.ip_network('1.1.1.0'),
ipaddress.ip_network('1.1.0.0')))
self.assertRaises(TypeError, list,
summarize(ipaddress.ip_network('1.1.1.0'),
ipaddress.ip_network('1.1.0.0')))
# test exception raised when first and last are not same version
self.assertRaises(TypeError, list,
summarize(ipaddress.ip_address('::'),
ipaddress.ip_network('1.1.0.0')))
def testAddressComparison(self):
self.assertTrue(ipaddress.ip_address('1.1.1.1') <=
ipaddress.ip_address('1.1.1.1'))
self.assertTrue(ipaddress.ip_address('1.1.1.1') <=
ipaddress.ip_address('1.1.1.2'))
self.assertTrue(ipaddress.ip_address('::1') <=
ipaddress.ip_address('::1'))
self.assertTrue(ipaddress.ip_address('::1') <=
ipaddress.ip_address('::2'))
def testInterfaceComparison(self):
self.assertTrue(ipaddress.ip_interface('1.1.1.1') <=
ipaddress.ip_interface('1.1.1.1'))
self.assertTrue(ipaddress.ip_interface('1.1.1.1') <=
ipaddress.ip_interface('1.1.1.2'))
self.assertTrue(ipaddress.ip_interface('::1') <=
ipaddress.ip_interface('::1'))
self.assertTrue(ipaddress.ip_interface('::1') <=
ipaddress.ip_interface('::2'))
def testNetworkComparison(self):
# ip1 and ip2 have the same network address
ip1 = ipaddress.IPv4Network('1.1.1.0/24')
ip2 = ipaddress.IPv4Network('1.1.1.0/32')
ip3 = ipaddress.IPv4Network('1.1.2.0/24')
self.assertTrue(ip1 < ip3)
self.assertTrue(ip3 > ip2)
self.assertEqual(ip1.compare_networks(ip1), 0)
# if addresses are the same, sort by netmask
self.assertEqual(ip1.compare_networks(ip2), -1)
self.assertEqual(ip2.compare_networks(ip1), 1)
self.assertEqual(ip1.compare_networks(ip3), -1)
self.assertEqual(ip3.compare_networks(ip1), 1)
self.assertTrue(ip1._get_networks_key() < ip3._get_networks_key())
ip1 = ipaddress.IPv6Network('2001:2000::/96')
ip2 = ipaddress.IPv6Network('2001:2001::/96')
ip3 = ipaddress.IPv6Network('2001:ffff:2000::/96')
self.assertTrue(ip1 < ip3)
self.assertTrue(ip3 > ip2)
self.assertEqual(ip1.compare_networks(ip3), -1)
self.assertTrue(ip1._get_networks_key() < ip3._get_networks_key())
# Test comparing different protocols.
# Should always raise a TypeError.
self.assertRaises(TypeError,
self.ipv4_network.compare_networks,
self.ipv6_network)
ipv6 = ipaddress.IPv6Interface('::/0')
ipv4 = ipaddress.IPv4Interface('0.0.0.0/0')
self.assertRaises(TypeError, ipv4.__lt__, ipv6)
self.assertRaises(TypeError, ipv4.__gt__, ipv6)
self.assertRaises(TypeError, ipv6.__lt__, ipv4)
self.assertRaises(TypeError, ipv6.__gt__, ipv4)
# Regression test for issue 19.
ip1 = ipaddress.ip_network('10.1.2.128/25')
self.assertFalse(ip1 < ip1)
self.assertFalse(ip1 > ip1)
ip2 = ipaddress.ip_network('10.1.3.0/24')
self.assertTrue(ip1 < ip2)
self.assertFalse(ip2 < ip1)
self.assertFalse(ip1 > ip2)
self.assertTrue(ip2 > ip1)
ip3 = ipaddress.ip_network('10.1.3.0/25')
self.assertTrue(ip2 < ip3)
self.assertFalse(ip3 < ip2)
self.assertFalse(ip2 > ip3)
self.assertTrue(ip3 > ip2)
# Regression test for issue 28.
ip1 = ipaddress.ip_network('10.10.10.0/31')
ip2 = ipaddress.ip_network('10.10.10.0')
ip3 = ipaddress.ip_network('10.10.10.2/31')
ip4 = ipaddress.ip_network('10.10.10.2')
sorted = [ip1, ip2, ip3, ip4]
unsorted = [ip2, ip4, ip1, ip3]
unsorted.sort()
self.assertEqual(sorted, unsorted)
unsorted = [ip4, ip1, ip3, ip2]
unsorted.sort()
self.assertEqual(sorted, unsorted)
self.assertRaises(TypeError, ip1.__lt__,
ipaddress.ip_address('10.10.10.0'))
self.assertRaises(TypeError, ip2.__lt__,
ipaddress.ip_address('10.10.10.0'))
# <=, >=
self.assertTrue(ipaddress.ip_network('1.1.1.1') <=
ipaddress.ip_network('1.1.1.1'))
self.assertTrue(ipaddress.ip_network('1.1.1.1') <=
ipaddress.ip_network('1.1.1.2'))
self.assertFalse(ipaddress.ip_network('1.1.1.2') <=
ipaddress.ip_network('1.1.1.1'))
self.assertTrue(ipaddress.ip_network('::1') <=
ipaddress.ip_network('::1'))
self.assertTrue(ipaddress.ip_network('::1') <=
ipaddress.ip_network('::2'))
self.assertFalse(ipaddress.ip_network('::2') <=
ipaddress.ip_network('::1'))
def testStrictNetworks(self):
self.assertRaises(ValueError, ipaddress.ip_network, '192.168.1.1/24')
self.assertRaises(ValueError, ipaddress.ip_network, '::1/120')
def testOverlaps(self):
other = ipaddress.IPv4Network('1.2.3.0/30')
other2 = ipaddress.IPv4Network('1.2.2.0/24')
other3 = ipaddress.IPv4Network('1.2.2.64/26')
self.assertTrue(self.ipv4_network.overlaps(other))
self.assertFalse(self.ipv4_network.overlaps(other2))
self.assertTrue(other2.overlaps(other3))
def testEmbeddedIpv4(self):
ipv4_string = '192.168.0.1'
ipv4 = ipaddress.IPv4Interface(ipv4_string)
v4compat_ipv6 = ipaddress.IPv6Interface('::%s' % ipv4_string)
self.assertEqual(int(v4compat_ipv6.ip), int(ipv4.ip))
v4mapped_ipv6 = ipaddress.IPv6Interface('::ffff:%s' % ipv4_string)
self.assertNotEqual(v4mapped_ipv6.ip, ipv4.ip)
self.assertRaises(ipaddress.AddressValueError, ipaddress.IPv6Interface,
'2001:1.1.1.1:1.1.1.1')
# Issue 67: IPv6 with embedded IPv4 address not recognized.
def testIPv6AddressTooLarge(self):
# RFC4291 2.5.5.2
self.assertEqual(ipaddress.ip_address('::FFFF:192.0.2.1'),
ipaddress.ip_address('::FFFF:c000:201'))
# RFC4291 2.2 (part 3) x::d.d.d.d
self.assertEqual(ipaddress.ip_address('FFFF::192.0.2.1'),
ipaddress.ip_address('FFFF::c000:201'))
def testIPVersion(self):
self.assertEqual(self.ipv4_address.version, 4)
self.assertEqual(self.ipv6_address.version, 6)
def testMaxPrefixLength(self):
self.assertEqual(self.ipv4_interface.max_prefixlen, 32)
self.assertEqual(self.ipv6_interface.max_prefixlen, 128)
def testPacked(self):
self.assertEqual(self.ipv4_address.packed,
b'\x01\x02\x03\x04')
self.assertEqual(ipaddress.IPv4Interface('255.254.253.252').packed,
b'\xff\xfe\xfd\xfc')
self.assertEqual(self.ipv6_address.packed,
b'\x20\x01\x06\x58\x02\x2a\xca\xfe'
b'\x02\x00\x00\x00\x00\x00\x00\x01')
self.assertEqual(ipaddress.IPv6Interface('ffff:2:3:4:ffff::').packed,
b'\xff\xff\x00\x02\x00\x03\x00\x04\xff\xff'
+ b'\x00' * 6)
self.assertEqual(ipaddress.IPv6Interface('::1:0:0:0:0').packed,
b'\x00' * 6 + b'\x00\x01' + b'\x00' * 8)
def testIpStrFromPrefixlen(self):
ipv4 = ipaddress.IPv4Interface('1.2.3.4/24')
self.assertEqual(ipv4._ip_string_from_prefix(), '255.255.255.0')
self.assertEqual(ipv4._ip_string_from_prefix(28), '255.255.255.240')
def testIpType(self):
ipv4net = ipaddress.ip_network('1.2.3.4')
ipv4addr = ipaddress.ip_address('1.2.3.4')
ipv6net = ipaddress.ip_network('::1.2.3.4')
ipv6addr = ipaddress.ip_address('::1.2.3.4')
self.assertEqual(ipaddress.IPv4Network, type(ipv4net))
self.assertEqual(ipaddress.IPv4Address, type(ipv4addr))
self.assertEqual(ipaddress.IPv6Network, type(ipv6net))
self.assertEqual(ipaddress.IPv6Address, type(ipv6addr))
def testReservedIpv4(self):
# test networks
self.assertEqual(True, ipaddress.ip_interface(
'224.1.1.1/31').is_multicast)
self.assertEqual(False, ipaddress.ip_network('240.0.0.0').is_multicast)
self.assertEqual(True, ipaddress.ip_network('240.0.0.0').is_reserved)
self.assertEqual(True, ipaddress.ip_interface(
'192.168.1.1/17').is_private)
self.assertEqual(False, ipaddress.ip_network('192.169.0.0').is_private)
self.assertEqual(True, ipaddress.ip_network(
'10.255.255.255').is_private)
self.assertEqual(False, ipaddress.ip_network('11.0.0.0').is_private)
self.assertEqual(False, ipaddress.ip_network('11.0.0.0').is_reserved)
self.assertEqual(True, ipaddress.ip_network(
'172.31.255.255').is_private)
self.assertEqual(False, ipaddress.ip_network('172.32.0.0').is_private)
self.assertEqual(True,
ipaddress.ip_network('169.254.1.0/24').is_link_local)
self.assertEqual(True,
ipaddress.ip_interface(
'169.254.100.200/24').is_link_local)
self.assertEqual(False,
ipaddress.ip_interface(
'169.255.100.200/24').is_link_local)
self.assertEqual(True,
ipaddress.ip_network(
'127.100.200.254/32').is_loopback)
self.assertEqual(True, ipaddress.ip_network(
'127.42.0.0/16').is_loopback)
self.assertEqual(False, ipaddress.ip_network('128.0.0.0').is_loopback)
# test addresses
self.assertEqual(True, ipaddress.ip_address('0.0.0.0').is_unspecified)
self.assertEqual(True, ipaddress.ip_address('224.1.1.1').is_multicast)
self.assertEqual(False, ipaddress.ip_address('240.0.0.0').is_multicast)
self.assertEqual(True, ipaddress.ip_address('240.0.0.1').is_reserved)
self.assertEqual(False,
ipaddress.ip_address('239.255.255.255').is_reserved)
self.assertEqual(True, ipaddress.ip_address('192.168.1.1').is_private)
self.assertEqual(False, ipaddress.ip_address('192.169.0.0').is_private)
self.assertEqual(True, ipaddress.ip_address(
'10.255.255.255').is_private)
self.assertEqual(False, ipaddress.ip_address('11.0.0.0').is_private)
self.assertEqual(True, ipaddress.ip_address(
'172.31.255.255').is_private)
self.assertEqual(False, ipaddress.ip_address('172.32.0.0').is_private)
self.assertEqual(True,
ipaddress.ip_address('169.254.100.200').is_link_local)
self.assertEqual(False,
ipaddress.ip_address('169.255.100.200').is_link_local)
self.assertEqual(True,
ipaddress.ip_address('127.100.200.254').is_loopback)
self.assertEqual(True, ipaddress.ip_address('127.42.0.0').is_loopback)
self.assertEqual(False, ipaddress.ip_address('128.0.0.0').is_loopback)
self.assertEqual(True, ipaddress.ip_network('0.0.0.0').is_unspecified)
def testReservedIpv6(self):
self.assertEqual(True, ipaddress.ip_network('ffff::').is_multicast)
self.assertEqual(True, ipaddress.ip_network(2**128 - 1).is_multicast)
self.assertEqual(True, ipaddress.ip_network('ff00::').is_multicast)
self.assertEqual(False, ipaddress.ip_network('fdff::').is_multicast)
self.assertEqual(True, ipaddress.ip_network('fecf::').is_site_local)
self.assertEqual(True, ipaddress.ip_network(
'feff:ffff:ffff:ffff::').is_site_local)
self.assertEqual(False, ipaddress.ip_network(
'fbf:ffff::').is_site_local)
self.assertEqual(False, ipaddress.ip_network('ff00::').is_site_local)
self.assertEqual(True, ipaddress.ip_network('fc00::').is_private)
self.assertEqual(True, ipaddress.ip_network(
'fc00:ffff:ffff:ffff::').is_private)
self.assertEqual(False, ipaddress.ip_network('fbff:ffff::').is_private)
self.assertEqual(False, ipaddress.ip_network('fe00::').is_private)
self.assertEqual(True, ipaddress.ip_network('fea0::').is_link_local)
self.assertEqual(True, ipaddress.ip_network(
'febf:ffff::').is_link_local)
self.assertEqual(False, ipaddress.ip_network(
'fe7f:ffff::').is_link_local)
self.assertEqual(False, ipaddress.ip_network('fec0::').is_link_local)
self.assertEqual(True, ipaddress.ip_interface('0:0::0:01').is_loopback)
self.assertEqual(False, ipaddress.ip_interface('::1/127').is_loopback)
self.assertEqual(False, ipaddress.ip_network('::').is_loopback)
self.assertEqual(False, ipaddress.ip_network('::2').is_loopback)
self.assertEqual(True, ipaddress.ip_network('0::0').is_unspecified)
self.assertEqual(False, ipaddress.ip_network('::1').is_unspecified)
self.assertEqual(False, ipaddress.ip_network('::/127').is_unspecified)
# test addresses
self.assertEqual(True, ipaddress.ip_address('ffff::').is_multicast)
self.assertEqual(True, ipaddress.ip_address(2**128 - 1).is_multicast)
self.assertEqual(True, ipaddress.ip_address('ff00::').is_multicast)
self.assertEqual(False, ipaddress.ip_address('fdff::').is_multicast)
self.assertEqual(True, ipaddress.ip_address('fecf::').is_site_local)
self.assertEqual(True, ipaddress.ip_address(
'feff:ffff:ffff:ffff::').is_site_local)
self.assertEqual(False, ipaddress.ip_address(
'fbf:ffff::').is_site_local)
self.assertEqual(False, ipaddress.ip_address('ff00::').is_site_local)
self.assertEqual(True, ipaddress.ip_address('fc00::').is_private)
self.assertEqual(True, ipaddress.ip_address(
'fc00:ffff:ffff:ffff::').is_private)
self.assertEqual(False, ipaddress.ip_address('fbff:ffff::').is_private)
self.assertEqual(False, ipaddress.ip_address('fe00::').is_private)
self.assertEqual(True, ipaddress.ip_address('fea0::').is_link_local)
self.assertEqual(True, ipaddress.ip_address(
'febf:ffff::').is_link_local)
self.assertEqual(False, ipaddress.ip_address(
'fe7f:ffff::').is_link_local)
self.assertEqual(False, ipaddress.ip_address('fec0::').is_link_local)
self.assertEqual(True, ipaddress.ip_address('0:0::0:01').is_loopback)
self.assertEqual(True, ipaddress.ip_address('::1').is_loopback)
self.assertEqual(False, ipaddress.ip_address('::2').is_loopback)
self.assertEqual(True, ipaddress.ip_address('0::0').is_unspecified)
self.assertEqual(False, ipaddress.ip_address('::1').is_unspecified)
# some generic IETF reserved addresses
self.assertEqual(True, ipaddress.ip_address('100::').is_reserved)
self.assertEqual(True, ipaddress.ip_network('4000::1/128').is_reserved)
def testIpv4Mapped(self):
self.assertEqual(
ipaddress.ip_address('::ffff:192.168.1.1').ipv4_mapped,
ipaddress.ip_address('192.168.1.1'))
self.assertEqual(ipaddress.ip_address('::c0a8:101').ipv4_mapped, None)
self.assertEqual(ipaddress.ip_address('::ffff:c0a8:101').ipv4_mapped,
ipaddress.ip_address('192.168.1.1'))
def testAddrExclude(self):
addr1 = ipaddress.ip_network('10.1.1.0/24')
addr2 = ipaddress.ip_network('10.1.1.0/26')
addr3 = ipaddress.ip_network('10.2.1.0/24')
addr4 = ipaddress.ip_address('10.1.1.0')
addr5 = ipaddress.ip_network('2001:db8::0/32')
self.assertEqual(sorted(list(addr1.address_exclude(addr2))),
[ipaddress.ip_network('10.1.1.64/26'),
ipaddress.ip_network('10.1.1.128/25')])
self.assertRaises(ValueError, list, addr1.address_exclude(addr3))
self.assertRaises(TypeError, list, addr1.address_exclude(addr4))
self.assertRaises(TypeError, list, addr1.address_exclude(addr5))
self.assertEqual(list(addr1.address_exclude(addr1)), [])
def testHash(self):
self.assertEqual(hash(ipaddress.ip_interface('10.1.1.0/24')),
hash(ipaddress.ip_interface('10.1.1.0/24')))
self.assertEqual(hash(ipaddress.ip_network('10.1.1.0/24')),
hash(ipaddress.ip_network('10.1.1.0/24')))
self.assertEqual(hash(ipaddress.ip_address('10.1.1.0')),
hash(ipaddress.ip_address('10.1.1.0')))
# i70
self.assertEqual(hash(ipaddress.ip_address('1.2.3.4')),
hash(ipaddress.ip_address(
int(ipaddress.ip_address('1.2.3.4')._ip))))
ip1 = ipaddress.ip_address('10.1.1.0')
ip2 = ipaddress.ip_address('1::')
dummy = {}
dummy[self.ipv4_address] = None
dummy[self.ipv6_address] = None
dummy[ip1] = None
dummy[ip2] = None
self.assertTrue(self.ipv4_address in dummy)
self.assertTrue(ip2 in dummy)
def testIPBases(self):
net = self.ipv4_network
self.assertEqual('1.2.3.0/24', net.compressed)
self.assertEqual(
net._ip_int_from_prefix(24),
net._ip_int_from_prefix(None))
net = self.ipv6_network
self.assertRaises(ValueError, net._string_from_ip_int, 2**128 + 1)
self.assertEqual(
self.ipv6_address._string_from_ip_int(self.ipv6_address._ip),
self.ipv6_address._string_from_ip_int(None))
def testIPv6NetworkHelpers(self):
net = self.ipv6_network
self.assertEqual('2001:658:22a:cafe::/64', net.with_prefixlen)
self.assertEqual('2001:658:22a:cafe::/ffff:ffff:ffff:ffff::',
net.with_netmask)
self.assertEqual('2001:658:22a:cafe::/::ffff:ffff:ffff:ffff',
net.with_hostmask)
self.assertEqual('2001:658:22a:cafe::/64', str(net))
def testIPv4NetworkHelpers(self):
net = self.ipv4_network
self.assertEqual('1.2.3.0/24', net.with_prefixlen)
self.assertEqual('1.2.3.0/255.255.255.0', net.with_netmask)
self.assertEqual('1.2.3.0/0.0.0.255', net.with_hostmask)
self.assertEqual('1.2.3.0/24', str(net))
def testCopyConstructor(self):
addr1 = ipaddress.ip_network('10.1.1.0/24')
addr2 = ipaddress.ip_network(addr1)
addr3 = ipaddress.ip_interface('2001:658:22a:cafe:200::1/64')
addr4 = ipaddress.ip_interface(addr3)
addr5 = ipaddress.IPv4Address('1.1.1.1')
addr6 = ipaddress.IPv6Address('2001:658:22a:cafe:200::1')
self.assertEqual(addr1, addr2)
self.assertEqual(addr3, addr4)
self.assertEqual(addr5, ipaddress.IPv4Address(addr5))
self.assertEqual(addr6, ipaddress.IPv6Address(addr6))
def testCompressIPv6Address(self):
test_addresses = {
'1:2:3:4:5:6:7:8': '1:2:3:4:5:6:7:8/128',
'2001:0:0:4:0:0:0:8': '2001:0:0:4::8/128',
'2001:0:0:4:5:6:7:8': '2001::4:5:6:7:8/128',
'2001:0:3:4:5:6:7:8': '2001:0:3:4:5:6:7:8/128',
'2001:0:3:4:5:6:7:8': '2001:0:3:4:5:6:7:8/128',
'0:0:3:0:0:0:0:ffff': '0:0:3::ffff/128',
'0:0:0:4:0:0:0:ffff': '::4:0:0:0:ffff/128',
'0:0:0:0:5:0:0:ffff': '::5:0:0:ffff/128',
'1:0:0:4:0:0:7:8': '1::4:0:0:7:8/128',
'0:0:0:0:0:0:0:0': '::/128',
'0:0:0:0:0:0:0:0/0': '::/0',
'0:0:0:0:0:0:0:1': '::1/128',
'2001:0658:022a:cafe:0000:0000:0000:0000/66':
'2001:658:22a:cafe::/66',
'::1.2.3.4': '::102:304/128',
'1:2:3:4:5:ffff:1.2.3.4': '1:2:3:4:5:ffff:102:304/128',
'::7:6:5:4:3:2:1': '0:7:6:5:4:3:2:1/128',
'::7:6:5:4:3:2:0': '0:7:6:5:4:3:2:0/128',
'7:6:5:4:3:2:1::': '7:6:5:4:3:2:1:0/128',
'0:6:5:4:3:2:1::': '0:6:5:4:3:2:1:0/128',
}
for uncompressed, compressed in list(test_addresses.items()):
self.assertEqual(compressed, str(ipaddress.IPv6Interface(
uncompressed)))
def testExplodeShortHandIpStr(self):
addr1 = ipaddress.IPv6Interface('2001::1')
addr2 = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
addr3 = ipaddress.IPv6Network('2001::/96')
addr4 = ipaddress.IPv4Address('192.168.178.1')
self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0001/128',
addr1.exploded)
self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0001/128',
ipaddress.IPv6Interface('::1/128').exploded)
# issue 77
self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1',
addr2.exploded)
self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0000/96',
addr3.exploded)
self.assertEqual('192.168.178.1', addr4.exploded)
def testIntRepresentation(self):
self.assertEqual(16909060, int(self.ipv4_address))
self.assertEqual(42540616829182469433547762482097946625,
int(self.ipv6_address))
def testForceVersion(self):
self.assertEqual(ipaddress.ip_network(1).version, 4)
self.assertEqual(ipaddress.IPv6Network(1).version, 6)
def testWithStar(self):
self.assertEqual(self.ipv4_interface.with_prefixlen, "1.2.3.4/24")
self.assertEqual(self.ipv4_interface.with_netmask,
"1.2.3.4/255.255.255.0")
self.assertEqual(self.ipv4_interface.with_hostmask,
"1.2.3.4/0.0.0.255")
self.assertEqual(self.ipv6_interface.with_prefixlen,
'2001:658:22a:cafe:200::1/64')
self.assertEqual(self.ipv6_interface.with_netmask,
'2001:658:22a:cafe:200::1/ffff:ffff:ffff:ffff::')
# this probably don't make much sense, but it's included for
# compatibility with ipv4
self.assertEqual(self.ipv6_interface.with_hostmask,
'2001:658:22a:cafe:200::1/::ffff:ffff:ffff:ffff')
def testNetworkElementCaching(self):
# V4 - make sure we're empty
self.assertFalse('network_address' in self.ipv4_network._cache)
self.assertFalse('broadcast_address' in self.ipv4_network._cache)
self.assertFalse('hostmask' in self.ipv4_network._cache)
# V4 - populate and test
self.assertEqual(self.ipv4_network.network_address,
ipaddress.IPv4Address('1.2.3.0'))
self.assertEqual(self.ipv4_network.broadcast_address,
ipaddress.IPv4Address('1.2.3.255'))
self.assertEqual(self.ipv4_network.hostmask,
ipaddress.IPv4Address('0.0.0.255'))
# V4 - check we're cached
self.assertTrue('broadcast_address' in self.ipv4_network._cache)
self.assertTrue('hostmask' in self.ipv4_network._cache)
# V6 - make sure we're empty
self.assertFalse('broadcast_address' in self.ipv6_network._cache)
self.assertFalse('hostmask' in self.ipv6_network._cache)
# V6 - populate and test
self.assertEqual(self.ipv6_network.network_address,
ipaddress.IPv6Address('2001:658:22a:cafe::'))
self.assertEqual(self.ipv6_interface.network.network_address,
ipaddress.IPv6Address('2001:658:22a:cafe::'))
self.assertEqual(
self.ipv6_network.broadcast_address,
ipaddress.IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff'))
self.assertEqual(self.ipv6_network.hostmask,
ipaddress.IPv6Address('::ffff:ffff:ffff:ffff'))
self.assertEqual(
self.ipv6_interface.network.broadcast_address,
ipaddress.IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff'))
self.assertEqual(self.ipv6_interface.network.hostmask,
ipaddress.IPv6Address('::ffff:ffff:ffff:ffff'))
# V6 - check we're cached
self.assertTrue('broadcast_address' in self.ipv6_network._cache)
self.assertTrue('hostmask' in self.ipv6_network._cache)
self.assertTrue(
'broadcast_address' in self.ipv6_interface.network._cache)
self.assertTrue('hostmask' in self.ipv6_interface.network._cache)
def testTeredo(self):
# stolen from wikipedia
server = ipaddress.IPv4Address('65.54.227.120')
client = ipaddress.IPv4Address('192.0.2.45')
teredo_addr = '2001:0000:4136:e378:8000:63bf:3fff:fdd2'
self.assertEqual((server, client),
ipaddress.ip_address(teredo_addr).teredo)
bad_addr = '2000::4136:e378:8000:63bf:3fff:fdd2'
self.assertFalse(ipaddress.ip_address(bad_addr).teredo)
bad_addr = '2001:0001:4136:e378:8000:63bf:3fff:fdd2'
self.assertFalse(ipaddress.ip_address(bad_addr).teredo)
# i77
teredo_addr = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
self.assertEqual((ipaddress.IPv4Address('94.245.121.253'),
ipaddress.IPv4Address('95.26.244.94')),
teredo_addr.teredo)
def testsixtofour(self):
sixtofouraddr = ipaddress.ip_address('2002:ac1d:2d64::1')
bad_addr = ipaddress.ip_address('2000:ac1d:2d64::1')
self.assertEqual(ipaddress.IPv4Address('172.29.45.100'),
sixtofouraddr.sixtofour)
self.assertFalse(bad_addr.sixtofour)
if __name__ == '__main__':
unittest.main() | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Author: Seunghyun Yoo (shyoo1st@cs.ucla.edu)
"""
import bisect
import pickle
import enum
from . import selector, util, tokenizer, tree
class TokenType(enum.Enum):
VARIANT = 0
NOT_UNIQUE_INVARIANT = 1
UNIQUE_INVARIANT = 2
def expand_segment(pivots, tokens_of, tentative_decision, rightward):
"""
This function tries to expand a segment by looking at adjacent tokens from pivot points.
If the adjacent tokens have the same value, they can be regarded as invariant tokens (they would get promoted).
:param pivots:
:param tokens_of:
:param tentative_decision:
:param rightward:
:return:
"""
current_pivots = pivots
is_valid_pivots = True
while is_valid_pivots:
if rightward:
current_pivots = util.get_next_line(current_pivots)
else:
current_pivots = util.get_prev_line(current_pivots)
# First of all, pivot points should be in the valid range.
for doc_index in range(len(tokens_of)):
if not util.in_range(current_pivots[doc_index], 0, len(tokens_of[doc_index])):
is_valid_pivots = False
break
if is_valid_pivots:
# In order to expand the segment, every token must have the same value.
temp_token = None
is_identical = True
for doc_index in range(len(tokens_of)):
current_token = tokens_of[doc_index][current_pivots[doc_index]]
if temp_token is None:
temp_token = current_token
else:
if temp_token != current_token:
is_identical = False
break
# Let's stop at the moment that invariant tokens are found.
is_all_variant = True
for doc_index in range(len(tokens_of)):
current_type = tentative_decision[doc_index][current_pivots[doc_index]]
if current_type != TokenType.VARIANT:
is_all_variant = False
break
if is_identical and is_all_variant:
for doc_index in range(len(tokens_of)):
# Type promotion
tentative_decision[doc_index][current_pivots[doc_index]] = TokenType.NOT_UNIQUE_INVARIANT
else:
break
def find_next_candidates(tokens_of, tokens_with_loc, current_line):
"""
To find the next candidates from the current line
:param tokens_of:
:param tokens_with_loc: an associative array containing key-value pairs of each token and its locations
:param current_line:
:return:
"""
candidates = []
for doc_index, tokens in enumerate(tokens_of):
if current_line[doc_index] < len(tokens):
token_current = tokens[current_line[doc_index]]
hash_current = util.compute_hash(token_current)
is_data_token = False
for another_doc_index, _ in enumerate(tokens_of):
if util.compute_freq(tokens_with_loc[hash_current][another_doc_index], current_line[another_doc_index]) == 0:
is_data_token = True
break
if is_data_token:
# Ignoring a data token (variant) as it doesn't appear in other documents.
continue
invariant_token = list(current_line)
for another_doc_index, _ in enumerate(tokens_of):
locs = tokens_with_loc[hash_current][another_doc_index]
# There must be at least one element.
next_token_idx = bisect.bisect_left(locs, current_line[another_doc_index])
next_token_pos = locs[next_token_idx]
invariant_token[another_doc_index] = next_token_pos
tuple_invariant_token = tuple(invariant_token)
if tuple_invariant_token not in candidates:
candidates.append(tuple_invariant_token)
return candidates
def find_unique_invariants(tokens_of, tokens_with_loc, current_line):
"""
In order to find the candidate tree quickly
:param tokens_of:
:param tokens_with_loc:
:param current_line:
:return:
"""
candidate_tree = tree.nary_tree() # the root node
candidate_tree.set_value("<root>")
node_cache = dict()
working_set = list()
working_set.append((current_line, "<root>"))
node_cache["<root>"] = candidate_tree
while working_set:
current_line, origin_line = working_set[0]
working_set.pop(0)
# current_line must be in the range of documents
is_out_of_range = False
for doc_index, tokens in enumerate(tokens_of):
if current_line[doc_index] >= len(tokens):
is_out_of_range = True
break
if is_out_of_range:
continue
is_detected = False
candidates = find_next_candidates(tokens_of, tokens_with_loc, current_line)
# print("cur ", current_line)
# print("candidates ", candidates)
for candidate in candidates:
freq = []
for doc_index, token_index in enumerate(candidate):
token_hash = util.compute_hash(tokens_of[doc_index][token_index])
token_freq = util.compute_freq(tokens_with_loc[token_hash][doc_index], token_index)
freq.append(token_freq)
# print(candidate, freq)
if all(map(lambda x:x == 1, freq)): # only for unique invariant tokens
if candidate not in node_cache: # do not recompute the path that was already searched
new_branch = tree.nary_tree()
new_branch.set_value(candidate)
node_cache[candidate] = new_branch
is_detected = True
working_set.append((util.get_next_line(candidate), candidate))
node_cache[origin_line].insert(node_cache[candidate])
# print("{} -> {}".format(origin_line, candidate))
if not is_detected:
# print("***")
working_set.append((util.get_next_line(current_line), origin_line))
# print(working_set)
# input()
# Getting the longest path
working_set = list()
working_set.append((candidate_tree, list()))
current_tree = None
temp = list()
while working_set:
current_tree, current_path = working_set[0]
working_set.pop(0)
if current_tree.get_value() != "<root>":
current_path.append(current_tree.get_value())
if not current_tree.get_children():
temp.append(current_path)
else:
for child in current_tree.get_children():
working_set.append((child, list(current_path)))
# print(temp)
return temp
def compute_tokens_with_loc(tokens_of):
"""
To make an associative array containing a pair of a token hash and its locations. (cache)
:param tokens_of:
:return:
"""
tokens_with_loc = {}
for doc_index, tokens in enumerate(tokens_of):
for token_index, token in enumerate(tokens):
token_hash = util.compute_hash(token)
if token_hash not in tokens_with_loc:
tokens_with_loc[token_hash] = util.make_empty_array(len(tokens_of))
tokens_with_loc[token_hash][doc_index].append(token_index)
return tokens_with_loc
def invariant_matching_algorithm(documents):
"""
Matching segments by referring to unique invariant tokens
This algorithm can be applied to documents recursively.
:param documents:
:return: a pair of invariant segment text and tentative decisions, which are for debug purpose.
"""
num_of_docs = len(documents)
# Tokenize raw documents
tokens_of = []
for doc_index, raw_html in enumerate(documents):
tokens = tokenizer.Tokenizer.tokenize("html", raw_html)
tokens_of.append(tokens)
# Cache each token's locations
tokens_with_loc = compute_tokens_with_loc(tokens_of)
# Search unique invariant tokens and construct a candidate tree
candidates = find_unique_invariants(tokens_of, tokens_with_loc, (0,) * num_of_docs)
# Choose the best one from the candidate tree (almost optimal)
max_length_of = 0
best_candidate = None
for candidate in candidates:
if max_length_of < len(candidate):
max_length_of = len(candidate)
best_candidate = candidate
tentative_decision = util.make_empty_array(num_of_docs)
for doc_index, tokens in enumerate(tokens_of):
tentative_decision[doc_index] = [TokenType.VARIANT] * len(tokens)
if best_candidate is None:
return [], tentative_decision
for c in best_candidate:
for doc_index, loc in enumerate(c):
tentative_decision[doc_index][loc] = TokenType.NOT_UNIQUE_INVARIANT
expand_segment(c, tokens_of, tentative_decision, True)
expand_segment(c, tokens_of, tentative_decision, False)
for c in best_candidate:
for doc_index, loc in enumerate(c):
tentative_decision[doc_index][loc] = TokenType.UNIQUE_INVARIANT
# Segmentation
is_searching = True
invariant_tokens = list()
invariant_segments_text = list()
current_loc = [0] * num_of_docs
while is_searching:
for doc_index in range(num_of_docs):
while tentative_decision[doc_index][current_loc[doc_index]] == TokenType.VARIANT:
if util.in_range(current_loc[doc_index], 0, len(tokens_of[doc_index]) - 1):
current_loc[doc_index] += 1 # Skipping variant tokens (they can't be a part of the template)
else:
is_searching = False
break
while is_searching:
is_invariant = True
for doc_index in range(num_of_docs):
if tentative_decision[doc_index][current_loc[doc_index]] == TokenType.VARIANT:
is_invariant = False
break
if is_invariant:
invariant_tokens.append(tokens_of[0][current_loc[0]])
for doc_index in range(num_of_docs):
current_loc[doc_index] += 1
is_in_range = True
for doc_index in range(num_of_docs):
if not util.in_range(current_loc[doc_index], 0, len(tokens_of[doc_index])):
is_in_range = False
break
if not is_in_range:
is_searching = False
break
else:
invariant_segments_text.append("".join(invariant_tokens))
invariant_tokens = list()
break
if len(invariant_tokens) > 0:
invariant_segments_text.append("".join(invariant_tokens))
# __print_decision(tentative_decision)
return invariant_segments_text, tentative_decision
def __print_decision(tentative_decision):
print("Decision")
for doc_index, decisions in enumerate(tentative_decision):
print("Doc {}:".format(doc_index), end="")
for decision in decisions:
if decision == TokenType.VARIANT:
print ("\033[41m\033[1;37m.\033[0m", end="")
elif decision == TokenType.NOT_UNIQUE_INVARIANT:
print ("\033[44m\033[37m.\033[0m", end="")
elif decision == TokenType.UNIQUE_INVARIANT:
print ("\033[44m\033[1;37mi\033[0m", end="")
print("")
def generate(documents, prev_text = []):
"""
To get the template recursively
:param documents:
:param prev_text:
:return:
"""
if not documents:
return None
text, _ = invariant_matching_algorithm(documents)
data_segments = list(map(lambda x: extract(text, x), documents))
data = [list(i) for i in zip(*data_segments)]
final_text = []
for seg_index in range(len(data)):
if prev_text != text:
data_len = list(map(lambda x:len(x), data[seg_index]))
if 0 not in data_len:
text_sub = generate(data[seg_index], text)
if len(text_sub) > 0:
final_text.extend(text_sub)
else:
pass
if seg_index < len(text):
final_text.append(text[seg_index])
return final_text
def extract(invariant_segments_text, document):
"""
To get data segments by removing invariant segments from the original document
:param invariant_segments_text:
:param document:
:return:
"""
cur_segment_offset = 0
prev_segment_offset = 0
data_segments = []
for index, invariant_segment in enumerate(invariant_segments_text):
cur_segment_offset = document.find(invariant_segment, cur_segment_offset)
if cur_segment_offset == -1:
# The invariant segment MUST be found in the document.
return None
else:
data_segments.append(document[prev_segment_offset:cur_segment_offset])
cur_segment_offset += len(invariant_segment)
prev_segment_offset = cur_segment_offset
data_segments.append(document[cur_segment_offset:len(document)])
return data_segments
def reconstruct(invariant_segments, data_segments):
buffer = ""
if len(data_segments) == len(invariant_segments) + 1:
for index in range(len(invariant_segments)):
buffer += (data_segments[index] + invariant_segments[index])
buffer += data_segments[-1]
return buffer
else:
return None
def select(features, combined_predicates, offset):
status_code, selected_index = selector.selector_impl(features, combined_predicates)
if status_code == selector.SelectorStatus.SUCCESS:
return selected_index + offset
else:
return None
def serialize_object(template_object):
return pickle.dumps(template_object)
def deserialize_object(serialized):
return pickle.loads(serialized)
def make_template_object(invariant_segments=None, merkle_root=None):
template_object = {"inv_seg": invariant_segments, "mk_root":merkle_root}
return template_object
def make_data_object(data_segments=None, template_merkle_root=None, data_merkle_root=None, original_hash=None):
data_object = {"data_seg": data_segments,
"mk_root_template": template_merkle_root,
"mk_root_data": data_merkle_root,
"original_hash": original_hash}
return data_object
# def candidates_pattern_repetition(edges, outgoing_count, incoming_count):
# cnt = {}
# for prev_token_hash in edges:
# for token_hash in edges[prev_token_hash]:
# edge_value = edges[prev_token_hash][token_hash]
# if edge_value > 1:
# if edge_value not in cnt:
# cnt[edge_value] = 0
# cnt[edge_value] += 1
#
# helper_update_count(cnt, outgoing_count)
# helper_update_count(cnt, incoming_count)
#
# # Choose the maximum
# max_v = -1
# max_k = None
# for k, v in cnt.items():
# if v > max_v:
# max_v = v
# max_k = k
#
# print(cnt)
#
# candidate = set()
# for prev_token_hash in edges:
# for token_hash in edges[prev_token_hash]:
# edge_value = edges[prev_token_hash][token_hash]
# if edge_value == max_k:
# candidate.add(prev_token_hash)
# candidate.add(token_hash)
#
# for token_hash, val in outgoing_count.items():
# if val == max_k:
# candidate.add(token_hash)
#
# for token_hash, val in incoming_count.items():
# if val == max_k:
# candidate.add(token_hash)
#
# return candidate
#
#
# def helper_update_count(n_candidates, vertex_count):
# filtered_vertex_count = {k: v for k, v in vertex_count.items() if v > 1}
# # print(filtered_vertex_count)
# for k, v in filtered_vertex_count.items():
# if v not in n_candidates:
# n_candidates[v] = 0
# n_candidates[v] += 1
#
#
# def find_repeating_pattern(data):
# # for data_segment in data:
# # tokens_of = []
# # tokens_metadata_of = []
# # helper_tokenize(data_segment, tokens_of, tokens_metadata_of)
# # for document_indexbuffer = []
# # for line_no in current_line:
# # buffer.append(line_no + 1)
# # return buffer, tokens in enumerate(tokens_of):
# # print(document_index, len(tokens))
# # edges = {}
# # outgoing_count = {}
# # incoming_count = {}
# # prev_token_hash = None
# # for token in tokens:
# # token_hash = compute_hash(token)
# # # print(token_hash, token)
# # if prev_token_hash is not None:
# # if prev_token_hash not in outgoing_count:
# # outgoing_count[prev_token_hash] = 0
# # if token_hash not in incoming_count:
# # incoming_count[token_hash] = 0
# # outgoing_count[prev_token_hash] += 1
# # incoming_count[token_hash] += 1
# # if prev_token_hash not in edges:
# # edges[prev_token_hash] = {}
# # if token_hash not in edges[prev_token_hash]:
# # edges[prev_token_hash][token_hash] = 0
# # edges[prev_token_hash][token_hash] += 1 """
#
# # prev_token_hash = token_hash
# #
# # candidates = candidates_pattern_repetition(edges, outgoing_count, incoming_count)
# # print(candidates)
# # print("".join(list(
# # map(lambda x: "\033[1;32m{}\033[0m".format(x) if (compute_hash(x)) in candidates else "\033[1;31m{}\033[0m".format(x),
# # tokens))))
# next_invariant = list(candidate)
#
#
#
# #token_loc = helper_compute_token_loc(tokens_of) # To cache the corresponding line number of the given token
# #print(token_loc)
#
# # print(len(data))
#
# # print(tokens_of)
# pass | unknown | codeparrot/codeparrot-clean | ||
from __future__ import absolute_import, division, print_function
import datashape
from datashape import Record, DataShape, dshape, TimeDelta
from datashape import coretypes as ct
from datashape.predicates import iscollection, isboolean, isnumeric, isdatelike
from numpy import inf
from odo.utils import copydoc
import toolz
from .core import common_subexpression
from .expressions import Expr, ndim
from .strings import isstring
from .expressions import dshape_method_list, method_properties
class Reduction(Expr):
""" A column-wise reduction
Blaze supports the same class of reductions as NumPy and Pandas.
sum, min, max, any, all, mean, var, std, count, nunique
Examples
--------
>>> from blaze import symbol
>>> t = symbol('t', 'var * {name: string, amount: int, id: int}')
>>> e = t['amount'].sum()
>>> data = [['Alice', 100, 1],
... ['Bob', 200, 2],
... ['Alice', 50, 3]]
>>> from blaze.compute.python import compute
>>> compute(e, data)
350
"""
__slots__ = '_hash', '_child', 'axis', 'keepdims'
def __init__(self, _child, axis=None, keepdims=False):
self._child = _child
if axis is None:
axis = tuple(range(_child.ndim))
if isinstance(axis, (set, list)):
axis = tuple(axis)
if not isinstance(axis, tuple):
axis = (axis,)
axis = tuple(sorted(axis))
self.axis = axis
self.keepdims = keepdims
@property
def dshape(self):
axis = self.axis
if self.keepdims:
shape = tuple(1 if i in axis else d
for i, d in enumerate(self._child.shape))
else:
shape = tuple(d
for i, d in enumerate(self._child.shape)
if i not in axis)
return DataShape(*(shape + (self.schema,)))
@property
def schema(self):
schema = self._child.schema[0]
if isinstance(schema, Record) and len(schema.types) == 1:
result = toolz.first(schema.types)
else:
result = schema
return DataShape(result)
@property
def symbol(self):
return type(self).__name__
@property
def _name(self):
child_name = self._child._name
if child_name is None or child_name == '_':
return type(self).__name__
else:
return '%s_%s' % (child_name, type(self).__name__)
def __str__(self):
kwargs = list()
if self.keepdims:
kwargs.append('keepdims=True')
if self.axis != tuple(range(self._child.ndim)):
kwargs.append('axis=' + str(self.axis))
other = sorted(
set(self.__slots__[1:]) - set(['_child', 'axis', 'keepdims']))
for slot in other:
kwargs.append('%s=%s' % (slot, getattr(self, slot)))
name = type(self).__name__
if kwargs:
return '%s(%s, %s)' % (name, self._child, ', '.join(kwargs))
else:
return '%s(%s)' % (name, self._child)
class any(Reduction):
schema = dshape(ct.bool_)
class all(Reduction):
schema = dshape(ct.bool_)
class sum(Reduction):
@property
def schema(self):
return DataShape(datashape.maxtype(super(sum, self).schema))
class max(Reduction):
pass
class min(Reduction):
pass
class mean(Reduction):
schema = dshape(ct.real)
class var(Reduction):
"""Variance
Parameters
----------
child : Expr
An expression
unbiased : bool, optional
Compute an unbiased estimate of the population variance if this is
``True``. In NumPy and pandas, this parameter is called ``ddof`` (delta
degrees of freedom) and is equal to 1 for unbiased and 0 for biased.
"""
__slots__ = '_hash', '_child', 'unbiased', 'axis', 'keepdims'
schema = dshape(ct.real)
def __init__(self, child, unbiased=False, *args, **kwargs):
self.unbiased = unbiased
super(var, self).__init__(child, *args, **kwargs)
class std(Reduction):
"""Standard Deviation
Parameters
----------
child : Expr
An expression
unbiased : bool, optional
Compute the square root of an unbiased estimate of the population
variance if this is ``True``.
.. warning::
This does *not* return an unbiased estimate of the population
standard deviation.
See Also
--------
var
"""
__slots__ = '_hash', '_child', 'unbiased', 'axis', 'keepdims'
schema = dshape(ct.real)
def __init__(self, child, unbiased=False, *args, **kwargs):
self.unbiased = unbiased
super(std, self).__init__(child, *args, **kwargs)
class count(Reduction):
""" The number of non-null elements """
schema = dshape(ct.int32)
class nunique(Reduction):
schema = dshape(ct.int32)
class nelements(Reduction):
"""Compute the number of elements in a collection, including missing values.
See Also
---------
blaze.expr.reductions.count: compute the number of non-null elements
Examples
--------
>>> from blaze import symbol
>>> t = symbol('t', 'var * {name: string, amount: float64}')
>>> t[t.amount < 1].nelements()
nelements(t[t.amount < 1])
"""
schema = dshape(ct.int32)
def nrows(expr):
return nelements(expr, axis=(0,))
class Summary(Expr):
""" A collection of named reductions
Examples
--------
>>> from blaze import symbol
>>> t = symbol('t', 'var * {name: string, amount: int, id: int}')
>>> expr = summary(number=t.id.nunique(), sum=t.amount.sum())
>>> data = [['Alice', 100, 1],
... ['Bob', 200, 2],
... ['Alice', 50, 1]]
>>> from blaze import compute
>>> compute(expr, data)
(2, 350)
"""
__slots__ = '_hash', '_child', 'names', 'values', 'axis', 'keepdims'
def __init__(self, _child, names, values, axis=None, keepdims=False):
self._child = _child
self.names = names
self.values = values
self.keepdims = keepdims
self.axis = axis
@property
def dshape(self):
axis = self.axis
if self.keepdims:
shape = tuple(1 if i in axis else d
for i, d in enumerate(self._child.shape))
else:
shape = tuple(d
for i, d in enumerate(self._child.shape)
if i not in axis)
measure = Record(list(zip(self.names,
[v.schema for v in self.values])))
return DataShape(*(shape + (measure,)))
def __str__(self):
s = 'summary('
s += ', '.join('%s=%s' % (name, str(val))
for name, val in zip(self.fields, self.values))
if self.keepdims:
s += ', keepdims=True'
s += ')'
return s
@copydoc(Summary)
def summary(keepdims=False, axis=None, **kwargs):
items = sorted(kwargs.items(), key=toolz.first)
names = tuple(map(toolz.first, items))
values = tuple(map(toolz.second, items))
child = common_subexpression(*values)
if len(kwargs) == 1 and not iscollection(child.dshape):
while not iscollection(child.dshape):
children = [i for i in child._inputs if isinstance(i, Expr)]
if len(children) == 1:
child = children[0]
else:
child = common_subexpression(*children)
if axis is None:
axis = tuple(range(ndim(child)))
if isinstance(axis, (set, list)):
axis = tuple(axis)
if not isinstance(axis, tuple):
axis = (axis,)
return Summary(child, names, values, keepdims=keepdims, axis=axis)
def vnorm(expr, ord=None, axis=None, keepdims=False):
""" Vector norm
See np.linalg.norm
"""
if ord is None or ord == 'fro':
ord = 2
if ord == inf:
return max(abs(expr), axis=axis, keepdims=keepdims)
elif ord == -inf:
return min(abs(expr), axis=axis, keepdims=keepdims)
elif ord == 1:
return sum(abs(expr), axis=axis, keepdims=keepdims)
elif ord % 2 == 0:
return sum(expr ** ord, axis=axis, keepdims=keepdims) ** (1.0 / ord)
return sum(abs(expr) ** ord, axis=axis, keepdims=keepdims) ** (1.0 / ord)
dshape_method_list.extend([
(iscollection, set([count, nelements])),
(lambda ds: (iscollection(ds) and
(isstring(ds) or isnumeric(ds) or isboolean(ds) or
isdatelike(ds) or isinstance(ds, TimeDelta))),
set([min, max])),
(lambda ds: len(ds.shape) == 1,
set([nrows, nunique])),
(lambda ds: iscollection(ds) and isboolean(ds),
set([any, all])),
(lambda ds: iscollection(ds) and (isnumeric(ds) or isboolean(ds)),
set([mean, sum, std, var, vnorm])),
])
method_properties.update([nrows]) | unknown | codeparrot/codeparrot-clean | ||
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kafka.common.security.token.delegation;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;
/**
* A class representing a delegation token.
*
*/
public class DelegationToken {
private final TokenInformation tokenInformation;
private final byte[] hmac;
public DelegationToken(TokenInformation tokenInformation, byte[] hmac) {
this.tokenInformation = tokenInformation;
this.hmac = hmac;
}
public TokenInformation tokenInfo() {
return tokenInformation;
}
public byte[] hmac() {
return hmac;
}
public String hmacAsBase64String() {
return Base64.getEncoder().encodeToString(hmac);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DelegationToken token = (DelegationToken) o;
return Objects.equals(tokenInformation, token.tokenInformation) && MessageDigest.isEqual(hmac, token.hmac);
}
@Override
public int hashCode() {
int result = tokenInformation != null ? tokenInformation.hashCode() : 0;
result = 31 * result + Arrays.hashCode(hmac);
return result;
}
@Override
public String toString() {
return "DelegationToken{" +
"tokenInformation=" + tokenInformation +
", hmac=[*******]" +
'}';
}
} | java | github | https://github.com/apache/kafka | clients/src/main/java/org/apache/kafka/common/security/token/delegation/DelegationToken.java |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: ucs_mac_pool
short_description: Configures MAC address pools on Cisco UCS Manager
description:
- Configures MAC address pools and MAC address blocks on Cisco UCS Manager.
- Examples can be used with the UCS Platform Emulator U(https://communities.cisco.com/ucspe).
extends_documentation_fragment: ucs
options:
state:
description:
- If C(present), will verify MAC pool is present and will create if needed.
- If C(absent), will verify MAC pool is absent and will delete if needed.
choices: [present, absent]
default: present
name:
description:
- The name of the MAC pool.
- This name can be between 1 and 32 alphanumeric characters.
- "You cannot use spaces or any special characters other than - (hyphen), \"_\" (underscore), : (colon), and . (period)."
- You cannot change this name after the MAC pool is created.
required: yes
descrption:
description:
- A description of the MAC pool.
- Enter up to 256 characters.
- "You can use any characters or spaces except the following:"
- "` (accent mark), \ (backslash), ^ (carat), \" (double quote), = (equal sign), > (greater than), < (less than), or ' (single quote)."
aliases: [ descr ]
order:
description:
- The Assignment Order field.
- "This can be one of the following:"
- "default - Cisco UCS Manager selects a random identity from the pool."
- "sequential - Cisco UCS Manager selects the lowest available identity from the pool."
choices: [default, sequential]
default: default
first_addr:
description:
- The first MAC address in the block of addresses.
- This is the From field in the UCS Manager MAC Blocks menu.
last_addr:
description:
- The last MAC address in the block of addresses.
- This is the To field in the UCS Manager Add MAC Blocks menu.
org_dn:
description:
- The distinguished name (dn) of the organization where the resource is assigned.
default: org-root
requirements:
- ucsmsdk
author:
- David Soper (@dsoper2)
- CiscoUcs (@CiscoUcs)
version_added: '2.5'
'''
EXAMPLES = r'''
- name: Configure MAC address pool
ucs_mac_pool:
hostname: 172.16.143.150
username: admin
password: password
name: mac-A
first_addr: 00:25:B5:00:66:00
last_addr: 00:25:B5:00:67:F3
order: sequential
- name: Remove MAC address pool
ucs_mac_pool:
hostname: 172.16.143.150
username: admin
password: password
name: mac-A
state: absent
'''
RETURN = r'''
#
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.remote_management.ucs import UCSModule, ucs_argument_spec
def main():
argument_spec = ucs_argument_spec
argument_spec.update(
org_dn=dict(type='str', default='org-root'),
name=dict(type='str', required=True),
descr=dict(type='str', default=''),
order=dict(type='str', default='default', choices=['default', 'sequential']),
first_addr=dict(type='str'),
last_addr=dict(type='str'),
state=dict(default='present', choices=['present', 'absent'], type='str'),
)
module = AnsibleModule(
argument_spec,
supports_check_mode=True,
)
# UCSModule verifies ucsmsdk is present and exits on failure. Imports are below ucs object creation.
ucs = UCSModule(module)
err = False
from ucsmsdk.mometa.macpool.MacpoolPool import MacpoolPool
from ucsmsdk.mometa.macpool.MacpoolBlock import MacpoolBlock
changed = False
try:
mo_exists = False
props_match = False
# dn is <org_dn>/mac-pool-<name>
dn = module.params['org_dn'] + '/mac-pool-' + module.params['name']
mo = ucs.login_handle.query_dn(dn)
if mo:
mo_exists = True
if module.params['state'] == 'absent':
if mo_exists:
if not module.check_mode:
ucs.login_handle.remove_mo(mo)
ucs.login_handle.commit()
changed = True
else:
if mo_exists:
# check top-level mo props
kwargs = dict(assignment_order=module.params['order'])
kwargs['descr'] = module.params['descr']
if (mo.check_prop_match(**kwargs)):
# top-level props match, check next level mo/props
if module.params['last_addr'] and module.params['first_addr']:
# mac address block specified, check properties
block_dn = dn + '/block-' + module.params['first_addr'].upper() + '-' + module.params['last_addr'].upper()
mo_1 = ucs.login_handle.query_dn(block_dn)
if mo_1:
props_match = True
else:
# no MAC address block specified, but top-level props matched
props_match = True
if not props_match:
if not module.check_mode:
# create if mo does not already exist
mo = MacpoolPool(
parent_mo_or_dn=module.params['org_dn'],
name=module.params['name'],
descr=module.params['descr'],
assignment_order=module.params['order'],
)
if module.params['last_addr'] and module.params['first_addr']:
mo_1 = MacpoolBlock(
parent_mo_or_dn=mo,
to=module.params['last_addr'],
r_from=module.params['first_addr'],
)
ucs.login_handle.add_mo(mo, True)
ucs.login_handle.commit()
changed = True
except Exception as e:
err = True
ucs.result['msg'] = "setup error: %s " % str(e)
ucs.result['changed'] = changed
if err:
module.fail_json(**ucs.result)
module.exit_json(**ucs.result)
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
""" path.py - An object representing a path to a file or directory.
Example:
from IPython.external.path import path
d = path('/home/guido/bin')
for f in d.files('*.py'):
f.chmod(0755)
This module requires Python 2.2 or later.
URL: http://www.jorendorff.com/articles/python/path
Author: Jason Orendorff <jason.orendorff\x40gmail\x2ecom> (and others - see the url!)
Date: 9 Mar 2007
"""
# TODO
# - Tree-walking functions don't avoid symlink loops. Matt Harrison
# sent me a patch for this.
# - Bug in write_text(). It doesn't support Universal newline mode.
# - Better error message in listdir() when self isn't a
# directory. (On Windows, the error message really sucks.)
# - Make sure everything has a good docstring.
# - Add methods for regex find and replace.
# - guess_content_type() method?
# - Perhaps support arguments to touch().
from __future__ import generators
import sys, warnings, os, fnmatch, glob, shutil, codecs
# deprecated in python 2.6
warnings.filterwarnings('ignore', r'.*md5.*')
import md5
__version__ = '2.2'
__all__ = ['path']
# Platform-specific support for path.owner
if os.name == 'nt':
try:
import win32security
except ImportError:
win32security = None
else:
try:
import pwd
except ImportError:
pwd = None
# Pre-2.3 support. Are unicode filenames supported?
_base = str
_getcwd = os.getcwd
try:
if os.path.supports_unicode_filenames:
_base = unicode
_getcwd = os.getcwdu
except AttributeError:
pass
# Pre-2.3 workaround for booleans
try:
True, False
except NameError:
True, False = 1, 0
# Pre-2.3 workaround for basestring.
try:
basestring
except NameError:
basestring = (str, unicode)
# Universal newline support
_textmode = 'r'
if hasattr(file, 'newlines'):
_textmode = 'U'
class TreeWalkWarning(Warning):
pass
class path(_base):
""" Represents a filesystem path.
For documentation on individual methods, consult their
counterparts in os.path.
"""
# --- Special Python methods.
def __repr__(self):
return 'path(%s)' % _base.__repr__(self)
# Adding a path and a string yields a path.
def __add__(self, more):
try:
resultStr = _base.__add__(self, more)
except TypeError: #Python bug
resultStr = NotImplemented
if resultStr is NotImplemented:
return resultStr
return self.__class__(resultStr)
def __radd__(self, other):
if isinstance(other, basestring):
return self.__class__(other.__add__(self))
else:
return NotImplemented
# The / operator joins paths.
def __div__(self, rel):
""" fp.__div__(rel) == fp / rel == fp.joinpath(rel)
Join two path components, adding a separator character if
needed.
"""
return self.__class__(os.path.join(self, rel))
# Make the / operator work even when true division is enabled.
__truediv__ = __div__
def getcwd(cls):
""" Return the current working directory as a path object. """
return cls(_getcwd())
getcwd = classmethod(getcwd)
# --- Operations on path strings.
isabs = os.path.isabs
def abspath(self): return self.__class__(os.path.abspath(self))
def normcase(self): return self.__class__(os.path.normcase(self))
def normpath(self): return self.__class__(os.path.normpath(self))
def realpath(self): return self.__class__(os.path.realpath(self))
def expanduser(self): return self.__class__(os.path.expanduser(self))
def expandvars(self): return self.__class__(os.path.expandvars(self))
def dirname(self): return self.__class__(os.path.dirname(self))
basename = os.path.basename
def expand(self):
""" Clean up a filename by calling expandvars(),
expanduser(), and normpath() on it.
This is commonly everything needed to clean up a filename
read from a configuration file, for example.
"""
return self.expandvars().expanduser().normpath()
def _get_namebase(self):
base, ext = os.path.splitext(self.name)
return base
def _get_ext(self):
f, ext = os.path.splitext(_base(self))
return ext
def _get_drive(self):
drive, r = os.path.splitdrive(self)
return self.__class__(drive)
parent = property(
dirname, None, None,
""" This path's parent directory, as a new path object.
For example, path('/usr/local/lib/libpython.so').parent == path('/usr/local/lib')
""")
name = property(
basename, None, None,
""" The name of this file or directory without the full path.
For example, path('/usr/local/lib/libpython.so').name == 'libpython.so'
""")
namebase = property(
_get_namebase, None, None,
""" The same as path.name, but with one file extension stripped off.
For example, path('/home/guido/python.tar.gz').name == 'python.tar.gz',
but path('/home/guido/python.tar.gz').namebase == 'python.tar'
""")
ext = property(
_get_ext, None, None,
""" The file extension, for example '.py'. """)
drive = property(
_get_drive, None, None,
""" The drive specifier, for example 'C:'.
This is always empty on systems that don't use drive specifiers.
""")
def splitpath(self):
""" p.splitpath() -> Return (p.parent, p.name). """
parent, child = os.path.split(self)
return self.__class__(parent), child
def splitdrive(self):
""" p.splitdrive() -> Return (p.drive, <the rest of p>).
Split the drive specifier from this path. If there is
no drive specifier, p.drive is empty, so the return value
is simply (path(''), p). This is always the case on Unix.
"""
drive, rel = os.path.splitdrive(self)
return self.__class__(drive), rel
def splitext(self):
""" p.splitext() -> Return (p.stripext(), p.ext).
Split the filename extension from this path and return
the two parts. Either part may be empty.
The extension is everything from '.' to the end of the
last path segment. This has the property that if
(a, b) == p.splitext(), then a + b == p.
"""
filename, ext = os.path.splitext(self)
return self.__class__(filename), ext
def stripext(self):
""" p.stripext() -> Remove one file extension from the path.
For example, path('/home/guido/python.tar.gz').stripext()
returns path('/home/guido/python.tar').
"""
return self.splitext()[0]
if hasattr(os.path, 'splitunc'):
def splitunc(self):
unc, rest = os.path.splitunc(self)
return self.__class__(unc), rest
def _get_uncshare(self):
unc, r = os.path.splitunc(self)
return self.__class__(unc)
uncshare = property(
_get_uncshare, None, None,
""" The UNC mount point for this path.
This is empty for paths on local drives. """)
def joinpath(self, *args):
""" Join two or more path components, adding a separator
character (os.sep) if needed. Returns a new path
object.
"""
return self.__class__(os.path.join(self, *args))
def splitall(self):
r""" Return a list of the path components in this path.
The first item in the list will be a path. Its value will be
either os.curdir, os.pardir, empty, or the root directory of
this path (for example, '/' or 'C:\\'). The other items in
the list will be strings.
path.path.joinpath(*result) will yield the original path.
"""
parts = []
loc = self
while loc != os.curdir and loc != os.pardir:
prev = loc
loc, child = prev.splitpath()
if loc == prev:
break
parts.append(child)
parts.append(loc)
parts.reverse()
return parts
def relpath(self):
""" Return this path as a relative path,
based from the current working directory.
"""
cwd = self.__class__(os.getcwd())
return cwd.relpathto(self)
def relpathto(self, dest):
""" Return a relative path from self to dest.
If there is no relative path from self to dest, for example if
they reside on different drives in Windows, then this returns
dest.abspath().
"""
origin = self.abspath()
dest = self.__class__(dest).abspath()
orig_list = origin.normcase().splitall()
# Don't normcase dest! We want to preserve the case.
dest_list = dest.splitall()
if orig_list[0] != os.path.normcase(dest_list[0]):
# Can't get here from there.
return dest
# Find the location where the two paths start to differ.
i = 0
for start_seg, dest_seg in zip(orig_list, dest_list):
if start_seg != os.path.normcase(dest_seg):
break
i += 1
# Now i is the point where the two paths diverge.
# Need a certain number of "os.pardir"s to work up
# from the origin to the point of divergence.
segments = [os.pardir] * (len(orig_list) - i)
# Need to add the diverging part of dest_list.
segments += dest_list[i:]
if len(segments) == 0:
# If they happen to be identical, use os.curdir.
relpath = os.curdir
else:
relpath = os.path.join(*segments)
return self.__class__(relpath)
# --- Listing, searching, walking, and matching
def listdir(self, pattern=None):
""" D.listdir() -> List of items in this directory.
Use D.files() or D.dirs() instead if you want a listing
of just files or just subdirectories.
The elements of the list are path objects.
With the optional 'pattern' argument, this only lists
items whose names match the given pattern.
"""
names = os.listdir(self)
if pattern is not None:
names = fnmatch.filter(names, pattern)
return [self / child for child in names]
def dirs(self, pattern=None):
""" D.dirs() -> List of this directory's subdirectories.
The elements of the list are path objects.
This does not walk recursively into subdirectories
(but see path.walkdirs).
With the optional 'pattern' argument, this only lists
directories whose names match the given pattern. For
example, d.dirs('build-*').
"""
return [p for p in self.listdir(pattern) if p.isdir()]
def files(self, pattern=None):
""" D.files() -> List of the files in this directory.
The elements of the list are path objects.
This does not walk into subdirectories (see path.walkfiles).
With the optional 'pattern' argument, this only lists files
whose names match the given pattern. For example,
d.files('*.pyc').
"""
return [p for p in self.listdir(pattern) if p.isfile()]
def walk(self, pattern=None, errors='strict'):
""" D.walk() -> iterator over files and subdirs, recursively.
The iterator yields path objects naming each child item of
this directory and its descendants. This requires that
D.isdir().
This performs a depth-first traversal of the directory tree.
Each directory is returned just before all its children.
The errors= keyword argument controls behavior when an
error occurs. The default is 'strict', which causes an
exception. The other allowed values are 'warn', which
reports the error via warnings.warn(), and 'ignore'.
"""
if errors not in ('strict', 'warn', 'ignore'):
raise ValueError("invalid errors parameter")
try:
childList = self.listdir()
except Exception:
if errors == 'ignore':
return
elif errors == 'warn':
warnings.warn(
"Unable to list directory '%s': %s"
% (self, sys.exc_info()[1]),
TreeWalkWarning)
return
else:
raise
for child in childList:
if pattern is None or child.fnmatch(pattern):
yield child
try:
isdir = child.isdir()
except Exception:
if errors == 'ignore':
isdir = False
elif errors == 'warn':
warnings.warn(
"Unable to access '%s': %s"
% (child, sys.exc_info()[1]),
TreeWalkWarning)
isdir = False
else:
raise
if isdir:
for item in child.walk(pattern, errors):
yield item
def walkdirs(self, pattern=None, errors='strict'):
""" D.walkdirs() -> iterator over subdirs, recursively.
With the optional 'pattern' argument, this yields only
directories whose names match the given pattern. For
example, mydir.walkdirs('*test') yields only directories
with names ending in 'test'.
The errors= keyword argument controls behavior when an
error occurs. The default is 'strict', which causes an
exception. The other allowed values are 'warn', which
reports the error via warnings.warn(), and 'ignore'.
"""
if errors not in ('strict', 'warn', 'ignore'):
raise ValueError("invalid errors parameter")
try:
dirs = self.dirs()
except Exception:
if errors == 'ignore':
return
elif errors == 'warn':
warnings.warn(
"Unable to list directory '%s': %s"
% (self, sys.exc_info()[1]),
TreeWalkWarning)
return
else:
raise
for child in dirs:
if pattern is None or child.fnmatch(pattern):
yield child
for subsubdir in child.walkdirs(pattern, errors):
yield subsubdir
def walkfiles(self, pattern=None, errors='strict'):
""" D.walkfiles() -> iterator over files in D, recursively.
The optional argument, pattern, limits the results to files
with names that match the pattern. For example,
mydir.walkfiles('*.tmp') yields only files with the .tmp
extension.
"""
if errors not in ('strict', 'warn', 'ignore'):
raise ValueError("invalid errors parameter")
try:
childList = self.listdir()
except Exception:
if errors == 'ignore':
return
elif errors == 'warn':
warnings.warn(
"Unable to list directory '%s': %s"
% (self, sys.exc_info()[1]),
TreeWalkWarning)
return
else:
raise
for child in childList:
try:
isfile = child.isfile()
isdir = not isfile and child.isdir()
except:
if errors == 'ignore':
continue
elif errors == 'warn':
warnings.warn(
"Unable to access '%s': %s"
% (self, sys.exc_info()[1]),
TreeWalkWarning)
continue
else:
raise
if isfile:
if pattern is None or child.fnmatch(pattern):
yield child
elif isdir:
for f in child.walkfiles(pattern, errors):
yield f
def fnmatch(self, pattern):
""" Return True if self.name matches the given pattern.
pattern - A filename pattern with wildcards,
for example '*.py'.
"""
return fnmatch.fnmatch(self.name, pattern)
def glob(self, pattern):
""" Return a list of path objects that match the pattern.
pattern - a path relative to this directory, with wildcards.
For example, path('/users').glob('*/bin/*') returns a list
of all the files users have in their bin directories.
"""
cls = self.__class__
return [cls(s) for s in glob.glob(_base(self / pattern))]
# --- Reading or writing an entire file at once.
def open(self, mode='r'):
""" Open this file. Return a file object. """
return file(self, mode)
def bytes(self):
""" Open this file, read all bytes, return them as a string. """
f = self.open('rb')
try:
return f.read()
finally:
f.close()
def write_bytes(self, bytes, append=False):
""" Open this file and write the given bytes to it.
Default behavior is to overwrite any existing file.
Call p.write_bytes(bytes, append=True) to append instead.
"""
if append:
mode = 'ab'
else:
mode = 'wb'
f = self.open(mode)
try:
f.write(bytes)
finally:
f.close()
def text(self, encoding=None, errors='strict'):
r""" Open this file, read it in, return the content as a string.
This uses 'U' mode in Python 2.3 and later, so '\r\n' and '\r'
are automatically translated to '\n'.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. If present, the content of the file is
decoded and returned as a unicode object; otherwise
it is returned as an 8-bit str.
errors - How to handle Unicode errors; see help(str.decode)
for the options. Default is 'strict'.
"""
if encoding is None:
# 8-bit
f = self.open(_textmode)
try:
return f.read()
finally:
f.close()
else:
# Unicode
f = codecs.open(self, 'r', encoding, errors)
# (Note - Can't use 'U' mode here, since codecs.open
# doesn't support 'U' mode, even in Python 2.3.)
try:
t = f.read()
finally:
f.close()
return (t.replace(u'\r\n', u'\n')
.replace(u'\r\x85', u'\n')
.replace(u'\r', u'\n')
.replace(u'\x85', u'\n')
.replace(u'\u2028', u'\n'))
def write_text(self, text, encoding=None, errors='strict', linesep=os.linesep, append=False):
r""" Write the given text to this file.
The default behavior is to overwrite any existing file;
to append instead, use the 'append=True' keyword argument.
There are two differences between path.write_text() and
path.write_bytes(): newline handling and Unicode handling.
See below.
Parameters:
- text - str/unicode - The text to be written.
- encoding - str - The Unicode encoding that will be used.
This is ignored if 'text' isn't a Unicode string.
- errors - str - How to handle Unicode encoding errors.
Default is 'strict'. See help(unicode.encode) for the
options. This is ignored if 'text' isn't a Unicode
string.
- linesep - keyword argument - str/unicode - The sequence of
characters to be used to mark end-of-line. The default is
os.linesep. You can also specify None; this means to
leave all newlines as they are in 'text'.
- append - keyword argument - bool - Specifies what to do if
the file already exists (True: append to the end of it;
False: overwrite it.) The default is False.
--- Newline handling.
write_text() converts all standard end-of-line sequences
('\n', '\r', and '\r\n') to your platform's default end-of-line
sequence (see os.linesep; on Windows, for example, the
end-of-line marker is '\r\n').
If you don't like your platform's default, you can override it
using the 'linesep=' keyword argument. If you specifically want
write_text() to preserve the newlines as-is, use 'linesep=None'.
This applies to Unicode text the same as to 8-bit text, except
there are three additional standard Unicode end-of-line sequences:
u'\x85', u'\r\x85', and u'\u2028'.
(This is slightly different from when you open a file for
writing with fopen(filename, "w") in C or file(filename, 'w')
in Python.)
--- Unicode
If 'text' isn't Unicode, then apart from newline handling, the
bytes are written verbatim to the file. The 'encoding' and
'errors' arguments are not used and must be omitted.
If 'text' is Unicode, it is first converted to bytes using the
specified 'encoding' (or the default encoding if 'encoding'
isn't specified). The 'errors' argument applies only to this
conversion.
"""
if isinstance(text, unicode):
if linesep is not None:
# Convert all standard end-of-line sequences to
# ordinary newline characters.
text = (text.replace(u'\r\n', u'\n')
.replace(u'\r\x85', u'\n')
.replace(u'\r', u'\n')
.replace(u'\x85', u'\n')
.replace(u'\u2028', u'\n'))
text = text.replace(u'\n', linesep)
if encoding is None:
encoding = sys.getdefaultencoding()
bytes = text.encode(encoding, errors)
else:
# It is an error to specify an encoding if 'text' is
# an 8-bit string.
assert encoding is None
if linesep is not None:
text = (text.replace('\r\n', '\n')
.replace('\r', '\n'))
bytes = text.replace('\n', linesep)
self.write_bytes(bytes, append)
def lines(self, encoding=None, errors='strict', retain=True):
r""" Open this file, read all lines, return them in a list.
Optional arguments:
encoding - The Unicode encoding (or character set) of
the file. The default is None, meaning the content
of the file is read as 8-bit characters and returned
as a list of (non-Unicode) str objects.
errors - How to handle Unicode errors; see help(str.decode)
for the options. Default is 'strict'
retain - If true, retain newline characters; but all newline
character combinations ('\r', '\n', '\r\n') are
translated to '\n'. If false, newline characters are
stripped off. Default is True.
This uses 'U' mode in Python 2.3 and later.
"""
if encoding is None and retain:
f = self.open(_textmode)
try:
return f.readlines()
finally:
f.close()
else:
return self.text(encoding, errors).splitlines(retain)
def write_lines(self, lines, encoding=None, errors='strict',
linesep=os.linesep, append=False):
r""" Write the given lines of text to this file.
By default this overwrites any existing file at this path.
This puts a platform-specific newline sequence on every line.
See 'linesep' below.
lines - A list of strings.
encoding - A Unicode encoding to use. This applies only if
'lines' contains any Unicode strings.
errors - How to handle errors in Unicode encoding. This
also applies only to Unicode strings.
linesep - The desired line-ending. This line-ending is
applied to every line. If a line already has any
standard line ending ('\r', '\n', '\r\n', u'\x85',
u'\r\x85', u'\u2028'), that will be stripped off and
this will be used instead. The default is os.linesep,
which is platform-dependent ('\r\n' on Windows, '\n' on
Unix, etc.) Specify None to write the lines as-is,
like file.writelines().
Use the keyword argument append=True to append lines to the
file. The default is to overwrite the file. Warning:
When you use this with Unicode data, if the encoding of the
existing data in the file is different from the encoding
you specify with the encoding= parameter, the result is
mixed-encoding data, which can really confuse someone trying
to read the file later.
"""
if append:
mode = 'ab'
else:
mode = 'wb'
f = self.open(mode)
try:
for line in lines:
isUnicode = isinstance(line, unicode)
if linesep is not None:
# Strip off any existing line-end and add the
# specified linesep string.
if isUnicode:
if line[-2:] in (u'\r\n', u'\x0d\x85'):
line = line[:-2]
elif line[-1:] in (u'\r', u'\n',
u'\x85', u'\u2028'):
line = line[:-1]
else:
if line[-2:] == '\r\n':
line = line[:-2]
elif line[-1:] in ('\r', '\n'):
line = line[:-1]
line += linesep
if isUnicode:
if encoding is None:
encoding = sys.getdefaultencoding()
line = line.encode(encoding, errors)
f.write(line)
finally:
f.close()
def read_md5(self):
""" Calculate the md5 hash for this file.
This reads through the entire file.
"""
f = self.open('rb')
try:
m = md5.new()
while True:
d = f.read(8192)
if not d:
break
m.update(d)
finally:
f.close()
return m.digest()
# --- Methods for querying the filesystem.
exists = os.path.exists
isdir = os.path.isdir
isfile = os.path.isfile
islink = os.path.islink
ismount = os.path.ismount
if hasattr(os.path, 'samefile'):
samefile = os.path.samefile
getatime = os.path.getatime
atime = property(
getatime, None, None,
""" Last access time of the file. """)
getmtime = os.path.getmtime
mtime = property(
getmtime, None, None,
""" Last-modified time of the file. """)
if hasattr(os.path, 'getctime'):
getctime = os.path.getctime
ctime = property(
getctime, None, None,
""" Creation time of the file. """)
getsize = os.path.getsize
size = property(
getsize, None, None,
""" Size of the file, in bytes. """)
if hasattr(os, 'access'):
def access(self, mode):
""" Return true if current user has access to this path.
mode - One of the constants os.F_OK, os.R_OK, os.W_OK, os.X_OK
"""
return os.access(self, mode)
def stat(self):
""" Perform a stat() system call on this path. """
return os.stat(self)
def lstat(self):
""" Like path.stat(), but do not follow symbolic links. """
return os.lstat(self)
def get_owner(self):
r""" Return the name of the owner of this file or directory.
This follows symbolic links.
On Windows, this returns a name of the form ur'DOMAIN\User Name'.
On Windows, a group can own a file or directory.
"""
if os.name == 'nt':
if win32security is None:
raise Exception("path.owner requires win32all to be installed")
desc = win32security.GetFileSecurity(
self, win32security.OWNER_SECURITY_INFORMATION)
sid = desc.GetSecurityDescriptorOwner()
account, domain, typecode = win32security.LookupAccountSid(None, sid)
return domain + u'\\' + account
else:
if pwd is None:
raise NotImplementedError("path.owner is not implemented on this platform.")
st = self.stat()
return pwd.getpwuid(st.st_uid).pw_name
owner = property(
get_owner, None, None,
""" Name of the owner of this file or directory. """)
if hasattr(os, 'statvfs'):
def statvfs(self):
""" Perform a statvfs() system call on this path. """
return os.statvfs(self)
if hasattr(os, 'pathconf'):
def pathconf(self, name):
return os.pathconf(self, name)
# --- Modifying operations on files and directories
def utime(self, times):
""" Set the access and modified times of this file. """
os.utime(self, times)
def chmod(self, mode):
os.chmod(self, mode)
if hasattr(os, 'chown'):
def chown(self, uid, gid):
os.chown(self, uid, gid)
def rename(self, new):
os.rename(self, new)
def renames(self, new):
os.renames(self, new)
# --- Create/delete operations on directories
def mkdir(self, mode=0777):
os.mkdir(self, mode)
def makedirs(self, mode=0777):
os.makedirs(self, mode)
def rmdir(self):
os.rmdir(self)
def removedirs(self):
os.removedirs(self)
# --- Modifying operations on files
def touch(self):
""" Set the access/modified times of this file to the current time.
Create the file if it does not exist.
"""
fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0666)
os.close(fd)
os.utime(self, None)
def remove(self):
os.remove(self)
def unlink(self):
os.unlink(self)
# --- Links
if hasattr(os, 'link'):
def link(self, newpath):
""" Create a hard link at 'newpath', pointing to this file. """
os.link(self, newpath)
if hasattr(os, 'symlink'):
def symlink(self, newlink):
""" Create a symbolic link at 'newlink', pointing here. """
os.symlink(self, newlink)
if hasattr(os, 'readlink'):
def readlink(self):
""" Return the path to which this symbolic link points.
The result may be an absolute or a relative path.
"""
return self.__class__(os.readlink(self))
def readlinkabs(self):
""" Return the path to which this symbolic link points.
The result is always an absolute path.
"""
p = self.readlink()
if p.isabs():
return p
else:
return (self.parent / p).abspath()
# --- High-level functions from shutil
copyfile = shutil.copyfile
copymode = shutil.copymode
copystat = shutil.copystat
copy = shutil.copy
copy2 = shutil.copy2
copytree = shutil.copytree
if hasattr(shutil, 'move'):
move = shutil.move
rmtree = shutil.rmtree
# --- Special stuff from os
if hasattr(os, 'chroot'):
def chroot(self):
os.chroot(self)
if hasattr(os, 'startfile'):
def startfile(self):
os.startfile(self) | unknown | codeparrot/codeparrot-clean | ||
"""
Enrollment API for creating, updating, and deleting enrollments. Also provides access to enrollment information at a
course level, such as available course modes.
"""
import importlib
import logging
from django.conf import settings
from django.core.cache import cache
from opaque_keys.edx.keys import CourseKey
from course_modes.models import CourseMode
from enrollment import errors
log = logging.getLogger(__name__)
DEFAULT_DATA_API = 'enrollment.data'
def get_enrollments(user_id, include_inactive=False):
"""Retrieves all the courses a user is enrolled in.
Takes a user and retrieves all relative enrollments. Includes information regarding how the user is enrolled
in the the course.
Args:
user_id (str): The username of the user we want to retrieve course enrollment information for.
include_inactive (bool): Determines whether inactive enrollments will be included
Returns:
A list of enrollment information for the given user.
Examples:
>>> get_enrollments("Bob")
[
{
"created": "2014-10-20T20:18:00Z",
"mode": "honor",
"is_active": True,
"user": "Bob",
"course_details": {
"course_id": "edX/DemoX/2014T2",
"course_name": "edX Demonstration Course",
"enrollment_end": "2014-12-20T20:18:00Z",
"enrollment_start": "2014-10-15T20:18:00Z",
"course_start": "2015-02-03T00:00:00Z",
"course_end": "2015-05-06T00:00:00Z",
"course_modes": [
{
"slug": "honor",
"name": "Honor Code Certificate",
"min_price": 0,
"suggested_prices": "",
"currency": "usd",
"expiration_datetime": null,
"description": null,
"sku": null,
"bulk_sku": null
}
],
"invite_only": False
}
},
{
"created": "2014-10-25T20:18:00Z",
"mode": "verified",
"is_active": True,
"user": "Bob",
"course_details": {
"course_id": "edX/edX-Insider/2014T2",
"course_name": "edX Insider Course",
"enrollment_end": "2014-12-20T20:18:00Z",
"enrollment_start": "2014-10-15T20:18:00Z",
"course_start": "2015-02-03T00:00:00Z",
"course_end": "2015-05-06T00:00:00Z",
"course_modes": [
{
"slug": "honor",
"name": "Honor Code Certificate",
"min_price": 0,
"suggested_prices": "",
"currency": "usd",
"expiration_datetime": null,
"description": null,
"sku": null,
"bulk_sku": null
}
],
"invite_only": True
}
}
]
"""
return _data_api().get_course_enrollments(user_id, include_inactive)
def get_enrollment(user_id, course_id):
"""Retrieves all enrollment information for the user in respect to a specific course.
Gets all the course enrollment information specific to a user in a course.
Args:
user_id (str): The user to get course enrollment information for.
course_id (str): The course to get enrollment information for.
Returns:
A serializable dictionary of the course enrollment.
Example:
>>> get_enrollment("Bob", "edX/DemoX/2014T2")
{
"created": "2014-10-20T20:18:00Z",
"mode": "honor",
"is_active": True,
"user": "Bob",
"course_details": {
"course_id": "edX/DemoX/2014T2",
"course_name": "edX Demonstration Course",
"enrollment_end": "2014-12-20T20:18:00Z",
"enrollment_start": "2014-10-15T20:18:00Z",
"course_start": "2015-02-03T00:00:00Z",
"course_end": "2015-05-06T00:00:00Z",
"course_modes": [
{
"slug": "honor",
"name": "Honor Code Certificate",
"min_price": 0,
"suggested_prices": "",
"currency": "usd",
"expiration_datetime": null,
"description": null,
"sku": null,
"bulk_sku": null
}
],
"invite_only": False
}
}
"""
return _data_api().get_course_enrollment(user_id, course_id)
def add_enrollment(user_id, course_id, mode=None, is_active=True, enrollment_attributes=None):
"""Enrolls a user in a course.
Enrolls a user in a course. If the mode is not specified, this will default to `CourseMode.DEFAULT_MODE_SLUG`.
Arguments:
user_id (str): The user to enroll.
course_id (str): The course to enroll the user in.
mode (str): Optional argument for the type of enrollment to create. Ex. 'audit', 'honor', 'verified',
'professional'. If not specified, this defaults to the default course mode.
is_active (boolean): Optional argument for making the new enrollment inactive. If not specified, is_active
defaults to True.
enrollment_attributes (list): Attributes to be set the enrollment.
Returns:
A serializable dictionary of the new course enrollment.
Example:
>>> add_enrollment("Bob", "edX/DemoX/2014T2", mode="audit")
{
"created": "2014-10-20T20:18:00Z",
"mode": "audit",
"is_active": True,
"user": "Bob",
"course_details": {
"course_id": "edX/DemoX/2014T2",
"course_name": "edX Demonstration Course",
"enrollment_end": "2014-12-20T20:18:00Z",
"enrollment_start": "2014-10-15T20:18:00Z",
"course_start": "2015-02-03T00:00:00Z",
"course_end": "2015-05-06T00:00:00Z",
"course_modes": [
{
"slug": "audit",
"name": "Audit",
"min_price": 0,
"suggested_prices": "",
"currency": "usd",
"expiration_datetime": null,
"description": null,
"sku": null,
"bulk_sku": null
}
],
"invite_only": False
}
}
"""
if mode is None:
mode = _default_course_mode(course_id)
validate_course_mode(course_id, mode, is_active=is_active)
enrollment = _data_api().create_course_enrollment(user_id, course_id, mode, is_active)
if enrollment_attributes is not None:
set_enrollment_attributes(user_id, course_id, enrollment_attributes)
return enrollment
def update_enrollment(user_id, course_id, mode=None, is_active=None, enrollment_attributes=None, include_expired=False):
"""Updates the course mode for the enrolled user.
Update a course enrollment for the given user and course.
Arguments:
user_id (str): The user associated with the updated enrollment.
course_id (str): The course associated with the updated enrollment.
Keyword Arguments:
mode (str): The new course mode for this enrollment.
is_active (bool): Sets whether the enrollment is active or not.
enrollment_attributes (list): Attributes to be set the enrollment.
include_expired (bool): Boolean denoting whether expired course modes should be included.
Returns:
A serializable dictionary representing the updated enrollment.
Example:
>>> update_enrollment("Bob", "edX/DemoX/2014T2", "honor")
{
"created": "2014-10-20T20:18:00Z",
"mode": "honor",
"is_active": True,
"user": "Bob",
"course_details": {
"course_id": "edX/DemoX/2014T2",
"course_name": "edX Demonstration Course",
"enrollment_end": "2014-12-20T20:18:00Z",
"enrollment_start": "2014-10-15T20:18:00Z",
"course_start": "2015-02-03T00:00:00Z",
"course_end": "2015-05-06T00:00:00Z",
"course_modes": [
{
"slug": "honor",
"name": "Honor Code Certificate",
"min_price": 0,
"suggested_prices": "",
"currency": "usd",
"expiration_datetime": null,
"description": null,
"sku": null,
"bulk_sku": null
}
],
"invite_only": False
}
}
"""
log.info(u'Starting Update Enrollment process for user {user} in course {course} to mode {mode}'.format(
user=user_id,
course=course_id,
mode=mode,
))
if mode is not None:
validate_course_mode(course_id, mode, is_active=is_active, include_expired=include_expired)
enrollment = _data_api().update_course_enrollment(user_id, course_id, mode=mode, is_active=is_active)
if enrollment is None:
msg = u"Course Enrollment not found for user {user} in course {course}".format(user=user_id, course=course_id)
log.warn(msg)
raise errors.EnrollmentNotFoundError(msg)
else:
if enrollment_attributes is not None:
set_enrollment_attributes(user_id, course_id, enrollment_attributes)
log.info(u'Course Enrollment updated for user {user} in course {course} to mode {mode}'.format(
user=user_id,
course=course_id,
mode=mode
))
return enrollment
def get_course_enrollment_details(course_id, include_expired=False):
"""Get the course modes for course. Also get enrollment start and end date, invite only, etc.
Given a course_id, return a serializable dictionary of properties describing course enrollment information.
Args:
course_id (str): The Course to get enrollment information for.
include_expired (bool): Boolean denoting whether expired course modes
should be included in the returned JSON data.
Returns:
A serializable dictionary of course enrollment information.
Example:
>>> get_course_enrollment_details("edX/DemoX/2014T2")
{
"course_id": "edX/DemoX/2014T2",
"course_name": "edX Demonstration Course",
"enrollment_end": "2014-12-20T20:18:00Z",
"enrollment_start": "2014-10-15T20:18:00Z",
"course_start": "2015-02-03T00:00:00Z",
"course_end": "2015-05-06T00:00:00Z",
"course_modes": [
{
"slug": "honor",
"name": "Honor Code Certificate",
"min_price": 0,
"suggested_prices": "",
"currency": "usd",
"expiration_datetime": null,
"description": null,
"sku": null,
"bulk_sku": null
}
],
"invite_only": False
}
"""
cache_key = u'enrollment.course.details.{course_id}.{include_expired}'.format(
course_id=course_id,
include_expired=include_expired
)
cached_enrollment_data = None
try:
cached_enrollment_data = cache.get(cache_key)
except Exception:
# The cache backend could raise an exception (for example, memcache keys that contain spaces)
log.exception(u"Error occurred while retrieving course enrollment details from the cache")
if cached_enrollment_data:
log.info(u"Get enrollment data for course %s (cached)", course_id)
return cached_enrollment_data
course_enrollment_details = _data_api().get_course_enrollment_info(course_id, include_expired)
try:
cache_time_out = getattr(settings, 'ENROLLMENT_COURSE_DETAILS_CACHE_TIMEOUT', 60)
cache.set(cache_key, course_enrollment_details, cache_time_out)
except Exception:
# Catch any unexpected errors during caching.
log.exception(u"Error occurred while caching course enrollment details for course %s", course_id)
raise errors.CourseEnrollmentError(u"An unexpected error occurred while retrieving course enrollment details.")
log.info(u"Get enrollment data for course %s", course_id)
return course_enrollment_details
def set_enrollment_attributes(user_id, course_id, attributes):
"""Set enrollment attributes for the enrollment of given user in the
course provided.
Args:
course_id (str): The Course to set enrollment attributes for.
user_id (str): The User to set enrollment attributes for.
attributes (list): Attributes to be set.
Example:
>>>set_enrollment_attributes(
"Bob",
"course-v1-edX-DemoX-1T2015",
[
{
"namespace": "credit",
"name": "provider_id",
"value": "hogwarts",
},
]
)
"""
_data_api().add_or_update_enrollment_attr(user_id, course_id, attributes)
def get_enrollment_attributes(user_id, course_id):
"""Retrieve enrollment attributes for given user for provided course.
Args:
user_id: The User to get enrollment attributes for
course_id (str): The Course to get enrollment attributes for.
Example:
>>>get_enrollment_attributes("Bob", "course-v1-edX-DemoX-1T2015")
[
{
"namespace": "credit",
"name": "provider_id",
"value": "hogwarts",
},
]
Returns: list
"""
return _data_api().get_enrollment_attributes(user_id, course_id)
def _default_course_mode(course_id):
"""Return the default enrollment for a course.
Special case the default enrollment to return if nothing else is found.
Arguments:
course_id (str): The course to check against for available course modes.
Returns:
str
"""
course_modes = CourseMode.modes_for_course(CourseKey.from_string(course_id))
available_modes = [m.slug for m in course_modes]
if CourseMode.DEFAULT_MODE_SLUG in available_modes:
return CourseMode.DEFAULT_MODE_SLUG
elif 'audit' in available_modes:
return 'audit'
elif 'honor' in available_modes:
return 'honor'
return CourseMode.DEFAULT_MODE_SLUG
def validate_course_mode(course_id, mode, is_active=None, include_expired=False):
"""Checks to see if the specified course mode is valid for the course.
If the requested course mode is not available for the course, raise an error with corresponding
course enrollment information.
Arguments:
course_id (str): The course to check against for available course modes.
mode (str): The slug for the course mode specified in the enrollment.
Keyword Arguments:
is_active (bool): Whether the enrollment is to be activated or deactivated.
include_expired (bool): Boolean denoting whether expired course modes should be included.
Returns:
None
Raises:
CourseModeNotFound: raised if the course mode is not found.
"""
# If the client has requested an enrollment deactivation, we want to include expired modes
# in the set of available modes. This allows us to unenroll users from expired modes.
# If include_expired is set as True we should not redetermine its value.
if not include_expired:
include_expired = not is_active if is_active is not None else False
course_enrollment_info = _data_api().get_course_enrollment_info(course_id, include_expired=include_expired)
course_modes = course_enrollment_info["course_modes"]
available_modes = [m['slug'] for m in course_modes]
if mode not in available_modes:
msg = (
u"Specified course mode '{mode}' unavailable for course {course_id}. "
u"Available modes were: {available}"
).format(
mode=mode,
course_id=course_id,
available=", ".join(available_modes)
)
log.warn(msg)
raise errors.CourseModeNotFoundError(msg, course_enrollment_info)
def unenroll_user_from_all_courses(user_id):
"""
Unenrolls a specified user from all of the courses they are currently enrolled in.
:param user_id: The id of the user being unenrolled.
:return: The IDs of all of the organizations from which the learner was unenrolled.
"""
return _data_api().unenroll_user_from_all_courses(user_id)
def _data_api():
"""Returns a Data API.
This relies on Django settings to find the appropriate data API.
"""
# We retrieve the settings in-line here (rather than using the
# top-level constant), so that @override_settings will work
# in the test suite.
api_path = getattr(settings, "ENROLLMENT_DATA_API", DEFAULT_DATA_API)
try:
return importlib.import_module(api_path)
except (ImportError, ValueError):
log.exception(u"Could not load module at '{path}'".format(path=api_path))
raise errors.EnrollmentApiLoadError(api_path) | unknown | codeparrot/codeparrot-clean | ||
{
"kind": "Dashboard",
"apiVersion": "dashboard.grafana.app/v2beta1",
"metadata": {
"name": "v0alpha1.relative_time_zone_support.v42"
},
"spec": {
"annotations": [
{
"kind": "AnnotationQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana",
"version": "v0",
"datasource": {
"name": "-- Grafana --"
},
"spec": {}
},
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations \u0026 Alerts",
"builtIn": true,
"legacyOptions": {
"type": "dashboard"
}
}
}
],
"cursorSync": "Off",
"editable": true,
"elements": {
"panel-2": {
"kind": "Panel",
"spec": {
"id": 2,
"title": "Panel in timezone",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"spec": {
"scenarioId": "random_walk",
"seriesCount": 1
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "table",
"version": "10.2.0-pre",
"spec": {
"options": {
"cellHeight": "sm",
"footer": {
"countRows": false,
"fields": "",
"reducer": [
"sum"
],
"show": false
},
"showHeader": true
},
"fieldConfig": {
"defaults": {
"thresholds": {
"mode": "absolute",
"steps": [
{
"value": null,
"color": "green"
},
{
"value": 80,
"color": "red"
}
]
},
"color": {
"mode": "thresholds"
},
"custom": {
"align": "auto",
"cellOptions": {
"type": "auto"
},
"inspect": false
}
},
"overrides": []
}
}
}
}
},
"panel-3": {
"kind": "Panel",
"spec": {
"id": 3,
"title": "Panel with relative time override",
"description": "",
"links": [],
"data": {
"kind": "QueryGroup",
"spec": {
"queries": [
{
"kind": "PanelQuery",
"spec": {
"query": {
"kind": "DataQuery",
"group": "grafana-testdata-datasource",
"version": "v0",
"spec": {
"scenarioId": "random_walk",
"seriesCount": 1
}
},
"refId": "A",
"hidden": false
}
}
],
"transformations": [],
"queryOptions": {
"timeFrom": "now/d"
}
}
},
"vizConfig": {
"kind": "VizConfig",
"group": "table",
"version": "10.2.0-pre",
"spec": {
"options": {
"cellHeight": "sm",
"footer": {
"countRows": false,
"fields": "",
"reducer": [
"sum"
],
"show": false
},
"showHeader": true
},
"fieldConfig": {
"defaults": {
"thresholds": {
"mode": "absolute",
"steps": [
{
"value": null,
"color": "green"
},
{
"value": 80,
"color": "red"
}
]
},
"color": {
"mode": "thresholds"
},
"custom": {
"align": "auto",
"cellOptions": {
"type": "auto"
},
"inspect": false
}
},
"overrides": []
}
}
}
}
}
},
"layout": {
"kind": "GridLayout",
"spec": {
"items": [
{
"kind": "GridLayoutItem",
"spec": {
"x": 0,
"y": 0,
"width": 12,
"height": 8,
"element": {
"kind": "ElementReference",
"name": "panel-2"
}
}
},
{
"kind": "GridLayoutItem",
"spec": {
"x": 12,
"y": 0,
"width": 12,
"height": 8,
"element": {
"kind": "ElementReference",
"name": "panel-3"
}
}
}
]
}
},
"links": [],
"liveNow": false,
"preload": false,
"tags": [],
"timeSettings": {
"timezone": "Asia/Tokyo",
"from": "now-3h",
"to": "now",
"autoRefresh": "",
"autoRefreshIntervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"hideTimepicker": false,
"fiscalYearStartMonth": 0
},
"title": "Panel Tests - Relative time zone support",
"variables": []
},
"status": {
"conversion": {
"failed": false,
"storedVersion": "v0alpha1"
}
}
} | json | github | https://github.com/grafana/grafana | apps/dashboard/pkg/migration/conversion/testdata/output/migrated_dev_dashboards/scenarios/v0alpha1.relative_time_zone_support.v42.v2beta1.json |
from __future__ import unicode_literals
import datetime
from django.db import models
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Author(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ('name',)
def __str__(self):
return self.name
class BetterAuthor(Author):
write_speed = models.IntegerField()
@python_2_unicode_compatible
class Book(models.Model):
author = models.ForeignKey(Author)
title = models.CharField(max_length=100)
class Meta:
unique_together = (
('author', 'title'),
)
ordering = ['id']
def __str__(self):
return self.title
@python_2_unicode_compatible
class BookWithCustomPK(models.Model):
my_pk = models.DecimalField(max_digits=5, decimal_places=0, primary_key=True)
author = models.ForeignKey(Author)
title = models.CharField(max_length=100)
def __str__(self):
return '%s: %s' % (self.my_pk, self.title)
class Editor(models.Model):
name = models.CharField(max_length=100)
@python_2_unicode_compatible
class BookWithOptionalAltEditor(models.Model):
author = models.ForeignKey(Author)
# Optional secondary author
alt_editor = models.ForeignKey(Editor, blank=True, null=True)
title = models.CharField(max_length=100)
class Meta:
unique_together = (
('author', 'title', 'alt_editor'),
)
def __str__(self):
return self.title
@python_2_unicode_compatible
class AlternateBook(Book):
notes = models.CharField(max_length=100)
def __str__(self):
return '%s - %s' % (self.title, self.notes)
@python_2_unicode_compatible
class AuthorMeeting(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
created = models.DateField(editable=False)
def __str__(self):
return self.name
class CustomPrimaryKey(models.Model):
my_pk = models.CharField(max_length=10, primary_key=True)
some_field = models.CharField(max_length=100)
# models for inheritance tests.
@python_2_unicode_compatible
class Place(models.Model):
name = models.CharField(max_length=50)
city = models.CharField(max_length=50)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Owner(models.Model):
auto_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
place = models.ForeignKey(Place)
def __str__(self):
return "%s at %s" % (self.name, self.place)
class Location(models.Model):
place = models.ForeignKey(Place, unique=True)
# this is purely for testing the data doesn't matter here :)
lat = models.CharField(max_length=100)
lon = models.CharField(max_length=100)
@python_2_unicode_compatible
class OwnerProfile(models.Model):
owner = models.OneToOneField(Owner, primary_key=True)
age = models.PositiveIntegerField()
def __str__(self):
return "%s is %d" % (self.owner.name, self.age)
@python_2_unicode_compatible
class Restaurant(Place):
serves_pizza = models.BooleanField()
def __str__(self):
return self.name
@python_2_unicode_compatible
class Product(models.Model):
slug = models.SlugField(unique=True)
def __str__(self):
return self.slug
@python_2_unicode_compatible
class Price(models.Model):
price = models.DecimalField(max_digits=10, decimal_places=2)
quantity = models.PositiveIntegerField()
def __str__(self):
return "%s for %s" % (self.quantity, self.price)
class Meta:
unique_together = (('price', 'quantity'),)
class MexicanRestaurant(Restaurant):
serves_tacos = models.BooleanField()
class ClassyMexicanRestaurant(MexicanRestaurant):
restaurant = models.OneToOneField(MexicanRestaurant, parent_link=True, primary_key=True)
tacos_are_yummy = models.BooleanField()
# models for testing unique_together validation when a fk is involved and
# using inlineformset_factory.
@python_2_unicode_compatible
class Repository(models.Model):
name = models.CharField(max_length=25)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Revision(models.Model):
repository = models.ForeignKey(Repository)
revision = models.CharField(max_length=40)
class Meta:
unique_together = (("repository", "revision"),)
def __str__(self):
return "%s (%s)" % (self.revision, six.text_type(self.repository))
# models for testing callable defaults (see bug #7975). If you define a model
# with a callable default value, you cannot rely on the initial value in a
# form.
class Person(models.Model):
name = models.CharField(max_length=128)
class Membership(models.Model):
person = models.ForeignKey(Person)
date_joined = models.DateTimeField(default=datetime.datetime.now)
karma = models.IntegerField()
# models for testing a null=True fk to a parent
class Team(models.Model):
name = models.CharField(max_length=100)
@python_2_unicode_compatible
class Player(models.Model):
team = models.ForeignKey(Team, null=True)
name = models.CharField(max_length=100)
def __str__(self):
return self.name
# Models for testing custom ModelForm save methods in formsets and inline formsets
@python_2_unicode_compatible
class Poet(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Poem(models.Model):
poet = models.ForeignKey(Poet)
name = models.CharField(max_length=100)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Post(models.Model):
title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
slug = models.CharField(max_length=50, unique_for_year='posted', blank=True)
subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True)
posted = models.DateField()
def __str__(self):
return self.name | unknown | codeparrot/codeparrot-clean | ||
from rdflib import URIRef, BNode, Literal
from rdflib.query import ResultSerializer
def _termString(t, namespace_manager):
if t == None:
return "-"
if namespace_manager:
if isinstance(t, URIRef):
return namespace_manager.normalizeUri(t)
elif isinstance(t, BNode):
return t.n3()
elif isinstance(t, Literal):
return t._literal_n3(qname_callback=namespace_manager.normalizeUri)
else:
return t.n3()
class TXTResultSerializer(ResultSerializer):
"""
A write only QueryResult serializer for text/ascii tables
"""
def serialize(self, stream, encoding, namespace_manager = None):
"""
return a text table of query results
"""
def c(s, w):
"""
center the string s in w wide string
"""
w -= len(s)
h1 = h2 = w // 2
if w % 2: h2 += 1
return " " * h1 + s + " " * h2
if self.result.type!='SELECT':
raise Exception("Can only pretty print SELECT results!")
if not self.result:
return "(no results)\n"
else:
keys = sorted(self.result.vars)
maxlen = [0] * len(keys)
b = [[_termString(r[k], namespace_manager) for k in keys] for r in self.result]
for r in b:
for i in range(len(keys)):
maxlen[i] = max(maxlen[i], len(r[i]))
stream.write(
"|".join([c(k, maxlen[i]) for i, k in enumerate(keys)]) + "\n")
stream.write("-" * (len(maxlen)+sum(maxlen)) + "\n")
for r in sorted(b):
stream.write("|".join(
[t + " " * (i - len(t)) for i, t in zip(maxlen, r)]) + "\n") | unknown | codeparrot/codeparrot-clean | ||
#ifndef READ_CACHE_LL_H
#define READ_CACHE_LL_H
#include "hash.h"
#include "hashmap.h"
#include "statinfo.h"
/*
* Basic data structures for the directory cache
*/
#define CACHE_SIGNATURE 0x44495243 /* "DIRC" */
struct cache_header {
uint32_t hdr_signature;
uint32_t hdr_version;
uint32_t hdr_entries;
};
#define INDEX_FORMAT_LB 2
#define INDEX_FORMAT_UB 4
struct cache_entry {
struct hashmap_entry ent;
struct stat_data ce_stat_data;
unsigned int ce_mode;
unsigned int ce_flags;
unsigned int mem_pool_allocated;
unsigned int ce_namelen;
unsigned int index; /* for link extension */
struct object_id oid;
char name[FLEX_ARRAY]; /* more */
};
#define CE_STAGEMASK (0x3000)
#define CE_EXTENDED (0x4000)
#define CE_VALID (0x8000)
#define CE_STAGESHIFT 12
/*
* Range 0xFFFF0FFF in ce_flags is divided into
* two parts: in-memory flags and on-disk ones.
* Flags in CE_EXTENDED_FLAGS will get saved on-disk
* if you want to save a new flag, add it in
* CE_EXTENDED_FLAGS
*
* In-memory only flags
*/
#define CE_UPDATE (1 << 16)
#define CE_REMOVE (1 << 17)
#define CE_UPTODATE (1 << 18)
#define CE_ADDED (1 << 19)
#define CE_HASHED (1 << 20)
#define CE_FSMONITOR_VALID (1 << 21)
#define CE_WT_REMOVE (1 << 22) /* remove in work directory */
#define CE_CONFLICTED (1 << 23)
#define CE_UNPACKED (1 << 24)
#define CE_NEW_SKIP_WORKTREE (1 << 25)
/* used to temporarily mark paths matched by pathspecs */
#define CE_MATCHED (1 << 26)
#define CE_UPDATE_IN_BASE (1 << 27)
#define CE_STRIP_NAME (1 << 28)
/*
* Extended on-disk flags
*/
#define CE_INTENT_TO_ADD (1 << 29)
#define CE_SKIP_WORKTREE (1 << 30)
/* CE_EXTENDED2 is for future extension */
#define CE_EXTENDED2 (1U << 31)
#define CE_EXTENDED_FLAGS (CE_INTENT_TO_ADD | CE_SKIP_WORKTREE)
/*
* Safeguard to avoid saving wrong flags:
* - CE_EXTENDED2 won't get saved until its semantic is known
* - Bits in 0x0000FFFF have been saved in ce_flags already
* - Bits in 0x003F0000 are currently in-memory flags
*/
#if CE_EXTENDED_FLAGS & 0x803FFFFF
#error "CE_EXTENDED_FLAGS out of range"
#endif
/* Forward structure decls */
struct pathspec;
struct tree;
/*
* Copy the sha1 and stat state of a cache entry from one to
* another. But we never change the name, or the hash state!
*/
static inline void copy_cache_entry(struct cache_entry *dst,
const struct cache_entry *src)
{
unsigned int state = dst->ce_flags & CE_HASHED;
int mem_pool_allocated = dst->mem_pool_allocated;
/* Don't copy hash chain and name */
memcpy(&dst->ce_stat_data, &src->ce_stat_data,
offsetof(struct cache_entry, name) -
offsetof(struct cache_entry, ce_stat_data));
/* Restore the hash state */
dst->ce_flags = (dst->ce_flags & ~CE_HASHED) | state;
/* Restore the mem_pool_allocated flag */
dst->mem_pool_allocated = mem_pool_allocated;
}
static inline unsigned create_ce_flags(unsigned stage)
{
return (stage << CE_STAGESHIFT);
}
#define ce_namelen(ce) ((ce)->ce_namelen)
#define ce_size(ce) cache_entry_size(ce_namelen(ce))
#define ce_stage(ce) ((CE_STAGEMASK & (ce)->ce_flags) >> CE_STAGESHIFT)
#define ce_uptodate(ce) ((ce)->ce_flags & CE_UPTODATE)
#define ce_skip_worktree(ce) ((ce)->ce_flags & CE_SKIP_WORKTREE)
#define ce_mark_uptodate(ce) ((ce)->ce_flags |= CE_UPTODATE)
#define ce_intent_to_add(ce) ((ce)->ce_flags & CE_INTENT_TO_ADD)
#define cache_entry_size(len) (offsetof(struct cache_entry,name) + (len) + 1)
#define SOMETHING_CHANGED (1 << 0) /* unclassified changes go here */
#define CE_ENTRY_CHANGED (1 << 1)
#define CE_ENTRY_REMOVED (1 << 2)
#define CE_ENTRY_ADDED (1 << 3)
#define RESOLVE_UNDO_CHANGED (1 << 4)
#define CACHE_TREE_CHANGED (1 << 5)
#define SPLIT_INDEX_ORDERED (1 << 6)
#define UNTRACKED_CHANGED (1 << 7)
#define FSMONITOR_CHANGED (1 << 8)
struct split_index;
struct untracked_cache;
struct progress;
struct pattern_list;
enum sparse_index_mode {
/*
* There are no sparse directories in the index at all.
*
* Repositories that don't use cone-mode sparse-checkout will
* always have their indexes in this mode.
*/
INDEX_EXPANDED = 0,
/*
* The index has already been collapsed to sparse directories
* wherever possible.
*/
INDEX_COLLAPSED,
/*
* The sparse directories that exist are outside the
* sparse-checkout boundary, but it is possible that some file
* entries could collapse to sparse directory entries.
*/
INDEX_PARTIALLY_SPARSE,
};
struct index_state {
struct cache_entry **cache;
unsigned int version;
unsigned int cache_nr, cache_alloc, cache_changed;
struct string_list *resolve_undo;
struct cache_tree *cache_tree;
struct split_index *split_index;
struct cache_time timestamp;
unsigned name_hash_initialized : 1,
initialized : 1,
drop_cache_tree : 1,
updated_workdir : 1,
updated_skipworktree : 1,
fsmonitor_has_run_once : 1;
enum sparse_index_mode sparse_index;
struct hashmap name_hash;
struct hashmap dir_hash;
struct object_id oid;
struct untracked_cache *untracked;
char *fsmonitor_last_update;
struct ewah_bitmap *fsmonitor_dirty;
struct mem_pool *ce_mem_pool;
struct progress *progress;
struct repository *repo;
struct pattern_list *sparse_checkout_patterns;
};
/**
* A "struct index_state istate" must be initialized with
* INDEX_STATE_INIT or the corresponding index_state_init().
*
* If the variable won't be used again, use release_index() to free()
* its resources. If it needs to be used again use discard_index(),
* which does the same thing, but will use index_state_init() at
* the end. The discard_index() will use its own "istate->repo" as the
* "r" argument to index_state_init() in that case.
*/
#define INDEX_STATE_INIT(r) { \
.repo = (r), \
}
void index_state_init(struct index_state *istate, struct repository *r);
void release_index(struct index_state *istate);
/* Cache entry creation and cleanup */
/*
* Create cache_entry intended for use in the specified index. Caller
* is responsible for discarding the cache_entry with
* `discard_cache_entry`.
*/
struct cache_entry *make_cache_entry(struct index_state *istate,
unsigned int mode,
const struct object_id *oid,
const char *path,
int stage,
unsigned int refresh_options);
struct cache_entry *make_empty_cache_entry(struct index_state *istate,
size_t name_len);
/*
* Create a cache_entry that is not intended to be added to an index. If
* `ce_mem_pool` is not NULL, the entry is allocated within the given memory
* pool. Caller is responsible for discarding "loose" entries with
* `discard_cache_entry()` and the memory pool with
* `mem_pool_discard(ce_mem_pool, should_validate_cache_entries())`.
*/
struct cache_entry *make_transient_cache_entry(unsigned int mode,
const struct object_id *oid,
const char *path,
int stage,
struct mem_pool *ce_mem_pool);
struct cache_entry *make_empty_transient_cache_entry(size_t len,
struct mem_pool *ce_mem_pool);
/*
* Discard cache entry.
*/
void discard_cache_entry(struct cache_entry *ce);
/*
* Check configuration if we should perform extra validation on cache
* entries.
*/
int should_validate_cache_entries(void);
/*
* Duplicate a cache_entry. Allocate memory for the new entry from a
* memory_pool. Takes into account cache_entry fields that are meant
* for managing the underlying memory allocation of the cache_entry.
*/
struct cache_entry *dup_cache_entry(const struct cache_entry *ce, struct index_state *istate);
/*
* Validate the cache entries in the index. This is an internal
* consistency check that the cache_entry structs are allocated from
* the expected memory pool.
*/
void validate_cache_entries(const struct index_state *istate);
/*
* Bulk prefetch all missing cache entries that are not GITLINKs and that match
* the given predicate. This function should only be called if
* repo_has_promisor_remote() returns true.
*/
typedef int (*must_prefetch_predicate)(const struct cache_entry *);
void prefetch_cache_entries(const struct index_state *istate,
must_prefetch_predicate must_prefetch);
/* Initialize and use the cache information */
struct lock_file;
int do_read_index(struct index_state *istate, const char *path,
int must_exist); /* for testting only! */
int read_index_from(struct index_state *, const char *path,
const char *gitdir);
int is_index_unborn(struct index_state *);
/* For use with `write_locked_index()`. */
#define COMMIT_LOCK (1 << 0)
#define SKIP_IF_UNCHANGED (1 << 1)
/*
* Write the index while holding an already-taken lock. Close the lock,
* and if `COMMIT_LOCK` is given, commit it.
*
* Unless a split index is in use, write the index into the lockfile.
*
* With a split index, write the shared index to a temporary file,
* adjust its permissions and rename it into place, then write the
* split index to the lockfile. If the temporary file for the shared
* index cannot be created, fall back to the behavior described in
* the previous paragraph.
*
* With `COMMIT_LOCK`, the lock is always committed or rolled back.
* Without it, the lock is closed, but neither committed nor rolled
* back.
*
* If `SKIP_IF_UNCHANGED` is given and the index is unchanged, nothing
* is written (and the lock is rolled back if `COMMIT_LOCK` is given).
*/
int write_locked_index(struct index_state *, struct lock_file *lock, unsigned flags);
void discard_index(struct index_state *);
void move_index_extensions(struct index_state *dst, struct index_state *src);
int unmerged_index(const struct index_state *);
/**
* Returns 1 if istate differs from tree, 0 otherwise. If tree is NULL,
* compares istate to HEAD. If tree is NULL and on an unborn branch,
* returns 1 if there are entries in istate, 0 otherwise. If an strbuf is
* provided, the space-separated list of files that differ will be appended
* to it.
*/
int repo_index_has_changes(struct repository *repo,
struct tree *tree,
struct strbuf *sb);
int verify_path(const char *path, unsigned mode);
int strcmp_offset(const char *s1, const char *s2, size_t *first_change);
/*
* Searches for an entry defined by name and namelen in the given index.
* If the return value is positive (including 0) it is the position of an
* exact match. If the return value is negative, the negated value minus 1
* is the position where the entry would be inserted.
* Example: The current index consists of these files and its stages:
*
* b#0, d#0, f#1, f#3
*
* index_name_pos(&index, "a", 1) -> -1
* index_name_pos(&index, "b", 1) -> 0
* index_name_pos(&index, "c", 1) -> -2
* index_name_pos(&index, "d", 1) -> 1
* index_name_pos(&index, "e", 1) -> -3
* index_name_pos(&index, "f", 1) -> -3
* index_name_pos(&index, "g", 1) -> -5
*/
int index_name_pos(struct index_state *, const char *name, int namelen);
/*
* Like index_name_pos, returns the position of an entry of the given name in
* the index if one exists, otherwise returns a negative value where the negated
* value minus 1 is the position where the index entry would be inserted. Unlike
* index_name_pos, however, a sparse index is not expanded to find an entry
* inside a sparse directory.
*/
int index_name_pos_sparse(struct index_state *, const char *name, int namelen);
/*
* Determines whether an entry with the given name exists within the
* given index. The return value is 1 if an exact match is found, otherwise
* it is 0. Note that, unlike index_name_pos, this function does not expand
* the index if it is sparse. If an item exists within the full index but it
* is contained within a sparse directory (and not in the sparse index), 0 is
* returned.
*/
int index_entry_exists(struct index_state *, const char *name, int namelen);
/*
* Some functions return the negative complement of an insert position when a
* precise match was not found but a position was found where the entry would
* need to be inserted. This helper protects that logic from any integer
* underflow.
*/
static inline int index_pos_to_insert_pos(uintmax_t pos)
{
if (pos > INT_MAX)
die("overflow: -1 - %"PRIuMAX, pos);
return -1 - (int)pos;
}
#define ADD_CACHE_OK_TO_ADD 1 /* Ok to add */
#define ADD_CACHE_OK_TO_REPLACE 2 /* Ok to replace file/directory */
#define ADD_CACHE_SKIP_DFCHECK 4 /* Ok to skip DF conflict checks */
#define ADD_CACHE_JUST_APPEND 8 /* Append only */
#define ADD_CACHE_NEW_ONLY 16 /* Do not replace existing ones */
#define ADD_CACHE_KEEP_CACHE_TREE 32 /* Do not invalidate cache-tree */
#define ADD_CACHE_RENORMALIZE 64 /* Pass along HASH_RENORMALIZE */
int add_index_entry(struct index_state *, struct cache_entry *ce, int option);
void rename_index_entry_at(struct index_state *, int pos, const char *new_name);
/* Remove entry, return true if there are more entries to go. */
int remove_index_entry_at(struct index_state *, int pos);
void remove_marked_cache_entries(struct index_state *istate, int invalidate);
int remove_file_from_index(struct index_state *, const char *path);
#define ADD_CACHE_VERBOSE 1
#define ADD_CACHE_PRETEND 2
#define ADD_CACHE_IGNORE_ERRORS 4
#define ADD_CACHE_IGNORE_REMOVAL 8
#define ADD_CACHE_INTENT 16
/*
* These two are used to add the contents of the file at path
* to the index, marking the working tree up-to-date by storing
* the cached stat info in the resulting cache entry. A caller
* that has already run lstat(2) on the path can call
* add_to_index(), and all others can call add_file_to_index();
* the latter will do necessary lstat(2) internally before
* calling the former.
*/
int add_to_index(struct index_state *, const char *path, struct stat *, int flags);
int add_file_to_index(struct index_state *, const char *path, int flags);
int chmod_index_entry(struct index_state *, struct cache_entry *ce, char flip);
int ce_same_name(const struct cache_entry *a, const struct cache_entry *b);
void set_object_name_for_intent_to_add_entry(struct cache_entry *ce);
int index_name_is_other(struct index_state *, const char *, int);
void *read_blob_data_from_index(struct index_state *, const char *, unsigned long *);
/* do stat comparison even if CE_VALID is true */
#define CE_MATCH_IGNORE_VALID 01
/* do not check the contents but report dirty on racily-clean entries */
#define CE_MATCH_RACY_IS_DIRTY 02
/* do stat comparison even if CE_SKIP_WORKTREE is true */
#define CE_MATCH_IGNORE_SKIP_WORKTREE 04
/* ignore non-existent files during stat update */
#define CE_MATCH_IGNORE_MISSING 0x08
/* enable stat refresh */
#define CE_MATCH_REFRESH 0x10
/* don't refresh_fsmonitor state or do stat comparison even if CE_FSMONITOR_VALID is true */
#define CE_MATCH_IGNORE_FSMONITOR 0X20
int is_racy_timestamp(const struct index_state *istate,
const struct cache_entry *ce);
int has_racy_timestamp(struct index_state *istate);
int ie_match_stat(struct index_state *, const struct cache_entry *, struct stat *, unsigned int);
int ie_modified(struct index_state *, const struct cache_entry *, struct stat *, unsigned int);
int match_stat_data_racy(const struct index_state *istate,
const struct stat_data *sd, struct stat *st);
void fill_stat_cache_info(struct index_state *istate, struct cache_entry *ce, struct stat *st);
/*
* Fill members of st by members of sd enough to convince match_stat()
* to consider that they match. It should be usable as a replacement
* for lstat() for a tracked path that is known to be up-to-date via
* some out-of-line means (like fsmonitor).
*/
int fake_lstat(const struct cache_entry *ce, struct stat *st);
#define REFRESH_REALLY (1 << 0) /* ignore_valid */
#define REFRESH_UNMERGED (1 << 1) /* allow unmerged */
#define REFRESH_QUIET (1 << 2) /* be quiet about it */
#define REFRESH_IGNORE_MISSING (1 << 3) /* ignore non-existent */
#define REFRESH_IGNORE_SUBMODULES (1 << 4) /* ignore submodules */
#define REFRESH_IN_PORCELAIN (1 << 5) /* user friendly output, not "needs update" */
#define REFRESH_PROGRESS (1 << 6) /* show progress bar if stderr is tty */
#define REFRESH_IGNORE_SKIP_WORKTREE (1 << 7) /* ignore skip_worktree entries */
int refresh_index(struct index_state *, unsigned int flags, const struct pathspec *pathspec, char *seen, const char *header_msg);
/*
* Refresh the index and write it to disk.
*
* 'refresh_flags' is passed directly to 'refresh_index()', while
* 'COMMIT_LOCK | write_flags' is passed to 'write_locked_index()', so
* the lockfile is always either committed or rolled back.
*
* If 'gentle' is passed, errors locking the index are ignored.
*
* Return 1 if refreshing the index returns an error, -1 if writing
* the index to disk fails, 0 on success.
*
* Note that if refreshing the index returns an error, we still write
* out the index (unless locking fails).
*/
int repo_refresh_and_write_index(struct repository*, unsigned int refresh_flags, unsigned int write_flags, int gentle, const struct pathspec *, char *seen, const char *header_msg);
struct cache_entry *refresh_cache_entry(struct index_state *, struct cache_entry *, unsigned int);
void set_alternate_index_output(const char *);
extern int verify_index_checksum;
extern int verify_ce_order;
int cmp_cache_name_compare(const void *a_, const void *b_);
int add_files_to_cache(struct repository *repo, const char *prefix,
const struct pathspec *pathspec, char *ps_matched,
int include_sparse, int flags);
void overlay_tree_on_index(struct index_state *istate,
const char *tree_name, const char *prefix);
#endif /* READ_CACHE_LL_H */ | c | github | https://github.com/git/git | read-cache-ll.h |
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# This is a DOCUMENTATION stub specific to this module, it extends
# a documentation fragment located in ansible.utils.module_docs_fragments
DOCUMENTATION = '''
---
module: rax_clb
short_description: create / delete a load balancer in Rackspace Public Cloud
description:
- creates / deletes a Rackspace Public Cloud load balancer.
version_added: "1.4"
options:
algorithm:
description:
- algorithm for the balancer being created
choices:
- RANDOM
- LEAST_CONNECTIONS
- ROUND_ROBIN
- WEIGHTED_LEAST_CONNECTIONS
- WEIGHTED_ROUND_ROBIN
default: LEAST_CONNECTIONS
meta:
description:
- A hash of metadata to associate with the instance
default: null
name:
description:
- Name to give the load balancer
default: null
port:
description:
- Port for the balancer being created
default: 80
protocol:
description:
- Protocol for the balancer being created
choices:
- DNS_TCP
- DNS_UDP
- FTP
- HTTP
- HTTPS
- IMAPS
- IMAPv4
- LDAP
- LDAPS
- MYSQL
- POP3
- POP3S
- SMTP
- TCP
- TCP_CLIENT_FIRST
- UDP
- UDP_STREAM
- SFTP
default: HTTP
state:
description:
- Indicate desired state of the resource
choices:
- present
- absent
default: present
timeout:
description:
- timeout for communication between the balancer and the node
default: 30
type:
description:
- type of interface for the balancer being created
choices:
- PUBLIC
- SERVICENET
default: PUBLIC
vip_id:
description:
- Virtual IP ID to use when creating the load balancer for purposes of
sharing an IP with another load balancer of another protocol
version_added: 1.5
wait:
description:
- wait for the balancer to be in state 'running' before returning
default: "no"
choices:
- "yes"
- "no"
wait_timeout:
description:
- how long before wait gives up, in seconds
default: 300
author:
- "Christopher H. Laco (@claco)"
- "Matt Martz (@sivel)"
extends_documentation_fragment: rackspace
'''
EXAMPLES = '''
- name: Build a Load Balancer
gather_facts: False
hosts: local
connection: local
tasks:
- name: Load Balancer create request
local_action:
module: rax_clb
credentials: ~/.raxpub
name: my-lb
port: 8080
protocol: HTTP
type: SERVICENET
timeout: 30
region: DFW
wait: yes
state: present
meta:
app: my-cool-app
register: my_lb
'''
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def cloud_load_balancer(module, state, name, meta, algorithm, port, protocol,
vip_type, timeout, wait, wait_timeout, vip_id):
if int(timeout) < 30:
module.fail_json(msg='"timeout" must be greater than or equal to 30')
changed = False
balancers = []
clb = pyrax.cloud_loadbalancers
if not clb:
module.fail_json(msg='Failed to instantiate client. This '
'typically indicates an invalid region or an '
'incorrectly capitalized region name.')
balancer_list = clb.list()
while balancer_list:
retrieved = clb.list(marker=balancer_list.pop().id)
balancer_list.extend(retrieved)
if len(retrieved) < 2:
break
for balancer in balancer_list:
if name != balancer.name and name != balancer.id:
continue
balancers.append(balancer)
if len(balancers) > 1:
module.fail_json(msg='Multiple Load Balancers were matched by name, '
'try using the Load Balancer ID instead')
if state == 'present':
if isinstance(meta, dict):
metadata = [dict(key=k, value=v) for k, v in meta.items()]
if not balancers:
try:
virtual_ips = [clb.VirtualIP(type=vip_type, id=vip_id)]
balancer = clb.create(name, metadata=metadata, port=port,
algorithm=algorithm, protocol=protocol,
timeout=timeout, virtual_ips=virtual_ips)
changed = True
except Exception, e:
module.fail_json(msg='%s' % e.message)
else:
balancer = balancers[0]
setattr(balancer, 'metadata',
[dict(key=k, value=v) for k, v in
balancer.get_metadata().items()])
atts = {
'name': name,
'algorithm': algorithm,
'port': port,
'protocol': protocol,
'timeout': timeout
}
for att, value in atts.iteritems():
current = getattr(balancer, att)
if current != value:
changed = True
if changed:
balancer.update(**atts)
if balancer.metadata != metadata:
balancer.set_metadata(meta)
changed = True
virtual_ips = [clb.VirtualIP(type=vip_type)]
current_vip_types = set([v.type for v in balancer.virtual_ips])
vip_types = set([v.type for v in virtual_ips])
if current_vip_types != vip_types:
module.fail_json(msg='Load balancer Virtual IP type cannot '
'be changed')
if wait:
attempts = wait_timeout / 5
pyrax.utils.wait_for_build(balancer, interval=5, attempts=attempts)
balancer.get()
instance = rax_to_dict(balancer, 'clb')
result = dict(changed=changed, balancer=instance)
if balancer.status == 'ERROR':
result['msg'] = '%s failed to build' % balancer.id
elif wait and balancer.status not in ('ACTIVE', 'ERROR'):
result['msg'] = 'Timeout waiting on %s' % balancer.id
if 'msg' in result:
module.fail_json(**result)
else:
module.exit_json(**result)
elif state == 'absent':
if balancers:
balancer = balancers[0]
try:
balancer.delete()
changed = True
except Exception, e:
module.fail_json(msg='%s' % e.message)
instance = rax_to_dict(balancer, 'clb')
if wait:
attempts = wait_timeout / 5
pyrax.utils.wait_until(balancer, 'status', ('DELETED'),
interval=5, attempts=attempts)
else:
instance = {}
module.exit_json(changed=changed, balancer=instance)
def main():
argument_spec = rax_argument_spec()
argument_spec.update(
dict(
algorithm=dict(choices=CLB_ALGORITHMS,
default='LEAST_CONNECTIONS'),
meta=dict(type='dict', default={}),
name=dict(required=True),
port=dict(type='int', default=80),
protocol=dict(choices=CLB_PROTOCOLS, default='HTTP'),
state=dict(default='present', choices=['present', 'absent']),
timeout=dict(type='int', default=30),
type=dict(choices=['PUBLIC', 'SERVICENET'], default='PUBLIC'),
vip_id=dict(),
wait=dict(type='bool'),
wait_timeout=dict(default=300),
)
)
module = AnsibleModule(
argument_spec=argument_spec,
required_together=rax_required_together(),
)
if not HAS_PYRAX:
module.fail_json(msg='pyrax is required for this module')
algorithm = module.params.get('algorithm')
meta = module.params.get('meta')
name = module.params.get('name')
port = module.params.get('port')
protocol = module.params.get('protocol')
state = module.params.get('state')
timeout = int(module.params.get('timeout'))
vip_id = module.params.get('vip_id')
vip_type = module.params.get('type')
wait = module.params.get('wait')
wait_timeout = int(module.params.get('wait_timeout'))
setup_rax_module(module, pyrax)
cloud_load_balancer(module, state, name, meta, algorithm, port, protocol,
vip_type, timeout, wait, wait_timeout, vip_id)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.rax import *
### invoke the module
main() | unknown | codeparrot/codeparrot-clean | ||
from ROOT import gDirectory, TH2F, TH1F, TFile
class Fitter2D(object):
def __init__(self, *args):
self.h2d = TH2F(*args)
def draw2D(self, *args):
self.h2d.Draw(*args)
self.hmean.Draw('psame')
def fit(self, bin, opt='0'):
hslice = self.h2d.ProjectionY("", bin, bin, "")
if not hslice.GetEntries():
return 0., 0., 0., 0., 0., 0.
hslice.Fit('gaus', opt)
func = hslice.GetFunction('gaus')
x = self.h2d.GetXaxis().GetBinCenter(bin)
dx = self.h2d.GetXaxis().GetBinWidth(bin)
mean = func.GetParameter(1)
dmean = func.GetParError(1)
sigma = func.GetParameter(2)
dsigma = func.GetParError(2)
return x, dx, mean, dmean, sigma, dsigma
def fit_slices(self):
self.h2d.FitSlicesY()
self.hmean = gDirectory.Get( self.h2d.GetName() + '_1' )
self.hsigma = gDirectory.Get( self.h2d.GetName() + '_2' )
# self.hsigma.SetYTitle('#sigma(MET_{x,y})')
self.hchi2 = gDirectory.Get( self.h2d.GetName() + '_chi2' )
def format(self, style, xtitle):
for hist in [self.hmean, self.hsigma, self.hchi2]:
style.format(hist)
hist.SetTitle('')
hist.SetXTitle(xtitle)
def write(self):
outfile = TFile(self.h2d.GetName()+'.root', 'recreate')
for hist in [self.hmean, self.hsigma, self.hchi2, self.h2d]:
hist.Clone()
hist.SetDirectory(outfile)
outfile.Write()
outfile.Close() | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
#
# Copyright (c) 2001 - 2016 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__revision__ = "test/Fortran/F77FILESUFFIXES2.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
import TestSCons
from common import write_fake_link
_python_ = TestSCons._python_
_exe = TestSCons._exe
test = TestSCons.TestSCons()
write_fake_link(test)
test.write('myfortran.py', r"""
import getopt
import sys
comment = '#' + sys.argv[1]
opts, args = getopt.getopt(sys.argv[2:], 'co:')
for opt, arg in opts:
if opt == '-o': out = arg
infile = open(args[0], 'rb')
outfile = open(out, 'wb')
for l in infile.readlines():
if l[:len(comment)] != comment:
outfile.write(l)
sys.exit(0)
""")
# Test non-default file suffix: .f/.F for F77
test.write('SConstruct', """
env = Environment(LINK = r'%(_python_)s mylink.py',
LINKFLAGS = [],
F77 = r'%(_python_)s myfortran.py g77',
F95 = r'%(_python_)s myfortran.py f95',
F77FILESUFFIXES = ['.f', '.F'],
tools = ['default', 'f77'])
env.Program(target = 'test01', source = 'test01.f')
env.Program(target = 'test02', source = 'test02.F')
env.Program(target = 'test05', source = 'test05.f95')
env.Program(target = 'test06', source = 'test06.F95')
""" % locals())
test.write('test01.f', "This is a .f file.\n#link\n#g77\n")
test.write('test02.F', "This is a .F file.\n#link\n#g77\n")
test.write('test05.f95', "This is a .f95 file.\n#link\n#f95\n")
test.write('test06.F95', "This is a .F95 file.\n#link\n#f95\n")
test.run(arguments = '.', stderr = None)
test.must_match('test01' + _exe, "This is a .f file.\n")
test.must_match('test02' + _exe, "This is a .F file.\n")
test.must_match('test05' + _exe, "This is a .f95 file.\n")
test.must_match('test06' + _exe, "This is a .F95 file.\n")
test.pass_test()
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: | unknown | codeparrot/codeparrot-clean | ||
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"io"
"path/filepath"
"sort"
"strings"
)
/*
* Helpers for building cmd/go and cmd/cgo.
*/
// generatedHeader is the string that all source files generated by dist start with.
//
// DO NOT CHANGE THIS STRING. If this string is changed then during
//
// ./make.bash
// git checkout other-rev
// ./make.bash
//
// the second make.bash will not find the files generated by the first make.bash
// and will not clean up properly.
const generatedHeader = "// Code generated by go tool dist; DO NOT EDIT.\n\n"
// writeHeader emits the standard "generated by" header for all files generated
// by dist.
func writeHeader(w io.Writer) {
fmt.Fprint(w, generatedHeader)
}
// mkzdefaultcc writes zdefaultcc.go:
//
// package main
// const defaultCC = <defaultcc>
// const defaultCXX = <defaultcxx>
// const defaultPkgConfig = <defaultpkgconfig>
//
// It is invoked to write cmd/go/internal/cfg/zdefaultcc.go
// but we also write cmd/cgo/zdefaultcc.go
func mkzdefaultcc(dir, file string) {
if strings.Contains(file, filepath.FromSlash("go/internal/cfg")) {
var buf strings.Builder
writeHeader(&buf)
fmt.Fprintf(&buf, "package cfg\n")
fmt.Fprintln(&buf)
fmt.Fprintf(&buf, "const DefaultPkgConfig = `%s`\n", defaultpkgconfig)
buf.WriteString(defaultCCFunc("DefaultCC", defaultcc))
buf.WriteString(defaultCCFunc("DefaultCXX", defaultcxx))
writefile(buf.String(), file, writeSkipSame)
return
}
var buf strings.Builder
writeHeader(&buf)
fmt.Fprintf(&buf, "package main\n")
fmt.Fprintln(&buf)
fmt.Fprintf(&buf, "const defaultPkgConfig = `%s`\n", defaultpkgconfig)
buf.WriteString(defaultCCFunc("defaultCC", defaultcc))
buf.WriteString(defaultCCFunc("defaultCXX", defaultcxx))
writefile(buf.String(), file, writeSkipSame)
}
func defaultCCFunc(name string, defaultcc map[string]string) string {
var buf strings.Builder
fmt.Fprintf(&buf, "func %s(goos, goarch string) string {\n", name)
fmt.Fprintf(&buf, "\tswitch goos+`/`+goarch {\n")
var keys []string
for k := range defaultcc {
if k != "" {
keys = append(keys, k)
}
}
sort.Strings(keys)
for _, k := range keys {
fmt.Fprintf(&buf, "\tcase %s:\n\t\treturn %s\n", quote(k), quote(defaultcc[k]))
}
fmt.Fprintf(&buf, "\t}\n")
if cc := defaultcc[""]; cc != "" {
fmt.Fprintf(&buf, "\treturn %s\n", quote(cc))
} else {
clang, gcc := "clang", "gcc"
if strings.HasSuffix(name, "CXX") {
clang, gcc = "clang++", "g++"
}
fmt.Fprintf(&buf, "\tswitch goos {\n")
fmt.Fprintf(&buf, "\tcase ")
for i, os := range clangos {
if i > 0 {
fmt.Fprintf(&buf, ", ")
}
fmt.Fprintf(&buf, "%s", quote(os))
}
fmt.Fprintf(&buf, ":\n")
fmt.Fprintf(&buf, "\t\treturn %s\n", quote(clang))
fmt.Fprintf(&buf, "\t}\n")
fmt.Fprintf(&buf, "\treturn %s\n", quote(gcc))
}
fmt.Fprintf(&buf, "}\n")
return buf.String()
}
// mktzdata src/time/tzdata/zzipdata.go:
//
// package tzdata
// const zipdata = "PK..."
func mktzdata(dir, file string) {
zip := readfile(filepath.Join(dir, "../../../lib/time/zoneinfo.zip"))
var buf strings.Builder
writeHeader(&buf)
fmt.Fprintf(&buf, "package tzdata\n")
fmt.Fprintln(&buf)
fmt.Fprintf(&buf, "const zipdata = %s\n", quote(zip))
writefile(buf.String(), file, writeSkipSame)
}
// quote is like strconv.Quote but simpler and has output
// that does not depend on the exact Go bootstrap version.
func quote(s string) string {
const hex = "0123456789abcdef"
var out strings.Builder
out.WriteByte('"')
for i := 0; i < len(s); i++ {
c := s[i]
if 0x20 <= c && c <= 0x7E && c != '"' && c != '\\' {
out.WriteByte(c)
} else {
out.WriteByte('\\')
out.WriteByte('x')
out.WriteByte(hex[c>>4])
out.WriteByte(hex[c&0xf])
}
}
out.WriteByte('"')
return out.String()
} | go | github | https://github.com/golang/go | src/cmd/dist/buildgo.go |
from multiprocessing import sharedctypes
from numpy import ctypeslib
import numpy as np
def wrap_params(params):
"""
For each parameter in a list of Theano TensorSharedVariable
we substitute the memory with a sharedctype using the
multiprocessing library.
The wrapped memory can then be used by other child processes
thereby synchronising different instances of a model across
processes (e.g. for multi cpu gradient descent using single cpu
Theano code).
Inputs:
-------
params list<TensorSharedVariable /> : the list of shared Theano
variables
Outputs:
--------
wrapped_instances list<multiprocessing.sharedctypes> : list of
sharedctypes (shared memory arrays) that point to the memory
used by the current process's Theano variable.
Usage:
------
# define some theano model:
mymodel = MyModel(20, 50, etc...)
# wrap the memory of the Theano variables:
shared_ctypes = wrap_params(mymodel.params)
Then you can use this memory in child processes
(See usage of `borrow_memory`)
"""
wrapped_instances = []
for param in params:
original = param.get_value(True,True)
size = original.size
shape = original.shape
original.shape = size
ctypes = sharedctypes.RawArray('f' if original.dtype == np.float32 else 'd', original)
wrapped = np.frombuffer(ctypes, dtype=original.dtype, count=size)
wrapped.shape = shape
param.set_value(wrapped, borrow=True)
wrapped_instances.append(ctypes)
return wrapped_instances
def borrow_memory(param, memory):
"""
Spawn different processes with the shared memory
of your theano model's variables.
Inputs:
-------
param TensorSharedVariable : the Theano shared variable where
shared memory should be used instead.
memory multiprocessing.sharedctypes : the memory shared across processes (e.g.
from `wrap_params`)
Outputs:
--------
None
Usage
-----
For each process in the target function run the theano_borrow_memory
method on the parameters you want to have share memory across processes.
In this example we have a model called "mymodel" with parameters stored in
a list called "params". We loop through each theano shared variable and
call `theano_borrow_memory` on it to share memory across processes.
def spawn_model(path, wrapped_params):
# prevent recompilation and arbitrary locks
theano.config.reoptimize_unpickled_function = False
theano.gof.compilelock.set_lock_status(False)
# load your model from its pickled instance (from path)
mymodel = MyModel.load(path)
# for each parameter in your model
# apply the borrow memory strategy to replace
# the internal parameter's memory with the
# across-process memory
for param, memory in zip(mymodel.params, wrapped_params):
borrow_memory(param, memory)
# acquire your dataset (either through some smart shared memory
# or by reloading it for each process)
dataset, dataset_labels = acquire_dataset()
# then run your model forward in this process
epochs = 20
for epoch in range(epochs):
model.update_fun(dataset, dataset_labels)
See `borrow_all_memories` for list usage.
"""
param_value = ctypeslib.as_array(memory)
param_value.shape = param.get_value(True,True).shape
param.set_value(param_value, borrow=True)
def borrow_all_memories(params, memory_handlers):
"""
Run theano_borrow_memory on a list of params and shared memory
sharedctypes.
Inputs:
-------
param list<TensorSharedVariable> : list of Theano shared variable where
shared memory should be used instead.
memory list<multiprocessing.sharedctypes> : list of memory shared across processes (e.g.
from `wrap_params`)
Outputs:
--------
None
Usage:
------
Same as `borrow_memory` but for lists of shared memories and
theano variables. See `borrow_memory`
"""
for param, memory_handler in zip(params, memory_handlers):
borrow_memory(param, memory_handler) | unknown | codeparrot/codeparrot-clean | ||
package command
import (
"fmt"
"github.com/moby/term"
"github.com/spf13/cobra"
)
// SetupRootCommand sets default usage, help, and error handling for the
// root command.
func SetupRootCommand(rootCmd *cobra.Command) {
cobra.AddTemplateFunc("wrappedFlagUsages", wrappedFlagUsages)
rootCmd.SetUsageTemplate(usageTemplate)
rootCmd.SetHelpTemplate(helpTemplate)
rootCmd.SetFlagErrorFunc(FlagErrorFunc)
rootCmd.SetVersionTemplate("Docker version {{.Version}}\n")
rootCmd.PersistentFlags().BoolP("help", "h", false, "Print usage")
rootCmd.PersistentFlags().MarkShorthandDeprecated("help", "please use --help")
}
// FlagErrorFunc prints an error message which matches the format of the
// docker/docker/cli error messages
func FlagErrorFunc(cmd *cobra.Command, err error) error {
if err == nil {
return nil
}
usage := ""
if cmd.HasSubCommands() {
usage = "\n\n" + cmd.UsageString()
}
return StatusError{
Status: fmt.Sprintf("%s\nSee '%s --help'.%s", err, cmd.CommandPath(), usage),
StatusCode: 125,
}
}
func wrappedFlagUsages(cmd *cobra.Command) string {
width := 80
if ws, err := term.GetWinsize(0); err == nil {
width = int(ws.Width)
}
return cmd.Flags().FlagUsagesWrapped(width - 1)
}
const usageTemplate = `Usage: {{.UseLine}}
{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}}
{{- end}}
{{- if gt .Aliases 0}}
Aliases:
{{.NameAndAliases}}
{{- end}}
{{- if .HasExample}}
Examples:
{{ .Example }}
{{- end}}
{{- if .HasAvailableSubCommands}}
Commands:
{{- range .Commands }}
{{rpad .Name .NamePadding }} {{.Short}}
{{- end}}
{{- end}}
{{- if .HasAvailableFlags}}
Options:
{{ wrappedFlagUsages . | trimRightSpace}}
{{- end}}
`
const helpTemplate = `
{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` | go | github | https://github.com/moby/moby | daemon/command/cobra.go |
# @vue/runtime-dom
```js
import { h, createApp } from '@vue/runtime-dom'
const RootComponent = {
render() {
return h('div', 'hello world')
},
}
createApp(RootComponent).mount('#app')
``` | unknown | github | https://github.com/vuejs/core | packages/runtime-dom/README.md |
{
"name": "typescript",
"author": "Microsoft Corp.",
"homepage": "https://www.typescriptlang.org/",
"version": "6.0.0",
"license": "Apache-2.0",
"description": "TypeScript is a language for application scale JavaScript development",
"keywords": [
"TypeScript",
"Microsoft",
"compiler",
"language",
"javascript"
],
"bugs": {
"url": "https://github.com/microsoft/TypeScript/issues"
},
"repository": {
"type": "git",
"url": "https://github.com/microsoft/TypeScript.git"
},
"main": "./lib/typescript.js",
"typings": "./lib/typescript.d.ts",
"bin": {
"tsc": "./bin/tsc",
"tsserver": "./bin/tsserver"
},
"engines": {
"node": ">=14.17"
},
"files": [
"bin",
"lib",
"!lib/enu",
"LICENSE.txt",
"README.md",
"SECURITY.md",
"ThirdPartyNoticeText.txt",
"!**/.gitattributes"
],
"devDependencies": {
"@dprint/formatter": "^0.4.1",
"@dprint/typescript": "0.93.4",
"@esfx/canceltoken": "^1.0.0",
"@eslint/js": "^9.39.1",
"@octokit/rest": "^22.0.1",
"@types/chai": "^4.3.20",
"@types/minimist": "^1.2.5",
"@types/mocha": "^10.0.10",
"@types/ms": "^2.1.0",
"@types/node": "latest",
"@types/source-map-support": "^0.5.10",
"@types/which": "^3.0.4",
"@typescript-eslint/rule-tester": "^8.47.0",
"@typescript-eslint/type-utils": "^8.47.0",
"@typescript-eslint/utils": "^8.47.0",
"azure-devops-node-api": "^15.1.1",
"c8": "^10.1.3",
"chai": "^4.5.0",
"chokidar": "^4.0.3",
"diff": "^8.0.2",
"dprint": "^0.49.1",
"esbuild": "^0.27.0",
"eslint": "^9.39.1",
"eslint-formatter-autolinkable-stylish": "^1.4.0",
"eslint-plugin-regexp": "^2.10.0",
"fast-xml-parser": "^5.3.2",
"glob": "^10.5.0",
"globals": "^16.5.0",
"hereby": "^1.11.1",
"jsonc-parser": "^3.3.1",
"knip": "^5.70.0",
"minimist": "^1.2.8",
"mocha": "^10.8.2",
"mocha-fivemat-progress-reporter": "^0.1.0",
"monocart-coverage-reports": "^2.12.9",
"ms": "^2.1.3",
"picocolors": "^1.1.1",
"playwright": "^1.56.1",
"source-map-support": "^0.5.21",
"tslib": "^2.8.1",
"typescript": "^5.9.3",
"typescript-eslint": "^8.47.0",
"which": "^3.0.1"
},
"overrides": {
"typescript@*": "$typescript"
},
"scripts": {
"test": "hereby runtests-parallel --light=false",
"test:eslint-rules": "hereby run-eslint-rules-tests",
"build": "npm run build:compiler && npm run build:tests",
"build:compiler": "hereby local",
"build:tests": "hereby tests",
"build:tests:notypecheck": "hereby tests --no-typecheck",
"clean": "hereby clean",
"gulp": "hereby",
"lint": "hereby lint",
"knip": "hereby knip",
"format": "dprint fmt",
"setup-hooks": "node scripts/link-hooks.mjs"
},
"browser": {
"fs": false,
"os": false,
"path": false,
"crypto": false,
"buffer": false,
"source-map-support": false,
"inspector": false,
"perf_hooks": false
},
"packageManager": "npm@8.19.4",
"volta": {
"node": "20.1.0",
"npm": "8.19.4"
}
} | json | github | https://github.com/microsoft/TypeScript | package.json |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.collect;
import static java.util.Arrays.asList;
import com.google.common.base.Function;
import com.google.common.collect.testing.QueueTestSuiteBuilder;
import com.google.common.collect.testing.TestStringQueueGenerator;
import com.google.common.collect.testing.features.CollectionFeature;
import com.google.common.collect.testing.features.CollectionSize;
import com.google.common.testing.ForwardingWrapperTester;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Queue;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jspecify.annotations.NullUnmarked;
import org.jspecify.annotations.Nullable;
/**
* Tests for {@code ForwardingQueue}.
*
* @author Robert Konigsberg
* @author Louis Wasserman
*/
@NullUnmarked
public class ForwardingQueueTest extends TestCase {
static final class StandardImplForwardingQueue<T> extends ForwardingQueue<T> {
private final Queue<T> backingQueue;
StandardImplForwardingQueue(Queue<T> backingQueue) {
this.backingQueue = backingQueue;
}
@Override
protected Queue<T> delegate() {
return backingQueue;
}
@Override
public boolean addAll(Collection<? extends T> collection) {
return standardAddAll(collection);
}
@Override
public void clear() {
standardClear();
}
@Override
public boolean contains(Object object) {
return standardContains(object);
}
@Override
public boolean containsAll(Collection<?> collection) {
return standardContainsAll(collection);
}
@Override
public boolean remove(Object object) {
return standardRemove(object);
}
@Override
public boolean removeAll(Collection<?> collection) {
return standardRemoveAll(collection);
}
@Override
public boolean retainAll(Collection<?> collection) {
return standardRetainAll(collection);
}
@Override
public Object[] toArray() {
return standardToArray();
}
@Override
public <T> T[] toArray(T[] array) {
return standardToArray(array);
}
@Override
public String toString() {
return standardToString();
}
@Override
public boolean offer(T o) {
return standardOffer(o);
}
@Override
public @Nullable T peek() {
return standardPeek();
}
@Override
public @Nullable T poll() {
return standardPoll();
}
}
@AndroidIncompatible // test-suite builders
public static Test suite() {
TestSuite suite = new TestSuite();
suite.addTestSuite(ForwardingQueueTest.class);
suite.addTest(
QueueTestSuiteBuilder.using(
new TestStringQueueGenerator() {
@Override
protected Queue<String> create(String[] elements) {
return new StandardImplForwardingQueue<>(new LinkedList<>(asList(elements)));
}
})
.named("ForwardingQueue[LinkedList] with standard implementations")
.withFeatures(
CollectionSize.ANY,
CollectionFeature.ALLOWS_NULL_VALUES,
CollectionFeature.GENERAL_PURPOSE)
.createTestSuite());
return suite;
}
@SuppressWarnings({"rawtypes", "unchecked"})
public void testForwarding() {
new ForwardingWrapperTester()
.testForwarding(
Queue.class,
new Function<Queue, Queue>() {
@Override
public Queue apply(Queue delegate) {
return wrap(delegate);
}
});
}
private static <T> Queue<T> wrap(Queue<T> delegate) {
return new ForwardingQueue<T>() {
@Override
protected Queue<T> delegate() {
return delegate;
}
};
}
} | java | github | https://github.com/google/guava | android/guava-tests/test/com/google/common/collect/ForwardingQueueTest.java |
#!/usr/bin/python
#
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
# Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: avi_cloudconnectoruser
author: Gaurav Rastogi (@grastogi23) <grastogi@avinetworks.com>
short_description: Module for setup of CloudConnectorUser Avi RESTful Object
description:
- This module is used to configure CloudConnectorUser object
- more examples at U(https://github.com/avinetworks/devops)
requirements: [ avisdk ]
version_added: "2.4"
options:
state:
description:
- The state that should be applied on the entity.
default: present
choices: ["absent", "present"]
avi_api_update_method:
description:
- Default method for object update is HTTP PUT.
- Setting to patch will override that behavior to use HTTP PATCH.
version_added: "2.5"
default: put
choices: ["put", "patch"]
avi_api_patch_op:
description:
- Patch operation to use when using avi_api_update_method as patch.
version_added: "2.5"
choices: ["add", "replace", "delete"]
azure_serviceprincipal:
description:
- Field introduced in 17.2.1.
version_added: "2.5"
azure_userpass:
description:
- Field introduced in 17.2.1.
version_added: "2.5"
gcp_credentials:
description:
- Credentials for google cloud platform.
- Field introduced in 18.2.1.
version_added: "2.9"
name:
description:
- Name of the object.
required: true
oci_credentials:
description:
- Credentials for oracle cloud infrastructure.
- Field introduced in 18.2.1,18.1.3.
version_added: "2.9"
private_key:
description:
- Private_key of cloudconnectoruser.
public_key:
description:
- Public_key of cloudconnectoruser.
tenant_ref:
description:
- It is a reference to an object of type tenant.
tencent_credentials:
description:
- Credentials for tencent cloud.
- Field introduced in 18.2.3.
version_added: "2.9"
url:
description:
- Avi controller URL of the object.
uuid:
description:
- Unique object identifier of the object.
extends_documentation_fragment:
- avi
'''
EXAMPLES = """
- name: Create a Cloud connector user that is used for integration into cloud platforms
avi_cloudconnectoruser:
controller: '{{ controller }}'
name: root
password: '{{ password }}'
private_key: |
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----'
public_key: 'ssh-rsa ...'
tenant_ref: admin
username: '{{ username }}'
"""
RETURN = '''
obj:
description: CloudConnectorUser (api/cloudconnectoruser) object
returned: success, changed
type: dict
'''
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.network.avi.avi import (
avi_common_argument_spec, avi_ansible_api, HAS_AVI)
except ImportError:
HAS_AVI = False
def main():
argument_specs = dict(
state=dict(default='present',
choices=['absent', 'present']),
avi_api_update_method=dict(default='put',
choices=['put', 'patch']),
avi_api_patch_op=dict(choices=['add', 'replace', 'delete']),
azure_serviceprincipal=dict(type='dict',),
azure_userpass=dict(type='dict',),
gcp_credentials=dict(type='dict',),
name=dict(type='str', required=True),
oci_credentials=dict(type='dict',),
private_key=dict(type='str', no_log=True,),
public_key=dict(type='str',),
tenant_ref=dict(type='str',),
tencent_credentials=dict(type='dict',),
url=dict(type='str',),
uuid=dict(type='str',),
)
argument_specs.update(avi_common_argument_spec())
module = AnsibleModule(
argument_spec=argument_specs, supports_check_mode=True)
if not HAS_AVI:
return module.fail_json(msg=(
'Avi python API SDK (avisdk>=17.1) or requests is not installed. '
'For more details visit https://github.com/avinetworks/sdk.'))
return avi_ansible_api(module, 'cloudconnectoruser',
set(['private_key']))
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
"""
Compatibility constants and functions. This module works on Python 1.5 to 2.5.
This module provides:
- True and False constants ;
- any() and all() function ;
- has_yield and has_slice values ;
- isinstance() with Python 2.3 behaviour ;
- reversed() and sorted() function.
True and False constants
========================
Truth constants: True is yes (one) and False is no (zero).
>>> int(True), int(False) # int value
(1, 0)
>>> int(False | True) # and binary operator
1
>>> int(True & False) # or binary operator
0
>>> int(not(True) == False) # not binary operator
1
Warning: on Python smaller than 2.3, True and False are aliases to
number 1 and 0. So "print True" will displays 1 and not True.
any() function
==============
any() returns True if at least one items is True, or False otherwise.
>>> any([False, True])
True
>>> any([True, True])
True
>>> any([False, False])
False
all() function
==============
all() returns True if all items are True, or False otherwise.
This function is just apply binary and operator (&) on all values.
>>> all([True, True])
True
>>> all([False, True])
False
>>> all([False, False])
False
has_yield boolean
=================
has_yield: boolean which indicatese if the interpreter supports yield keyword.
yield keyworkd is available since Python 2.0.
has_yield boolean
=================
has_slice: boolean which indicates if the interpreter supports slices with step
argument or not. slice with step is available since Python 2.3.
reversed() and sorted() function
================================
reversed() and sorted() function has been introduced in Python 2.4.
It's should returns a generator, but this module it may be a list.
>>> data = list("cab")
>>> list(sorted(data))
['a', 'b', 'c']
>>> list(reversed("abc"))
['c', 'b', 'a']
"""
import copy
import operator
# --- True and False constants from Python 2.0 ---
# --- Warning: for Python < 2.3, they are aliases for 1 and 0 ---
try:
True = True
False = False
except NameError:
True = 1
False = 0
# --- any() from Python 2.5 ---
try:
from __builtin__ import any
except ImportError:
def any(items):
for item in items:
if item:
return True
return False
# ---all() from Python 2.5 ---
try:
from __builtin__ import all
except ImportError:
def all(items):
return reduce(operator.__and__, items)
# --- test if interpreter supports yield keyword ---
try:
eval(compile("""
from __future__ import generators
def gen():
yield 1
yield 2
if list(gen()) != [1, 2]:
raise KeyError("42")
""", "<string>", "exec"))
except (KeyError, SyntaxError):
has_yield = False
else:
has_yield = True
# --- test if interpreter supports slices (with step argument) ---
try:
has_slice = eval('"abc"[::-1] == "cba"')
except (TypeError, SyntaxError):
has_slice = False
# --- isinstance with isinstance Python 2.3 behaviour (arg 2 is a type) ---
try:
if isinstance(1, int):
from __builtin__ import isinstance
except TypeError:
print "Redef isinstance"
def isinstance20(a, typea):
if type(typea) != type(type):
raise TypeError("TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types")
return type(typea) != typea
isinstance = isinstance20
# --- reversed() from Python 2.4 ---
try:
from __builtin__ import reversed
except ImportError:
# if hasYield() == "ok":
# code = """
#def reversed(data):
# for index in xrange(len(data)-1, -1, -1):
# yield data[index];
#reversed"""
# reversed = eval(compile(code, "<string>", "exec"))
if has_slice:
def reversed(data):
if not isinstance(data, list):
data = list(data)
return data[::-1]
else:
def reversed(data):
if not isinstance(data, list):
data = list(data)
reversed_data = []
for index in xrange(len(data)-1, -1, -1):
reversed_data.append(data[index])
return reversed_data
# --- sorted() from Python 2.4 ---
try:
from __builtin__ import sorted
except ImportError:
def sorted(data):
sorted_data = copy.copy(data)
sorted_data.sort()
return sorted
__all__ = ("True", "False",
"any", "all", "has_yield", "has_slice",
"isinstance", "reversed", "sorted") | unknown | codeparrot/codeparrot-clean | ||
"""ThreatConnect API Service App"""
# third-party
import falcon
# first-party
from api_service_app import ApiServiceApp # Import default API Service Class (Required)
from tcex import TcEx
class TcExMiddleware:
"""TcEx middleware module.
Adds access to self.args, self.tcex and self.log in resource Class.
"""
def __init__(self, args: object, tcex: TcEx):
"""Initialize class properties.
Args:
args: The argparser arg namespace.
tcex: An instance of tcex
"""
self.args = args
self.tcex = tcex
# properties
self.log = tcex.log
def process_resource( # pylint: disable=no-self-use,unused-argument
self, req: falcon.Request, resp: falcon.Response, resource: object, params: dict
):
"""Process resource method."""
resource.args = self.args
resource.log = self.log
resource.tcex = self.tcex
class OneResource:
"""Handle request to /one endpoint."""
# provided by TcEx middleware
args = None
log = None
tcex = None
def on_get(self, req, resp): # pylint: disable=no-self-use,unused-argument
"""Handle GET requests"""
data = {'data': 'one'}
resp.media = data
class TwoResource:
"""Handle request to /two endpoint."""
# provided by TcEx middleware
args = None
log = None
tcex = None
def on_get(self, req, resp): # pylint: disable=no-self-use,unused-argument
"""Handle GET requests"""
data = {'data': 'two'}
resp.media = data
class App(ApiServiceApp):
"""API Service App"""
def __init__(self, _tcex):
"""Initialize class properties."""
super().__init__(_tcex)
# create Falcon API with tcex middleware
self.api = falcon.API(middleware=[TcExMiddleware(args=self.args, tcex=self.tcex)])
# Add routes
self.api.add_route('/one', OneResource())
self.api.add_route('/two', TwoResource())
self.tcex.log.trace(f'args: {self.tcex.args}')
def api_event_callback(self, environ, response_handler):
"""Run the trigger logic."""
return self.api(environ, response_handler) | unknown | codeparrot/codeparrot-clean | ||
#ifndef SERVER_INFO_H
#define SERVER_INFO_H
struct repository;
/* Dumb servers support */
int update_server_info(struct repository *r, int force);
#endif /* SERVER_INFO_H */ | c | github | https://github.com/git/git | server-info.h |
# -*- coding: utf-8 -*-
#
# Cuckoo Sandbox documentation build configuration file.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Cuckoo Sandbox'
copyright = u'2010-2015, Cuckoo Foundation'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '1.2'
# The full version, including alpha/beta/rc tags.
release = '1.2'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = en
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "%s v%s Book" % (project, version)
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_images/logo/cuckoo.png"
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_domain_indices = False
# If false, no index is generated.
html_use_index = False
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'CuckooSandboxdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'CuckooSandbox.tex', u'Cuckoo Sandbox Book',
u'Cuckoo Sandbox', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'cuckoosandbox', u'Cuckoo Sandbox Book',
[u'Cuckoo Sandbox'], 1)
] | unknown | codeparrot/codeparrot-clean | ||
import sys, os
# Quick hack to put frontendadmin from the parent directory into pythonpath
# If this is not working correctly, uncomment these lines and put
# frontendadmin manually into pythonpath.
sys.path.append(
os.path.abspath(
os.path.normpath('%s/../' % os.path.dirname(__file__))
)
)
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'myproject.db' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'site_media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/site_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = '^6qlxq*maky)*u!fl+!_97m^zcywod0c)tujsm5+fngj1+y55x'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.auth',
'django.core.context_processors.debug',
'django.core.context_processors.i18n',
'django.core.context_processors.media',
)
ROOT_URLCONF = 'example_project.urls'
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.comments',
'django.contrib.flatpages',
# Put frontendadmin before your applications, so that they can overwrite
# the frontendadmin templates.
'frontendadmin',
'example_project.weblog',
)
# Define custom forms to handle any model
FRONTEND_FORMS = {
# ``app_label.model_name`` : ``form_class``,
'weblog.entry': 'weblog.forms.EntryForm',
}
# Define which fields to exclude on a particular model
FRONTEND_EXCLUDES = {
# ``app_label.model_name`` : ``tuple``,
'weblog.entry': ('public',),
} | unknown | codeparrot/codeparrot-clean | ||
# -*- coding: utf-8 -*-
# See the "Code officiel géographique" on the INSEE website <www.insee.fr>.
DEPARTMENT_CHOICES = (
# Metropolitan departments
('01', u'01 - Ain'),
('02', u'02 - Aisne'),
('03', u'03 - Allier'),
('04', u'04 - Alpes-de-Haute-Provence'),
('05', u'05 - Hautes-Alpes'),
('06', u'06 - Alpes-Maritimes'),
('07', u'07 - Ardèche'),
('08', u'08 - Ardennes'),
('09', u'09 - Ariège'),
('10', u'10 - Aube'),
('11', u'11 - Aude'),
('12', u'12 - Aveyron'),
('13', u'13 - Bouches-du-Rhône'),
('14', u'14 - Calvados'),
('15', u'15 - Cantal'),
('16', u'16 - Charente'),
('17', u'17 - Charente-Maritime'),
('18', u'18 - Cher'),
('19', u'19 - Corrèze'),
('2A', u'2A - Corse-du-Sud'),
('2B', u'2B - Haute-Corse'),
('21', u'21 - Côte-d\'Or'),
('22', u'22 - Côtes-d\'Armor'),
('23', u'23 - Creuse'),
('24', u'24 - Dordogne'),
('25', u'25 - Doubs'),
('26', u'26 - Drôme'),
('27', u'27 - Eure'),
('28', u'28 - Eure-et-Loir'),
('29', u'29 - Finistère'),
('30', u'30 - Gard'),
('31', u'31 - Haute-Garonne'),
('32', u'32 - Gers'),
('33', u'33 - Gironde'),
('34', u'34 - Hérault'),
('35', u'35 - Ille-et-Vilaine'),
('36', u'36 - Indre'),
('37', u'37 - Indre-et-Loire'),
('38', u'38 - Isère'),
('39', u'39 - Jura'),
('40', u'40 - Landes'),
('41', u'41 - Loir-et-Cher'),
('42', u'42 - Loire'),
('43', u'43 - Haute-Loire'),
('44', u'44 - Loire-Atlantique'),
('45', u'45 - Loiret'),
('46', u'46 - Lot'),
('47', u'47 - Lot-et-Garonne'),
('48', u'48 - Lozère'),
('49', u'49 - Maine-et-Loire'),
('50', u'50 - Manche'),
('51', u'51 - Marne'),
('52', u'52 - Haute-Marne'),
('53', u'53 - Mayenne'),
('54', u'54 - Meurthe-et-Moselle'),
('55', u'55 - Meuse'),
('56', u'56 - Morbihan'),
('57', u'57 - Moselle'),
('58', u'58 - Nièvre'),
('59', u'59 - Nord'),
('60', u'60 - Oise'),
('61', u'61 - Orne'),
('62', u'62 - Pas-de-Calais'),
('63', u'63 - Puy-de-Dôme'),
('64', u'64 - Pyrénées-Atlantiques'),
('65', u'65 - Hautes-Pyrénées'),
('66', u'66 - Pyrénées-Orientales'),
('67', u'67 - Bas-Rhin'),
('68', u'68 - Haut-Rhin'),
('69', u'69 - Rhône'),
('70', u'70 - Haute-Saône'),
('71', u'71 - Saône-et-Loire'),
('72', u'72 - Sarthe'),
('73', u'73 - Savoie'),
('74', u'74 - Haute-Savoie'),
('75', u'75 - Paris'),
('76', u'76 - Seine-Maritime'),
('77', u'77 - Seine-et-Marne'),
('78', u'78 - Yvelines'),
('79', u'79 - Deux-Sèvres'),
('80', u'80 - Somme'),
('81', u'81 - Tarn'),
('82', u'82 - Tarn-et-Garonne'),
('83', u'83 - Var'),
('84', u'84 - Vaucluse'),
('85', u'85 - Vendée'),
('86', u'86 - Vienne'),
('87', u'87 - Haute-Vienne'),
('88', u'88 - Vosges'),
('89', u'89 - Yonne'),
('90', u'90 - Territoire de Belfort'),
('91', u'91 - Essonne'),
('92', u'92 - Hauts-de-Seine'),
('93', u'93 - Seine-Saint-Denis'),
('94', u'94 - Val-de-Marne'),
('95', u'95 - Val-d\'Oise'),
# Overseas departments, communities, and other territories
('971', u'971 - Guadeloupe'),
('972', u'972 - Martinique'),
('973', u'973 - Guyane'),
('974', u'974 - La Réunion'),
('975', u'975 - Saint-Pierre-et-Miquelon'),
('976', u'976 - Mayotte'),
('977', u'977 - Saint-Barthélemy'),
('978', u'978 - Saint-Martin'),
('984', u'984 - Terres australes et antarctiques françaises'),
('986', u'986 - Wallis et Futuna'),
('987', u'987 - Polynésie française'),
('988', u'988 - Nouvelle-Calédonie'),
('989', u'989 - Île de Clipperton'),
) | unknown | codeparrot/codeparrot-clean | ||
/* Copyright 2024 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_COMPILER_MLIR_LITE_PYTHON_INTERPRETER_WRAPPER_PYTHON_UTILS_H_
#define TENSORFLOW_COMPILER_MLIR_LITE_PYTHON_INTERPRETER_WRAPPER_PYTHON_UTILS_H_
#include <Python.h>
#include <cstddef>
namespace mlirlite {
namespace python_utils {
struct PyDecrefDeleter {
void operator()(PyObject* p) const { Py_DECREF(p); }
};
int ConvertFromPyString(PyObject* obj, char** data, Py_ssize_t* length);
PyObject* ConvertToPyString(const char* data, size_t length);
} // namespace python_utils
} // namespace mlirlite
#endif // TENSORFLOW_COMPILER_MLIR_LITE_PYTHON_INTERPRETER_WRAPPER_PYTHON_UTILS_H_ | c | github | https://github.com/tensorflow/tensorflow | tensorflow/compiler/mlir/lite/python/interpreter_wrapper/python_utils.h |
#!/usr/bin/env python
import argparse
import os
import time
import Common
import Mif
import Parser
"""
Title: Assembler for RISC_721
Author: Connor Goldberg
"""
def main(args):
start = time.clock()
assemblyFile = args["assembly-file"]
output = args["output"]
if output == None:
programOutput = os.path.join(os.path.split(os.path.abspath(assemblyFile))[0],os.path.splitext(os.path.basename(assemblyFile))[0]+".mif")
dataOutput = os.path.join(os.path.split(os.path.abspath(assemblyFile))[0],os.path.splitext(os.path.basename(assemblyFile))[0]+"_dm.mif")
elif not output.endswith(".mif"):
programOutput = output + ".mif"
dataOutput = output + "_dm.mif"
else:
programOutput = output
split = os.path.splitext(output)
dataOutput = split[0] + "_dm"
if len(split) == 2:
dataOutput = dataOutput + split[1]
else:
dataOutput = dataOutput + ".mif"
stuffMem = 0
if args["stuff"] is not None:
try:
if args["stuff"].upper().startswith("0X"):
stuffMem = int(args["stuff"], 16)
else:
stuffMem = int(args["stuff"])
except Exception as e:
Common.Error("Cannot stuff with: {}".format(args["stuff"]))
programMif = Mif.Mif(format_=args["format"], output=programOutput, width=args["width"], addressWidth=args["address_width"], memoryWidth=args["memory_width"], headers=["Program memory for: %s" % assemblyFile], stuffWith=stuffMem)
dataMif = Mif.Mif(format_=args["format"], output=dataOutput, width=args["width"], addressWidth=args["address_width"], memoryWidth=args["memory_width"], headers=["Data memory for: %s" % assemblyFile], stuffWith=stuffMem)
myParser = Parser.Parser(assemblyFile, width=args["width"], addressWidth=args["address_width"], memoryWidth=args["memory_width"], canInclude=True)
myParser.Parse()
programMif.AddData(myParser.GetAssemblyData()).Write()
dataMif.AddData(Parser.Parser.GetInterruptVectorTable()).AddData(myParser.GetConstantsData()).Write()
end = time.clock()
print "Successfully assembled {} into {}{}".format(assemblyFile, programOutput, " and "+dataOutput if dataMif.Data else '')
print "Time elapsed: %s ms" % str(round(float(end-start)*1000,3))
print "Completed on %s at %s" % (time.strftime("%m/%d/%Y"), time.strftime("%I:%M:%S"))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Assembler for RISC_721 by Connor Goldberg")
parser.add_argument("assembly-file", help="File to be assembled")
parser.add_argument("-o", "--output", metavar="out-file", type=str, help="The path of the MIF file")
parser.add_argument("-a", "--address_width", metavar="address-width", type=int, help="The width of the address bus", default=16)
parser.add_argument("-m", "--memory_width", metavar="memory-width", type=int, help="The width of a word in memory in bits (default = 8)", default=8)
parser.add_argument("-w", "--width", metavar="width", type=int, help="The width of instruction words in bits (default = 32)", default=32)
parser.add_argument("-f", "--format", metavar="format", type=str, help="The output format of the assembled mif file", choices=["altera","cadence"], default="cadence")
parser.add_argument("-s", "--stuff", metavar="stuff", type=str, help="Specify if uninitialized values should be exlicitly written")
args = vars(parser.parse_args())
main(args) | unknown | codeparrot/codeparrot-clean | ||
// Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package server_test
import (
"os"
"testing"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/kv/kvclient/kvtenant"
"github.com/cockroachdb/cockroach/pkg/security/securityassets"
"github.com/cockroachdb/cockroach/pkg/security/securitytest"
"github.com/cockroachdb/cockroach/pkg/server"
"github.com/cockroachdb/cockroach/pkg/server/rangetestutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/testcluster"
)
func TestMain(m *testing.M) {
securityassets.SetLoader(securitytest.EmbeddedAssets)
serverutils.InitTestServerFactory(server.TestServerFactory)
serverutils.InitTestClusterFactory(testcluster.TestClusterFactory)
rangetestutils.InitRangeTestServerFactory(server.TestServerFactory)
kvtenant.InitTestConnectorFactory()
defer serverutils.TestingSetDefaultTenantSelectionOverride(
base.TestIsForStuffThatShouldWorkWithSecondaryTenantsButDoesntYet(156304),
)()
defer serverutils.TestingGlobalDRPCOption(
base.TestDRPCEnabledRandomly,
)()
os.Exit(m.Run())
}
//go:generate ../util/leaktest/add-leaktest.sh *_test.go | go | github | https://github.com/cockroachdb/cockroach | pkg/server/main_test.go |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = r'''
---
module: slurp
version_added: historical
short_description: Slurps a file from remote nodes
description:
- This module works like M(fetch). It is used for fetching a base64-
encoded blob containing the data in a remote file.
- This module is also supported for Windows targets.
options:
src:
description:
- The file on the remote system to fetch. This I(must) be a file, not a directory.
type: path
required: true
aliases: [ path ]
notes:
- This module returns an 'in memory' base64 encoded version of the file, take into account that this will require at least twice the RAM as the
original file size.
- This module is also supported for Windows targets.
seealso:
- module: fetch
author:
- Ansible Core Team
- Michael DeHaan (@mpdehaan)
'''
EXAMPLES = r'''
- name: Find out what the remote machine's mounts are
slurp:
src: /proc/mounts
register: mounts
- debug:
msg: "{{ mounts['content'] | b64decode }}"
# From the commandline, find the pid of the remote machine's sshd
# $ ansible host -m slurp -a 'src=/var/run/sshd.pid'
# host | SUCCESS => {
# "changed": false,
# "content": "MjE3OQo=",
# "encoding": "base64",
# "source": "/var/run/sshd.pid"
# }
# $ echo MjE3OQo= | base64 -d
# 2179
'''
import base64
import os
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
src=dict(type='path', required=True, aliases=['path']),
),
supports_check_mode=True,
)
source = module.params['src']
if not os.path.exists(source):
module.fail_json(msg="file not found: %s" % source)
if not os.access(source, os.R_OK):
module.fail_json(msg="file is not readable: %s" % source)
with open(source, 'rb') as source_fh:
source_content = source_fh.read()
data = base64.b64encode(source_content)
module.exit_json(content=data, source=source, encoding='base64')
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from . import models
class WatchedInline(GenericTabularInline):
model = models.Watched
extra = 0 | unknown | codeparrot/codeparrot-clean | ||
"""
Parallelization utilities
"""
from functools import reduce
import multiprocessing
class Sketch(object):
@staticmethod
def initializer(cls, *args):
"""
FIXME: use of global not really nice (possible root of mysterious issue for user)
"""
global sketch_constructor
def sketch_constructor():
return cls(*args)
@staticmethod
def map_sequence(sequence):
"""
- sequence: a bytes-like object
return: a sketch
"""
mhs = sketch_constructor()
mhs.add(sequence)
return mhs
@staticmethod
def map_sequences(iterable):
"""
- iterable: an iterable of bytes-like objects
return: a sketch
"""
mhs = sketch_constructor()
for sequence in iterable:
mhs.add(sequence)
return mhs
@staticmethod
def reduce(a, b):
"""
Update the sketch a with the content of sketch b.
- a: a sketch
- b: a sketch
return a.update(b)
"""
a.update(b)
return a
class SketchList(object):
@staticmethod
def initializer(clslist, argslist):
"""
FIXME: use of global not really nice (possible root of mysterious issue for user)
"""
# Allow automagic expansion of the list of classes
if len(clslist) == 1:
clslist = tuple(clslist[0] for x in range(len(argslist)))
# Allow automagic expansion of the list of args
if len(argslist) == 1:
argslist = tuple(argslist[0] for x in range(len(clslist)))
if len(clslist) != len(argslist):
raise ValueError("The arguments argslist and clslist must be sequences of either the "
"same length, or of length 1.")
global sketchlist_constructor
def sketchlist_constructor():
return (cls(*args) for cls, args in zip(clslist, argslist))
@staticmethod
def map_sequence(sequence):
"""
- sequence: a bytes-like object
return: a sketch
"""
mhslist = tuple(sketchlist_constructor())
for mhs in mhslist:
mhs.add(sequence)
return mhslist
@staticmethod
def map_sequences(iterable):
"""
- iterable: an iterable of bytes-like objects
return: a sketch
"""
mhslist = sketchlist_constructor()
for sequence in iterable:
for mhs in mhslist:
mhs.add(sequence)
return mhs
@staticmethod
def reduce(alist, blist):
"""
Update the sketch a with the content of sketch b.
- alist: a sequence of sketches
- blist: a sequence of sketches
return alist after each of its elements has been updated to the corresponding element in blist
"""
for a,b in zip(alist, blist):
a.update(b)
return alist | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.ruby as ruby
import logging
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICMicrogenerator()
library = gapic.ruby_library(
"apigateway", "v1",
generator_args={
"ruby-cloud-gem-name": "google-cloud-api_gateway",
"ruby-cloud-title": "API Gateway",
"ruby-cloud-description": "API Gateway enables you to provide secure access to your backend services through a well-defined REST API that is consistent across all of your services, regardless of the service implementation. Clients consume your REST APIS to implement standalone apps for a mobile device or tablet, through apps running in a browser, or through any other type of app that can make a request to an HTTP endpoint.",
"ruby-cloud-env-prefix": "API_GATEWAY",
"ruby-cloud-wrapper-of": "v1:0.1",
"ruby-cloud-product-url": "https://cloud.google.com/api-gateway/",
"ruby-cloud-api-id": "apigateway.googleapis.com",
"ruby-cloud-api-shortname": "apigateway",
}
)
s.copy(library, merge=ruby.global_merge) | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright © 2012 Thomas Krug
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from optparse import OptionParser
import xmmsclient
import os
import sys
parser = OptionParser()
parser.add_option("-n", "--next",
action="store_true", dest="next", default=False,
help="switch to next playlist")
parser.add_option("-p", "--prev",
action="store_true", dest="prev", default=False,
help="switch to previous playlist")
(options, args) = parser.parse_args()
if options.next and options.prev:
parser.error("options -n and -p are mutually exclusive")
sys.exit(1)
xmms = xmmsclient.XMMSSync("xmms2switch")
try:
xmms.connect(os.getenv("XMMS_PATH"))
except IOError, detail:
print "Error:", detail
sys.exit(1)
playlist_cur = xmms.playlist_current_active()
position_cur = 0
position = 0
playlists = []
for playlist in xmms.playlist_list():
if not playlist.startswith("_"):
playlists.append(playlist)
if playlist == playlist_cur:
position_cur = position
position += 1
if options.next:
position_new = position_cur + 1
if position_new >= position:
position_new -= position
xmms.playlist_load(playlists[position_new])
if options.prev:
position_new = position_cur - 1
if position_new < 0:
position_new += position
xmms.playlist_load(playlists[position_new])
xmms.disconnect() | unknown | codeparrot/codeparrot-clean | ||
"Test searchengine, coverage 99%."
from idlelib import searchengine as se
import unittest
# from test.support import requires
from tkinter import BooleanVar, StringVar, TclError # ,Tk, Text
from tkinter import messagebox
from idlelib.idle_test.mock_tk import Var, Mbox
from idlelib.idle_test.mock_tk import Text as mockText
import re
# With mock replacements, the module does not use any gui widgets.
# The use of tk.Text is avoided (for now, until mock Text is improved)
# by patching instances with an index function returning what is needed.
# This works because mock Text.get does not use .index.
# The tkinter imports are used to restore searchengine.
def setUpModule():
# Replace s-e module tkinter imports other than non-gui TclError.
se.BooleanVar = Var
se.StringVar = Var
se.messagebox = Mbox
def tearDownModule():
# Restore 'just in case', though other tests should also replace.
se.BooleanVar = BooleanVar
se.StringVar = StringVar
se.messagebox = messagebox
class Mock:
def __init__(self, *args, **kwargs): pass
class GetTest(unittest.TestCase):
# SearchEngine.get returns singleton created & saved on first call.
def test_get(self):
saved_Engine = se.SearchEngine
se.SearchEngine = Mock # monkey-patch class
try:
root = Mock()
engine = se.get(root)
self.assertIsInstance(engine, se.SearchEngine)
self.assertIs(root._searchengine, engine)
self.assertIs(se.get(root), engine)
finally:
se.SearchEngine = saved_Engine # restore class to module
class GetLineColTest(unittest.TestCase):
# Test simple text-independent helper function
def test_get_line_col(self):
self.assertEqual(se.get_line_col('1.0'), (1, 0))
self.assertEqual(se.get_line_col('1.11'), (1, 11))
self.assertRaises(ValueError, se.get_line_col, ('1.0 lineend'))
self.assertRaises(ValueError, se.get_line_col, ('end'))
class GetSelectionTest(unittest.TestCase):
# Test text-dependent helper function.
## # Need gui for text.index('sel.first/sel.last/insert').
## @classmethod
## def setUpClass(cls):
## requires('gui')
## cls.root = Tk()
##
## @classmethod
## def tearDownClass(cls):
## cls.root.destroy()
## del cls.root
def test_get_selection(self):
# text = Text(master=self.root)
text = mockText()
text.insert('1.0', 'Hello World!')
# fix text.index result when called in get_selection
def sel(s):
# select entire text, cursor irrelevant
if s == 'sel.first': return '1.0'
if s == 'sel.last': return '1.12'
raise TclError
text.index = sel # replaces .tag_add('sel', '1.0, '1.12')
self.assertEqual(se.get_selection(text), ('1.0', '1.12'))
def mark(s):
# no selection, cursor after 'Hello'
if s == 'insert': return '1.5'
raise TclError
text.index = mark # replaces .mark_set('insert', '1.5')
self.assertEqual(se.get_selection(text), ('1.5', '1.5'))
class ReverseSearchTest(unittest.TestCase):
# Test helper function that searches backwards within a line.
def test_search_reverse(self):
Equal = self.assertEqual
line = "Here is an 'is' test text."
prog = re.compile('is')
Equal(se.search_reverse(prog, line, len(line)).span(), (12, 14))
Equal(se.search_reverse(prog, line, 14).span(), (12, 14))
Equal(se.search_reverse(prog, line, 13).span(), (5, 7))
Equal(se.search_reverse(prog, line, 7).span(), (5, 7))
Equal(se.search_reverse(prog, line, 6), None)
class SearchEngineTest(unittest.TestCase):
# Test class methods that do not use Text widget.
def setUp(self):
self.engine = se.SearchEngine(root=None)
# Engine.root is only used to create error message boxes.
# The mock replacement ignores the root argument.
def test_is_get(self):
engine = self.engine
Equal = self.assertEqual
Equal(engine.getpat(), '')
engine.setpat('hello')
Equal(engine.getpat(), 'hello')
Equal(engine.isre(), False)
engine.revar.set(1)
Equal(engine.isre(), True)
Equal(engine.iscase(), False)
engine.casevar.set(1)
Equal(engine.iscase(), True)
Equal(engine.isword(), False)
engine.wordvar.set(1)
Equal(engine.isword(), True)
Equal(engine.iswrap(), True)
engine.wrapvar.set(0)
Equal(engine.iswrap(), False)
Equal(engine.isback(), False)
engine.backvar.set(1)
Equal(engine.isback(), True)
def test_setcookedpat(self):
engine = self.engine
engine.setcookedpat(r'\s')
self.assertEqual(engine.getpat(), r'\s')
engine.revar.set(1)
engine.setcookedpat(r'\s')
self.assertEqual(engine.getpat(), r'\\s')
def test_getcookedpat(self):
engine = self.engine
Equal = self.assertEqual
Equal(engine.getcookedpat(), '')
engine.setpat('hello')
Equal(engine.getcookedpat(), 'hello')
engine.wordvar.set(True)
Equal(engine.getcookedpat(), r'\bhello\b')
engine.wordvar.set(False)
engine.setpat(r'\s')
Equal(engine.getcookedpat(), r'\\s')
engine.revar.set(True)
Equal(engine.getcookedpat(), r'\s')
def test_getprog(self):
engine = self.engine
Equal = self.assertEqual
engine.setpat('Hello')
temppat = engine.getprog()
Equal(temppat.pattern, re.compile('Hello', re.IGNORECASE).pattern)
engine.casevar.set(1)
temppat = engine.getprog()
Equal(temppat.pattern, re.compile('Hello').pattern, 0)
engine.setpat('')
Equal(engine.getprog(), None)
Equal(Mbox.showerror.message,
'Error: Empty regular expression')
engine.setpat('+')
engine.revar.set(1)
Equal(engine.getprog(), None)
Equal(Mbox.showerror.message,
'Error: nothing to repeat\nPattern: +\nOffset: 0')
def test_report_error(self):
showerror = Mbox.showerror
Equal = self.assertEqual
pat = '[a-z'
msg = 'unexpected end of regular expression'
Equal(self.engine.report_error(pat, msg), None)
Equal(showerror.title, 'Regular expression error')
expected_message = ("Error: " + msg + "\nPattern: [a-z")
Equal(showerror.message, expected_message)
Equal(self.engine.report_error(pat, msg, 5), None)
Equal(showerror.title, 'Regular expression error')
expected_message += "\nOffset: 5"
Equal(showerror.message, expected_message)
class SearchTest(unittest.TestCase):
# Test that search_text makes right call to right method.
@classmethod
def setUpClass(cls):
## requires('gui')
## cls.root = Tk()
## cls.text = Text(master=cls.root)
cls.text = mockText()
test_text = (
'First line\n'
'Line with target\n'
'Last line\n')
cls.text.insert('1.0', test_text)
cls.pat = re.compile('target')
cls.engine = se.SearchEngine(None)
cls.engine.search_forward = lambda *args: ('f', args)
cls.engine.search_backward = lambda *args: ('b', args)
## @classmethod
## def tearDownClass(cls):
## cls.root.destroy()
## del cls.root
def test_search(self):
Equal = self.assertEqual
engine = self.engine
search = engine.search_text
text = self.text
pat = self.pat
engine.patvar.set(None)
#engine.revar.set(pat)
Equal(search(text), None)
def mark(s):
# no selection, cursor after 'Hello'
if s == 'insert': return '1.5'
raise TclError
text.index = mark
Equal(search(text, pat), ('f', (text, pat, 1, 5, True, False)))
engine.wrapvar.set(False)
Equal(search(text, pat), ('f', (text, pat, 1, 5, False, False)))
engine.wrapvar.set(True)
engine.backvar.set(True)
Equal(search(text, pat), ('b', (text, pat, 1, 5, True, False)))
engine.backvar.set(False)
def sel(s):
if s == 'sel.first': return '2.10'
if s == 'sel.last': return '2.16'
raise TclError
text.index = sel
Equal(search(text, pat), ('f', (text, pat, 2, 16, True, False)))
Equal(search(text, pat, True), ('f', (text, pat, 2, 10, True, True)))
engine.backvar.set(True)
Equal(search(text, pat), ('b', (text, pat, 2, 10, True, False)))
Equal(search(text, pat, True), ('b', (text, pat, 2, 16, True, True)))
class ForwardBackwardTest(unittest.TestCase):
# Test that search_forward method finds the target.
## @classmethod
## def tearDownClass(cls):
## cls.root.destroy()
## del cls.root
@classmethod
def setUpClass(cls):
cls.engine = se.SearchEngine(None)
## requires('gui')
## cls.root = Tk()
## cls.text = Text(master=cls.root)
cls.text = mockText()
# search_backward calls index('end-1c')
cls.text.index = lambda index: '4.0'
test_text = (
'First line\n'
'Line with target\n'
'Last line\n')
cls.text.insert('1.0', test_text)
cls.pat = re.compile('target')
cls.res = (2, (10, 16)) # line, slice indexes of 'target'
cls.failpat = re.compile('xyz') # not in text
cls.emptypat = re.compile(r'\w*') # empty match possible
def make_search(self, func):
def search(pat, line, col, wrap, ok=0):
res = func(self.text, pat, line, col, wrap, ok)
# res is (line, matchobject) or None
return (res[0], res[1].span()) if res else res
return search
def test_search_forward(self):
# search for non-empty match
Equal = self.assertEqual
forward = self.make_search(self.engine.search_forward)
pat = self.pat
Equal(forward(pat, 1, 0, True), self.res)
Equal(forward(pat, 3, 0, True), self.res) # wrap
Equal(forward(pat, 3, 0, False), None) # no wrap
Equal(forward(pat, 2, 10, False), self.res)
Equal(forward(self.failpat, 1, 0, True), None)
Equal(forward(self.emptypat, 2, 9, True, ok=True), (2, (9, 9)))
#Equal(forward(self.emptypat, 2, 9, True), self.res)
# While the initial empty match is correctly ignored, skipping
# the rest of the line and returning (3, (0,4)) seems buggy - tjr.
Equal(forward(self.emptypat, 2, 10, True), self.res)
def test_search_backward(self):
# search for non-empty match
Equal = self.assertEqual
backward = self.make_search(self.engine.search_backward)
pat = self.pat
Equal(backward(pat, 3, 5, True), self.res)
Equal(backward(pat, 2, 0, True), self.res) # wrap
Equal(backward(pat, 2, 0, False), None) # no wrap
Equal(backward(pat, 2, 16, False), self.res)
Equal(backward(self.failpat, 3, 9, True), None)
Equal(backward(self.emptypat, 2, 10, True, ok=True), (2, (9,9)))
# Accepted because 9 < 10, not because ok=True.
# It is not clear that ok=True is useful going back - tjr
Equal(backward(self.emptypat, 2, 9, True), (2, (5, 9)))
if __name__ == '__main__':
unittest.main(verbosity=2) | python | github | https://github.com/python/cpython | Lib/idlelib/idle_test/test_searchengine.py |
//// [tests/cases/compiler/accessorWithInitializer.ts] ////
//// [accessorWithInitializer.ts]
class C {
set X(v = 0) { }
static set X(v2 = 0) { }
}
//// [accessorWithInitializer.js]
"use strict";
var C = /** @class */ (function () {
function C() {
}
Object.defineProperty(C.prototype, "X", {
set: function (v) {
if (v === void 0) { v = 0; }
},
enumerable: false,
configurable: true
});
Object.defineProperty(C, "X", {
set: function (v2) {
if (v2 === void 0) { v2 = 0; }
},
enumerable: false,
configurable: true
});
return C;
}()); | javascript | github | https://github.com/microsoft/TypeScript | tests/baselines/reference/accessorWithInitializer(target=es5).js |
#!/usr/bin/env python3
import os
from shutil import copytree, copy2
from pathlib import Path
from scripts.build_env import BuildEnv, Platform
from scripts.platform_builder import PlatformBuilder
class pugixmliOSBuilder(PlatformBuilder):
def __init__(self,
config_package: dict=None,
config_platform: dict=None):
super().__init__(config_package, config_platform)
def build(self):
build_path = '{}/{}/scripts/build'.format(
self.env.source_path,
self.config['name']
)
_check = self.env.install_lib_path / self.config.get("checker")
if os.path.exists(_check):
self.tag_log("Already built.")
return
self.tag_log("Start building ...")
BuildEnv.mkdir_p(build_path)
os.chdir(build_path)
cmd = 'CMD_PREFIX={} {}/ios-build.sh pugixml arm64'.format(
self.env.install_path,
self.env.working_path
)
self.env.run_command(cmd, module_name=self.config['name'])
cmd = 'CMD_PREFIX={} {}/ios-build.sh pugixml armv7'.format(
self.env.install_path,
self.env.working_path
)
self.env.run_command(cmd, module_name=self.config['name'])
def post(self):
# Copy header files also
include_path = '{}/{}/src'.format(
self.env.source_path,
self.config['name']
)
_path = Path(include_path)
_files = [x for x in _path.iterdir() if x.is_file()]
for ff in _files:
if not ff.name.endswith('.hpp') and not ff.name.endswith('.h'):
continue
copy2(str(ff), self.env.install_include_path)
self.create_framework_iOS()
def create_framework_iOS(self):
# Required path
include_path = '{}/{}/src'.format(
self.env.source_path,
self.config['name']
)
_framework_dir = '{}/{}.framework'.format(
self.env.framework_path,
self.config['name'],
)
_framework_header_dir = '{}/{}.framework/Headers'.format(
self.env.framework_path,
self.config['name'],
)
_framework_resource_dir = '{}/{}.framework/Resources'.format(
self.env.framework_path,
self.config['name'],
)
# Copy headers into Framework directory
self.tag_log("Framework : Copying header ...")
BuildEnv.mkdir_p(_framework_header_dir)
_path = Path(include_path)
_files = [x for x in _path.iterdir() if x.is_file()]
for ff in _files:
if not ff.name.endswith('.hpp') and not ff.name.endswith('.h'):
continue
copy2(str(ff), _framework_header_dir)
# Copy binaries
self.tag_log("Framework : Copying binary ...")
BuildEnv.mkdir_p(_framework_dir)
_lib_src_file = '{}/libpugixml.a'.format(self.env.install_lib_path)
_lib_dst_file = '{}/pugixml'.format(_framework_dir)
copy2(_lib_src_file, _lib_dst_file)
# Create plist
BuildEnv.mkdir_p(_framework_resource_dir)
plist_str = self.env.apple_framework_plist.replace(
'${FRAMEWORK_NAME}', self.config['name']
).replace(
'${FRAMEWORK_CURRENT_VERSION}', self.config['name']
)
plist_file = '{}/Info.plist'.format(_framework_resource_dir)
with open(plist_file, "w") as pf:
pf.write(plist_str) | unknown | codeparrot/codeparrot-clean | ||
""" Operation handler to set the status for transformation files
"""
from DIRAC import S_OK, S_ERROR
from DIRAC.Core.Utilities import DEncode
from DIRAC.RequestManagementSystem.private.OperationHandlerBase import OperationHandlerBase
from DIRAC.TransformationSystem.Client.TransformationClient import TransformationClient
__RCSID__ = "$Id $"
class SetFileStatus( OperationHandlerBase ):
"""
.. class:: SetFileStatus
SetFileStatus operation handler
"""
def __init__( self, operation = None, csPath = None ):
"""c'tor
:param self: self reference
:param Operation operation: Operation instance
:param str csPath: CS path for this handler
"""
OperationHandlerBase.__init__( self, operation, csPath )
def __call__( self ):
""" It expects to find the arguments for tc.setFileStatusForTransformation in operation.Arguments
"""
try:
setFileStatusDict = DEncode.decode( self.operation.Arguments )[0]
self.log.debug( "decoded filStatusDict=%s" % str( setFileStatusDict ) )
except ValueError, error:
self.log.exception( error )
self.operation.Error = str( error )
self.operation.Status = "Failed"
return S_ERROR( str( error ) )
tc = TransformationClient()
setStatus = tc.setFileStatusForTransformation( setFileStatusDict['transformation'],
setFileStatusDict['statusDict'],
setFileStatusDict['force'] )
if not setStatus['OK']:
errorStr = "failed to change status: %s" % setStatus['Message']
self.operation.Error = errorStr
self.log.warn( errorStr )
return S_ERROR( self.operation.Error )
else:
self.operation.Status = "Done"
return S_OK() | unknown | codeparrot/codeparrot-clean | ||
"""Load / save to libwww-perl (LWP) format files.
Actually, the format is slightly extended from that used by LWP's
(libwww-perl's) HTTP::Cookies, to avoid losing some RFC 2965 information
not recorded by LWP.
It uses the version string "2.0", though really there isn't an LWP Cookies
2.0 format. This indicates that there is extra information in here
(domain_dot and # port_spec) while still being compatible with
libwww-perl, I hope.
"""
import time, re
from cookielib import (_warn_unhandled_exception, FileCookieJar, LoadError,
Cookie, MISSING_FILENAME_TEXT,
join_header_words, split_header_words,
iso2time, time2isoz)
def lwp_cookie_str(cookie):
"""Return string representation of Cookie in an the LWP cookie file format.
Actually, the format is extended a bit -- see module docstring.
"""
h = [(cookie.name, cookie.value),
("path", cookie.path),
("domain", cookie.domain)]
if cookie.port is not None: h.append(("port", cookie.port))
if cookie.path_specified: h.append(("path_spec", None))
if cookie.port_specified: h.append(("port_spec", None))
if cookie.domain_initial_dot: h.append(("domain_dot", None))
if cookie.secure: h.append(("secure", None))
if cookie.expires: h.append(("expires",
time2isoz(float(cookie.expires))))
if cookie.discard: h.append(("discard", None))
if cookie.comment: h.append(("comment", cookie.comment))
if cookie.comment_url: h.append(("commenturl", cookie.comment_url))
keys = cookie._rest.keys()
keys.sort()
for k in keys:
h.append((k, str(cookie._rest[k])))
h.append(("version", str(cookie.version)))
return join_header_words([h])
class LWPCookieJar(FileCookieJar):
"""
The LWPCookieJar saves a sequence of "Set-Cookie3" lines.
"Set-Cookie3" is the format used by the libwww-perl libary, not known
to be compatible with any browser, but which is easy to read and
doesn't lose information about RFC 2965 cookies.
Additional methods
as_lwp_str(ignore_discard=True, ignore_expired=True)
"""
def as_lwp_str(self, ignore_discard=True, ignore_expires=True):
"""Return cookies as a string of "\\n"-separated "Set-Cookie3" headers.
ignore_discard and ignore_expires: see docstring for FileCookieJar.save
"""
now = time.time()
r = []
for cookie in self:
if not ignore_discard and cookie.discard:
continue
if not ignore_expires and cookie.is_expired(now):
continue
r.append("Set-Cookie3: %s" % lwp_cookie_str(cookie))
return "\n".join(r+[""])
def save(self, filename=None, ignore_discard=False, ignore_expires=False):
if filename is None:
if self.filename is not None: filename = self.filename
else: raise ValueError(MISSING_FILENAME_TEXT)
f = open(filename, "w")
try:
# There really isn't an LWP Cookies 2.0 format, but this indicates
# that there is extra information in here (domain_dot and
# port_spec) while still being compatible with libwww-perl, I hope.
f.write("#LWP-Cookies-2.0\n")
f.write(self.as_lwp_str(ignore_discard, ignore_expires))
finally:
f.close()
def _really_load(self, f, filename, ignore_discard, ignore_expires):
magic = f.readline()
if not re.search(self.magic_re, magic):
msg = ("%r does not look like a Set-Cookie3 (LWP) format "
"file" % filename)
raise LoadError(msg)
now = time.time()
header = "Set-Cookie3:"
boolean_attrs = ("port_spec", "path_spec", "domain_dot",
"secure", "discard")
value_attrs = ("version",
"port", "path", "domain",
"expires",
"comment", "commenturl")
try:
while 1:
line = f.readline()
if line == "": break
if not line.startswith(header):
continue
line = line[len(header):].strip()
for data in split_header_words([line]):
name, value = data[0]
standard = {}
rest = {}
for k in boolean_attrs:
standard[k] = False
for k, v in data[1:]:
if k is not None:
lc = k.lower()
else:
lc = None
# don't lose case distinction for unknown fields
if (lc in value_attrs) or (lc in boolean_attrs):
k = lc
if k in boolean_attrs:
if v is None: v = True
standard[k] = v
elif k in value_attrs:
standard[k] = v
else:
rest[k] = v
h = standard.get
expires = h("expires")
discard = h("discard")
if expires is not None:
expires = iso2time(expires)
if expires is None:
discard = True
domain = h("domain")
domain_specified = domain.startswith(".")
c = Cookie(h("version"), name, value,
h("port"), h("port_spec"),
domain, domain_specified, h("domain_dot"),
h("path"), h("path_spec"),
h("secure"),
expires,
discard,
h("comment"),
h("commenturl"),
rest)
if not ignore_discard and c.discard:
continue
if not ignore_expires and c.is_expired(now):
continue
self.set_cookie(c)
except IOError:
raise
except Exception:
_warn_unhandled_exception()
raise LoadError("invalid Set-Cookie3 format file %r: %r" %
(filename, line)) | unknown | codeparrot/codeparrot-clean | ||
"""Prettyprinter by Jurjen Bos.
(I hate spammers: mail me at pietjepuk314 at the reverse of ku.oc.oohay).
All objects have a method that create a "stringPict",
that can be used in the str method for pretty printing.
Updates by Jason Gedge (email <my last name> at cs mun ca)
- terminal_string() method
- minor fixes and changes (mostly to prettyForm)
TODO:
- Allow left/center/right alignment options for above/below and
top/center/bottom alignment options for left/right
"""
from __future__ import print_function, division
from .pretty_symbology import hobj, vobj, xsym, xobj, pretty_use_unicode
from sympy.core.compatibility import string_types, range
class stringPict(object):
"""An ASCII picture.
The pictures are represented as a list of equal length strings.
"""
#special value for stringPict.below
LINE = 'line'
def __init__(self, s, baseline=0):
"""Initialize from string.
Multiline strings are centered.
"""
self.s = s
#picture is a string that just can be printed
self.picture = stringPict.equalLengths(s.splitlines())
#baseline is the line number of the "base line"
self.baseline = baseline
self.binding = None
@staticmethod
def equalLengths(lines):
# empty lines
if not lines:
return ['']
width = max(len(line) for line in lines)
return [line.center(width) for line in lines]
def height(self):
"""The height of the picture in characters."""
return len(self.picture)
def width(self):
"""The width of the picture in characters."""
return len(self.picture[0])
@staticmethod
def next(*args):
"""Put a string of stringPicts next to each other.
Returns string, baseline arguments for stringPict.
"""
#convert everything to stringPicts
objects = []
for arg in args:
if isinstance(arg, string_types):
arg = stringPict(arg)
objects.append(arg)
#make a list of pictures, with equal height and baseline
newBaseline = max(obj.baseline for obj in objects)
newHeightBelowBaseline = max(
obj.height() - obj.baseline
for obj in objects)
newHeight = newBaseline + newHeightBelowBaseline
pictures = []
for obj in objects:
oneEmptyLine = [' '*obj.width()]
basePadding = newBaseline - obj.baseline
totalPadding = newHeight - obj.height()
pictures.append(
oneEmptyLine * basePadding +
obj.picture +
oneEmptyLine * (totalPadding - basePadding))
result = [''.join(lines) for lines in zip(*pictures)]
return '\n'.join(result), newBaseline
def right(self, *args):
r"""Put pictures next to this one.
Returns string, baseline arguments for stringPict.
(Multiline) strings are allowed, and are given a baseline of 0.
Examples
========
>>> from sympy.printing.pretty.stringpict import stringPict
>>> print(stringPict("10").right(" + ",stringPict("1\r-\r2",1))[0])
1
10 + -
2
"""
return stringPict.next(self, *args)
def left(self, *args):
"""Put pictures (left to right) at left.
Returns string, baseline arguments for stringPict.
"""
return stringPict.next(*(args + (self,)))
@staticmethod
def stack(*args):
"""Put pictures on top of each other,
from top to bottom.
Returns string, baseline arguments for stringPict.
The baseline is the baseline of the second picture.
Everything is centered.
Baseline is the baseline of the second picture.
Strings are allowed.
The special value stringPict.LINE is a row of '-' extended to the width.
"""
#convert everything to stringPicts; keep LINE
objects = []
for arg in args:
if arg is not stringPict.LINE and isinstance(arg, string_types):
arg = stringPict(arg)
objects.append(arg)
#compute new width
newWidth = max(
obj.width()
for obj in objects
if obj is not stringPict.LINE)
lineObj = stringPict(hobj('-', newWidth))
#replace LINE with proper lines
for i, obj in enumerate(objects):
if obj is stringPict.LINE:
objects[i] = lineObj
#stack the pictures, and center the result
newPicture = []
for obj in objects:
newPicture.extend(obj.picture)
newPicture = [line.center(newWidth) for line in newPicture]
newBaseline = objects[0].height() + objects[1].baseline
return '\n'.join(newPicture), newBaseline
def below(self, *args):
"""Put pictures under this picture.
Returns string, baseline arguments for stringPict.
Baseline is baseline of top picture
Examples
========
>>> from sympy.printing.pretty.stringpict import stringPict
>>> print(stringPict("x+3").below(
... stringPict.LINE, '3')[0]) #doctest: +NORMALIZE_WHITESPACE
x+3
---
3
"""
s, baseline = stringPict.stack(self, *args)
return s, self.baseline
def above(self, *args):
"""Put pictures above this picture.
Returns string, baseline arguments for stringPict.
Baseline is baseline of bottom picture.
"""
string, baseline = stringPict.stack(*(args + (self,)))
baseline = len(string.splitlines()) - self.height() + self.baseline
return string, baseline
def parens(self, left='(', right=')', ifascii_nougly=False):
"""Put parentheses around self.
Returns string, baseline arguments for stringPict.
left or right can be None or empty string which means 'no paren from
that side'
"""
h = self.height()
b = self.baseline
# XXX this is a hack -- ascii parens are ugly!
if ifascii_nougly and not pretty_use_unicode():
h = 1
b = 0
res = self
if left:
lparen = stringPict(vobj(left, h), baseline=b)
res = stringPict(*lparen.right(self))
if right:
rparen = stringPict(vobj(right, h), baseline=b)
res = stringPict(*res.right(rparen))
return ('\n'.join(res.picture), res.baseline)
def leftslash(self):
"""Precede object by a slash of the proper size.
"""
# XXX not used anywhere ?
height = max(
self.baseline,
self.height() - 1 - self.baseline)*2 + 1
slash = '\n'.join(
' '*(height - i - 1) + xobj('/', 1) + ' '*i
for i in range(height)
)
return self.left(stringPict(slash, height//2))
def root(self, n=None):
"""Produce a nice root symbol.
Produces ugly results for big n inserts.
"""
# XXX not used anywhere
# XXX duplicate of root drawing in pretty.py
#put line over expression
result = self.above('_'*self.width())
#construct right half of root symbol
height = self.height()
slash = '\n'.join(
' ' * (height - i - 1) + '/' + ' ' * i
for i in range(height)
)
slash = stringPict(slash, height - 1)
#left half of root symbol
if height > 2:
downline = stringPict('\\ \n \\', 1)
else:
downline = stringPict('\\')
#put n on top, as low as possible
if n is not None and n.width() > downline.width():
downline = downline.left(' '*(n.width() - downline.width()))
downline = downline.above(n)
#build root symbol
root = downline.right(slash)
#glue it on at the proper height
#normally, the root symbel is as high as self
#which is one less than result
#this moves the root symbol one down
#if the root became higher, the baseline has to grow too
root.baseline = result.baseline - result.height() + root.height()
return result.left(root)
def render(self, * args, **kwargs):
"""Return the string form of self.
Unless the argument line_break is set to False, it will
break the expression in a form that can be printed
on the terminal without being broken up.
"""
if kwargs["wrap_line"] is False:
return "\n".join(self.picture)
if kwargs["num_columns"] is not None:
# Read the argument num_columns if it is not None
ncols = kwargs["num_columns"]
else:
# Attempt to get a terminal width
ncols = self.terminal_width()
ncols -= 2
if ncols <= 0:
ncols = 78
# If smaller than the terminal width, no need to correct
if self.width() <= ncols:
return type(self.picture[0])(self)
# for one-line pictures we don't need v-spacers. on the other hand, for
# multiline-pictures, we need v-spacers between blocks, compare:
#
# 2 2 3 | a*c*e + a*c*f + a*d | a*c*e + a*c*f + a*d | 3.14159265358979323
# 6*x *y + 4*x*y + | | *e + a*d*f + b*c*e | 84626433832795
# | *e + a*d*f + b*c*e | + b*c*f + b*d*e + b |
# 3 4 4 | | *d*f |
# 4*y*x + x + y | + b*c*f + b*d*e + b | |
# | | |
# | *d*f
i = 0
svals = []
do_vspacers = (self.height() > 1)
while i < self.width():
svals.extend([ sval[i:i + ncols] for sval in self.picture ])
if do_vspacers:
svals.append("") # a vertical spacer
i += ncols
if svals[-1] == '':
del svals[-1] # Get rid of the last spacer
return "\n".join(svals)
def terminal_width(self):
"""Return the terminal width if possible, otherwise return 0.
"""
ncols = 0
try:
import curses
import io
try:
curses.setupterm()
ncols = curses.tigetnum('cols')
except AttributeError:
# windows curses doesn't implement setupterm or tigetnum
# code below from
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694
from ctypes import windll, create_string_buffer
# stdin handle is -10
# stdout handle is -11
# stderr handle is -12
h = windll.kernel32.GetStdHandle(-12)
csbi = create_string_buffer(22)
res = windll.kernel32.GetConsoleScreenBufferInfo(h, csbi)
if res:
import struct
(bufx, bufy, curx, cury, wattr,
left, top, right, bottom, maxx, maxy) = struct.unpack("hhhhHhhhhhh", csbi.raw)
ncols = right - left + 1
except curses.error:
pass
except io.UnsupportedOperation:
pass
except (ImportError, TypeError):
pass
return ncols
def __eq__(self, o):
if isinstance(o, str):
return '\n'.join(self.picture) == o
elif isinstance(o, stringPict):
return o.picture == self.picture
return False
def __hash__(self):
return super(stringPict, self).__hash__()
def __str__(self):
return str.join('\n', self.picture)
def __unicode__(self):
return unicode.join(u'\n', self.picture)
def __repr__(self):
return "stringPict(%r,%d)" % ('\n'.join(self.picture), self.baseline)
def __getitem__(self, index):
return self.picture[index]
def __len__(self):
return len(self.s)
class prettyForm(stringPict):
"""
Extension of the stringPict class that knows about basic math applications,
optimizing double minus signs.
"Binding" is interpreted as follows::
ATOM this is an atom: never needs to be parenthesized
FUNC this is a function application: parenthesize if added (?)
DIV this is a division: make wider division if divided
POW this is a power: only parenthesize if exponent
MUL this is a multiplication: parenthesize if powered
ADD this is an addition: parenthesize if multiplied or powered
NEG this is a negative number: optimize if added, parenthesize if
multiplied or powered
OPEN this is an open object: parenthesize if added, multiplied, or
powered (example: Piecewise)
"""
ATOM, FUNC, DIV, POW, MUL, ADD, NEG, OPEN = range(8)
def __init__(self, s, baseline=0, binding=0, unicode=None):
"""Initialize from stringPict and binding power."""
stringPict.__init__(self, s, baseline)
self.binding = binding
self.unicode = unicode or s
# Note: code to handle subtraction is in _print_Add
def __add__(self, *others):
"""Make a pretty addition.
Addition of negative numbers is simplified.
"""
arg = self
if arg.binding > prettyForm.NEG:
arg = stringPict(*arg.parens())
result = [arg]
for arg in others:
#add parentheses for weak binders
if arg.binding > prettyForm.NEG:
arg = stringPict(*arg.parens())
#use existing minus sign if available
if arg.binding != prettyForm.NEG:
result.append(' + ')
result.append(arg)
return prettyForm(binding=prettyForm.ADD, *stringPict.next(*result))
def __div__(self, den, slashed=False):
"""Make a pretty division; stacked or slashed.
"""
if slashed:
raise NotImplementedError("Can't do slashed fraction yet")
num = self
if num.binding == prettyForm.DIV:
num = stringPict(*num.parens())
if den.binding == prettyForm.DIV:
den = stringPict(*den.parens())
if num.binding==prettyForm.NEG:
num = num.right(" ")[0]
return prettyForm(binding=prettyForm.DIV, *stringPict.stack(
num,
stringPict.LINE,
den))
def __truediv__(self, o):
return self.__div__(o)
def __mul__(self, *others):
"""Make a pretty multiplication.
Parentheses are needed around +, - and neg.
"""
quantity = {
'degree': u"\N{DEGREE SIGN}"
}
if len(others) == 0:
return self # We aren't actually multiplying... So nothing to do here.
args = self
if args.binding > prettyForm.MUL:
arg = stringPict(*args.parens())
result = [args]
for arg in others:
if arg.picture[0] not in quantity.values():
result.append(xsym('*'))
#add parentheses for weak binders
if arg.binding > prettyForm.MUL:
arg = stringPict(*arg.parens())
result.append(arg)
len_res = len(result)
for i in range(len_res):
if i < len_res - 1 and result[i] == '-1' and result[i + 1] == xsym('*'):
# substitute -1 by -, like in -1*x -> -x
result.pop(i)
result.pop(i)
result.insert(i, '-')
if result[0][0] == '-':
# if there is a - sign in front of all
# This test was failing to catch a prettyForm.__mul__(prettyForm("-1", 0, 6)) being negative
bin = prettyForm.NEG
if result[0] == '-':
right = result[1]
if right.picture[right.baseline][0] == '-':
result[0] = '- '
else:
bin = prettyForm.MUL
return prettyForm(binding=bin, *stringPict.next(*result))
def __repr__(self):
return "prettyForm(%r,%d,%d)" % (
'\n'.join(self.picture),
self.baseline,
self.binding)
def __pow__(self, b):
"""Make a pretty power.
"""
a = self
use_inline_func_form = False
if b.binding == prettyForm.POW:
b = stringPict(*b.parens())
if a.binding > prettyForm.FUNC:
a = stringPict(*a.parens())
elif a.binding == prettyForm.FUNC:
# heuristic for when to use inline power
if b.height() > 1:
a = stringPict(*a.parens())
else:
use_inline_func_form = True
if use_inline_func_form:
# 2
# sin + + (x)
b.baseline = a.prettyFunc.baseline + b.height()
func = stringPict(*a.prettyFunc.right(b))
return prettyForm(*func.right(a.prettyArgs))
else:
# 2 <-- top
# (x+y) <-- bot
top = stringPict(*b.left(' '*a.width()))
bot = stringPict(*a.right(' '*b.width()))
return prettyForm(binding=prettyForm.POW, *bot.above(top))
simpleFunctions = ["sin", "cos", "tan"]
@staticmethod
def apply(function, *args):
"""Functions of one or more variables.
"""
if function in prettyForm.simpleFunctions:
#simple function: use only space if possible
assert len(
args) == 1, "Simple function %s must have 1 argument" % function
arg = args[0].__pretty__()
if arg.binding <= prettyForm.DIV:
#optimization: no parentheses necessary
return prettyForm(binding=prettyForm.FUNC, *arg.left(function + ' '))
argumentList = []
for arg in args:
argumentList.append(',')
argumentList.append(arg.__pretty__())
argumentList = stringPict(*stringPict.next(*argumentList[1:]))
argumentList = stringPict(*argumentList.parens())
return prettyForm(binding=prettyForm.ATOM, *argumentList.left(function)) | unknown | codeparrot/codeparrot-clean | ||
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// The Google C++ Testing and Mocking Framework (Google Test)
//
// This header file declares the String class and functions used internally by
// Google Test. They are subject to change without notice. They should not used
// by code external to Google Test.
//
// This header file is #included by gtest-internal.h.
// It should not be #included by other files.
// IWYU pragma: private, include "gtest/gtest.h"
// IWYU pragma: friend gtest/.*
// IWYU pragma: friend gmock/.*
#ifndef GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
#define GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_
#ifdef __BORLANDC__
// string.h is not guaranteed to provide strcpy on C++ Builder.
#include <mem.h>
#endif
#include <string.h>
#include <cstdint>
#include <sstream>
#include <string>
#include "gtest/internal/gtest-port.h"
namespace testing {
namespace internal {
// String - an abstract class holding static string utilities.
class GTEST_API_ [[nodiscard]] String {
public:
// Static utility methods
// Clones a 0-terminated C string, allocating memory using new. The
// caller is responsible for deleting the return value using
// delete[]. Returns the cloned string, or NULL if the input is
// NULL.
//
// This is different from strdup() in string.h, which allocates
// memory using malloc().
static const char* CloneCString(const char* c_str);
#ifdef GTEST_OS_WINDOWS_MOBILE
// Windows CE does not have the 'ANSI' versions of Win32 APIs. To be
// able to pass strings to Win32 APIs on CE we need to convert them
// to 'Unicode', UTF-16.
// Creates a UTF-16 wide string from the given ANSI string, allocating
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the wide string, or NULL if the
// input is NULL.
//
// The wide string is created using the ANSI codepage (CP_ACP) to
// match the behaviour of the ANSI versions of Win32 calls and the
// C runtime.
static LPCWSTR AnsiToUtf16(const char* c_str);
// Creates an ANSI string from the given wide string, allocating
// memory using new. The caller is responsible for deleting the return
// value using delete[]. Returns the ANSI string, or NULL if the
// input is NULL.
//
// The returned string is created using the ANSI codepage (CP_ACP) to
// match the behaviour of the ANSI versions of Win32 calls and the
// C runtime.
static const char* Utf16ToAnsi(LPCWSTR utf16_str);
#endif
// Compares two C strings. Returns true if and only if they have the same
// content.
//
// Unlike strcmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string,
// including the empty string.
static bool CStringEquals(const char* lhs, const char* rhs);
// Converts a wide C string to a String using the UTF-8 encoding.
// NULL will be converted to "(null)". If an error occurred during
// the conversion, "(failed to convert from wide string)" is
// returned.
static std::string ShowWideCString(const wchar_t* wide_c_str);
// Compares two wide C strings. Returns true if and only if they have the
// same content.
//
// Unlike wcscmp(), this function can handle NULL argument(s). A
// NULL C string is considered different to any non-NULL C string,
// including the empty string.
static bool WideCStringEquals(const wchar_t* lhs, const wchar_t* rhs);
// Compares two C strings, ignoring case. Returns true if and only if
// they have the same content.
//
// Unlike strcasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL C string,
// including the empty string.
static bool CaseInsensitiveCStringEquals(const char* lhs, const char* rhs);
// Compares two wide C strings, ignoring case. Returns true if and only if
// they have the same content.
//
// Unlike wcscasecmp(), this function can handle NULL argument(s).
// A NULL C string is considered different to any non-NULL wide C string,
// including the empty string.
// NB: The implementations on different platforms slightly differ.
// On windows, this method uses _wcsicmp which compares according to LC_CTYPE
// environment variable. On GNU platform this method uses wcscasecmp
// which compares according to LC_CTYPE category of the current locale.
// On MacOS X, it uses towlower, which also uses LC_CTYPE category of the
// current locale.
static bool CaseInsensitiveWideCStringEquals(const wchar_t* lhs,
const wchar_t* rhs);
// Returns true if and only if the given string ends with the given suffix,
// ignoring case. Any string is considered to end with an empty suffix.
static bool EndsWithCaseInsensitive(const std::string& str,
const std::string& suffix);
// Formats an int value as "%02d".
static std::string FormatIntWidth2(int value); // "%02d" for width == 2
// Formats an int value to given width with leading zeros.
static std::string FormatIntWidthN(int value, int width);
// Formats an int value as "%X".
static std::string FormatHexInt(int value);
// Formats an int value as "%X".
static std::string FormatHexUInt32(uint32_t value);
// Formats a byte as "%02X".
static std::string FormatByte(unsigned char value);
private:
String(); // Not meant to be instantiated.
}; // class String
// Gets the content of the stringstream's buffer as an std::string. Each '\0'
// character in the buffer is replaced with "\\0".
GTEST_API_ std::string StringStreamToString(::std::stringstream* stream);
} // namespace internal
} // namespace testing
#endif // GOOGLETEST_INCLUDE_GTEST_INTERNAL_GTEST_STRING_H_ | c | github | https://github.com/google/googletest | googletest/include/gtest/internal/gtest-string.h |
import sys
def matrixChainOrder(p):
n = len(p)-1
m = {}
s = {}
for i in xrange(1, n+1):
m[(i, i)] = 0
for l in range(2, n+1):
for i in range(1, n-l+2):
j = i+l-1
m[(i, j)] = sys.maxint
for k in range(i, j):
q = m[i, k] + m[k+1, j] + p[i-1]*p[k]*p[j]
if q < m[(i, j)]:
m[(i, j)] = q
s[(i, j)] = k
return (m, s)
def printOptimalParens(s, i, j):
if i == j:
print ("A[%d"%i)+']',
else:
print "(",
printOptimalParens(s, i, s[i, j])
printOptimalParens(s, s[i, j]+1, j)
print ")",
def matrixMultiply(A, B):
if A.columns != B.rows:
print "incompatible dimensions"
return
else:
C = [[0 for col in range(A.rows)] for row in range(B.columns)]
for i in range(0, A.rows):
for j in xrange(0, B.columns):
C[i][j] = 0
for k in xrange(0,A.columns):
C[i][j] = C[i][j]+A[i][k]*B[k][j]
return C
def matrixChainMultiply(A, s, i, j):
if i == j:
return A[i]
else:
return matrixMultiply(matrixChainMultiply(A, s, i, s[i][j]), matrixChainMultiply(A, s, s[i][j]+1, j))
# p = [30,35,15,5,10,20,25]
# (m, s) = matrixChainOrder(p)
# printOptimalParens(s, 1, len(p)-1)
# mul = [[0]*5]*3
# print mul | unknown | codeparrot/codeparrot-clean | ||
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for L{twisted.python.sendmsg}.
"""
import sys
import errno
import warnings
from os import devnull, pipe, read, close, pathsep
from struct import pack
from socket import SOL_SOCKET, AF_INET, AF_INET6, socket, error
try:
from socket import AF_UNIX, socketpair
except ImportError:
nonUNIXSkip = "Platform does not support AF_UNIX sockets"
else:
nonUNIXSkip = None
from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.internet.error import ProcessDone
from twisted.internet.protocol import ProcessProtocol
from twisted.python.compat import _PY3, intToBytes, bytesEnviron
from twisted.python.filepath import FilePath
from twisted.python.runtime import platform
from twisted.trial.unittest import TestCase
if platform.isLinux():
from socket import MSG_DONTWAIT
dontWaitSkip = None
else:
# It would be nice to be able to test flags on more platforms, but finding
# a flag that works *at all* is somewhat challenging.
dontWaitSkip = "MSG_DONTWAIT is only known to work as intended on Linux"
try:
from twisted.python.sendmsg import sendmsg, recvmsg
from twisted.python.sendmsg import SCM_RIGHTS, getSocketFamily
except ImportError:
importSkip = "Platform doesn't support sendmsg."
else:
importSkip = None
try:
from twisted.python.sendmsg import send1msg, recv1msg
from twisted.python.sendmsg import getsockfam
except ImportError:
CModuleImportSkip = "Cannot import twisted.python.sendmsg"
else:
CModuleImportSkip = None
class _FDHolder(object):
"""
A wrapper around a FD that will remember if it has been closed or not.
"""
def __init__(self, fd):
self._fd = fd
def fileno(self):
"""
Return the fileno of this FD.
"""
return self._fd
def close(self):
"""
Close the FD. If it's already been closed, do nothing.
"""
if self._fd:
close(self._fd)
self._fd = None
def __del__(self):
"""
If C{self._fd} is unclosed, raise a warning.
"""
if self._fd:
if not _PY3:
ResourceWarning = Warning
warnings.warn("FD %s was not closed!" % (self._fd,),
ResourceWarning)
self.close()
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def _makePipe():
"""
Create a pipe, and return the two FDs wrapped in L{_FDHolders}.
"""
r, w = pipe()
return (_FDHolder(r), _FDHolder(w))
class ExitedWithStderr(Exception):
"""
A process exited with some stderr.
"""
def __str__(self):
"""
Dump the errors in a pretty way in the event of a subprocess traceback.
"""
result = b'\n'.join([b''] + list(self.args))
if _PY3:
result = repr(result)
return result
class StartStopProcessProtocol(ProcessProtocol):
"""
An L{IProcessProtocol} with a Deferred for events where the subprocess
starts and stops.
@ivar started: A L{Deferred} which fires with this protocol's
L{IProcessTransport} provider when it is connected to one.
@ivar stopped: A L{Deferred} which fires with the process output or a
failure if the process produces output on standard error.
@ivar output: A C{str} used to accumulate standard output.
@ivar errors: A C{str} used to accumulate standard error.
"""
def __init__(self):
self.started = Deferred()
self.stopped = Deferred()
self.output = b''
self.errors = b''
def connectionMade(self):
self.started.callback(self.transport)
def outReceived(self, data):
self.output += data
def errReceived(self, data):
self.errors += data
def processEnded(self, reason):
if reason.check(ProcessDone):
self.stopped.callback(self.output)
else:
self.stopped.errback(ExitedWithStderr(
self.errors, self.output))
def _spawn(script, outputFD):
"""
Start a script that is a peer of this test as a subprocess.
@param script: the module name of the script in this directory (no
package prefix, no '.py')
@type script: C{str}
@rtype: L{StartStopProcessProtocol}
"""
pyExe = FilePath(sys.executable).asBytesMode().path
env = bytesEnviron()
env[b"PYTHONPATH"] = FilePath(
pathsep.join(sys.path)).asBytesMode().path
sspp = StartStopProcessProtocol()
reactor.spawnProcess(
sspp, pyExe, [
pyExe,
FilePath(__file__).sibling(script + ".py").asBytesMode().path,
intToBytes(outputFD),
],
env=env,
childFDs={0: "w", 1: "r", 2: "r", outputFD: outputFD}
)
return sspp
class BadList(list):
"""
A list which cannot be iterated sometimes.
This is a C{list} subclass to get past the type check in L{send1msg}, not
as an example of how real programs might want to interact with L{send1msg}
(or anything else). A custom C{list} subclass makes it easier to trigger
certain error cases in the implementation.
@ivar iterate: A flag which indicates whether an instance of L{BadList}
will allow iteration over itself or not. If C{False}, an attempt to
iterate over the instance will raise an exception.
"""
iterate = True
def __iter__(self):
"""
Allow normal list iteration, or raise an exception.
If C{self.iterate} is C{True}, it will be flipped to C{False} and then
normal iteration will proceed. If C{self.iterate} is C{False},
L{RuntimeError} is raised instead.
"""
if self.iterate:
self.iterate = False
return super(BadList, self).__iter__()
raise RuntimeError("Something bad happened")
class WorseList(list):
"""
A list which at first gives the appearance of being iterable, but then
raises an exception.
See L{BadList} for a warning about not writing code like this.
"""
def __iter__(self):
"""
Return an iterator which will raise an exception as soon as C{next} is
called on it.
"""
class BadIterator(object):
def next(self):
raise RuntimeError("This is a really bad case.")
return BadIterator()
class CModuleSendmsgTests(TestCase):
"""
Tests for sendmsg extension module and associated file-descriptor sending
functionality.
"""
if nonUNIXSkip is not None:
skip = nonUNIXSkip
elif CModuleImportSkip is not None:
skip = CModuleImportSkip
def setUp(self):
"""
Create a pair of UNIX sockets.
"""
self.input, self.output = socketpair(AF_UNIX)
def tearDown(self):
"""
Close the sockets opened by setUp.
"""
self.input.close()
self.output.close()
def test_sendmsgBadArguments(self):
"""
The argument types accepted by L{send1msg} are:
1. C{int}
2. read-only character buffer
3. C{int}
4. sequence
The 3rd and 4th arguments are optional. If fewer than two arguments or
more than four arguments are passed, or if any of the arguments passed
are not compatible with these types, L{TypeError} is raised.
"""
# Exercise the wrong number of arguments cases
self.assertRaises(TypeError, send1msg)
self.assertRaises(TypeError, send1msg, 1)
self.assertRaises(TypeError, send1msg,
1, "hello world", 2, [], object())
# Exercise the wrong type of arguments cases
self.assertRaises(TypeError, send1msg, object(), "hello world", 2, [])
self.assertRaises(TypeError, send1msg, 1, object(), 2, [])
self.assertRaises(TypeError, send1msg, 1, "hello world", object(), [])
self.assertRaises(TypeError, send1msg, 1, "hello world", 2, object())
def test_badAncillaryIter(self):
"""
If iteration over the ancillary data list fails (at the point of the
C{__iter__} call), the exception with which it fails is propagated to
the caller of L{send1msg}.
"""
badList = BadList()
badList.append((1, 2, "hello world"))
badList.iterate = False
self.assertRaises(RuntimeError, send1msg, 1, "hello world", 2, badList)
# Hit the second iteration
badList.iterate = True
self.assertRaises(RuntimeError, send1msg, 1, "hello world", 2, badList)
def test_badAncillaryNext(self):
"""
If iteration over the ancillary data list fails (at the point of a
C{next} call), the exception with which it fails is propagated to the
caller of L{send1msg}.
"""
worseList = WorseList()
self.assertRaises(RuntimeError, send1msg,
1, "hello world", 2,worseList)
def test_sendmsgBadAncillaryItem(self):
"""
The ancillary data list contains three-tuples with element types of:
1. C{int}
2. C{int}
3. read-only character buffer
If a tuple in the ancillary data list does not elements of these types,
L{TypeError} is raised.
"""
# Exercise the wrong number of arguments cases
self.assertRaises(TypeError, send1msg, 1, "hello world", 2, [()])
self.assertRaises(TypeError, send1msg, 1, "hello world", 2, [(1,)])
self.assertRaises(TypeError, send1msg, 1, "hello world", 2, [(1, 2)])
self.assertRaises(
TypeError,
send1msg, 1, "hello world", 2, [(1, 2, "goodbye", object())])
# Exercise the wrong type of arguments cases
exc = self.assertRaises(
TypeError, send1msg, 1, "hello world", 2, [object()])
self.assertEqual(
"send1msg argument 3 expected list of tuple, "
"got list containing object",
str(exc))
self.assertRaises(
TypeError,
send1msg, 1, "hello world", 2, [(object(), 1, "goodbye")])
self.assertRaises(
TypeError,
send1msg, 1, "hello world", 2, [(1, object(), "goodbye")])
self.assertRaises(
TypeError,
send1msg, 1, "hello world", 2, [(1, 1, object())])
def test_syscallError(self):
"""
If the underlying C{sendmsg} call fails, L{send1msg} raises
L{socket.error} with its errno set to the underlying errno value.
"""
with open(devnull) as probe:
fd = probe.fileno()
exc = self.assertRaises(error, send1msg, fd, "hello, world")
self.assertEqual(exc.args[0], errno.EBADF)
def test_syscallErrorWithControlMessage(self):
"""
The behavior when the underlying C{sendmsg} call fails is the same
whether L{send1msg} is passed ancillary data or not.
"""
with open(devnull) as probe:
fd = probe.fileno()
exc = self.assertRaises(
error, send1msg, fd, "hello, world", 0, [(0, 0, "0123")])
self.assertEqual(exc.args[0], errno.EBADF)
def test_roundtrip(self):
"""
L{recv1msg} will retrieve a message sent via L{send1msg}.
"""
message = "hello, world!"
self.assertEqual(
len(message),
send1msg(self.input.fileno(), message, 0))
result = recv1msg(fd=self.output.fileno())
self.assertEqual(result, (message, 0, []))
def test_shortsend(self):
"""
L{send1msg} returns the number of bytes which it was able to send.
"""
message = "x" * 1024 * 1024
self.input.setblocking(False)
sent = send1msg(self.input.fileno(), message)
# Sanity check - make sure the amount of data we sent was less than the
# message, but not the whole message, as we should have filled the send
# buffer. This won't work if the send buffer is more than 1MB, though.
self.assertTrue(sent < len(message))
received = recv1msg(self.output.fileno(), 0, len(message))
self.assertEqual(len(received[0]), sent)
def test_roundtripEmptyAncillary(self):
"""
L{send1msg} treats an empty ancillary data list the same way it treats
receiving no argument for the ancillary parameter at all.
"""
send1msg(self.input.fileno(), "hello, world!", 0, [])
result = recv1msg(fd=self.output.fileno())
self.assertEqual(result, ("hello, world!", 0, []))
def test_flags(self):
"""
The C{flags} argument to L{send1msg} is passed on to the underlying
C{sendmsg} call, to affect it in whatever way is defined by those
flags.
"""
# Just exercise one flag with simple, well-known behavior. MSG_DONTWAIT
# makes the send a non-blocking call, even if the socket is in blocking
# mode. See also test_flags in RecvmsgTests
for i in range(1024):
try:
send1msg(self.input.fileno(), "x" * 1024, MSG_DONTWAIT)
except error as e:
self.assertEqual(e.args[0], errno.EAGAIN)
break
else:
self.fail(
"Failed to fill up the send buffer, "
"or maybe send1msg blocked for a while")
if dontWaitSkip is not None:
test_flags.skip = dontWaitSkip
def test_wrongTypeAncillary(self):
"""
L{send1msg} will show a helpful exception message when given the wrong
type of object for the 'ancillary' argument.
"""
error = self.assertRaises(TypeError,
send1msg, self.input.fileno(),
"hello, world!", 0, 4321)
self.assertEqual(str(error),
"send1msg argument 3 expected list, got int")
@inlineCallbacks
def test_sendSubProcessFD(self):
"""
Calling L{sendsmsg} with SOL_SOCKET, SCM_RIGHTS, and a platform-endian
packed file descriptor number should send that file descriptor to a
different process, where it can be retrieved by using L{recv1msg}.
"""
sspp = _spawn("cmodulepullpipe", self.output.fileno())
yield sspp.started
pipeOut, pipeIn = _makePipe()
self.addCleanup(pipeOut.close)
self.addCleanup(pipeIn.close)
with pipeIn:
send1msg(
self.input.fileno(), "blonk", 0,
[(SOL_SOCKET, SCM_RIGHTS, pack("i", pipeIn.fileno()))])
yield sspp.stopped
self.assertEqual(read(pipeOut.fileno(), 1024),
"Test fixture data: blonk.\n")
# Make sure that the pipe is actually closed now.
self.assertEqual(read(pipeOut.fileno(), 1024), "")
def test_sendmsgTwoAncillaryDoesNotSegfault(self):
"""
L{sendmsg} with two FDs in two separate ancillary entries
does not segfault.
"""
ancillary = [
(SOL_SOCKET, SCM_RIGHTS, pack("i", self.input.fileno())),
(SOL_SOCKET, SCM_RIGHTS, pack("i", self.output.fileno())),
]
try:
send1msg(self.input.fileno(), b"some data", 0, ancillary)
except error:
# Ok as long as it doesn't segfault.
pass
class CModuleRecvmsgTests(TestCase):
"""
Tests for L{recv1msg} (primarily error handling cases).
"""
if CModuleImportSkip is not None:
skip = CModuleImportSkip
def test_badArguments(self):
"""
The argument types accepted by L{recv1msg} are:
1. C{int}
2. C{int}
3. C{int}
4. C{int}
The 2nd, 3rd, and 4th arguments are optional. If fewer than one
argument or more than four arguments are passed, or if any of the
arguments passed are not compatible with these types, L{TypeError} is
raised.
"""
# Exercise the wrong number of arguments cases
self.assertRaises(TypeError, recv1msg)
self.assertRaises(TypeError, recv1msg, 1, 2, 3, 4, object())
# Exercise the wrong type of arguments cases
self.assertRaises(TypeError, recv1msg, object(), 2, 3, 4)
self.assertRaises(TypeError, recv1msg, 1, object(), 3, 4)
self.assertRaises(TypeError, recv1msg, 1, 2, object(), 4)
self.assertRaises(TypeError, recv1msg, 1, 2, 3, object())
def test_cmsgSpaceOverflow(self):
"""
L{recv1msg} raises L{OverflowError} if passed a value for the
C{cmsg_size} argument which exceeds C{SOCKLEN_MAX}.
"""
self.assertRaises(OverflowError, recv1msg, 0, 0, 0, 0x7FFFFFFF)
def test_syscallError(self):
"""
If the underlying C{recvmsg} call fails, L{recv1msg} raises
L{socket.error} with its errno set to the underlying errno value.
"""
with open(devnull) as probe:
fd = probe.fileno()
exc = self.assertRaises(error, recv1msg, fd)
self.assertEqual(exc.args[0], errno.EBADF)
def test_flags(self):
"""
The C{flags} argument to L{recv1msg} is passed on to the underlying
C{recvmsg} call, to affect it in whatever way is defined by those
flags.
"""
# See test_flags in SendmsgTests
reader, writer = socketpair(AF_UNIX)
exc = self.assertRaises(
error, recv1msg, reader.fileno(), MSG_DONTWAIT)
self.assertEqual(exc.args[0], errno.EAGAIN)
if dontWaitSkip is not None:
test_flags.skip = dontWaitSkip
class CModuleGetSocketFamilyTests(TestCase):
"""
Tests for L{getsockfam}, a helper which reveals the address family of an
arbitrary socket.
"""
if CModuleImportSkip is not None:
skip = CModuleImportSkip
def _socket(self, addressFamily):
"""
Create a new socket using the given address family and return that
socket's file descriptor. The socket will automatically be closed when
the test is torn down.
"""
s = socket(addressFamily)
self.addCleanup(s.close)
return s.fileno()
def test_badArguments(self):
"""
L{getsockfam} accepts a single C{int} argument. If it is called in
some other way, L{TypeError} is raised.
"""
self.assertRaises(TypeError, getsockfam)
self.assertRaises(TypeError, getsockfam, 1, 2)
self.assertRaises(TypeError, getsockfam, object())
def test_syscallError(self):
"""
If the underlying C{getsockname} call fails, L{getsockfam} raises
L{socket.error} with its errno set to the underlying errno value.
"""
with open(devnull) as probe:
fd = probe.fileno()
exc = self.assertRaises(error, getsockfam, fd)
self.assertEqual(errno.EBADF, exc.args[0])
def test_inet(self):
"""
When passed the file descriptor of a socket created with the C{AF_INET}
address family, L{getsockfam} returns C{AF_INET}.
"""
self.assertEqual(AF_INET, getsockfam(self._socket(AF_INET)))
def test_inet6(self):
"""
When passed the file descriptor of a socket created with the
C{AF_INET6} address family, L{getsockfam} returns C{AF_INET6}.
"""
self.assertEqual(AF_INET6, getsockfam(self._socket(AF_INET6)))
def test_unix(self):
"""
When passed the file descriptor of a socket created with the C{AF_UNIX}
address family, L{getsockfam} returns C{AF_UNIX}.
"""
self.assertEqual(AF_UNIX, getsockfam(self._socket(AF_UNIX)))
if nonUNIXSkip is not None:
test_unix.skip = nonUNIXSkip
class SendmsgTests(TestCase):
"""
Tests for the Python2/3 compatible L{sendmsg} interface.
"""
if importSkip is not None:
skip = importSkip
def setUp(self):
"""
Create a pair of UNIX sockets.
"""
self.input, self.output = socketpair(AF_UNIX)
def tearDown(self):
"""
Close the sockets opened by setUp.
"""
self.input.close()
self.output.close()
def test_syscallError(self):
"""
If the underlying C{sendmsg} call fails, L{send1msg} raises
L{socket.error} with its errno set to the underlying errno value.
"""
self.input.close()
exc = self.assertRaises(error, sendmsg, self.input, b"hello, world")
self.assertEqual(exc.args[0], errno.EBADF)
def test_syscallErrorWithControlMessage(self):
"""
The behavior when the underlying C{sendmsg} call fails is the same
whether L{sendmsg} is passed ancillary data or not.
"""
self.input.close()
exc = self.assertRaises(
error, sendmsg, self.input, b"hello, world", [(0, 0, b"0123")], 0)
self.assertEqual(exc.args[0], errno.EBADF)
def test_roundtrip(self):
"""
L{recvmsg} will retrieve a message sent via L{sendmsg}.
"""
message = b"hello, world!"
self.assertEqual(
len(message),
sendmsg(self.input, message))
result = recvmsg(self.output)
self.assertEqual(result.data, b"hello, world!")
self.assertEqual(result.flags, 0)
self.assertEqual(result.ancillary, [])
def test_shortsend(self):
"""
L{sendmsg} returns the number of bytes which it was able to send.
"""
message = b"x" * 1024 * 1024
self.input.setblocking(False)
sent = sendmsg(self.input, message)
# Sanity check - make sure the amount of data we sent was less than the
# message, but not the whole message, as we should have filled the send
# buffer. This won't work if the send buffer is more than 1MB, though.
self.assertTrue(sent < len(message))
received = recvmsg(self.output, len(message))
self.assertEqual(len(received[0]), sent)
def test_roundtripEmptyAncillary(self):
"""
L{sendmsg} treats an empty ancillary data list the same way it treats
receiving no argument for the ancillary parameter at all.
"""
sendmsg(self.input, b"hello, world!", [], 0)
result = recvmsg(self.output)
self.assertEqual(result, (b"hello, world!", [], 0))
def test_flags(self):
"""
The C{flags} argument to L{sendmsg} is passed on to the underlying
C{sendmsg} call, to affect it in whatever way is defined by those
flags.
"""
# Just exercise one flag with simple, well-known behavior. MSG_DONTWAIT
# makes the send a non-blocking call, even if the socket is in blocking
# mode. See also test_flags in RecvmsgTests
for i in range(1024):
try:
sendmsg(self.input, b"x" * 1024, flags=MSG_DONTWAIT)
except error as e:
self.assertEqual(e.args[0], errno.EAGAIN)
break
else:
self.fail(
"Failed to fill up the send buffer, "
"or maybe send1msg blocked for a while")
if dontWaitSkip is not None:
test_flags.skip = dontWaitSkip
@inlineCallbacks
def test_sendSubProcessFD(self):
"""
Calling L{sendmsg} with SOL_SOCKET, SCM_RIGHTS, and a platform-endian
packed file descriptor number should send that file descriptor to a
different process, where it can be retrieved by using L{recv1msg}.
"""
sspp = _spawn("pullpipe", self.output.fileno())
yield sspp.started
pipeOut, pipeIn = _makePipe()
self.addCleanup(pipeOut.close)
self.addCleanup(pipeIn.close)
with pipeIn:
sendmsg(
self.input, b"blonk",
[(SOL_SOCKET, SCM_RIGHTS, pack("i", pipeIn.fileno()))])
yield sspp.stopped
self.assertEqual(read(pipeOut.fileno(), 1024),
b"Test fixture data: blonk.\n")
# Make sure that the pipe is actually closed now.
self.assertEqual(read(pipeOut.fileno(), 1024), b"")
class GetSocketFamilyTests(TestCase):
"""
Tests for L{getSocketFamily}.
"""
if importSkip is not None:
skip = importSkip
def _socket(self, addressFamily):
"""
Create a new socket using the given address family and return that
socket's file descriptor. The socket will automatically be closed when
the test is torn down.
"""
s = socket(addressFamily)
self.addCleanup(s.close)
return s
def test_inet(self):
"""
When passed the file descriptor of a socket created with the C{AF_INET}
address family, L{getSocketFamily} returns C{AF_INET}.
"""
self.assertEqual(AF_INET, getSocketFamily(self._socket(AF_INET)))
def test_inet6(self):
"""
When passed the file descriptor of a socket created with the
C{AF_INET6} address family, L{getSocketFamily} returns C{AF_INET6}.
"""
self.assertEqual(AF_INET6, getSocketFamily(self._socket(AF_INET6)))
def test_unix(self):
"""
When passed the file descriptor of a socket created with the C{AF_UNIX}
address family, L{getSocketFamily} returns C{AF_UNIX}.
"""
self.assertEqual(AF_UNIX, getSocketFamily(self._socket(AF_UNIX)))
if nonUNIXSkip is not None:
test_unix.skip = nonUNIXSkip | unknown | codeparrot/codeparrot-clean | ||
package daemon
import (
"testing"
"github.com/moby/moby/api/types/container"
)
func TestToContainerdResources_Defaults(t *testing.T) {
checkResourcesAreUnset(t, toContainerdResources(container.Resources{}))
} | go | github | https://github.com/moby/moby | daemon/update_linux_test.go |
groups:
- name: test_2 copy
rules:
- record: test_2
expr: vector(2) | unknown | github | https://github.com/prometheus/prometheus | rules/fixtures/rules2_copy.yaml |
#!/usr/bin/env python
# Copyright (c) 2010 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
import time
output = sys.argv[1]
persistoutput = "%s.persist" % sys.argv[1]
count = 0
try:
count = open(persistoutput, 'r').read()
except:
pass
count = int(count) + 1
if len(sys.argv) > 2:
max_count = int(sys.argv[2])
if count > max_count:
count = max_count
oldcount = 0
try:
oldcount = open(output, 'r').read()
except:
pass
# Save the count in a file that is undeclared, and thus hidden, to gyp. We need
# to do this because, prior to running commands, scons deletes any declared
# outputs, so we would lose our count if we just wrote to the given output file.
# (The other option is to use Precious() in the scons generator, but that seems
# too heavy-handed just to support this somewhat unrealistic test case, and
# might lead to unintended side-effects).
open(persistoutput, 'w').write('%d' % (count))
# Only write the given output file if the count has changed.
if int(oldcount) != count:
open(output, 'w').write('%d' % (count))
# Sleep so the next run changes the file time sufficiently to make the build
# detect the file as changed.
time.sleep(1)
sys.exit(0) | unknown | codeparrot/codeparrot-clean | ||
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
Base classes for writing management commands (named commands which can
be executed through ``django-admin.py`` or ``manage.py``).
"""
import os
import sys
import warnings
from optparse import make_option, OptionParser
import django
from django.core import checks
from django.core.exceptions import ImproperlyConfigured
from django.core.management.color import color_style, no_style
from django.utils.deprecation import RemovedInDjango19Warning
from django.utils.encoding import force_str
class CommandError(Exception):
"""
Exception class indicating a problem while executing a management
command.
If this exception is raised during the execution of a management
command, it will be caught and turned into a nicely-printed error
message to the appropriate output stream (i.e., stderr); as a
result, raising this exception (with a sensible description of the
error) is the preferred way to indicate that something has gone
wrong in the execution of a command.
"""
pass
def handle_default_options(options):
"""
Include any default options that all commands should accept here
so that ManagementUtility can handle them before searching for
user commands.
"""
if options.settings:
os.environ['DJANGO_SETTINGS_MODULE'] = options.settings
if options.pythonpath:
sys.path.insert(0, options.pythonpath)
class OutputWrapper(object):
"""
Wrapper around stdout/stderr
"""
def __init__(self, out, style_func=None, ending='\n'):
self._out = out
self.style_func = None
if hasattr(out, 'isatty') and out.isatty():
self.style_func = style_func
self.ending = ending
def __getattr__(self, name):
return getattr(self._out, name)
def write(self, msg, style_func=None, ending=None):
ending = self.ending if ending is None else ending
if ending and not msg.endswith(ending):
msg += ending
style_func = [f for f in (style_func, self.style_func, lambda x:x)
if f is not None][0]
self._out.write(force_str(style_func(msg)))
class BaseCommand(object):
"""
The base class from which all management commands ultimately
derive.
Use this class if you want access to all of the mechanisms which
parse the command-line arguments and work out what code to call in
response; if you don't need to change any of that behavior,
consider using one of the subclasses defined in this file.
If you are interested in overriding/customizing various aspects of
the command-parsing and -execution behavior, the normal flow works
as follows:
1. ``django-admin.py`` or ``manage.py`` loads the command class
and calls its ``run_from_argv()`` method.
2. The ``run_from_argv()`` method calls ``create_parser()`` to get
an ``OptionParser`` for the arguments, parses them, performs
any environment changes requested by options like
``pythonpath``, and then calls the ``execute()`` method,
passing the parsed arguments.
3. The ``execute()`` method attempts to carry out the command by
calling the ``handle()`` method with the parsed arguments; any
output produced by ``handle()`` will be printed to standard
output and, if the command is intended to produce a block of
SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``.
4. If ``handle()`` or ``execute()`` raised any exception (e.g.
``CommandError``), ``run_from_argv()`` will instead print an error
message to ``stderr``.
Thus, the ``handle()`` method is typically the starting point for
subclasses; many built-in commands and command types either place
all of their logic in ``handle()``, or perform some additional
parsing work in ``handle()`` and then delegate from it to more
specialized methods as needed.
Several attributes affect behavior at various steps along the way:
``args``
A string listing the arguments accepted by the command,
suitable for use in help messages; e.g., a command which takes
a list of application names might set this to '<app_label
app_label ...>'.
``can_import_settings``
A boolean indicating whether the command needs to be able to
import Django settings; if ``True``, ``execute()`` will verify
that this is possible before proceeding. Default value is
``True``.
``help``
A short description of the command, which will be printed in
help messages.
``option_list``
This is the list of ``optparse`` options which will be fed
into the command's ``OptionParser`` for parsing arguments.
``output_transaction``
A boolean indicating whether the command outputs SQL
statements; if ``True``, the output will automatically be
wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is
``False``.
``requires_system_checks``
A boolean; if ``True``, entire Django project will be checked for errors
prior to executing the command. Default value is ``True``.
To validate an individual application's models
rather than all applications' models, call
``self.check(app_configs)`` from ``handle()``, where ``app_configs``
is the list of application's configuration provided by the
app registry.
``requires_model_validation``
DEPRECATED - This value will only be used if requires_system_checks
has not been provided. Defining both ``requires_system_checks`` and
``requires_model_validation`` will result in an error.
A boolean; if ``True``, validation of installed models will be
performed prior to executing the command. Default value is
``True``. To validate an individual application's models
rather than all applications' models, call
``self.validate(app_config)`` from ``handle()``, where ``app_config``
is the application's configuration provided by the app registry.
``leave_locale_alone``
A boolean indicating whether the locale set in settings should be
preserved during the execution of the command instead of being
forcibly set to 'en-us'.
Default value is ``False``.
Make sure you know what you are doing if you decide to change the value
of this option in your custom command if it creates database content
that is locale-sensitive and such content shouldn't contain any
translations (like it happens e.g. with django.contrim.auth
permissions) as making the locale differ from the de facto default
'en-us' might cause unintended effects.
This option can't be False when the can_import_settings option is set
to False too because attempting to set the locale needs access to
settings. This condition will generate a CommandError.
"""
# Metadata about this command.
option_list = (
make_option('-v', '--verbosity', action='store', dest='verbosity', default='1',
type='choice', choices=['0', '1', '2', '3'],
help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output'),
make_option('--settings',
help='The Python path to a settings module, e.g. "myproject.settings.main". If this isn\'t provided, the DJANGO_SETTINGS_MODULE environment variable will be used.'),
make_option('--pythonpath',
help='A directory to add to the Python path, e.g. "/home/djangoprojects/myproject".'),
make_option('--traceback', action='store_true',
help='Raise on exception'),
make_option('--no-color', action='store_true', dest='no_color', default=False,
help="Don't colorize the command output."),
)
help = ''
args = ''
# Configuration shortcuts that alter various logic.
can_import_settings = True
output_transaction = False # Whether to wrap the output in a "BEGIN; COMMIT;"
leave_locale_alone = False
# Uncomment the following line of code after deprecation plan for
# requires_model_validation comes to completion:
#
# requires_system_checks = True
def __init__(self):
self.style = color_style()
# `requires_model_validation` is deprecated in favor of
# `requires_system_checks`. If both options are present, an error is
# raised. Otherwise the present option is used. If none of them is
# defined, the default value (True) is used.
has_old_option = hasattr(self, 'requires_model_validation')
has_new_option = hasattr(self, 'requires_system_checks')
if has_old_option:
warnings.warn(
'"requires_model_validation" is deprecated '
'in favor of "requires_system_checks".',
RemovedInDjango19Warning)
if has_old_option and has_new_option:
raise ImproperlyConfigured(
'Command %s defines both "requires_model_validation" '
'and "requires_system_checks", which is illegal. Use only '
'"requires_system_checks".' % self.__class__.__name__)
self.requires_system_checks = (
self.requires_system_checks if has_new_option else
self.requires_model_validation if has_old_option else
True)
def get_version(self):
"""
Return the Django version, which should be correct for all
built-in Django commands. User-supplied commands should
override this method.
"""
return django.get_version()
def usage(self, subcommand):
"""
Return a brief description of how to use this command, by
default from the attribute ``self.help``.
"""
usage = '%%prog %s [options] %s' % (subcommand, self.args)
if self.help:
return '%s\n\n%s' % (usage, self.help)
else:
return usage
def create_parser(self, prog_name, subcommand):
"""
Create and return the ``OptionParser`` which will be used to
parse the arguments to this command.
"""
return OptionParser(prog=prog_name,
usage=self.usage(subcommand),
version=self.get_version(),
option_list=self.option_list)
def print_help(self, prog_name, subcommand):
"""
Print the help message for this command, derived from
``self.usage()``.
"""
parser = self.create_parser(prog_name, subcommand)
parser.print_help()
def run_from_argv(self, argv):
"""
Set up any environment changes requested (e.g., Python path
and Django settings), then run this command. If the
command raises a ``CommandError``, intercept it and print it sensibly
to stderr. If the ``--traceback`` option is present or the raised
``Exception`` is not ``CommandError``, raise it.
"""
parser = self.create_parser(argv[0], argv[1])
options, args = parser.parse_args(argv[2:])
handle_default_options(options)
try:
self.execute(*args, **options.__dict__)
except Exception as e:
if options.traceback or not isinstance(e, CommandError):
raise
# self.stderr is not guaranteed to be set here
stderr = getattr(self, 'stderr', OutputWrapper(sys.stderr, self.style.ERROR))
stderr.write('%s: %s' % (e.__class__.__name__, e))
sys.exit(1)
def execute(self, *args, **options):
"""
Try to execute this command, performing system checks if needed (as
controlled by attributes ``self.requires_system_checks`` and
``self.requires_model_validation``, except if force-skipped).
"""
self.stdout = OutputWrapper(options.get('stdout', sys.stdout))
if options.get('no_color'):
self.style = no_style()
self.stderr = OutputWrapper(options.get('stderr', sys.stderr))
os.environ[str("DJANGO_COLORS")] = str("nocolor")
else:
self.stderr = OutputWrapper(options.get('stderr', sys.stderr), self.style.ERROR)
if self.can_import_settings:
from django.conf import settings # NOQA
saved_locale = None
if not self.leave_locale_alone:
# Only mess with locales if we can assume we have a working
# settings file, because django.utils.translation requires settings
# (The final saying about whether the i18n machinery is active will be
# found in the value of the USE_I18N setting)
if not self.can_import_settings:
raise CommandError("Incompatible values of 'leave_locale_alone' "
"(%s) and 'can_import_settings' (%s) command "
"options." % (self.leave_locale_alone,
self.can_import_settings))
# Switch to US English, because django-admin.py creates database
# content like permissions, and those shouldn't contain any
# translations.
from django.utils import translation
saved_locale = translation.get_language()
translation.activate('en-us')
try:
if (self.requires_system_checks and
not options.get('skip_validation') and # This will be removed at the end of deprecation process for `skip_validation`.
not options.get('skip_checks')):
self.check()
output = self.handle(*args, **options)
if output:
if self.output_transaction:
# This needs to be imported here, because it relies on
# settings.
from django.db import connections, DEFAULT_DB_ALIAS
connection = connections[options.get('database', DEFAULT_DB_ALIAS)]
if connection.ops.start_transaction_sql():
self.stdout.write(self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()))
self.stdout.write(output)
if self.output_transaction:
self.stdout.write('\n' + self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()))
finally:
if saved_locale is not None:
translation.activate(saved_locale)
def validate(self, app_config=None, display_num_errors=False):
""" Deprecated. Delegates to ``check``."""
if app_config is None:
app_configs = None
else:
app_configs = [app_config]
return self.check(app_configs=app_configs, display_num_errors=display_num_errors)
def check(self, app_configs=None, tags=None, display_num_errors=False):
"""
Uses the system check framework to validate entire Django project.
Raises CommandError for any serious message (error or critical errors).
If there are only light messages (like warnings), they are printed to
stderr and no exception is raised.
"""
all_issues = checks.run_checks(app_configs=app_configs, tags=tags)
msg = ""
visible_issue_count = 0 # excludes silenced warnings
if all_issues:
debugs = [e for e in all_issues if e.level < checks.INFO and not e.is_silenced()]
infos = [e for e in all_issues if checks.INFO <= e.level < checks.WARNING and not e.is_silenced()]
warnings = [e for e in all_issues if checks.WARNING <= e.level < checks.ERROR and not e.is_silenced()]
errors = [e for e in all_issues if checks.ERROR <= e.level < checks.CRITICAL]
criticals = [e for e in all_issues if checks.CRITICAL <= e.level]
sorted_issues = [
(criticals, 'CRITICALS'),
(errors, 'ERRORS'),
(warnings, 'WARNINGS'),
(infos, 'INFOS'),
(debugs, 'DEBUGS'),
]
for issues, group_name in sorted_issues:
if issues:
visible_issue_count += len(issues)
formatted = (
color_style().ERROR(force_str(e))
if e.is_serious()
else color_style().WARNING(force_str(e))
for e in issues)
formatted = "\n".join(sorted(formatted))
msg += '\n%s:\n%s\n' % (group_name, formatted)
if msg:
msg = "System check identified some issues:\n%s" % msg
if display_num_errors:
if msg:
msg += '\n'
msg += "System check identified %s (%s silenced)." % (
"no issues" if visible_issue_count == 0 else
"1 issue" if visible_issue_count == 1 else
"%s issues" % visible_issue_count,
len(all_issues) - visible_issue_count,
)
if any(e.is_serious() and not e.is_silenced() for e in all_issues):
raise CommandError(msg)
elif msg and visible_issue_count:
self.stderr.write(msg)
elif msg:
self.stdout.write(msg)
def handle(self, *args, **options):
"""
The actual logic of the command. Subclasses must implement
this method.
"""
raise NotImplementedError('subclasses of BaseCommand must provide a handle() method')
class AppCommand(BaseCommand):
"""
A management command which takes one or more installed application labels
as arguments, and does something with each of them.
Rather than implementing ``handle()``, subclasses must implement
``handle_app_config()``, which will be called once for each application.
"""
args = '<app_label app_label ...>'
def handle(self, *app_labels, **options):
from django.apps import apps
if not app_labels:
raise CommandError("Enter at least one application label.")
try:
app_configs = [apps.get_app_config(app_label) for app_label in app_labels]
except (LookupError, ImportError) as e:
raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)
output = []
for app_config in app_configs:
app_output = self.handle_app_config(app_config, **options)
if app_output:
output.append(app_output)
return '\n'.join(output)
def handle_app_config(self, app_config, **options):
"""
Perform the command's actions for app_config, an AppConfig instance
corresponding to an application label given on the command line.
"""
try:
# During the deprecation path, keep delegating to handle_app if
# handle_app_config isn't implemented in a subclass.
handle_app = self.handle_app
except AttributeError:
# Keep only this exception when the deprecation completes.
raise NotImplementedError(
"Subclasses of AppCommand must provide"
"a handle_app_config() method.")
else:
warnings.warn(
"AppCommand.handle_app() is superseded by "
"AppCommand.handle_app_config().",
RemovedInDjango19Warning, stacklevel=2)
if app_config.models_module is None:
raise CommandError(
"AppCommand cannot handle app '%s' in legacy mode "
"because it doesn't have a models module."
% app_config.label)
return handle_app(app_config.models_module, **options)
class LabelCommand(BaseCommand):
"""
A management command which takes one or more arbitrary arguments
(labels) on the command line, and does something with each of
them.
Rather than implementing ``handle()``, subclasses must implement
``handle_label()``, which will be called once for each label.
If the arguments should be names of installed applications, use
``AppCommand`` instead.
"""
args = '<label label ...>'
label = 'label'
def handle(self, *labels, **options):
if not labels:
raise CommandError('Enter at least one %s.' % self.label)
output = []
for label in labels:
label_output = self.handle_label(label, **options)
if label_output:
output.append(label_output)
return '\n'.join(output)
def handle_label(self, label, **options):
"""
Perform the command's actions for ``label``, which will be the
string as given on the command line.
"""
raise NotImplementedError('subclasses of LabelCommand must provide a handle_label() method')
class NoArgsCommand(BaseCommand):
"""
A command which takes no arguments on the command line.
Rather than implementing ``handle()``, subclasses must implement
``handle_noargs()``; ``handle()`` itself is overridden to ensure
no arguments are passed to the command.
Attempting to pass arguments will raise ``CommandError``.
"""
args = ''
def handle(self, *args, **options):
if args:
raise CommandError("Command doesn't accept any arguments")
return self.handle_noargs(**options)
def handle_noargs(self, **options):
"""
Perform this command's actions.
"""
raise NotImplementedError('subclasses of NoArgsCommand must provide a handle_noargs() method') | unknown | codeparrot/codeparrot-clean | ||
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package providers
import (
"testing"
"github.com/go-test/deep"
"github.com/hashicorp/terraform/internal/addrs"
)
func TestAddressedTypesAbs(t *testing.T) {
providerAddrs := []addrs.AbsProviderConfig{
addrs.AbsProviderConfig{
Module: addrs.RootModule,
Provider: addrs.NewDefaultProvider("aws"),
},
addrs.AbsProviderConfig{
Module: addrs.RootModule,
Provider: addrs.NewDefaultProvider("aws"),
Alias: "foo",
},
addrs.AbsProviderConfig{
Module: addrs.RootModule,
Provider: addrs.NewDefaultProvider("azure"),
},
addrs.AbsProviderConfig{
Module: addrs.RootModule,
Provider: addrs.NewDefaultProvider("null"),
},
addrs.AbsProviderConfig{
Module: addrs.RootModule,
Provider: addrs.NewDefaultProvider("null"),
},
}
got := AddressedTypesAbs(providerAddrs)
want := []addrs.Provider{
addrs.NewDefaultProvider("aws"),
addrs.NewDefaultProvider("azure"),
addrs.NewDefaultProvider("null"),
}
for _, problem := range deep.Equal(got, want) {
t.Error(problem)
}
} | go | github | https://github.com/hashicorp/terraform | internal/providers/addressed_types_test.go |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
"""
Knowledge base module objects
"""
from django.db import models
from treeio.core.models import Object
from django.core.urlresolvers import reverse
from django.template import defaultfilters
from unidecode import unidecode
# KnowledgeFolder model
class KnowledgeFolder(Object):
""" KnowledgeFolder """
name = models.CharField(max_length=255)
details = models.TextField(max_length=255, null=True, blank=True)
parent = models.ForeignKey('self', blank=True, null=True, related_name='child_set')
treepath = models.CharField(max_length=800)
access_inherit = ('parent', '*module', '*user')
def __unicode__(self):
return self.name
class Meta:
" Type "
ordering = ['name']
def get_absolute_url(self):
"Returns absolute URL of the object"
try:
return reverse('knowledge_folder_view', args=[self.treepath])
except Exception:
return ""
def treewalk(self, save=True):
"Walks up the tree to construct Type treepath"
treepath = ''
for folder in self.get_tree_path():
slug = unicode(folder.name).replace(" ", "-")
slug = defaultfilters.slugify(unidecode(slug))
treepath += slug + "/"
self.treepath = treepath
if save:
self.save()
return self
def by_path(treePath):
"Returns a KnowledgeFolder instance matching the given treepath"
folder = KnowledgeFolder.objects.filter(treepath=unicode(treePath))
if folder:
folder = folder[0]
else:
folder = None
return folder
by_path = staticmethod(by_path)
def save(self, *args, **kwargs):
"Overridden save() method to compute treepath and full names"
self.treewalk(save=False)
super(KnowledgeFolder, self).save(*args, **kwargs)
# KnowledgeCategory model
class KnowledgeCategory(Object):
""" Knowledge Category that contains Knowledge Items"""
name = models.CharField(max_length=255)
details = models.TextField(max_length=255, null=True, blank=True)
treepath = models.CharField(max_length=800)
def __unicode__(self):
return self.name
class Meta:
" Category "
ordering = ['name']
def get_absolute_url(self):
"Returns absolute URL of the object"
try:
return reverse('knowledge_category_view', args=[self.treepath])
except Exception:
return ""
def treewalk(self, save=True):
"Walks up the tree to construct Category"
slug = unicode(self.name).replace(" ", "-")
slug = defaultfilters.slugify(unidecode(slug))
treepath = slug + "/"
self.treepath = treepath
if save:
self.save()
return self
def by_path(path):
"Returns a Knowledge Category instance matching the given treepath"
category = KnowledgeCategory.objects.filter(treepath=unidecode(path))
if category:
category = category[0]
else:
category = None
return category
by_path = staticmethod(by_path)
def save(self, *args, **kwargs):
"Overridden save() method to compute treepath and full names"
self.treewalk(save=False)
super(KnowledgeCategory, self).save(*args, **kwargs)
# KnowledgeItem model
class KnowledgeItem(Object):
"""" A readable piece of knowledge """
name = models.CharField(max_length=255)
folder = models.ForeignKey(KnowledgeFolder)
category = models.ForeignKey(KnowledgeCategory, blank=True, null=True, on_delete=models.SET_NULL)
body = models.TextField(null=True, blank=True)
treepath = models.CharField(max_length=800)
access_inherit = ('folder', '*module', '*user')
def __unicode__(self):
return self.name
class Meta:
" Item "
ordering = ['-last_updated']
def get_absolute_url(self):
"Returns absolute URL of the object"
try:
return reverse('knowledge_item_view', args=[self.folder.treepath, self.treepath])
except Exception:
return ""
def treewalk(self, save=True):
"Walks up the tree to construct both Item treepath and item.name from database"
slug = unicode(self.name).replace(" ", "-")
slug = defaultfilters.slugify(unidecode(slug))
treepath = slug + "/"
self.treepath = treepath
if save:
self.save()
return self
def by_path(treePath, itemPath):
"Returns a Knowledge Item instance matching the given treepath"
folder = KnowledgeFolder.by_path(unidecode(treePath))
item = KnowledgeItem.objects.filter(treepath=unidecode(itemPath), folder=folder)
if item:
item = item[0]
else:
item = None
return item
by_path = staticmethod(by_path)
def save(self, *args, **kwargs):
"Overridden save() method to compute treepath and full names"
self.treewalk(save=False)
super(KnowledgeItem, self).save(*args, **kwargs) | unknown | codeparrot/codeparrot-clean | ||
# Copyright (c) 2014 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import re
from poppy.transport.validators.stoplight import decorators
from poppy.transport.validators.stoplight import exceptions
from tests.functional import base
error_count = 0
def abort(code):
global error_count
error_count = error_count + 1
@decorators.validation_function
def is_valid_json(r):
'''Test for a valid JSON string.'''
if len(r.body) == 0:
return
else:
try:
json.loads(r.body.decode('utf-8'))
except Exception as e:
e
raise exceptions.ValidationFailed('Invalid JSON string')
else:
return
class DummyRequest(object):
def __init__(self):
self.headers = dict(header1='headervalue1')
self.method = 'POST'
self.body = json.dumps({
'name': 'fake_service_name',
'domains': [
{'domain': 'www.mywebsite.com'},
{'domain': 'blog.mywebsite.com'},
],
'origins': [
{
'origin': 'mywebsite.com',
'port': 80,
'ssl': False
},
{
'origin': 'mywebsite.com',
'rules': [{
'name': 'img',
'request_url': '/img'
}]
}
],
'caching': [
{'name': 'default', 'ttl': 3600},
{'name': 'home',
'ttl': 17200,
'rules': [
{'name': 'index', 'request_url': '/index.htm'}
]
},
{"name": "images",
"ttl": 12800,
"rules": [
{"name": "img", "request_url": "/img/*"}
]
}
],
"flavor_id": "standard"
})
class DummyRequestWithInvalidHeader(DummyRequest):
def client_accepts(self, header='application/json'):
return False
def accept(self, header='application/json'):
return False
fake_request_good = DummyRequest()
fake_request_bad_missing_domain = DummyRequest()
fake_request_bad_missing_domain.body = json.dumps({
'name': 'fake_service_name',
'origins': [
{
'origin': 'mywebsite.com',
'port': 80,
'ssl': False
}
],
'caching': [
{'name': 'default', 'ttl': 3600},
{'name': 'home',
'ttl': 17200,
'rules': [
{'name': 'index', 'request_url': '/index.htm'}
]
},
{'name': 'images',
'ttl': 12800,
'rules': [
{'name': 'images', 'request_url': '*.png'}
]
}
],
"flavor_id": "standard"
})
fake_request_bad_invalid_json_body = DummyRequest()
fake_request_bad_invalid_json_body.body = '{'
class _AssertRaisesContext(object):
'''A context manager used to implement TestCase.assertRaises* methods.'''
def __init__(self, expected, test_case, expected_regexp=None):
self.expected = expected
self.failureException = test_case.failureException
self.expected_regexp = expected_regexp
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, tb):
if exc_type is None:
try:
exc_name = self.expected.__name__
except AttributeError:
exc_name = str(self.expected)
raise self.failureException(
'{0} not raised'.format(exc_name))
if not issubclass(exc_type, self.expected):
return False # let unexpected exceptions pass through
self.exception = exc_value # store for later retrieval
if self.expected_regexp is None:
return True
expected_regexp = self.expected_regexp
try:
basestring
except NameError:
# Python 3 compatibility
basestring = unicode = str
unicode # For pep8: unicode is defined but not used.
if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp)
if not expected_regexp.search(str(exc_value)):
raise self.failureException('"%s" does not match "%s"' %
(expected_regexp.pattern,
str(exc_value)))
return True
class BaseTestCase(base.TestCase):
def assertRaises(self, excClass, callableObj=None, *args, **kwargs):
'''Check the expected Exception is raised.
Fail unless an exception of class excClass is raised
by callableObj when invoked with arguments args and keyword
arguments kwargs. If a different type of exception is
raised, it will not be caught, and the test case will be
deemed to have suffered an error, exactly as for an
unexpected exception.
If called with callableObj omitted or None, will return a
context object used like this::
with self.assertRaises(SomeException):
do_something()
The context manager keeps a reference to the exception as
the 'exception' attribute. This allows you to inspect the
exception after the assertion::
with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)
'''
context = _AssertRaisesContext(excClass, self)
if callableObj is None:
return context
with context:
callableObj(*args, **kwargs)
def assertRaisesRegexp(self, expected_exception, expected_regexp,
callable_obj=None, *args, **kwargs):
'''Asserts that the message in a raised exception matches a regexp.'''
context = _AssertRaisesContext(expected_exception, self,
expected_regexp)
if callable_obj is None:
return context
with context:
callable_obj(*args, **kwargs)
@decorators.validation_function
def is_response(candidate):
pass | unknown | codeparrot/codeparrot-clean | ||
# $Id: af.py 7119 2011-09-02 13:00:23Z milde $
# Author: Jannie Hofmeyr <jhsh@sun.ac.za>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
Afrikaans-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
'aandag': 'attention',
'versigtig': 'caution',
'code (translation required)': 'code',
'gevaar': 'danger',
'fout': 'error',
'wenk': 'hint',
'belangrik': 'important',
'nota': 'note',
'tip': 'tip', # hint and tip both have the same translation: wenk
'waarskuwing': 'warning',
'vermaning': 'admonition',
'kantstreep': 'sidebar',
'onderwerp': 'topic',
'lynblok': 'line-block',
'math (translation required)': 'math',
'parsed-literal (translation required)': 'parsed-literal',
'rubriek': 'rubric',
'epigraaf': 'epigraph',
'hoogtepunte': 'highlights',
'pull-quote (translation required)': 'pull-quote',
u'compound (translation required)': 'compound',
u'container (translation required)': 'container',
#'vrae': 'questions',
#'qa': 'questions',
#'faq': 'questions',
'table (translation required)': 'table',
'csv-table (translation required)': 'csv-table',
'list-table (translation required)': 'list-table',
'meta': 'meta',
#'beeldkaart': 'imagemap',
'beeld': 'image',
'figuur': 'figure',
'insluiting': 'include',
'rou': 'raw',
'vervang': 'replace',
'unicode': 'unicode', # should this be translated? unikode
'datum': 'date',
'klas': 'class',
'role (translation required)': 'role',
'default-role (translation required)': 'default-role',
'title (translation required)': 'title',
'inhoud': 'contents',
'sectnum': 'sectnum',
'section-numbering': 'sectnum',
u'header (translation required)': 'header',
u'footer (translation required)': 'footer',
#'voetnote': 'footnotes',
#'aanhalings': 'citations',
'teikennotas': 'target-notes',
'restructuredtext-test-directive': 'restructuredtext-test-directive'}
"""Afrikaans name to registered (in directives/__init__.py) directive name
mapping."""
roles = {
'afkorting': 'abbreviation',
'ab': 'abbreviation',
'akroniem': 'acronym',
'ac': 'acronym',
u'code (translation required)': 'code',
'indeks': 'index',
'i': 'index',
'voetskrif': 'subscript',
'sub': 'subscript',
'boskrif': 'superscript',
'sup': 'superscript',
'titelverwysing': 'title-reference',
'titel': 'title-reference',
't': 'title-reference',
'pep-verwysing': 'pep-reference',
'pep': 'pep-reference',
'rfc-verwysing': 'rfc-reference',
'rfc': 'rfc-reference',
'nadruk': 'emphasis',
'sterk': 'strong',
'literal (translation required)': 'literal',
'math (translation required)': 'math',
'benoemde verwysing': 'named-reference',
'anonieme verwysing': 'anonymous-reference',
'voetnootverwysing': 'footnote-reference',
'aanhalingverwysing': 'citation-reference',
'vervangingsverwysing': 'substitution-reference',
'teiken': 'target',
'uri-verwysing': 'uri-reference',
'uri': 'uri-reference',
'url': 'uri-reference',
'rou': 'raw',}
"""Mapping of Afrikaans role names to canonical role names for interpreted text.
""" | unknown | codeparrot/codeparrot-clean | ||
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from django import shortcuts
from django.contrib import messages
from django.core import validators
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import api
from horizon import exceptions
from horizon import forms
LOG = logging.getLogger(__name__)
no_slash_validator = validators.RegexValidator(r'^(?u)[^/]+$',
_("Slash is not an allowed "
"character."),
code="noslash")
class CreateContainer(forms.SelfHandlingForm):
parent = forms.CharField(max_length=255,
required=False,
widget=forms.HiddenInput)
name = forms.CharField(max_length=255,
label=_("Container Name"),
validators=[no_slash_validator])
def handle(self, request, data):
try:
if not data['parent']:
# Create a container
api.swift_create_container(request, data["name"])
messages.success(request, _("Container created successfully."))
else:
# Create a pseudo-folder
container, slash, remainder = data['parent'].partition("/")
remainder = remainder.rstrip("/")
subfolder_name = "/".join([bit for bit
in (remainder, data['name'])
if bit])
api.swift_create_subfolder(request,
container,
subfolder_name)
messages.success(request, _("Folder created successfully."))
url = "horizon:nova:containers:object_index"
if remainder:
remainder = remainder.rstrip("/")
remainder += "/"
return shortcuts.redirect(url, container, remainder)
except:
exceptions.handle(request, _('Unable to create container.'))
return shortcuts.redirect("horizon:nova:containers:index")
class UploadObject(forms.SelfHandlingForm):
path = forms.CharField(max_length=255,
required=False,
widget=forms.HiddenInput)
name = forms.CharField(max_length=255,
label=_("Object Name"),
validators=[no_slash_validator])
object_file = forms.FileField(label=_("File"))
container_name = forms.CharField(widget=forms.HiddenInput())
def handle(self, request, data):
object_file = self.files['object_file']
if data['path']:
object_path = "/".join([data['path'].rstrip("/"), data['name']])
else:
object_path = data['name']
try:
obj = api.swift_upload_object(request,
data['container_name'],
object_path,
object_file)
obj.metadata['orig-filename'] = object_file.name
obj.sync_metadata()
messages.success(request, _("Object was successfully uploaded."))
except:
exceptions.handle(request, _("Unable to upload object."))
return shortcuts.redirect("horizon:nova:containers:object_index",
data['container_name'], data['path'])
class CopyObject(forms.SelfHandlingForm):
new_container_name = forms.ChoiceField(label=_("Destination container"),
validators=[no_slash_validator])
path = forms.CharField(max_length=255, required=False)
new_object_name = forms.CharField(max_length=255,
label=_("Destination object name"),
validators=[no_slash_validator])
orig_container_name = forms.CharField(widget=forms.HiddenInput())
orig_object_name = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
containers = kwargs.pop('containers')
super(CopyObject, self).__init__(*args, **kwargs)
self.fields['new_container_name'].choices = containers
def handle(self, request, data):
object_index = "horizon:nova:containers:object_index"
orig_container = data['orig_container_name']
orig_object = data['orig_object_name']
new_container = data['new_container_name']
new_object = data['new_object_name']
new_path = "%s%s" % (data['path'], new_object)
# Iteratively make sure all the directory markers exist.
if data['path']:
path_component = ""
for bit in data['path'].split("/"):
path_component += bit
try:
api.swift.swift_create_subfolder(request,
new_container,
path_component)
except:
redirect = reverse(object_index, args=(orig_container,))
exceptions.handle(request,
_("Unable to copy object."),
redirect=redirect)
path_component += "/"
# Now copy the object itself.
try:
api.swift_copy_object(request,
orig_container,
orig_object,
new_container,
new_path)
dest = "%s/%s" % (new_container, data['path'])
vals = {"dest": dest.rstrip("/"),
"orig": orig_object.split("/")[-1],
"new": new_object}
messages.success(request,
_('Copied "%(orig)s" to "%(dest)s" as "%(new)s".')
% vals)
except exceptions.HorizonException, exc:
messages.error(request, exc)
return shortcuts.redirect(object_index, orig_container)
except:
redirect = reverse(object_index, args=(orig_container,))
exceptions.handle(request,
_("Unable to copy object."),
redirect=redirect)
return shortcuts.redirect(object_index, new_container, data['path']) | unknown | codeparrot/codeparrot-clean | ||
/*-------------------------------------------------------------------------
*
* extendplan.c
* Extend core planner objects with additional private state
*
* Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
* Portions Copyright (c) 1994-5, Regents of the University of California
*
* The interfaces defined in this file make it possible for loadable
* modules to store their own private state inside of key planner data
* structures -- specifically, the PlannerGlobal, PlannerInfo, and
* RelOptInfo structures. This can make it much easier to write
* reasonably efficient planner extensions; for instance, code that
* uses set_join_pathlist_hook can arrange to compute a key intermediate
* result once per joinrel rather than on every call.
*
* IDENTIFICATION
* src/backend/optimizer/util/extendplan.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "optimizer/extendplan.h"
#include "port/pg_bitutils.h"
#include "utils/memutils.h"
static const char **PlannerExtensionNameArray = NULL;
static int PlannerExtensionNamesAssigned = 0;
static int PlannerExtensionNamesAllocated = 0;
/*
* Map the name of a planner extension to an integer ID.
*
* Within the lifetime of a particular backend, the same name will be mapped
* to the same ID every time. IDs are not stable across backends. Use the ID
* that you get from this function to call the remaining functions in this
* file.
*/
int
GetPlannerExtensionId(const char *extension_name)
{
/* Search for an existing extension by this name; if found, return ID. */
for (int i = 0; i < PlannerExtensionNamesAssigned; ++i)
if (strcmp(PlannerExtensionNameArray[i], extension_name) == 0)
return i;
/* If there is no array yet, create one. */
if (PlannerExtensionNameArray == NULL)
{
PlannerExtensionNamesAllocated = 16;
PlannerExtensionNameArray = (const char **)
MemoryContextAlloc(TopMemoryContext,
PlannerExtensionNamesAllocated
* sizeof(char *));
}
/* If there's an array but it's currently full, expand it. */
if (PlannerExtensionNamesAssigned >= PlannerExtensionNamesAllocated)
{
int i = pg_nextpower2_32(PlannerExtensionNamesAssigned + 1);
PlannerExtensionNameArray = (const char **)
repalloc(PlannerExtensionNameArray, i * sizeof(char *));
PlannerExtensionNamesAllocated = i;
}
/* Assign and return new ID. */
PlannerExtensionNameArray[PlannerExtensionNamesAssigned] = extension_name;
return PlannerExtensionNamesAssigned++;
}
/*
* Store extension-specific state into a PlannerGlobal.
*/
void
SetPlannerGlobalExtensionState(PlannerGlobal *glob, int extension_id,
void *opaque)
{
Assert(extension_id >= 0);
/* If there is no array yet, create one. */
if (glob->extension_state == NULL)
{
MemoryContext planner_cxt;
Size sz;
planner_cxt = GetMemoryChunkContext(glob);
glob->extension_state_allocated =
Max(4, pg_nextpower2_32(extension_id + 1));
sz = glob->extension_state_allocated * sizeof(void *);
glob->extension_state = MemoryContextAllocZero(planner_cxt, sz);
}
/* If there's an array but it's currently full, expand it. */
if (extension_id >= glob->extension_state_allocated)
{
int i;
i = pg_nextpower2_32(extension_id + 1);
glob->extension_state = repalloc0_array(glob->extension_state, void *,
glob->extension_state_allocated, i);
glob->extension_state_allocated = i;
}
glob->extension_state[extension_id] = opaque;
}
/*
* Store extension-specific state into a PlannerInfo.
*/
void
SetPlannerInfoExtensionState(PlannerInfo *root, int extension_id,
void *opaque)
{
Assert(extension_id >= 0);
/* If there is no array yet, create one. */
if (root->extension_state == NULL)
{
Size sz;
root->extension_state_allocated =
Max(4, pg_nextpower2_32(extension_id + 1));
sz = root->extension_state_allocated * sizeof(void *);
root->extension_state = MemoryContextAllocZero(root->planner_cxt, sz);
}
/* If there's an array but it's currently full, expand it. */
if (extension_id >= root->extension_state_allocated)
{
int i;
i = pg_nextpower2_32(extension_id + 1);
root->extension_state = repalloc0_array(root->extension_state, void *,
root->extension_state_allocated, i);
root->extension_state_allocated = i;
}
root->extension_state[extension_id] = opaque;
}
/*
* Store extension-specific state into a RelOptInfo.
*/
void
SetRelOptInfoExtensionState(RelOptInfo *rel, int extension_id,
void *opaque)
{
Assert(extension_id >= 0);
/* If there is no array yet, create one. */
if (rel->extension_state == NULL)
{
MemoryContext planner_cxt;
Size sz;
planner_cxt = GetMemoryChunkContext(rel);
rel->extension_state_allocated =
Max(4, pg_nextpower2_32(extension_id + 1));
sz = rel->extension_state_allocated * sizeof(void *);
rel->extension_state = MemoryContextAllocZero(planner_cxt, sz);
}
/* If there's an array but it's currently full, expand it. */
if (extension_id >= rel->extension_state_allocated)
{
int i;
i = pg_nextpower2_32(extension_id + 1);
rel->extension_state = repalloc0_array(rel->extension_state, void *,
rel->extension_state_allocated, i);
rel->extension_state_allocated = i;
}
rel->extension_state[extension_id] = opaque;
} | c | github | https://github.com/postgres/postgres | src/backend/optimizer/util/extendplan.c |
#!/usr/bin/python3
import sys
sys.path.append('..')
from utils import *
from random import random
class Sampler:
def __init__(self):
self.debug = False
self.min_tags = 16
self.goal_samples_per_score = 20000
self.all_stats = load_obj(booru_path("pickle_files/statistics"))
self.all_duplicates = load_obj(booru_path("pickle_files/duplicates"))
def process_row(self, row):
# don't sample duplicates
is_dupe = self.all_duplicates[row["id"]]
if is_dupe:
if self.debug:
print("rejecting duplicate")
return False
# don't sample images with only a few tags
if len(row["tags"]) < self.min_tags:
if self.debug:
print("Reject: {} is not enough tags (min: {})".format(len(row["tags"]), self.min_tags))
return False
# definitely sample images with uncommon scores (very high or very low)
score = row["score"]
if self.all_stats["times_score_occurred"][score] < self.goal_samples_per_score:
if self.debug:
print("Accept: score of {} happens infrequently".format(row["score"]))
return True
# use stratified sampling across rest of scores
if (score == 0 and random() < self.goal_samples_per_score/self.all_stats["times_score_occurred"][score]):
if self.debug:
print("Accept: using stratified sampling on score of {}".format(row["score"]))
return True
return False | unknown | codeparrot/codeparrot-clean | ||
"""Module for testing string variables."""
class TestStringVar(BaseTestCase):
def setUp(self):
BaseTestCase.setUp(self)
self.rawData = []
self.dataByKey = {}
for i in range(1, 11):
stringCol = "String %d" % i
fixedCharCol = ("Fixed Char %d" % i).ljust(40)
rawCol = "Raw %d" % i
if i % 2:
nullableCol = "Nullable %d" % i
else:
nullableCol = None
dataTuple = (i, stringCol, rawCol, fixedCharCol, nullableCol)
self.rawData.append(dataTuple)
self.dataByKey[i] = dataTuple
def testBindString(self):
"test binding in a string"
self.cursor.execute("""
select * from TestStrings
where StringCol = :p_Value""",
p_Value = "String 5")
self.failUnlessEqual(self.cursor.fetchall(), [self.dataByKey[5]])
def testBindDifferentVar(self):
"test binding a different variable on second execution"
retval_1 = self.cursor.var(cx_Oracle.STRING, 30)
retval_2 = self.cursor.var(cx_Oracle.STRING, 30)
self.cursor.execute("begin :retval := 'Called'; end;",
retval = retval_1)
self.failUnlessEqual(retval_1.getvalue(), "Called")
self.cursor.execute("begin :retval := 'Called'; end;",
retval = retval_2)
self.failUnlessEqual(retval_2.getvalue(), "Called")
def testBindStringAfterNumber(self):
"test binding in a string after setting input sizes to a number"
self.cursor.setinputsizes(p_Value = cx_Oracle.NUMBER)
self.cursor.execute("""
select * from TestStrings
where StringCol = :p_Value""",
p_Value = "String 6")
self.failUnlessEqual(self.cursor.fetchall(), [self.dataByKey[6]])
def testBindStringArrayDirect(self):
"test binding in a string array"
returnValue = self.cursor.var(cx_Oracle.NUMBER)
array = [r[1] for r in self.rawData]
statement = """
begin
:p_ReturnValue := pkg_TestStringArrays.TestInArrays(
:p_IntegerValue, :p_Array);
end;"""
self.cursor.execute(statement,
p_ReturnValue = returnValue,
p_IntegerValue = 5,
p_Array = array)
self.failUnlessEqual(returnValue.getvalue(), 86)
array = [ "String - %d" % i for i in range(15) ]
self.cursor.execute(statement,
p_IntegerValue = 8,
p_Array = array)
self.failUnlessEqual(returnValue.getvalue(), 163)
def testBindStringArrayBySizes(self):
"test binding in a string array (with setinputsizes)"
returnValue = self.cursor.var(cx_Oracle.NUMBER)
self.cursor.setinputsizes(p_Array = [cx_Oracle.STRING, 10])
array = [r[1] for r in self.rawData]
self.cursor.execute("""
begin
:p_ReturnValue := pkg_TestStringArrays.TestInArrays(
:p_IntegerValue, :p_Array);
end;""",
p_ReturnValue = returnValue,
p_IntegerValue = 6,
p_Array = array)
self.failUnlessEqual(returnValue.getvalue(), 87)
def testBindStringArrayByVar(self):
"test binding in a string array (with arrayvar)"
returnValue = self.cursor.var(cx_Oracle.NUMBER)
array = self.cursor.arrayvar(cx_Oracle.STRING, 10, 20)
array.setvalue(0, [r[1] for r in self.rawData])
self.cursor.execute("""
begin
:p_ReturnValue := pkg_TestStringArrays.TestInArrays(
:p_IntegerValue, :p_Array);
end;""",
p_ReturnValue = returnValue,
p_IntegerValue = 7,
p_Array = array)
self.failUnlessEqual(returnValue.getvalue(), 88)
def testBindInOutStringArrayByVar(self):
"test binding in/out a string array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.STRING, 10, 100)
originalData = [r[1] for r in self.rawData]
expectedData = ["Converted element # %d originally had length %d" % \
(i, len(originalData[i - 1])) for i in range(1, 6)] + \
originalData[5:]
array.setvalue(0, originalData)
self.cursor.execute("""
begin
pkg_TestStringArrays.TestInOutArrays(:p_NumElems, :p_Array);
end;""",
p_NumElems = 5,
p_Array = array)
self.failUnlessEqual(array.getvalue(), expectedData)
def testBindOutStringArrayByVar(self):
"test binding out a string array (with arrayvar)"
array = self.cursor.arrayvar(cx_Oracle.STRING, 6, 100)
expectedData = ["Test out element # %d" % i for i in range(1, 7)]
self.cursor.execute("""
begin
pkg_TestStringArrays.TestOutArrays(:p_NumElems, :p_Array);
end;""",
p_NumElems = 6,
p_Array = array)
self.failUnlessEqual(array.getvalue(), expectedData)
def testBindRaw(self):
"test binding in a raw"
self.cursor.setinputsizes(p_Value = cx_Oracle.BINARY)
self.cursor.execute("""
select * from TestStrings
where RawCol = :p_Value""",
p_Value = "Raw 4")
self.failUnlessEqual(self.cursor.fetchall(), [self.dataByKey[4]])
def testBindAndFetchRowid(self):
"test binding (and fetching) a rowid"
self.cursor.execute("""
select rowid
from TestStrings
where IntCol = 3""")
rowid, = self.cursor.fetchone()
self.cursor.execute("""
select *
from TestStrings
where rowid = :p_Value""",
p_Value = rowid)
self.failUnlessEqual(self.cursor.fetchall(), [self.dataByKey[3]])
def testBindNull(self):
"test binding in a null"
self.cursor.execute("""
select * from TestStrings
where StringCol = :p_Value""",
p_Value = None)
self.failUnlessEqual(self.cursor.fetchall(), [])
def testBindOutSetInputSizesByType(self):
"test binding out with set input sizes defined (by type)"
vars = self.cursor.setinputsizes(p_Value = cx_Oracle.STRING)
self.cursor.execute("""
begin
:p_Value := 'TSI';
end;""")
self.failUnlessEqual(vars["p_Value"].getvalue(), "TSI")
def testBindOutSetInputSizesByInteger(self):
"test binding out with set input sizes defined (by integer)"
vars = self.cursor.setinputsizes(p_Value = 30)
self.cursor.execute("""
begin
:p_Value := 'TSI (I)';
end;""")
self.failUnlessEqual(vars["p_Value"].getvalue(), "TSI (I)")
def testBindInOutSetInputSizesByType(self):
"test binding in/out with set input sizes defined (by type)"
vars = self.cursor.setinputsizes(p_Value = cx_Oracle.STRING)
self.cursor.execute("""
begin
:p_Value := :p_Value || ' TSI';
end;""",
p_Value = "InVal")
self.failUnlessEqual(vars["p_Value"].getvalue(), "InVal TSI")
def testBindInOutSetInputSizesByInteger(self):
"test binding in/out with set input sizes defined (by integer)"
vars = self.cursor.setinputsizes(p_Value = 30)
self.cursor.execute("""
begin
:p_Value := :p_Value || ' TSI (I)';
end;""",
p_Value = "InVal")
self.failUnlessEqual(vars["p_Value"].getvalue(), "InVal TSI (I)")
def testBindOutVar(self):
"test binding out with cursor.var() method"
var = self.cursor.var(cx_Oracle.STRING)
self.cursor.execute("""
begin
:p_Value := 'TSI (VAR)';
end;""",
p_Value = var)
self.failUnlessEqual(var.getvalue(), "TSI (VAR)")
def testBindInOutVarDirectSet(self):
"test binding in/out with cursor.var() method"
var = self.cursor.var(cx_Oracle.STRING)
var.setvalue(0, "InVal")
self.cursor.execute("""
begin
:p_Value := :p_Value || ' TSI (VAR)';
end;""",
p_Value = var)
self.failUnlessEqual(var.getvalue(), "InVal TSI (VAR)")
def testBindLongString(self):
"test that binding a long string succeeds"
self.cursor.execute("""
declare
t_Temp varchar2(10000);
begin
t_Temp := :bigString;
end;""",
bigString = "X" * 10000)
def testBindLongStringAfterSettingSize(self):
"test that setinputsizes() returns a long variable"
var = self.cursor.setinputsizes(test = 90000)["test"]
self.failUnlessEqual(type(var), cx_Oracle.LONG_STRING)
inString = "1234567890" * 9000
var.setvalue(0, inString)
outString = var.getvalue()
self.failUnlessEqual(inString, outString,
"output does not match: in was %d, out was %d" % \
(len(inString), len(outString)))
def testStringMaximumReached(self):
"test that an error is raised when maximum string length exceeded"
var = self.cursor.setinputsizes(test = 100)["test"]
inString = "1234567890" * 400
var.setvalue(0, inString)
outString = var.getvalue()
self.failUnlessEqual(inString, outString,
"output does not match: in was %d, out was %d" % \
(len(inString), len(outString)))
badStringSize = 4000 * self.connection.maxBytesPerCharacter + 1
inString = "X" * badStringSize
self.failUnlessRaises(ValueError, var.setvalue, 0, inString)
def testCursorDescription(self):
"test cursor description is accurate"
self.cursor.execute("select * from TestStrings")
self.failUnlessEqual(self.cursor.description,
[ ('INTCOL', cx_Oracle.NUMBER, 10, 22, 9, 0, 0),
('STRINGCOL', cx_Oracle.STRING, 20, 20, 0, 0, 0),
('RAWCOL', cx_Oracle.BINARY, 30, 30, 0, 0, 0),
('FIXEDCHARCOL', cx_Oracle.FIXED_CHAR, 40, 40, 0, 0, 0),
('NULLABLECOL', cx_Oracle.STRING, 50, 50, 0, 0, 1) ])
def testFetchAll(self):
"test that fetching all of the data returns the correct results"
self.cursor.execute("select * From TestStrings order by IntCol")
self.failUnlessEqual(self.cursor.fetchall(), self.rawData)
self.failUnlessEqual(self.cursor.fetchall(), [])
def testFetchMany(self):
"test that fetching data in chunks returns the correct results"
self.cursor.execute("select * From TestStrings order by IntCol")
self.failUnlessEqual(self.cursor.fetchmany(3), self.rawData[0:3])
self.failUnlessEqual(self.cursor.fetchmany(2), self.rawData[3:5])
self.failUnlessEqual(self.cursor.fetchmany(4), self.rawData[5:9])
self.failUnlessEqual(self.cursor.fetchmany(3), self.rawData[9:])
self.failUnlessEqual(self.cursor.fetchmany(3), [])
def testFetchOne(self):
"test that fetching a single row returns the correct results"
self.cursor.execute("""
select *
from TestStrings
where IntCol in (3, 4)
order by IntCol""")
self.failUnlessEqual(self.cursor.fetchone(), self.dataByKey[3])
self.failUnlessEqual(self.cursor.fetchone(), self.dataByKey[4])
self.failUnlessEqual(self.cursor.fetchone(), None) | unknown | codeparrot/codeparrot-clean | ||
import numpy as np
from impyute.ops import matrix
from impyute.ops import wrapper
# pylint: disable=invalid-name, too-many-arguments, too-many-locals, too-many-branches, broad-except, len-as-condition
@wrapper.wrappers
@wrapper.checks
def moving_window(data, nindex=None, wsize=5, errors="coerce", func=np.mean,
inplace=False):
""" Interpolate the missing values based on nearby values.
For example, with an array like this:
array([[-1.24940, -1.38673, -0.03214945, 0.08255145, -0.007415],
[ 2.14662, 0.32758 , -0.82601414, 1.78124027, 0.873998],
[-0.41400, -0.977629, nan, -1.39255344, 1.680435],
[ 0.40975, 1.067599, 0.29152388, -1.70160145, -0.565226],
[-0.54592, -1.126187, 2.04004377, 0.16664863, -0.010677]])
Using a `k` or window size of 3. The one missing value would be set
to -1.18509122. The window operates on the horizontal axis.
Usage
-----
The parameters default the function to a moving mean. You may want to change
the default window size:
moving_window(data, wsize=10)
To only look at past data (null value is at the rightmost index in the window):
moving_window(data, nindex=-1)
To use a custom function:
moving_window(data, func=np.median)
You can also do something like take 1.5x the max of previous values in the window:
moving_window(data, func=lambda arr: max(arr) * 1.50, nindex=-1)
Parameters
----------
data: numpy.ndarray
2D matrix to impute.
nindex: int
Null index. Index of the null value inside the moving average window.
Use cases: Say you wanted to make value skewed toward the left or right
side. 0 would only take the average of values from the right and -1
would only take the average of values from the left
wsize: int
Window size. Size of the moving average window/area of values being used
for each local imputation. This number includes the missing value.
errors: {"raise", "coerce", "ignore"}
Errors will occur with the indexing of the windows - for example if there
is a nan at data[x][0] and `nindex` is set to -1 or there is a nan at
data[x][-1] and `nindex` is set to 0. `"raise"` will raise an error,
`"coerce"` will try again using an nindex set to the middle and `"ignore"`
will just leave it as a nan.
inplace: {True, False}
Whether to return a copy or run on the passed-in array
Returns
-------
numpy.ndarray
Imputed data.
"""
if errors == "ignore":
raise Exception("`errors` value `ignore` not implemented yet. Sorry!")
if not inplace:
data = data.copy()
if nindex is None: # If using equal window side lengths
assert wsize % 2 == 1, "The parameter `wsize` should not be even "\
"if the value `nindex` is not set since it defaults to the midpoint "\
"and an even `wsize` makes the midpoint ambiguous"
wside_left = wsize // 2
wside_right = wsize // 2
else: # If using custom window side lengths
assert nindex < wsize, "The null index must be smaller than the window size"
if nindex == -1:
wside_left = wsize - 1
wside_right = 0
else:
wside_left = nindex
wside_right = wsize - nindex - 1
while True:
nan_xy = matrix.nan_indices(data)
n_nan_prev = len(nan_xy)
for x_i, y_i in nan_xy:
left_i = max(0, y_i-wside_left)
right_i = min(len(data), y_i+wside_right+1)
window = data[x_i, left_i: right_i]
window_not_null = window[~np.isnan(window)]
if len(window_not_null) > 0:
try:
data[x_i][y_i] = func(window_not_null)
continue
except Exception as e:
if errors == "raise":
raise e
if errors == "coerce":
# If either the window has a length of 0 or the aggregate function fails somehow,
# do a fallback of just trying the best we can by using it as the middle and trying
# to recalculate. Use temporary wside_left/wside_right, for only the calculation of
# this specific problamatic value
wside_left_tmp = wsize // 2
wside_right_tmp = wside_left_tmp
left_i_tmp = max(0, y_i-wside_left_tmp)
right_i_tmp = min(len(data), y_i+wside_right_tmp+1)
window = data[x_i, left_i_tmp:right_i_tmp]
window_not_null = window[~np.isnan(window)]
try:
data[x_i][y_i] = func(window_not_null)
except Exception as e:
print("Exception:", e)
if n_nan_prev == len(matrix.nan_indices(data)):
break
return data | unknown | codeparrot/codeparrot-clean | ||
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
]; | php | github | https://github.com/laravel/framework | config-stubs/app.php |
import unittest
from yesaide import worker
class FakeDbSession(object):
def __init__(self):
self.has_been_committed = False
def commit(self):
self.has_been_committed = True
class FakeForeman(object):
def __init__(self):
self._dbsession = FakeDbSession()
class FakeMapping(object):
a_prop = 12
a_req_prop = "bla"
class BaseTestWorker(unittest.TestCase):
def setUp(self):
self.dbsession = FakeDbSession()
def tearDown(self):
del self.dbsession
class TestRawWorker(BaseTestWorker):
def test_init(self):
worker.RawWorker(self.dbsession)
class TestSupervisedWorker(BaseTestWorker):
def test_init(self):
foreman = FakeForeman()
supervised_worker = worker.SupervisedWorker(foreman)
self.assertEqual(supervised_worker._foreman, foreman)
supervised_worker = worker.SupervisedWorker(foreman, "_for")
self.assertEqual(supervised_worker._for, foreman)
class TestObjectManagingWorker(BaseTestWorker):
def test_init(self):
foreman = FakeForeman()
worker.MappingManagingWorker(
foreman, managed_sqla_map=FakeMapping, managed_sqla_map_name="fake"
)
def test__get(self):
foreman = FakeForeman()
a_worker = worker.MappingManagingWorker(
foreman, managed_sqla_map=FakeMapping, managed_sqla_map_name="fake"
)
a_worker._get(sqla_obj=FakeMapping()) | unknown | codeparrot/codeparrot-clean | ||
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import parse_iso8601
class NYTimesIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?nytimes\.com/video/(?:[^/]+/)+(?P<id>\d+)'
_TEST = {
'url': 'http://www.nytimes.com/video/opinion/100000002847155/verbatim-what-is-a-photocopier.html?playlistId=100000001150263',
'md5': '18a525a510f942ada2720db5f31644c0',
'info_dict': {
'id': '100000002847155',
'ext': 'mov',
'title': 'Verbatim: What Is a Photocopier?',
'description': 'md5:93603dada88ddbda9395632fdc5da260',
'timestamp': 1398631707,
'upload_date': '20140427',
'uploader': 'Brett Weiner',
'duration': 419,
}
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
video_data = self._download_json(
'http://www.nytimes.com/svc/video/api/v2/video/%s' % video_id, video_id, 'Downloading video JSON')
title = video_data['headline']
description = video_data['summary']
duration = video_data['duration'] / 1000.0
uploader = video_data['byline']
timestamp = parse_iso8601(video_data['publication_date'][:-8])
def get_file_size(file_size):
if isinstance(file_size, int):
return file_size
elif isinstance(file_size, dict):
return int(file_size.get('value', 0))
else:
return 0
formats = [
{
'url': video['url'],
'format_id': video['type'],
'vcodec': video['video_codec'],
'width': video['width'],
'height': video['height'],
'filesize': get_file_size(video['fileSize']),
} for video in video_data['renditions']
]
self._sort_formats(formats)
thumbnails = [
{
'url': 'http://www.nytimes.com/%s' % image['url'],
'resolution': '%dx%d' % (image['width'], image['height']),
} for image in video_data['images']
]
return {
'id': video_id,
'title': title,
'description': description,
'timestamp': timestamp,
'uploader': uploader,
'duration': duration,
'formats': formats,
'thumbnails': thumbnails,
} | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Keras category crossing preprocessing layers."""
# pylint: disable=g-classes-have-attributes
import itertools
import numpy as np
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_spec
from tensorflow.python.keras.engine import base_layer
from tensorflow.python.keras.utils import tf_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import sparse_ops
from tensorflow.python.ops.ragged import ragged_array_ops
from tensorflow.python.ops.ragged import ragged_tensor
from tensorflow.python.util.tf_export import keras_export
@keras_export('keras.layers.experimental.preprocessing.CategoryCrossing')
class CategoryCrossing(base_layer.Layer):
"""Category crossing layer.
This layer concatenates multiple categorical inputs into a single categorical
output (similar to Cartesian product). The output dtype is string.
Usage:
>>> inp_1 = ['a', 'b', 'c']
>>> inp_2 = ['d', 'e', 'f']
>>> layer = tf.keras.layers.experimental.preprocessing.CategoryCrossing()
>>> layer([inp_1, inp_2])
<tf.Tensor: shape=(3, 1), dtype=string, numpy=
array([[b'a_X_d'],
[b'b_X_e'],
[b'c_X_f']], dtype=object)>
>>> inp_1 = ['a', 'b', 'c']
>>> inp_2 = ['d', 'e', 'f']
>>> layer = tf.keras.layers.experimental.preprocessing.CategoryCrossing(
... separator='-')
>>> layer([inp_1, inp_2])
<tf.Tensor: shape=(3, 1), dtype=string, numpy=
array([[b'a-d'],
[b'b-e'],
[b'c-f']], dtype=object)>
Args:
depth: depth of input crossing. By default None, all inputs are crossed into
one output. It can also be an int or tuple/list of ints. Passing an
integer will create combinations of crossed outputs with depth up to that
integer, i.e., [1, 2, ..., `depth`), and passing a tuple of integers will
create crossed outputs with depth for the specified values in the tuple,
i.e., `depth`=(N1, N2) will create all possible crossed outputs with depth
equal to N1 or N2. Passing `None` means a single crossed output with all
inputs. For example, with inputs `a`, `b` and `c`, `depth=2` means the
output will be [a;b;c;cross(a, b);cross(bc);cross(ca)].
separator: A string added between each input being joined. Defaults to
'_X_'.
name: Name to give to the layer.
**kwargs: Keyword arguments to construct a layer.
Input shape: a list of string or int tensors or sparse tensors of shape
`[batch_size, d1, ..., dm]`
Output shape: a single string or int tensor or sparse tensor of shape
`[batch_size, d1, ..., dm]`
Returns:
If any input is `RaggedTensor`, the output is `RaggedTensor`.
Else, if any input is `SparseTensor`, the output is `SparseTensor`.
Otherwise, the output is `Tensor`.
Example: (`depth`=None)
If the layer receives three inputs:
`a=[[1], [4]]`, `b=[[2], [5]]`, `c=[[3], [6]]`
the output will be a string tensor:
`[[b'1_X_2_X_3'], [b'4_X_5_X_6']]`
Example: (`depth` is an integer)
With the same input above, and if `depth`=2,
the output will be a list of 6 string tensors:
`[[b'1'], [b'4']]`
`[[b'2'], [b'5']]`
`[[b'3'], [b'6']]`
`[[b'1_X_2'], [b'4_X_5']]`,
`[[b'2_X_3'], [b'5_X_6']]`,
`[[b'3_X_1'], [b'6_X_4']]`
Example: (`depth` is a tuple/list of integers)
With the same input above, and if `depth`=(2, 3)
the output will be a list of 4 string tensors:
`[[b'1_X_2'], [b'4_X_5']]`,
`[[b'2_X_3'], [b'5_X_6']]`,
`[[b'3_X_1'], [b'6_X_4']]`,
`[[b'1_X_2_X_3'], [b'4_X_5_X_6']]`
"""
def __init__(self, depth=None, name=None, separator='_X_', **kwargs):
super(CategoryCrossing, self).__init__(name=name, **kwargs)
self.depth = depth
self.separator = separator
if isinstance(depth, (tuple, list)):
self._depth_tuple = depth
elif depth is not None:
self._depth_tuple = tuple([i for i in range(1, depth + 1)])
def partial_crossing(self, partial_inputs, ragged_out, sparse_out):
"""Gets the crossed output from a partial list/tuple of inputs."""
# If ragged_out=True, convert output from sparse to ragged.
if ragged_out:
# TODO(momernick): Support separator with ragged_cross.
if self.separator != '_X_':
raise ValueError('Non-default separator with ragged input is not '
'supported yet, given {}'.format(self.separator))
return ragged_array_ops.cross(partial_inputs)
elif sparse_out:
return sparse_ops.sparse_cross(partial_inputs, separator=self.separator)
else:
return sparse_ops.sparse_tensor_to_dense(
sparse_ops.sparse_cross(partial_inputs, separator=self.separator))
def _preprocess_input(self, inp):
if isinstance(inp, (list, tuple, np.ndarray)):
inp = ops.convert_to_tensor_v2_with_dispatch(inp)
if inp.shape.rank == 1:
inp = array_ops.expand_dims(inp, axis=-1)
return inp
def call(self, inputs):
inputs = [self._preprocess_input(inp) for inp in inputs]
depth_tuple = self._depth_tuple if self.depth else (len(inputs),)
ragged_out = sparse_out = False
if any(tf_utils.is_ragged(inp) for inp in inputs):
ragged_out = True
elif any(isinstance(inp, sparse_tensor.SparseTensor) for inp in inputs):
sparse_out = True
outputs = []
for depth in depth_tuple:
if len(inputs) < depth:
raise ValueError(
'Number of inputs cannot be less than depth, got {} input tensors, '
'and depth {}'.format(len(inputs), depth))
for partial_inps in itertools.combinations(inputs, depth):
partial_out = self.partial_crossing(
partial_inps, ragged_out, sparse_out)
outputs.append(partial_out)
if sparse_out:
return sparse_ops.sparse_concat_v2(axis=1, sp_inputs=outputs)
return array_ops.concat(outputs, axis=1)
def compute_output_shape(self, input_shape):
if not isinstance(input_shape, (tuple, list)):
raise ValueError('A `CategoryCrossing` layer should be called '
'on a list of inputs.')
input_shapes = input_shape
batch_size = None
for inp_shape in input_shapes:
inp_tensor_shape = tensor_shape.TensorShape(inp_shape).as_list()
if len(inp_tensor_shape) != 2:
raise ValueError('Inputs must be rank 2, get {}'.format(input_shapes))
if batch_size is None:
batch_size = inp_tensor_shape[0]
# The second dimension is dynamic based on inputs.
output_shape = [batch_size, None]
return tensor_shape.TensorShape(output_shape)
def compute_output_signature(self, input_spec):
input_shapes = [x.shape for x in input_spec]
output_shape = self.compute_output_shape(input_shapes)
if any(
isinstance(inp_spec, ragged_tensor.RaggedTensorSpec)
for inp_spec in input_spec):
return tensor_spec.TensorSpec(shape=output_shape, dtype=dtypes.string)
elif any(
isinstance(inp_spec, sparse_tensor.SparseTensorSpec)
for inp_spec in input_spec):
return sparse_tensor.SparseTensorSpec(
shape=output_shape, dtype=dtypes.string)
return tensor_spec.TensorSpec(shape=output_shape, dtype=dtypes.string)
def get_config(self):
config = {
'depth': self.depth,
'separator': self.separator,
}
base_config = super(CategoryCrossing, self).get_config()
return dict(list(base_config.items()) + list(config.items())) | unknown | codeparrot/codeparrot-clean | ||
//go:build !ignore_autogenerated
// +build !ignore_autogenerated
/*
Copyright The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Code generated by conversion-gen. DO NOT EDIT.
package v2
import (
unsafe "unsafe"
autoscalingv2 "k8s.io/api/autoscaling/v2"
v1 "k8s.io/api/core/v1"
resource "k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
conversion "k8s.io/apimachinery/pkg/conversion"
runtime "k8s.io/apimachinery/pkg/runtime"
autoscaling "k8s.io/kubernetes/pkg/apis/autoscaling"
core "k8s.io/kubernetes/pkg/apis/core"
)
func init() {
localSchemeBuilder.Register(RegisterConversions)
}
// RegisterConversions adds conversion functions to the given scheme.
// Public to allow building arbitrary schemes.
func RegisterConversions(s *runtime.Scheme) error {
if err := s.AddGeneratedConversionFunc((*autoscalingv2.ContainerResourceMetricSource)(nil), (*autoscaling.ContainerResourceMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(a.(*autoscalingv2.ContainerResourceMetricSource), b.(*autoscaling.ContainerResourceMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.ContainerResourceMetricSource)(nil), (*autoscalingv2.ContainerResourceMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_ContainerResourceMetricSource_To_v2_ContainerResourceMetricSource(a.(*autoscaling.ContainerResourceMetricSource), b.(*autoscalingv2.ContainerResourceMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.ContainerResourceMetricStatus)(nil), (*autoscaling.ContainerResourceMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(a.(*autoscalingv2.ContainerResourceMetricStatus), b.(*autoscaling.ContainerResourceMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.ContainerResourceMetricStatus)(nil), (*autoscalingv2.ContainerResourceMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_ContainerResourceMetricStatus_To_v2_ContainerResourceMetricStatus(a.(*autoscaling.ContainerResourceMetricStatus), b.(*autoscalingv2.ContainerResourceMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.CrossVersionObjectReference)(nil), (*autoscaling.CrossVersionObjectReference)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference(a.(*autoscalingv2.CrossVersionObjectReference), b.(*autoscaling.CrossVersionObjectReference), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.CrossVersionObjectReference)(nil), (*autoscalingv2.CrossVersionObjectReference)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_CrossVersionObjectReference_To_v2_CrossVersionObjectReference(a.(*autoscaling.CrossVersionObjectReference), b.(*autoscalingv2.CrossVersionObjectReference), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.ExternalMetricSource)(nil), (*autoscaling.ExternalMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_ExternalMetricSource_To_autoscaling_ExternalMetricSource(a.(*autoscalingv2.ExternalMetricSource), b.(*autoscaling.ExternalMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.ExternalMetricSource)(nil), (*autoscalingv2.ExternalMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_ExternalMetricSource_To_v2_ExternalMetricSource(a.(*autoscaling.ExternalMetricSource), b.(*autoscalingv2.ExternalMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.ExternalMetricStatus)(nil), (*autoscaling.ExternalMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus(a.(*autoscalingv2.ExternalMetricStatus), b.(*autoscaling.ExternalMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.ExternalMetricStatus)(nil), (*autoscalingv2.ExternalMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_ExternalMetricStatus_To_v2_ExternalMetricStatus(a.(*autoscaling.ExternalMetricStatus), b.(*autoscalingv2.ExternalMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.HPAScalingPolicy)(nil), (*autoscaling.HPAScalingPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_HPAScalingPolicy_To_autoscaling_HPAScalingPolicy(a.(*autoscalingv2.HPAScalingPolicy), b.(*autoscaling.HPAScalingPolicy), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.HPAScalingPolicy)(nil), (*autoscalingv2.HPAScalingPolicy)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_HPAScalingPolicy_To_v2_HPAScalingPolicy(a.(*autoscaling.HPAScalingPolicy), b.(*autoscalingv2.HPAScalingPolicy), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.HPAScalingRules)(nil), (*autoscaling.HPAScalingRules)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_HPAScalingRules_To_autoscaling_HPAScalingRules(a.(*autoscalingv2.HPAScalingRules), b.(*autoscaling.HPAScalingRules), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.HPAScalingRules)(nil), (*autoscalingv2.HPAScalingRules)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_HPAScalingRules_To_v2_HPAScalingRules(a.(*autoscaling.HPAScalingRules), b.(*autoscalingv2.HPAScalingRules), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.HorizontalPodAutoscalerBehavior)(nil), (*autoscaling.HorizontalPodAutoscalerBehavior)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_HorizontalPodAutoscalerBehavior_To_autoscaling_HorizontalPodAutoscalerBehavior(a.(*autoscalingv2.HorizontalPodAutoscalerBehavior), b.(*autoscaling.HorizontalPodAutoscalerBehavior), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.HorizontalPodAutoscalerBehavior)(nil), (*autoscalingv2.HorizontalPodAutoscalerBehavior)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_HorizontalPodAutoscalerBehavior_To_v2_HorizontalPodAutoscalerBehavior(a.(*autoscaling.HorizontalPodAutoscalerBehavior), b.(*autoscalingv2.HorizontalPodAutoscalerBehavior), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.HorizontalPodAutoscalerCondition)(nil), (*autoscaling.HorizontalPodAutoscalerCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_HorizontalPodAutoscalerCondition_To_autoscaling_HorizontalPodAutoscalerCondition(a.(*autoscalingv2.HorizontalPodAutoscalerCondition), b.(*autoscaling.HorizontalPodAutoscalerCondition), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.HorizontalPodAutoscalerCondition)(nil), (*autoscalingv2.HorizontalPodAutoscalerCondition)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_HorizontalPodAutoscalerCondition_To_v2_HorizontalPodAutoscalerCondition(a.(*autoscaling.HorizontalPodAutoscalerCondition), b.(*autoscalingv2.HorizontalPodAutoscalerCondition), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.HorizontalPodAutoscalerList)(nil), (*autoscaling.HorizontalPodAutoscalerList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_HorizontalPodAutoscalerList_To_autoscaling_HorizontalPodAutoscalerList(a.(*autoscalingv2.HorizontalPodAutoscalerList), b.(*autoscaling.HorizontalPodAutoscalerList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.HorizontalPodAutoscalerList)(nil), (*autoscalingv2.HorizontalPodAutoscalerList)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_HorizontalPodAutoscalerList_To_v2_HorizontalPodAutoscalerList(a.(*autoscaling.HorizontalPodAutoscalerList), b.(*autoscalingv2.HorizontalPodAutoscalerList), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.HorizontalPodAutoscalerSpec)(nil), (*autoscaling.HorizontalPodAutoscalerSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec(a.(*autoscalingv2.HorizontalPodAutoscalerSpec), b.(*autoscaling.HorizontalPodAutoscalerSpec), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.HorizontalPodAutoscalerSpec)(nil), (*autoscalingv2.HorizontalPodAutoscalerSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v2_HorizontalPodAutoscalerSpec(a.(*autoscaling.HorizontalPodAutoscalerSpec), b.(*autoscalingv2.HorizontalPodAutoscalerSpec), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.HorizontalPodAutoscalerStatus)(nil), (*autoscaling.HorizontalPodAutoscalerStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus(a.(*autoscalingv2.HorizontalPodAutoscalerStatus), b.(*autoscaling.HorizontalPodAutoscalerStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.HorizontalPodAutoscalerStatus)(nil), (*autoscalingv2.HorizontalPodAutoscalerStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_HorizontalPodAutoscalerStatus_To_v2_HorizontalPodAutoscalerStatus(a.(*autoscaling.HorizontalPodAutoscalerStatus), b.(*autoscalingv2.HorizontalPodAutoscalerStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.MetricIdentifier)(nil), (*autoscaling.MetricIdentifier)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(a.(*autoscalingv2.MetricIdentifier), b.(*autoscaling.MetricIdentifier), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.MetricIdentifier)(nil), (*autoscalingv2.MetricIdentifier)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(a.(*autoscaling.MetricIdentifier), b.(*autoscalingv2.MetricIdentifier), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.MetricSpec)(nil), (*autoscaling.MetricSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_MetricSpec_To_autoscaling_MetricSpec(a.(*autoscalingv2.MetricSpec), b.(*autoscaling.MetricSpec), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.MetricSpec)(nil), (*autoscalingv2.MetricSpec)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_MetricSpec_To_v2_MetricSpec(a.(*autoscaling.MetricSpec), b.(*autoscalingv2.MetricSpec), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.MetricStatus)(nil), (*autoscaling.MetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_MetricStatus_To_autoscaling_MetricStatus(a.(*autoscalingv2.MetricStatus), b.(*autoscaling.MetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.MetricStatus)(nil), (*autoscalingv2.MetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_MetricStatus_To_v2_MetricStatus(a.(*autoscaling.MetricStatus), b.(*autoscalingv2.MetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.MetricTarget)(nil), (*autoscaling.MetricTarget)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_MetricTarget_To_autoscaling_MetricTarget(a.(*autoscalingv2.MetricTarget), b.(*autoscaling.MetricTarget), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.MetricTarget)(nil), (*autoscalingv2.MetricTarget)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_MetricTarget_To_v2_MetricTarget(a.(*autoscaling.MetricTarget), b.(*autoscalingv2.MetricTarget), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.MetricValueStatus)(nil), (*autoscaling.MetricValueStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(a.(*autoscalingv2.MetricValueStatus), b.(*autoscaling.MetricValueStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.MetricValueStatus)(nil), (*autoscalingv2.MetricValueStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(a.(*autoscaling.MetricValueStatus), b.(*autoscalingv2.MetricValueStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.ObjectMetricSource)(nil), (*autoscaling.ObjectMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_ObjectMetricSource_To_autoscaling_ObjectMetricSource(a.(*autoscalingv2.ObjectMetricSource), b.(*autoscaling.ObjectMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.ObjectMetricSource)(nil), (*autoscalingv2.ObjectMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_ObjectMetricSource_To_v2_ObjectMetricSource(a.(*autoscaling.ObjectMetricSource), b.(*autoscalingv2.ObjectMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.ObjectMetricStatus)(nil), (*autoscaling.ObjectMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus(a.(*autoscalingv2.ObjectMetricStatus), b.(*autoscaling.ObjectMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.ObjectMetricStatus)(nil), (*autoscalingv2.ObjectMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_ObjectMetricStatus_To_v2_ObjectMetricStatus(a.(*autoscaling.ObjectMetricStatus), b.(*autoscalingv2.ObjectMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.PodsMetricSource)(nil), (*autoscaling.PodsMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_PodsMetricSource_To_autoscaling_PodsMetricSource(a.(*autoscalingv2.PodsMetricSource), b.(*autoscaling.PodsMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.PodsMetricSource)(nil), (*autoscalingv2.PodsMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_PodsMetricSource_To_v2_PodsMetricSource(a.(*autoscaling.PodsMetricSource), b.(*autoscalingv2.PodsMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.PodsMetricStatus)(nil), (*autoscaling.PodsMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_PodsMetricStatus_To_autoscaling_PodsMetricStatus(a.(*autoscalingv2.PodsMetricStatus), b.(*autoscaling.PodsMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.PodsMetricStatus)(nil), (*autoscalingv2.PodsMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_PodsMetricStatus_To_v2_PodsMetricStatus(a.(*autoscaling.PodsMetricStatus), b.(*autoscalingv2.PodsMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.ResourceMetricSource)(nil), (*autoscaling.ResourceMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_ResourceMetricSource_To_autoscaling_ResourceMetricSource(a.(*autoscalingv2.ResourceMetricSource), b.(*autoscaling.ResourceMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.ResourceMetricSource)(nil), (*autoscalingv2.ResourceMetricSource)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_ResourceMetricSource_To_v2_ResourceMetricSource(a.(*autoscaling.ResourceMetricSource), b.(*autoscalingv2.ResourceMetricSource), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscalingv2.ResourceMetricStatus)(nil), (*autoscaling.ResourceMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus(a.(*autoscalingv2.ResourceMetricStatus), b.(*autoscaling.ResourceMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddGeneratedConversionFunc((*autoscaling.ResourceMetricStatus)(nil), (*autoscalingv2.ResourceMetricStatus)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_ResourceMetricStatus_To_v2_ResourceMetricStatus(a.(*autoscaling.ResourceMetricStatus), b.(*autoscalingv2.ResourceMetricStatus), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*autoscaling.HorizontalPodAutoscaler)(nil), (*autoscalingv2.HorizontalPodAutoscaler)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_autoscaling_HorizontalPodAutoscaler_To_v2_HorizontalPodAutoscaler(a.(*autoscaling.HorizontalPodAutoscaler), b.(*autoscalingv2.HorizontalPodAutoscaler), scope)
}); err != nil {
return err
}
if err := s.AddConversionFunc((*autoscalingv2.HorizontalPodAutoscaler)(nil), (*autoscaling.HorizontalPodAutoscaler)(nil), func(a, b interface{}, scope conversion.Scope) error {
return Convert_v2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(a.(*autoscalingv2.HorizontalPodAutoscaler), b.(*autoscaling.HorizontalPodAutoscaler), scope)
}); err != nil {
return err
}
return nil
}
func autoConvert_v2_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(in *autoscalingv2.ContainerResourceMetricSource, out *autoscaling.ContainerResourceMetricSource, s conversion.Scope) error {
out.Name = core.ResourceName(in.Name)
if err := Convert_v2_MetricTarget_To_autoscaling_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
out.Container = in.Container
return nil
}
// Convert_v2_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource is an autogenerated conversion function.
func Convert_v2_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(in *autoscalingv2.ContainerResourceMetricSource, out *autoscaling.ContainerResourceMetricSource, s conversion.Scope) error {
return autoConvert_v2_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(in, out, s)
}
func autoConvert_autoscaling_ContainerResourceMetricSource_To_v2_ContainerResourceMetricSource(in *autoscaling.ContainerResourceMetricSource, out *autoscalingv2.ContainerResourceMetricSource, s conversion.Scope) error {
out.Name = v1.ResourceName(in.Name)
out.Container = in.Container
if err := Convert_autoscaling_MetricTarget_To_v2_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_ContainerResourceMetricSource_To_v2_ContainerResourceMetricSource is an autogenerated conversion function.
func Convert_autoscaling_ContainerResourceMetricSource_To_v2_ContainerResourceMetricSource(in *autoscaling.ContainerResourceMetricSource, out *autoscalingv2.ContainerResourceMetricSource, s conversion.Scope) error {
return autoConvert_autoscaling_ContainerResourceMetricSource_To_v2_ContainerResourceMetricSource(in, out, s)
}
func autoConvert_v2_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(in *autoscalingv2.ContainerResourceMetricStatus, out *autoscaling.ContainerResourceMetricStatus, s conversion.Scope) error {
out.Name = core.ResourceName(in.Name)
if err := Convert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
out.Container = in.Container
return nil
}
// Convert_v2_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus is an autogenerated conversion function.
func Convert_v2_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(in *autoscalingv2.ContainerResourceMetricStatus, out *autoscaling.ContainerResourceMetricStatus, s conversion.Scope) error {
return autoConvert_v2_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(in, out, s)
}
func autoConvert_autoscaling_ContainerResourceMetricStatus_To_v2_ContainerResourceMetricStatus(in *autoscaling.ContainerResourceMetricStatus, out *autoscalingv2.ContainerResourceMetricStatus, s conversion.Scope) error {
out.Name = v1.ResourceName(in.Name)
out.Container = in.Container
if err := Convert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_ContainerResourceMetricStatus_To_v2_ContainerResourceMetricStatus is an autogenerated conversion function.
func Convert_autoscaling_ContainerResourceMetricStatus_To_v2_ContainerResourceMetricStatus(in *autoscaling.ContainerResourceMetricStatus, out *autoscalingv2.ContainerResourceMetricStatus, s conversion.Scope) error {
return autoConvert_autoscaling_ContainerResourceMetricStatus_To_v2_ContainerResourceMetricStatus(in, out, s)
}
func autoConvert_v2_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference(in *autoscalingv2.CrossVersionObjectReference, out *autoscaling.CrossVersionObjectReference, s conversion.Scope) error {
out.Kind = in.Kind
out.Name = in.Name
out.APIVersion = in.APIVersion
return nil
}
// Convert_v2_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference is an autogenerated conversion function.
func Convert_v2_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference(in *autoscalingv2.CrossVersionObjectReference, out *autoscaling.CrossVersionObjectReference, s conversion.Scope) error {
return autoConvert_v2_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference(in, out, s)
}
func autoConvert_autoscaling_CrossVersionObjectReference_To_v2_CrossVersionObjectReference(in *autoscaling.CrossVersionObjectReference, out *autoscalingv2.CrossVersionObjectReference, s conversion.Scope) error {
out.Kind = in.Kind
out.Name = in.Name
out.APIVersion = in.APIVersion
return nil
}
// Convert_autoscaling_CrossVersionObjectReference_To_v2_CrossVersionObjectReference is an autogenerated conversion function.
func Convert_autoscaling_CrossVersionObjectReference_To_v2_CrossVersionObjectReference(in *autoscaling.CrossVersionObjectReference, out *autoscalingv2.CrossVersionObjectReference, s conversion.Scope) error {
return autoConvert_autoscaling_CrossVersionObjectReference_To_v2_CrossVersionObjectReference(in, out, s)
}
func autoConvert_v2_ExternalMetricSource_To_autoscaling_ExternalMetricSource(in *autoscalingv2.ExternalMetricSource, out *autoscaling.ExternalMetricSource, s conversion.Scope) error {
if err := Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_v2_MetricTarget_To_autoscaling_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
return nil
}
// Convert_v2_ExternalMetricSource_To_autoscaling_ExternalMetricSource is an autogenerated conversion function.
func Convert_v2_ExternalMetricSource_To_autoscaling_ExternalMetricSource(in *autoscalingv2.ExternalMetricSource, out *autoscaling.ExternalMetricSource, s conversion.Scope) error {
return autoConvert_v2_ExternalMetricSource_To_autoscaling_ExternalMetricSource(in, out, s)
}
func autoConvert_autoscaling_ExternalMetricSource_To_v2_ExternalMetricSource(in *autoscaling.ExternalMetricSource, out *autoscalingv2.ExternalMetricSource, s conversion.Scope) error {
if err := Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_autoscaling_MetricTarget_To_v2_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_ExternalMetricSource_To_v2_ExternalMetricSource is an autogenerated conversion function.
func Convert_autoscaling_ExternalMetricSource_To_v2_ExternalMetricSource(in *autoscaling.ExternalMetricSource, out *autoscalingv2.ExternalMetricSource, s conversion.Scope) error {
return autoConvert_autoscaling_ExternalMetricSource_To_v2_ExternalMetricSource(in, out, s)
}
func autoConvert_v2_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus(in *autoscalingv2.ExternalMetricStatus, out *autoscaling.ExternalMetricStatus, s conversion.Scope) error {
if err := Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
return nil
}
// Convert_v2_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus is an autogenerated conversion function.
func Convert_v2_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus(in *autoscalingv2.ExternalMetricStatus, out *autoscaling.ExternalMetricStatus, s conversion.Scope) error {
return autoConvert_v2_ExternalMetricStatus_To_autoscaling_ExternalMetricStatus(in, out, s)
}
func autoConvert_autoscaling_ExternalMetricStatus_To_v2_ExternalMetricStatus(in *autoscaling.ExternalMetricStatus, out *autoscalingv2.ExternalMetricStatus, s conversion.Scope) error {
if err := Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_ExternalMetricStatus_To_v2_ExternalMetricStatus is an autogenerated conversion function.
func Convert_autoscaling_ExternalMetricStatus_To_v2_ExternalMetricStatus(in *autoscaling.ExternalMetricStatus, out *autoscalingv2.ExternalMetricStatus, s conversion.Scope) error {
return autoConvert_autoscaling_ExternalMetricStatus_To_v2_ExternalMetricStatus(in, out, s)
}
func autoConvert_v2_HPAScalingPolicy_To_autoscaling_HPAScalingPolicy(in *autoscalingv2.HPAScalingPolicy, out *autoscaling.HPAScalingPolicy, s conversion.Scope) error {
out.Type = autoscaling.HPAScalingPolicyType(in.Type)
out.Value = in.Value
out.PeriodSeconds = in.PeriodSeconds
return nil
}
// Convert_v2_HPAScalingPolicy_To_autoscaling_HPAScalingPolicy is an autogenerated conversion function.
func Convert_v2_HPAScalingPolicy_To_autoscaling_HPAScalingPolicy(in *autoscalingv2.HPAScalingPolicy, out *autoscaling.HPAScalingPolicy, s conversion.Scope) error {
return autoConvert_v2_HPAScalingPolicy_To_autoscaling_HPAScalingPolicy(in, out, s)
}
func autoConvert_autoscaling_HPAScalingPolicy_To_v2_HPAScalingPolicy(in *autoscaling.HPAScalingPolicy, out *autoscalingv2.HPAScalingPolicy, s conversion.Scope) error {
out.Type = autoscalingv2.HPAScalingPolicyType(in.Type)
out.Value = in.Value
out.PeriodSeconds = in.PeriodSeconds
return nil
}
// Convert_autoscaling_HPAScalingPolicy_To_v2_HPAScalingPolicy is an autogenerated conversion function.
func Convert_autoscaling_HPAScalingPolicy_To_v2_HPAScalingPolicy(in *autoscaling.HPAScalingPolicy, out *autoscalingv2.HPAScalingPolicy, s conversion.Scope) error {
return autoConvert_autoscaling_HPAScalingPolicy_To_v2_HPAScalingPolicy(in, out, s)
}
func autoConvert_v2_HPAScalingRules_To_autoscaling_HPAScalingRules(in *autoscalingv2.HPAScalingRules, out *autoscaling.HPAScalingRules, s conversion.Scope) error {
out.StabilizationWindowSeconds = (*int32)(unsafe.Pointer(in.StabilizationWindowSeconds))
out.SelectPolicy = (*autoscaling.ScalingPolicySelect)(unsafe.Pointer(in.SelectPolicy))
out.Policies = *(*[]autoscaling.HPAScalingPolicy)(unsafe.Pointer(&in.Policies))
out.Tolerance = (*resource.Quantity)(unsafe.Pointer(in.Tolerance))
return nil
}
// Convert_v2_HPAScalingRules_To_autoscaling_HPAScalingRules is an autogenerated conversion function.
func Convert_v2_HPAScalingRules_To_autoscaling_HPAScalingRules(in *autoscalingv2.HPAScalingRules, out *autoscaling.HPAScalingRules, s conversion.Scope) error {
return autoConvert_v2_HPAScalingRules_To_autoscaling_HPAScalingRules(in, out, s)
}
func autoConvert_autoscaling_HPAScalingRules_To_v2_HPAScalingRules(in *autoscaling.HPAScalingRules, out *autoscalingv2.HPAScalingRules, s conversion.Scope) error {
out.StabilizationWindowSeconds = (*int32)(unsafe.Pointer(in.StabilizationWindowSeconds))
out.SelectPolicy = (*autoscalingv2.ScalingPolicySelect)(unsafe.Pointer(in.SelectPolicy))
out.Policies = *(*[]autoscalingv2.HPAScalingPolicy)(unsafe.Pointer(&in.Policies))
out.Tolerance = (*resource.Quantity)(unsafe.Pointer(in.Tolerance))
return nil
}
// Convert_autoscaling_HPAScalingRules_To_v2_HPAScalingRules is an autogenerated conversion function.
func Convert_autoscaling_HPAScalingRules_To_v2_HPAScalingRules(in *autoscaling.HPAScalingRules, out *autoscalingv2.HPAScalingRules, s conversion.Scope) error {
return autoConvert_autoscaling_HPAScalingRules_To_v2_HPAScalingRules(in, out, s)
}
func autoConvert_v2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(in *autoscalingv2.HorizontalPodAutoscaler, out *autoscaling.HorizontalPodAutoscaler, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
if err := Convert_v2_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec(&in.Spec, &out.Spec, s); err != nil {
return err
}
if err := Convert_v2_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus(&in.Status, &out.Status, s); err != nil {
return err
}
return nil
}
func autoConvert_autoscaling_HorizontalPodAutoscaler_To_v2_HorizontalPodAutoscaler(in *autoscaling.HorizontalPodAutoscaler, out *autoscalingv2.HorizontalPodAutoscaler, s conversion.Scope) error {
out.ObjectMeta = in.ObjectMeta
if err := Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v2_HorizontalPodAutoscalerSpec(&in.Spec, &out.Spec, s); err != nil {
return err
}
if err := Convert_autoscaling_HorizontalPodAutoscalerStatus_To_v2_HorizontalPodAutoscalerStatus(&in.Status, &out.Status, s); err != nil {
return err
}
return nil
}
func autoConvert_v2_HorizontalPodAutoscalerBehavior_To_autoscaling_HorizontalPodAutoscalerBehavior(in *autoscalingv2.HorizontalPodAutoscalerBehavior, out *autoscaling.HorizontalPodAutoscalerBehavior, s conversion.Scope) error {
out.ScaleUp = (*autoscaling.HPAScalingRules)(unsafe.Pointer(in.ScaleUp))
out.ScaleDown = (*autoscaling.HPAScalingRules)(unsafe.Pointer(in.ScaleDown))
return nil
}
// Convert_v2_HorizontalPodAutoscalerBehavior_To_autoscaling_HorizontalPodAutoscalerBehavior is an autogenerated conversion function.
func Convert_v2_HorizontalPodAutoscalerBehavior_To_autoscaling_HorizontalPodAutoscalerBehavior(in *autoscalingv2.HorizontalPodAutoscalerBehavior, out *autoscaling.HorizontalPodAutoscalerBehavior, s conversion.Scope) error {
return autoConvert_v2_HorizontalPodAutoscalerBehavior_To_autoscaling_HorizontalPodAutoscalerBehavior(in, out, s)
}
func autoConvert_autoscaling_HorizontalPodAutoscalerBehavior_To_v2_HorizontalPodAutoscalerBehavior(in *autoscaling.HorizontalPodAutoscalerBehavior, out *autoscalingv2.HorizontalPodAutoscalerBehavior, s conversion.Scope) error {
out.ScaleUp = (*autoscalingv2.HPAScalingRules)(unsafe.Pointer(in.ScaleUp))
out.ScaleDown = (*autoscalingv2.HPAScalingRules)(unsafe.Pointer(in.ScaleDown))
return nil
}
// Convert_autoscaling_HorizontalPodAutoscalerBehavior_To_v2_HorizontalPodAutoscalerBehavior is an autogenerated conversion function.
func Convert_autoscaling_HorizontalPodAutoscalerBehavior_To_v2_HorizontalPodAutoscalerBehavior(in *autoscaling.HorizontalPodAutoscalerBehavior, out *autoscalingv2.HorizontalPodAutoscalerBehavior, s conversion.Scope) error {
return autoConvert_autoscaling_HorizontalPodAutoscalerBehavior_To_v2_HorizontalPodAutoscalerBehavior(in, out, s)
}
func autoConvert_v2_HorizontalPodAutoscalerCondition_To_autoscaling_HorizontalPodAutoscalerCondition(in *autoscalingv2.HorizontalPodAutoscalerCondition, out *autoscaling.HorizontalPodAutoscalerCondition, s conversion.Scope) error {
out.Type = autoscaling.HorizontalPodAutoscalerConditionType(in.Type)
out.Status = autoscaling.ConditionStatus(in.Status)
out.LastTransitionTime = in.LastTransitionTime
out.Reason = in.Reason
out.Message = in.Message
return nil
}
// Convert_v2_HorizontalPodAutoscalerCondition_To_autoscaling_HorizontalPodAutoscalerCondition is an autogenerated conversion function.
func Convert_v2_HorizontalPodAutoscalerCondition_To_autoscaling_HorizontalPodAutoscalerCondition(in *autoscalingv2.HorizontalPodAutoscalerCondition, out *autoscaling.HorizontalPodAutoscalerCondition, s conversion.Scope) error {
return autoConvert_v2_HorizontalPodAutoscalerCondition_To_autoscaling_HorizontalPodAutoscalerCondition(in, out, s)
}
func autoConvert_autoscaling_HorizontalPodAutoscalerCondition_To_v2_HorizontalPodAutoscalerCondition(in *autoscaling.HorizontalPodAutoscalerCondition, out *autoscalingv2.HorizontalPodAutoscalerCondition, s conversion.Scope) error {
out.Type = autoscalingv2.HorizontalPodAutoscalerConditionType(in.Type)
out.Status = v1.ConditionStatus(in.Status)
out.LastTransitionTime = in.LastTransitionTime
out.Reason = in.Reason
out.Message = in.Message
return nil
}
// Convert_autoscaling_HorizontalPodAutoscalerCondition_To_v2_HorizontalPodAutoscalerCondition is an autogenerated conversion function.
func Convert_autoscaling_HorizontalPodAutoscalerCondition_To_v2_HorizontalPodAutoscalerCondition(in *autoscaling.HorizontalPodAutoscalerCondition, out *autoscalingv2.HorizontalPodAutoscalerCondition, s conversion.Scope) error {
return autoConvert_autoscaling_HorizontalPodAutoscalerCondition_To_v2_HorizontalPodAutoscalerCondition(in, out, s)
}
func autoConvert_v2_HorizontalPodAutoscalerList_To_autoscaling_HorizontalPodAutoscalerList(in *autoscalingv2.HorizontalPodAutoscalerList, out *autoscaling.HorizontalPodAutoscalerList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]autoscaling.HorizontalPodAutoscaler, len(*in))
for i := range *in {
if err := Convert_v2_HorizontalPodAutoscaler_To_autoscaling_HorizontalPodAutoscaler(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
// Convert_v2_HorizontalPodAutoscalerList_To_autoscaling_HorizontalPodAutoscalerList is an autogenerated conversion function.
func Convert_v2_HorizontalPodAutoscalerList_To_autoscaling_HorizontalPodAutoscalerList(in *autoscalingv2.HorizontalPodAutoscalerList, out *autoscaling.HorizontalPodAutoscalerList, s conversion.Scope) error {
return autoConvert_v2_HorizontalPodAutoscalerList_To_autoscaling_HorizontalPodAutoscalerList(in, out, s)
}
func autoConvert_autoscaling_HorizontalPodAutoscalerList_To_v2_HorizontalPodAutoscalerList(in *autoscaling.HorizontalPodAutoscalerList, out *autoscalingv2.HorizontalPodAutoscalerList, s conversion.Scope) error {
out.ListMeta = in.ListMeta
if in.Items != nil {
in, out := &in.Items, &out.Items
*out = make([]autoscalingv2.HorizontalPodAutoscaler, len(*in))
for i := range *in {
if err := Convert_autoscaling_HorizontalPodAutoscaler_To_v2_HorizontalPodAutoscaler(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.Items = nil
}
return nil
}
// Convert_autoscaling_HorizontalPodAutoscalerList_To_v2_HorizontalPodAutoscalerList is an autogenerated conversion function.
func Convert_autoscaling_HorizontalPodAutoscalerList_To_v2_HorizontalPodAutoscalerList(in *autoscaling.HorizontalPodAutoscalerList, out *autoscalingv2.HorizontalPodAutoscalerList, s conversion.Scope) error {
return autoConvert_autoscaling_HorizontalPodAutoscalerList_To_v2_HorizontalPodAutoscalerList(in, out, s)
}
func autoConvert_v2_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec(in *autoscalingv2.HorizontalPodAutoscalerSpec, out *autoscaling.HorizontalPodAutoscalerSpec, s conversion.Scope) error {
if err := Convert_v2_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference(&in.ScaleTargetRef, &out.ScaleTargetRef, s); err != nil {
return err
}
out.MinReplicas = (*int32)(unsafe.Pointer(in.MinReplicas))
out.MaxReplicas = in.MaxReplicas
if in.Metrics != nil {
in, out := &in.Metrics, &out.Metrics
*out = make([]autoscaling.MetricSpec, len(*in))
for i := range *in {
if err := Convert_v2_MetricSpec_To_autoscaling_MetricSpec(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.Metrics = nil
}
out.Behavior = (*autoscaling.HorizontalPodAutoscalerBehavior)(unsafe.Pointer(in.Behavior))
return nil
}
// Convert_v2_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec is an autogenerated conversion function.
func Convert_v2_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec(in *autoscalingv2.HorizontalPodAutoscalerSpec, out *autoscaling.HorizontalPodAutoscalerSpec, s conversion.Scope) error {
return autoConvert_v2_HorizontalPodAutoscalerSpec_To_autoscaling_HorizontalPodAutoscalerSpec(in, out, s)
}
func autoConvert_autoscaling_HorizontalPodAutoscalerSpec_To_v2_HorizontalPodAutoscalerSpec(in *autoscaling.HorizontalPodAutoscalerSpec, out *autoscalingv2.HorizontalPodAutoscalerSpec, s conversion.Scope) error {
if err := Convert_autoscaling_CrossVersionObjectReference_To_v2_CrossVersionObjectReference(&in.ScaleTargetRef, &out.ScaleTargetRef, s); err != nil {
return err
}
out.MinReplicas = (*int32)(unsafe.Pointer(in.MinReplicas))
out.MaxReplicas = in.MaxReplicas
if in.Metrics != nil {
in, out := &in.Metrics, &out.Metrics
*out = make([]autoscalingv2.MetricSpec, len(*in))
for i := range *in {
if err := Convert_autoscaling_MetricSpec_To_v2_MetricSpec(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.Metrics = nil
}
out.Behavior = (*autoscalingv2.HorizontalPodAutoscalerBehavior)(unsafe.Pointer(in.Behavior))
return nil
}
// Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v2_HorizontalPodAutoscalerSpec is an autogenerated conversion function.
func Convert_autoscaling_HorizontalPodAutoscalerSpec_To_v2_HorizontalPodAutoscalerSpec(in *autoscaling.HorizontalPodAutoscalerSpec, out *autoscalingv2.HorizontalPodAutoscalerSpec, s conversion.Scope) error {
return autoConvert_autoscaling_HorizontalPodAutoscalerSpec_To_v2_HorizontalPodAutoscalerSpec(in, out, s)
}
func autoConvert_v2_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus(in *autoscalingv2.HorizontalPodAutoscalerStatus, out *autoscaling.HorizontalPodAutoscalerStatus, s conversion.Scope) error {
out.ObservedGeneration = (*int64)(unsafe.Pointer(in.ObservedGeneration))
out.LastScaleTime = (*metav1.Time)(unsafe.Pointer(in.LastScaleTime))
out.CurrentReplicas = in.CurrentReplicas
out.DesiredReplicas = in.DesiredReplicas
if in.CurrentMetrics != nil {
in, out := &in.CurrentMetrics, &out.CurrentMetrics
*out = make([]autoscaling.MetricStatus, len(*in))
for i := range *in {
if err := Convert_v2_MetricStatus_To_autoscaling_MetricStatus(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.CurrentMetrics = nil
}
out.Conditions = *(*[]autoscaling.HorizontalPodAutoscalerCondition)(unsafe.Pointer(&in.Conditions))
return nil
}
// Convert_v2_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus is an autogenerated conversion function.
func Convert_v2_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus(in *autoscalingv2.HorizontalPodAutoscalerStatus, out *autoscaling.HorizontalPodAutoscalerStatus, s conversion.Scope) error {
return autoConvert_v2_HorizontalPodAutoscalerStatus_To_autoscaling_HorizontalPodAutoscalerStatus(in, out, s)
}
func autoConvert_autoscaling_HorizontalPodAutoscalerStatus_To_v2_HorizontalPodAutoscalerStatus(in *autoscaling.HorizontalPodAutoscalerStatus, out *autoscalingv2.HorizontalPodAutoscalerStatus, s conversion.Scope) error {
out.ObservedGeneration = (*int64)(unsafe.Pointer(in.ObservedGeneration))
out.LastScaleTime = (*metav1.Time)(unsafe.Pointer(in.LastScaleTime))
out.CurrentReplicas = in.CurrentReplicas
out.DesiredReplicas = in.DesiredReplicas
if in.CurrentMetrics != nil {
in, out := &in.CurrentMetrics, &out.CurrentMetrics
*out = make([]autoscalingv2.MetricStatus, len(*in))
for i := range *in {
if err := Convert_autoscaling_MetricStatus_To_v2_MetricStatus(&(*in)[i], &(*out)[i], s); err != nil {
return err
}
}
} else {
out.CurrentMetrics = nil
}
out.Conditions = *(*[]autoscalingv2.HorizontalPodAutoscalerCondition)(unsafe.Pointer(&in.Conditions))
return nil
}
// Convert_autoscaling_HorizontalPodAutoscalerStatus_To_v2_HorizontalPodAutoscalerStatus is an autogenerated conversion function.
func Convert_autoscaling_HorizontalPodAutoscalerStatus_To_v2_HorizontalPodAutoscalerStatus(in *autoscaling.HorizontalPodAutoscalerStatus, out *autoscalingv2.HorizontalPodAutoscalerStatus, s conversion.Scope) error {
return autoConvert_autoscaling_HorizontalPodAutoscalerStatus_To_v2_HorizontalPodAutoscalerStatus(in, out, s)
}
func autoConvert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(in *autoscalingv2.MetricIdentifier, out *autoscaling.MetricIdentifier, s conversion.Scope) error {
out.Name = in.Name
out.Selector = (*metav1.LabelSelector)(unsafe.Pointer(in.Selector))
return nil
}
// Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier is an autogenerated conversion function.
func Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(in *autoscalingv2.MetricIdentifier, out *autoscaling.MetricIdentifier, s conversion.Scope) error {
return autoConvert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(in, out, s)
}
func autoConvert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(in *autoscaling.MetricIdentifier, out *autoscalingv2.MetricIdentifier, s conversion.Scope) error {
out.Name = in.Name
out.Selector = (*metav1.LabelSelector)(unsafe.Pointer(in.Selector))
return nil
}
// Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier is an autogenerated conversion function.
func Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(in *autoscaling.MetricIdentifier, out *autoscalingv2.MetricIdentifier, s conversion.Scope) error {
return autoConvert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(in, out, s)
}
func autoConvert_v2_MetricSpec_To_autoscaling_MetricSpec(in *autoscalingv2.MetricSpec, out *autoscaling.MetricSpec, s conversion.Scope) error {
out.Type = autoscaling.MetricSourceType(in.Type)
out.Object = (*autoscaling.ObjectMetricSource)(unsafe.Pointer(in.Object))
out.Pods = (*autoscaling.PodsMetricSource)(unsafe.Pointer(in.Pods))
out.Resource = (*autoscaling.ResourceMetricSource)(unsafe.Pointer(in.Resource))
if in.ContainerResource != nil {
in, out := &in.ContainerResource, &out.ContainerResource
*out = new(autoscaling.ContainerResourceMetricSource)
if err := Convert_v2_ContainerResourceMetricSource_To_autoscaling_ContainerResourceMetricSource(*in, *out, s); err != nil {
return err
}
} else {
out.ContainerResource = nil
}
out.External = (*autoscaling.ExternalMetricSource)(unsafe.Pointer(in.External))
return nil
}
// Convert_v2_MetricSpec_To_autoscaling_MetricSpec is an autogenerated conversion function.
func Convert_v2_MetricSpec_To_autoscaling_MetricSpec(in *autoscalingv2.MetricSpec, out *autoscaling.MetricSpec, s conversion.Scope) error {
return autoConvert_v2_MetricSpec_To_autoscaling_MetricSpec(in, out, s)
}
func autoConvert_autoscaling_MetricSpec_To_v2_MetricSpec(in *autoscaling.MetricSpec, out *autoscalingv2.MetricSpec, s conversion.Scope) error {
out.Type = autoscalingv2.MetricSourceType(in.Type)
out.Object = (*autoscalingv2.ObjectMetricSource)(unsafe.Pointer(in.Object))
out.Pods = (*autoscalingv2.PodsMetricSource)(unsafe.Pointer(in.Pods))
out.Resource = (*autoscalingv2.ResourceMetricSource)(unsafe.Pointer(in.Resource))
if in.ContainerResource != nil {
in, out := &in.ContainerResource, &out.ContainerResource
*out = new(autoscalingv2.ContainerResourceMetricSource)
if err := Convert_autoscaling_ContainerResourceMetricSource_To_v2_ContainerResourceMetricSource(*in, *out, s); err != nil {
return err
}
} else {
out.ContainerResource = nil
}
out.External = (*autoscalingv2.ExternalMetricSource)(unsafe.Pointer(in.External))
return nil
}
// Convert_autoscaling_MetricSpec_To_v2_MetricSpec is an autogenerated conversion function.
func Convert_autoscaling_MetricSpec_To_v2_MetricSpec(in *autoscaling.MetricSpec, out *autoscalingv2.MetricSpec, s conversion.Scope) error {
return autoConvert_autoscaling_MetricSpec_To_v2_MetricSpec(in, out, s)
}
func autoConvert_v2_MetricStatus_To_autoscaling_MetricStatus(in *autoscalingv2.MetricStatus, out *autoscaling.MetricStatus, s conversion.Scope) error {
out.Type = autoscaling.MetricSourceType(in.Type)
out.Object = (*autoscaling.ObjectMetricStatus)(unsafe.Pointer(in.Object))
out.Pods = (*autoscaling.PodsMetricStatus)(unsafe.Pointer(in.Pods))
out.Resource = (*autoscaling.ResourceMetricStatus)(unsafe.Pointer(in.Resource))
if in.ContainerResource != nil {
in, out := &in.ContainerResource, &out.ContainerResource
*out = new(autoscaling.ContainerResourceMetricStatus)
if err := Convert_v2_ContainerResourceMetricStatus_To_autoscaling_ContainerResourceMetricStatus(*in, *out, s); err != nil {
return err
}
} else {
out.ContainerResource = nil
}
out.External = (*autoscaling.ExternalMetricStatus)(unsafe.Pointer(in.External))
return nil
}
// Convert_v2_MetricStatus_To_autoscaling_MetricStatus is an autogenerated conversion function.
func Convert_v2_MetricStatus_To_autoscaling_MetricStatus(in *autoscalingv2.MetricStatus, out *autoscaling.MetricStatus, s conversion.Scope) error {
return autoConvert_v2_MetricStatus_To_autoscaling_MetricStatus(in, out, s)
}
func autoConvert_autoscaling_MetricStatus_To_v2_MetricStatus(in *autoscaling.MetricStatus, out *autoscalingv2.MetricStatus, s conversion.Scope) error {
out.Type = autoscalingv2.MetricSourceType(in.Type)
out.Object = (*autoscalingv2.ObjectMetricStatus)(unsafe.Pointer(in.Object))
out.Pods = (*autoscalingv2.PodsMetricStatus)(unsafe.Pointer(in.Pods))
out.Resource = (*autoscalingv2.ResourceMetricStatus)(unsafe.Pointer(in.Resource))
if in.ContainerResource != nil {
in, out := &in.ContainerResource, &out.ContainerResource
*out = new(autoscalingv2.ContainerResourceMetricStatus)
if err := Convert_autoscaling_ContainerResourceMetricStatus_To_v2_ContainerResourceMetricStatus(*in, *out, s); err != nil {
return err
}
} else {
out.ContainerResource = nil
}
out.External = (*autoscalingv2.ExternalMetricStatus)(unsafe.Pointer(in.External))
return nil
}
// Convert_autoscaling_MetricStatus_To_v2_MetricStatus is an autogenerated conversion function.
func Convert_autoscaling_MetricStatus_To_v2_MetricStatus(in *autoscaling.MetricStatus, out *autoscalingv2.MetricStatus, s conversion.Scope) error {
return autoConvert_autoscaling_MetricStatus_To_v2_MetricStatus(in, out, s)
}
func autoConvert_v2_MetricTarget_To_autoscaling_MetricTarget(in *autoscalingv2.MetricTarget, out *autoscaling.MetricTarget, s conversion.Scope) error {
out.Type = autoscaling.MetricTargetType(in.Type)
out.Value = (*resource.Quantity)(unsafe.Pointer(in.Value))
out.AverageValue = (*resource.Quantity)(unsafe.Pointer(in.AverageValue))
out.AverageUtilization = (*int32)(unsafe.Pointer(in.AverageUtilization))
return nil
}
// Convert_v2_MetricTarget_To_autoscaling_MetricTarget is an autogenerated conversion function.
func Convert_v2_MetricTarget_To_autoscaling_MetricTarget(in *autoscalingv2.MetricTarget, out *autoscaling.MetricTarget, s conversion.Scope) error {
return autoConvert_v2_MetricTarget_To_autoscaling_MetricTarget(in, out, s)
}
func autoConvert_autoscaling_MetricTarget_To_v2_MetricTarget(in *autoscaling.MetricTarget, out *autoscalingv2.MetricTarget, s conversion.Scope) error {
out.Type = autoscalingv2.MetricTargetType(in.Type)
out.Value = (*resource.Quantity)(unsafe.Pointer(in.Value))
out.AverageValue = (*resource.Quantity)(unsafe.Pointer(in.AverageValue))
out.AverageUtilization = (*int32)(unsafe.Pointer(in.AverageUtilization))
return nil
}
// Convert_autoscaling_MetricTarget_To_v2_MetricTarget is an autogenerated conversion function.
func Convert_autoscaling_MetricTarget_To_v2_MetricTarget(in *autoscaling.MetricTarget, out *autoscalingv2.MetricTarget, s conversion.Scope) error {
return autoConvert_autoscaling_MetricTarget_To_v2_MetricTarget(in, out, s)
}
func autoConvert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(in *autoscalingv2.MetricValueStatus, out *autoscaling.MetricValueStatus, s conversion.Scope) error {
out.Value = (*resource.Quantity)(unsafe.Pointer(in.Value))
out.AverageValue = (*resource.Quantity)(unsafe.Pointer(in.AverageValue))
out.AverageUtilization = (*int32)(unsafe.Pointer(in.AverageUtilization))
return nil
}
// Convert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus is an autogenerated conversion function.
func Convert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(in *autoscalingv2.MetricValueStatus, out *autoscaling.MetricValueStatus, s conversion.Scope) error {
return autoConvert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(in, out, s)
}
func autoConvert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(in *autoscaling.MetricValueStatus, out *autoscalingv2.MetricValueStatus, s conversion.Scope) error {
out.Value = (*resource.Quantity)(unsafe.Pointer(in.Value))
out.AverageValue = (*resource.Quantity)(unsafe.Pointer(in.AverageValue))
out.AverageUtilization = (*int32)(unsafe.Pointer(in.AverageUtilization))
return nil
}
// Convert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus is an autogenerated conversion function.
func Convert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(in *autoscaling.MetricValueStatus, out *autoscalingv2.MetricValueStatus, s conversion.Scope) error {
return autoConvert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(in, out, s)
}
func autoConvert_v2_ObjectMetricSource_To_autoscaling_ObjectMetricSource(in *autoscalingv2.ObjectMetricSource, out *autoscaling.ObjectMetricSource, s conversion.Scope) error {
if err := Convert_v2_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference(&in.DescribedObject, &out.DescribedObject, s); err != nil {
return err
}
if err := Convert_v2_MetricTarget_To_autoscaling_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
if err := Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
return nil
}
// Convert_v2_ObjectMetricSource_To_autoscaling_ObjectMetricSource is an autogenerated conversion function.
func Convert_v2_ObjectMetricSource_To_autoscaling_ObjectMetricSource(in *autoscalingv2.ObjectMetricSource, out *autoscaling.ObjectMetricSource, s conversion.Scope) error {
return autoConvert_v2_ObjectMetricSource_To_autoscaling_ObjectMetricSource(in, out, s)
}
func autoConvert_autoscaling_ObjectMetricSource_To_v2_ObjectMetricSource(in *autoscaling.ObjectMetricSource, out *autoscalingv2.ObjectMetricSource, s conversion.Scope) error {
if err := Convert_autoscaling_CrossVersionObjectReference_To_v2_CrossVersionObjectReference(&in.DescribedObject, &out.DescribedObject, s); err != nil {
return err
}
if err := Convert_autoscaling_MetricTarget_To_v2_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
if err := Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_ObjectMetricSource_To_v2_ObjectMetricSource is an autogenerated conversion function.
func Convert_autoscaling_ObjectMetricSource_To_v2_ObjectMetricSource(in *autoscaling.ObjectMetricSource, out *autoscalingv2.ObjectMetricSource, s conversion.Scope) error {
return autoConvert_autoscaling_ObjectMetricSource_To_v2_ObjectMetricSource(in, out, s)
}
func autoConvert_v2_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus(in *autoscalingv2.ObjectMetricStatus, out *autoscaling.ObjectMetricStatus, s conversion.Scope) error {
if err := Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
if err := Convert_v2_CrossVersionObjectReference_To_autoscaling_CrossVersionObjectReference(&in.DescribedObject, &out.DescribedObject, s); err != nil {
return err
}
return nil
}
// Convert_v2_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus is an autogenerated conversion function.
func Convert_v2_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus(in *autoscalingv2.ObjectMetricStatus, out *autoscaling.ObjectMetricStatus, s conversion.Scope) error {
return autoConvert_v2_ObjectMetricStatus_To_autoscaling_ObjectMetricStatus(in, out, s)
}
func autoConvert_autoscaling_ObjectMetricStatus_To_v2_ObjectMetricStatus(in *autoscaling.ObjectMetricStatus, out *autoscalingv2.ObjectMetricStatus, s conversion.Scope) error {
if err := Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
if err := Convert_autoscaling_CrossVersionObjectReference_To_v2_CrossVersionObjectReference(&in.DescribedObject, &out.DescribedObject, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_ObjectMetricStatus_To_v2_ObjectMetricStatus is an autogenerated conversion function.
func Convert_autoscaling_ObjectMetricStatus_To_v2_ObjectMetricStatus(in *autoscaling.ObjectMetricStatus, out *autoscalingv2.ObjectMetricStatus, s conversion.Scope) error {
return autoConvert_autoscaling_ObjectMetricStatus_To_v2_ObjectMetricStatus(in, out, s)
}
func autoConvert_v2_PodsMetricSource_To_autoscaling_PodsMetricSource(in *autoscalingv2.PodsMetricSource, out *autoscaling.PodsMetricSource, s conversion.Scope) error {
if err := Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_v2_MetricTarget_To_autoscaling_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
return nil
}
// Convert_v2_PodsMetricSource_To_autoscaling_PodsMetricSource is an autogenerated conversion function.
func Convert_v2_PodsMetricSource_To_autoscaling_PodsMetricSource(in *autoscalingv2.PodsMetricSource, out *autoscaling.PodsMetricSource, s conversion.Scope) error {
return autoConvert_v2_PodsMetricSource_To_autoscaling_PodsMetricSource(in, out, s)
}
func autoConvert_autoscaling_PodsMetricSource_To_v2_PodsMetricSource(in *autoscaling.PodsMetricSource, out *autoscalingv2.PodsMetricSource, s conversion.Scope) error {
if err := Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_autoscaling_MetricTarget_To_v2_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_PodsMetricSource_To_v2_PodsMetricSource is an autogenerated conversion function.
func Convert_autoscaling_PodsMetricSource_To_v2_PodsMetricSource(in *autoscaling.PodsMetricSource, out *autoscalingv2.PodsMetricSource, s conversion.Scope) error {
return autoConvert_autoscaling_PodsMetricSource_To_v2_PodsMetricSource(in, out, s)
}
func autoConvert_v2_PodsMetricStatus_To_autoscaling_PodsMetricStatus(in *autoscalingv2.PodsMetricStatus, out *autoscaling.PodsMetricStatus, s conversion.Scope) error {
if err := Convert_v2_MetricIdentifier_To_autoscaling_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
return nil
}
// Convert_v2_PodsMetricStatus_To_autoscaling_PodsMetricStatus is an autogenerated conversion function.
func Convert_v2_PodsMetricStatus_To_autoscaling_PodsMetricStatus(in *autoscalingv2.PodsMetricStatus, out *autoscaling.PodsMetricStatus, s conversion.Scope) error {
return autoConvert_v2_PodsMetricStatus_To_autoscaling_PodsMetricStatus(in, out, s)
}
func autoConvert_autoscaling_PodsMetricStatus_To_v2_PodsMetricStatus(in *autoscaling.PodsMetricStatus, out *autoscalingv2.PodsMetricStatus, s conversion.Scope) error {
if err := Convert_autoscaling_MetricIdentifier_To_v2_MetricIdentifier(&in.Metric, &out.Metric, s); err != nil {
return err
}
if err := Convert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_PodsMetricStatus_To_v2_PodsMetricStatus is an autogenerated conversion function.
func Convert_autoscaling_PodsMetricStatus_To_v2_PodsMetricStatus(in *autoscaling.PodsMetricStatus, out *autoscalingv2.PodsMetricStatus, s conversion.Scope) error {
return autoConvert_autoscaling_PodsMetricStatus_To_v2_PodsMetricStatus(in, out, s)
}
func autoConvert_v2_ResourceMetricSource_To_autoscaling_ResourceMetricSource(in *autoscalingv2.ResourceMetricSource, out *autoscaling.ResourceMetricSource, s conversion.Scope) error {
out.Name = core.ResourceName(in.Name)
if err := Convert_v2_MetricTarget_To_autoscaling_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
return nil
}
// Convert_v2_ResourceMetricSource_To_autoscaling_ResourceMetricSource is an autogenerated conversion function.
func Convert_v2_ResourceMetricSource_To_autoscaling_ResourceMetricSource(in *autoscalingv2.ResourceMetricSource, out *autoscaling.ResourceMetricSource, s conversion.Scope) error {
return autoConvert_v2_ResourceMetricSource_To_autoscaling_ResourceMetricSource(in, out, s)
}
func autoConvert_autoscaling_ResourceMetricSource_To_v2_ResourceMetricSource(in *autoscaling.ResourceMetricSource, out *autoscalingv2.ResourceMetricSource, s conversion.Scope) error {
out.Name = v1.ResourceName(in.Name)
if err := Convert_autoscaling_MetricTarget_To_v2_MetricTarget(&in.Target, &out.Target, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_ResourceMetricSource_To_v2_ResourceMetricSource is an autogenerated conversion function.
func Convert_autoscaling_ResourceMetricSource_To_v2_ResourceMetricSource(in *autoscaling.ResourceMetricSource, out *autoscalingv2.ResourceMetricSource, s conversion.Scope) error {
return autoConvert_autoscaling_ResourceMetricSource_To_v2_ResourceMetricSource(in, out, s)
}
func autoConvert_v2_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus(in *autoscalingv2.ResourceMetricStatus, out *autoscaling.ResourceMetricStatus, s conversion.Scope) error {
out.Name = core.ResourceName(in.Name)
if err := Convert_v2_MetricValueStatus_To_autoscaling_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
return nil
}
// Convert_v2_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus is an autogenerated conversion function.
func Convert_v2_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus(in *autoscalingv2.ResourceMetricStatus, out *autoscaling.ResourceMetricStatus, s conversion.Scope) error {
return autoConvert_v2_ResourceMetricStatus_To_autoscaling_ResourceMetricStatus(in, out, s)
}
func autoConvert_autoscaling_ResourceMetricStatus_To_v2_ResourceMetricStatus(in *autoscaling.ResourceMetricStatus, out *autoscalingv2.ResourceMetricStatus, s conversion.Scope) error {
out.Name = v1.ResourceName(in.Name)
if err := Convert_autoscaling_MetricValueStatus_To_v2_MetricValueStatus(&in.Current, &out.Current, s); err != nil {
return err
}
return nil
}
// Convert_autoscaling_ResourceMetricStatus_To_v2_ResourceMetricStatus is an autogenerated conversion function.
func Convert_autoscaling_ResourceMetricStatus_To_v2_ResourceMetricStatus(in *autoscaling.ResourceMetricStatus, out *autoscalingv2.ResourceMetricStatus, s conversion.Scope) error {
return autoConvert_autoscaling_ResourceMetricStatus_To_v2_ResourceMetricStatus(in, out, s)
} | go | github | https://github.com/kubernetes/kubernetes | pkg/apis/autoscaling/v2/zz_generated.conversion.go |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from lxml import etree
import re
rml_parents = ['tr','story','section']
html_parents = ['tr','body','div']
sxw_parents = ['{http://openoffice.org/2000/table}table-row','{http://openoffice.org/2000/office}body','{http://openoffice.org/2000/text}section']
odt_parents = ['{urn:oasis:names:tc:opendocument:xmlns:office:1.0}body','{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table-row','{urn:oasis:names:tc:opendocument:xmlns:text:1.0}section']
class report(object):
def preprocess_rml(self, root_node,type='pdf'):
_regex1 = re.compile("\[\[(.*?)(repeatIn\(.*?\s*,\s*[\'\"].*?[\'\"]\s*(?:,\s*(.*?)\s*)?\s*\))(.*?)\]\]")
_regex11= re.compile("\[\[(.*?)(repeatIn\(.*?\s*\(.*?\s*[\'\"].*?[\'\"]\s*\),[\'\"].*?[\'\"](?:,\s*(.*?)\s*)?\s*\))(.*?)\]\]")
_regex2 = re.compile("\[\[(.*?)(removeParentNode\(\s*(?:['\"](.*?)['\"])\s*\))(.*?)\]\]")
_regex3 = re.compile("\[\[\s*(.*?setTag\(\s*['\"](.*?)['\"]\s*,\s*['\"].*?['\"]\s*(?:,.*?)?\).*?)\s*\]\]")
for node in root_node:
if node.tag == etree.Comment:
continue
if node.text or node.tail:
def _sub3(txt):
n = node
while n.tag != txt.group(2):
n = n.getparent()
n.set('rml_tag', txt.group(1))
return "[[ '' ]]"
def _sub2(txt):
if txt.group(3):
n = node
try:
while n.tag != txt.group(3):
n = n.getparent()
except Exception:
n = node
else:
n = node.getparent()
n.set('rml_except', txt.group(0)[2:-2])
return txt.group(0)
def _sub1(txt):
if len(txt.group(4)) > 1:
return " "
match = rml_parents
if type == 'odt':
match = odt_parents
if type == 'sxw':
match = sxw_parents
if type =='html2html':
match = html_parents
if txt.group(3):
group_3 = txt.group(3)
if group_3.startswith("'") or group_3.startswith('"'):
group_3 = group_3[1:-1]
match = [group_3]
n = node
while n.tag not in match:
n = n.getparent()
n.set('rml_loop', txt.group(2))
return '[['+txt.group(1)+"''"+txt.group(4)+']]'
t = _regex1.sub(_sub1, node.text or node.tail)
if t == " ":
t = _regex11.sub(_sub1, node.text or node.tail)
t = _regex3.sub(_sub3, t)
node.text = _regex2.sub(_sub2, t)
self.preprocess_rml(node,type)
return root_node
if __name__=='__main__':
node = etree.XML('''<story>
<para>This is a test[[ setTag('para','xpre') ]]</para>
<blockTable>
<tr>
<td><para>Row 1 [[ setTag('tr','tr',{'style':'TrLevel'+str(a['level']), 'paraStyle':('Level'+str(a['level']))}) ]] </para></td>
<td>Row 2 [[ True and removeParentNode('td') ]] </td>
</tr><tr>
<td>Row 1 [[repeatIn(o.order_line,'o')]] </td>
<td>Row 2</td>
</tr>
</blockTable>
<p>This isa test</p>
</story>''')
a = report()
result = a.preprocess_rml(node)
print etree.tostring(result)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | unknown | codeparrot/codeparrot-clean | ||
/*
Copyright 2020 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package image
import "testing"
func TestTagFromImage(t *testing.T) {
tests := map[string]string{
"kindest/node": "",
"kindest/node:latest": "latest",
"kindest/node:v1.17.0": "v1.17.0",
"kindest/node:v1.17.0@sha256:9512edae126da271b66b990b6fff768fbb7cd786c7d39e86bdf55906352fdf62": "v1.17.0",
"kindest/node@sha256:9512edae126da271b66b990b6fff768fbb7cd786c7d39e86bdf55906352fdf62": "",
"example.com/kindest/node": "",
"example.com/kindest/node:latest": "latest",
"example.com/kindest/node:v1.17.0": "v1.17.0",
"example.com/kindest/node:v1.17.0@sha256:9512edae126da271b66b990b6fff768fbb7cd786c7d39e86bdf55906352fdf62": "v1.17.0",
"example.com/kindest/node@sha256:9512edae126da271b66b990b6fff768fbb7cd786c7d39e86bdf55906352fdf62": "",
"example.com:3000/kindest/node": "",
"example.com:3000/kindest/node:latest": "latest",
"example.com:3000/kindest/node:v1.17.0": "v1.17.0",
"example.com:3000/kindest/node:v1.17.0@sha256:9512edae126da271b66b990b6fff768fbb7cd786c7d39e86bdf55906352fdf62": "v1.17.0",
"example.com:3000/kindest/node@sha256:9512edae126da271b66b990b6fff768fbb7cd786c7d39e86bdf55906352fdf62": "",
}
for in, expected := range tests {
out := TagFromImage(in)
if out != expected {
t.Errorf("TagFromImage(%q) = %q, expected %q instead", in, out, expected)
}
}
} | go | github | https://github.com/kubernetes/kubernetes | cmd/kubeadm/app/util/image/image_test.go |
# Copyright 2010 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Test suites for 'common' code used throughout the OpenStack HTTP API.
"""
import mock
import six
from testtools import matchers
import webob
import webob.exc
import webob.multidict
from nova.api.openstack import common
from nova.compute import task_states
from nova.compute import vm_states
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import utils
NS = "{http://docs.openstack.org/compute/api/v1.1}"
ATOMNS = "{http://www.w3.org/2005/Atom}"
class LimiterTest(test.NoDBTestCase):
"""Unit tests for the `nova.api.openstack.common.limited` method which
takes in a list of items and, depending on the 'offset' and 'limit' GET
params, returns a subset or complete set of the given items.
"""
def setUp(self):
"""Run before each test."""
super(LimiterTest, self).setUp()
self.tiny = range(1)
self.small = range(10)
self.medium = range(1000)
self.large = range(10000)
def test_limiter_offset_zero(self):
# Test offset key works with 0.
req = webob.Request.blank('/?offset=0')
self.assertEqual(common.limited(self.tiny, req), self.tiny)
self.assertEqual(common.limited(self.small, req), self.small)
self.assertEqual(common.limited(self.medium, req), self.medium)
self.assertEqual(common.limited(self.large, req), self.large[:1000])
def test_limiter_offset_medium(self):
# Test offset key works with a medium sized number.
req = webob.Request.blank('/?offset=10')
self.assertEqual(0, len(common.limited(self.tiny, req)))
self.assertEqual(common.limited(self.small, req), self.small[10:])
self.assertEqual(common.limited(self.medium, req), self.medium[10:])
self.assertEqual(common.limited(self.large, req), self.large[10:1010])
def test_limiter_offset_over_max(self):
# Test offset key works with a number over 1000 (max_limit).
req = webob.Request.blank('/?offset=1001')
self.assertEqual(0, len(common.limited(self.tiny, req)))
self.assertEqual(0, len(common.limited(self.small, req)))
self.assertEqual(0, len(common.limited(self.medium, req)))
self.assertEqual(
common.limited(self.large, req), self.large[1001:2001])
def test_limiter_offset_blank(self):
# Test offset key works with a blank offset.
req = webob.Request.blank('/?offset=')
self.assertRaises(
webob.exc.HTTPBadRequest, common.limited, self.tiny, req)
def test_limiter_offset_bad(self):
# Test offset key works with a BAD offset.
req = webob.Request.blank(u'/?offset=\u0020aa')
self.assertRaises(
webob.exc.HTTPBadRequest, common.limited, self.tiny, req)
def test_limiter_nothing(self):
# Test request with no offset or limit.
req = webob.Request.blank('/')
self.assertEqual(common.limited(self.tiny, req), self.tiny)
self.assertEqual(common.limited(self.small, req), self.small)
self.assertEqual(common.limited(self.medium, req), self.medium)
self.assertEqual(common.limited(self.large, req), self.large[:1000])
def test_limiter_limit_zero(self):
# Test limit of zero.
req = webob.Request.blank('/?limit=0')
self.assertEqual(common.limited(self.tiny, req), self.tiny)
self.assertEqual(common.limited(self.small, req), self.small)
self.assertEqual(common.limited(self.medium, req), self.medium)
self.assertEqual(common.limited(self.large, req), self.large[:1000])
def test_limiter_limit_medium(self):
# Test limit of 10.
req = webob.Request.blank('/?limit=10')
self.assertEqual(common.limited(self.tiny, req), self.tiny)
self.assertEqual(common.limited(self.small, req), self.small)
self.assertEqual(common.limited(self.medium, req), self.medium[:10])
self.assertEqual(common.limited(self.large, req), self.large[:10])
def test_limiter_limit_over_max(self):
# Test limit of 3000.
req = webob.Request.blank('/?limit=3000')
self.assertEqual(common.limited(self.tiny, req), self.tiny)
self.assertEqual(common.limited(self.small, req), self.small)
self.assertEqual(common.limited(self.medium, req), self.medium)
self.assertEqual(common.limited(self.large, req), self.large[:1000])
def test_limiter_limit_and_offset(self):
# Test request with both limit and offset.
items = range(2000)
req = webob.Request.blank('/?offset=1&limit=3')
self.assertEqual(common.limited(items, req), items[1:4])
req = webob.Request.blank('/?offset=3&limit=0')
self.assertEqual(common.limited(items, req), items[3:1003])
req = webob.Request.blank('/?offset=3&limit=1500')
self.assertEqual(common.limited(items, req), items[3:1003])
req = webob.Request.blank('/?offset=3000&limit=10')
self.assertEqual(0, len(common.limited(items, req)))
def test_limiter_custom_max_limit(self):
# Test a max_limit other than 1000.
items = range(2000)
req = webob.Request.blank('/?offset=1&limit=3')
self.assertEqual(
common.limited(items, req, max_limit=2000), items[1:4])
req = webob.Request.blank('/?offset=3&limit=0')
self.assertEqual(
common.limited(items, req, max_limit=2000), items[3:])
req = webob.Request.blank('/?offset=3&limit=2500')
self.assertEqual(
common.limited(items, req, max_limit=2000), items[3:])
req = webob.Request.blank('/?offset=3000&limit=10')
self.assertEqual(0, len(common.limited(items, req, max_limit=2000)))
def test_limiter_negative_limit(self):
# Test a negative limit.
req = webob.Request.blank('/?limit=-3000')
self.assertRaises(
webob.exc.HTTPBadRequest, common.limited, self.tiny, req)
def test_limiter_negative_offset(self):
# Test a negative offset.
req = webob.Request.blank('/?offset=-30')
self.assertRaises(
webob.exc.HTTPBadRequest, common.limited, self.tiny, req)
class SortParamUtilsTest(test.NoDBTestCase):
def test_get_sort_params_defaults(self):
'''Verifies the default sort key and direction.'''
sort_keys, sort_dirs = common.get_sort_params({})
self.assertEqual(['created_at'], sort_keys)
self.assertEqual(['desc'], sort_dirs)
def test_get_sort_params_override_defaults(self):
'''Verifies that the defaults can be overriden.'''
sort_keys, sort_dirs = common.get_sort_params({}, default_key='key1',
default_dir='dir1')
self.assertEqual(['key1'], sort_keys)
self.assertEqual(['dir1'], sort_dirs)
sort_keys, sort_dirs = common.get_sort_params({}, default_key=None,
default_dir=None)
self.assertEqual([], sort_keys)
self.assertEqual([], sort_dirs)
def test_get_sort_params_single_value(self):
'''Verifies a single sort key and direction.'''
params = webob.multidict.MultiDict()
params.add('sort_key', 'key1')
params.add('sort_dir', 'dir1')
sort_keys, sort_dirs = common.get_sort_params(params)
self.assertEqual(['key1'], sort_keys)
self.assertEqual(['dir1'], sort_dirs)
def test_get_sort_params_single_with_default(self):
'''Verifies a single sort value with a default.'''
params = webob.multidict.MultiDict()
params.add('sort_key', 'key1')
sort_keys, sort_dirs = common.get_sort_params(params)
self.assertEqual(['key1'], sort_keys)
# sort_key was supplied, sort_dir should be defaulted
self.assertEqual(['desc'], sort_dirs)
params = webob.multidict.MultiDict()
params.add('sort_dir', 'dir1')
sort_keys, sort_dirs = common.get_sort_params(params)
self.assertEqual(['created_at'], sort_keys)
# sort_dir was supplied, sort_key should be defaulted
self.assertEqual(['dir1'], sort_dirs)
def test_get_sort_params_multiple_values(self):
'''Verifies multiple sort parameter values.'''
params = webob.multidict.MultiDict()
params.add('sort_key', 'key1')
params.add('sort_key', 'key2')
params.add('sort_key', 'key3')
params.add('sort_dir', 'dir1')
params.add('sort_dir', 'dir2')
params.add('sort_dir', 'dir3')
sort_keys, sort_dirs = common.get_sort_params(params)
self.assertEqual(['key1', 'key2', 'key3'], sort_keys)
self.assertEqual(['dir1', 'dir2', 'dir3'], sort_dirs)
# Also ensure that the input parameters are not modified
sort_key_vals = []
sort_dir_vals = []
while 'sort_key' in params:
sort_key_vals.append(params.pop('sort_key'))
while 'sort_dir' in params:
sort_dir_vals.append(params.pop('sort_dir'))
self.assertEqual(['key1', 'key2', 'key3'], sort_key_vals)
self.assertEqual(['dir1', 'dir2', 'dir3'], sort_dir_vals)
self.assertEqual(0, len(params))
class PaginationParamsTest(test.NoDBTestCase):
"""Unit tests for the `nova.api.openstack.common.get_pagination_params`
method which takes in a request object and returns 'marker' and 'limit'
GET params.
"""
def test_no_params(self):
# Test no params.
req = webob.Request.blank('/')
self.assertEqual(common.get_pagination_params(req), {})
def test_valid_marker(self):
# Test valid marker param.
req = webob.Request.blank(
'/?marker=263abb28-1de6-412f-b00b-f0ee0c4333c2')
self.assertEqual(common.get_pagination_params(req),
{'marker': '263abb28-1de6-412f-b00b-f0ee0c4333c2'})
def test_valid_limit(self):
# Test valid limit param.
req = webob.Request.blank('/?limit=10')
self.assertEqual(common.get_pagination_params(req), {'limit': 10})
def test_invalid_limit(self):
# Test invalid limit param.
req = webob.Request.blank('/?limit=-2')
self.assertRaises(
webob.exc.HTTPBadRequest, common.get_pagination_params, req)
def test_valid_limit_and_marker(self):
# Test valid limit and marker parameters.
marker = '263abb28-1de6-412f-b00b-f0ee0c4333c2'
req = webob.Request.blank('/?limit=20&marker=%s' % marker)
self.assertEqual(common.get_pagination_params(req),
{'marker': marker, 'limit': 20})
def test_valid_page_size(self):
# Test valid page_size param.
req = webob.Request.blank('/?page_size=10')
self.assertEqual(common.get_pagination_params(req),
{'page_size': 10})
def test_invalid_page_size(self):
# Test invalid page_size param.
req = webob.Request.blank('/?page_size=-2')
self.assertRaises(
webob.exc.HTTPBadRequest, common.get_pagination_params, req)
def test_valid_limit_and_page_size(self):
# Test valid limit and page_size parameters.
req = webob.Request.blank('/?limit=20&page_size=5')
self.assertEqual(common.get_pagination_params(req),
{'page_size': 5, 'limit': 20})
class MiscFunctionsTest(test.TestCase):
def test_remove_trailing_version_from_href(self):
fixture = 'http://www.testsite.com/v1.1'
expected = 'http://www.testsite.com'
actual = common.remove_trailing_version_from_href(fixture)
self.assertEqual(actual, expected)
def test_remove_trailing_version_from_href_2(self):
fixture = 'http://www.testsite.com/compute/v1.1'
expected = 'http://www.testsite.com/compute'
actual = common.remove_trailing_version_from_href(fixture)
self.assertEqual(actual, expected)
def test_remove_trailing_version_from_href_3(self):
fixture = 'http://www.testsite.com/v1.1/images/v10.5'
expected = 'http://www.testsite.com/v1.1/images'
actual = common.remove_trailing_version_from_href(fixture)
self.assertEqual(actual, expected)
def test_remove_trailing_version_from_href_bad_request(self):
fixture = 'http://www.testsite.com/v1.1/images'
self.assertRaises(ValueError,
common.remove_trailing_version_from_href,
fixture)
def test_remove_trailing_version_from_href_bad_request_2(self):
fixture = 'http://www.testsite.com/images/v'
self.assertRaises(ValueError,
common.remove_trailing_version_from_href,
fixture)
def test_remove_trailing_version_from_href_bad_request_3(self):
fixture = 'http://www.testsite.com/v1.1images'
self.assertRaises(ValueError,
common.remove_trailing_version_from_href,
fixture)
def test_get_id_from_href_with_int_url(self):
fixture = 'http://www.testsite.com/dir/45'
actual = common.get_id_from_href(fixture)
expected = '45'
self.assertEqual(actual, expected)
def test_get_id_from_href_with_int(self):
fixture = '45'
actual = common.get_id_from_href(fixture)
expected = '45'
self.assertEqual(actual, expected)
def test_get_id_from_href_with_int_url_query(self):
fixture = 'http://www.testsite.com/dir/45?asdf=jkl'
actual = common.get_id_from_href(fixture)
expected = '45'
self.assertEqual(actual, expected)
def test_get_id_from_href_with_uuid_url(self):
fixture = 'http://www.testsite.com/dir/abc123'
actual = common.get_id_from_href(fixture)
expected = "abc123"
self.assertEqual(actual, expected)
def test_get_id_from_href_with_uuid_url_query(self):
fixture = 'http://www.testsite.com/dir/abc123?asdf=jkl'
actual = common.get_id_from_href(fixture)
expected = "abc123"
self.assertEqual(actual, expected)
def test_get_id_from_href_with_uuid(self):
fixture = 'abc123'
actual = common.get_id_from_href(fixture)
expected = 'abc123'
self.assertEqual(actual, expected)
def test_raise_http_conflict_for_instance_invalid_state(self):
exc = exception.InstanceInvalidState(attr='fake_attr',
state='fake_state', method='fake_method',
instance_uuid='fake')
try:
common.raise_http_conflict_for_instance_invalid_state(exc,
'meow', 'fake_server_id')
except webob.exc.HTTPConflict as e:
self.assertEqual(six.text_type(e),
"Cannot 'meow' instance fake_server_id while it is in "
"fake_attr fake_state")
else:
self.fail("webob.exc.HTTPConflict was not raised")
def test_check_img_metadata_properties_quota_valid_metadata(self):
ctxt = utils.get_test_admin_context()
metadata1 = {"key": "value"}
actual = common.check_img_metadata_properties_quota(ctxt, metadata1)
self.assertIsNone(actual)
metadata2 = {"key": "v" * 260}
actual = common.check_img_metadata_properties_quota(ctxt, metadata2)
self.assertIsNone(actual)
metadata3 = {"key": ""}
actual = common.check_img_metadata_properties_quota(ctxt, metadata3)
self.assertIsNone(actual)
def test_check_img_metadata_properties_quota_inv_metadata(self):
ctxt = utils.get_test_admin_context()
metadata1 = {"a" * 260: "value"}
self.assertRaises(webob.exc.HTTPBadRequest,
common.check_img_metadata_properties_quota, ctxt, metadata1)
metadata2 = {"": "value"}
self.assertRaises(webob.exc.HTTPBadRequest,
common.check_img_metadata_properties_quota, ctxt, metadata2)
metadata3 = "invalid metadata"
self.assertRaises(webob.exc.HTTPBadRequest,
common.check_img_metadata_properties_quota, ctxt, metadata3)
metadata4 = None
self.assertIsNone(common.check_img_metadata_properties_quota(ctxt,
metadata4))
metadata5 = {}
self.assertIsNone(common.check_img_metadata_properties_quota(ctxt,
metadata5))
def test_status_from_state(self):
for vm_state in (vm_states.ACTIVE, vm_states.STOPPED):
for task_state in (task_states.RESIZE_PREP,
task_states.RESIZE_MIGRATING,
task_states.RESIZE_MIGRATED,
task_states.RESIZE_FINISH):
actual = common.status_from_state(vm_state, task_state)
expected = 'RESIZE'
self.assertEqual(expected, actual)
def test_status_rebuild_from_state(self):
for vm_state in (vm_states.ACTIVE, vm_states.STOPPED,
vm_states.ERROR):
for task_state in (task_states.REBUILDING,
task_states.REBUILD_BLOCK_DEVICE_MAPPING,
task_states.REBUILD_SPAWNING):
actual = common.status_from_state(vm_state, task_state)
expected = 'REBUILD'
self.assertEqual(expected, actual)
def test_status_migrating_from_state(self):
for vm_state in (vm_states.ACTIVE, vm_states.PAUSED):
task_state = task_states.MIGRATING
actual = common.status_from_state(vm_state, task_state)
expected = 'MIGRATING'
self.assertEqual(expected, actual)
def test_task_and_vm_state_from_status(self):
fixture1 = ['reboot']
actual = common.task_and_vm_state_from_status(fixture1)
expected = [vm_states.ACTIVE], [task_states.REBOOT_PENDING,
task_states.REBOOT_STARTED,
task_states.REBOOTING]
self.assertEqual(expected, actual)
fixture2 = ['resize']
actual = common.task_and_vm_state_from_status(fixture2)
expected = ([vm_states.ACTIVE, vm_states.STOPPED],
[task_states.RESIZE_FINISH,
task_states.RESIZE_MIGRATED,
task_states.RESIZE_MIGRATING,
task_states.RESIZE_PREP])
self.assertEqual(expected, actual)
fixture3 = ['resize', 'reboot']
actual = common.task_and_vm_state_from_status(fixture3)
expected = ([vm_states.ACTIVE, vm_states.STOPPED],
[task_states.REBOOT_PENDING,
task_states.REBOOT_STARTED,
task_states.REBOOTING,
task_states.RESIZE_FINISH,
task_states.RESIZE_MIGRATED,
task_states.RESIZE_MIGRATING,
task_states.RESIZE_PREP])
self.assertEqual(expected, actual)
def test_is_all_tenants_true(self):
for value in ('', '1', 'true', 'True'):
search_opts = {'all_tenants': value}
self.assertTrue(common.is_all_tenants(search_opts))
self.assertIn('all_tenants', search_opts)
def test_is_all_tenants_false(self):
for value in ('0', 'false', 'False'):
search_opts = {'all_tenants': value}
self.assertFalse(common.is_all_tenants(search_opts))
self.assertIn('all_tenants', search_opts)
def test_is_all_tenants_missing(self):
self.assertFalse(common.is_all_tenants({}))
def test_is_all_tenants_invalid(self):
search_opts = {'all_tenants': 'wonk'}
self.assertRaises(exception.InvalidInput, common.is_all_tenants,
search_opts)
class TestCollectionLinks(test.NoDBTestCase):
"""Tests the _get_collection_links method."""
@mock.patch('nova.api.openstack.common.ViewBuilder._get_next_link')
def test_items_less_than_limit(self, href_link_mock):
items = [
{"uuid": "123"}
]
req = mock.MagicMock()
params = mock.PropertyMock(return_value=dict(limit=10))
type(req).params = params
builder = common.ViewBuilder()
results = builder._get_collection_links(req, items, "ignored", "uuid")
self.assertFalse(href_link_mock.called)
self.assertThat(results, matchers.HasLength(0))
@mock.patch('nova.api.openstack.common.ViewBuilder._get_next_link')
def test_items_equals_given_limit(self, href_link_mock):
items = [
{"uuid": "123"}
]
req = mock.MagicMock()
params = mock.PropertyMock(return_value=dict(limit=1))
type(req).params = params
builder = common.ViewBuilder()
results = builder._get_collection_links(req, items,
mock.sentinel.coll_key,
"uuid")
href_link_mock.assert_called_once_with(req, "123",
mock.sentinel.coll_key)
self.assertThat(results, matchers.HasLength(1))
@mock.patch('nova.api.openstack.common.ViewBuilder._get_next_link')
def test_items_equals_default_limit(self, href_link_mock):
items = [
{"uuid": "123"}
]
req = mock.MagicMock()
params = mock.PropertyMock(return_value=dict())
type(req).params = params
self.flags(osapi_max_limit=1)
builder = common.ViewBuilder()
results = builder._get_collection_links(req, items,
mock.sentinel.coll_key,
"uuid")
href_link_mock.assert_called_once_with(req, "123",
mock.sentinel.coll_key)
self.assertThat(results, matchers.HasLength(1))
@mock.patch('nova.api.openstack.common.ViewBuilder._get_next_link')
def test_items_equals_default_limit_with_given(self, href_link_mock):
items = [
{"uuid": "123"}
]
req = mock.MagicMock()
# Given limit is greater than default max, only return default max
params = mock.PropertyMock(return_value=dict(limit=2))
type(req).params = params
self.flags(osapi_max_limit=1)
builder = common.ViewBuilder()
results = builder._get_collection_links(req, items,
mock.sentinel.coll_key,
"uuid")
href_link_mock.assert_called_once_with(req, "123",
mock.sentinel.coll_key)
self.assertThat(results, matchers.HasLength(1))
class LinkPrefixTest(test.NoDBTestCase):
def test_update_link_prefix(self):
vb = common.ViewBuilder()
result = vb._update_link_prefix("http://192.168.0.243:24/",
"http://127.0.0.1/compute")
self.assertEqual("http://127.0.0.1/compute", result)
result = vb._update_link_prefix("http://foo.x.com/v1",
"http://new.prefix.com")
self.assertEqual("http://new.prefix.com/v1", result)
result = vb._update_link_prefix(
"http://foo.x.com/v1",
"http://new.prefix.com:20455/new_extra_prefix")
self.assertEqual("http://new.prefix.com:20455/new_extra_prefix/v1",
result)
class UrlJoinTest(test.NoDBTestCase):
def test_url_join(self):
pieces = ["one", "two", "three"]
joined = common.url_join(*pieces)
self.assertEqual("one/two/three", joined)
def test_url_join_extra_slashes(self):
pieces = ["one/", "/two//", "/three/"]
joined = common.url_join(*pieces)
self.assertEqual("one/two/three", joined)
def test_url_join_trailing_slash(self):
pieces = ["one", "two", "three", ""]
joined = common.url_join(*pieces)
self.assertEqual("one/two/three/", joined)
def test_url_join_empty_list(self):
pieces = []
joined = common.url_join(*pieces)
self.assertEqual("", joined)
def test_url_join_single_empty_string(self):
pieces = [""]
joined = common.url_join(*pieces)
self.assertEqual("", joined)
def test_url_join_single_slash(self):
pieces = ["/"]
joined = common.url_join(*pieces)
self.assertEqual("", joined)
class ViewBuilderLinkTest(test.NoDBTestCase):
project_id = "fake"
api_version = "2.1"
def setUp(self):
super(ViewBuilderLinkTest, self).setUp()
self.request = self.req("/%s" % self.project_id)
self.vb = common.ViewBuilder()
def req(self, url, use_admin_context=False):
return fakes.HTTPRequest.blank(url,
use_admin_context=use_admin_context, version=self.api_version)
def test_get_project_id(self):
proj_id = self.vb._get_project_id(self.request)
self.assertEqual(self.project_id, proj_id)
def test_get_next_link(self):
identifier = "identifier"
collection = "collection"
next_link = self.vb._get_next_link(self.request, identifier,
collection)
expected = "/".join((self.request.url,
"%s?marker=%s" % (collection, identifier)))
self.assertEqual(expected, next_link)
def test_get_href_link(self):
identifier = "identifier"
collection = "collection"
href_link = self.vb._get_href_link(self.request, identifier,
collection)
expected = "/".join((self.request.url, collection, identifier))
self.assertEqual(expected, href_link)
def test_get_bookmark_link(self):
identifier = "identifier"
collection = "collection"
bookmark_link = self.vb._get_bookmark_link(self.request, identifier,
collection)
bmk_url = common.remove_trailing_version_from_href(
self.request.application_url)
expected = "/".join((bmk_url, self.project_id, collection, identifier))
self.assertEqual(expected, bookmark_link) | unknown | codeparrot/codeparrot-clean | ||
<?php
namespace Illuminate\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class TrustProxies
{
/**
* The trusted proxies for the application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The trusted proxies headers for the application.
*
* @var int
*/
protected $headers = Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_PREFIX |
Request::HEADER_X_FORWARDED_AWS_ELB;
/**
* The proxies that have been configured to always be trusted.
*
* @var array<int, string>|string|null
*/
protected static $alwaysTrustProxies;
/**
* The proxies headers that have been configured to always be trusted.
*
* @var int|null
*/
protected static $alwaysTrustHeaders;
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*
* @throws \Symfony\Component\HttpKernel\Exception\HttpException
*/
public function handle(Request $request, Closure $next)
{
$request::setTrustedProxies([], $this->getTrustedHeaderNames());
$this->setTrustedProxyIpAddresses($request);
return $next($request);
}
/**
* Sets the trusted proxies on the request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function setTrustedProxyIpAddresses(Request $request)
{
$trustedIps = $this->proxies() ?: config('trustedproxy.proxies');
if (is_null($trustedIps) &&
(laravel_cloud() ||
str_ends_with($request->host(), '.on-forge.com') ||
str_ends_with($request->host(), '.on-vapor.com'))) {
$trustedIps = '*';
}
if (str_ends_with($request->host(), '.on-forge.com') ||
str_ends_with($request->host(), '.on-vapor.com')) {
$request->headers->remove('X-Forwarded-Host');
}
if ($trustedIps === '*' || $trustedIps === '**') {
return $this->setTrustedProxyIpAddressesToTheCallingIp($request);
}
$trustedIps = is_string($trustedIps)
? array_map(trim(...), explode(',', $trustedIps))
: $trustedIps;
if (is_array($trustedIps)) {
return $this->setTrustedProxyIpAddressesToSpecificIps($request, $trustedIps);
}
}
/**
* Specify the IP addresses to trust explicitly.
*
* @param \Illuminate\Http\Request $request
* @param array $trustedIps
* @return void
*/
protected function setTrustedProxyIpAddressesToSpecificIps(Request $request, array $trustedIps)
{
$request->setTrustedProxies(array_reduce($trustedIps, function ($ips, $trustedIp) use ($request) {
$ips[] = $trustedIp === 'REMOTE_ADDR'
? $request->server->get('REMOTE_ADDR')
: $trustedIp;
return $ips;
}, []), $this->getTrustedHeaderNames());
}
/**
* Set the trusted proxy to be the IP address calling this servers.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function setTrustedProxyIpAddressesToTheCallingIp(Request $request)
{
$request->setTrustedProxies([$request->server->get('REMOTE_ADDR')], $this->getTrustedHeaderNames());
}
/**
* Retrieve trusted header name(s), falling back to defaults if config not set.
*
* @return int A bit field of Request::HEADER_*, to set which headers to trust from your proxies.
*/
protected function getTrustedHeaderNames()
{
$headers = $this->headers();
if (is_int($headers)) {
return $headers;
}
return match ($headers) {
'HEADER_X_FORWARDED_AWS_ELB' => Request::HEADER_X_FORWARDED_AWS_ELB,
'HEADER_FORWARDED' => Request::HEADER_FORWARDED,
'HEADER_X_FORWARDED_FOR' => Request::HEADER_X_FORWARDED_FOR,
'HEADER_X_FORWARDED_HOST' => Request::HEADER_X_FORWARDED_HOST,
'HEADER_X_FORWARDED_PORT' => Request::HEADER_X_FORWARDED_PORT,
'HEADER_X_FORWARDED_PROTO' => Request::HEADER_X_FORWARDED_PROTO,
'HEADER_X_FORWARDED_PREFIX' => Request::HEADER_X_FORWARDED_PREFIX,
default => Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_PREFIX | Request::HEADER_X_FORWARDED_AWS_ELB,
};
}
/**
* Get the trusted headers.
*
* @return int
*/
protected function headers()
{
return static::$alwaysTrustHeaders ?: $this->headers;
}
/**
* Get the trusted proxies.
*
* @return array|string|null
*/
protected function proxies()
{
return static::$alwaysTrustProxies ?: $this->proxies;
}
/**
* Specify the IP addresses of proxies that should always be trusted.
*
* @param array|string $proxies
* @return void
*/
public static function at(array|string $proxies)
{
static::$alwaysTrustProxies = $proxies;
}
/**
* Specify the proxy headers that should always be trusted.
*
* @param int $headers
* @return void
*/
public static function withHeaders(int $headers)
{
static::$alwaysTrustHeaders = $headers;
}
/**
* Flush the state of the middleware.
*
* @return void
*/
public static function flushState()
{
static::$alwaysTrustHeaders = null;
static::$alwaysTrustProxies = null;
}
} | php | github | https://github.com/laravel/framework | src/Illuminate/Http/Middleware/TrustProxies.php |
from __future__ import unicode_literals
import mimetypes
import posixpath
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
from django.utils import importlib
from django.utils.encoding import smart_str
from pipeline.conf import settings
def to_class(class_str):
if not class_str:
return None
module_bits = class_str.split('.')
module_path, class_name = '.'.join(module_bits[:-1]), module_bits[-1]
module = importlib.import_module(module_path)
return getattr(module, class_name, None)
def filepath_to_uri(path):
if path is None:
return path
return quote(smart_str(path).replace("\\", "/"), safe="/~!*()'#?")
def guess_type(path, default=None):
for type, ext in settings.PIPELINE_MIMETYPES:
mimetypes.add_type(type, ext)
mimetype, _ = mimetypes.guess_type(path)
if not mimetype:
return default
return smart_str(mimetype)
def relpath(path, start=posixpath.curdir):
"""Return a relative version of a path"""
if not path:
raise ValueError("no path specified")
start_list = posixpath.abspath(start).split(posixpath.sep)
path_list = posixpath.abspath(path).split(posixpath.sep)
# Work out how much of the filepath is shared by start and path.
i = len(posixpath.commonprefix([start_list, path_list]))
rel_list = [posixpath.pardir] * (len(start_list) - i) + path_list[i:]
if not rel_list:
return posixpath.curdir
return posixpath.join(*rel_list) | unknown | codeparrot/codeparrot-clean | ||
# coding: utf-8
from __future__ import unicode_literals
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.core.urlresolvers import (
NoReverseMatch, Resolver404, get_script_prefix, resolve
)
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.utils import six
from django.utils.encoding import smart_text
from django.utils.six.moves.urllib import parse as urlparse
from django.utils.translation import ugettext_lazy as _
from rest_framework.compat import OrderedDict
from rest_framework.fields import (
Field, empty, get_attribute, is_simple_callable, iter_options
)
from rest_framework.reverse import reverse
from rest_framework.utils import html
class Hyperlink(six.text_type):
"""
A string like object that additionally has an associated name.
We use this for hyperlinked URLs that may render as a named link
in some contexts, or render as a plain URL in others.
"""
def __new__(self, url, name):
ret = six.text_type.__new__(self, url)
ret.name = name
return ret
is_hyperlink = True
class PKOnlyObject(object):
"""
This is a mock object, used for when we only need the pk of the object
instance, but still want to return an object with a .pk attribute,
in order to keep the same interface as a regular model instance.
"""
def __init__(self, pk):
self.pk = pk
# We assume that 'validators' are intended for the child serializer,
# rather than the parent serializer.
MANY_RELATION_KWARGS = (
'read_only', 'write_only', 'required', 'default', 'initial', 'source',
'label', 'help_text', 'style', 'error_messages', 'allow_empty'
)
class RelatedField(Field):
queryset = None
html_cutoff = 1000
html_cutoff_text = _('More than {count} items...')
def __init__(self, **kwargs):
self.queryset = kwargs.pop('queryset', self.queryset)
self.html_cutoff = kwargs.pop('html_cutoff', self.html_cutoff)
self.html_cutoff_text = kwargs.pop('html_cutoff_text', self.html_cutoff_text)
assert self.queryset is not None or kwargs.get('read_only', None), (
'Relational field must provide a `queryset` argument, '
'or set read_only=`True`.'
)
assert not (self.queryset is not None and kwargs.get('read_only', None)), (
'Relational fields should not provide a `queryset` argument, '
'when setting read_only=`True`.'
)
kwargs.pop('many', None)
kwargs.pop('allow_empty', None)
super(RelatedField, self).__init__(**kwargs)
def __new__(cls, *args, **kwargs):
# We override this method in order to automagically create
# `ManyRelatedField` classes instead when `many=True` is set.
if kwargs.pop('many', False):
return cls.many_init(*args, **kwargs)
return super(RelatedField, cls).__new__(cls, *args, **kwargs)
@classmethod
def many_init(cls, *args, **kwargs):
"""
This method handles creating a parent `ManyRelatedField` instance
when the `many=True` keyword argument is passed.
Typically you won't need to override this method.
Note that we're over-cautious in passing most arguments to both parent
and child classes in order to try to cover the general case. If you're
overriding this method you'll probably want something much simpler, eg:
@classmethod
def many_init(cls, *args, **kwargs):
kwargs['child'] = cls()
return CustomManyRelatedField(*args, **kwargs)
"""
list_kwargs = {'child_relation': cls(*args, **kwargs)}
for key in kwargs.keys():
if key in MANY_RELATION_KWARGS:
list_kwargs[key] = kwargs[key]
return ManyRelatedField(**list_kwargs)
def run_validation(self, data=empty):
# We force empty strings to None values for relational fields.
if data == '':
data = None
return super(RelatedField, self).run_validation(data)
def get_queryset(self):
queryset = self.queryset
if isinstance(queryset, (QuerySet, Manager)):
# Ensure queryset is re-evaluated whenever used.
# Note that actually a `Manager` class may also be used as the
# queryset argument. This occurs on ModelSerializer fields,
# as it allows us to generate a more expressive 'repr' output
# for the field.
# Eg: 'MyRelationship(queryset=ExampleModel.objects.all())'
queryset = queryset.all()
return queryset
def use_pk_only_optimization(self):
return False
def get_attribute(self, instance):
if self.use_pk_only_optimization() and self.source_attrs:
# Optimized case, return a mock object only containing the pk attribute.
try:
instance = get_attribute(instance, self.source_attrs[:-1])
value = instance.serializable_value(self.source_attrs[-1])
if is_simple_callable(value):
# Handle edge case where the relationship `source` argument
# points to a `get_relationship()` method on the model
value = value().pk
return PKOnlyObject(pk=value)
except AttributeError:
pass
# Standard case, return the object instance.
return get_attribute(instance, self.source_attrs)
@property
def choices(self):
queryset = self.get_queryset()
if queryset is None:
# Ensure that field.choices returns something sensible
# even when accessed with a read-only field.
return {}
return OrderedDict([
(
six.text_type(self.to_representation(item)),
self.display_value(item)
)
for item in queryset
])
@property
def grouped_choices(self):
return self.choices
def iter_options(self):
return iter_options(
self.grouped_choices,
cutoff=self.html_cutoff,
cutoff_text=self.html_cutoff_text
)
def display_value(self, instance):
return six.text_type(instance)
class StringRelatedField(RelatedField):
"""
A read only field that represents its targets using their
plain string representation.
"""
def __init__(self, **kwargs):
kwargs['read_only'] = True
super(StringRelatedField, self).__init__(**kwargs)
def to_representation(self, value):
return six.text_type(value)
class PrimaryKeyRelatedField(RelatedField):
default_error_messages = {
'required': _('This field is required.'),
'does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'),
'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'),
}
def __init__(self, **kwargs):
self.pk_field = kwargs.pop('pk_field', None)
super(PrimaryKeyRelatedField, self).__init__(**kwargs)
def use_pk_only_optimization(self):
return True
def to_internal_value(self, data):
if self.pk_field is not None:
data = self.pk_field.to_internal_value(data)
try:
return self.get_queryset().get(pk=data)
except ObjectDoesNotExist:
self.fail('does_not_exist', pk_value=data)
except (TypeError, ValueError):
self.fail('incorrect_type', data_type=type(data).__name__)
def to_representation(self, value):
if self.pk_field is not None:
return self.pk_field.to_representation(value.pk)
return value.pk
class HyperlinkedRelatedField(RelatedField):
lookup_field = 'pk'
view_name = None
default_error_messages = {
'required': _('This field is required.'),
'no_match': _('Invalid hyperlink - No URL match.'),
'incorrect_match': _('Invalid hyperlink - Incorrect URL match.'),
'does_not_exist': _('Invalid hyperlink - Object does not exist.'),
'incorrect_type': _('Incorrect type. Expected URL string, received {data_type}.'),
}
def __init__(self, view_name=None, **kwargs):
if view_name is not None:
self.view_name = view_name
assert self.view_name is not None, 'The `view_name` argument is required.'
self.lookup_field = kwargs.pop('lookup_field', self.lookup_field)
self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field)
self.format = kwargs.pop('format', None)
# We include this simply for dependency injection in tests.
# We can't add it as a class attributes or it would expect an
# implicit `self` argument to be passed.
self.reverse = reverse
super(HyperlinkedRelatedField, self).__init__(**kwargs)
def use_pk_only_optimization(self):
return self.lookup_field == 'pk'
def get_object(self, view_name, view_args, view_kwargs):
"""
Return the object corresponding to a matched URL.
Takes the matched URL conf arguments, and should return an
object instance, or raise an `ObjectDoesNotExist` exception.
"""
lookup_value = view_kwargs[self.lookup_url_kwarg]
lookup_kwargs = {self.lookup_field: lookup_value}
return self.get_queryset().get(**lookup_kwargs)
def get_url(self, obj, view_name, request, format):
"""
Given an object, return the URL that hyperlinks to the object.
May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
attributes are not configured to correctly match the URL conf.
"""
# Unsaved objects will not yet have a valid URL.
if hasattr(obj, 'pk') and obj.pk is None:
return None
lookup_value = getattr(obj, self.lookup_field)
kwargs = {self.lookup_url_kwarg: lookup_value}
return self.reverse(view_name, kwargs=kwargs, request=request, format=format)
def get_name(self, obj):
return six.text_type(obj)
def to_internal_value(self, data):
request = self.context.get('request', None)
try:
http_prefix = data.startswith(('http:', 'https:'))
except AttributeError:
self.fail('incorrect_type', data_type=type(data).__name__)
if http_prefix:
# If needed convert absolute URLs to relative path
data = urlparse.urlparse(data).path
prefix = get_script_prefix()
if data.startswith(prefix):
data = '/' + data[len(prefix):]
try:
match = resolve(data)
except Resolver404:
self.fail('no_match')
try:
expected_viewname = request.versioning_scheme.get_versioned_viewname(
self.view_name, request
)
except AttributeError:
expected_viewname = self.view_name
if match.view_name != expected_viewname:
self.fail('incorrect_match')
try:
return self.get_object(match.view_name, match.args, match.kwargs)
except (ObjectDoesNotExist, TypeError, ValueError):
self.fail('does_not_exist')
def to_representation(self, value):
request = self.context.get('request', None)
format = self.context.get('format', None)
assert request is not None, (
"`%s` requires the request in the serializer"
" context. Add `context={'request': request}` when instantiating "
"the serializer." % self.__class__.__name__
)
# By default use whatever format is given for the current context
# unless the target is a different type to the source.
#
# Eg. Consider a HyperlinkedIdentityField pointing from a json
# representation to an html property of that representation...
#
# '/snippets/1/' should link to '/snippets/1/highlight/'
# ...but...
# '/snippets/1/.json' should link to '/snippets/1/highlight/.html'
if format and self.format and self.format != format:
format = self.format
# Return the hyperlink, or error if incorrectly configured.
try:
url = self.get_url(value, self.view_name, request, format)
except NoReverseMatch:
msg = (
'Could not resolve URL for hyperlinked relationship using '
'view name "%s". You may have failed to include the related '
'model in your API, or incorrectly configured the '
'`lookup_field` attribute on this field.'
)
if value in ('', None):
value_string = {'': 'the empty string', None: 'None'}[value]
msg += (
" WARNING: The value of the field on the model instance "
"was %s, which may be why it didn't match any "
"entries in your URL conf." % value_string
)
raise ImproperlyConfigured(msg % self.view_name)
if url is None:
return None
name = self.get_name(value)
return Hyperlink(url, name)
class HyperlinkedIdentityField(HyperlinkedRelatedField):
"""
A read-only field that represents the identity URL for an object, itself.
This is in contrast to `HyperlinkedRelatedField` which represents the
URL of relationships to other objects.
"""
def __init__(self, view_name=None, **kwargs):
assert view_name is not None, 'The `view_name` argument is required.'
kwargs['read_only'] = True
kwargs['source'] = '*'
super(HyperlinkedIdentityField, self).__init__(view_name, **kwargs)
def use_pk_only_optimization(self):
# We have the complete object instance already. We don't need
# to run the 'only get the pk for this relationship' code.
return False
class SlugRelatedField(RelatedField):
"""
A read-write field the represents the target of the relationship
by a unique 'slug' attribute.
"""
default_error_messages = {
'does_not_exist': _('Object with {slug_name}={value} does not exist.'),
'invalid': _('Invalid value.'),
}
def __init__(self, slug_field=None, **kwargs):
assert slug_field is not None, 'The `slug_field` argument is required.'
self.slug_field = slug_field
super(SlugRelatedField, self).__init__(**kwargs)
def to_internal_value(self, data):
try:
return self.get_queryset().get(**{self.slug_field: data})
except ObjectDoesNotExist:
self.fail('does_not_exist', slug_name=self.slug_field, value=smart_text(data))
except (TypeError, ValueError):
self.fail('invalid')
def to_representation(self, obj):
return getattr(obj, self.slug_field)
class ManyRelatedField(Field):
"""
Relationships with `many=True` transparently get coerced into instead being
a ManyRelatedField with a child relationship.
The `ManyRelatedField` class is responsible for handling iterating through
the values and passing each one to the child relationship.
This class is treated as private API.
You shouldn't generally need to be using this class directly yourself,
and should instead simply set 'many=True' on the relationship.
"""
initial = []
default_empty_html = []
default_error_messages = {
'not_a_list': _('Expected a list of items but got type "{input_type}".'),
'empty': _('This list may not be empty.')
}
html_cutoff = 1000
html_cutoff_text = _('More than {count} items...')
def __init__(self, child_relation=None, *args, **kwargs):
self.child_relation = child_relation
self.allow_empty = kwargs.pop('allow_empty', True)
self.html_cutoff = kwargs.pop('html_cutoff', self.html_cutoff)
self.html_cutoff_text = kwargs.pop('html_cutoff_text', self.html_cutoff_text)
assert child_relation is not None, '`child_relation` is a required argument.'
super(ManyRelatedField, self).__init__(*args, **kwargs)
self.child_relation.bind(field_name='', parent=self)
def get_value(self, dictionary):
# We override the default field access in order to support
# lists in HTML forms.
if html.is_html_input(dictionary):
# Don't return [] if the update is partial
if self.field_name not in dictionary:
if getattr(self.root, 'partial', False):
return empty
return dictionary.getlist(self.field_name)
return dictionary.get(self.field_name, empty)
def to_internal_value(self, data):
if isinstance(data, type('')) or not hasattr(data, '__iter__'):
self.fail('not_a_list', input_type=type(data).__name__)
if not self.allow_empty and len(data) == 0:
self.fail('empty')
return [
self.child_relation.to_internal_value(item)
for item in data
]
def get_attribute(self, instance):
# Can't have any relationships if not created
if hasattr(instance, 'pk') and instance.pk is None:
return []
relationship = get_attribute(instance, self.source_attrs)
return relationship.all() if (hasattr(relationship, 'all')) else relationship
def to_representation(self, iterable):
return [
self.child_relation.to_representation(value)
for value in iterable
]
@property
def choices(self):
return self.child_relation.choices
@property
def grouped_choices(self):
return self.choices
def iter_options(self):
return iter_options(
self.grouped_choices,
cutoff=self.html_cutoff,
cutoff_text=self.html_cutoff_text
) | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
# Copyright 2008 The Closure Linter Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Parser for JavaScript files."""
from closure_linter import javascripttokens
from closure_linter import statetracker
from closure_linter import tokenutil
# Shorthand
Type = javascripttokens.JavaScriptTokenType
class JsDocFlag(statetracker.DocFlag):
"""Javascript doc flag object.
Attribute:
flag_type: param, return, define, type, etc.
flag_token: The flag token.
type_start_token: The first token specifying the flag JS type,
including braces.
type_end_token: The last token specifying the flag JS type,
including braces.
type: The type spec string.
jstype: The type spec, a TypeAnnotation instance.
name_token: The token specifying the flag name.
name: The flag name
description_start_token: The first token in the description.
description_end_token: The end token in the description.
description: The description.
"""
# Please keep these lists alphabetized.
# Some projects use the following extensions to JsDoc.
# TODO(robbyw): determine which of these, if any, should be illegal.
EXTENDED_DOC = frozenset([
'class', 'code', 'desc', 'final', 'hidden', 'inheritDoc', 'link',
'meaning', 'provideGoog', 'throws'])
LEGAL_DOC = EXTENDED_DOC | statetracker.DocFlag.LEGAL_DOC
class JavaScriptStateTracker(statetracker.StateTracker):
"""JavaScript state tracker.
Inherits from the core EcmaScript StateTracker adding extra state tracking
functionality needed for JavaScript.
"""
def __init__(self):
"""Initializes a JavaScript token stream state tracker."""
statetracker.StateTracker.__init__(self, JsDocFlag)
def Reset(self):
self._scope_depth = 0
self._block_stack = []
super(JavaScriptStateTracker, self).Reset()
def InTopLevel(self):
"""Compute whether we are at the top level in the class.
This function call is language specific. In some languages like
JavaScript, a function is top level if it is not inside any parenthesis.
In languages such as ActionScript, a function is top level if it is directly
within a class.
Returns:
Whether we are at the top level in the class.
"""
return self._scope_depth == self.ParenthesesDepth()
def InFunction(self):
"""Returns true if the current token is within a function.
This js-specific override ignores goog.scope functions.
Returns:
True if the current token is within a function.
"""
return self._scope_depth != self.FunctionDepth()
def InNonScopeBlock(self):
"""Compute whether we are nested within a non-goog.scope block.
Returns:
True if the token is not enclosed in a block that does not originate from
a goog.scope statement. False otherwise.
"""
return self._scope_depth != self.BlockDepth()
def GetBlockType(self, token):
"""Determine the block type given a START_BLOCK token.
Code blocks come after parameters, keywords like else, and closing parens.
Args:
token: The current token. Can be assumed to be type START_BLOCK
Returns:
Code block type for current token.
"""
last_code = tokenutil.SearchExcept(token, Type.NON_CODE_TYPES, reverse=True)
if last_code.type in (Type.END_PARAMETERS, Type.END_PAREN,
Type.KEYWORD) and not last_code.IsKeyword('return'):
return self.CODE
else:
return self.OBJECT_LITERAL
def GetCurrentBlockStart(self):
"""Gets the start token of current block.
Returns:
Starting token of current block. None if not in block.
"""
if self._block_stack:
return self._block_stack[-1]
else:
return None
def HandleToken(self, token, last_non_space_token):
"""Handles the given token and updates state.
Args:
token: The token to handle.
last_non_space_token: The last non space token encountered
"""
if token.type == Type.START_BLOCK:
self._block_stack.append(token)
if token.type == Type.IDENTIFIER and token.string == 'goog.scope':
self._scope_depth += 1
if token.type == Type.END_BLOCK:
start_token = self._block_stack.pop()
if tokenutil.GoogScopeOrNoneFromStartBlock(start_token):
self._scope_depth -= 1
super(JavaScriptStateTracker, self).HandleToken(token,
last_non_space_token) | unknown | codeparrot/codeparrot-clean | ||
import os
import re
import sublime
from ..package_manager import PackageManager
class ExistingPackagesCommand():
"""
Allows listing installed packages and their current version
"""
def __init__(self):
self.manager = PackageManager()
def make_package_list(self, action=''):
"""
Returns a list of installed packages suitable for displaying in the
quick panel.
:param action:
An action to display at the beginning of the third element of the
list returned for each package
:return:
A list of lists, each containing three strings:
0 - package name
1 - package description
2 - [action] installed version; package url
"""
packages = self.manager.list_packages()
if action:
action += ' '
package_list = []
for package in sorted(packages, key=lambda s: s.lower()):
package_entry = [package]
metadata = self.manager.get_metadata(package)
package_dir = os.path.join(sublime.packages_path(), package)
description = metadata.get('description')
if not description:
description = 'No description provided'
package_entry.append(description)
version = metadata.get('version')
if not version and os.path.exists(os.path.join(package_dir,
'.git')):
installed_version = 'git repository'
elif not version and os.path.exists(os.path.join(package_dir,
'.hg')):
installed_version = 'hg repository'
else:
installed_version = 'v' + version if version else \
'unknown version'
url = metadata.get('url')
if url:
url = '; ' + re.sub('^https?://', '', url)
else:
url = ''
package_entry.append(action + installed_version + url)
package_list.append(package_entry)
return package_list | unknown | codeparrot/codeparrot-clean | ||
import numpy as np
import pandas as pd
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.feature_extraction.text import TfidfVectorizer
import spacy
from constants import PICKLE_PATH, TWEET_CSV_PATH
# python -m spacy download en
def load_arxiv_and_tweets():
arxiv = pd.read_pickle(PICKLE_PATH)
arxiv['link'] = arxiv.link.apply(clean_arxiv_api_link)
miles_links = pd.read_csv(TWEET_CSV_PATH)
miles_links['time'] = miles_links.time.apply(pd.Timestamp)
miles_links['link'] = miles_links['link'].apply(clean_miles_link)
df = miles_links.set_index('link').join(arxiv.set_index('link'), how='right')
df = df.reset_index().groupby('link').apply(group_tweeted_multiple).reset_index(drop=True)
df = df.assign(tweeted=(~df.time.isnull()).astype(int))
# remove papers past the day of the last tweet
return df
def get_sklearn_data():
"""Get data for training an sklearn model"""
df = load_arxiv_and_tweets().sort_values('published')
max_date = df[df.tweeted == 1].published.max()
return get_features_matrix(df[df.published < max_date])
def get_tokenized_list_of_dicts():
"""Get data as a list of dictionaries with spacy docs + labels for training the conv net"""
df = load_arxiv_and_tweets()
max_date = df[df.tweeted == 1].published.max()
data_dicts = arxiv_df_to_list_of_dicts(df[df.published < max_date])
tokenized_data = parse_content_serial(data_dicts)
return tokenized_data
def get_features_matrix(df, min_author_freq=3, min_term_freq=30, ngram_range=(1, 3)):
"""Return numpy array of data for sklearn models"""
text = [title + ' ' + summary for title, summary in zip(df.title.values, df.summary.values)]
vectorizer = TfidfVectorizer(min_df=min_term_freq, stop_words='english', ngram_range=ngram_range)
text_features = vectorizer.fit_transform(text).toarray()
author_counts = pd.Series([a for author_set in df.authors.values for a in author_set]).value_counts()
allowed_authors = author_counts[author_counts >= min_author_freq].index
filtered_authors = df.authors.apply(lambda authors: [a for a in authors if a in allowed_authors])
author_binarizer = MultiLabelBinarizer()
author_features = author_binarizer.fit_transform(filtered_authors.values)
category_dummies = pd.get_dummies(df.category)
category_features = category_dummies.values
all_features = [text_features, author_features, category_features]
x = np.concatenate(all_features, axis=1)
if 'tweeted' in df:
y = df.tweeted.astype(int).values
else:
y = None
feature_names = np.concatenate((vectorizer.get_feature_names(),
category_dummies.columns.values,
author_binarizer.classes_))
return x, y, feature_names
def get_spacy_parser():
return spacy.load('en')
def group_tweeted_multiple(df):
row = df.iloc[0]
if df.shape[0] > 1:
row[['rts', 'favorites']] = df.rts.sum(), df.favorites.sum()
return row
def arxiv_df_to_list_of_dicts(df):
def row_to_example(row):
def to_token(s):
"""Squash a string into one token by removing non-alpha characters"""
return ''.join([c for c in s if c.isalpha()])
category_token = to_token(row.category)
author_tokens = ' '.join([to_token(author) for author in row.authors])
to_concat = [row.title, row.summary, author_tokens, category_token]
text = ' '.join(to_concat).replace('\n', ' ')
return {
'label': row.tweeted,
'id': row['index'],
'content': text,
'link': row.link
}
return [row_to_example(row) for i, row in df.reset_index().iterrows()]
def clean_arxiv_api_link(link):
if not link[-1].isdigit():
return None
return link.replace('http://', '').replace('https://', '')[:-2]
def clean_miles_link(link):
if not link[-1].isdigit():
return None
return link.replace('http://', '').replace('https://', '')
def parse_content_serial(data):
"""Parse the content field of a list of dicts from unicode to a spacy doc"""
spacy_parser = get_spacy_parser()
for row in data:
row['content'] = spacy_parser(row['content'])
return data
def sorted_train_test_split(x, y, test_size):
train_size = 1. - test_size
train_end_index = int(len(x) * train_size)
return x[:train_end_index], x[train_end_index:], y[:train_end_index], y[train_end_index:] | unknown | codeparrot/codeparrot-clean | ||
//go:build !windows
package metrics
import (
"context"
"net"
"net/http"
"os"
"sync"
"time"
"github.com/containerd/log"
gometrics "github.com/docker/go-metrics"
"github.com/moby/moby/v2/daemon/pkg/plugin"
"github.com/moby/moby/v2/pkg/plugingetter"
"github.com/moby/moby/v2/pkg/plugins"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/pkg/errors"
)
const pluginType = "MetricsCollector"
// Plugin represents a metrics collector plugin
type Plugin interface {
StartMetrics() error
StopMetrics() error
}
type metricsPluginAdapter struct {
client *plugins.Client
}
func (a *metricsPluginAdapter) StartMetrics() error {
return a.client.Call("/MetricsCollector.StartMetrics", nil, nil)
}
func (a *metricsPluginAdapter) StopMetrics() error {
return a.client.Call("/MetricsCollector.StopMetrics", nil, nil)
}
func makePluginAdapter(p plugingetter.CompatPlugin) (Plugin, error) {
adapted := p.Client()
return &metricsPluginAdapter{adapted}, nil
}
// RegisterPlugin starts the metrics server listener and registers the metrics plugin
// callback with the plugin store
func RegisterPlugin(store *plugin.Store, path string) error {
if err := listen(path); err != nil {
return err
}
store.RegisterRuntimeOpt(pluginType, func(s *specs.Spec) {
f := plugin.WithSpecMounts([]specs.Mount{
{Type: "bind", Source: path, Destination: "/run/docker/metrics.sock", Options: []string{"bind", "ro"}},
})
f(s)
})
store.Handle(pluginType, func(name string, client *plugins.Client) {
// Use lookup since nothing in the system can really reference it, no need
// to protect against removal
p, err := store.Get(name, pluginType, plugingetter.Lookup)
if err != nil {
return
}
adapter, err := makePluginAdapter(p)
if err != nil {
log.G(context.TODO()).WithError(err).WithField("plugin", p.Name()).Error("Error creating plugin adapter")
}
if err := adapter.StartMetrics(); err != nil {
log.G(context.TODO()).WithError(err).WithField("plugin", p.Name()).Error("Error starting metrics collector plugin")
}
})
return nil
}
// CleanupPlugin stops metrics collection for all plugins
func CleanupPlugin(store plugingetter.PluginGetter) {
var wg sync.WaitGroup
for _, p := range store.GetAllManagedPluginsByCap(pluginType) {
wg.Go(func() {
adapter, err := makePluginAdapter(p)
if err != nil {
log.G(context.TODO()).WithFields(log.Fields{
"error": err,
"plugin": p.Name(),
}).Error("Error creating metrics plugin adapter")
return
}
if err := adapter.StopMetrics(); err != nil {
log.G(context.TODO()).WithFields(log.Fields{
"error": err,
"plugin": p.Name(),
}).Error("Error stopping plugin metrics collection")
}
})
}
wg.Wait()
if listener != nil {
_ = listener.Close()
}
}
var listener net.Listener
func listen(path string) error {
_ = os.Remove(path)
l, err := net.Listen("unix", path)
if err != nil {
return errors.Wrap(err, "error setting up metrics plugin listener")
}
mux := http.NewServeMux()
mux.Handle("/metrics", gometrics.Handler())
go func() {
log.G(context.TODO()).Debugf("metrics API listening on %s", l.Addr())
srv := &http.Server{
Handler: mux,
ReadHeaderTimeout: 5 * time.Minute, // "G112: Potential Slowloris Attack (gosec)"; not a real concern for our use, so setting a long timeout.
}
if err := srv.Serve(l); err != nil && !errors.Is(err, net.ErrClosed) {
log.G(context.TODO()).WithError(err).Error("error serving metrics API")
}
}()
listener = l
return nil
} | go | github | https://github.com/moby/moby | daemon/internal/metrics/plugin_unix.go |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.