text:
The query builder is a utility to **generate CQL queries programmatically**. For example, it could
be used to:

* given a set of optional search parameters, build a search query dynamically depending on which
  parameters are provided;
* given a Java class, generate the CRUD queries that map instances of that class to a Cassandra
  table.

To use it in your application, add the following dependency:

```xml
<dependency>
  <groupId>com.datastax.oss</groupId>
  <artifactId>java-driver-query-builder</artifactId>
  <version>${driver.version}</version>
</dependency>
```

Here is our canonical example rewritten with the query builder:

```java
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.*;

try (CqlSession session = CqlSession.builder().build()) {

  Select query = selectFrom("system", "local").column("release_version"); // SELECT release_version FROM system.local
  SimpleStatement statement = query.build();

  ResultSet rs = session.execute(statement);
  Row row = rs.one();
  System.out.println(row.getString("release_version"));
}
```

### General concepts

#### Fluent API

All the starting methods are centralized in the [QueryBuilder] and [SchemaBuilder] classes. To get
started, add one of the following imports:

```java
// For DML queries, such as SELECT
import static com.datastax.oss.driver.api.querybuilder.QueryBuilder.*;

// For DDL queries, such as CREATE TABLE
import static com.datastax.oss.driver.api.querybuilder.SchemaBuilder.*;
```

Choose the method matching your desired statement, for example `selectFrom`. Then use your IDE's
completion and the javadocs to add query parts:

```java
Select select =
    selectFrom("ks", "user")
          .column("first_name")
          .column("last_name")
          .whereColumn("id").isEqualTo(bindMarker());
// SELECT first_name,last_name FROM ks.user WHERE id=?
```

When your query is complete, you can either extract a raw query string, or turn it into a
[simple statement](../core/statements/simple) (or its builder):

```java
String cql = select.asCql();
SimpleStatement statement = select.build();
SimpleStatementBuilder builder = select.builder();
```

#### DataStax Enterprise

The driver provides two additional entry points for DSE-specific queries: [DseQueryBuilder] and
[DseSchemaBuilder]. They extend their respective non-DSE counterparts, so anything that is available
on the default query builder can also be done with the DSE query builder.

We recommend that you use those classes if you are targeting DataStax Enterprise; they will be
enriched in the future if DSE adds custom CQL syntax.

Currently, the only difference is the support for the `DETERMINISTIC` and `MONOTONIC` keywords when
generating `CREATE FUNCTION` or `CREATE AGGREGATE` statements:

```java
import static com.datastax.dse.driver.api.querybuilder.DseSchemaBuilder.createDseFunction;

createDseFunction("func1")
    .withParameter("param1", DataTypes.INT)
    .returnsNullOnNull()
    .returnsType(DataTypes.INT)
    .deterministic()
    .monotonic();
// CREATE FUNCTION func1 (param1 int) RETURNS NULL ON NULL INPUT RETURNS int DETERMINISTIC MONOTONIC
```

#### Immutability

All types in the fluent API are immutable. This means that every step creates a new object:

```java
SelectFrom selectFrom = selectFrom("ks", "user");

Select select1 = selectFrom.column("first_name"); // SELECT first_name FROM ks.user
Select select2 = selectFrom.column("last_name"); // SELECT last_name FROM ks.user

assert select1 != select2;
```

Immutability has great benefits:

* **thread safety**: you can share built queries across threads, without any race condition or
  badly published state.
* **zero sharing**: when you build multiple queries from a shared "base" (as in the example above),
  all the queries are totally independent, changes to one query will never "pollute" another.

On the downside, immutability means that the query builder creates lots of short-lived objects.
Modern garbage collectors are good at handling that, but still we recommend that you **avoid using
the query builder in your hot path**:

* favor [bound statements](../core/statements/prepared) for queries that are used often. You can
  still use the query builder and prepare the result:

  ```java
  // During application initialization:
  Select selectUser = selectFrom("user").all().whereColumn("id").isEqualTo(bindMarker());
  // SELECT * FROM user WHERE id=?
  PreparedStatement preparedSelectUser = session.prepare(selectUser.build());

  // At runtime:
  session.execute(preparedSelectUser.bind(userId));
  ```
* for queries that never change, build them when your application initializes, and store them in a
  field or constant for later.
* for queries that are built dynamically, consider using a cache.

#### Identifiers

All fluent API methods use [CqlIdentifier] for schema element names (keyspaces, tables, columns...).
But, for convenience, there are also `String` overloads that take the CQL form (as see [Case
sensitivity](../case_sensitivity) for more explanations).

For conciseness, we'll use the string-based versions for the examples in this manual.

### Non-goals

The query builder is **NOT**:

#### A crutch to learn CQL

While the fluent API guides you, it does not encode every rule of the CQL grammar. Also, it supports
a wide range of Cassandra versions, some of which may be more recent than your production target, or
not even released yet. It's still possible to generate invalid CQL syntax if you don't know what
you're doing.

You should always start with a clear idea of the CQL query, and write the builder code that produces
it, not the other way around.

#### A better way to write static queries

The primary use case of the query builder is dynamic generation. You will get the most value out of
it when you do things like:

```java
// The columns to select are only known at runtime:
for (String columnName : columnNames) {
  select = select.column(columnName)
}

// If a search parameter is present, add the corresponding WHERE clause:
if (name != null) {
  select = select.whereColumn("name").isEqualTo(name);
}
```

If all of your queries could also be written as compile-time string constants, ask yourself what the
query builder is really buying you:

```java
// Built version:
private static final Statement SELECT_USERS =
    selectFrom("user").all().limit(10).build();

// String version:
private static final Statement SELECT_USERS =
    SimpleStatement.newInstance("SELECT * FROM user LIMIT 10");
```

The built version:

* is slightly more expensive to build (admittedly, that is not really an issue for constants);
* is not more readable;
* is not necessarily less error-prone (see the previous section).

It eventually boils down to personal taste, but for simple cases you should consider raw strings as
a better alternative.

### Building queries

For a complete tour of the API, browse the child pages in this manual:

* statement types:
  * [SELECT](select/)
  * [INSERT](insert/)
  * [UPDATE](update/)
  * [DELETE](delete/)
  * [TRUNCATE](truncate/)
  * [Schema builder](schema/) (for DDL statements such as CREATE TABLE, etc.)
* common topics:
  * [Relations](relation/)
  * [Conditions](condition/)
  * [Terms](term/)
  * [Idempotence](idempotence/)

