text:
/*jslint es5: true nomen: true forin: true vars: true*/
(function (angular) {
    "use strict";

    var app = angular.module('fratpos');

    app.controller('PosController', function ($scope, api, $timeout, $modal) {

        var getData = function () {
            api.posdata().then(function (response) {
                $scope.users = response.data.users;
                $scope.transactions = response.data.transactions;
                $scope.products = response.data.products;
                $scope.paytypes = response.data.paytypes;
            });
        };

        getData();

        //Update data when browser comes back online.
        $scope.$on('online', getData);

        $scope.isUserSelected = function () {
            console.dir($scope.user);
            return angular.isObject($scope.user);
        };

        $scope.clear = function () {
            $scope.user = null;
            $timeout(function () {
                angular.element('#usernotselected').focus();
            });
        };

        $scope.selectedProducts = {};

        $scope.showAllProducts = false;

        $scope.toggleShowAllProducts = function () {
            $scope.showAllProducts = !$scope.showAllProducts;
        };

        $scope.filteredProducts = function () {
            if ($scope.showAllProducts || $scope.products === undefined) {
                return $scope.products;
            }
            return $scope.products.filter(function (product) { return product.quantity > 0; });
        };

        $scope.haveZeroQuantity = function () {
            if ($scope.products === undefined) {
                return false;
            }
            return $scope.products.some(function (product) { return product.quantity <= 0; });
        };

        $scope.changeQuantity = function (product, quantity) {
            var selectedProduct = $scope.selectedProducts[product.id];
            if (selectedProduct === undefined) {
                selectedProduct = angular.copy(product);
                selectedProduct.quantity = 0;
                $scope.selectedProducts[product.id] = selectedProduct;
            }
            var newQuantity = selectedProduct.quantity + quantity;
            if (newQuantity > 0) {
                selectedProduct.quantity = newQuantity;
            } else {
                delete $scope.selectedProducts[product.id];
            }
        };

        $scope.quantity = function (product) {
            var qty = 0;
            var selectedProduct = $scope.selectedProducts[product.id];
            if (selectedProduct) {
                qty = selectedProduct.quantity;
            }
            return ' ' + qty + ' ';
        };

        $scope.sum = function () {
            var sum = 0, id;
            for (id in $scope.selectedProducts) {
                var product = $scope.selectedProducts[id];
                sum += product.price * product.quantity;
            }
            return sum;
        };

        $scope.isDisabled = function (paytype) {
            if ($scope.user) {
                var i, status;
                for (i = 0; i < paytype.allowedForStatus.length; i += 1) {
                    status = paytype.allowedForStatus[i];
                    if ($scope.user.status !== undefined && status.name === $scope.user.status.name) {
                        return false;
                    }
                }
            }
            return true;
        };

        var updateStatus = function (message, error) {
            $scope.statusMessage = message;
            $scope.status = error ? 'Viga!' : 'Korras!';
            $scope.statusError = error;
            $timeout(function () {
                $scope.status = undefined;
            }, 1000);
        };

        var productsArray = function (products) {
            var arr = [], p;
            for (p in products) {
                var product = products[p];
                var transactionProduct = angular.copy(product);
                transactionProduct.product = product;
                transactionProduct.id = null;
                arr.push(transactionProduct);
            }
            return arr;
        };

        $scope.pay = function (paytype) {
            var isEmpty = function (o) {
                var i;
                for (i in o) {
                    if (Object.prototype.hasOwnProperty.call(o, i)) {
                        return false;
                    }
                }
                return true;
            };
            if (!isEmpty($scope.selectedProducts) && $scope.user !== undefined) {
                var transaction = new api.Transaction({products: productsArray($scope.selectedProducts), paytype: paytype, user: $scope.user});
                transaction.$save(function () {
                    updateStatus('Tooted läksid edukalt kirja!', false);
                    $scope.user = null;
                    $scope.selectedProducts = {};
                    getData();
                    $scope.$broadcast("paid");
                });

            } else {
                updateStatus('Palun vali toode ja kasutaja enne maksmist', true);
            }
        };

        $scope.showAllTransactions = false;

        $scope.toggleTransactions = function (show) {
            $scope.showAllTransactions = show;
        };

        $scope.filteredTransactions = function () {
            var transactions = $scope.transactions || [];
            if ($scope.showAllTransactions || transactions.length <= 5) {
                return transactions;
            } else {
                return transactions.slice(0, 5);
            }
        };

        $scope.openFeedbackDialog = function () {

            var modalScope = $scope.$new();
            modalScope.feedback = new api.Feedback();

            var d = $modal({
                templateUrl: '/dialog/feedback',
                scope: modalScope
            });

            modalScope.save = function (feedback) {
                feedback.$save(function () {
                    modalScope.error = false;
                    updateStatus('Tagasiside edastatud!', false);
                    d.hide();
                }, function () {
                    modalScope.error = true;
                });
            };
        };

        $scope.openInfoDialog = function (user) {

            var modalScope = $scope.$new();
            modalScope.user = user;

            var d = $modal({
                templateUrl: '/dialog/info',
                scope: modalScope
            });

            api.stat(user).then(function (response) {
                var stat = response.data;
                modalScope.stat = stat;
                var colors = ['#4A89DC', '#37BC9B', '#3BAFDA', '#DA4453', '#8CC152', '#434A54', '#E9573F', '#D770AD', '#967ADC', '#F6BB42'];
                modalScope.colors = colors;

                var data = [], i;

                for (i = 0; (i < 10) && (i < stat.popularProducts.length); i += 1) {
                    data.push({value: stat.popularProducts[i].count, color: colors[i]});
                }

                modalScope.chartdata = data;
            });

        };

        $scope.openTransactionDialog = function (transaction) {

            var modalScope = $scope.$new();
            modalScope.transaction = transaction;

            var d = $modal({
                templateUrl: '/dialog/transaction',
                scope: modalScope
            });

            modalScope.invalidate = function (transaction) {
                api.invalidate(transaction).then(function () {
                    getData();
                    d.hide();
                });
            };
        };
    });

    app.controller('NavController', function ($scope, $location) {
        $scope.isActive = function (page) {
            return $location.path() === '/' + page;
        };
    });

    app.controller('UsersController', function ($scope, $modal, $window, api) {

        $scope.users = api.User.query();

        $scope.filteredUsers = function () {
            var users = $scope.users;
            if ($scope.filter !== undefined && $scope.filter.length > 0) {
                users = users.filter(function (user) {return user.label.toLowerCase().indexOf($scope.filter.toLowerCase()) !== -1; });
            }
            if ($scope.sortfield !== undefined) {
                var sort = function (a, b) {
                    if ($scope.asc) {
                        return String(a[$scope.sortfield]).localeCompare(b[$scope.sortfield]);
                    } else {
                        return String(b[$scope.sortfield]).localeCompare(a[$scope.sortfield]);
                    }
                };
                users = users.sort(sort);
            }
            return users;
        };

        $scope.asc = true;

        $scope.sort = function (sortfield) {
            if ($scope.sortfield === sortfield) {
                $scope.asc = !$scope.asc;
            }
            $scope.sortfield = sortfield;
        };

        $scope.totalBalance = function () {
            var users = $scope.filteredUsers();
            if (users !== undefined) {
                return users.reduce(function (sum, user) { return sum + user.balance; }, 0);
            }
            return 0;
        };

        $scope.openUserDialog = function (user) {

            api.Status.query(function (statuses) {

                var modalScope = $scope.$new();
                modalScope.user = angular.copy(user) || new api.User();
                modalScope.statuses = statuses;

                var i;
                for (i = 0; i < statuses.length; i += 1) {
                    if (modalScope.user.status === undefined || (user && statuses[i].id === user.status.id)) {
                        modalScope.user.status = statuses[i];
                        break;
                    }
                }

                var d = $modal({
                    templateUrl: '/dialog/user',
                    scope: modalScope
                });

                modalScope.save = function (user) {
                    user.$save(function () {
                        modalScope.error = false;
                        api.User.query(function (users) {
                            $scope.users = users;
                        });
                        d.hide();
                    }, function () {
                        modalScope.error = true;
                    });
                };

                modalScope.delete = function (user) {
                    var confirmed = $window.confirm('Oled kindel, et tahad kasutaja kustutada?');
                    if (confirmed) {
                        user.$remove(function () {
                            $scope.users = $scope.users.filter(function (u) {return user.id !== u.id; });
                            d.hide();
                        }, function () {
                            modalScope.error = true;
                        });
                    }
                };

            });
        };
    });

    app.controller('TransactionsController', function ($scope, api, $modal) {

        $scope.transactions = api.Transaction.query();

        $scope.totalSum = function () {
            var transactions = $scope.transactions;
            if (transactions !== undefined) {
                return transactions.reduce(function (sum, transaction) {
                    if (!transaction.invalid) {
                        return sum + transaction.sum;
                    }
                    return sum;
                }, 0);
            }
            return 0;
        };

        $scope.openDialog = function (transaction) {

            var modalScope = $scope.$new();
            modalScope.transaction = transaction;

            var d = $modal({
                templateUrl: '/dialog/transaction',
                scope: modalScope
            });

            modalScope.invalidate = function (transaction) {
                transaction.$invalidate(function () {
                    transaction.invalid = true;
                    d.hide();
                });
            };
        };
    });

    app.controller('ProductsController', function ($scope, api, $modal, $window) {

        $scope.products = api.Product.query();

        $scope.totalProducts = function () {
            if ($scope.products !== undefined) {
                return $scope.products.reduce(function (sum, product) { return sum + product.quantity; }, 0);
            }
            return 0;
        };

        $scope.sortedProducts = function () {
            var products = $scope.products;
            if ($scope.sortfield !== undefined) {
                var sort = function (a, b) {
                    if ($scope.asc) {
                        return String(a[$scope.sortfield]).localeCompare(b[$scope.sortfield]);
                    } else {
                        return String(b[$scope.sortfield]).localeCompare(a[$scope.sortfield]);
                    }
                };
                products = products.sort(sort);
            }
            return products;
        };

        $scope.asc = true;

        $scope.sort = function (sortfield) {
            if ($scope.sortfield === sortfield) {
                $scope.asc = !$scope.asc;
            }
            $scope.sortfield = sortfield;
        };

        $scope.openProductDialog = function (product) {

            var modalScope = $scope.$new();
            modalScope.product = angular.copy(product) || new api.Product();

            var d = $modal({
                templateUrl: '/dialog/product',
                scope: modalScope
            });

            modalScope.save = function (product) {
                product.$save(function (data) {
                    modalScope.error = false;
                    $scope.products = api.Product.query();
                    d.hide();
                }, function () {
                    modalScope.error = true;
                });
            };

            modalScope.delete = function (product) {
                var confirmed = $window.confirm('Oled kindel, et tahad toote kustutada?');
                if (confirmed) {
                    product.$remove(function () {
                        $scope.products = $scope.products.filter(function (u) {return product.id !== u.id; });
                        d.hide();
                    }, function () {
                        modalScope.error = true;
                    });
                }
            };

        };
    });

    app.controller('PaytypesController', function ($scope, api, $modal, $window) {

        $scope.paytypes = api.Paytype.query();

        $scope.openPaytypeDialog = function (paytype) {
            api.Status.query(function (statuses) {

                var modalScope = $scope.$new();
                modalScope.paytype = angular.copy(paytype) || new api.Paytype();
                modalScope.statuses = statuses;
                modalScope.checked = {};
                modalScope.allowedForStatus = {};

                if (paytype !== undefined) {
                    paytype.allowedForStatus.forEach(function (status) {
                        modalScope.allowedForStatus[status.id] = true;
                    });
                }

                var d = $modal({
                    templateUrl: '/dialog/paytype',
                    scope: modalScope
                });

                modalScope.save = function (p) {
                    if (p !== undefined) {
                        p.allowedForStatus = [];
                        var selected, i;
                        for (selected in modalScope.allowedForStatus) {
                            if (modalScope.allowedForStatus[selected]) {
                                for (i = 0; i < statuses.length; i += 1) {
                                    var status = statuses[i];
                                    if (status.id === parseInt(selected, 10)) {
                                        p.allowedForStatus.push(status);
                                    }
                                }
                            }
                        }
                    }
                    p.$save(function (data) {
                        modalScope.error = false;
                        $scope.paytypes = api.Paytype.query();
                        d.hide();
                    }, function () {
                        modalScope.error = true;
                    });
                };

                modalScope.delete = function (paytype) {
                    var confirmed = $window.confirm('Oled kindel, et tahad makseviisi kustutada?');
                    if (confirmed) {
                        paytype.$remove(function () {
                            $scope.paytypes = $scope.paytypes.filter(function (u) {return paytype.id !== u.id; });
                            d.hide();
                        }, function () {
                            modalScope.error = true;
                        });
                    }
                };

            });
        };

        $scope.statuses = function (paytype) {
            return paytype.allowedForStatus.reduce(function (prev, curr) {
                return prev + curr.name + ", ";
            }, "").slice(0, -2);
        };
    });

    app.controller('StatusesController', function ($scope, api, $modal, $window) {

        $scope.statuses = api.Status.query();

        $scope.openStatusDialog = function (status) {

            console.log(status);

            var modalScope = $scope.$new();
            modalScope.status = angular.copy(status) || new api.Status();

            var d = $modal({
                templateUrl: '/dialog/status',
                scope: modalScope
            });
            modalScope.save = function (s) {
                s.$save(function (data) {
                    modalScope.error = false;
                    $scope.statuses = api.Status.query();
                    d.hide();
                }, function () {
                    modalScope.error = true;
                });
            };
            modalScope.delete = function (status) {
                var confirmed = $window.confirm('Oled kindel, et tahad staatuse kustutada?');
                if (confirmed) {
                    status.$remove(function () {
                        $scope.statuses = $scope.statuses.filter(function (u) {return status.id !== u.id; });
                        d.hide();
                    }, function () {
                        modalScope.error = true;
                    });
                }
            };
        };
    });

    app.controller('StocktakingController', function ($scope, api, $location, $window) {

        $scope.stocktakings = api.Stocktaking.query();

        $scope.view = function (stocktaking) {
            $location.url('/stocktaking/' + stocktaking.id);
        };

        $scope.stocktaking = function () {
            var confirmed = $window.confirm('Oled kindel, et tahad teha inventuuri? Kasutajate saldod nullitakse ja tehingud eemaldatakse.');
            if (confirmed) {
                var stocktaking = new api.Stocktaking();
                stocktaking.$save(function (data) {
                    $scope.stocktakings.push(data);
                });
            }
        };
    });

    app.controller('StocktakingViewController', function ($scope, api, $location, $routeParams, $window) {

        $scope.stocktaking = api.Stocktaking.get({id: $routeParams.id});

        var previous = api.Stocktaking.get({id: $routeParams.id - 1}, function () {
            $scope.previous = previous;
        });

        $scope.back = function () {
            $location.url('/stocktakings');
        };

        $scope.download = function (stocktaking) {
            $window.open('/stocktaking/csv/' + stocktaking.id);
        };

    });

    app.controller('FeedbackController', function ($scope, api) {

        $scope.feedbacks = api.Feedback.query();

        $scope.deleteFeedback = function (feedback) {
            feedback.$remove(function () {
                $scope.feedbacks = $scope.feedbacks.filter(function (u) {return feedback.id !== u.id; });
            });
        };
    });

}(this.angular));


