code
stringlengths 4
4.48k
| docstring
stringlengths 1
6.45k
| _id
stringlengths 24
24
|
---|---|---|
class ImproperlyConfigured(Exception): <NEW_LINE> <INDENT> pass | SQLAlchemy-Utils is improperly configured; normally due to usage of
a utility that depends on a missing library. | 6259903f23e79379d538d765 |
class PointCloud: <NEW_LINE> <INDENT> def points(self, n, box): <NEW_LINE> <INDENT> raise NotImplementedError( "class {.__name__!r} should implement 'points'".format(type(self))) | The abstract base class for point generators | 6259903f23849d37ff85231f |
class Shave(BaseManipulator): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def shave(self): <NEW_LINE> <INDENT> self._setEdges() <NEW_LINE> extra = (len(self.image) - max(abs(self._toCenter.left - self._toCenter.right), abs(self._toCenter.top - self._toCenter.bottom) ) ) <NEW_LINE> for i in range(extra - 1): <NEW_LINE> <INDENT> if self._toCenter.bottom: <NEW_LINE> <INDENT> del self.image[0] <NEW_LINE> self._toCenter.bottom -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> del self.image[-1] <NEW_LINE> <DEDENT> if self._toCenter.left: <NEW_LINE> <INDENT> for eachRow in self.image: <NEW_LINE> <INDENT> del eachRow[0] <NEW_LINE> <DEDENT> self._toCenter.left -= 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> for eachRow in self.image: <NEW_LINE> <INDENT> del eachRow[-1] <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> self.height = len(self.image) <NEW_LINE> self.width = len(self.image[0]) <NEW_LINE> self._resetParameters() <NEW_LINE> return | BI manipulator which removes as much inactive region as possible
while returning a square | 6259903f711fe17d825e15cf |
class _ControlOutputCache(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.cache = {} <NEW_LINE> <DEDENT> def calc_control_outputs(self, graph): <NEW_LINE> <INDENT> control_outputs = {} <NEW_LINE> for op in graph.get_operations(): <NEW_LINE> <INDENT> for control_input in op.control_inputs: <NEW_LINE> <INDENT> if control_input not in control_outputs: <NEW_LINE> <INDENT> control_outputs[control_input] = set() <NEW_LINE> <DEDENT> control_outputs[control_input].add(op) <NEW_LINE> <DEDENT> <DEDENT> return control_outputs <NEW_LINE> <DEDENT> def get_control_outputs(self, op): <NEW_LINE> <INDENT> if op.graph not in self.cache: <NEW_LINE> <INDENT> control_outputs = self.calc_control_outputs(op.graph) <NEW_LINE> self.cache[op.graph] = control_outputs <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> control_outputs = self.cache[op.graph] <NEW_LINE> <DEDENT> return control_outputs.get(op, []) | Helper class to manage calculating and caching control_outputs in graph. | 6259903fb57a9660fecd2ce1 |
class AtomEmbedding(nn.Module): <NEW_LINE> <INDENT> def __init__(self, dim=128, type_num=100, pre_train=None): <NEW_LINE> <INDENT> super(AtomEmbedding, self).__init__() <NEW_LINE> self._dim = dim <NEW_LINE> self._type_num = type_num <NEW_LINE> if pre_train is not None: <NEW_LINE> <INDENT> self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.embedding = nn.Embedding(type_num, dim, padding_idx=0) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, atom_types): <NEW_LINE> <INDENT> return self.embedding(atom_types) | Convert the atom(node) list to atom embeddings.
The atoms with the same element share the same initial embedding.
Parameters
----------
dim : int
Size of embeddings, default to be 128.
type_num : int
The largest atomic number of atoms in the dataset, default to be 100.
pre_train : None or pre-trained embeddings
Pre-trained embeddings, default to be None. | 6259903f30dc7b76659a0a98 |
class TestDestinyDefinitionsDestinyEntitySearchResultItem(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def testDestinyDefinitionsDestinyEntitySearchResultItem(self): <NEW_LINE> <INDENT> pass | DestinyDefinitionsDestinyEntitySearchResultItem unit test stubs | 6259903fd4950a0f3b111773 |
class TestClark1987Conserve(Clark1987): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(TestClark1987Conserve, self).__init__( dtype=float, conserve_memory=0x01 | 0x02 ) <NEW_LINE> self.init_filter() <NEW_LINE> self.run_filter() | Memory conservation test for the loglikelihood and filtered states. | 6259903f26238365f5faddbe |
class ProtocConan(ConanFile): <NEW_LINE> <INDENT> name = "Protoc" <NEW_LINE> version = "3.3.1" <NEW_LINE> description = "Conan package for Protoc" <NEW_LINE> _sha256 = '30f23a45c6f4515598702a6d19c4295ba92c4a635d7ad8d331a4db9fccff392d' <NEW_LINE> _shared_lib_version = 10 <NEW_LINE> _source_dir = "protobuf-%s" % version <NEW_LINE> url = "https://github.com/osechet/conan-protobuf.git" <NEW_LINE> license = "https://github.com/google/protobuf/blob/master/LICENSE" <NEW_LINE> requires = "zlib/1.2.11@conan/stable" <NEW_LINE> settings = "os", "compiler", "build_type", "arch" <NEW_LINE> generators = "cmake" <NEW_LINE> def source(self): <NEW_LINE> <INDENT> download_filename = "v%s.tar.gz" % self.version <NEW_LINE> tools.download('https://github.com/google/protobuf/archive/%s' % download_filename, download_filename) <NEW_LINE> tools.check_sha256(download_filename, self._sha256) <NEW_LINE> tools.unzip(download_filename) <NEW_LINE> os.unlink(download_filename) <NEW_LINE> <DEDENT> def system_requirements(self): <NEW_LINE> <INDENT> if os_info.is_linux: <NEW_LINE> <INDENT> installer = SystemPackageTool() <NEW_LINE> for pkg in ["autoconf", "automake", "libtool", "curl", "make", "g++", "unzip"]: <NEW_LINE> <INDENT> installer.install(pkg) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def build(self): <NEW_LINE> <INDENT> if self.settings.os == "Windows": <NEW_LINE> <INDENT> args = ['-Dprotobuf_BUILD_TESTS=OFF', '-DBUILD_SHARED_LIBS=OFF'] <NEW_LINE> if self.settings.compiler == "Visual Studio": <NEW_LINE> <INDENT> args += ['-Dprotobuf_MSVC_STATIC_RUNTIME=ON'] <NEW_LINE> <DEDENT> cmake = CMake(self.settings) <NEW_LINE> cmake_dir = os.path.sep.join([self._source_dir, "cmake"]) <NEW_LINE> cmake.definitions["CMAKE_INSTALL_PREFIX"] = "%s/release" % self.build_folder <NEW_LINE> self.run('cmake . %s %s' % (cmake.command_line, ' '.join(args)), cwd=cmake_dir) <NEW_LINE> self.run("cmake --build . --target install %s" % cmake.build_config, cwd=cmake_dir) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> env = AutoToolsBuildEnvironment(self) <NEW_LINE> with tools.environment_append(env.vars): <NEW_LINE> <INDENT> cpus = tools.cpu_count() <NEW_LINE> self.run("./autogen.sh", cwd=self._source_dir) <NEW_LINE> self.output.info("prefix is: %s/release" % self.build_folder) <NEW_LINE> args = ['--disable-dependency-tracking', '--with-zlib', '--prefix=%s/release' % self.build_folder] <NEW_LINE> self.run("./configure %s" % (' '.join(args)), cwd=self._source_dir) <NEW_LINE> self.run("make -j %s install" % cpus, cwd=self._source_dir) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def package(self): <NEW_LINE> <INDENT> if self.settings.os == "Windows": <NEW_LINE> <INDENT> self.copy("*.exe", "bin", "%s/release/bin" % self.build_folder, keep_path=False) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.output.info("prefix is: %s/release/bin" % self.build_folder) <NEW_LINE> self.copy("protoc", "bin", "%s/release/bin" % self.build_folder, keep_path=False) | Conan package for protoc | 6259903f1d351010ab8f4d83 |
class Item(models.Model): <NEW_LINE> <INDENT> content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) <NEW_LINE> object_id = models.PositiveIntegerField() <NEW_LINE> content_object = GenericForeignKey('content_type', 'object_id') <NEW_LINE> requisition = models.ForeignKey("Requisition", on_delete=models.CASCADE) <NEW_LINE> quantity = models.PositiveIntegerField() <NEW_LINE> additional = models.TextField(blank=True, null=True) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.content_object.name <NEW_LINE> <DEDENT> def save(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.additional: <NEW_LINE> <INDENT> self.additional = self.content_object.order_info() <NEW_LINE> <DEDENT> super(Item, self).save(*args, **kwargs) | Model of object that can be ordered.
This links any object in the software in order to be orderable. | 6259903f8e05c05ec3f6f78e |
class CpuRegister(ResourceRegister): <NEW_LINE> <INDENT> def __init__(self, fit): <NEW_LINE> <INDENT> ResourceRegister.__init__(self, fit, 'cpu', Attribute.cpu, Restriction.cpu) | Implements restriction:
CPU usage by holders should not exceed ship CPU output.
Details:
For validation, stats module data is used. | 6259903fe76e3b2f99fd9c72 |
class ProductListView(ListView): <NEW_LINE> <INDENT> model = Product <NEW_LINE> template_name = "products/prodcut_list.html" <NEW_LINE> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context['CATEGORIES'] = Category.objects.all() <NEW_LINE> context['cart_add_form'] = CartAddProductForm() <NEW_LINE> return context | View for listing all products. | 6259903f21bff66bcd723ed0 |
@dataclass <NEW_LINE> class ImpactFactor(Entity): <NEW_LINE> <INDENT> olca_type: str = 'ImpactFactor' <NEW_LINE> flow: Optional[Ref] = None <NEW_LINE> location: Optional[Ref] = None <NEW_LINE> flow_property: Optional[Ref] = None <NEW_LINE> unit: Optional[Ref] = None <NEW_LINE> value: Optional[float] = None <NEW_LINE> formula: Optional[str] = None <NEW_LINE> uncertainty: Optional[Uncertainty] = None <NEW_LINE> def to_json(self) -> dict: <NEW_LINE> <INDENT> json: dict = super(ImpactFactor, self).to_json() <NEW_LINE> if self.flow is not None: <NEW_LINE> <INDENT> json['flow'] = self.flow.to_json() <NEW_LINE> <DEDENT> if self.location is not None: <NEW_LINE> <INDENT> json['location'] = self.location.to_json() <NEW_LINE> <DEDENT> if self.flow_property is not None: <NEW_LINE> <INDENT> json['flowProperty'] = self.flow_property.to_json() <NEW_LINE> <DEDENT> if self.unit is not None: <NEW_LINE> <INDENT> json['unit'] = self.unit.to_json() <NEW_LINE> <DEDENT> if self.value is not None: <NEW_LINE> <INDENT> json['value'] = self.value <NEW_LINE> <DEDENT> if self.formula is not None: <NEW_LINE> <INDENT> json['formula'] = self.formula <NEW_LINE> <DEDENT> if self.uncertainty is not None: <NEW_LINE> <INDENT> json['uncertainty'] = self.uncertainty.to_json() <NEW_LINE> <DEDENT> return json <NEW_LINE> <DEDENT> def read_json(self, json: dict): <NEW_LINE> <INDENT> super(ImpactFactor, self).read_json(json) <NEW_LINE> val = json.get('flow') <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> self.flow = Ref() <NEW_LINE> self.flow.read_json(val) <NEW_LINE> <DEDENT> val = json.get('location') <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> self.location = Ref() <NEW_LINE> self.location.read_json(val) <NEW_LINE> <DEDENT> val = json.get('flowProperty') <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> self.flow_property = Ref() <NEW_LINE> self.flow_property.read_json(val) <NEW_LINE> <DEDENT> val = json.get('unit') <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> self.unit = Ref() <NEW_LINE> self.unit.read_json(val) <NEW_LINE> <DEDENT> val = json.get('value') <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> self.value = val <NEW_LINE> <DEDENT> val = json.get('formula') <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> self.formula = val <NEW_LINE> <DEDENT> val = json.get('uncertainty') <NEW_LINE> if val is not None: <NEW_LINE> <INDENT> self.uncertainty = Uncertainty() <NEW_LINE> self.uncertainty.read_json(val) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def from_json(json: dict): <NEW_LINE> <INDENT> instance = ImpactFactor() <NEW_LINE> instance.read_json(json) <NEW_LINE> return instance | A single characterisation factor of a LCIA category for a flow.
Attributes
----------
flow: Ref
The [Flow] of the impact assessment factor.
location: Ref
In case of a regionalized impact category, this field can contain the
location for which this factor is valid.
flow_property: Ref
The quantity of the flow to which the LCIA factor is related (e.g.
Mass).
unit: Ref
The flow unit to which the LCIA factor is related (e.g. kg).
value: float
The value of the impact assessment factor.
formula: str
A mathematical formula for calculating the value of the LCIA factor.
uncertainty: Uncertainty
The uncertainty distribution of the factors' value. | 6259903f82261d6c527307f7 |
class ObjectListKeyboardMixin(BaseIntent, APIResponsePaginator): <NEW_LINE> <INDENT> def get_current_page(self): <NEW_LINE> <INDENT> return int(self.chat_data.get('current_page', 1)) <NEW_LINE> <DEDENT> def set_current_page(self, value): <NEW_LINE> <INDENT> self.chat_data['current_page'] = int(value) or 1 <NEW_LINE> <DEDENT> def filter_list(self, lst): <NEW_LINE> <INDENT> return lst <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def format_object(obj): <NEW_LINE> <INDENT> return str(obj) <NEW_LINE> <DEDENT> def get_keyboard(self, column_count=2): <NEW_LINE> <INDENT> if not self.iterable: <NEW_LINE> <INDENT> self.iterable = self.fetch() <NEW_LINE> <DEDENT> buttons, header_buttons, footer_buttons = [], [], [] <NEW_LINE> for obj in self.filter_list(self.iterable): <NEW_LINE> <INDENT> buttons.append( InlineKeyboardButton( self.format_object(obj), callback_data=obj.id or obj.url, ) ) <NEW_LINE> <DEDENT> if self.has_prev_page: <NEW_LINE> <INDENT> footer_buttons.append( InlineKeyboardButton( "<<", callback_data=inftybot.core.constants.PREV_PAGE, ) ) <NEW_LINE> <DEDENT> if self.has_next_page: <NEW_LINE> <INDENT> footer_buttons.append( InlineKeyboardButton( ">>", callback_data=inftybot.core.constants.NEXT_PAGE, ) ) <NEW_LINE> <DEDENT> return build_menu( buttons, column_count, header_buttons=header_buttons, footer_buttons=footer_buttons ) | Mixin is used in ```Intents```.
Handles paginated data retrieved from API | 6259903f96565a6dacd2d8be |
class Change: <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> self.name = name <NEW_LINE> self.old = None <NEW_LINE> self.new = None <NEW_LINE> if CHANGELOG_URLS.get(name): <NEW_LINE> <INDENT> self.url = CHANGELOG_URLS[name] <NEW_LINE> self.link = '[{}]({})'.format(self.name, self.url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.url = '(no changelog)' <NEW_LINE> self.link = self.name <NEW_LINE> <DEDENT> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> if self.old is None: <NEW_LINE> <INDENT> return '- {} new: {} {}'.format(self.name, self.new, self.url) <NEW_LINE> <DEDENT> elif self.new is None: <NEW_LINE> <INDENT> return '- {} removed: {} {}'.format(self.name, self.old, self.url) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '- {} {} -> {} {}'.format(self.name, self.old, self.new, self.url) <NEW_LINE> <DEDENT> <DEDENT> def table_str(self): <NEW_LINE> <INDENT> if self.old is None: <NEW_LINE> <INDENT> return '| {} | -- | {} |'.format(self.link, self.new) <NEW_LINE> <DEDENT> elif self.new is None: <NEW_LINE> <INDENT> return '| {} | {} | -- |'.format(self.link, self.old) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return '| {} | {} | {} |'.format(self.link, self.old, self.new) | A single requirements change from a git diff output. | 6259903fe64d504609df9d05 |
class PageSchema(Schema): <NEW_LINE> <INDENT> title = DublinCoreSchema.title <NEW_LINE> description = DublinCoreSchema.description <NEW_LINE> data = SchemaNode(String(), description="Data for the page") | Get Page fields and Plone-style uber-common DublinCore fields.
__name__ like Plone 'id' generated from Title. | 6259903f63f4b57ef00866a8 |
class StopTrainingHook(TriggeredHook): <NEW_LINE> <INDENT> def __init__(self, trigger): <NEW_LINE> <INDENT> super().__init__(EndTrigger.new(trigger)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def priority(self): <NEW_LINE> <INDENT> return Priority.END <NEW_LINE> <DEDENT> def pre_step(self, trainer): <NEW_LINE> <INDENT> if self.trigger(trainer.iteration, trainer.epoch): <NEW_LINE> <INDENT> print(f'Training ended after {trainer.epoch} epochs and' f' {trainer.iteration} iterations') <NEW_LINE> raise StopTraining | Raises a StopTraining exception if triggered. | 6259903fa4f1c619b294f7bb |
class GFTrace(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def from_trace(cls, tr): <NEW_LINE> <INDENT> return cls(data=tr.ydata.copy(), tmin=tr.tmin, deltat=tr.deltat) <NEW_LINE> <DEDENT> def __init__(self, data=None, itmin=None, deltat=1.0, is_zero=False, begin_value=None, end_value=None, tmin=None): <NEW_LINE> <INDENT> assert sum((x is None) for x in (tmin, itmin)) == 1, 'GFTrace: either tmin or itmin must be given' <NEW_LINE> if tmin is not None: <NEW_LINE> <INDENT> itmin = int(round(tmin / deltat)) <NEW_LINE> if abs(itmin*deltat - tmin) > sampling_check_eps*deltat: <NEW_LINE> <INDENT> raise NotMultipleOfSamplingInterval( 'GFTrace: tmin (%g) is not a multiple of sampling ' 'interval (%g)' % (tmin, deltat)) <NEW_LINE> <DEDENT> <DEDENT> if data is not None: <NEW_LINE> <INDENT> data = num.asarray(data, dtype=gf_dtype) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> data = num.array([], dtype=gf_dtype) <NEW_LINE> begin_value = 0.0 <NEW_LINE> end_value = 0.0 <NEW_LINE> <DEDENT> self.data = data <NEW_LINE> self.itmin = itmin <NEW_LINE> self.deltat = deltat <NEW_LINE> self.is_zero = is_zero <NEW_LINE> self.n_records_stacked = 0. <NEW_LINE> self.t_stack = 0. <NEW_LINE> self.t_optimize = 0. <NEW_LINE> if data is not None and data.size > 0: <NEW_LINE> <INDENT> if begin_value is None: <NEW_LINE> <INDENT> begin_value = data[0] <NEW_LINE> <DEDENT> if end_value is None: <NEW_LINE> <INDENT> end_value = data[-1] <NEW_LINE> <DEDENT> <DEDENT> self.begin_value = begin_value <NEW_LINE> self.end_value = end_value <NEW_LINE> <DEDENT> @property <NEW_LINE> def t(self): <NEW_LINE> <INDENT> return num.linspace( self.itmin*self.deltat, (self.itmin+self.data.size-1)*self.deltat, self.data.size) <NEW_LINE> <DEDENT> def __str__(self, itmin=0): <NEW_LINE> <INDENT> if self.is_zero: <NEW_LINE> <INDENT> return 'ZERO' <NEW_LINE> <DEDENT> s = [] <NEW_LINE> for i in range(itmin, self.itmin + self.data.size): <NEW_LINE> <INDENT> if i >= self.itmin and i < self.itmin + self.data.size: <NEW_LINE> <INDENT> s.append('%7.4g' % self.data[i-self.itmin]) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> s.append(' '*7) <NEW_LINE> <DEDENT> <DEDENT> return '|'.join(s) <NEW_LINE> <DEDENT> def to_trace(self, net, sta, loc, cha): <NEW_LINE> <INDENT> from pyrocko import trace <NEW_LINE> return trace.Trace( net, sta, loc, cha, ydata=self.data, deltat=self.deltat, tmin=self.itmin*self.deltat) | Green's Function trace class for handling traces from the GF Store. | 6259903f0a366e3fb87ddc4d |
class IonException(Exception): <NEW_LINE> <INDENT> pass | Root exception for Ion Python. | 6259903f50485f2cf55dc1eb |
class MessagingManager(object): <NEW_LINE> <INDENT> def __init__(self, client): <NEW_LINE> <INDENT> self.client = client <NEW_LINE> <DEDENT> def list_accounts(self, **kwargs): <NEW_LINE> <INDENT> if 'mask' not in kwargs: <NEW_LINE> <INDENT> items = set([ 'id', 'name', 'status', 'nodes', ]) <NEW_LINE> kwargs['mask'] = "mask[%s]" % ','.join(items) <NEW_LINE> <DEDENT> return self.client['Account'].getMessageQueueAccounts(**kwargs) <NEW_LINE> <DEDENT> def get_endpoint(self, datacenter=None, network=None): <NEW_LINE> <INDENT> if datacenter is None: <NEW_LINE> <INDENT> datacenter = 'dal05' <NEW_LINE> <DEDENT> if network is None: <NEW_LINE> <INDENT> network = 'public' <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> host = ENDPOINTS[datacenter][network] <NEW_LINE> return "https://%s" % host <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise TypeError('Invalid endpoint %s/%s' % (datacenter, network)) <NEW_LINE> <DEDENT> <DEDENT> def get_endpoints(self): <NEW_LINE> <INDENT> return ENDPOINTS <NEW_LINE> <DEDENT> def get_connection(self, account_id, datacenter=None, network=None): <NEW_LINE> <INDENT> if not self.client.auth or not getattr(self.client.auth, 'username', None) or not getattr(self.client.auth, 'api_key', None): <NEW_LINE> <INDENT> raise SoftLayerError( 'Client instance auth must be BasicAuthentication.') <NEW_LINE> <DEDENT> client = MessagingConnection( account_id, endpoint=self.get_endpoint(datacenter, network)) <NEW_LINE> client.authenticate(self.client.auth.username, self.client.auth.api_key) <NEW_LINE> return client <NEW_LINE> <DEDENT> def ping(self, datacenter=None, network=None): <NEW_LINE> <INDENT> resp = requests.get('%s/v1/ping' % self.get_endpoint(datacenter, network)) <NEW_LINE> resp.raise_for_status() <NEW_LINE> return True | Manage SoftLayer Message Queue | 6259903f30c21e258be99a75 |
class PatchRouteFilter(SubResource): <NEW_LINE> <INDENT> _validation = { 'provisioning_state': {'readonly': True}, 'name': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'rules': {'key': 'properties.rules', 'type': '[RouteFilterRule]'}, 'peerings': {'key': 'properties.peerings', 'type': '[ExpressRouteCircuitPeering]'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } <NEW_LINE> def __init__(self, id=None, rules=None, peerings=None, tags=None): <NEW_LINE> <INDENT> super(PatchRouteFilter, self).__init__(id=id) <NEW_LINE> self.rules = rules <NEW_LINE> self.peerings = peerings <NEW_LINE> self.provisioning_state = None <NEW_LINE> self.name = None <NEW_LINE> self.etag = None <NEW_LINE> self.type = None <NEW_LINE> self.tags = tags | Route Filter Resource.
Variables are only populated by the server, and will be ignored when
sending a request.
:param id: Resource ID.
:type id: str
:param rules: Collection of RouteFilterRules contained within a route
filter.
:type rules: list[~azure.mgmt.network.v2017_06_01.models.RouteFilterRule]
:param peerings: A collection of references to express route circuit
peerings.
:type peerings:
list[~azure.mgmt.network.v2017_06_01.models.ExpressRouteCircuitPeering]
:ivar provisioning_state: The provisioning state of the resource. Possible
values are: 'Updating', 'Deleting', 'Succeeded' and 'Failed'.
:vartype provisioning_state: str
:ivar name: The name of the resource that is unique within a resource
group. This name can be used to access the resource.
:vartype name: str
:ivar etag: A unique read-only string that changes whenever the resource
is updated.
:vartype etag: str
:ivar type: Resource type.
:vartype type: str
:param tags: Resource tags.
:type tags: dict[str, str] | 6259903f6fece00bbacccc18 |
class PartialInviteChannel(namedtuple('PartialInviteChannel', 'id name type')): <NEW_LINE> <INDENT> __slots__ = () <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> @property <NEW_LINE> def mention(self): <NEW_LINE> <INDENT> return '<#%s>' % self.id <NEW_LINE> <DEDENT> @property <NEW_LINE> def created_at(self): <NEW_LINE> <INDENT> return snowflake_time(self.id) | Represents a "partial" invite channel.
This model will be given when the user is not part of the
guild the :class:`Invite` resolves to.
.. container:: operations
.. describe:: x == y
Checks if two partial channels are the same.
.. describe:: x != y
Checks if two partial channels are not the same.
.. describe:: hash(x)
Return the partial channel's hash.
.. describe:: str(x)
Returns the partial channel's name.
Attributes
-----------
name: :class:`str`
The partial channel's name.
id: :class:`int`
The partial channel's ID.
type: :class:`ChannelType`
The partial channel's type. | 6259903f30dc7b76659a0a9a |
class TestGebaeude(TestVarnish): <NEW_LINE> <INDENT> def test_gebaude_no_referer(self): <NEW_LINE> <INDENT> payload = {'_id': self.hash()} <NEW_LINE> r = requests.get(self.api_url + '/rest/services/ech/MapServer/ch.bfs.gebaeude_wohnungs_register/490830_0', params=payload) <NEW_LINE> self.assertTrue('geometry' not in r.json()['feature'].keys()) <NEW_LINE> <DEDENT> def test_find_gebaude_no_referer(self): <NEW_LINE> <INDENT> payload = {'layer': 'ch.bfs.gebaeude_wohnungs_register', 'searchText': 'berges', 'searchField': 'strname1', '_id': self.hash()} <NEW_LINE> r = requests.get(self.api_url + '/rest/services/ech/MapServer/find', params=payload) <NEW_LINE> self.assertTrue('geometry' not in r.json()['results'][0].keys()) <NEW_LINE> <DEDENT> def test_gebaude_good_referer(self): <NEW_LINE> <INDENT> payload = {'type': 'location', 'searchText': 'dorf', '_id': self.hash()} <NEW_LINE> headers = {'referer': 'http://unittest.geo.admin.ch'} <NEW_LINE> r = requests.get(self.api_url + '/rest/services/ech/MapServer/ch.bfs.gebaeude_wohnungs_register/490830_0', params=payload, headers=headers) <NEW_LINE> self.assertTrue('geometry' in r.json()['feature'].keys()) <NEW_LINE> <DEDENT> def test_find_gebaude_good_referer(self): <NEW_LINE> <INDENT> payload = {'layer': 'ch.bfs.gebaeude_wohnungs_register', 'searchText': 'berges', 'searchField': 'strname1', '_id': self.hash()} <NEW_LINE> headers = {'referer': 'http://unittest.geo.admin.ch'} <NEW_LINE> r = requests.get(self.api_url + '/rest/services/ech/MapServer/find', params=payload, headers=headers) <NEW_LINE> self.assertTrue('geometry' in r.json()['results'][0].keys()) | Results with layer 'ch.bfs.gebaeude_wohnungs_register' should never return a geometry
for invalid referers
See https://github.com/geoadmin/mf-chsdi3/issues/886 | 6259903f07f4c71912bb069a |
class Network(object): <NEW_LINE> <INDENT> __type = {1: 'region', 2:'nationwide', 3: 'temporary',4: 'other'} <NEW_LINE> def __init__(self, name, ntype): <NEW_LINE> <INDENT> self.ntype=ntype <NEW_LINE> self._name=name <NEW_LINE> self.sta_list = [] <NEW_LINE> self.sta_table = [] <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> print('%s type network %s, which include %d stations'%(self._ntype,self._name,len(self.sta_list))) <NEW_LINE> return "====Network Print by BACGS====" <NEW_LINE> <DEDENT> @property <NEW_LINE> def ntype(self): <NEW_LINE> <INDENT> return self._ntype <NEW_LINE> <DEDENT> @ntype.setter <NEW_LINE> def ntype(self, value): <NEW_LINE> <INDENT> if isinstance(value, float): <NEW_LINE> <INDENT> raise ValueError('Network type cannot be an float!') <NEW_LINE> <DEDENT> if isinstance(value, int): <NEW_LINE> <INDENT> if value < 1 or value > 4: <NEW_LINE> <INDENT> raise ValueError('Network type should be 1-4!') <NEW_LINE> <DEDENT> self._ntype = self.__type[value] <NEW_LINE> <DEDENT> elif isinstance(value, str): <NEW_LINE> <INDENT> list(self.__type.values()).index(value.lower()) <NEW_LINE> self._ntype = value.lower() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Network type wrong!!!') <NEW_LINE> <DEDENT> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> def add_station(self,sta): <NEW_LINE> <INDENT> if not isinstance(sta, Station): <NEW_LINE> <INDENT> raise ValueError('Input data type must be a Station!') <NEW_LINE> <DEDENT> self.sta_list.append(sta) <NEW_LINE> <DEDENT> def read_pnts(self, filename): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> fh = open(filename, 'r') <NEW_LINE> i = 0 <NEW_LINE> for line in fh: <NEW_LINE> <INDENT> i += 1 <NEW_LINE> line = line.strip() <NEW_LINE> if (not line) or (line[0] == '/') or (line[0] == '#'): continue <NEW_LINE> if (line[0:5] == '99999') or (line[0:5] == '66666'): break <NEW_LINE> vals=line.split() <NEW_LINE> self.sta_table.append(vals) <NEW_LINE> self.add_station(Station(vals[1],vals[0],1,float(vals[3]), float(vals[2]),float(vals[4]))) <NEW_LINE> <DEDENT> <DEDENT> except IOError: <NEW_LINE> <INDENT> print('No file : %s' %(filename)) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> print('Reading at line %d : check raw data file'%(i)) <NEW_LINE> <DEDENT> except IndexError: <NEW_LINE> <INDENT> print('Reading at line %d : check raw data file: possibly last line?'%(i)) | Gravity Network Configure
Properties:
functions:
-
| 6259903f1d351010ab8f4d86 |
class TestCommandSensorBinarySensor(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.hass = get_test_home_assistant() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> self.hass.stop() <NEW_LINE> <DEDENT> def test_setup(self): <NEW_LINE> <INDENT> config = { "name": "Test", "command": "echo 1", "payload_on": "1", "payload_off": "0", "command_timeout": 15, } <NEW_LINE> devices = [] <NEW_LINE> def add_dev_callback(devs, update): <NEW_LINE> <INDENT> for dev in devs: <NEW_LINE> <INDENT> devices.append(dev) <NEW_LINE> <DEDENT> <DEDENT> command_line.setup_platform(self.hass, config, add_dev_callback) <NEW_LINE> assert 1 == len(devices) <NEW_LINE> entity = devices[0] <NEW_LINE> entity.update() <NEW_LINE> assert "Test" == entity.name <NEW_LINE> assert STATE_ON == entity.state <NEW_LINE> <DEDENT> def test_template(self): <NEW_LINE> <INDENT> data = command_line.CommandSensorData(self.hass, "echo 10", 15) <NEW_LINE> entity = command_line.CommandBinarySensor( self.hass, data, "test", None, "1.0", "0", template.Template("{{ value | multiply(0.1) }}", self.hass), ) <NEW_LINE> entity.update() <NEW_LINE> assert STATE_ON == entity.state <NEW_LINE> <DEDENT> def test_sensor_off(self): <NEW_LINE> <INDENT> data = command_line.CommandSensorData(self.hass, "echo 0", 15) <NEW_LINE> entity = command_line.CommandBinarySensor( self.hass, data, "test", None, "1", "0", None ) <NEW_LINE> entity.update() <NEW_LINE> assert STATE_OFF == entity.state | Test the Command line Binary sensor. | 6259903fe76e3b2f99fd9c74 |
class GitHubEventSubscriptionResource(MethodView): <NEW_LINE> <INDENT> decorators = [github_verification_required] <NEW_LINE> def post(self): <NEW_LINE> <INDENT> data = request.json <NEW_LINE> logger.info("Received GitHub event", extra={"request_json": data}) <NEW_LINE> event_type = request.headers.get("X-GitHub-Event", None) <NEW_LINE> if not event_type: <NEW_LINE> <INDENT> raise UnverifiedWebhookRequest("Missing GitHub event type") <NEW_LINE> <DEDENT> result = process_github_event_subscription(event_type, data) <NEW_LINE> return jsonify(result) | Callback endpoint for GitHub event subscriptions | 6259903f63b5f9789fe863d4 |
class DBDecoratorsTestCase(TestCase): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def setUpClass(cls): <NEW_LINE> <INDENT> cls.orm = ORM.get() <NEW_LINE> <DEDENT> def test_sqlalchemy_session(self): <NEW_LINE> <INDENT> session = self.orm.sessionmaker() <NEW_LINE> self.assertEqual(passthrough(session=session), session) <NEW_LINE> self.orm.sessionmaker_remove() <NEW_LINE> self.assertIsNotNone(passthrough()) <NEW_LINE> self.assertNotEqual(passthrough(), session) <NEW_LINE> self.assertEqual(passthrough.__doc__, 'Test docstring.') | Tests :mod:`baph.decorators.db`. | 6259903fd53ae8145f9196c4 |
@dataclass(frozen=True) <NEW_LINE> class Credentials: <NEW_LINE> <INDENT> access_token: str <NEW_LINE> token_expiry: int <NEW_LINE> token_type: str <NEW_LINE> refresh_token: str <NEW_LINE> userid: int <NEW_LINE> client_id: str <NEW_LINE> consumer_secret: str | Credentials. | 6259903f21bff66bcd723ed2 |
class Actor: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self._description = "" <NEW_LINE> self._text = "" <NEW_LINE> self._position = Point(0, 0) <NEW_LINE> self._velocity = Point(0, 0) <NEW_LINE> <DEDENT> def get_position(self): <NEW_LINE> <INDENT> return self._position <NEW_LINE> <DEDENT> def get_text(self): <NEW_LINE> <INDENT> return self._text <NEW_LINE> <DEDENT> def get_velocity(self): <NEW_LINE> <INDENT> return self._velocity <NEW_LINE> <DEDENT> def set_position(self, position): <NEW_LINE> <INDENT> self._position = position <NEW_LINE> <DEDENT> def set_text(self, text): <NEW_LINE> <INDENT> self._text = text <NEW_LINE> <DEDENT> def set_velocity(self, velocity): <NEW_LINE> <INDENT> self._velocity = velocity | A visible, movable thing that participates in the game. The responsibility of Actor is to keep track of its appearance, position
and velocity in 2d space.
Stereotype:
Information Holder
Attributes:
_tag (string): The actor's tag.
_text (string): The textual representation of the actor.
_position (Point): The actor's position in 2d space.
_velocity (Point): The actor's speed and direction. | 6259903fd99f1b3c44d06905 |
class Crateify( object ): <NEW_LINE> <INDENT> def __init__( self, readfn=pycrates.read_file ): <NEW_LINE> <INDENT> self.reader = readfn <NEW_LINE> <DEDENT> def __call__( self, tool ): <NEW_LINE> <INDENT> def write_read_crate( mycmd, mycrate, **kwargs ): <NEW_LINE> <INDENT> import tempfile <NEW_LINE> try: <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile() as outfile: <NEW_LINE> <INDENT> with tempfile.NamedTemporaryFile() as infile: <NEW_LINE> <INDENT> mycrate.write( infile.name, clobber=True ) <NEW_LINE> tool( mycmd, infile.name, outfile.name, **kwargs ) <NEW_LINE> newcrate = self.reader( outfile.name ) <NEW_LINE> return newcrate <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> except Exception as E: <NEW_LINE> <INDENT> print(E) <NEW_LINE> raise E <NEW_LINE> <DEDENT> <DEDENT> return write_read_crate | A decorator to make tools seem "crate-aware"
The CIAO tools require files to work, but when in python
and reading file into crates means that a lot of the CIAO
functionaltiy is hard to access since it requires
writing the crate out, running the tool, then
reading the file back in.
This decorator can be used to do just this.
Example:
@Crateify()
def bin_to_image( bincmd, infile, outfile )
bincmd(infile=infile+"[bin sky=1]", outfile=outfile, clobber=True)
from ciao_contriub.runtool import dmcopy
tab = read_file("evt.fits")
img = bin_to_image(dmcopy, tab)
| 6259903fcad5886f8bdc59b1 |
class WeatherEntity(Entity): <NEW_LINE> <INDENT> @property <NEW_LINE> def temperature(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def temperature_unit(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def pressure(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def humidity(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> @property <NEW_LINE> def wind_speed(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def wind_bearing(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def ozone(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def attribution(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def forecast(self): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> @property <NEW_LINE> def state_attributes(self): <NEW_LINE> <INDENT> data = { ATTR_WEATHER_TEMPERATURE: self._temp_for_display(self.temperature), ATTR_WEATHER_HUMIDITY: self.humidity, } <NEW_LINE> ozone = self.ozone <NEW_LINE> if ozone is not None: <NEW_LINE> <INDENT> data[ATTR_WEATHER_OZONE] = ozone <NEW_LINE> <DEDENT> pressure = self.pressure <NEW_LINE> if pressure is not None: <NEW_LINE> <INDENT> data[ATTR_WEATHER_PRESSURE] = pressure <NEW_LINE> <DEDENT> wind_bearing = self.wind_bearing <NEW_LINE> if wind_bearing is not None: <NEW_LINE> <INDENT> data[ATTR_WEATHER_WIND_BEARING] = wind_bearing <NEW_LINE> <DEDENT> wind_speed = self.wind_speed <NEW_LINE> if wind_speed is not None: <NEW_LINE> <INDENT> data[ATTR_WEATHER_WIND_SPEED] = wind_speed <NEW_LINE> <DEDENT> attribution = self.attribution <NEW_LINE> if attribution is not None: <NEW_LINE> <INDENT> data[ATTR_WEATHER_ATTRIBUTION] = attribution <NEW_LINE> <DEDENT> if self.forecast is not None: <NEW_LINE> <INDENT> forecast = [] <NEW_LINE> for forecast_entry in self.forecast: <NEW_LINE> <INDENT> forecast_entry = dict(forecast_entry) <NEW_LINE> forecast_entry[ATTR_FORECAST_TEMP] = self._temp_for_display( forecast_entry[ATTR_FORECAST_TEMP]) <NEW_LINE> forecast.append(forecast_entry) <NEW_LINE> <DEDENT> data[ATTR_FORECAST] = forecast <NEW_LINE> <DEDENT> return data <NEW_LINE> <DEDENT> @property <NEW_LINE> def state(self): <NEW_LINE> <INDENT> return self.condition <NEW_LINE> <DEDENT> @property <NEW_LINE> def condition(self): <NEW_LINE> <INDENT> raise NotImplementedError() <NEW_LINE> <DEDENT> def _temp_for_display(self, temp): <NEW_LINE> <INDENT> unit = self.temperature_unit <NEW_LINE> hass_unit = self.hass.config.units.temperature_unit <NEW_LINE> if (temp is None or not isinstance(temp, Number) or unit == hass_unit): <NEW_LINE> <INDENT> return temp <NEW_LINE> <DEDENT> value = convert_temperature(temp, unit, hass_unit) <NEW_LINE> if hass_unit == TEMP_CELSIUS: <NEW_LINE> <INDENT> return round(value, 1) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return round(value) | ABC for a weather data. | 6259903f66673b3332c31661 |
class ShootSearch(object): <NEW_LINE> <INDENT> MAX_STEP = 5000 <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self.strat = ShootExpe() <NEW_LINE> team1 = SoccerTeam("test") <NEW_LINE> team1.add("Salah",IntelligentStrategy()) <NEW_LINE> team1.add("Brahimi",IntelligentStrategy()) <NEW_LINE> team2 = SoccerTeam("test2") <NEW_LINE> team2.add("Warda",MyDefenseStrategy()) <NEW_LINE> self.simu = Simulation(team1,team2,max_steps=1000000) <NEW_LINE> self.simu.listeners+=self <NEW_LINE> self.discr_step = 10 <NEW_LINE> self.nb_essais = 10 <NEW_LINE> <DEDENT> def start(self,visu=True): <NEW_LINE> <INDENT> if visu : <NEW_LINE> <INDENT> show_simu(self.simu) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.simu.start() <NEW_LINE> <DEDENT> <DEDENT> def begin_match(self,team1,team2,state): <NEW_LINE> <INDENT> self.res = dict() <NEW_LINE> self.last = 0 <NEW_LINE> self.but = 0 <NEW_LINE> self.cpt = 0 <NEW_LINE> self.params = [x for x in np.linspace(1,settings.maxPlayerShoot,self.discr_step)] <NEW_LINE> self.idx=0 <NEW_LINE> <DEDENT> def begin_round(self,team1,team2,state): <NEW_LINE> <INDENT> position = Vector2D(np.random.random()*settings.GAME_WIDTH/2.+settings.GAME_WIDTH/2.,np.random.random()*settings.GAME_HEIGHT) <NEW_LINE> self.simu.state.states[(1,0)].position = Vector2D(0,75) <NEW_LINE> self.simu.state.states[(1,1)].position =Vector2D(0,20) <NEW_LINE> self.simu.state.states[(1,0)].vitesse = Vector2D() <NEW_LINE> self.simu.state.ball.position = Vector2D(20,45) <NEW_LINE> self.strat.norm = self.params[self.idx] <NEW_LINE> self.last = self.simu.step <NEW_LINE> <DEDENT> def update_round(self,team1,team2,state): <NEW_LINE> <INDENT> if state.step>self.last+self.MAX_STEP: <NEW_LINE> <INDENT> self.simu.end_round() <NEW_LINE> <DEDENT> <DEDENT> def end_round(self,team1,team2,state): <NEW_LINE> <INDENT> if state.goal>0: <NEW_LINE> <INDENT> self.but+=1 <NEW_LINE> <DEDENT> self.cpt+=1 <NEW_LINE> if self.cpt>=self.nb_essais: <NEW_LINE> <INDENT> self.res[self.params[self.idx]] = self.but*1./self.cpt <NEW_LINE> logger.debug("parametre %s : %f" %((str(self.params[self.idx]),self.res[self.params[self.idx]]))) <NEW_LINE> self.idx+=1 <NEW_LINE> self.but=0 <NEW_LINE> self.cpt=0 <NEW_LINE> <DEDENT> """ si plus de parametre, fin du match""" <NEW_LINE> if self.idx>=len(self.params): <NEW_LINE> <INDENT> self.simu.end_match() | nombre d'iterations maximales jusqu'a l'arret d'un round
discr_step : pas de discretisation du parametre
nb_essais : nombre d'essais par parametre | 6259903f24f1403a92686201 |
class Redactor(RequiredConfig): <NEW_LINE> <INDENT> required_config = Namespace() <NEW_LINE> required_config.add_option( name="forbidden_keys", doc="a list of keys not allowed in a redacted processed crash", default=( "url, exploitability," "json_dump.sensitive," "upload_file_minidump_flash1.json_dump.sensitive," "upload_file_minidump_flash2.json_dump.sensitive," "upload_file_minidump_browser.json_dump.sensitive," "memory_info" ), reference_value_from="resource.redactor", ) <NEW_LINE> def __init__(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.forbidden_keys = [x.strip() for x in self.config.forbidden_keys.split(",")] <NEW_LINE> <DEDENT> def redact(self, a_mapping): <NEW_LINE> <INDENT> for a_key in self.forbidden_keys: <NEW_LINE> <INDENT> sub_mapping = a_mapping <NEW_LINE> sub_keys = a_key.split(".") <NEW_LINE> try: <NEW_LINE> <INDENT> for a_sub_key in sub_keys[:-1]: <NEW_LINE> <INDENT> sub_mapping = sub_mapping[a_sub_key.strip()] <NEW_LINE> <DEDENT> del sub_mapping[sub_keys[-1]] <NEW_LINE> <DEDENT> except (AttributeError, KeyError): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __call__(self, a_mapping): <NEW_LINE> <INDENT> self.redact(a_mapping) | This class is the implementation of a functor for in situ redacting
of sensitive keys from a mapping. Keys that are to be redacted are placed
in the configuration under the name 'forbidden_keys'. They may take the
form of dotted keys with subkeys. For example, "a.b.c" means that the key,
"c" is to be redacted. | 6259903f21a7993f00c671d7 |
class AVGenerator(keras.utils.Sequence): <NEW_LINE> <INDENT> def __init__(self, filename, database_dir_path, X1dim=(298, 257, 2), X2dim=(75, 1, 1792, 2), ydim=(298, 257, 2, 2), batch_size=4, shuffle=True): <NEW_LINE> <INDENT> self.filename = filename <NEW_LINE> self.X1dim = X1dim <NEW_LINE> self.X2dim = X2dim <NEW_LINE> self.ydim = ydim <NEW_LINE> self.batch_size = batch_size <NEW_LINE> self.shuffle = shuffle <NEW_LINE> self.on_epoch_end() <NEW_LINE> self.database_dir_path = database_dir_path <NEW_LINE> <DEDENT> def __len__(self): <NEW_LINE> <INDENT> return int(np.floor(len(self.filename) / self.batch_size)) <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] <NEW_LINE> filename_temp = [self.filename[k] for k in indexes] <NEW_LINE> [X1, X2], y = self.__data_generation(filename_temp) <NEW_LINE> return [X1, X2], y <NEW_LINE> <DEDENT> def on_epoch_end(self): <NEW_LINE> <INDENT> self.indexes = np.arange(len(self.filename)) <NEW_LINE> if self.shuffle: <NEW_LINE> <INDENT> np.random.shuffle(self.indexes) <NEW_LINE> <DEDENT> <DEDENT> def __data_generation(self, filename_temp): <NEW_LINE> <INDENT> X1 = np.empty((self.batch_size, *self.X1dim)) <NEW_LINE> X2 = np.empty((self.batch_size, *self.X2dim)) <NEW_LINE> y = np.empty((self.batch_size, *self.ydim)) <NEW_LINE> for i, ID in enumerate(filename_temp): <NEW_LINE> <INDENT> info = ID.strip().split(' ') <NEW_LINE> X1[i, ] = np.load(self.database_dir_path+'audio/AV_model_database/mix/' + info[0]) <NEW_LINE> for j in range(2): <NEW_LINE> <INDENT> y[i, :, :, :, j] = np.load(self.database_dir_path+'audio/AV_model_database/crm/' + info[j + 1]) <NEW_LINE> X2[i, :, :, :, j] = np.load(self.database_dir_path+'video/face_emb/' + info[j + 3]) <NEW_LINE> <DEDENT> <DEDENT> return [X1, X2], y | Generates data for Keras | 6259903fdc8b845886d54820 |
class TriangularLatticeEmbedding(Embedding): <NEW_LINE> <INDENT> def __init__(self, c: SimplicialComplex, h: float = 1.0, w: float = 1.0): <NEW_LINE> <INDENT> super(TriangularLatticeEmbedding, self).__init__(c, 2) <NEW_LINE> self._height = h <NEW_LINE> self._width = w <NEW_LINE> <DEDENT> def height(self) -> float: <NEW_LINE> <INDENT> return self._height <NEW_LINE> <DEDENT> def width(self) -> float: <NEW_LINE> <INDENT> return self._width <NEW_LINE> <DEDENT> def computePositionOf(self, s: Simplex) -> List[float]: <NEW_LINE> <INDENT> c = self.complex() <NEW_LINE> n = c.indexOf(s) <NEW_LINE> nr = c.rows() <NEW_LINE> nc = c.columns() <NEW_LINE> i = int(n / c.columns()) <NEW_LINE> j = n % c.columns() <NEW_LINE> rh = (self.height() + 0.0) / nr <NEW_LINE> cw = (self.width() + 0.0) / (2 * nc) <NEW_LINE> y = self.height() - rh * i <NEW_LINE> if i % 2 == 0: <NEW_LINE> <INDENT> x = cw * (j * 2) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> x = cw * ((j * 2) + 1) <NEW_LINE> <DEDENT> return [x, y] | A regular embedding of a triangular lattice into a plane. The default is
to embed into a unit plane, but this can be scaled as required. The lattice
can be distorted by providing explicit positions for 0-simplices as required.
:param c: the complex
:param h: height of the plane (defaults to 1.0)
:param w: width of the plane (defaults to 1.0) | 6259903f287bf620b6272e56 |
class string_string_dict_t(object): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> this = _uhd_swig.new_string_string_dict_t() <NEW_LINE> try: self.this.append(this) <NEW_LINE> except: self.this = this <NEW_LINE> <DEDENT> def size(self): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t_size(self) <NEW_LINE> <DEDENT> def keys(self): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t_keys(self) <NEW_LINE> <DEDENT> def vals(self): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t_vals(self) <NEW_LINE> <DEDENT> def has_key(self, *args, **kwargs): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t_has_key(self, *args, **kwargs) <NEW_LINE> <DEDENT> def get(self, *args): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t_get(self, *args) <NEW_LINE> <DEDENT> def set(self, *args, **kwargs): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t_set(self, *args, **kwargs) <NEW_LINE> <DEDENT> def pop(self, *args, **kwargs): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t_pop(self, *args, **kwargs) <NEW_LINE> <DEDENT> def __getitem__(self, *args, **kwargs): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t___getitem__(self, *args, **kwargs) <NEW_LINE> <DEDENT> def __setitem__(self, *args, **kwargs): <NEW_LINE> <INDENT> return _uhd_swig.string_string_dict_t___setitem__(self, *args, **kwargs) <NEW_LINE> <DEDENT> __swig_destroy__ = _uhd_swig.delete_string_string_dict_t <NEW_LINE> __del__ = lambda self : None; | Proxy of C++ uhd::dict<(std::string,std::string)> class | 6259903fa4f1c619b294f7bc |
class Wrapper(environment.Base): <NEW_LINE> <INDENT> def __init__(self, env, pixels_only=True, render_kwargs=None, observation_key='pixels'): <NEW_LINE> <INDENT> if render_kwargs is None: <NEW_LINE> <INDENT> render_kwargs = {} <NEW_LINE> <DEDENT> wrapped_observation_spec = env.observation_spec() <NEW_LINE> if isinstance(wrapped_observation_spec, specs.ArraySpec): <NEW_LINE> <INDENT> self._observation_is_dict = False <NEW_LINE> invalid_keys = set([STATE_KEY]) <NEW_LINE> <DEDENT> elif isinstance(wrapped_observation_spec, collections.MutableMapping): <NEW_LINE> <INDENT> self._observation_is_dict = True <NEW_LINE> invalid_keys = set(wrapped_observation_spec.keys()) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise ValueError('Unsupported observation spec structure.') <NEW_LINE> <DEDENT> if not pixels_only and observation_key in invalid_keys: <NEW_LINE> <INDENT> raise ValueError('Duplicate or reserved observation key {!r}.' .format(observation_key)) <NEW_LINE> <DEDENT> if pixels_only: <NEW_LINE> <INDENT> self._observation_spec = collections.OrderedDict() <NEW_LINE> <DEDENT> elif self._observation_is_dict: <NEW_LINE> <INDENT> self._observation_spec = wrapped_observation_spec.copy() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._observation_spec = collections.OrderedDict() <NEW_LINE> self._observation_spec[STATE_KEY] = wrapped_observation_spec <NEW_LINE> <DEDENT> pixels = env.physics.render(**render_kwargs) <NEW_LINE> pixels_spec = specs.ArraySpec( shape=pixels.shape, dtype=pixels.dtype, name=observation_key) <NEW_LINE> self._observation_spec[observation_key] = pixels_spec <NEW_LINE> self._env = env <NEW_LINE> self._pixels_only = pixels_only <NEW_LINE> self._render_kwargs = render_kwargs <NEW_LINE> self._observation_key = observation_key <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> time_step = self._env.reset() <NEW_LINE> return self._add_pixel_observation(time_step) <NEW_LINE> <DEDENT> def step(self, action): <NEW_LINE> <INDENT> time_step = self._env.step(action) <NEW_LINE> return self._add_pixel_observation(time_step) <NEW_LINE> <DEDENT> def observation_spec(self): <NEW_LINE> <INDENT> return self._observation_spec <NEW_LINE> <DEDENT> def action_spec(self): <NEW_LINE> <INDENT> return self._env.action_spec() <NEW_LINE> <DEDENT> def _add_pixel_observation(self, time_step): <NEW_LINE> <INDENT> if self._pixels_only: <NEW_LINE> <INDENT> observation = collections.OrderedDict() <NEW_LINE> <DEDENT> elif self._observation_is_dict: <NEW_LINE> <INDENT> observation = type(time_step.observation)(time_step.observation) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> observation = collections.OrderedDict() <NEW_LINE> observation[STATE_KEY] = time_step.observation <NEW_LINE> <DEDENT> pixels = self._env.physics.render(**self._render_kwargs) <NEW_LINE> observation[self._observation_key] = pixels <NEW_LINE> return time_step._replace(observation=observation) <NEW_LINE> <DEDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> return getattr(self._env, name) | Wraps a control environment and adds a rendered pixel observation. | 6259903f50485f2cf55dc1ed |
class TestWiresUtilization(mixin_use_new_instance.UseNewInstanceMixin, mixin_test_usage.TestWiresUsageMixin, unittest.TestCase): <NEW_LINE> <INDENT> pass | Utilization tests for the Wires instances. | 6259903f004d5f362081f919 |
class AdminLoginPage(login_base.LoginPageBase): <NEW_LINE> <INDENT> _location = location <NEW_LINE> def login_user(self, username, password, domain=None): <NEW_LINE> <INDENT> self.fill_form_values(username=username, password=password, domain=domain) <NEW_LINE> try: <NEW_LINE> <INDENT> home_page = admin_home.AdminHomePage(self.driver) <NEW_LINE> <DEDENT> except excepts.InitPageValidationError as ex: <NEW_LINE> <INDENT> self._proceed_login_error() <NEW_LINE> raise ex <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return home_page | Login page abstraction class.
Parameters
----------
* _location - initial URL to load upon instance creation | 6259903fb5575c28eb7135fe |
class DummyClass(object): <NEW_LINE> <INDENT> text = "0003970-140910143529206" <NEW_LINE> status_code = 201 | A dummy response as given by the requests.post, which can be used
to mock the posting of requests | 6259903f6fece00bbacccc1a |
class Group(models.Model): <NEW_LINE> <INDENT> class Meta(object): <NEW_LINE> <INDENT> verbose_name = u"Група" <NEW_LINE> verbose_name_plural = u"Групи" <NEW_LINE> <DEDENT> title = models.CharField( max_length=256, blank=False, verbose_name=u"Назва") <NEW_LINE> leader = models.OneToOneField( 'students.Student', verbose_name=u"Староста", blank=True, null=True, on_delete=models.SET_NULL) <NEW_LINE> notes = models.TextField( blank=True, verbose_name=u"Додаткові нотатки") <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> if self.leader: <NEW_LINE> <INDENT> return u"%s (%s %s)" % ( self.title, self.leader.first_name, self.leader.last_name) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return u"%s" % (self.title,) | Group Model | 6259903fd99f1b3c44d06906 |
class SeatMap(object): <NEW_LINE> <INDENT> def __init__(self, static_url=None): <NEW_LINE> <INDENT> self.swagger_types = { 'static_url': 'str' } <NEW_LINE> self.attribute_map = { 'static_url': 'staticUrl' } <NEW_LINE> self._static_url = static_url <NEW_LINE> <DEDENT> @property <NEW_LINE> def static_url(self): <NEW_LINE> <INDENT> return self._static_url <NEW_LINE> <DEDENT> @static_url.setter <NEW_LINE> def static_url(self, static_url): <NEW_LINE> <INDENT> self._static_url = static_url <NEW_LINE> <DEDENT> def to_dict(self): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for attr, _ in iteritems(self.swagger_types): <NEW_LINE> <INDENT> value = getattr(self, attr) <NEW_LINE> if isinstance(value, list): <NEW_LINE> <INDENT> result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) <NEW_LINE> <DEDENT> elif hasattr(value, "to_dict"): <NEW_LINE> <INDENT> result[attr] = value.to_dict() <NEW_LINE> <DEDENT> elif isinstance(value, dict): <NEW_LINE> <INDENT> result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[attr] = value <NEW_LINE> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> def to_str(self): <NEW_LINE> <INDENT> return pformat(self.to_dict()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.to_str() <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if not isinstance(other, SeatMap): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not self == other | NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually. | 6259903f73bcbd0ca4bcb4f5 |
class AnsiblePlaybookAPI(object): <NEW_LINE> <INDENT> def __init__(self, playbook, extra_vars={}): <NEW_LINE> <INDENT> self.stats = callbacks.AggregateStats() <NEW_LINE> self.playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY) <NEW_LINE> self.extra_vars = extra_vars <NEW_LINE> self.playbook = playbook <NEW_LINE> self.setbook = self.book_set() <NEW_LINE> <DEDENT> def book_set(self): <NEW_LINE> <INDENT> runner_cb = callbacks.PlaybookRunnerCallbacks(self.stats, verbose=2) <NEW_LINE> self.pb = ansible.playbook.PlayBook( playbook=self.playbook, stats=self.stats, extra_vars=self.extra_vars, callbacks=self.playbook_cb, runner_callbacks=runner_cb ) <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> simple = self.pb.run() <NEW_LINE> with open('/tmp/ansible/ansible.log.tmp', 'r') as f: <NEW_LINE> <INDENT> detail = f.read() <NEW_LINE> <DEDENT> with open('/tmp/ansible/ansible.log.tmp', 'w') as f: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return {'simple': simple, 'detail': detail} | 1.9.x 上通过测试 | 6259903fd10714528d69efc1 |
class ChangeState_Response(metaclass=Metaclass): <NEW_LINE> <INDENT> __slots__ = [ '_success', ] <NEW_LINE> def __init__(self, **kwargs): <NEW_LINE> <INDENT> assert all(['_' + key in self.__slots__ for key in kwargs.keys()]), 'Invalid arguments passed to constructor: %r' % kwargs.keys() <NEW_LINE> self.success = kwargs.get('success', bool()) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> typename = self.__class__.__module__.split('.') <NEW_LINE> typename.pop() <NEW_LINE> typename.append(self.__class__.__name__) <NEW_LINE> args = [s[1:] + '=' + repr(getattr(self, s, None)) for s in self.__slots__] <NEW_LINE> return '%s(%s)' % ('.'.join(typename), ', '.join(args)) <NEW_LINE> <DEDENT> @property <NEW_LINE> def success(self): <NEW_LINE> <INDENT> return self._success <NEW_LINE> <DEDENT> @success.setter <NEW_LINE> def success(self, value): <NEW_LINE> <INDENT> assert isinstance(value, bool), "The 'success' field must of type 'bool'" <NEW_LINE> self._success = value | Message class 'ChangeState_Response'. | 6259903f097d151d1a2c22d0 |
class SortedFilter(VectorFilter): <NEW_LINE> <INDENT> def __call__(self, distances): <NEW_LINE> <INDENT> return np.argsort(distances) | Sorts vectors with respect to distance. | 6259903f66673b3332c31663 |
class Configuration(object): <NEW_LINE> <INDENT> array_serialization = "indexed" <NEW_LINE> base_uri = 'https://api.mundipagg.com/core/v1' <NEW_LINE> basic_auth_user_name = None <NEW_LINE> basic_auth_password = None | A class used for configuring the SDK by a user.
This class need not be instantiated and all properties and methods
are accessible without instance creation. | 6259903f96565a6dacd2d8c0 |
class Payment: <NEW_LINE> <INDENT> def __init__(self, app, wallet, allowed_methods=None, zeroconf=False, sync_period=600, endpoint='/payment', db_dir=None, username=None): <NEW_LINE> <INDENT> if allowed_methods is None: <NEW_LINE> <INDENT> self.allowed_methods = [ PaymentChannel(*flask_channel_adapter(app, PaymentServer( wallet, zeroconf=zeroconf, sync_period=sync_period, db_dir=db_dir ), endpoint=endpoint)), OnChain(wallet, db_dir=db_dir), BitTransfer(wallet, username=username) ] <NEW_LINE> self.allowed_methods[0].server.sync() <NEW_LINE> <DEDENT> <DEDENT> def required(self, price, **kwargs): <NEW_LINE> <INDENT> def decorator(fn): <NEW_LINE> <INDENT> @wraps(fn) <NEW_LINE> def _fn(*fn_args, **fn_kwargs): <NEW_LINE> <INDENT> nonlocal price <NEW_LINE> _price = price(request) if callable(price) else price <NEW_LINE> if 'server_url' not in kwargs: <NEW_LINE> <INDENT> url = urlparse(request.url_root) <NEW_LINE> kwargs.update({'server_url': url.scheme + '://' + url.netloc}) <NEW_LINE> <DEDENT> if _price == 0 or self.is_valid_payment(_price, request.headers, **kwargs): <NEW_LINE> <INDENT> return fn(*fn_args, **fn_kwargs) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> payment_headers = {} <NEW_LINE> for method in self.allowed_methods: <NEW_LINE> <INDENT> payment_headers.update(method.get_402_headers(_price, **kwargs)) <NEW_LINE> <DEDENT> raise PaymentRequiredException(payment_headers) <NEW_LINE> <DEDENT> <DEDENT> return _fn <NEW_LINE> <DEDENT> return decorator <NEW_LINE> <DEDENT> def is_valid_payment(self, price, request_headers, **kwargs): <NEW_LINE> <INDENT> for method in self.allowed_methods: <NEW_LINE> <INDENT> if method.should_redeem(request_headers): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> v = method.redeem_payment(price, request_headers, **kwargs) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> return Response(str(e), BAD_REQUEST) <NEW_LINE> <DEDENT> return v <NEW_LINE> <DEDENT> <DEDENT> return False | Class to store merchant settings. | 6259903fec188e330fdf9b05 |
class RegexTag(object): <NEW_LINE> <INDENT> def __init__(self, regextag, *args): <NEW_LINE> <INDENT> if regextag.text == None: <NEW_LINE> <INDENT> raise ValueError( 'Required tag content missing: {0}' .format(regextag.tag)) <NEW_LINE> <DEDENT> self.regex = re.compile(regextag.text, *args) <NEW_LINE> self.sense = (re.match(r'(1|true|yes)$', regextag.get('sense', default='1'), re.IGNORECASE) != None) <NEW_LINE> <DEDENT> def match(self, text): <NEW_LINE> <INDENT> if self.sense: <NEW_LINE> <INDENT> return (self.regex.match(text) != None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.regex.match(text) == None) <NEW_LINE> <DEDENT> <DEDENT> def search(self, text): <NEW_LINE> <INDENT> if self.sense: <NEW_LINE> <INDENT> return (self.regex.search(text) != None) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (self.regex.search(text) == None) | Regular Expression Tag Class
Evaluate text against regular expression details provided by a
hook configuration XML tag. | 6259903f50485f2cf55dc1ef |
class SurveyUnpublishEvent(ObjectEvent): <NEW_LINE> <INDENT> implements(ISurveyUnpublishEvent) | A survey is being removed from the client. | 6259903fd99f1b3c44d06908 |
class QueueAsyncDriver(QueueContract, BaseDriver): <NEW_LINE> <INDENT> def __init__(self, Container): <NEW_LINE> <INDENT> self.container = Container <NEW_LINE> <DEDENT> def push(self, *objects): <NEW_LINE> <INDENT> for obj in objects: <NEW_LINE> <INDENT> obj = self.container.resolve(obj) <NEW_LINE> thread = threading.Thread( target=obj.dispatch(), args=(), kwargs={}) <NEW_LINE> thread.start() | Queue Aysnc Driver
| 6259903fd53ae8145f9196c8 |
class AuthenticatorAddView(PermissionRequiredMixin, Fido2RegistrationView): <NEW_LINE> <INDENT> permission_required = 'django_fido.add_authenticator' <NEW_LINE> form_class = Fido2RegistrationAdminForm <NEW_LINE> template_name = 'django_fido/add_authenticator.html' <NEW_LINE> fido2_request_url = reverse_lazy('admin:django_fido_registration_request') <NEW_LINE> extra_context = None <NEW_LINE> def form_valid(self, form: forms.Form) -> HttpResponse: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.complete_registration(form) <NEW_LINE> <DEDENT> except ValidationError as error: <NEW_LINE> <INDENT> form.add_error(None, error) <NEW_LINE> return self.form_invalid(form) <NEW_LINE> <DEDENT> authenticator = Authenticator.objects.create( user=form.cleaned_data['user'], attestation=form.cleaned_data['attestation'], label=form.cleaned_data.get('label'), user_handle=form.cleaned_data.get('user_handle'), ) <NEW_LINE> return HttpResponseRedirect(reverse('admin:django_fido_authenticator_change', args=(authenticator.pk,))) <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> if self.extra_context: <NEW_LINE> <INDENT> context.update(self.extra_context) <NEW_LINE> <DEDENT> return context | Authenticator add view. | 6259903fe76e3b2f99fd9c78 |
class ISpecificationBug(IBugLink): <NEW_LINE> <INDENT> specification = Object(title=_('The specification linked to the bug.'), required=True, readonly=True, schema=ISpecification) | A link between a Bug and a specification. | 6259903fd10714528d69efc2 |
class ObjectLiteral: <NEW_LINE> <INDENT> def __init__(self, **kwds): <NEW_LINE> <INDENT> self.__dict__.update(kwds) | ObjectLiteral transforms named arguments into object attributes.
This is useful for creating object literals to be used as return
values from mocked API calls.
Source: https://stackoverflow.com/a/3335732 | 6259903f63b5f9789fe863d8 |
class InvalidFSUseType(InvalidSymbol): <NEW_LINE> <INDENT> pass | Exception for invalid fs_use_* types. | 6259903fcad5886f8bdc59b3 |
class Scheduler(object): <NEW_LINE> <INDENT> def __init__(self, manager, session): <NEW_LINE> <INDENT> raise RuntimeError ('Not Implemented!') <NEW_LINE> <DEDENT> def pilot_added (self, pilot) : <NEW_LINE> <INDENT> logger.warn ("scheduler %s does not implement 'pilot_added()'" % self.name) <NEW_LINE> <DEDENT> def pilot_removed (self, pilot) : <NEW_LINE> <INDENT> logger.warn ("scheduler %s does not implement 'pilot_removed()'" % self.name) <NEW_LINE> <DEDENT> def schedule (self, units) : <NEW_LINE> <INDENT> raise RuntimeError ("scheduler %s does not implement 'pilot_removed()'" % self.name) <NEW_LINE> <DEDENT> def unschedule (self, units) : <NEW_LINE> <INDENT> logger.warn ("scheduler %s does not implement 'unschedule()'" % self.name) <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.__class__.__name__ | Scheduler provides an abstsract interface for all schedulers.
| 6259903f287bf620b6272e59 |
class DateRangeMixin(object): <NEW_LINE> <INDENT> DATE_FMT = '%Y-%m-%d' <NEW_LINE> END_OFFSET = datetime.timedelta( hours=23, minutes=59, seconds=59, ) <NEW_LINE> context_end_date = 'end_date' <NEW_LINE> context_start_date = 'start_date' <NEW_LINE> end_date_param = 'end_date' <NEW_LINE> start_date_param = 'start_date' <NEW_LINE> @property <NEW_LINE> def end_date(self): <NEW_LINE> <INDENT> date_str = self.request.GET.get(self.end_date_param) <NEW_LINE> if not date_str: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> date = datetime.datetime.strptime( date_str, self.DATE_FMT, ) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> date += self.END_OFFSET <NEW_LINE> if self.start_date and self.start_date > date: <NEW_LINE> <INDENT> return self.start_date + self.END_OFFSET <NEW_LINE> <DEDENT> return date <NEW_LINE> <DEDENT> def filter_by_date( self, queryset, start_attr='time_start', end_attr='time_end', ): <NEW_LINE> <INDENT> start_filter = f'{start_attr}__gte' <NEW_LINE> end_filter = f'{end_attr}__lte' <NEW_LINE> if self.start_date: <NEW_LINE> <INDENT> queryset = queryset.filter(**{start_filter: self.start_date}) <NEW_LINE> <DEDENT> if self.end_date: <NEW_LINE> <INDENT> queryset = queryset.filter(**{end_filter: self.end_date}) <NEW_LINE> <DEDENT> return queryset <NEW_LINE> <DEDENT> def get_context_data(self, **kwargs): <NEW_LINE> <INDENT> context = super().get_context_data(**kwargs) <NEW_LINE> context[self.context_end_date] = self.end_date <NEW_LINE> context[self.context_start_date] = self.start_date <NEW_LINE> return context <NEW_LINE> <DEDENT> @property <NEW_LINE> def start_date(self): <NEW_LINE> <INDENT> date_str = self.request.GET.get(self.start_date_param) <NEW_LINE> if not date_str: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> return datetime.datetime.strptime( date_str, self.DATE_FMT, ) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return None | Mixin providing functionality for filtering by a date range.
The starting and ending times are specified as GET parameters. | 6259903f8c3a8732951f77c5 |
class _NullHandler(L.Handler): <NEW_LINE> <INDENT> def emit(self, _record): <NEW_LINE> <INDENT> pass | Logging handler that does nothing. | 6259903f66673b3332c31665 |
class Catch(object): <NEW_LINE> <INDENT> result = None <NEW_LINE> success = None <NEW_LINE> def __call__(self, func, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Catch.result = func(*args, **kwargs) <NEW_LINE> Catch.success = True <NEW_LINE> return 0 <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> Catch.success = False <NEW_LINE> return 1 <NEW_LINE> <DEDENT> <DEDENT> def reset(self): <NEW_LINE> <INDENT> Catch.result = None <NEW_LINE> Catch.success = None | Reproduces the behavior of the mel command of the same name. if writing
pymel scripts from scratch, you should use the try/except structure. This
command is provided for python scripts generated by py2mel. stores the
result of the function in catch.result.
>>> if not catch( lambda: myFunc( "somearg" ) ):
... result = catch.result
... print("succeeded:", result) | 6259903f07f4c71912bb069f |
class EffectiveNetworkSecurityGroupListResult(msrest.serialization.Model): <NEW_LINE> <INDENT> _validation = { 'next_link': {'readonly': True}, } <NEW_LINE> _attribute_map = { 'value': {'key': 'value', 'type': '[EffectiveNetworkSecurityGroup]'}, 'next_link': {'key': 'nextLink', 'type': 'str'}, } <NEW_LINE> def __init__( self, *, value: Optional[List["EffectiveNetworkSecurityGroup"]] = None, **kwargs ): <NEW_LINE> <INDENT> super(EffectiveNetworkSecurityGroupListResult, self).__init__(**kwargs) <NEW_LINE> self.value = value <NEW_LINE> self.next_link = None | Response for list effective network security groups API service call.
Variables are only populated by the server, and will be ignored when sending a request.
:param value: A list of effective network security groups.
:type value: list[~azure.mgmt.network.v2019_08_01.models.EffectiveNetworkSecurityGroup]
:ivar next_link: The URL to get the next set of results.
:vartype next_link: str | 6259903f63f4b57ef00866ab |
@admin.register(Genre) <NEW_LINE> class GenreAdmin(admin.ModelAdmin): <NEW_LINE> <INDENT> list_display = ("name", "url") | Жанры | 6259903fec188e330fdf9b07 |
class ParamError(APIException): <NEW_LINE> <INDENT> def __init__(self, err): <NEW_LINE> <INDENT> self.detail = err <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return self.msg | http参数错误
| 6259903f1f5feb6acb163e61 |
class ConvParameters(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.patch_size = 5 <NEW_LINE> self.stride = 1 <NEW_LINE> self.in_channels = 1 <NEW_LINE> self.out_channels = 0 <NEW_LINE> self.with_bias = True <NEW_LINE> self.relu = True <NEW_LINE> self.max_pool = True <NEW_LINE> self.max_pool_size = 2 <NEW_LINE> self.max_pool_stride = 2 <NEW_LINE> self.trainable = False <NEW_LINE> self.in_size = 28 <NEW_LINE> self.name = "" <NEW_LINE> self.num_outputs = 0 <NEW_LINE> self.bias_stddev = 0.1 | class that defines a conv layer. | 6259903f596a897236128ee5 |
class Annotator(ABC): <NEW_LINE> <INDENT> @abstractmethod <NEW_LINE> def on_post(self, req, resp): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def create( self, health_endpoint="/api/v1/health", health_impl=HealthResource(), post_endpoint="/api/v1/annotate/cdr", ): <NEW_LINE> <INDENT> app = falcon.API() <NEW_LINE> app.add_route(health_endpoint, health_impl) <NEW_LINE> app.add_route(post_endpoint, self) <NEW_LINE> return app | Annotator is a falcon-based "analytic".
Implementations must implement one method:
on_post(request, response) | 6259903f15baa723494631ff |
class Feed(csvfeed.BarFeed): <NEW_LINE> <INDENT> def __init__(self, frequency=bar.Frequency.DAY, timezone=None, maxLen=dataseries.DEFAULT_MAX_LEN): <NEW_LINE> <INDENT> if frequency not in [bar.Frequency.DAY]: <NEW_LINE> <INDENT> raise Exception("Invalid frequency.") <NEW_LINE> <DEDENT> csvfeed.BarFeed.__init__(self, frequency, maxLen) <NEW_LINE> self.__timezone = timezone <NEW_LINE> self.__sanitizeBars = False <NEW_LINE> <DEDENT> def sanitizeBars(self, sanitize): <NEW_LINE> <INDENT> self.__sanitizeBars = sanitize <NEW_LINE> <DEDENT> def barsHaveAdjClose(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> def addBarsFromCSV(self, instrument, path, timezone=None): <NEW_LINE> <INDENT> if timezone is None: <NEW_LINE> <INDENT> timezone = self.__timezone <NEW_LINE> <DEDENT> rowParser = RowParser(self.getDailyBarTime(), self.getFrequency(), timezone, self.__sanitizeBars) <NEW_LINE> csvfeed.BarFeed.addBarsFromCSV(self, instrument, path, rowParser) | A :class:`pyalgotrade.barfeed.csvfeed.BarFeed` that loads bars from CSV files downloaded from Google Finance.
:param frequency: The frequency of the bars. Only **pyalgotrade.bar.Frequency.DAY** is currently supported.
:param timezone: The default timezone to use to localize bars. Check :mod:`pyalgotrade.marketsession`.
:type timezone: A pytz timezone.
:param maxLen: The maximum number of values that the :class:`pyalgotrade.dataseries.bards.BarDataSeries` will hold.
Once a bounded length is full, when new items are added, a corresponding number of items are discarded from the opposite end.
:type maxLen: int.
.. note::
Google Finance csv files lack timezone information.
When working with multiple instruments:
* If all the instruments loaded are in the same timezone, then the timezone parameter may not be specified.
* If any of the instruments loaded are in different timezones, then the timezone parameter must be set. | 6259903f07d97122c4217f0d |
class FeedbackIPCChannel(IPCChannel): <NEW_LINE> <INDENT> def __init__(self, conn, feedback): <NEW_LINE> <INDENT> IPCChannel.__init__(self, conn) <NEW_LINE> self.feedback = feedback <NEW_LINE> <DEDENT> def handle_message(self, message): <NEW_LINE> <INDENT> self.feedback.logger.debug("Processing signal") <NEW_LINE> if message.type == bcixml.CONTROL_SIGNAL: <NEW_LINE> <INDENT> self.feedback._on_control_event(message.data) <NEW_LINE> return <NEW_LINE> <DEDENT> cmd = message.commands[0][0] if len(message.commands) > 0 else None <NEW_LINE> if cmd == bcixml.CMD_GET_VARIABLES: <NEW_LINE> <INDENT> reply = bcixml.BciSignal({"variables" : self.feedback._get_variables()}, None, bcixml.REPLY_SIGNAL) <NEW_LINE> reply.peeraddr = message.peeraddr <NEW_LINE> self.feedback.logger.debug("Sending variables") <NEW_LINE> self.send_message(reply) <NEW_LINE> <DEDENT> self.feedback._on_interaction_event(message.data) <NEW_LINE> if cmd == bcixml.CMD_PLAY: <NEW_LINE> <INDENT> self.feedback._playEvent.set() <NEW_LINE> <DEDENT> elif cmd == bcixml.CMD_PAUSE: <NEW_LINE> <INDENT> self.feedback._on_pause() <NEW_LINE> <DEDENT> elif cmd == bcixml.CMD_STOP: <NEW_LINE> <INDENT> self.feedback._on_stop() <NEW_LINE> <DEDENT> elif cmd == bcixml.CMD_QUIT: <NEW_LINE> <INDENT> self.feedback._on_quit() <NEW_LINE> <DEDENT> elif cmd == bcixml.CMD_SEND_INIT: <NEW_LINE> <INDENT> self.feedback._on_init() <NEW_LINE> <DEDENT> elif cmd == bcixml.CMD_SAVE_VARIABLES: <NEW_LINE> <INDENT> filename = message.commands[0][1]['filename'] <NEW_LINE> self.feedback.save_variables(filename) <NEW_LINE> <DEDENT> elif cmd == bcixml.CMD_LOAD_VARIABLES: <NEW_LINE> <INDENT> filename = message.commands[0][1]['filename'] <NEW_LINE> self.feedback.load_variables(filename) | IPC Channel for Feedback's end. | 6259903f379a373c97d9a297 |
class ExchangeRatesAPI(Resource): <NEW_LINE> <INDENT> def get(self, comparison): <NEW_LINE> <INDENT> key = '3c350b71f4e249f1a01c7573fb3b9998' <NEW_LINE> currencies = get( 'https://openexchangerates.org/api/latest.json', params={'app_id': key}).json() <NEW_LINE> return [{'exchange_rate': currencies['rates'][comparison]}] | Compare a currency to USD
Data source: OpenExchangeRates
Notes:
- Using a free plan, which means there is only one base currency (USD) allowed
- Free plan is also limited to 1,000 queries per month | 6259903f07f4c71912bb06a0 |
class ModelMeta(type): <NEW_LINE> <INDENT> def __init__(self, name, bases, dct): <NEW_LINE> <INDENT> self._fields = {key for key, value in dct.iteritems() if isinstance(value, AbstractGenerator)} <NEW_LINE> super(ModelMeta, self).__init__(name, bases, dct) | Model metaclass.
Metclass to create Models correctly.
It is done to support nested models
and iteratio through fields | 6259903fc432627299fa4238 |
class Player(pygame.sprite.Sprite): <NEW_LINE> <INDENT> def __init__(self,screen,player_num): <NEW_LINE> <INDENT> pygame.sprite.Sprite.__init__(self) <NEW_LINE> self.__p1 = pygame.image.load("Player_1.png") <NEW_LINE> self.__p2 = pygame.image.load("Player_2.png") <NEW_LINE> self.__p1_jump = pygame.image.load("Player1_Jump2.png") <NEW_LINE> self.__screen = screen <NEW_LINE> self.__change_y =0 <NEW_LINE> self.__player_num = player_num <NEW_LINE> self.__running = 1 <NEW_LINE> self.__run_factor = 10 <NEW_LINE> if player_num == 1: <NEW_LINE> <INDENT> self.image = self.__p1 <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.bottom = screen.get_height() - 200 <NEW_LINE> self.rect.left = 250 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image = self.__p2 <NEW_LINE> self.rect = self.image.get_rect() <NEW_LINE> self.rect.bottom = screen.get_height() - 200 <NEW_LINE> self.rect.left = screen.get_width() - 250 <NEW_LINE> <DEDENT> <DEDENT> def change_direction(self, xy_change): <NEW_LINE> <INDENT> self.rect.right += (xy_change[0] * 10) <NEW_LINE> if self.__running == self.__run_factor: <NEW_LINE> <INDENT> self.__p1 = pygame.image.load("Player1_running0.png") <NEW_LINE> <DEDENT> elif self.__running == self.__run_factor/2 : <NEW_LINE> <INDENT> self.__p1 = pygame.image.load("Player1_running1.png") <NEW_LINE> <DEDENT> self.__running += 1 <NEW_LINE> if self.__running > self.__run_factor: <NEW_LINE> <INDENT> self.__running = 0 <NEW_LINE> <DEDENT> <DEDENT> def jump (self): <NEW_LINE> <INDENT> self.rect.bottom += 2 <NEW_LINE> if self.__player_num == 1: <NEW_LINE> <INDENT> self.image = self.__p1_jump <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image = self.__p2 <NEW_LINE> <DEDENT> if self.rect.top == self.__screen.get_height() / 2: <NEW_LINE> <INDENT> self.rect.bottom -= 2 <NEW_LINE> <DEDENT> if self.rect.bottom >= self.__screen.get_height()/2+100: <NEW_LINE> <INDENT> self.__change_y = -10 <NEW_LINE> <DEDENT> <DEDENT> def gravity(self): <NEW_LINE> <INDENT> if self.__change_y == 0: <NEW_LINE> <INDENT> self.__change_y = 1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.__change_y += .35 <NEW_LINE> <DEDENT> if self.rect.y >= self.__screen.get_height()/2+100 - self.rect.height and self.__change_y >= 0: <NEW_LINE> <INDENT> self.__change_y = 0 <NEW_LINE> self.rect.y = self.__screen.get_height()/2+100 - self.rect.height <NEW_LINE> if self.__player_num == 1: <NEW_LINE> <INDENT> self.image = self.__p1 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.image = self.__p2 <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def update(self): <NEW_LINE> <INDENT> if self.rect.left < 125: <NEW_LINE> <INDENT> self.rect.left = 125 <NEW_LINE> <DEDENT> elif self.rect.right > self.__screen.get_width() - 125: <NEW_LINE> <INDENT> self.rect.right = self.__screen.get_width() -125 <NEW_LINE> <DEDENT> self.gravity() <NEW_LINE> self.rect.y += self.__change_y | This class defines the sprite for Player 1 and Player 2 | 6259903f82261d6c527307fb |
class Faces: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') <NEW_LINE> self.eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') <NEW_LINE> <DEDENT> def process(self, source0): <NEW_LINE> <INDENT> img = source0 <NEW_LINE> gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) <NEW_LINE> faces = self.face_cascade.detectMultiScale(gray, 1.3, 5) <NEW_LINE> for (x,y,w,h) in faces: <NEW_LINE> <INDENT> cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) <NEW_LINE> roi_gray = gray[y:y+h, x:x+w] <NEW_LINE> roi_color = img[y:y+h, x:x+w] <NEW_LINE> eyes = self.eye_cascade.detectMultiScale(roi_gray) <NEW_LINE> for (ex,ey,ew,eh) in eyes: <NEW_LINE> <INDENT> cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) <NEW_LINE> <DEDENT> <DEDENT> return img | An OpenCV pipeline created to find faces | 6259903fcad5886f8bdc59b4 |
class LiteralInteger(Literal): <NEW_LINE> <INDENT> __slots__ = ('_value',) <NEW_LINE> _dtype = NativeInteger() <NEW_LINE> def __init__(self, value, precision = -1): <NEW_LINE> <INDENT> super().__init__(precision) <NEW_LINE> assert(value >= 0) <NEW_LINE> if not isinstance(value, int): <NEW_LINE> <INDENT> raise TypeError("A LiteralInteger can only be created with an integer") <NEW_LINE> <DEDENT> self._value = value <NEW_LINE> <DEDENT> @property <NEW_LINE> def python_value(self): <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> def __index__(self): <NEW_LINE> <INDENT> return self.python_value | Represents an integer literal in python | 6259903fa79ad1619776b2ee |
class DocumentAddForm(silvaforms.SMIAddForm): <NEW_LINE> <INDENT> grok.context(IDocument) <NEW_LINE> grok.name('Silva Document') <NEW_LINE> fields = silvaforms.Fields(ITitledContent) | Add form for Documents
| 6259903f16aa5153ce40175c |
class UpdateInfo: <NEW_LINE> <INDENT> @param.input("username, declaration?") <NEW_LINE> def POST(self, username, declaration): <NEW_LINE> <INDENT> if web.ctx.username != username: <NEW_LINE> <INDENT> return {"code": 1, "message": "access denied"} <NEW_LINE> <DEDENT> if username not in user_info_data: <NEW_LINE> <INDENT> return {"code": 1, "message": "user not exist"} <NEW_LINE> <DEDENT> if declaration is not None: <NEW_LINE> <INDENT> user_info_data[username]["declaration"] = declaration <NEW_LINE> <DEDENT> return {"code": 0} | 更新用户信息 | 6259903fb830903b9686edb1 |
class AuthenticateUserView(APIView): <NEW_LINE> <INDENT> permission_classes = (AllowAny,) <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> email = request.data['email'] <NEW_LINE> password = request.data['password'] <NEW_LINE> user = User.objects.get(email=email, password=password) <NEW_LINE> if user: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> payload = jwt_payload_handler(user) <NEW_LINE> token = jwt.encode(payload, settings.SECRET_KEY) <NEW_LINE> user_details = {} <NEW_LINE> user_details['name'] = "%s %s" % ( user.first_name, user.last_name) <NEW_LINE> user_details['token'] = token <NEW_LINE> user_logged_in.send(sender=user.__class__, request=request, user=user) <NEW_LINE> return Response(user_details, status=status.HTTP_200_OK) <NEW_LINE> <DEDENT> except Exception as e: <NEW_LINE> <INDENT> raise e <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> res = { 'error': 'can not authenticate with the given credentials or the account has been deactivated'} <NEW_LINE> return Response(res, status=status.HTTP_403_FORBIDDEN) <NEW_LINE> <DEDENT> <DEDENT> except KeyError: <NEW_LINE> <INDENT> res = {'error': 'please provide a email and a password'} <NEW_LINE> return Response(res) | Allow any user (authenticated or not) to access this url | 6259903f3eb6a72ae038b8da |
class GeneralRegressionModel(ind.GeneralRegressionModel): <NEW_LINE> <INDENT> def __init__(self, attribs): <NEW_LINE> <INDENT> super(GeneralRegressionModel, self).__init__() <NEW_LINE> self.targetVariableName = None <NEW_LINE> self.modelType = None <NEW_LINE> self.modelName = None <NEW_LINE> self.functionName = None <NEW_LINE> self.algorithmName = None <NEW_LINE> self.cumulativeLink = None <NEW_LINE> self.linkFunction = None <NEW_LINE> self.linkParameter = None <NEW_LINE> self.trialsVariable = None <NEW_LINE> self.trialsValue = None <NEW_LINE> self.distribution = None <NEW_LINE> self.distParameter = None <NEW_LINE> self.offsetVariable = None <NEW_LINE> self.offsetValue = None <NEW_LINE> for key, value in attribs.items(): <NEW_LINE> <INDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> self.CovariateList = [] <NEW_LINE> self.Extension = [] <NEW_LINE> self.FactorList = [] <NEW_LINE> self.LocalTransformations = [] <NEW_LINE> self.MiningSchema = [] <NEW_LINE> self.ModelStats = [] <NEW_LINE> self.ModelVerification = [] <NEW_LINE> self.Output = [] <NEW_LINE> self.PCovMatrix = [] <NEW_LINE> self.PPMatrix = [] <NEW_LINE> self.ParamMatrix = [] <NEW_LINE> self.ParameterList = [] <NEW_LINE> self.Targets = [] | Represents a <GeneralRegressionModel> tag in v3.2 and provides methods to convert to PFA. | 6259903fec188e330fdf9b09 |
class Accuracy(EvalMetric): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(Accuracy, self).__init__('accuracy') <NEW_LINE> <DEDENT> def update(self, labels, preds): <NEW_LINE> <INDENT> check_label_shapes(labels, preds) <NEW_LINE> for label, pred_label in zip(labels, preds): <NEW_LINE> <INDENT> if pred_label.shape != label.shape: <NEW_LINE> <INDENT> pred_label = ndarray.argmax_channel(pred_label) <NEW_LINE> <DEDENT> pred_label = pred_label.asnumpy().astype('int32') <NEW_LINE> label = label.asnumpy().astype('int32') <NEW_LINE> check_label_shapes(label, pred_label) <NEW_LINE> self.sum_metric += (pred_label.flat == label.flat).sum() <NEW_LINE> self.num_inst += len(pred_label.flat) | Calculate accuracy. | 6259903f50485f2cf55dc1f3 |
class StringWrapper(Base): <NEW_LINE> <INDENT> def __init__(self, value): <NEW_LINE> <INDENT> super(StringWrapper, self).__init__() <NEW_LINE> self.value = value <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> return hash(self.value) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> return self.value == other.value <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.value <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def getPropertyType(cls): <NEW_LINE> <INDENT> from ceguitype_editor_properties import BaseProperty <NEW_LINE> return BaseProperty | Simple string that does no parsing but allows us to map editors to it | 6259903f26238365f5faddc8 |
class TestConfig(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.tmpdir = tempfile.mkdtemp(prefix="config_test", dir=".") <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> if os.path.exists(self.tmpdir): <NEW_LINE> <INDENT> shutil.rmtree(self.tmpdir) <NEW_LINE> <DEDENT> <DEDENT> def testReadingWhenAttributeExists(self): <NEW_LINE> <INDENT> cfg_path = os.path.join(self.tmpdir, "config.ini") <NEW_LINE> with open(cfg_path, "wb") as fp: <NEW_LINE> <INDENT> fp.write("[login]\ntoken_info = MY_TOKEN\n".encode("utf-8")) <NEW_LINE> <DEDENT> cfg = Config(cfg_path) <NEW_LINE> self.assertEqual(cfg.token_info, "MY_TOKEN") | Test Config file items are exposed as attributes on config object | 6259903fd99f1b3c44d0690c |
class Activity (CacheClearingModel, TimeStampedModel): <NEW_LINE> <INDENT> action = models.CharField(max_length=16, default='create') <NEW_LINE> data = models.ForeignKey(SubmittedThing) <NEW_LINE> cache = cache.ActivityCache() <NEW_LINE> next_version = 'sa_api_v2.models.Action' <NEW_LINE> @property <NEW_LINE> def submitter_name(self): <NEW_LINE> <INDENT> return self.data.submitter_name <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> managed = False <NEW_LINE> db_table = 'sa_api_activity' | Metadata about SubmittedThings:
what happened when. | 6259903f30c21e258be99a7d |
class DictAttr(dict): <NEW_LINE> <INDENT> def __getattr__(self, name): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> raise AttributeError | Dictionary class
>>> x = DictAttr([('one', 1), ('two', 2), ('three', 3)])
>>> x
{'one': 1, 'two': 2, 'three': 3}
>>> x['three']
3
>>> x.get('one')
1
>>> x.get('five', 'missing')
'missing'
>>> x.one
1
>>> x.five
Traceback (most recent call last):
...
AttributeError | 6259903f097d151d1a2c22d6 |
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') <NEW_LINE> @ddt.ddt <NEW_LINE> class XDomainProxyTest(TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> super(XDomainProxyTest, self).setUp() <NEW_LINE> try: <NEW_LINE> <INDENT> self.url = reverse('xdomain_proxy') <NEW_LINE> <DEDENT> except NoReverseMatch: <NEW_LINE> <INDENT> self.skipTest('xdomain_proxy URL is not configured') <NEW_LINE> <DEDENT> cache.clear() <NEW_LINE> <DEDENT> def test_xdomain_proxy_disabled(self): <NEW_LINE> <INDENT> self._configure(False) <NEW_LINE> response = self._load_page() <NEW_LINE> self.assertEqual(response.status_code, 404) <NEW_LINE> <DEDENT> @ddt.data(None, [' '], [' ', ' ']) <NEW_LINE> def test_xdomain_proxy_enabled_no_whitelist(self, whitelist): <NEW_LINE> <INDENT> self._configure(True, whitelist=whitelist) <NEW_LINE> response = self._load_page() <NEW_LINE> self.assertEqual(response.status_code, 404) <NEW_LINE> <DEDENT> @ddt.data( (['example.com'], ['example.com']), (['example.com', 'sub.example.com'], ['example.com', 'sub.example.com']), ([' example.com '], ['example.com']), ([' ', 'example.com'], ['example.com']), ) <NEW_LINE> @ddt.unpack <NEW_LINE> def test_xdomain_proxy_enabled_with_whitelist(self, whitelist, expected_whitelist): <NEW_LINE> <INDENT> self._configure(True, whitelist=whitelist) <NEW_LINE> response = self._load_page() <NEW_LINE> self._check_whitelist(response, expected_whitelist) <NEW_LINE> <DEDENT> def _configure(self, is_enabled, whitelist=None): <NEW_LINE> <INDENT> config = XDomainProxyConfiguration.current() <NEW_LINE> config.enabled = is_enabled <NEW_LINE> if whitelist: <NEW_LINE> <INDENT> config.whitelist = "\n".join(whitelist) <NEW_LINE> <DEDENT> config.save() <NEW_LINE> cache.clear() <NEW_LINE> <DEDENT> def _load_page(self): <NEW_LINE> <INDENT> return self.client.get(reverse('xdomain_proxy')) <NEW_LINE> <DEDENT> def _check_whitelist(self, response, expected_whitelist): <NEW_LINE> <INDENT> rendered_whitelist = json.dumps({ domain: '*' for domain in expected_whitelist }) <NEW_LINE> self.assertContains(response, 'xdomain.min.js') <NEW_LINE> self.assertContains(response, rendered_whitelist) | Tests for the xdomain proxy end-point. | 6259903f287bf620b6272e5d |
class Blocks(Extension): <NEW_LINE> <INDENT> def onUserBlockBuilding(self, event): <NEW_LINE> <INDENT> if context.user.can("manage_blocks"): <NEW_LINE> <INDENT> event.add_link("Blocks Editor", make_link("blocks/list")) <NEW_LINE> <DEDENT> <DEDENT> def onPageRequest(self, event, request, config, database, page, user, cache): <NEW_LINE> <INDENT> blocks = cache.get("blocks") <NEW_LINE> if not blocks: <NEW_LINE> <INDENT> blocks = database.query(DataBlock).all() <NEW_LINE> cache.set("blocks", blocks, 600) <NEW_LINE> <DEDENT> for block in blocks: <NEW_LINE> <INDENT> if fnmatch(block.pages, "/".join(event.args)): <NEW_LINE> <INDENT> page.add_block(Block(block.title, block.content, block.area, block.priority)) <NEW_LINE> <DEDENT> <DEDENT> if event.page_matches("blocks") and user.can("manage_blocks"): <NEW_LINE> <INDENT> if event.get_arg(0) == "add": <NEW_LINE> <INDENT> if user.check_auth_token(): <NEW_LINE> <INDENT> database.add(DataBlock( pages=request.POST["pages"], title=request.POST["title"], area=request.POST["area"], priority=request.POST["priority"], content=request.POST["content"], )) <NEW_LINE> log.info("Added Block", block_id=database.get_last_insert_id('blocks_id_seq'), title=request.POST['title']) <NEW_LINE> cache.delete("blocks") <NEW_LINE> page.mode = "redirect" <NEW_LINE> page.redirect = make_link("blocks/list") <NEW_LINE> <DEDENT> <DEDENT> elif event.get_arg(0) == "update": <NEW_LINE> <INDENT> if user.check_auth_token(): <NEW_LINE> <INDENT> if request.POST['delete']: <NEW_LINE> <INDENT> database.query(DataBlock).get(request.POST["id"]).delete() <NEW_LINE> log.info("Deleted Block", block_id=request.POST['id']) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> bl = database.query(DataBlock).get(request.POST["id"]) <NEW_LINE> bl.pages = request.POST["pages"] <NEW_LINE> bl.title = request.POST["title"] <NEW_LINE> bl.area = request.POST["area"] <NEW_LINE> bl.priority = request.POST["priority"] <NEW_LINE> bl.content = request.POST["content"] <NEW_LINE> log.info("Updated Block", block_id=request.POST['id'], title=request.POST['title']) <NEW_LINE> <DEDENT> cache.delete("blocks") <NEW_LINE> page.mode = "redirect" <NEW_LINE> page.redirect = make_link("blocks/list") <NEW_LINE> <DEDENT> <DEDENT> elif event.get_arg(0) == "list": <NEW_LINE> <INDENT> self.theme.display_blocks(database.query(DataBlock).order_by("area", "priority")) | Name: Generic Blocks
Author: Shish <[email protected]>
Link: http://code.shishnet.org/shimmie2/
License: GPLv2
Description: Add HTML to some space (News, Ads, etc) | 6259903fbe383301e0254a89 |
class zTopFoolball(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.tim0Str_gid='2010-01-01' <NEW_LINE> self.tim0_gid=arrow.get(self.tim0Str_gid) <NEW_LINE> self.gid_tim0str,self.gid_tim9str='','' <NEW_LINE> self.gid_nday,self.gid_nday_tim9=0,0 <NEW_LINE> self.tim0,self.tim9,self.tim_now=None,None,None <NEW_LINE> self.tim0Str,self.tim9Str,self.timStr_now='','','' <NEW_LINE> self.kgid='' <NEW_LINE> self.kcid='' <NEW_LINE> self.ktimStr='' <NEW_LINE> self.poolInx=[] <NEW_LINE> self.poolDay=pd.DataFrame(columns=poolSgn) <NEW_LINE> self.poolTrd=pd.DataFrame(columns=poolSgn) <NEW_LINE> self.poolRet=pd.DataFrame(columns=retSgn) <NEW_LINE> self.poolTrdFN,self.poolRetFN='','' <NEW_LINE> self.bars=None <NEW_LINE> self.gid10=None <NEW_LINE> self.xdat10=None <NEW_LINE> self.funPre,self.funSta=None,None <NEW_LINE> self.preVars,self.staVars=[],[] <NEW_LINE> self.ai_mxFN0='' <NEW_LINE> self.ai_mx_sgn_lst=[] <NEW_LINE> self.ai_xlst=[] <NEW_LINE> self.ai_ysgn='' <NEW_LINE> self.ai_xdat,self.ai_xdat=None,None <NEW_LINE> self.ret_nday,self.ret_nWin=0,0 <NEW_LINE> self.ret_nplay,self.ret_nplayWin=0,0 <NEW_LINE> self.ret_msum=0 | 设置TopFoolball项目的各个全局参数
尽量做到all in one | 6259903fa79ad1619776b2f0 |
class ResourceManagerTestCase(TransactionTestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.user = test_utils.setup_user("user", "changeme") <NEW_LINE> test_utils.set_competition_round() <NEW_LINE> self.team = self.user.get_profile().team <NEW_LINE> <DEDENT> def testEnergy(self): <NEW_LINE> <INDENT> date = datetime.date.today() <NEW_LINE> EnergyUsage( team=self.team, date=date, time=datetime.time(hour=15), usage=100, ).save() <NEW_LINE> rank = resource_mgr.resource_team_rank_info(self.team, "energy")["rank"] <NEW_LINE> usage = resource_mgr.team_resource_usage(date=date, team=self.team, resource="energy") <NEW_LINE> self.assertEqual(rank, 1, "The team should be first rank.") <NEW_LINE> self.assertEqual(usage, 100, "The team usage is not correct.") | ResourceManager Test | 6259903fd6c5a102081e3397 |
class WhileBodyFuncGraph(func_graph.FuncGraph): <NEW_LINE> <INDENT> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> super(WhileBodyFuncGraph, self).__init__(*args, **kwargs) <NEW_LINE> if ops.executing_eagerly_outside_functions(): <NEW_LINE> <INDENT> func_graph.override_func_graph_name_scope( self, self.outer_graph.get_name_scope()) | FuncGraph for the body of tf.while_loop().
This is used to distinguish while bodies from other functions. | 6259903f1f5feb6acb163e65 |
class ComponentTests(ossie.utils.testing.ScaComponentTestCase): <NEW_LINE> <INDENT> def testScaBasicBehavior(self): <NEW_LINE> <INDENT> execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False) <NEW_LINE> execparams = dict([(x.id, any.from_any(x.value)) for x in execparams]) <NEW_LINE> self.launch(execparams) <NEW_LINE> self.assertNotEqual(self.comp, None) <NEW_LINE> self.assertEqual(self.comp.ref._non_existent(), False) <NEW_LINE> self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True) <NEW_LINE> expectedProps = [] <NEW_LINE> expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True)) <NEW_LINE> expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True)) <NEW_LINE> props = self.comp.query([]) <NEW_LINE> props = dict((x.id, any.from_any(x.value)) for x in props) <NEW_LINE> for expectedProp in expectedProps: <NEW_LINE> <INDENT> self.assertEquals(props.has_key(expectedProp.id), True) <NEW_LINE> <DEDENT> for port in self.scd.get_componentfeatures().get_ports().get_uses(): <NEW_LINE> <INDENT> port_obj = self.comp.getPort(str(port.get_usesname())) <NEW_LINE> self.assertNotEqual(port_obj, None) <NEW_LINE> self.assertEqual(port_obj._non_existent(), False) <NEW_LINE> self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True) <NEW_LINE> <DEDENT> for port in self.scd.get_componentfeatures().get_ports().get_provides(): <NEW_LINE> <INDENT> port_obj = self.comp.getPort(str(port.get_providesname())) <NEW_LINE> self.assertNotEqual(port_obj, None) <NEW_LINE> self.assertEqual(port_obj._non_existent(), False) <NEW_LINE> self.assertEqual(port_obj._is_a(port.get_repid()), True) <NEW_LINE> <DEDENT> self.comp.start() <NEW_LINE> self.comp.stop() <NEW_LINE> self.comp.releaseObject() | Test for all component implementations in argmax_ss_1i | 6259903f711fe17d825e15d5 |
class CcUpdate(atom.core.XmlElement): <NEW_LINE> <INDENT> _qname = ISSUES_TEMPLATE % 'ccUpdate' | The issues:ccUpdate element. | 6259903f004d5f362081f91d |
class ChannelNormalizer(object): <NEW_LINE> <INDENT> def __init__(self, mean_r, mean_g, mean_b, std_r, std_g, std_b): <NEW_LINE> <INDENT> self.mean_r = mean_r <NEW_LINE> self.mean_g = mean_g <NEW_LINE> self.mean_b = mean_b <NEW_LINE> self.std_r = std_r <NEW_LINE> self.std_g = std_g <NEW_LINE> self.std_b = std_b <NEW_LINE> <DEDENT> def __call__(self, img): <NEW_LINE> <INDENT> mean = np.array([self.mean_b, self.mean_g, self.mean_r]) <NEW_LINE> std = np.array([self.std_b, self.std_g, self.std_r]) <NEW_LINE> mean_sub = img[:, :] - mean <NEW_LINE> return mean_sub[:, :] / std | Normalize image which is an numpy array by means and std of each channel. The shape of image is (height, width, channel)
:param mean_r: mean for red channel
:param mean_g: mean for green channel
:param mean_b: mean for blue channel
:param std_r: std for red channel
:param std_g: std for green channel
:param std_b: std for blue channel
:return: normalized image. The shape of image is (height, width, channel) | 6259903f26238365f5faddca |
class InputLocationMessageContent(InputMessageContent): <NEW_LINE> <INDENT> def __init__(self, latitude, longitude): <NEW_LINE> <INDENT> super(InputLocationMessageContent, self).__init__() <NEW_LINE> assert(latitude is not None) <NEW_LINE> assert(isinstance(latitude, float)) <NEW_LINE> self.latitude = latitude <NEW_LINE> assert(longitude is not None) <NEW_LINE> assert(isinstance(longitude, float)) <NEW_LINE> self.longitude = longitude <NEW_LINE> <DEDENT> def to_array(self): <NEW_LINE> <INDENT> array = super(InputLocationMessageContent, self).to_array() <NEW_LINE> array['latitude'] = float(self.latitude) <NEW_LINE> array['longitude'] = float(self.longitude) <NEW_LINE> return array <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def from_array(array): <NEW_LINE> <INDENT> if array is None or not array: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> assert(isinstance(array, dict)) <NEW_LINE> data = {} <NEW_LINE> data['latitude'] = float(array.get('latitude')) <NEW_LINE> data['longitude'] = float(array.get('longitude')) <NEW_LINE> return InputLocationMessageContent(**data) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return "InputLocationMessageContent(latitude={self.latitude!r}, longitude={self.longitude!r})".format(self=self) <NEW_LINE> <DEDENT> def __contains__(self, key): <NEW_LINE> <INDENT> return key in ["latitude", "longitude"] | Represents the content of a location message to be sent as the result of an inline query.
Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.
https://core.telegram.org/bots/api#inputlocationmessagecontent | 6259903f30dc7b76659a0aa4 |
class Project(models.Model): <NEW_LINE> <INDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = "проект" <NEW_LINE> verbose_name_plural = "проекты" <NEW_LINE> <DEDENT> name = models.CharField(verbose_name="название", max_length=100) <NEW_LINE> description = HTMLField(verbose_name="описание") <NEW_LINE> start_date = models.DateField(verbose_name="начало") <NEW_LINE> end_date = models.DateField(verbose_name="окончание") <NEW_LINE> price = models.DecimalField(verbose_name="цена", max_digits=20, decimal_places=2) <NEW_LINE> company = models.ForeignKey(Company, verbose_name="компания", on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return self.name <NEW_LINE> <DEDENT> def get_absolute_url(self): <NEW_LINE> <INDENT> return reverse('project:detail', kwargs={'pk': self.pk}) | Companies project model. | 6259903fd4950a0f3b111779 |
class InstalledExtensionState(Model): <NEW_LINE> <INDENT> _attribute_map = { 'flags': {'key': 'flags', 'type': 'object'}, 'installation_issues': {'key': 'installationIssues', 'type': '[InstalledExtensionStateIssue]'}, 'last_updated': {'key': 'lastUpdated', 'type': 'iso-8601'} } <NEW_LINE> def __init__(self, flags=None, installation_issues=None, last_updated=None): <NEW_LINE> <INDENT> super(InstalledExtensionState, self).__init__() <NEW_LINE> self.flags = flags <NEW_LINE> self.installation_issues = installation_issues <NEW_LINE> self.last_updated = last_updated | InstalledExtensionState.
:param flags: States of an installed extension
:type flags: object
:param installation_issues: List of installation issues
:type installation_issues: list of :class:`InstalledExtensionStateIssue <contributions.v4_1.models.InstalledExtensionStateIssue>`
:param last_updated: The time at which this installation was last updated
:type last_updated: datetime | 6259903f8e05c05ec3f6f794 |
class uniform_grid_end(uniform_grid): <NEW_LINE> <INDENT> def __init__(self,link,pointer=0): <NEW_LINE> <INDENT> if pointer==0: <NEW_LINE> <INDENT> f=link.o2scl.o2scl_create_uniform_grid_end_ <NEW_LINE> f.restype=ctypes.c_void_p <NEW_LINE> f.argtypes=[] <NEW_LINE> self._ptr=f() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self._ptr=pointer <NEW_LINE> self._owner=False <NEW_LINE> <DEDENT> self._link=link <NEW_LINE> return <NEW_LINE> <DEDENT> def __del__(self): <NEW_LINE> <INDENT> if self._owner==True: <NEW_LINE> <INDENT> f=self._link.o2scl.o2scl_free_uniform_grid_end_ <NEW_LINE> f.argtypes=[ctypes.c_void_p] <NEW_LINE> f(self._ptr) <NEW_LINE> self._owner=False <NEW_LINE> self._ptr=0 <NEW_LINE> <DEDENT> return <NEW_LINE> <DEDENT> def __copy__(self): <NEW_LINE> <INDENT> new_obj=type(self)(self._link,self._ptr) <NEW_LINE> return new_obj <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def init(cls,link,start,end,n_bins): <NEW_LINE> <INDENT> f=link.o2scl.o2scl_uniform_grid_end__init <NEW_LINE> f.restype=ctypes.c_void_p <NEW_LINE> f.argtypes=[ctypes.c_double,ctypes.c_double,ctypes.c_size_t] <NEW_LINE> return cls(link,f(start,end,n_bins)) | Python interface for O\ :sub:`2`\ scl class ``uniform_grid_end``,
see
https://neutronstars.utk.edu/code/o2scl/html/class/uniform_grid_end.html . | 6259903f21bff66bcd723edd |
class GenotypeSplitter(BaseVspSplitter): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> _simuPOP_std.GenotypeSplitter_swiginit(self, _simuPOP_std.new_GenotypeSplitter(*args, **kwargs)) <NEW_LINE> <DEDENT> __swig_destroy__ = _simuPOP_std.delete_GenotypeSplitter | Details:
This class defines a VSP splitter that defines VSPs according to
individual genotype at specified loci. | 6259903f287bf620b6272e5f |
class BaseMessage(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.id = None <NEW_LINE> self.seq = float('-inf') <NEW_LINE> self.addr_v4 = None <NEW_LINE> self.addr_v6 = None <NEW_LINE> self.networks = {} <NEW_LINE> self.routing_data = {} <NEW_LINE> self.node_data = {} <NEW_LINE> self.reflect = {} <NEW_LINE> self.reflected = {} <NEW_LINE> <DEDENT> def apply_base_data(self, msg): <NEW_LINE> <INDENT> self.id = msg.id <NEW_LINE> self.seq = msg.seq <NEW_LINE> self.addr_v4 = msg.addr_v4 <NEW_LINE> self.addr_v6 = msg.addr_v6 <NEW_LINE> self.networks = msg.networks <NEW_LINE> self.routing_data = msg.routing_data <NEW_LINE> self.node_data = msg.node_data <NEW_LINE> self.reflected = msg.reflected | Auxiliary class to encapsulate basic message fields | 6259903f07f4c71912bb06a5 |
class CRUDExternalApi(CRUDApi): <NEW_LINE> <INDENT> def update_by_external_id(self, api_objects): <NEW_LINE> <INDENT> if not isinstance(api_objects, collections.Iterable): <NEW_LINE> <INDENT> api_objects = [api_objects] <NEW_LINE> <DEDENT> return CRUDRequest(self).put(api_objects, update_many_external=True) <NEW_LINE> <DEDENT> def delete_by_external_id(self, api_objects): <NEW_LINE> <INDENT> if not isinstance(api_objects, collections.Iterable): <NEW_LINE> <INDENT> api_objects = [api_objects] <NEW_LINE> <DEDENT> return CRUDRequest(self).delete(api_objects, destroy_many_external=True) | The CRUDExternalApi exposes some extra methods for operating on external ids. | 6259903f23e79379d538d772 |
class CoquetelDecorator(Coquetel): <NEW_LINE> <INDENT> def __init__(self, coquetel): <NEW_LINE> <INDENT> self.coquetel = coquetel <NEW_LINE> <DEDENT> def get_nome(self): <NEW_LINE> <INDENT> nome = "{0} + {1}".format(self.coquetel.get_nome(), self.nome) <NEW_LINE> return nome <NEW_LINE> <DEDENT> def get_preco(self): <NEW_LINE> <INDENT> return self.coquetel.get_preco() + self.preco | Adicional para o coquetel. | 6259903fa4f1c619b294f7c1 |
class ArctanExpInfo: <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> self.Name = 'Arctan with Exp' <NEW_LINE> self.Order = 7 <NEW_LINE> self.ParameterNumber = 6 <NEW_LINE> self.ParameterNames = ['Position', 'Factor', 'Amplitude', 'Offset', 'Decay Fact', 'Decay Pos'] <NEW_LINE> self.ParameterUnit = ['cm-1', 'cm', 'Intensity', 'Intensity', 'cm'] <NEW_LINE> self.ParameterBoundaries = [['-10','10'], ['xmin','xmax'], ['-2','2'], ['-Inf','Inf'], ['-1000','1000'], ['-Inf','Inf'], ['-10','10'], ['-Inf','Inf'], ['-10','10'], ['-Inf','Inf'], ['-10','10'], ['-Inf','Inf'], ] <NEW_LINE> self.ParameterProcessing = ['1', '0,1,2,3,4,5'] | ###############################################################################
This class will contain information about the function, parameters and names
############################################################################### | 6259903f1f5feb6acb163e67 |
class MorphosynSequencer(nn.Module): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(MorphosynSequencer, self).__init__() <NEW_LINE> if 0: <NEW_LINE> <INDENT> W_ = torch.ones(config.ndim, config.ndim) <NEW_LINE> W1_ = W_.triu() * 1.0 <NEW_LINE> W2_ = W_.tril() * -10.0 <NEW_LINE> W_ = (W1_ + W2_) <NEW_LINE> W_.diagonal().fill_(-10.0) <NEW_LINE> self.W = W_ <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.W = Parameter(0.1 * torch.randn(config.ndim, config.ndim)) <NEW_LINE> self.W.diagonal().clamp(-10.0, -10.0) <NEW_LINE> <DEDENT> <DEDENT> def forward(self, morphosyn, nslot): <NEW_LINE> <INDENT> alpha = [morphosyn[i][:, 0] == 0.0 for i in range(config.ndim)] <NEW_LINE> alpha = torch.stack(alpha, -1).float() <NEW_LINE> W = exp(self.W) <NEW_LINE> gammas = [] <NEW_LINE> for i in range(nslot): <NEW_LINE> <INDENT> beta = einsum('bj,ij->bi', alpha, W) <NEW_LINE> gamma = alpha * exp(-beta) <NEW_LINE> alpha = alpha * (1.0 - gamma) <NEW_LINE> gammas.append(gamma) <NEW_LINE> <DEDENT> Mslot2dim_attn = torch.stack(gammas, -1) <NEW_LINE> return Mslot2dim_attn | Sequence morphosyntactic specifications with inhibition | 6259903f004d5f362081f91e |
class Transaction(metaclass(TransactionMeta)): <NEW_LINE> <INDENT> __actions__, __scoped__ = {}, False <NEW_LINE> __getattr__, __setattr__ = getter, setter <NEW_LINE> def __init__(self, *args, **kwargs): <NEW_LINE> <INDENT> self.__context__ = (args, kwargs) <NEW_LINE> self.__root__ = self.__path__ = "" <NEW_LINE> <DEDENT> def __chain__(self, root, path): <NEW_LINE> <INDENT> self.__root__, self.__path__ = root, path <NEW_LINE> return self <NEW_LINE> <DEDENT> def __call__(self, *args, **kwargs): <NEW_LINE> <INDENT> if not self.__root__: <NEW_LINE> <INDENT> raise TypeError("'{}' object is not callable".format(type(self).__name__)) <NEW_LINE> <DEDENT> if not self.__root__.__scoped__: <NEW_LINE> <INDENT> raise RuntimeError("Cannot execute actions outside of scope.") <NEW_LINE> <DEDENT> with self.__root__.__lock__: <NEW_LINE> <INDENT> action = self.__actions__[self.__path__](*self.__context__[0], **self.__context__[1]) <NEW_LINE> self.__root__.__queue__.append(action) <NEW_LINE> <DEDENT> return action.execute(self.__root__, *args, **kwargs) <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.__queue__, self.__lock__, self.__scoped__ = [], threading.Lock(), True <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, err, *_): <NEW_LINE> <INDENT> with self.__lock__: <NEW_LINE> <INDENT> self.__scoped__ = False <NEW_LINE> try: <NEW_LINE> <INDENT> while not err and self.__queue__: <NEW_LINE> <INDENT> self.__queue__.pop(0).commit() <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> for action in reversed(self.__queue__): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> action.revert() <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> LOG.error(traceback.format_exc()) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> @property <NEW_LINE> def start(self): <NEW_LINE> <INDENT> return self.__enter__ <NEW_LINE> <DEDENT> @property <NEW_LINE> def end(self): <NEW_LINE> <INDENT> return self.__exit__ | Generate a transaction scope. All actions within the scope should finish
successfully or else will undo themselves, and revert state safely. | 6259903f26238365f5faddcc |
class BaseEstimator(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def _get_param_names(cls): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> init = getattr(cls.__init__, 'deprecated_original', cls.__init__) <NEW_LINE> args, varargs, kw, default = inspect.getargspec(init) <NEW_LINE> if not varargs is None: <NEW_LINE> <INDENT> raise RuntimeError("scikit-learn estimators should always " "specify their parameters in the signature" " of their __init__ (no varargs)." " %s doesn't follow this convention." % (cls, )) <NEW_LINE> <DEDENT> args.pop(0) <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> args = [] <NEW_LINE> <DEDENT> args.sort() <NEW_LINE> return args <NEW_LINE> <DEDENT> def get_params(self, deep=True): <NEW_LINE> <INDENT> out = dict() <NEW_LINE> for key in self._get_param_names(): <NEW_LINE> <INDENT> warnings.simplefilter("always", DeprecationWarning) <NEW_LINE> try: <NEW_LINE> <INDENT> with warnings.catch_warnings(record=True) as w: <NEW_LINE> <INDENT> value = getattr(self, key, None) <NEW_LINE> <DEDENT> if len(w) and w[0].category == DeprecationWarning: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> warnings.filters.pop(0) <NEW_LINE> <DEDENT> if deep and hasattr(value, 'get_params'): <NEW_LINE> <INDENT> deep_items = value.get_params().items() <NEW_LINE> out.update((key + '__' + k, val) for k, val in deep_items) <NEW_LINE> <DEDENT> out[key] = value <NEW_LINE> <DEDENT> return out <NEW_LINE> <DEDENT> def set_params(self, **params): <NEW_LINE> <INDENT> if not params: <NEW_LINE> <INDENT> return self <NEW_LINE> <DEDENT> valid_params = self.get_params(deep=True) <NEW_LINE> for key, value in six.iteritems(params): <NEW_LINE> <INDENT> split = key.split('__', 1) <NEW_LINE> if len(split) > 1: <NEW_LINE> <INDENT> name, sub_name = split <NEW_LINE> if not name in valid_params: <NEW_LINE> <INDENT> raise ValueError('Invalid parameter %s for estimator %s' % (name, self)) <NEW_LINE> <DEDENT> sub_object = valid_params[name] <NEW_LINE> sub_object.set_params(**{sub_name: value}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if not key in valid_params: <NEW_LINE> <INDENT> raise ValueError('Invalid parameter %s ' 'for estimator %s' % (key, self.__class__.__name__)) <NEW_LINE> <DEDENT> setattr(self, key, value) <NEW_LINE> <DEDENT> <DEDENT> return self <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> class_name = self.__class__.__name__ <NEW_LINE> return '%s(%s)' % (class_name, _pprint(self.get_params(deep=False), offset=len(class_name),),) | Base class for all estimators in scikit-learn
Notes
-----
All estimators should specify all the parameters that can be set
at the class level in their __init__ as explicit keyword
arguments (no *args, **kwargs). | 6259903f82261d6c527307fe |
class named_user(run_user_base): <NEW_LINE> <INDENT> def _init_test_depenent(self): <NEW_LINE> <INDENT> user = None <NEW_LINE> for line in self.parent_subtest.stuff['passwd'].splitlines(): <NEW_LINE> <INDENT> line = line.strip() <NEW_LINE> if not line or line.startswith('root') or line.startswith('#'): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> user, _, uid, _ = line.split(':', 3) <NEW_LINE> break <NEW_LINE> <DEDENT> if not user: <NEW_LINE> <INDENT> msg = ("This container's image doesn't contain passwd with " "multiple users, unable to execute this test\n%s" % self.parent_subtest.stuff['passwd']) <NEW_LINE> raise xceptions.DockerTestNAError(msg) <NEW_LINE> <DEDENT> self.sub_stuff['execution_failure'] = False <NEW_LINE> self.sub_stuff['uid_check'] = "UIDCHECK: %s:" % uid <NEW_LINE> self.sub_stuff['whoami_check'] = "WHOAMICHECK: %s" % user <NEW_LINE> self.sub_stuff['subargs'] = ['--rm', '--interactive', '--user=%s' % user] | Finds any user but root existing on container and uses it by name | 6259903f94891a1f408ba031 |
class TurtleWaipoint(object): <NEW_LINE> <INDENT> def __init__(self, waypoint_x=None, waypoint_y=None): <NEW_LINE> <INDENT> self.x = None <NEW_LINE> self.y = None <NEW_LINE> self.theta = None <NEW_LINE> self.tolerance = 0.1 <NEW_LINE> self.got_position = False <NEW_LINE> self.finished = False <NEW_LINE> rospy.init_node('turtle_waypoint') <NEW_LINE> self.waypoint_x = waypoint_x <NEW_LINE> self.waypoint_y = waypoint_y <NEW_LINE> if waypoint_x is None or waypoint_y is None: <NEW_LINE> <INDENT> if False: <NEW_LINE> <INDENT> print("Waypoint found in param server") <NEW_LINE> self.waypoint_x = 0 <NEW_LINE> self.waypoint_y = 0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> print("No waypoint found in param server") <NEW_LINE> exit(1) <NEW_LINE> <DEDENT> <DEDENT> print('Heading to: {:.2f}, {:.2f}'.format(self.waypoint_x, self.waypoint_y)) <NEW_LINE> <DEDENT> def callback(self, msg): <NEW_LINE> <INDENT> self.got_position = True <NEW_LINE> <DEDENT> def iterate(self): <NEW_LINE> <INDENT> if self.finished: <NEW_LINE> <INDENT> print('Waypoint reached') <NEW_LINE> exit(0) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if self.got_position: <NEW_LINE> <INDENT> if True: <NEW_LINE> <INDENT> self.finished = True <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> math.atan2(1, 0) | Class to guide the turtle to the specified waypoint. | 6259903fb57a9660fecd2cf0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.