[QueryBuilder]:  https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/querybuilder/QueryBuilder.html
[SchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/querybuilder/SchemaBuilder.html
[CqlIdentifier]: https://docs.datastax.com/en/drivers/java/4.14/com/datastax/oss/driver/api/core/CqlIdentifier.html
[DseQueryBuilder]: https://docs.datastax.com/en/drivers/java/4.14/com/datastax/dse/driver/api/querybuilder/DseQueryBuilder.html
[DseSchemaBuilder]: https://docs.datastax.com/en/drivers/java/4.14/com/datastax/dse/driver/api/querybuilder/DseSchemaBuilder.html


text:
@interface ARArtworkPriceRowView : UIView

@property (nonatomic, strong) UILabel *messageLabel;
@property (nonatomic) CGFloat margin;
@property (nonatomic, assign) NSString *bidStatusText;
@property (nonatomic, strong) UILabel *priceLabel;

@end

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

RSpec.describe OneviewSDK::API2000::Synergy::LogicalInterconnect do
  include_context 'shared context'

  it 'inherits from OneviewSDK::API2000::C7000::LogicalInterconnect' do
    expect(described_class).to be < OneviewSDK::API2000::C7000::LogicalInterconnect
  end
end


text:
""" Tests for cpu resource limits
"""
# Import Local Modules
from nose.plugins.attrib import attr
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.lib.base import (
                                        Account,
                                        ServiceOffering,
                                        VirtualMachine,
                                        Domain,
                                        Resources
                                        )
from marvin.lib.common import (get_domain,
                                        get_zone,
                                        get_template,
                                        findSuitableHostForMigration,
                                        get_resource_type
                                        )
from marvin.lib.utils import cleanup_resources
from marvin.codes import ERROR_NO_HOST_FOR_MIGRATION

class Services:
    """Test resource limit services
    """

    def __init__(self):
        self.services = {
                        "account": {
                                "email": "test@test.com",
                                "firstname": "Test",
                                "lastname": "User",
                                "username": "resource",
                                # Random characters are appended for unique
                                # username
                                "password": "password",
                         },
                         "service_offering": {
                                "name": "Tiny Instance",
                                "displaytext": "Tiny Instance",
                                "cpunumber": 4,
                                "cpuspeed": 100,    # in MHz
                                "memory": 128,    # In MBs
                        },
                        "virtual_machine": {
                                "displayname": "TestVM",
                                "username": "root",
                                "password": "password",
                                "ssh_port": 22,
                                "hypervisor": 'KVM',
                                "privateport": 22,
                                "publicport": 22,
                                "protocol": 'TCP',
                                },
                         "network": {
                                "name": "Test Network",
                                "displaytext": "Test Network",
                                "netmask": '255.255.255.0'
                                },
                         "project": {
                                "name": "Project",
                                "displaytext": "Test project",
                                },
                         "domain": {
                                "name": "Domain",
                                },
                        "ostype": 'CentOS 5.3 (64-bit)',
                        "sleep": 60,
                        "timeout": 10,
                        "mode": 'advanced',
                        # Networking mode: Advanced, Basic
                    }

class TestCPULimits(cloudstackTestCase):

    @classmethod
    def setUpClass(cls):
        cls.testClient = super(TestCPULimits, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
        cls.services["mode"] = cls.zone.networktype

        cls.template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )

        cls.services["virtual_machine"]["zoneid"] = cls.zone.id

        cls.service_offering = ServiceOffering.create(
                                            cls.api_client,
                                            cls.services["service_offering"]
                                            )

        cls._cleanup = [cls.service_offering, ]
        return

    @classmethod
    def tearDownClass(cls):
        try:
            # Cleanup resources used
            cleanup_resources(cls.api_client, cls._cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()
        self.account = Account.create(
                            self.apiclient,
                            self.services["account"],
                            admin=True
                            )

        self.debug("Creating an instance with service offering: %s" %
                                                    self.service_offering.name)
        self.vm = self.createInstance(service_off=self.service_offering)

        self.cleanup = [self.account, ]
        return

    def tearDown(self):
        try:
            # Clean up, terminate the created instance, volumes and snapshots
            cleanup_resources(self.apiclient, self.cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    def createInstance(self, service_off, networks=None, api_client=None):
        """Creates an instance in account
        """
        if api_client is None:
            api_client = self.apiclient

        self.debug("Deploying an instance in account: %s" %
                       self.account.name)
        try:
            vm = VirtualMachine.create(
                    api_client,
                    self.services["virtual_machine"],
                    templateid=self.template.id,
                    accountid=self.account.name,
                    domainid=self.account.domainid,
                    networkids=networks,
                    serviceofferingid=service_off.id)
            vms = VirtualMachine.list(api_client, id=vm.id, listall=True)
            self.assertIsInstance(vms,
                    list,
                    "List VMs should return a valid response")
            self.assertEqual(vms[0].state, "Running",
                    "Vm state should be running after deployment")
            return vm
        except Exception as e:
            self.fail("Failed to deploy an instance: %s" % e)

    @attr(tags=["advanced", "advancedns","simulator"], required_hardware="false")
    def test_01_multiplecore_start_stop_instance(self):
        """Test Deploy VM with multiple core CPU & verify the usage"""

        # Validate the following
        # 1. Deploy VM with multiple core CPU & verify the usage
        # 2. Stop VM & verify the update resource count of Root Admin Account
        # 3. Start VM & verify the update resource count of Root Admin Account
        # 4. Resource count should list properly.

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
                              list,
                              "List Accounts should return a valid response"
                              )
        resource_count = account_list[0].cputotal

        expected_resource_count = int(self.services["service_offering"]["cpunumber"])

        self.assertEqual(resource_count, expected_resource_count,
                         "Resource count should match with the expected resource count")

        self.debug("Stopping instance: %s" % self.vm.name)
        try:
            self.vm.stop(self.apiclient)
        except Exception as e:
            self.fail("Failed to stop instance: %s" % e)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
                              list,
                              "List Accounts should return a valid response"
                              )
        resource_count_after_stop = account_list[0].cputotal

        self.assertEqual(resource_count, resource_count_after_stop,
                         "Resource count should be same after stopping the instance")

        self.debug("Starting instance: %s" % self.vm.name)
        try:
            self.vm.start(self.apiclient)
        except Exception as e:
            self.fail("Failed to start instance: %s" % e)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
                              list,
                              "List Accounts should return a valid response"
                              )
        resource_count_after_start = account_list[0].cputotal

        self.assertEqual(resource_count, resource_count_after_start,
                         "Resource count should be same after stopping the instance")
        return

    @attr(tags=["advanced", "advancedns","simulator"], required_hardware="true")
    def test_02_multiplecore_migrate_instance(self):
        """Test Deploy VM with multiple core CPU & verify the usage"""

        # Validate the following
        # 1. Deploy VM with multiple core CPU & verify the usage
        # 2. Migrate VM & verify updated resource count of Root Admin Account
        # 3. Resource count should list properly.
        self.hypervisor = self.testClient.getHypervisorInfo()
        if self.hypervisor.lower() in ['lxc']:
            self.skipTest("vm migrate is not supported in %s" % self.hypervisor)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
                              list,
                              "List Accounts should return a valid response"
                              )
        resource_count = account_list[0].cputotal

        expected_resource_count = int(self.services["service_offering"]["cpunumber"])

        self.assertEqual(resource_count, expected_resource_count,
                         "Resource count should match with the expected resource count")

        host = findSuitableHostForMigration(self.apiclient, self.vm.id)
        if host is None:
            self.skipTest(ERROR_NO_HOST_FOR_MIGRATION)
        self.debug("Migrating instance: %s to host: %s" % (self.vm.name, host.name))
        try:
            self.vm.migrate(self.apiclient, host.id)
        except Exception as e:
            self.fail("Failed to migrate instance: %s" % e)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
                              list,
                              "List Accounts should return a valid response"
                              )
        resource_count_after_migrate = account_list[0].cputotal

        self.assertEqual(resource_count, resource_count_after_migrate,
                         "Resource count should be same after migrating the instance")
        return

    @attr(tags=["advanced", "advancedns","simulator"], required_hardware="false")
    def test_03_multiplecore_delete_instance(self):
        """Test Deploy VM with multiple core CPU & verify the usage"""

        # Validate the following
        # 1. Deploy VM with multiple core CPU & verify the usage
        # 2. Destroy VM & verify update resource count of Root Admin Account
        # 3. Resource count should list properly.

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
                              list,
                              "List Accounts should return a valid response"
                              )
        resource_count = account_list[0].cputotal

        expected_resource_count = int(self.services["service_offering"]["cpunumber"])

        self.assertEqual(resource_count, expected_resource_count,
                         "Resource count should match with the expected resource count")

        self.debug("Destroying instance: %s" % self.vm.name)
        try:
            self.vm.delete(self.apiclient)
        except Exception as e:
            self.fail("Failed to delete instance: %s" % e)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
                              list,
                              "List Accounts should return a valid response"
                              )
        resource_count = account_list[0].cputotal
        self.assertEqual(resource_count, 0 , "Resource count for %s should be 0" % get_resource_type(resource_id=8))#CPU
        return

    @attr(tags=["advanced", "advancedns","simulator"], required_hardware="true")
    def test_04_deploy_multiple_vm_with_multiple_cpus(self):
        """Test Deploy multiple VM with 4 core CPU & verify the usage"""

        # Validate the following
        # 1. Create compute offering with 4 core CPU
        # 2. Deploy multiple VMs with this service offering
        # 3. List Resource count for the root admin CPU usage
        # 4. CPU usage should list properly
        # 5. Destroy one VM among multiple VM's and verify the resource count
        # 6. Migrate VM from & verify resource updates
        # 7. List resource count for Root Admin
        # 8. Failed to deploy VM and verify the resource usage

        self.debug("Creating service offering with 4 CPU cores")
        self.service_offering = ServiceOffering.create(
                                            self.apiclient,
                                            self.services["service_offering"]
                                            )
        # Adding to cleanup list after execution
        self.cleanup.append(self.service_offering)

        self.debug("Creating an instance with service offering: %s" %
                                                    self.service_offering.name)
        vm_1 = self.createInstance(service_off=self.service_offering)
        vm_2 = self.createInstance(service_off=self.service_offering)
        self.createInstance(service_off=self.service_offering)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
                              list,
                              "List Accounts should return a valid response"
                              )
        resource_count = account_list[0].cputotal

        expected_resource_count = int(self.services["service_offering"]["cpunumber"]) * 4 #Total 4 Vms
        self.assertTrue(resource_count == expected_resource_count,
                         "Resource count does not match the expected vavlue")
        return