text:
These Spinnaker integration tests depend on the [Cloud Integration Testing]
(https://github.com/google/citest) python package. You'll need to run the
setup script to install the dependencies into your environment, then can
run the tests at will.

To write new tests refer to existing tests and see
[the citest README.md](https://github.com/google/citest/blob/master/README.md)
gifor the time being, and ask questions on the [Spinnaker #dev slack channel]
(https://spinnakerteam.slack.com/messages/dev/).

# About This Subtree

This part of the repository is divided into the following parts:

Directory | Purpose
----------|--------
'tests'  | The actual Spinnaker integration tests.
'spinnaker_testing' | Support modules for the Spinnaker integration tests.
'unittests'        | Unit tests for parts of spinnaker_testing.

# Installing dependencies

## Install and Create a Virtual Env
These tests are written in Python. Instead of installing the dependencies
into system folders consider using something like [virtualenv]
(https://virtualenv.pypa.io/en/stable/). This is optional,
but suggested.

    # Install the python package manager if you dont already have it
    sudo apt-get install python-pip

    # Instal FFI package needed by pyopenssl
    sudo apt-get install libffi-dev libssl-dev python-dev

    # Install virtualenv tools  and setup a Virtual Environment.
    pip install virtualenv

    # Create an environment to use.
    MYENV=my-virtualenv   # to clarify documentation
    virtualenv $MYENV     # create a new environment directory

    # Use the environment for a session (in the current shell).
    source $MYENV/bin/activate  # use $MYENV in the current shell
    ...
    deactivate            # leave the virtualenv when you are done

If you are using Virtual Env, then all the remaining instructions
would be performed within the virtual environment, entered by
`source $MYENV/bin/activate` within the shell you run the commands in.

## Install citest Dependencies
The citest library is not yet published to a pip repository so you need to clone
the citest repository and install it from there.
```
# From another directoy, such as the parent directory to this repository.
cd <parent directory>
git clone https://github.com/google/citest.git
cd citest
pip install -r requirements.txt
```

Then navigate back to the Spinnaker testing directory and install the
requirements for the Spinnaker testing library.
```
cd <parent directory>/spinnaker/testing/citest
pip install -r requirements.txt
```

When executing tests, the `spinnaker/testing/citest/spinnaker_testing` library
needs to be added to your `PYTHONPATH`, e.g.

    cd spinnaker/testing/citest
    PYTHONPATH=.:spinnaker_testing python <test name>.py <args>

## Install Platform Dependencies
Installation of platform-specific tools are not yet automated.
Depending on the platforms involved either by hosting Spinnaker
or being the platform the test is running against, you may need
additional tools.

Platform | Tools | Installation Command
---------|-------|---------------------
Amazon Web Services | awscli | ```sudo apt-get install -y awscli```
Microsoft Azure | az | [See instructions](https://docs.microsoft.com/cli/azure/install-azure-cli)
Google Cloud Platform | gcloud | ```curl https://sdk.cloud.google.com | bash```
Kubernetes | kubectl | [See instructions](http://kubernetes.io/docs/user-guide/prereqs/)
DC/OS | dcos | [See instructions](https://dcos.io/docs/1.9/cli/install/)
OpenStack | openstack | [See instructions](https://docs.openstack.org/user-guide/common/cli-install-openstack-command-line-clients.html)

## Defining Environment Variables
### OpenStack

Below mentioned environment variables are needed in order for OpenStack client to work.

Variable | Description
---------|------------
OS_AUTH_URL | Keystone authentication server URL. (https://identityHost:portNumber/version)
OS_PROJECT_ID | OpenStack project ID.
OS_PROJECT_NAME | OpenStack project name.
OS_USER_DOMAIN_NAME | OpenStack user domain name.
OS_USERNAME | OpenStack user name.
OS_PASSWORD | OpenStack user password.
OS_REGION_NAME | OpenStack region name.
OS_IDENTITY_API_VERSION | Keystone service endpoint version number.
OS_PROJECT_DOMAIN_NAME | OpenStack project domain name.

# Preparing a deployment to test against
Normally these tests do not require any particular type of deployment.
The tests themselves can be run from anywhere provided they can gain
access to the microservices and backend services they need to talk to.

You can run the tests against any standard deployment. The tests will
typically inspect your configuration and adapt themselves if possible
while providing command-line flags for remaining parameters or overrides
for what it may find.

Some tests require unique parameters, or may require certain features
enabled in order to test them, but even so do not typically dictate any
particular values beyond the feature being properly enabled in standard
ways.

2016-09-22 The documentation is sparse at this time. Currently only the
bake_and_deploy test requires special configuration, which is basically
a Jenkins job that it can trigger. Even there, the triggering information is
passed to the test via command-line arguments. Instructions for this can be
found in the test itself: [bake_and_deploy_test.py]
(https://github.com/spinnaker/spinnaker/blob/master/testing/citest/tests/bake_and_deploy_test.py)

## Providing access
If your deployment is firewalled in a way that the machine you are running
from cannot normally access the service endpoints then you will need to tunnel
in or use one of the other suggestions recommended for users to gain access
to the Spinnaker UI. While these tests do not use the UI, the networking
techniques are the same.

If Spinnaker is deployed on the Google Cloud Platform, the tests will
tunnel into them if you use the --gce_[project|zone|instance] parameters.
Otherwise, if you use --native_hostname then you must tunnel in (or provide
some other means).

### Providing the SSH passphrase
If spinnaker tunnels on your behalf, it will need your ssh passphrase.
Since the tests are meant to be automated, these can be implicit by
running something like ssh-agent in the shell you are running the tests from,
or you can create a file containing the passphrase and pass the path on the
command-line using --ssh_passphrase_file. If using the file, be sure to protect
it using `chmod 200`.

# Running the tests

## Optional configuration for exposing deployment configuration

Some configuration parameters in tests can be discovered from the runtime services
rather than relying on manual flag passing. However doing so requires that the
server security configuration be loosened up with the following configuration
parameters which will expose the /resolvedEnv endpoint of microservices as well
as prevent Spring from redacting the values of some sensitive values. While the
tests do not rely on getting the senstive values from the server, they wind up
getting exposed (and possibly logged) as collateral damage.

Again, this particular configuration change is entirely optional.

In spinnaker-local.yml, add the following:
```
management:
  security:
    enabled: false

endpoints:
  resolvedEnv:
    keys-to-sanitize: password,secret,key,token
```

## Standard Parameters For Talking To Spinnaker

The following parameters can be passed on the command-line using a flag
`--`*<parameter_name>*`=`*<parameter_value>*.

### Platform Independent Parameters
Flag | Description
-----|------------
native_hostname | The hostname (or IP address) for the Spinnaker endpoint.
native_port | The portnumber for the Spinnaker endpoint.

### When Spinnaker Is Deployed on GCE
When spinnaker is on GCE you can use the `native_hostname` flag, or
these custom flags which will locate the instance for you. If using the
flags below, citest will automatically attempt to tunnel into the instance
if it is not already reachable.

Flag | Description
-----|------------
gce_project | The Google Cloud Project *running spinnaker* is used to locate spinnaker on GCE.
gce_instance | The name of the Google Cloud Instance that the instance is running on.
gce_zone | The name of the Google Cloud Platform zone the instance is in.
gce_ssh_passphrase_file | The path to the passphrase file for tunneling. Alternatively, you can run something like ssh-agent.

## Standard Parameters Controlling Created Resources
These parameters are typically obtained from the deployed Spinnaker where
possible, and if not have default values so do not need to be specified.

Flag | Description
-----|------------
test_stack | The default Spinnaker Stack to specify in test operations. Setting this could be helpful to identify where resources have come from if you have a shared environment where multiple people or accounts can be running tests independently.
test_app | The Spinnaker application name to use for the test. The tests usually set a default unique name.
managed_gce_project | The Google Cloud Platform for the project that GCE is
managing.
test_gce_zone | The Google Cloud Platform zone you prefer to deploy test
resources into.
test_gce_region | The Google Cloud Platform region you prefer to deploy test
resources into.
test_gce_image_name | The default Google Compute Engine image name to use
when creating test instances requiring an image.
aws_iam_role | The Spinnaker IAM role name for test operations.
test_aws_zone | The Amazon Web Services zone you prefer to deploy test
resources into.
test_aws_region | The Amazon Web Services region you prefer to deploy test
resources into.
test_aws_ami | The default Amazon Web Services Machine Image name to use
when creating test instances requiring an image.
test_aws_vpc_id' | The default AWS VpcId to use when creating test resources.
test_aws_security_group_id: The default AWS SecurityGroupId to use when
creating test resources.
test_azure_rg_location | The azure location where the test resources should be created. Default to westus.
azure_storage_account_key | The key used to read the content from the Azure storage account used by Spinnaker when Spinnaker is configured to use Azure Storage for front50.
azure_storage_account_name | The name of the Azure storage account used by Spinnaker when Spinnaker is configured to use Azure Storage for front50.

### Account Information
Flag | Description
-----|------------
spinnaker_google_credentials | The name of the Spinnaker [clouddriver] account that you wish to use for Google operations. If not specified, this will use the configured primary account.
spinnaker_kubernetes_credentials |  The name of the Spinnaker [clouddriver] account that you wish to use for Kubernetes operations. If not specified, this will use the configured primary account.
spinnaker_aws_credentials |  The name of the Spinnaker [clouddriver] account that you wish to use for Amazon Web Services operations. If not specified, this will use the configured primary account.
spinnaker_os_account | The name of the Spinnaker [clouddriver] account that you wish to use for OpenStack operations. If not specified, this will use the configured primary account.
spinnaker_azure_account | The name of the Spinnaker [clouddriver] account that you wish to use for the Azure operations. If not specified, this will use the configured primary account.
spinnaker_dcos_account | The name of the Spinnaker [clouddriver] account that you wish to use for DC/OS operations. If not specified, this will use the configured primary account.
spinnaker_dcos_cluster | The name of the DC/OS cluster associated to spinnaker_dcos_account to use for DC/OS operations.

## Standard Parameters For Configuring Observers
Flag | Description
-----|------------
gce_credentials_path | The path to a service account JSON credentials file used by the test to verify effects on GCE. The permissions needed on the account may vary depending on what the test is doing. You can use the same service account that you have configured spinnaker with,
aws_profile | The name of the awscli profile to use when verifying effects on AWS. The permissions needed in the profile may vary depending on what the test is doing. You can use the same AWS credentials as those you configured spinnaker to use.
os_cloud | The name of the cloud. OpenStack will look for a clouds.yaml file that contains a cloud configuration to use for authentication.
azure | For Azure, you must login with the following command on the test environment ```az login -u SPN_Client_ID -p SPN_Application_key --tenant Tenant_Name --service-principal``` prior to test execution.

## Typical Invocations

Typical tests assume that the platform running Spinnaker is independent of
the platform providing the resources that Spinnaker is managing. Therefore,
a typical invocation has three sets of commandline parameters.
One set specifies "spinnaker" things, another specifies "managed resource"
things, and lastly, additional "observer" things.

    # Assuming cwd is spinnaker/testing/citest
    PYTHONPATH=.:spinnaker_testing \
    python tests/<fixture name>.py \
    <Talking to Spinnaker Parameters> \
    <Managing Resource Parameters> \
    <Observer Parameters>

### Talking to Spinnaker Parameters
#### Google
        --gce_project=$PROJECT \
        --gce_zone=$ZONE \
        --gce_instance=$INSTANCE \
        --gce_ssh_passphrase_file=<path to optional passphrase file>

#### Aws
        --native_hostname=$HOST

#### Other
        --native_hostname=$HOST

### Managed Resource Parameters

### Observer Parameters
#### Google
        --gce_credentials_path=<path to downloaded JSON credentials>

### Aws
        --aws_profile=$PROFILE

### Kubernetes
        None (when on GCE)

### OpenStack
        --os_cloud=$OS_CLOUD

### Azure
        --azure_storage_account_key=Key to access the storage account used by Spinnaker
        --azure_storage_account_name=Name of the Azure storage account used by Spinnaker

# Usage Examples

Assuming you are in the `spinnaker/testing/citest` directory and testing against GCE
where:

    PROJECT_ID=ewiseblatt-spinnaker-test
    INSTANCE=ewiseblatt-20150805
    ZONE=us-central1-c

then:

    PYTHONPATH=.:spinnaker_testing python \
      tests/google_kato_test.py \
      --gce_project=$PROJECT_ID \
      --gce_instance=$INSTANCE \
      --gce_zone=$ZONE \
      --gce_ssh_passphrase_file=$HOME/.ssh/google_compute_engine.passphrase

If you were testing against some "native" host:

    PYTHONPATH=.:spinnaker_testing python \
      tests/google_kato_test.py \
      --native_host=$HOSTNAME \
      --managed_gce_project=$PROJECT_ID \
      --test_gce_zone=$ZONE

Note that `google_kato_test.py` is written to specifically test managing GCE
instances regardless of where Spinnaker is running from. So you can run
it against an AWS deployment, but will still be observing changes on GCE.

An example testing managing AWS instances, with Spinnaker running on
a "native" host where:

    HOSTNAME=localhost  # IP address where spinnaker is running.
    PROFILE=test        # user creates profile for aws cli tool outside citest.
    ZONE=us-east-1a     # an AWS zone.

then:

    PYTHONPATH=.:spinnaker_testing python \
      tests/aws_kato_test.py \
      --native_host=$HOSTNAME \
      --aws_profile=$PROFILE \
      --test_aws_zone=$ZONE

Note that `aws_kato_test.py` is written to specifically test managing AWS
instances regardless of where Spinnaker is running from. So you can run
it against a GCE deployment, but will still be observing changes on AWS.

redpajama_set_name: RedPajamaGithub


text:
<?php namespace Analogue\ORM\System;

class CachedRelationship {

    protected $hash;

    protected $pivotAttributes;

    public function __construct($hash, $pivotAttributes = [])
    {
        $this->hash = $hash;
        $this->pivotAttributes = $pivotAttributes;
    }

    public function hasPivotAttributes()
    {
        return count($this->pivotAttributes) > 0 ? true : false;
    }

    public function getHash()
    {
        return $this->hash;
    }

    public function getPivotAttributes()
    {
        return $this->pivotAttributes;
    }

    public function __toString()
    {
        return $this->hash;
    }
}


text:
package cloudwf

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// GetLatestStaStatistic invokes the cloudwf.GetLatestStaStatistic API synchronously
// api document: https://help.aliyun.com/api/cloudwf/getlateststastatistic.html
func (client *Client) GetLatestStaStatistic(request *GetLatestStaStatisticRequest) (response *GetLatestStaStatisticResponse, err error) {
	response = CreateGetLatestStaStatisticResponse()
	err = client.DoAction(request, response)
	return
}

// GetLatestStaStatisticWithChan invokes the cloudwf.GetLatestStaStatistic API asynchronously
// api document: https://help.aliyun.com/api/cloudwf/getlateststastatistic.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetLatestStaStatisticWithChan(request *GetLatestStaStatisticRequest) (<-chan *GetLatestStaStatisticResponse, <-chan error) {
	responseChan := make(chan *GetLatestStaStatisticResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.GetLatestStaStatistic(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// GetLatestStaStatisticWithCallback invokes the cloudwf.GetLatestStaStatistic API asynchronously
// api document: https://help.aliyun.com/api/cloudwf/getlateststastatistic.html
// asynchronous document: https://help.aliyun.com/document_detail/66220.html
func (client *Client) GetLatestStaStatisticWithCallback(request *GetLatestStaStatisticRequest, callback func(response *GetLatestStaStatisticResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *GetLatestStaStatisticResponse
		var err error
		defer close(result)
		response, err = client.GetLatestStaStatistic(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// GetLatestStaStatisticRequest is the request struct for api GetLatestStaStatistic
type GetLatestStaStatisticRequest struct {
	*requests.RpcRequest
	ApgroupId requests.Integer `position:"Query" name:"ApgroupId"`
}

// GetLatestStaStatisticResponse is the response struct for api GetLatestStaStatistic
type GetLatestStaStatisticResponse struct {
	*responses.BaseResponse
	RequestId string `json:"RequestId" xml:"RequestId"`
	Success   bool   `json:"Success" xml:"Success"`
	Message   string `json:"Message" xml:"Message"`
	Data      string `json:"Data" xml:"Data"`
	ErrorCode int    `json:"ErrorCode" xml:"ErrorCode"`
	ErrorMsg  string `json:"ErrorMsg" xml:"ErrorMsg"`
}

// CreateGetLatestStaStatisticRequest creates a request to invoke GetLatestStaStatistic API
func CreateGetLatestStaStatisticRequest() (request *GetLatestStaStatisticRequest) {
	request = &GetLatestStaStatisticRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("cloudwf", "2017-03-28", "GetLatestStaStatistic", "cloudwf", "openAPI")
	return
}

// CreateGetLatestStaStatisticResponse creates a response to parse from GetLatestStaStatistic response
func CreateGetLatestStaStatisticResponse() (response *GetLatestStaStatisticResponse) {
	response = &GetLatestStaStatisticResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}


text:
The Reports Page shows the reports documents, the correspondance documents as well as the
reference documents. You can print any of these documents or export them to Word (.doc), Pdf
(.pdf) or Open Office compatible (.rtf) formats. Please see section 16 (Reports Viewer) for more
information.


text:
package org.binxance.service;

import javax.crypto.Mac;

import org.binxance.api.IApiAuthenticationProvider;
import org.binxance.api.IRequest;
import org.binxance.api.ITimeProvider;
import org.binxance.api.Utils;
import org.binxance.api.annotations.ServiceMethod.Auth;
import org.binxance.api.impl.BaseRequestSigner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Signer extends BaseRequestSigner {

	private static final Logger logger = LoggerFactory.getLogger(Signer.class);

	//System.currentTimeMillis()+timeDifference

	@Override
	protected void addSignatureInfo(Auth authType, IRequest req, IApiAuthenticationProvider authInfo, ITimeProvider timeProvider) {
		req.addHeader(Constants.ReqParameters.API_HEADER_NAME, authInfo.getApiKey());
		if ( authType == Auth.SIGNED ){
			Mac mac = macs.computeIfAbsent(authInfo.getApiSecret(), Utils::createHmac);
			//add timestamp param
			req.addParameter(Constants.ReqParameters.API_SIGNED_TIMESTAMP_QPARAM, (timeProvider.getTime())+"");
			//add signature
			String sig = Utils.genreateHmacSignature(mac,req.getParameters());
			logger.trace("Signature generated {}",sig);
			req.addParameter(Constants.ReqParameters.API_SIGNED_SIGNATURE_QPARAM, sig);
		}
	}

}


text:
(function(angular, saveAs) {
    'use strict';

    /**
     * @ngdoc module
     * @name tubular.services
     *
     * @description
     * Tubular Services module.
     * It contains common services like HTTP client, filtering and printing services.
     */
    angular.module('tubular.services', ['ui.bootstrap'])
        /**
         * @ngdoc service
         * @name tubularPopupService
         *
         * @description
         * Use `tubularPopupService` to show or generate popups with a `tbForm` inside.
         */
        .service('tubularPopupService', [
            '$uibModal', '$rootScope', 'tubularTemplateService',
            function($modal, $rootScope, tubularTemplateService) {
                var me = this;

                me.onSuccessForm = function(callback) {
                    $rootScope.$on('tbForm_OnSuccessfulSave', callback);
                };

                me.onConnectionError = function(callback) {
                    $rootScope.$on('tbForm_OnConnectionError', callback);
                };

                /**
                 * Opens a new Popup
                 *
                 * @param {string} template
                 * @param {object} model
                 * @param {object} gridScope
                 * @param {string} size
                 * @returns {object} The Popup instance
                 */
                me.openDialog = function(template, model, gridScope, size) {
                    if (angular.isUndefined(template)) {
                        template = tubularTemplateService.generatePopup(model);
                    }

                    var dialog = $modal.open({
                        templateUrl: template,
                        backdropClass: 'fullHeight',
                        animation: false,
                        size: size,
                        controller: [
                            '$scope', function($scope) {
                                $scope.Model = model;

                                $scope.savePopup = function(innerModel, forceUpdate) {
                                    innerModel = innerModel || $scope.Model;

                                    // If we have nothing to save and it's not a new record, just close
                                    if (!forceUpdate && !innerModel.$isNew && !innerModel.$hasChanges) {
                                        $scope.closePopup();
                                        return null;
                                    }

                                    var result = innerModel.save(forceUpdate);

                                    if (angular.isUndefined(result) || result === false) {
                                        return null;
                                    }

                                    result.then(
                                        function(data) {
                                            $scope.$emit('tbForm_OnSuccessfulSave', data);
                                            $rootScope.$broadcast('tbForm_OnSuccessfulSave', data);
                                            $scope.Model.$isLoading = false;
                                            if (gridScope.autoRefresh) gridScope.retrieveData();
                                            dialog.close();

                                            return data;
                                        }, function(error) {
                                            $scope.$emit('tbForm_OnConnectionError', error);
                                            $rootScope.$broadcast('tbForm_OnConnectionError', error);
                                            $scope.Model.$isLoading = false;

                                            return error;
                                        });

                                    return result;
                                };

                                $scope.closePopup = function() {
                                    if (angular.isDefined($scope.Model.revertChanges)) {
                                        $scope.Model.revertChanges();
                                    }

                                    dialog.close();
                                };
                            }
                        ]
                    });

                    return dialog;
                };
            }
        ])
        /**
         * @ngdoc service
         * @name tubularGridExportService
         *
         * @description
         * Use `tubularGridExportService` to export your `tbGrid` to a CSV file.
         */
        .service('tubularGridExportService', function() {
            var me = this;

            me.getColumns = function(gridScope) {
                return gridScope.columns.map(function(c) { return c.Label; });
            };

            me.getColumnsVisibility = function(gridScope) {
                return gridScope.columns
                    .map(function(c) { return c.Visible; });
            };

            me.exportAllGridToCsv = function(filename, gridScope) {
                var columns = me.getColumns(gridScope);
                var visibility = me.getColumnsVisibility(gridScope);

                gridScope.getFullDataSource(function(data) {
                    me.exportToCsv(filename, columns, data, visibility);
                });
            };

            me.exportGridToCsv = function(filename, gridScope) {
                var columns = me.getColumns(gridScope);
                var visibility = me.getColumnsVisibility(gridScope);

                gridScope.currentRequest = {};
                me.exportToCsv(filename, columns, gridScope.dataSource.Payload, visibility);
                gridScope.currentRequest = null;
            };

            me.exportToCsv = function(filename, header, rows, visibility) {
                var processRow = function(row) {
                    if (typeof (row) === 'object') {
                        row = Object.keys(row).map(function(key) { return row[key]; });
                    }

                    var finalVal = '';
                    for (var j = 0; j < row.length; j++) {
                        if (!visibility[j]) {
                            continue;
                        }

                        var innerValue = row[j] == null ? '' : row[j].toString();

                        if (row[j] instanceof Date) {
                            innerValue = row[j].toLocaleString();
                        }

                        var result = innerValue.replace(/"/g, '""');

                        if (result.search(/("|,|\n)/g) >= 0) {
                            result = '"' + result + '"';
                        }

                        if (j > 0) {
                            finalVal += ',';
                        }

                        finalVal += result;
                    }
                    return finalVal + '\n';
                };

                var csvFile = '';

                if (header.length > 0) {
                    csvFile += processRow(header);
                }

                for (var i = 0; i < rows.length; i++) {
                    csvFile += processRow(rows[i]);
                }

                // Add "\uFEFF" (UTF-8 BOM)
                var blob = new Blob(["\uFEFF" + csvFile], { type: 'text/csv;charset=utf-8;' });
                saveAs(blob, filename);
            };
        })
        /**
         * @ngdoc service
         * @name tubularEditorService
         *
         * @description
         * The `tubularEditorService` service is a internal helper to setup any `TubularModel` with a UI.
         */
        .service('tubularEditorService', [
            '$filter', function($filter) {
                var me = this;

                me.isValid = function(value) {
                    return !(!value);
                };

                /**
                * Simple helper to generate a unique name for Tubular Forms
                */
                me.getUniqueTbFormName = function() {
                    me.tbFormCounter = me.tbFormCounter || (me.tbFormCounter = -1);
                    me.tbFormCounter++;
                    return "tbForm" + me.tbFormCounter;
                };

                /**
             * Setups a new Editor, this functions is like a common class constructor to be used
             * with all the tubularEditors.
             */
                me.setupScope = function(scope, defaultFormat, ctrl, setDirty) {
                    if (angular.isUndefined(ctrl)) ctrl = scope;

                    ctrl.isEditing = angular.isUndefined(ctrl.isEditing) ? true : ctrl.isEditing;
                    ctrl.showLabel = ctrl.showLabel || false;
                    ctrl.label = ctrl.label || (ctrl.name || '').replace(/([a-z])([A-Z])/g, '$1 $2');
                    ctrl.required = ctrl.required || false;
                    ctrl.readOnly = ctrl.readOnly || false;
                    ctrl.format = ctrl.format || defaultFormat;
                    ctrl.$valid = true;

                    // Get the field reference using the Angular way
                    ctrl.getFormField = function() {
                        var parent = scope.$parent;

                        while (true) {
                            if (parent == null) break;
                            if (angular.isDefined(parent.tubularDirective) && parent.tubularDirective === 'tubular-form') {
                                var formScope = parent.getFormScope();

                                return formScope == null ? null : formScope[scope.Name];
                            }

                            parent = parent.$parent;
                        }

                        return null;
                    };

                    ctrl.$dirty = function() {
                        // Just forward the property
                        var formField = ctrl.getFormField();

                        return formField == null ? true : formField.$dirty;
                    };

                    ctrl.checkValid = function() {
                        ctrl.$valid = true;
                        ctrl.state.$errors = [];

                        if ((angular.isUndefined(ctrl.value) && ctrl.required) ||
                        (Object.prototype.toString.call(ctrl.value) === "[object Date]" && isNaN(ctrl.value.getTime()) && ctrl.required)) {
                            ctrl.$valid = false;
                            ctrl.state.$errors = [$filter('translate')('EDITOR_REQUIRED')];

                            if (angular.isDefined(scope.$parent.Model)) {
                                scope.$parent.Model.$state[scope.Name] = ctrl.state;
                            }

                            return;
                        }

                        // Check if we have a validation function, otherwise return
                        if (angular.isUndefined(ctrl.validate)) {
                            return;
                        }

                        ctrl.validate();
                    };

                    scope.$watch(function() {
                        return ctrl.value;
                    }, function(newValue, oldValue) {
                        if (angular.isUndefined(oldValue) && angular.isUndefined(newValue)) {
                            return;
                        }

                        // This is the state API for every property in the Model
                        ctrl.state = {
                            $valid: function() {
                                ctrl.checkValid();
                                return this.$errors.length === 0;
                            },
                            $dirty: ctrl.$dirty,
                            $errors: []
                        };

                        ctrl.$valid = true;

                        // Try to match the model to the parent, if it exists
                        if (angular.isDefined(scope.$parent.Model)) {
                            if (angular.isDefined(scope.$parent.Model[ctrl.name])) {
                                scope.$parent.Model[ctrl.name] = newValue;

                                if (angular.isUndefined(scope.$parent.Model.$state)) {
                                    scope.$parent.Model.$state = [];
                                }

                                scope.$parent.Model.$state[scope.Name] = ctrl.state;
                            } else if (angular.isDefined(scope.$parent.Model.$addField)) {
                                scope.$parent.Model.$addField(ctrl.name, newValue, true);
                            }
                        }

                        ctrl.checkValid();
                    });

                    var parent = scope.$parent;

                    // We try to find a Tubular Form in the parents
                    while (true) {
                        if (parent == null) break;
                        if (angular.isDefined(parent.tubularDirective) &&
                        (parent.tubularDirective === 'tubular-form' ||
                            parent.tubularDirective === 'tubular-rowset')) {

                            if (ctrl.name === null) {
                                return;
                            }

                            if (parent.hasFieldsDefinitions !== false) {
                                throw 'Cannot define more fields. Field definitions have been sealed';
                            }

                            ctrl.$component = parent.tubularDirective === 'tubular-form' ? parent : parent.$component;

                            scope.Name = ctrl.name;

                            ctrl.bindScope = function() {
                                scope.$parent.Model = parent.model;

                                if (angular.equals(ctrl.value, parent.model[scope.Name]) === false) {
                                    if (angular.isDefined(parent.model[scope.Name])) {
                                        if (ctrl.DataType === 'date' && parent.model[scope.Name] != null && typeof parent.model[scope.Name] === 'string') {
                                            // TODO: Include MomentJS
                                            var timezone = new Date(Date.parse(parent.model[scope.Name])).toString().match(/([-\+][0-9]+)\s/)[1];
                                            timezone = timezone.substr(0, timezone.length - 2) + ':' + timezone.substr(timezone.length - 2, 2);
                                            ctrl.value = new Date(Date.parse(parent.model[scope.Name].replace('Z', '') + timezone));
                                        } else {
                                            ctrl.value = parent.model[scope.Name];
                                        }
                                    }

                                    parent.$watch(function() {
                                        return ctrl.value;
                                    }, function(value) {
                                        if (value === parent.model[scope.Name]) return;

                                        parent.model[scope.Name] = value;
                                    });
                                }

                                scope.$watch(function() {
                                    return parent.model[scope.Name];
                                }, function(value) {
                                    if (value === ctrl.value) return;

                                    ctrl.value = value;
                                }, true);

                                if ((!ctrl.value || ctrl.value == null) && (ctrl.defaultValue && ctrl.defaultValue != null)) {
                                    if (ctrl.DataType === 'date' && ctrl.defaultValue != null) {
                                        ctrl.defaultValue = new Date(ctrl.defaultValue);
                                    }
                                    if (ctrl.DataType === 'numeric' && ctrl.defaultValue != null) {
                                        ctrl.defaultValue = parseFloat(ctrl.defaultValue);
                                    }

                                    ctrl.value = ctrl.defaultValue;
                                }

                                if (angular.isUndefined(parent.model.$state)) {
                                    parent.model.$state = {};
                                }

                                // This is the state API for every property in the Model
                                parent.model.$state[scope.Name] = {
                                    $valid: function() {
                                        ctrl.checkValid();
                                        return this.$errors.length === 0;
                                    },
                                    $dirty: ctrl.$dirty,
                                    $errors: []
                                };

                                if (angular.equals(ctrl.state, parent.model.$state[scope.Name]) === false) {
                                    ctrl.state = parent.model.$state[scope.Name];
                                }

                                if (setDirty) {
                                    var formScope = ctrl.getFormField();
                                    if (formScope) formScope.$setDirty();
                                }
                            };

                            parent.fields.push(ctrl);

                            break;
                        }

                        parent = parent.$parent;
                    }
                };
            }
        ]);
})(window.angular, window.saveAs);


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEstoqueProdutosTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('estoque_produtos', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('produto_id')->unsigned();
            $table->integer('movimento_entrada')->default(0);
            $table->integer('movimento_saida')->default(0);
            $table->integer('compra')->default(0);
            $table->integer('venda')->default(0);
            $table->integer('total')->default(0);
            $table->timestamps();

            $table->foreign('produto_id')->references('id')->on('produtos')->onDelete('CASCADE');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('estoque_produtos');
    }
}


text:
void Cache::init(LCDDevice *dev) {
    if(!Cache::enabled) {
        Cache::id = 0;
        Cache::enabled = true;
    }
}

void Cache::clean() {

}

unsigned int Cache::getId() {
    return Cache::id++;
}

unsigned int cachearea(int x, int y, int w, int h) {
    std::ostringstream o;
    unsigned int id = Cache::getId();
    o << id << ".gcf";

    // TODO

    return id;
}


text:
namespace protobuf_unittest {

// Internal implementation detail -- do not call these.
void  protobuf_AddDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
void protobuf_AssignDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();

class TestOptimizedForSize;
class TestRequiredOptimizedForSize;
class TestOptionalOptimizedForSize;

// ===================================================================

class TestOptimizedForSize : public ::google::protobuf::Message {
 public:
  TestOptimizedForSize();
  virtual ~TestOptimizedForSize();

  TestOptimizedForSize(const TestOptimizedForSize& from);

  inline TestOptimizedForSize& operator=(const TestOptimizedForSize& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _unknown_fields_;
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return &_unknown_fields_;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const TestOptimizedForSize& default_instance();
  void Swap(TestOptimizedForSize* other);

  // implements Message ----------------------------------------------

  TestOptimizedForSize* New() const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const { _cached_size_ = size; }
  public:

  const ::google::protobuf::Descriptor* GetDescriptor() const;
  const ::google::protobuf::Reflection* GetReflection() const;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // optional int32 i = 1;
  inline bool has_i() const;
  inline void clear_i();
  static const int kIFieldNumber = 1;
  inline ::google::protobuf::int32 i() const;
  inline void set_i(::google::protobuf::int32 value);

  // optional .protobuf_unittest.ForeignMessage msg = 19;
  inline bool has_msg() const;
  inline void clear_msg();
  static const int kMsgFieldNumber = 19;
  inline const ::protobuf_unittest::ForeignMessage& msg() const;
  inline ::protobuf_unittest::ForeignMessage* mutable_msg();

  GOOGLE_PROTOBUF_EXTENSION_ACCESSORS(TestOptimizedForSize)
  static const int kTestExtensionFieldNumber = 1234;
  static ::google::protobuf::internal::ExtensionIdentifier< ::protobuf_unittest::TestOptimizedForSize,
      ::google::protobuf::internal::PrimitiveTypeTraits< ::google::protobuf::int32 >, 5, false >
    test_extension;
  static const int kTestExtension2FieldNumber = 1235;
  static ::google::protobuf::internal::ExtensionIdentifier< ::protobuf_unittest::TestOptimizedForSize,
      ::google::protobuf::internal::MessageTypeTraits< ::protobuf_unittest::TestRequiredOptimizedForSize >, 11, false >
    test_extension2;
 private:
  ::google::protobuf::internal::ExtensionSet _extensions_;
  ::google::protobuf::UnknownFieldSet _unknown_fields_;
  mutable int _cached_size_;

  ::google::protobuf::int32 i_;
  ::protobuf_unittest::ForeignMessage* msg_;
  friend void  protobuf_AddDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  friend void protobuf_AssignDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  ::google::protobuf::uint32 _has_bits_[(2 + 31) / 32];

  // WHY DOES & HAVE LOWER PRECEDENCE THAN != !?
  inline bool _has_bit(int index) const {
    return (_has_bits_[index / 32] & (1u << (index % 32))) != 0;
  }
  inline void _set_bit(int index) {
    _has_bits_[index / 32] |= (1u << (index % 32));
  }
  inline void _clear_bit(int index) {
    _has_bits_[index / 32] &= ~(1u << (index % 32));
  }

  void InitAsDefaultInstance();
  static TestOptimizedForSize* default_instance_;
};
// -------------------------------------------------------------------

class TestRequiredOptimizedForSize : public ::google::protobuf::Message {
 public:
  TestRequiredOptimizedForSize();
  virtual ~TestRequiredOptimizedForSize();

  TestRequiredOptimizedForSize(const TestRequiredOptimizedForSize& from);

  inline TestRequiredOptimizedForSize& operator=(const TestRequiredOptimizedForSize& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _unknown_fields_;
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return &_unknown_fields_;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const TestRequiredOptimizedForSize& default_instance();
  void Swap(TestRequiredOptimizedForSize* other);

  // implements Message ----------------------------------------------

  TestRequiredOptimizedForSize* New() const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const { _cached_size_ = size; }
  public:

  const ::google::protobuf::Descriptor* GetDescriptor() const;
  const ::google::protobuf::Reflection* GetReflection() const;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // required int32 x = 1;
  inline bool has_x() const;
  inline void clear_x();
  static const int kXFieldNumber = 1;
  inline ::google::protobuf::int32 x() const;
  inline void set_x(::google::protobuf::int32 value);

 private:
  ::google::protobuf::UnknownFieldSet _unknown_fields_;
  mutable int _cached_size_;

  ::google::protobuf::int32 x_;
  friend void  protobuf_AddDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  friend void protobuf_AssignDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32];

  // WHY DOES & HAVE LOWER PRECEDENCE THAN != !?
  inline bool _has_bit(int index) const {
    return (_has_bits_[index / 32] & (1u << (index % 32))) != 0;
  }
  inline void _set_bit(int index) {
    _has_bits_[index / 32] |= (1u << (index % 32));
  }
  inline void _clear_bit(int index) {
    _has_bits_[index / 32] &= ~(1u << (index % 32));
  }

  void InitAsDefaultInstance();
  static TestRequiredOptimizedForSize* default_instance_;
};
// -------------------------------------------------------------------

class TestOptionalOptimizedForSize : public ::google::protobuf::Message {
 public:
  TestOptionalOptimizedForSize();
  virtual ~TestOptionalOptimizedForSize();

  TestOptionalOptimizedForSize(const TestOptionalOptimizedForSize& from);

  inline TestOptionalOptimizedForSize& operator=(const TestOptionalOptimizedForSize& from) {
    CopyFrom(from);
    return *this;
  }

  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _unknown_fields_;
  }

  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return &_unknown_fields_;
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const TestOptionalOptimizedForSize& default_instance();
  void Swap(TestOptionalOptimizedForSize* other);

  // implements Message ----------------------------------------------

  TestOptionalOptimizedForSize* New() const;
  int GetCachedSize() const { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const { _cached_size_ = size; }
  public:

  const ::google::protobuf::Descriptor* GetDescriptor() const;
  const ::google::protobuf::Reflection* GetReflection() const;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // optional .protobuf_unittest.TestRequiredOptimizedForSize o = 1;
  inline bool has_o() const;
  inline void clear_o();
  static const int kOFieldNumber = 1;
  inline const ::protobuf_unittest::TestRequiredOptimizedForSize& o() const;
  inline ::protobuf_unittest::TestRequiredOptimizedForSize* mutable_o();

 private:
  ::google::protobuf::UnknownFieldSet _unknown_fields_;
  mutable int _cached_size_;

  ::protobuf_unittest::TestRequiredOptimizedForSize* o_;
  friend void  protobuf_AddDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  friend void protobuf_AssignDesc_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  friend void protobuf_ShutdownFile_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto();
  ::google::protobuf::uint32 _has_bits_[(1 + 31) / 32];

  // WHY DOES & HAVE LOWER PRECEDENCE THAN != !?
  inline bool _has_bit(int index) const {
    return (_has_bits_[index / 32] & (1u << (index % 32))) != 0;
  }
  inline void _set_bit(int index) {
    _has_bits_[index / 32] |= (1u << (index % 32));
  }
  inline void _clear_bit(int index) {
    _has_bits_[index / 32] &= ~(1u << (index % 32));
  }

  void InitAsDefaultInstance();
  static TestOptionalOptimizedForSize* default_instance_;
};
// ===================================================================

// ===================================================================

// ===================================================================

// TestOptimizedForSize

// optional int32 i = 1;
inline bool TestOptimizedForSize::has_i() const {
  return _has_bit(0);
}
inline void TestOptimizedForSize::clear_i() {
  i_ = 0;
  _clear_bit(0);
}
inline ::google::protobuf::int32 TestOptimizedForSize::i() const {
  return i_;
}
inline void TestOptimizedForSize::set_i(::google::protobuf::int32 value) {
  _set_bit(0);
  i_ = value;
}

// optional .protobuf_unittest.ForeignMessage msg = 19;
inline bool TestOptimizedForSize::has_msg() const {
  return _has_bit(1);
}
inline void TestOptimizedForSize::clear_msg() {
  if (msg_ != NULL) msg_->::protobuf_unittest::ForeignMessage::Clear();
  _clear_bit(1);
}
inline const ::protobuf_unittest::ForeignMessage& TestOptimizedForSize::msg() const {
  return msg_ != NULL ? *msg_ : *default_instance_->msg_;
}
inline ::protobuf_unittest::ForeignMessage* TestOptimizedForSize::mutable_msg() {
  _set_bit(1);
  if (msg_ == NULL) msg_ = new ::protobuf_unittest::ForeignMessage;
  return msg_;
}

// -------------------------------------------------------------------

// TestRequiredOptimizedForSize

// required int32 x = 1;
inline bool TestRequiredOptimizedForSize::has_x() const {
  return _has_bit(0);
}
inline void TestRequiredOptimizedForSize::clear_x() {
  x_ = 0;
  _clear_bit(0);
}
inline ::google::protobuf::int32 TestRequiredOptimizedForSize::x() const {
  return x_;
}
inline void TestRequiredOptimizedForSize::set_x(::google::protobuf::int32 value) {
  _set_bit(0);
  x_ = value;
}

// -------------------------------------------------------------------

// TestOptionalOptimizedForSize

// optional .protobuf_unittest.TestRequiredOptimizedForSize o = 1;
inline bool TestOptionalOptimizedForSize::has_o() const {
  return _has_bit(0);
}
inline void TestOptionalOptimizedForSize::clear_o() {
  if (o_ != NULL) o_->::protobuf_unittest::TestRequiredOptimizedForSize::Clear();
  _clear_bit(0);
}
inline const ::protobuf_unittest::TestRequiredOptimizedForSize& TestOptionalOptimizedForSize::o() const {
  return o_ != NULL ? *o_ : *default_instance_->o_;
}
inline ::protobuf_unittest::TestRequiredOptimizedForSize* TestOptionalOptimizedForSize::mutable_o() {
  _set_bit(0);
  if (o_ == NULL) o_ = new ::protobuf_unittest::TestRequiredOptimizedForSize;
  return o_;
}

}  // namespace protobuf_unittest
#endif  // PROTOBUF_google_2fprotobuf_2funittest_5foptimize_5ffor_2eproto__INCLUDED


text:
module L
  # Moduł helpera dodający metody ułatwiajace wstawianie pól formularza.
  module FormHelper

    def custom_check_box(object_name, method, options = {}, cvalue = '1', ucvalue = '0')
      class_name = *options.delete(:class)
      class_name.push :'custom-check-box'
      label(object_name, method, class: class_name) do
        [
          check_box(object_name, method, options, cvalue, ucvalue),
          content_tag(:i)
        ].join.html_safe
      end
    end

    module FormBuilder
      @@dateoptions = [ :altField, :altFormat, :appendText, :autoSize, :beforeShow, :beforeShowDay, :buttonImage, :buttonImageOnly, :buttonText, :calculateWeek, :changeMonth, :changeYear, :closeText, :constrainInput, :currentText, :dateFormat, :dayNames, :dayNamesMin, :dayNamesShort, :defaultDate, :duration, :firstDay, :gotoCurrent, :hideIfNoPrevNext, :isRTL, :maxDate, :minDate, :monthNames, :monthNamesShort, :navigationAsDateFormat, :nextText, :numberOfMonths, :onChangeMonthYear, :onClose, :onSelect, :prevText, :selectOtherMonths, :shortYearCutoff, :showAnim, :showButtonPanel, :showCurrentAtPos, :showMonthAfterYear, :showOn, :showOptions, :showOtherMonths, :showWeek, :stepMonths, :weekHeader, :yearRange, :yearSuffix]
      @@datetimeoptions = [ :currentText, :closeText, :amNames, :pmNames, :timeFormat, :timeSuffix, :timeOnlyTitle, :timeText, :hourText, :minuteText, :secondText, :millisecText, :microsecText, :timezoneText, :isRTL, :altFieldTimeOnly, :altSeparator, :altTimeSuffix, :altTimeFormat, :timezoneList, :controlType, :showHour, :showMinute, :showSecond, :showMillisec, :showMicrosec, :showTimezone, :showTime, :stepHour, :stepMinute, :stepSecond, :stepMillisec, :stepMicrosec, :hour, :minute, :second, :millisec, :microsec, :timezone, :hourMin, :minuteMin, :secondMin, :millisecMin, :microsecMin, :hourMax, :minuteMax, :secondMax, :millisecMax, :microsecMax, :hourGrid, :minuteGrid, :secondGrid, :millisecGrid, :microsecGrid, :showButtonPanel, :timeOnly, :timeOnlyShowDate, :onSelect, :alwaysSetTime, :separator, :pickerTimeFormat, :pickerTimeSuffix, :showTimepicker, :addSliderAccess, :sliderAccessArgs, :defaultValue, :minDateTime, :maxDateTime, :minTime, :maxTime, :parse ]

      def select_box(method, object, options = {})
        plural_name = method.to_s.pluralize
        options.merge!(multiple: true)
        class_name = *options.delete(:class)
        class_name.push :'custom-check-box'
        tag_value = object.send(method).to_s.gsub(/\s/, "_").gsub(/[^-\w]/, "").downcase
        label("#{plural_name}_#{tag_value}", class: class_name) do
          [
            check_box(plural_name, options, object.send(method), nil),
            @template.content_tag(:i)
          ].join.html_safe
        end
      end

      def datetimepicker(method, options = {})
        option_names = @@dateoptions | @@datetimeoptions
        datetime_opts = options.slice!(option_names)

        sanitized_object_name = @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")
        sanitized_method_name = method.to_s.sub(/\?$/,"")

        _id = options.fetch("id") do
          if options.has_key?("index")
            "#{sanitized_object_name}_#{options['index']}_#{sanitized_method_name}"
          elsif defined?(@auto_index)
            "#{sanitized_object_name}_#{@auto_index}_#{sanitized_method_name}"
          else
            "#{sanitized_object_name}_#{sanitized_method_name}"
          end
        end

        _id = [options.fetch('namespace', nil), _id].compact.join("_").presence
        calendar_id = [options.fetch('namespace', nil), _id, 'calendar'].compact.join("_").presence

        datetime_opts[:altField] = "##{_id}"
        datetime_opts[:altFieldTimeOnly] = false

        [
          hidden_field(method),
          @template.content_tag(:div, '', id: calendar_id),
          @template.javascript_tag("$('##{calendar_id}').datetimepicker(#{datetime_opts.to_json}).datetimepicker('setDate', '#{@object.send(method)}');")
          ].join.html_safe
      end

      def error?(name)
        @object.errors.include?(name)
      end

      def error_messages(name)
        @object.errors[name].try(:map) do |error|
          @object.errors.full_message(name, error)
        end
      end

      def error_message(name)
        error_messages(name).try(:first)
      end
    end

    # Metoda wyswietlająca checkbox dla obiektu jakiego modelu. Uzywane przy
    # wybieraniu stron do masowych akcji na liście elementów.
    #
    # * *Argumenty*:
    #
    #   - +object+ - Obiekt dla którego chcemy wyświetlić checkbox (musi mieć
    #     +id+)
    #   - +name+ - nazwa grupy checkboksów, domyślnie +selected+. Używane w js
    #     do manipulacji wybranymi obiektami.
    #   - +options+ - opcje elementu checkbox, domyślnie: <tt>class='selection'</tt>
    #     i <tt>id="/name/_/id/</tt>.
    def selection_tag(object, name = 'selected', options = {})
      options.merge! class: 'selection', id: "#{name}_#{object.id}"
      check_box_tag "#{name}[]", object.id, false, options
    end

    def sort_column(name, *args)
      options = args.extract_options!
      title = args.pop || t(name, scope:[:sort_columns], default: name.to_s.titleize)
      direction = :asc

      disabled = options.delete(:disabled) { false }
      class_name = [:sort, *options.delete(:class)].compact

      if params[:sort].try(:[], :column).try(:to_sym) == name
        direction = params[:sort].try(:[], :dir) == 'asc' ? :desc : :asc
        class_name << :current
        class_name << direction
      end

      options[:class] = class_name

      filter = params[:filter]

      if disabled
        content_tag(:span, title, options)
      else
        link_to title, {sort: {column: name, dir: direction}, filter: filter}, options
      end
    end

    # Metoda wyświetlajaca przycisk do sortowania, jako +button_tag+.
    #
    # * *Argumenty*:
    #
    #   - +name+ - nazwa pola które chcemy sortować
    #   - +type+ - typ sortowania, +:desc+ lub +:asc+
    #   - +options+ - opcje elementu +submit_tag+, domyślnie klasa up/down w
    #     zależności od typu sortowania, <tt>name="sort"</tt> oraz tytuł
    #     (+title+) równie tłumaczeniu +sort.asc+ lub +sort.desc+, do zmiany w
    #     pliku +config/locales/pl.yml+.
    def sort_tag(name, type, options = {})
      options = options.reverse_merge({
        title: I18n.t("sort.#{type.to_s}")
      })

      class_name = ["sort", *options.delete(:class)]

      sort_type = "#{name.to_s}_#{type.to_s}"

      if (params[:sort] == sort_type)
        class_name << "current"
      end

      class_name << (type == :asc ? 'up' : 'down')

      options[:class] = class_name

      link_to "", {sort: sort_type}, options
    end

    # Tag input[type=files] obsługiwany przez plugin
    # jquery-fileupload. Argumenty jak w file_field_tag.
    # Domyślnie możliwy wybór wielu plików
    #
    def file_upload_tag(name, options = {})
      class_name = options.delete(:class)
      options[:class] = [:fileupload, :'custom-file-input', class_name].flatten.compact!
      options[:multiple] = true if options[:multiple].nil?

      options[:data] ||= {}
      options[:data][:label] ||= I18n.t(:label, default: 'Select file', scope: 'helpers.fileupload')

      file_field_tag(name, options)
    end
  end
end


text:
package com.sequenceiq.cloudbreak.service.decorator.responseprovider;

import com.sequenceiq.cloudbreak.api.model.StackResponse;
import com.sequenceiq.cloudbreak.domain.Stack;

public interface ResponseProvider {

    StackResponse providerEntriesToStackResponse(Stack stack, StackResponse stackResponse);

    String type();
}


text:
package me.marksill.realisticsurvival.item;

import me.marksill.realisticsurvival.RealisticSurvival;
import me.marksill.realisticsurvival.util.Helper;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.registry.GameRegistry;

public class BaseItem extends Item {

	public String texture;

	public BaseItem(String name) {
		this(name, name);
	}

	public BaseItem(String name, String texture) {
		this.setUnlocalizedName(name);
		this.texture = texture;
		this.setCreativeTab(RealisticSurvival.tab1);
		GameRegistry.registerItem(this, name);
		RSItems.items.add(this);
	}

}


text:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- Pretty hint text, and maxLines -->
    <EditText android:id="@+id/search_box"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="type to filter"
        android:inputType="text"
        android:maxLines="1"/>

    <!-- Set height to 0, and let the weight param expand it -->
    <!-- Note the use of the default ID! This lets us use a
         ListActivity still! -->
    <ListView android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1"
         />
</LinearLayout>


text:
declare module "react-responsive" {
    import * as React from "react";

    namespace MediaQuery {
        export interface MediaQueryProps {
            query?: string;
            // matchers
            orientation?: "portrait" | "landscape";
            scan?: "progressive" | "interlace";
            aspectRatio?: string;
            deviceAspectRatio?: string;
            height?: number | string;
            deviceHeight?: number | string;
            width?: number | string;
            deviceWidth?: number | string;
            color?: boolean;
            colorIndex?: boolean;
            monochrome?: boolean;
            resolution?: number | string;
            // types
            minAspectRatio?: string;
            maxAspectRatio?: string;
            minDeviceAspectRatio?: string;
            maxDeviceAspectRatio?: string;
            minHeight?: number | string;
            maxHeight?: number | string;
            minDeviceHeight?: number | string;
            maxDeviceHeight?: number | string;
            minDeviceWidth?: number | string;
            maxDeviceWidth?: number | string;
            minWidth?: number | string;
            maxWidth?: number | string;
            minColor?: number;
            maxColor?: number;
            minColorIndex?: number;
            maxColorIndex?: number;
            minMonochrome?: number;
            maxMonochrome?: number;
            minResolution?: number | string;
            maxResolution?: number | string;
            // types
            all?: boolean;
            grid?: boolean;
            aural?: boolean;
            braille?: boolean;
            handheld?: boolean;
            print?: boolean;
            projection?: boolean;
            screen?: boolean;
            tty?: boolean;
            tv?: boolean;
            embossed?: boolean;
        }
    }

    class MediaQuery extends React.Component<MediaQuery.MediaQueryProps> { }
    export = MediaQuery;

}


text:
package db

import (
	"database/sql"
	"log"
	"time"
)

const (
	INSERT_USER = `
		INSERT INTO "user"
		("uuid", "email", "hash", "firstname", "lastname", "creation_time", "last_login")
		VALUES
		($1, $2, $3, $4, $5, $6, $7)
	`

	INSERT_SESSION = `
		INSERT INTO "session"
		("token", "uuid", "hit_time")
		VALUES
		($1, $2, $3)
	`

	EXISTING_EMAIL = `
		SELECT "email"
		FROM "user"
		WHERE "email" = $1
	`

	USER_BY_EMAIL = `
		SELECT "uuid", "email", "firstname", "lastname", "creation_time", "last_login", "hash" FROM "user"
		WHERE "email" = $1
		LIMIT 1
	`

	USER_FROM_SESSION_UUID = `
		SELECT "user"."uuid", "user"."email", "user"."firstname", "user"."lastname", "user"."creation_time", "user"."last_login"
		FROM "user"
		JOIN "session" ON "session"."uuid" = "user"."uuid" AND "session"."token" = $1
	`

	DELETE_SESSION = `
		DELETE FROM "session"
		WHERE "token" = $1
	`

	UPDATE_SESSION = `
		UPDATE "session"
		SET "hit_time" = $1
		WHERE "token" = $2
	`

	DELETE_EXPIRED_SESSIONS = `
		DELETE FROM "session"
		WHERE "hit_time" < $1
	`
)

func (c Conn) InsertUser(user User, hash string) (sql.Result, error) {
	return c.db.Exec(INSERT_USER, user.Uuid, user.Email, hash, user.Firstname, user.Lastname, user.CreationTime, user.LastLogin)
}

func (c Conn) InsertSession(session Session) error {
	_, err := c.db.Exec(INSERT_SESSION, session.Token, session.User.Uuid, session.HitTime)
	return err
}

func (c Conn) ExistingEmail(email string) (bool, error) {
	r, err := c.db.Query(EXISTING_EMAIL, email)
	if err != nil {
		return false, err
	}

	if r == nil {
		return false, nil
	}

	defer r.Close()

	if r.Next() {
		return true, nil
	}
	return false, nil
}

func (c Conn) DeleteExpiredSessions(sessionExpiration time.Duration) (sql.Result, error) {
	return c.db.Exec(DELETE_EXPIRED_SESSIONS, time.Now().Add(-sessionExpiration))
}

func (c Conn) UpdateSession(token string) {
	if _, err := c.db.Exec(UPDATE_SESSION, time.Now(), token); err != nil {
		log.Printf("err: while updating the session '%s': %s'", token, err.Error())
	}
}

func (c Conn) DeleteSession(token string) {
	if _, err := c.db.Exec(DELETE_SESSION, token); err != nil {
		log.Printf("err: while deleting the session '%s': %s'", token, err.Error())
	}
}

// GetUserByEmail returns the found user by email
// and its hash in a separate string.
func (c Conn) GetUserByEmail(email string) (User, string, error) {
	r, err := c.db.Query(USER_BY_EMAIL, email)
	if err != nil {
		return User{}, "", err
	}

	if r == nil {
		return User{}, "", nil
	}

	defer r.Close()

	var user User
	var hash string
	if r.Next() {
		if err := r.Scan(&user.Uuid, &user.Email, &user.Firstname, &user.Lastname, &user.CreationTime, &user.LastLogin, &hash); err != nil {
			return User{}, "", err
		}
	}
	return user, hash, nil
}

func (c Conn) GetUserFromSessionToken(token string) (User, error) {
	r, err := c.db.Query(USER_FROM_SESSION_UUID, token)
	if err != nil {
		return User{}, err
	}

	if r == nil {
		return User{}, nil
	}

	defer r.Close()

	if r.Next() {
		var uuid, email, firstname, lastname string
		var creationTime, lastLogin time.Time

		if err := r.Scan(&uuid, &email, &firstname, &lastname, &creationTime, &lastLogin); err == nil {
			return User{
				Uuid:         uuid,
				Email:        email,
				Firstname:    firstname,
				Lastname:     lastname,
				CreationTime: creationTime,
				LastLogin:    lastLogin,
			}, nil
		} else {
			return User{}, err
		}
	}

	return User{}, nil
}


text:
AUTH_ENABLED = True    # set to True to enable LDAP SSL auth.
                        # Note: when set to False you will only be able to
                        # login as TESTUSER

DEBUG = True            # set to False in production

DB_PATH = '/Users/james.denness/virtualenv/graphite-boards/graphite-boards/db/db.db'              # full path to a sqllite db. this will be created
                        # automatically on first start

LDAP_SERVER = ""        # fqdn for ldap server
LDAP_BASEDN = ""        # basedn e.g. "c=gb,dc=mycompany,dc=com"
LDAP_OU = ""            # search ou for user e.g. "ou=People"
LDAP_CERTIFICATE  = ""  # full path to your LDAP ssl certificate
LDAP_ENABLED = False    # Enable LDAP based auth


text:
Most of the time, if you write something of significant complexity, you may
need to set a breakpoint and trace through it. The M-Web-Server supports a mode
for allowing you to do that, where all the processing will take place in a
foreground process. You need to set your breakpoints first, and then you start
the web server using `DO START^VPRJREQ(<port>,1)`. The second parameter of 1
means that the web server won't job off new processes but will use the current
process to service the request.

Here's an example: Suppose we want to debug the code that displays routines for
us at r/{routine}. From the home page, we know that it calls R^%W0. So what we
can do is put a break point there, and then launch the web server in debug mode.

```
zbreak R^%webapi
D start^%webreq(9080,1)
```

Now, we need to make a web service call to get a routine. In another terminal
on the same machine, we can run curl.

```
curl localhost:9080/r/XUS
```

At this point, we will hit the break point and we will be able to step into it:

```
%YDB-I-BREAKZBA, Break instruction encountered during ZBREAK action
                At M source location R^%W0
%YDB-W-NOTPRINCIO, Output currently directed to device SCK$9080

VEHU6>zst into
 S RESULT("mime")="text/plain; charset=utf-8"
%YDB-I-BREAKZST, Break instruction encountered during ZSTEP action
                At M source location R+1^%W0

VEHU6>zst into
 S RESULT=$NA(^TMP($J))
%YDB-I-BREAKZST, Break instruction encountered during ZSTEP action
                At M source location R+2^%W0

VEHU6>zst into
 K @RESULT
%YDB-I-BREAKZST, Break instruction encountered during ZSTEP action
                At M source location R+3^%W0

VEHU6>
```

That's it. You are now stepping into the code. Of note, you can use the same
mechanism to debug the M Web Server itself.

For help learning how to debug on specific M platforms:

 * GTM: http://tinco.pair.com/bhaskar/gtm/doc/books/pg/UNIX_manual/ch04s02.html
 * YottaDB: https://docs.yottadb.com/ProgrammersGuide/opdebug.html#debugging-a-routine-in-direct-mode
 * Cache: https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY=GCOS_debug


text:
<?php

namespace Application\EservicesBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * NotesRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class EproduitNotesRepository extends EntityRepository {

    public function myFindAll() {
        return $this->createQueryBuilder('a')
                        ->getQuery();

        //->getResult();
    }

    public function getUserNotesForProduit($user_id,$produit_id)
    {
        $qb = $this->createQueryBuilder('c')
                   ->select('c')
                   ->where('c.user = :userId')

                   ->addOrderBy('c.isComment')
                   ->addOrderBy('c.created')
                   ->setParameter('produit_id', $produitId);

        if (false === is_null($approved))
            $qb->andWhere('c.approved = :approved')
               ->setParameter('approved', $approved);

        return $qb->getQuery()
                  ->getResult();
    }

}


text:
<?xml version="1.0" ?>
<tei>
	<teiHeader>
		<fileDesc xml:id="55010033"/>
	</teiHeader>
	<text xml:lang="en">
		<front>
<lb/>
	<docTitle>
	<titlePart>Determining the Influence of Contaminants on<lb/> Biodiesel Properties<lb/></titlePart>
	</docTitle>

	<note type="other">Final report prepared for:<lb/> The Iowa Soybean Promotion Board<lb/> Submitted by:<lb/></note>

	<byline>
	<docAuthor>Jon H. Van Gerpen<lb/> Earl G. Hammond<lb/> Lawrence A. Johnson<lb/> Stephen J. Marley<lb/> Liangping Yu<lb/> Inmok Lee<lb/> Abdul Monyem<lb/></docAuthor>
	</byline>

	<byline>
	<affiliation>Iowa State University<lb/></affiliation>
	</byline>

	<date>July 31, 1996<lb/></date>

	<note type="other">Table of Contents<lb/></note>

		</front>
	</text>
</tei>


text:
'use strict'

const Router = require('express').Router
const passport = require('passport')
var GoogleStrategy = require('passport-google-oauth20').Strategy
const config = require('../../config')
const { setReturnToFromReferer, passportGeneralCallback } = require('../utils')

const googleAuth = module.exports = Router()

passport.use(new GoogleStrategy({
  clientID: config.google.clientID,
  clientSecret: config.google.clientSecret,
  callbackURL: config.serverURL + '/auth/google/callback',
  userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo'
}, passportGeneralCallback))

googleAuth.get('/auth/google', function (req, res, next) {
  setReturnToFromReferer(req)
  passport.authenticate('google', {
    scope: ['profile'],
    hostedDomain: config.google.hostedDomain
  })(req, res, next)
})
// google auth callback
googleAuth.get('/auth/google/callback',
  passport.authenticate('google', {
    successReturnToOrRedirect: config.serverURL + '/',
    failureRedirect: config.serverURL + '/'
  })
)


text:
@import Specta;
@import Expecta;
@import AUTLogKit;

#import "AUTExtObjC.h"

SpecBegin(AUTLogFilteringFormatter)

let CreateLogMessage = ^(DDLogLevel level, DDLogFlag flag, NSInteger context) {
    return [[DDLogMessage alloc]
        initWithMessage:@"foo"
        level:level
        flag:flag
        context:context
        file:@(__FILE__)
        function:@(__FUNCTION__)
        line:0
        tag:nil
        options:0
        timestamp:nil];
};

it(@"should not filter messages that do not have contexts", ^{
    let includingLevelsByContextID = @{ @1: @(AUTLogLevelOff) };
    let logFormatter = [[AUTLogFilteringFormatter alloc] initWithIncludedLevelsByContextID:includingLevelsByContextID];

    let logMessage = CreateLogMessage(DDLogLevelInfo, DDLogFlagInfo, 0);

    let formattedMessage = [logFormatter formatLogMessage:logMessage];
    expect(formattedMessage).toNot.beNil();
});

it(@"should filter message not within the included contexts", ^{
    let includingLevelsByContextID = @{ @1: @(AUTLogLevelAll) };
    let logFormatter = [[AUTLogFilteringFormatter alloc] initWithIncludedLevelsByContextID:includingLevelsByContextID];

    let logMessage = CreateLogMessage(DDLogLevelInfo, DDLogFlagInfo, 2);

    let formattedMessage = [logFormatter formatLogMessage:logMessage];
    expect(formattedMessage).to.beNil();
});

it(@"should filter messages that are below the highest allowed log level", ^{
    NSUInteger context = 1;
    let includingLevelsByContextID = @{ @(context): @(AUTLogLevelError) };
    let logFormatter = [[AUTLogFilteringFormatter alloc] initWithIncludedLevelsByContextID:includingLevelsByContextID];

    let logMessage = CreateLogMessage(DDLogLevelInfo, DDLogFlagInfo, context);

    let formattedMessage = [logFormatter formatLogMessage:logMessage];
    expect(formattedMessage).to.beNil();
});

it(@"should not filter messages that meet the highest allowed log level", ^{
    NSUInteger context = 1;
    let includingLevelsByContextID = @{ @(context): @(AUTLogLevelInfo) };
    let logFormatter = [[AUTLogFilteringFormatter alloc] initWithIncludedLevelsByContextID:includingLevelsByContextID];

    let logMessage = CreateLogMessage(DDLogLevelInfo, DDLogFlagInfo, context);

    let formattedMessage = [logFormatter formatLogMessage:logMessage];
    expect(formattedMessage).toNot.beNil();
});

it(@"should not filter messages that exceed the highest allowed log level", ^{
    NSUInteger context = 1;
    let includingLevelsByContextID = @{ @(context): @(AUTLogLevelInfo) };
    let logFormatter = [[AUTLogFilteringFormatter alloc] initWithIncludedLevelsByContextID:includingLevelsByContextID];

    let logMessage = CreateLogMessage(DDLogLevelError, DDLogFlagError, context);

    let formattedMessage = [logFormatter formatLogMessage:logMessage];
    expect(formattedMessage).toNot.beNil();
});

it(@"should not filter message with non excluded context", ^{
    NSUInteger context = 1;
    let includingLevelsByContextID = @{ @(context): @(AUTLogLevelAll) };
    let logFormatter = [[AUTLogFilteringFormatter alloc] initWithIncludedLevelsByContextID:includingLevelsByContextID];

    let logMessage = CreateLogMessage(DDLogLevelInfo, DDLogFlagInfo, context);

    let formattedMessage = [logFormatter formatLogMessage:logMessage];
    expect(formattedMessage).toNot.beNil();
});

SpecEnd


text:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

# By converting each letter in a word to a number corresponding to its
# alphabetical position and adding these values we form a word value. For
# example, the word value for SKY is 19 + 11 + 25 = 55 = t10. If the word
# value is a triangle number then we shall call the word a triangle word.

# Using words.txt (right click and 'Save Link/Target As...'), a 16K text file
# containing nearly two-thousand common English words, how many are triangle
# words?

import helpers.file as fileutils

# arbitrary value for the highest reachable triangle number
MAX = 1000

def euler():
    # set of the triangle numbers until an arbitrary maximum number
    triangles = set()
    # generate triangle numbers
    n = 1
    highest_triangle = 0
    while highest_triangle < MAX:
        highest_triangle = n * (n + 1) // 2
        triangles.add(highest_triangle)
        n += 1
    # read the words and put them into a list of strings
    words = fileutils.flattened_list_from_file('data/042.txt',
            separator = ',', convert_to = str)
    # strip the quote-sign from the strings, leaving only the word
    words = [word.replace('"', '') for word in words]
    # accumulator for the final answer, the number of triangle words
    triangle_word_count = 0
    # count the number of triangle words
    for word in words:
        if word_to_int(word) in triangles:
            triangle_word_count += 1
    # return it
    return triangle_word_count

def word_to_int(word):
    """Returns the sum of the 'letter value' of each letter in the word.

    ('a' = 1, 'b' = 2, 'c' = 3, ...)"""
    return sum(ord(letter) - ord('a') + 1 for letter in word.lower())


text:
package com.guardtime.ksi.service.client;

import com.guardtime.ksi.pdu.PduVersion;

import java.io.Closeable;

/**
 * Defining KSI related services.
 */
interface KSICredentialsAwareClient extends Closeable {

    /**
     * Gets the service credentials used by this client.
     */
    ServiceCredentials getServiceCredentials();

    /**
     * Gets the PDU format version of the client.
     */
    PduVersion getPduVersion();

}


text:
A script that re-indexes a mail directory using `mu` and creates notifications for each new email. This is best run as a cron job or systemd timer.

#### Dependencies

* **[mu](https://github.com/djcb/mu)** - maildir indexer & searcher
* **[notify-send](https://ss64.com/bash/notify-send.html)** - sends desktop notifications

#### Usage

    ./mu-index <maildir> <folders> <optional-user>

#### Parameters

* **maildir** - The directory where the maildir is located at (eg: ~/.mail)
* **folders** - Comma delimited list of folders to consider when looking for new mail (eg: "/fastmail/INBOX,/gmail/INBOX")
* **user** - Optional parameter that is required if running as root.

#### Example

    ./mu-index '~/.mail' '/fastmail/INBOX,/gmail/INBOX' myuser