class TestDomainCPULimitsConfiguration(cloudstackTestCase):

    @classmethod
    def setUpClass(cls):
        cls.testClient = super(TestDomainCPULimitsConfiguration, cls).getClsTestClient()
        cls.api_client = cls.testClient.getApiClient()

        cls.services = Services().services
        # Get Zone, Domain and templates
        cls.domain = get_domain(cls.api_client)
        cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())

        cls.services["mode"] = cls.zone.networktype
        cls.template = get_template(
                            cls.api_client,
                            cls.zone.id,
                            cls.services["ostype"]
                            )

        cls.service_offering = ServiceOffering.create(
                                            cls.api_client,
                                            cls.services["service_offering"]
                                            )

        cls.services["virtual_machine"]["zoneid"] = cls.zone.id

        cls._cleanup = [cls.service_offering, ]
        return

    @classmethod
    def tearDownClass(cls):
        try:
            # Cleanup resources used
            cleanup_resources(cls.api_client, cls._cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    def setUp(self):
        self.apiclient = self.testClient.getApiClient()
        self.dbclient = self.testClient.getDbConnection()
        self.cleanup = []
        return

    def tearDown(self):
        try:
            # Clean up, terminate the created instance, volumes and snapshots
            cleanup_resources(self.apiclient, self.cleanup)
        except Exception as e:
            raise Exception("Warning: Exception during cleanup : %s" % e)
        return

    def createInstance(self, service_off, networks=None, api_client=None):
        """Creates an instance in account
        """
        if api_client is None:
            api_client = self.apiclient

        self.debug("Deploying an instance in account: %s" %
                       self.account.name)
        try:
            vm = VirtualMachine.create(
                    api_client,
                    self.services["virtual_machine"],
                    templateid=self.template.id,
                    accountid=self.account.name,
                    domainid=self.account.domainid,
                    networkids=networks,
                    serviceofferingid=service_off.id)
            vms = VirtualMachine.list(api_client, id=vm.id, listall=True)
            self.assertIsInstance(vms,
                    list,
                    "List VMs should return a valid response")
            self.assertEqual(vms[0].state, "Running",
                    "Vm state should be running after deployment")
            return vm
        except Exception as e:
            self.fail("Failed to deploy an instance: %s" % e)

    def setupAccounts(self):

        self.debug("Creating a sub-domain under: %s" % self.domain.name)
        self.child_domain_1 = Domain.create(
            self.apiclient,
            services=self.services["domain"],
            parentdomainid=self.domain.id
        )
        self.child_do_admin_1 = Account.create(
            self.apiclient,
            self.services["account"],
            admin=True,
            domainid=self.child_domain_1.id
        )
        # Cleanup the resources created at end of test
        self.cleanup.append(self.child_do_admin_1)
        self.cleanup.append(self.child_domain_1)

        self.child_domain_2 = Domain.create(
            self.apiclient,
            services=self.services["domain"],
            parentdomainid=self.domain.id
        )

        self.child_do_admin_2 = Account.create(
            self.apiclient,
            self.services["account"],
            admin=True,
            domainid=self.child_domain_2.id
        )

        # Cleanup the resources created at end of test
        self.cleanup.append(self.child_do_admin_2)
        self.cleanup.append(self.child_domain_2)

        return

    @attr(tags=["advanced", "advancedns","simulator"], required_hardware="false")
    def test_01_stop_start_instance(self):
        """Test Deploy VM with 4 core CPU & verify the usage"""

        # Validate the following
        # 1. Create compute offering with 4 core CPU & Deploy VM
        # 2. List Resource count CPU usage
        # 3. Stop and Start instance, check resource count.
        # 4. Resource count should list properly.

        self.debug("Setting up account and domain hierarchy")
        self.setupAccounts()
        users = {self.child_domain_1: self.child_do_admin_1,
                 self.child_domain_2: self.child_do_admin_2
                 }
        for domain, admin in users.items():
            self.account = admin
            self.domain = domain

        api_client = self.testClient.getUserApiClient(
            UserName=self.account.name,
            DomainName=self.account.domain)

        self.debug("Creating an instance with service offering: %s" %
                   self.service_offering.name)
        vm = self.createInstance(service_off=self.service_offering, api_client=api_client)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
            list,
            "List Accounts should return a valid response"
        )
        resource_count = account_list[0].cputotal

        expected_resource_count = int(self.services["service_offering"]["cpunumber"])

        self.assertEqual(resource_count, expected_resource_count,
            "Initial resource count should match with the expected resource count")

        self.debug("Stopping instance: %s" % vm.name)
        try:
            vm.stop(self.apiclient)
        except Exception as e:
            self.fail("Failed to stop instance: %s" % e)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
            list,
            "List Accounts should return a valid response"
        )
        resource_count_after_stop = account_list[0].cputotal

        self.assertEqual(resource_count, resource_count_after_stop,
            "Resource count should be same after stopping the instance")

        self.debug("Starting instance: %s" % vm.name)
        try:
            vm.start(self.apiclient)
        except Exception as e:
            self.fail("Failed to start instance: %s" % e)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
            list,
            "List Accounts should return a valid response"
        )
        resource_count_after_start = account_list[0].cputotal

        self.assertEqual(resource_count_after_stop, resource_count_after_start,
            "Resource count should be same after starting the instance")
        return

    @attr(tags=["advanced", "advancedns","simulator"], required_hardware="true")
    def test_02_migrate_instance(self):
        """Test Deploy VM with 4 core CPU & verify the usage"""

        # Validate the following
        # 1. Create compute offering with 4 core CPU & Deploy VM
        # 2. List Resource count
        # 3. Migrate instance to another host
        # 4. Resource count should list properly.
        self.hypervisor = self.testClient.getHypervisorInfo()
        if self.hypervisor.lower() in ['lxc']:
            self.skipTest("vm migrate is not supported in %s" % self.hypervisor)

        self.debug("Setting up account and domain hierarchy")
        self.setupAccounts()
        users = {self.child_domain_1: self.child_do_admin_1,
                 self.child_domain_2: self.child_do_admin_2
                 }
        for domain, admin in users.items():
            self.account = admin
            self.domain = domain

        api_client = self.testClient.getUserApiClient(
            UserName=self.account.name,
            DomainName=self.account.domain)

        self.debug("Creating an instance with service offering: %s" %
                   self.service_offering.name)
        vm = self.createInstance(service_off=self.service_offering, api_client=api_client)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
            list,
            "List Accounts should return a valid response"
        )
        resource_count = account_list[0].cputotal

        expected_resource_count = int(self.services["service_offering"]["cpunumber"])

        self.assertEqual(resource_count, expected_resource_count,
            "Initial resource count should with the expected resource count")

        host = findSuitableHostForMigration(self.apiclient, vm.id)
        if host is None:
            self.skipTest(ERROR_NO_HOST_FOR_MIGRATION)
        self.debug("Migrating instance: %s to host: %s" %
                   (vm.name, host.name))
        try:
            vm.migrate(self.apiclient, host.id)
        except Exception as e:
            self.fail("Failed to migrate instance: %s" % e)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
            list,
            "List Accounts should return a valid response"
        )
        resource_count_after_migrate = account_list[0].cputotal

        self.assertEqual(resource_count, resource_count_after_migrate,
            "Resource count should be same after starting the instance")
        return

    @attr(tags=["advanced", "advancedns","simulator"], required_hardware="false")
    def test_03_delete_instance(self):
        """Test Deploy VM with 4 core CPU & verify the usage"""

        # Validate the following
        # 1. Create compute offering with 4 core CPU & Deploy VM
        # 2. List Resource count for the CPU usage
        # 3. Delete instance
        # 4. Resource count should list as 0

        self.debug("Setting up account and domain hierarchy")
        self.setupAccounts()
        users = {self.child_domain_1: self.child_do_admin_1,
                 self.child_domain_2: self.child_do_admin_2
                 }
        for domain, admin in users.items():
            self.account = admin
            self.domain = domain

        api_client = self.testClient.getUserApiClient(
            UserName=self.account.name,
            DomainName=self.account.domain)

        self.debug("Creating an instance with service offering: %s" %
                   self.service_offering.name)
        vm = self.createInstance(service_off=self.service_offering, api_client=api_client)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
            list,
            "List Accounts should return a valid response"
        )
        resource_count = account_list[0].cputotal

        expected_resource_count = int(self.services["service_offering"]["cpunumber"])

        self.assertEqual(resource_count, expected_resource_count,
            "Initial resource count should match with the expected resource count")

        self.debug("Destroying instance: %s" % vm.name)
        try:
            vm.delete(self.apiclient)
        except Exception as e:
            self.fail("Failed to delete instance: %s" % e)

        account_list = Account.list(self.apiclient, id=self.account.id)
        self.assertIsInstance(account_list,
            list,
            "List Accounts should return a valid response"
        )
        resource_count = account_list[0].cputotal
        self.assertEqual(resource_count, 0, "Resource count for %s should be 0" % get_resource_type(resource_id=8))#CPU
        return

    @attr(tags=["advanced", "advancedns","simulator"])
    @attr(configuration='max.account.cpus')
    def test_04_deploy_multiple_vm_with_multiple_cpus(self):
        """Test Deploy multiple VM with 4 core CPU & verify the usage"""
        #keep the configuration value - max.account.cpus number = 16
        # Validate the following
        # 1. Create compute offering with 4 core CPU
        # 2. Deploy multiple VMs with this service offering
        # 3. List Resource count for the root admin CPU usage
        # 4. CPU usage should list properly

        self.debug("Creating service offering with 4 CPU cores")
        self.service_offering = ServiceOffering.create(
                                            self.apiclient,
                                            self.services["service_offering"]
                                            )
        # Adding to cleanup list after execution
        self.cleanup.append(self.service_offering)

        self.debug("Setting up account and domain hierarchy")
        self.setupAccounts()
        users = {self.child_domain_1: self.child_do_admin_1,
                 self.child_domain_2: self.child_do_admin_2
                 }
        for domain, admin in users.items():
            self.account = admin
            self.domain = domain

            cpu_account_gc = Resources.list(self.apiclient,
                                resourcetype = 8, #CPU
                                account = self.account.name,
                                domainid = self.domain.id
                                )

            if cpu_account_gc[0].max != 16:
                self.skipTest("This test case requires configuration value max.account.cpus to be 16")

            api_client = self.testClient.getUserApiClient(
                UserName=self.account.name,
                DomainName=self.account.domain)

            self.debug("Creating an instance with service offering: %s" %
                       self.service_offering.name)
            vm_1 = self.createInstance(service_off=self.service_offering, api_client=api_client)
            vm_2 = self.createInstance(service_off=self.service_offering, api_client=api_client)
            self.createInstance(service_off=self.service_offering, api_client=api_client)
            self.createInstance(service_off=self.service_offering, api_client=api_client)

            self.debug("Deploying instance - CPU capacity is fully utilized")
            with self.assertRaises(Exception):
                self.createInstance(service_off=self.service_offering, api_client=api_client)

            account_list = Account.list(self.apiclient, id=self.account.id)
            self.assertIsInstance(account_list,
                list,
                "List Accounts should return a valid response"
            )
            resource_count = account_list[0].cputotal

            expected_resource_count = int(self.services["service_offering"]["cpunumber"]) * 4 #Total 4 vms

            self.assertEqual(resource_count, expected_resource_count,
                "Initial resource count should with the expected resource count")

            self.debug("Destroying instance: %s" % vm_1.name)
            try:
                vm_1.delete(self.apiclient)
            except Exception as e:
                self.fail("Failed to delete instance: %s" % e)

            account_list = Account.list(self.apiclient, id=self.account.id)
            self.assertIsInstance(account_list,
                list,
                "List Accounts should return a valid response"
            )
            resource_count_after_delete = account_list[0].cputotal

            expected_resource_count -= int(self.services["service_offering"]["cpunumber"])

            self.assertEqual(resource_count_after_delete, expected_resource_count,
                "Resource count should be less than before after deleting the instance")

            host = findSuitableHostForMigration(self.apiclient, vm_2.id)
            if host is None:
                self.skipTest(ERROR_NO_HOST_FOR_MIGRATION)
            self.debug("Migrating instance: %s to host: %s" % (vm_2.name,
                                                               host.name))
            try:
                vm_2.migrate(self.apiclient, host.id)
            except Exception as e:
                self.fail("Failed to migrate instance: %s" % e)

            account_list = Account.list(self.apiclient, id=self.account.id)
            self.assertIsInstance(account_list,
                list,
                "List Accounts should return a valid response"
            )
            resource_count_after_migrate = account_list[0].cputotal

            self.debug(resource_count_after_migrate)
            self.assertEqual(resource_count_after_delete, resource_count_after_migrate,
                "Resource count should be same after migrating the instance")


text:
namespace ndnboost {

#if !defined( __CODEGEARC__ )

namespace detail{

#if !(defined(__EDG_VERSION__) && __EDG_VERSION__ <= 238) && !defined(NDNBOOST_NO_INCLASS_MEMBER_INITIALIZATION)

template <class T>
struct is_unsigned_values
{
   //
   // Note that we cannot use NDNBOOST_STATIC_CONSTANT here, using enum's
   // rather than "real" static constants simply doesn't work or give
   // the correct answer.
   //
   typedef typename remove_cv<T>::type no_cv_t;
   static const no_cv_t minus_one = (static_cast<no_cv_t>(-1));
   static const no_cv_t zero = (static_cast<no_cv_t>(0));
};

template <class T>
struct is_ununsigned_helper
{
   NDNBOOST_STATIC_CONSTANT(bool, value = (::ndnboost::detail::is_unsigned_values<T>::minus_one > ::ndnboost::detail::is_unsigned_values<T>::zero));
};

template <bool integral_type>
struct is_ununsigned_select_helper
{
   template <class T>
   struct rebind
   {
      typedef is_ununsigned_helper<T> type;
   };
};

template <>
struct is_ununsigned_select_helper<false>
{
   template <class T>
   struct rebind
   {
      typedef false_type type;
   };
};

template <class T>
struct is_unsigned_imp
{
   typedef is_ununsigned_select_helper<
      ::ndnboost::type_traits::ice_or<
         ::ndnboost::is_integral<T>::value,
         ::ndnboost::is_enum<T>::value>::value
   > selector;
   typedef typename selector::template rebind<T> binder;
   typedef typename binder::type type;
   NDNBOOST_STATIC_CONSTANT(bool, value = type::value);
};

#else

template <class T> struct is_unsigned_imp : public false_type{};
template <> struct is_unsigned_imp<unsigned char> : public true_type{};
template <> struct is_unsigned_imp<const unsigned char> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned char> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned char> : public true_type{};
template <> struct is_unsigned_imp<unsigned short> : public true_type{};
template <> struct is_unsigned_imp<const unsigned short> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned short> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned short> : public true_type{};
template <> struct is_unsigned_imp<unsigned int> : public true_type{};
template <> struct is_unsigned_imp<const unsigned int> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned int> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned int> : public true_type{};
template <> struct is_unsigned_imp<unsigned long> : public true_type{};
template <> struct is_unsigned_imp<const unsigned long> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned long> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned long> : public true_type{};
#ifdef NDNBOOST_HAS_LONG_LONG
template <> struct is_unsigned_imp<unsigned long long> : public true_type{};
template <> struct is_unsigned_imp<const unsigned long long> : public true_type{};
template <> struct is_unsigned_imp<volatile unsigned long long> : public true_type{};
template <> struct is_unsigned_imp<const volatile unsigned long long> : public true_type{};
#endif
#if defined(CHAR_MIN) && (CHAR_MIN == 0)
template <> struct is_unsigned_imp<char> : public true_type{};
template <> struct is_unsigned_imp<const char> : public true_type{};
template <> struct is_unsigned_imp<volatile char> : public true_type{};
template <> struct is_unsigned_imp<const volatile char> : public true_type{};
#endif
#if defined(WCHAR_MIN) && (WCHAR_MIN == 0) && !defined(NDNBOOST_NO_INTRINSIC_WCHAR_T)
template <> struct is_unsigned_imp<wchar_t> : public true_type{};
template <> struct is_unsigned_imp<const wchar_t> : public true_type{};
template <> struct is_unsigned_imp<volatile wchar_t> : public true_type{};
template <> struct is_unsigned_imp<const volatile wchar_t> : public true_type{};
#endif

#endif

}

#endif // !defined( __CODEGEARC__ )

#if defined( __CODEGEARC__ )
NDNBOOST_TT_AUX_BOOL_TRAIT_DEF1(is_unsigned,T,__is_unsigned(T))
#else
NDNBOOST_TT_AUX_BOOL_TRAIT_DEF1(is_unsigned,T,::ndnboost::detail::is_unsigned_imp<T>::value)
#endif

} // namespace ndnboost

#include <ndnboost/type_traits/detail/bool_trait_undef.hpp>

#endif // NDNBOOST_TT_IS_MEMBER_FUNCTION_POINTER_HPP_INCLUDED


text:
package org.acre.pdmengine.analyzer;

import org.acre.pdmengine.model.ArtifactLink;

import java.util.ArrayList;
import java.util.List;

/**
 * @author rajmohan@Sun.com
 */
public class ArtifactLinksTreeNode {
    private ArtifactLink link;

    public ArtifactLinksTreeNode(ArtifactLink link) {
        this.link = link;
    }

    public ArtifactLink getLink() { return link; }

    // List<ArtifactLinksTreeNode>
    public List getNextLinkNodes() {
            return chains;
    }

    void addLinkNode(ArtifactLinksTreeNode chainedLink) {
        chains.add(chainedLink);
    }

    List chains = new ArrayList();
}


text:
extern zend_class_entry *stub_bench_foo_ce;

ZEPHIR_INIT_CLASS(Stub_Bench_Foo);

PHP_METHOD(Stub_Bench_Foo, emptyForInRange);
PHP_METHOD(Stub_Bench_Foo, readStatic);
PHP_METHOD(Stub_Bench_Foo, writeStatic);
PHP_METHOD(Stub_Bench_Foo, issetStatic);
PHP_METHOD(Stub_Bench_Foo, emptyStatic);
PHP_METHOD(Stub_Bench_Foo, readProp);
PHP_METHOD(Stub_Bench_Foo, writeProp);
PHP_METHOD(Stub_Bench_Foo, assignAddProp);
PHP_METHOD(Stub_Bench_Foo, postIncProp);
PHP_METHOD(Stub_Bench_Foo, postDecProp);
PHP_METHOD(Stub_Bench_Foo, issetProp);
PHP_METHOD(Stub_Bench_Foo, emptyProp);
PHP_METHOD(Stub_Bench_Foo, g);
PHP_METHOD(Stub_Bench_Foo, call);
PHP_METHOD(Stub_Bench_Foo, staticMethod);
PHP_METHOD(Stub_Bench_Foo, staticMethod1);
PHP_METHOD(Stub_Bench_Foo, scall);
PHP_METHOD(Stub_Bench_Foo, scallWithReturnTrue);
PHP_METHOD(Stub_Bench_Foo, readConst);

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_emptyforinrange, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_readstatic, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_writestatic, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_issetstatic, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_emptystatic, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_readprop, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_writeprop, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_assignaddprop, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_postincprop, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_postdecprop, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_issetprop, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_emptyprop, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_g, 0, 0, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_call, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_stub_bench_foo_staticmethod, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_stub_bench_foo_staticmethod1, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_scall, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_scallwithreturntrue, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEND_BEGIN_ARG_INFO_EX(arginfo_stub_bench_foo_readconst, 0, 0, 1)
	ZEND_ARG_INFO(0, n)
ZEND_END_ARG_INFO()

ZEPHIR_INIT_FUNCS(stub_bench_foo_method_entry) {
	PHP_ME(Stub_Bench_Foo, emptyForInRange, arginfo_stub_bench_foo_emptyforinrange, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	PHP_ME(Stub_Bench_Foo, readStatic, arginfo_stub_bench_foo_readstatic, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	PHP_ME(Stub_Bench_Foo, writeStatic, arginfo_stub_bench_foo_writestatic, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	PHP_ME(Stub_Bench_Foo, issetStatic, arginfo_stub_bench_foo_issetstatic, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	PHP_ME(Stub_Bench_Foo, emptyStatic, arginfo_stub_bench_foo_emptystatic, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
	PHP_ME(Stub_Bench_Foo, readProp, arginfo_stub_bench_foo_readprop, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, writeProp, arginfo_stub_bench_foo_writeprop, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, assignAddProp, arginfo_stub_bench_foo_assignaddprop, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, postIncProp, arginfo_stub_bench_foo_postincprop, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, postDecProp, arginfo_stub_bench_foo_postdecprop, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, issetProp, arginfo_stub_bench_foo_issetprop, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, emptyProp, arginfo_stub_bench_foo_emptyprop, ZEND_ACC_PUBLIC)
#if PHP_VERSION_ID >= 80000
	PHP_ME(Stub_Bench_Foo, g, arginfo_stub_bench_foo_g, ZEND_ACC_PUBLIC)
#else
	PHP_ME(Stub_Bench_Foo, g, NULL, ZEND_ACC_PUBLIC)
#endif
	PHP_ME(Stub_Bench_Foo, call, arginfo_stub_bench_foo_call, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, staticMethod, arginfo_stub_bench_foo_staticmethod, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, staticMethod1, arginfo_stub_bench_foo_staticmethod1, ZEND_ACC_STATIC|ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, scall, arginfo_stub_bench_foo_scall, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, scallWithReturnTrue, arginfo_stub_bench_foo_scallwithreturntrue, ZEND_ACC_PUBLIC)
	PHP_ME(Stub_Bench_Foo, readConst, arginfo_stub_bench_foo_readconst, ZEND_ACC_PUBLIC)
	PHP_FE_END
};


text:
#ifndef __RegionAttachment_h__
#define __RegionAttachment_h__

#include "Attachment.h"
#include "Atlas.h"
#include "Slot.h"

namespace spine {

typedef enum
{
	VERTEX_X1 = 0, VERTEX_Y1, VERTEX_X2, VERTEX_Y2, VERTEX_X3, VERTEX_Y3, VERTEX_X4, VERTEX_Y4
} VertexIndex;

typedef struct RegionAttachment RegionAttachment;
struct RegionAttachment
{
	Attachment		super;
	KDfloat			x, y, scaleX, scaleY, rotation, width, height;

	KDvoid*			rendererObject;
	KDint			regionOffsetX, regionOffsetY;				/* Pixels stripped from the bottom left, unrotated. */
	KDint			regionWidth, regionHeight;					/* Unrotated, stripped pixel size. */
	KDint			regionOriginalWidth, regionOriginalHeight;	/* Unrotated, unstripped pixel size. */

	KDfloat			offset[8];
	KDfloat			uvs[8];
};

RegionAttachment*	RegionAttachment_create ( const KDchar* pName );
KDvoid				RegionAttachment_setUVs ( RegionAttachment* pSelf, KDfloat u, KDfloat v, KDfloat u2, KDfloat v2, KDint nRotate );
KDvoid				RegionAttachment_updateOffset ( RegionAttachment* pSelf );
KDvoid				RegionAttachment_computeVertices ( RegionAttachment* pSelf, KDfloat x, KDfloat y, Bone* pBone, KDfloat* pVertices );

} // namespace spine {

#endif	// __RegionAttachment_h__


text:
.. _pbkdf:

Password Based Key Derivation
========================================

Often one needs to convert a human readable password into a cryptographic
key. It is useful to slow down the computation of these computations in order to
reduce the speed of brute force search, thus they are parameterized in some
way which allows their required computation to be tuned.

PasswordHash
--------------

.. versionadded:: 2.8.0

This API, declared in ``pwdhash.h``, has two classes, ``PasswordHashFamily``
representing the general algorithm, such as "PBKDF2(SHA-256)", or "Scrypt", and
``PasswordHash`` representing a specific instance of the problem which is fully
specified with all parameters (say "Scrypt" with ``N`` = 8192, ``r`` = 64, and
``p`` = 8) and which can be used to derive keys.

.. cpp:class:: PasswordHash

   .. cpp:function:: void derive_key(uint8_t out[], size_t out_len, \
                     const char* password, const size_t password_len, \
                     const uint8_t salt[], size_t salt_len) const

      Derive a key from the specified password and salt, placing it into output.

   .. cpp:function:: void derive_key(uint8_t out[], size_t out_len, \
                     const char* password, const size_t password_len, \
                     const uint8_t salt[], size_t salt_len, \
                     const uint8_t ad[], size_t ad_len, \
                     const uint8_t key[], size_t key_len) const

      Derive a key from the specified password, salt, associated data, and
      secret key, placing it into output. The ad and key are both allowed
      to be empty. Currently non-empty AD/key is only supported with Argon2.

   .. cpp:function:: std::string to_string() const

      Return a descriptive string including the parameters (iteration count, etc)

   .. cpp:function:: size_t iterations() const

      Return the iteration parameter

   .. cpp:function:: size_t memory_param() const

      Return the memory usage parameter, or 0 if the algorithm does not offer
      a memory usage option.

   .. cpp:function:: size_t parallelism() const

      Returns the parallelism parameter, or 0 if the algorithm does not offer a
      parallelism option.

   .. cpp:function:: size_t total_memory_usage() const

      Return a guesstimate of the total number of bytes of memory consumed when
      running this algorithm. If the function is not intended to be memory-hard
      and uses an effictively fixed amount of memory when running, this function
      returns 0.

The ``PasswordHashFamily`` creates specific instances of ``PasswordHash``:

.. cpp:class:: PasswordHashFamily

   .. cpp:function:: static std::unique_ptr<PasswordHashFamily> create(const std::string& what)

      For example "PBKDF2(SHA-256)", "Scrypt", "Argon2id". Returns null if the
      algorithm is not available.

   .. cpp:function:: std::unique_ptr<PasswordHash> default_params() const

      Create a default instance of the password hashing algorithm. Be warned the
      value returned here may change from release to release.

   .. cpp:function:: std::unique_ptr<PasswordHash> tune(size_t output_len, std::chrono::milliseconds msec) const

      Return a password hash instance tuned to run for approximately ``msec``
      milliseconds when producing an output of length ``output_len``. (Accuracy
      may vary, use the command line utility ``botan pbkdf_tune`` to check.)

   .. cpp:function:: std::unique_ptr<PasswordHash> from_params( \
         size_t i1, size_t i2 = 0, size_t i3 = 0) const

      Create a password hash using some scheme specific format. Parameters are as follows:

      * For PBKDF2, PGP-S2K, and Bcrypt-PBKDF, ``i1`` is iterations
      * Scrypt uses ``i1`` == ``N``, ``i2`` == ``r``, and ``i3`` == ``p``
      * Argon2 family uses ``i1`` == ``M``, ``i2`` == ``t``, and ``i3`` == ``p``

      All unneeded parameters should be set to 0 or left blank.

Available Schemes
----------------------

General Recommendations
^^^^^^^^^^^^^^^^^^^^^^^^^

If you need wide interoperability use PBKDF2 with HMAC-SHA256 and at least 50K
iterations. If you don't, use Argon2id with p=1, t=3 and M as large as you
can reasonable set (say 1 gigabyte).

You can test how long a particular PBKDF takes to execute using the cli tool
``pbkdf_tune``::

  $ ./botan pbkdf_tune --algo=Argon2id 500 --max-mem=192 --check
  For 500 ms selected Argon2id(196608,3,1) using 192 MiB took 413.159 msec to compute

This returns the parameters chosen by the fast auto-tuning algorithm, and
because ``--check`` was supplied the hash is also executed with the full set of
parameters and timed.

PBKDF2
^^^^^^^^^^^^

PBKDF2 is the "standard" password derivation scheme, widely implemented in many
different libraries. It uses HMAC internally and requires choosing a hash
function to use. (If in doubt use SHA-256 or SHA-512). It also requires choosing
an iteration count, which makes brute force attacks more expensive. Use *at
least* 50000 and preferably much more. Using 250,000 would not be unreasonable.

Scrypt
^^^^^^^^^^

.. versionadded:: 2.7.0

Scrypt is a relatively newer design which is "memory hard" - in
addition to requiring large amounts of CPU power it uses a large block
of memory to compute the hash. This makes brute force attacks using
ASICs substantially more expensive.

Scrypt has three parameters, usually termed ``N``, ``r``, and ``p``.  ``N`` is
the primary control of the workfactor, and must be a power of 2. For interactive
logins use 32768, for protection of secret keys or backups use 1048576.

The ``r`` parameter controls how 'wide' the internal hashing operation is. It
also increases the amount of memory that is used. Values from 1 to 8 are
reasonable.

Setting ``p`` parameter to greater than 1 splits up the work in a way that up
to p processors can work in parallel.

As a general recommendation, use ``N`` = 32768, ``r`` = 8, ``p`` = 1

Argon2
^^^^^^^^^^

.. versionadded:: 2.11.0

Argon2 is the winner of the PHC (Password Hashing Competition) and
provides a tunable memory hard PBKDF. There are three minor variants
of Argon2 - Argon2d, Argon2i, and Argon2id. All three are implemented.

Bcrypt
^^^^^^^^^^^^

.. versionadded:: 2.11.0

Bcrypt-PBKDF is a variant of the well known ``bcrypt`` password hashing
function.  Like ``bcrypt`` it is based around using Blowfish for the key
expansion, which requires 4 KiB of fast random access memory, making hardware
based attacks more expensive. Unlike Argon2 or Scrypt, the memory usage is not
tunable.

This function is relatively obscure but is used for example in OpenSSH.
Prefer Argon2 or Scrypt in new systems.

OpenPGP S2K
^^^^^^^^^^^^

.. warning::

   The OpenPGP algorithm is weak and strange, and should be avoided unless
   implementing OpenPGP.

There are some oddities about OpenPGP's S2K algorithms that are documented
here. For one thing, it uses the iteration count in a strange manner; instead of
specifying how many times to iterate the hash, it tells how many *bytes* should
be hashed in total (including the salt). So the exact iteration count will
depend on the size of the salt (which is fixed at 8 bytes by the OpenPGP
standard, though the implementation will allow any salt size) and the size of
the passphrase.

To get what OpenPGP calls "Simple S2K", set iterations to 0, and do not specify
a salt. To get "Salted S2K", again leave the iteration count at 0, but give an
8-byte salt. "Salted and Iterated S2K" requires an 8-byte salt and some
iteration count (this should be significantly larger than the size of the
longest passphrase that might reasonably be used; somewhere from 1024 to 65536
would probably be about right). Using both a reasonably sized salt and a large
iteration count is highly recommended to prevent password guessing attempts.

PBKDF
---------

:cpp:class:`PBKDF` is the older API for this functionality, presented in header
``pbkdf.h``. It only supports PBKDF2 and the PGP S2K algorithm, not
Scrypt, Argon2, or bcrypt. This interface is deprecated and will be removed
in a future major release.

In addition, this API requires the passphrase be entered as a
``std::string``, which means the secret will be stored in memory that
will not be zeroed.

.. cpp:class:: PBKDF

   .. cpp:function:: static std::unique_ptr<PBKDF> create(const std::string& algo_spec, \
                                                          const std::string& provider = "")

      Return a newly created PBKDF object. The name should be in the
      format "PBKDF2(HASHNAME)", "PBKDF2(HMAC(HASHNAME))", or
      "OpenPGP-S2K".  Returns null if the algorithm is not available.

   .. cpp:function:: void pbkdf_iterations(uint8_t out[], size_t out_len, \
                            const std::string& passphrase, \
                            const uint8_t salt[], size_t salt_len, \
                            size_t iterations) const

      Run the PBKDF algorithm for the specified number of iterations,
      with the given salt, and write output to the buffer.

   .. cpp:function:: void pbkdf_timed(uint8_t out[], size_t out_len, \
                         const std::string& passphrase, \
                         const uint8_t salt[], size_t salt_len, \
                         std::chrono::milliseconds msec, \
                         size_t& iterations) const

      Choose (via short run-time benchmark) how many iterations to perform
      in order to run for roughly msec milliseconds. Writes the number
      of iterations used to reference argument.

   .. cpp:function:: OctetString derive_key( \
               size_t output_len, const std::string& passphrase, \
               const uint8_t* salt, size_t salt_len, \
               size_t iterations) const

   Computes a key from *passphrase* and the *salt* (of length
   *salt_len* bytes) using an algorithm-specific interpretation of
   *iterations*, producing a key of length *output_len*.

   Use an iteration count of at least 10000. The salt should be
   randomly chosen by a good random number generator (see
   :ref:`random_number_generators` for how), or at the very least
   unique to this usage of the passphrase.

   If you call this function again with the same parameters, you will
   get the same key.


text:
require 'spec_helper'

RSpec.describe RoomPolicy, type: :policy do

  let(:user) { create(:user) }
  let(:room) { create(:room, public: public) }
  let(:public) { false }

  subject { RoomPolicy.new user, room }

  context 'for a guest user' do
    let(:user) { create(:user, guest: true) }

    it { is_expected.not_to permit_auth :create_public }
  end

  context 'for a registered user' do
    let(:user) { create(:user, guest: false) }

    it { is_expected.to permit_auth :create_public }
  end

  context 'for any user' do

    it { is_expected.to permit_auth :index }
    it { is_expected.to permit_auth :new }
    it { is_expected.to permit_auth :create }
  end

  context 'for the owner' do

    before { user.add_role :owner, room }

    context 'of a private room' do
      let(:public) { false }

      it { is_expected.to permit_auth :show }
      it { is_expected.to permit_auth :edit }
      it { is_expected.to permit_auth :update }
      it { is_expected.to permit_auth :destroy }
    end

    context 'of a public room' do
      let(:public) { true }

      it { is_expected.to permit_auth :show }
      it { is_expected.to permit_auth :edit }
      it { is_expected.to permit_auth :update }
      it { is_expected.to permit_auth :destroy }
    end
  end

  context 'for a user with access' do

    before { user.add_role :access, room }

    context 'to a private room' do
      let(:public) { false }

      it { is_expected.to permit_auth :show }
      it { is_expected.not_to permit_auth :edit }
      it { is_expected.not_to permit_auth :update }
      it { is_expected.not_to permit_auth :destroy }
    end

    context 'to a public room' do
      let(:public) { true }

      it { is_expected.to permit_auth :show }
      it { is_expected.not_to permit_auth :edit }
      it { is_expected.not_to permit_auth :update }
      it { is_expected.not_to permit_auth :destroy }
    end
  end

  context 'for an unauthorized user' do

    context 'to a private room' do
      let(:public) { false }

      it { is_expected.not_to permit_auth :show }
      it { is_expected.not_to permit_auth :edit }
      it { is_expected.not_to permit_auth :update }
      it { is_expected.not_to permit_auth :destroy }
    end

    context 'to a public room' do
      let(:public) { true }

      it { is_expected.to permit_auth :show }
      it { is_expected.not_to permit_auth :edit }
      it { is_expected.not_to permit_auth :update }
      it { is_expected.not_to permit_auth :destroy }
    end
  end

end


text:
import logging
import warnings
from io import BytesIO
from urllib.parse import parse_qsl, urlparse

from .util import CaseInsensitiveDict

log = logging.getLogger(__name__)

class Request:
    """
    VCR's representation of a request.
    """

    def __init__(self, method, uri, body, headers):
        self.method = method
        self.uri = uri
        self._was_file = hasattr(body, "read")
        if self._was_file:
            self.body = body.read()
        else:
            self.body = body
        self.headers = headers
        log.debug("Invoking Request %s", self.uri)

    @property
    def headers(self):
        return self._headers

    @headers.setter
    def headers(self, value):
        if not isinstance(value, HeadersDict):
            value = HeadersDict(value)
        self._headers = value

    @property
    def body(self):
        return BytesIO(self._body) if self._was_file else self._body

    @body.setter
    def body(self, value):
        if isinstance(value, str):
            value = value.encode("utf-8")
        self._body = value

    def add_header(self, key, value):
        warnings.warn(
            "Request.add_header is deprecated. " "Please assign to request.headers instead.",
            DeprecationWarning,
        )
        self.headers[key] = value

    @property
    def scheme(self):
        return urlparse(self.uri).scheme

    @property
    def host(self):
        return urlparse(self.uri).hostname

    @property
    def port(self):
        parse_uri = urlparse(self.uri)
        port = parse_uri.port
        if port is None:
            try:
                port = {"https": 443, "http": 80}[parse_uri.scheme]
            except KeyError:
                pass
        return port

    @property
    def path(self):
        return urlparse(self.uri).path

    @property
    def query(self):
        q = urlparse(self.uri).query
        return sorted(parse_qsl(q))

    # alias for backwards compatibility
    @property
    def url(self):
        return self.uri

    # alias for backwards compatibility
    @property
    def protocol(self):
        return self.scheme

    def __str__(self):
        return "<Request ({}) {}>".format(self.method, self.uri)

    def __repr__(self):
        return self.__str__()

    def _to_dict(self):
        return {
            "method": self.method,
            "uri": self.uri,
            "body": self.body,
            "headers": {k: [v] for k, v in self.headers.items()},
        }

    @classmethod
    def _from_dict(cls, dct):
        return Request(**dct)

class HeadersDict(CaseInsensitiveDict):
    """
    There is a weird quirk in HTTP.  You can send the same header twice.  For
    this reason, headers are represented by a dict, with lists as the values.
    However, it appears that HTTPlib is completely incapable of sending the
    same header twice.  This puts me in a weird position: I want to be able to
    accurately represent HTTP headers in cassettes, but I don't want the extra
    step of always having to do [0] in the general case, i.e.
    request.headers['key'][0]

    In addition, some servers sometimes send the same header more than once,
    and httplib *can* deal with this situation.

    Furthermore, I wanted to keep the request and response cassette format as
    similar as possible.

    For this reason, in cassettes I keep a dict with lists as keys, but once
    deserialized into VCR, I keep them as plain, naked dicts.
    """

    def __setitem__(self, key, value):
        if isinstance(value, (tuple, list)):
            value = value[0]

        # Preserve the case from the first time this key was set.
        old = self._store.get(key.lower())
        if old:
            key = old[0]

        super().__setitem__(key, value)


text:
/* Functions to help coverity do static analysis on cmocka */
void exit_test(const int quit_application)
{
      __coverity_panic__();
}


text:
{% if site.twitter %}
<meta name="twitter:card" content="summary">
<meta name="twitter:site" content="@{{site.twitter_username}}">
<meta name="twitter:creator" content="@{{site.twitter_username}}">
{% if page.title %}<meta name="twitter:title" content="{{ page.title }}">
{% else %}<meta name="twitter:title" content="{{ site.title }}">
{% endif %}{% if page.url %}<meta name="twitter:url" content="{{ site.url }}{{ page.url }}">
{% endif %}{% if page.description %}<meta name="twitter:description" content="{{ page.summary }}">
{% else %}<meta name="twitter:description" content="{{ site.description }}">
{% endif %}{% if page.thumbnail %}<meta name="twitter:image:src" content="{{ site.url }}/images/{{ page.thumbnail }}">
{% else %}<meta name="twitter:image:src" content="{{ site.url }}/images/logo.png">{% endif %}
{% endif %}


text:
#include "clustertest.h"

#include <cluster_framework/bucket.h>
#include <cluster_framework/cluster.h>
#include <protocol/connection/client_connection.h>
#include <protocol/connection/client_mcbp_commands.h>
#include <protocol/connection/frameinfo.h>
#include <condition_variable>
#include <string>

/**
 * Get a frame info vector with a durability entry with Majority
 */
static FrameInfoVector GetMajorityDurabilityFrameInfoVector() {
    FrameInfoVector ret;
    ret.emplace_back(std::make_unique<DurabilityFrameInfo>(
            cb::durability::Level::Majority));
    return ret;
}

class DurabilityTest : public cb::test::ClusterTest {
protected:
    static void mutate(MemcachedConnection& conn,
                       std::string id,
                       MutationType type) {
        MutationInfo old{};
        if (type != MutationType::Add) {
            old = conn.store(id, Vbid{0}, "", cb::mcbp::Datatype::Raw);
        }

        Document doc{};
        doc.value = "body";
        doc.info.id = std::move(id);
        doc.info.datatype = cb::mcbp::Datatype::Raw;
        const auto info = conn.mutate(
                doc, Vbid{0}, type, GetMajorityDurabilityFrameInfoVector);
        EXPECT_NE(0, info.cas);
        EXPECT_NE(old.cas, info.cas);
    }

    static void subdoc(MemcachedConnection& conn,
                       std::string id,
                       cb::mcbp::ClientOpcode opcode) {
        BinprotSubdocCommand cmd(opcode);
        cmd.setKey(std::move(id));
        cmd.setPath("foo");
        if (opcode != cb::mcbp::ClientOpcode::SubdocDelete) {
            cmd.setValue("1");
            if (opcode == cb::mcbp::ClientOpcode::SubdocArrayInsert) {
                cmd.setPath("foo.[0]");
            } else if (opcode != cb::mcbp::ClientOpcode::SubdocReplace) {
                cmd.addPathFlags(SUBDOC_FLAG_MKDIR_P);
                cmd.addDocFlags(mcbp::subdoc::doc_flag::Mkdoc);
            }
        }
        cmd.addFrameInfo(DurabilityFrameInfo{cb::durability::Level::Majority});
        auto rsp = conn.execute(cmd);
        EXPECT_TRUE(rsp.isSuccess())
                << "Status: " << to_string(rsp.getStatus()) << std::endl
                << "Value: " << rsp.getDataString();
        EXPECT_NE(0, rsp.getCas());
    }

    static std::unique_ptr<MemcachedConnection> getConnection() {
        auto bucket = cluster->getBucket("default");
        auto conn = bucket->getConnection(Vbid(0));
        conn->authenticate("@admin", "password", "PLAIN");
        conn->selectBucket(bucket->getName());
        return conn;
    }
};

TEST_F(DurabilityTest, Set) {
    mutate(*getConnection(), "Set", MutationType::Set);
}

TEST_F(DurabilityTest, Add) {
    mutate(*getConnection(), "Add", MutationType::Add);
}

TEST_F(DurabilityTest, Replace) {
    mutate(*getConnection(), "Replace", MutationType::Replace);
}

TEST_F(DurabilityTest, Append) {
    mutate(*getConnection(), "Append", MutationType::Append);
}

TEST_F(DurabilityTest, Prepend) {
    mutate(*getConnection(), "Prepend", MutationType::Prepend);
}

TEST_F(DurabilityTest, Delete) {
    auto conn = getConnection();
    const auto old =
            conn->store("Delete", Vbid{0}, "", cb::mcbp::Datatype::Raw);
    auto info = getConnection()->remove(
            "Delete", Vbid{0}, 0, GetMajorityDurabilityFrameInfoVector);
    EXPECT_NE(0, info.cas);
    EXPECT_NE(old.cas, info.cas);
}

TEST_F(DurabilityTest, Increment) {
    auto conn = getConnection();
    for (uint64_t ii = 0; ii < 10ULL; ++ii)
        EXPECT_EQ(ii,
                  conn->increment("Increment",
                                  1,
                                  0,
                                  0,
                                  nullptr,
                                  GetMajorityDurabilityFrameInfoVector));
}

TEST_F(DurabilityTest, Decrement) {
    auto conn = getConnection();
    for (uint64_t ii = 10; ii > 0ULL; --ii)
        EXPECT_EQ(ii,
                  conn->decrement("Decrement",
                                  1,
                                  10,
                                  0,
                                  nullptr,
                                  GetMajorityDurabilityFrameInfoVector));
}

TEST_F(DurabilityTest, SubdocDictAdd) {
    subdoc(*getConnection(),
           "SubdocDictAdd",
           cb::mcbp::ClientOpcode::SubdocDictAdd);
}

TEST_F(DurabilityTest, SubdocDictUpsert) {
    subdoc(*getConnection(),
           "SubdocDictUpsert",
           cb::mcbp::ClientOpcode::SubdocDictUpsert);
}

TEST_F(DurabilityTest, SubdocDelete) {
    auto conn = getConnection();
    conn->store("SubdocDelete",
                Vbid{0},
                R"({"foo":"bar"})",
                cb::mcbp::Datatype::JSON);
    subdoc(*conn, "SubdocDelete", cb::mcbp::ClientOpcode::SubdocDelete);
}

TEST_F(DurabilityTest, SubdocReplace) {
    auto conn = getConnection();
    conn->store("SubdocReplace",
                Vbid{0},
                R"({"foo":"bar"})",
                cb::mcbp::Datatype::JSON);
    subdoc(*conn, "SubdocReplace", cb::mcbp::ClientOpcode::SubdocReplace);
}

TEST_F(DurabilityTest, SubdocArrayPushLast) {
    subdoc(*getConnection(),
           "SubdocArrayPushLast",
           cb::mcbp::ClientOpcode::SubdocArrayPushLast);
}
TEST_F(DurabilityTest, SubdocArrayPushFirst) {
    subdoc(*getConnection(),
           "SubdocArrayPushFirst",
           cb::mcbp::ClientOpcode::SubdocArrayPushFirst);
}
TEST_F(DurabilityTest, SubdocArrayInsert) {
    auto conn = getConnection();
    conn->store("SubdocArrayInsert",
                Vbid{0},
                R"({"foo":[]})",
                cb::mcbp::Datatype::JSON);
    subdoc(*conn,
           "SubdocArrayInsert",
           cb::mcbp::ClientOpcode::SubdocArrayInsert);
}
TEST_F(DurabilityTest, SubdocArrayAddUnique) {
    subdoc(*getConnection(),
           "SubdocArrayAddUnique",
           cb::mcbp::ClientOpcode::SubdocArrayAddUnique);
}

TEST_F(DurabilityTest, SubdocCounter) {
    subdoc(*getConnection(),
           "SubdocCounter",
           cb::mcbp::ClientOpcode::SubdocCounter);
}

TEST_F(DurabilityTest, SubdocMultiMutation) {
    BinprotSubdocMultiMutationCommand cmd;
    cmd.setKey("SubdocMultiMutation");
    cmd.addMutation(cb::mcbp::ClientOpcode::SubdocDictAdd,
                    SUBDOC_FLAG_MKDIR_P,
                    "foo",
                    R"("value")");
    cmd.addDocFlag(mcbp::subdoc::doc_flag::Mkdoc);
    cmd.addFrameInfo(DurabilityFrameInfo{cb::durability::Level::Majority});
    auto rsp = getConnection()->execute(cmd);
    EXPECT_TRUE(rsp.isSuccess())
            << "Status: " << to_string(rsp.getStatus()) << std::endl
            << "Value: " << rsp.getDataString();
    EXPECT_NE(0, rsp.getCas());
}

/**
 * MB-34780 - Bucket delete fails if we've got pending sync writes
 *
 * As part of bucket deletion all of the DCP streams get torn down so
 * a sync write will _never_ complete. This caused bucket deletion to
 * block as the cookie was in an ewouldblock state
 */
TEST_F(DurabilityTest, MB34780) {
    cluster->deleteBucket("default");
    std::mutex mutex;
    std::condition_variable cond;
    bool prepare_seen = false;

    auto bucket = cluster->createBucket(
            "default",
            {{"replicas", 2}, {"max_vbuckets", 8}},
            [&mutex, &cond, &prepare_seen](const std::string& source,
                                           const std::string& destination,
                                           std::vector<uint8_t>& packet) {
                if (prepare_seen) {
                    // Swallow everything..
                    packet.clear();
                    return;
                }

                const auto* h = reinterpret_cast<const cb::mcbp::Header*>(
                        packet.data());
                if (h->isRequest()) {
                    const auto& req = h->getRequest();
                    if (req.getClientOpcode() ==
                        cb::mcbp::ClientOpcode::DcpPrepare) {
                        std::lock_guard<std::mutex> guard(mutex);
                        prepare_seen = true;
                        cond.notify_all();
                        packet.clear();
                    }
                }
            });
    ASSERT_TRUE(bucket) << "Failed to create bucket default";

    auto conn = bucket->getConnection(Vbid(0));
    conn->authenticate("@admin", "password", "PLAIN");
    conn->selectBucket(bucket->getName());

    BinprotMutationCommand command;
    command.setKey("MB34780");
    command.setMutationType(MutationType::Set);
    DurabilityFrameInfo frameInfo(cb::durability::Level::Majority);
    command.addFrameInfo(frameInfo);
    conn->sendCommand(command);

    std::unique_lock<std::mutex> lock(mutex);
    cond.wait(lock, [&prepare_seen]() { return prepare_seen; });

    // At this point we've sent the prepare, it is registered in the
    // durability manager.. We should be able to delete the bucket
    cluster->deleteBucket("default");
}


text:
#ifndef _http_hpp__
#define _http_hpp__

// Copyright(c) Andre Caron <andre.l.caron@gmail.com>, 2011
//
// This document is covered by the an Open Source Initiative approved license. A
// copy of the license should have been provided alongside this software package
// (see "LICENSE.txt"). If not, terms of the license are available online at
// "http://www.opensource.org/licenses/mit".

#include "BufferedMessage.hpp"
#include "UserBufferedMessage.hpp"
#include "Error.hpp"
#include "Flags.hpp"
#include "icompare.hpp"
#include "Message.hpp"
#include "MessageBuilder.hpp"
#include "Method.hpp"
#include "Request.hpp"
#include "RequestBuilder.hpp"
#include "Response.hpp"
#include "ResponseBuilder.hpp"
#include "Url.hpp"

#endif /* _http_hpp__ */


text: require 'slack-ruby-client'


text:
from django import template

from administration.models import Flag

register = template.Library()

@register.filter
def can_view_flagged_item(user, flag):
    """A filter for deciding if a user can view a flagged item."""
    if user in flag.participants.all():
        return True
    if user.has_perm('administration.can_view_social_flags') and \
            flag.flag_type == Flag.SOCIAL:
        return True
    if user.has_perm('administration.can_view_content_flags') and \
            flag.flag_type == Flag.CONTENT:
        return True
    return False


text:
using System;
using System.Collections.Specialized;
using System.Web.DynamicData;
using System.Web.UI;

namespace NuGetGallery.Areas.Admin.DynamicData
{
    public partial class Decimal_EditField : FieldTemplateUserControl
    {
        public override Control DataControl
        {
            get { return TextBox1; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.ToolTip = Column.Description;

            SetUpValidator(RequiredFieldValidator1);
            SetUpValidator(CompareValidator1);
            SetUpValidator(RegularExpressionValidator1);
            SetUpValidator(RangeValidator1);
            SetUpValidator(DynamicValidator1);
        }

        protected override void ExtractValues(IOrderedDictionary dictionary)
        {
            dictionary[Column.Name] = ConvertEditedValue(TextBox1.Text);
        }
    }
}


text:
package org.apache.spark.sql.connector.read;

import org.apache.spark.sql.catalyst.InternalRow;

/**
 * A mix-in for input partitions whose records are clustered on the same set of partition keys
 * (provided via {@link SupportsReportPartitioning}, see below). Data sources can opt-in to
 * implement this interface for the partitions they report to Spark, which will use the
 * information to avoid data shuffling in certain scenarios, such as join, aggregate, etc. Note
 * that Spark requires ALL input partitions to implement this interface, otherwise it can't take
 * advantage of it.
 *

 * This interface should be used in combination with {@link SupportsReportPartitioning}, which
 * allows data sources to report distribution and ordering spec to Spark. In particular, Spark
 * expects data sources to report
 * {@link org.apache.spark.sql.connector.distributions.ClusteredDistribution} whenever its input
 * partitions implement this interface. Spark derives partition keys spec (e.g., column names,
 * transforms) from the distribution, and partition values from the input partitions.
 *

 * It is implementor's responsibility to ensure that when an input partition implements this
 * interface, its records all have the same value for the partition keys. Spark doesn't check
 * this property.
 *
 * @see org.apache.spark.sql.connector.read.SupportsReportPartitioning
 * @see org.apache.spark.sql.connector.read.partitioning.Partitioning
 * @since 3.3.0
 */
public interface HasPartitionKey extends InputPartition {
  /**
   * Returns the value of the partition key(s) associated to this partition. An input partition
   * implementing this interface needs to ensure that all its records have the same value for the
   * partition keys. Note that the value is after partition transform has been applied, if there
   * is any.
   */
  InternalRow partitionKey();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:background="@color/white"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/tv_maybe_know"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="14dp"
        android:text="可能认识的人"
        android:textColor="@color/Text_date"
        android:textSize="14sp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="14dp"
        android:text=">"
        android:textColor="@color/Text_date"
        android:textSize="14sp" />

</RelativeLayout>


text:
inline void Log(std::string str)
{
	std::cout << "[" << __LINE__ << "] " << __FUNCTION__ << " : " << str << std::endl;
}

inline void LogFnStart()
{
	Log("Entered");
}

inline void LogFnEnd()
{
	Log("Finished");
}

inline void NestedLog(std::string str)
{
	std::cout << "\n\t" << str << "\n" << std::endl;
}

namespace CppChart
{
	std::ostream& operator<<(std::ostream&, const sf::Vector2f&);
	std::ostream& operator<<(std::ostream&, const sf::Vector2u&);
	std::ostream& operator<<(std::ostream&, const sf::Color&);

	template <typename T>
	std::string ToString(const T&);
}

#endif


text:
namespace Http.Query.Filter.Test.Filters
{
    using System.Collections;
    using System.Collections.Generic;

    using FluentAssertions;

    using Http.Query.Filter.Filters.Condition;
    using Http.Query.Filter.Filters.Condition.Operators;

    using Xunit;

    using static System.String;
    using static Http.Query.Filter.Filters.Condition.Operators.Logical;

    public class WhereTests
    {
        [Theory]
        [ClassData(typeof(TestData))]
        public void Parse_GivenQuery_ShouldReturn(string query, Where expected)
        {
            Where actual = query;

            actual.Should().BeEquivalentTo(expected);
        }

        [Theory]
        [InlineData("?filter[condition][id]=1")]
        [InlineData("?filter[where][last name]=Test")]
        [InlineData("?filter[where][id][eq]=1")]
        [InlineData("?filter[where][id][equal]=1")]
        [InlineData("?filter[condition][id][gt]=1")]
        [InlineData("?filter[where][id][greaterthan]=1")]
        [InlineData("?filter[condition][id][lt]=1")]
        [InlineData("?filter[where][id][lessthan]=1")]
        public void Parse_GivenQuery_ShouldReturnEmpty(string query)
        {
            Where actual = query;

            actual.Should().BeEmpty();
        }

        public class TestData : IEnumerable<object[]>
        {
            public IEnumerator<object[]> GetEnumerator()
            {
                // Equal to
                yield return new object[] { "?filter[where][id]=", Expected(new Condition("id", Empty)) };
                yield return new object[] { "?filter[where][id]=2", Expected(new Condition("id", "2")) };
                yield return new object[] { "?FILTER[WHERE][NAME]=NAME", Expected(new Condition("NAME", "NAME")) };
                yield return new object[] { "?Filter[Where][Surname]=Surname", Expected(new Condition("Surname", "Surname")) };
                yield return new object[] { "?filter%5Bwhere%5D%5Bid%5D=2", Expected(new Condition("id", "2")) };

                // Greater than
                yield return new object[] { "?filter[where][id][gt]=", Expected(new Condition("id", Empty, Comparison.GreaterThan)) };
                yield return new object[] { "?filter[where][id][gt]=2", Expected(new Condition("id", "2", Comparison.GreaterThan)) };
                yield return new object[] { "?FILTER[WHERE][ID][GT]=2", Expected(new Condition("ID", "2", Comparison.GreaterThan)) };
                yield return new object[] { "?Filter[Where][Id][Gt]=2", Expected(new Condition("Id", "2", Comparison.GreaterThan)) };
                yield return new object[] { "?filter%5Bwhere%5D%5Bid%5D%5Bgt%5D=2", Expected(new Condition("id", "2", Comparison.GreaterThan)) };

                // Less than
                yield return new object[] { "?filter[where][id][lt]=", Expected(new Condition("id", Empty, Comparison.LessThan)) };
                yield return new object[] { "?filter[where][id][lt]=2", Expected(new Condition("id", "2", Comparison.LessThan)) };
                yield return new object[] { "?FILTER[WHERE][ID][LT]=2", Expected(new Condition("ID", "2", Comparison.LessThan)) };
                yield return new object[] { "?Filter[Where][Id][Lt]=2", Expected(new Condition("Id", "2", Comparison.LessThan)) };
                yield return new object[] { "?filter%5Bwhere%5D%5Bid%5D%5Blt%5D=2", Expected(new Condition("id", "2", Comparison.LessThan)) };

                yield return new object[] { "?filter[where][id][inq]=&filter[where][id][inq]=Empty", Expected(new Condition("id", Empty, Comparison.Inq), new Condition("id", "Empty", Comparison.Inq)) };
                yield return new object[] { "?filter[where][id][inq]=2&filter[where][id][inq]=3", Expected(new Condition("id", "2", Comparison.Inq), new Condition("id", "3", Comparison.Inq)) };
                yield return new object[] { "?FILTER[WHERE][ID][INQ]=2&FILTER[WHERE][ID][INQ]=3", Expected(new Condition("ID", "2", Comparison.Inq), new Condition("ID", "3", Comparison.Inq)) };
                yield return new object[] { "?Filter[Where][Id][Inq]=2&Filter[Where][Id][Inq]=3", Expected(new Condition("Id", "2", Comparison.Inq), new Condition("Id", "3", Comparison.Inq)) };
                yield return new object[] { "?filter%5Bwhere%5D%5Bid%5D%5Binq%5D=2&filter%5Bwhere%5D%5Bid%5D%5Binq%5D=3", Expected(new Condition("id", "2", Comparison.Inq), new Condition("id", "3", Comparison.Inq)) };

                // And
                yield return new object[] { "?filter[where][and][0][id]=&filter[where][and][1][name]=", Expected(new Condition("id", Empty, And, 0), new Condition("name", Empty, And, 1)) };
                yield return new object[] { "?filter[where][and][0][id]=2&filter[where][and][1][name]=junior", Expected(new Condition("id", "2", And, 0), new Condition("name", "junior", And, 1)) };
                yield return new object[] { "?FILTER[WHERE][AND][0][ID]=2&FILTER[WHERE][AND][1][NAME]=junior", Expected(new Condition("ID", "2", And, 0), new Condition("NAME", "junior", And, 1)) };
                yield return new object[] { "?Filter[Where][And][0][Id]=2&Filter[Where][And][1][Name]=junior", Expected(new Condition("Id", "2", And, 0), new Condition("Name", "junior", And, 1)) };
                yield return new object[] { "?filter%5Bwhere%5D%5Band%5D%5B0%5D%5Bid%5D=2&filter%5Bwhere%5D%5Band%5D%5B1%5D%5Bname%5D=junior", Expected(new Condition("id", "2", And, 0), new Condition("name", "junior", And, 1)) };

                // Or
                yield return new object[] { "?filter[where][or][0][id]=&filter[where][or][1][name]=", Expected(new Condition("id", Empty, Or, 0), new Condition("name", Empty, Or, 1)) };
                yield return new object[] { "?filter[where][or][0][id]=2&filter[where][or][1][name]=junior", Expected(new Condition("id", "2", Or, 0), new Condition("name", "junior", Or, 1)) };
                yield return new object[] { "?FILTER[WHERE][OR][0][ID]=2&FILTER[WHERE][OR][1][NAME]=junior", Expected(new Condition("ID", "2", Or, 0), new Condition("NAME", "junior", Or, 1)) };
                yield return new object[] { "?Filter[Where][Or][0][Id]=2&Filter[Where][Or][1][Name]=junior", Expected(new Condition("Id", "2", Or, 0), new Condition("Name", "junior", Or, 1)) };
                yield return new object[] { "?filter%5Bwhere%5D%5Bor%5D%5B0%5D%5Bid%5D=2&filter%5Bwhere%5D%5Bor%5D%5B1%5D%5Bname%5D=junior", Expected(new Condition("id", "2", Or, 0), new Condition("name", "junior", Or, 1)) };
            }

            IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();

            private static Where Expected(params Condition[] conditions) => new Where(conditions);
        }
    }
}


text:
import org.jspecify.nullness.NullMarked;
import org.jspecify.nullness.Nullable;
import org.jspecify.nullness.NullnessUnspecified;

@NullMarked
class ContainmentSuper {
  void x() {
    new Check<Lib<? super Foo>, Lib<? super Foo>>();

    new Check<Lib<? super Foo>, Lib<? super @NullnessUnspecified Foo>>();

    new Check<Lib<? super Foo>, Lib<? super @Nullable Foo>>();

    // jspecify_nullness_not_enough_information
    new Check<Lib<? super @NullnessUnspecified Foo>, Lib<? super Foo>>();

    // jspecify_nullness_not_enough_information
    new Check<Lib<? super @NullnessUnspecified Foo>, Lib<? super @NullnessUnspecified Foo>>();

    new Check<Lib<? super @NullnessUnspecified Foo>, Lib<? super @Nullable Foo>>();

    // jspecify_nullness_mismatch
    new Check<Lib<? super @Nullable Foo>, Lib<? super Foo>>();

    // jspecify_nullness_not_enough_information
    new Check<Lib<? super @Nullable Foo>, Lib<? super @NullnessUnspecified Foo>>();

    new Check<Lib<? super @Nullable Foo>, Lib<? super @Nullable Foo>>();
  }

  interface Lib<T extends @Nullable Object> {}

  interface Foo {}

  static class Check<F extends @Nullable Object, A extends F> {}
}


text:
<?php

/*
 * Arquivo do projeto Pisotaria para disciplina SIT150 (Cliente/Servidor) da UNIFEI
 * Autores:
 * 	Adan Reno
 * 	Fernando Marcato
 * 	Hendrix Silva
 * 	Thiago Sales
 */

?>

    <li role="presentation"<?php
        if(site_url("argamassa") == current_url()){
            echo ' class="active"';
        }?>><a href="<?php echo base_url("argamassa") ?>">Argamassa

    <li role="presentation"<?php
        if(site_url("argamassa/ver") == current_url()){
            echo ' class="active"';
        }?>><a href="<?php echo base_url("argamassa/ver") ?>">Listar Argamassas

    <li role="presentation"<?php
        if(site_url("argamassa/inserir") == current_url()){
            echo ' class="active"';
        }?>><a href="<?php echo base_url("argamassa/inserir") ?>">Inserir Argamassa


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace NServiceMVC.WebStack
{
    /// <summary>
    /// Controller that services NServiceMVC static content at ~/__NServiceMvcContent/
    /// </summary>
    public class NServiceMvcContentController : Controller
    {

        public ActionResult File(string filename)
        {
            var data = WebStack.TemplateEngine.LoadEmbeddedResource("NServiceMVC.Content." + filename);
            if (data == null)
                return new HttpNotFoundResult();

            return new ContentResult() {
                Content = data,
                ContentType = InferContentType(filename)
            };
        }

        /// <summary>
        /// Very naieve method to get a mime content-type
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private string InferContentType(string filename)
        {
            switch (System.IO.Path.GetExtension(filename).ToLower())
            {
                case ".css": return "text/css";
                case ".js": return "text/javascript";
                case ".gif": return "image/gif";
                case ".jpg": case ".jpeg": return "image/jpeg";
                case ".png": return "image/png";
                case ".txt": return "text/plain";
                default: return "text/html";
            }
        }
    }
}