text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **

'use strict';

function main(account, updateMask) {
  // [START analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_async]
  /**
   * This snippet has been automatically generated and should be regarded as a code template only.
   * It will require modifications to work.
   * It may require correct/in-range values for request initialization.
   * TODO(developer): Uncomment these variables before running the sample.
   */
  /**
   *  Required. The account to update.
   *  The account's `name` field is used to identify the account.
   */
  // const account = {}
  /**
   *  Required. The list of fields to be updated. Field names must be in snake case
   *  (e.g., "field_to_update"). Omitted fields will not be updated. To replace
   *  the entire entity, use one path with the string "*" to match all fields.
   */
  // const updateMask = {}

  // Imports the Admin library
  const {AnalyticsAdminServiceClient} = require('@google-cloud/admin').v1beta;

  // Instantiates a client
  const adminClient = new AnalyticsAdminServiceClient();

  async function callUpdateAccount() {
    // Construct request
    const request = {
      account,
      updateMask,
    };

    // Run request
    const response = await adminClient.updateAccount(request);
    console.log(response);
  }

  callUpdateAccount();
  // [END analyticsadmin_v1beta_generated_AnalyticsAdminService_UpdateAccount_async]
}

process.on('unhandledRejection', err => {
  console.error(err.message);
  process.exitCode = 1;
});
main(...process.argv.slice(2));


text:
class BrowserFrameViewLinux : public OpaqueBrowserFrameView,
                              public ui::WindowButtonOrderObserver {
 public:
  BrowserFrameViewLinux(BrowserFrame* frame,
                        BrowserView* browser_view,
                        BrowserFrameViewLayoutLinux* layout);

  BrowserFrameViewLinux(const BrowserFrameViewLinux&) = delete;
  BrowserFrameViewLinux& operator=(const BrowserFrameViewLinux&) = delete;

  ~BrowserFrameViewLinux() override;

  BrowserFrameViewLayoutLinux* layout() { return layout_; }

  // Gets the rounded-rect that will be used to clip the window frame when
  // drawing.  The region will be as if the window was restored, and will be in
  // view coordinates.
  SkRRect GetRestoredClipRegion() const;

  // Gets the shadow metrics (radius, offset, and number of shadows).  This will
  // always return shadow values, even if shadows are not actually drawn.
  static gfx::ShadowValues GetShadowValues();

 protected:
  // ui::WindowButtonOrderObserver:
  void OnWindowButtonOrderingChange() override;

  // views::View:
  void PaintRestoredFrameBorder(gfx::Canvas* canvas) const override;

  // views::NonClientFrameView:
  void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override;

  // OpaqueBrowserFrameViewLayoutDelegate:
  bool ShouldDrawRestoredFrameShadow() const override;

  // Gets the radius of the top corners when the window is restored.  The
  // returned value is in DIPs.  The result will be 0 if rounded corners are
  // disabled (eg. if the compositor doesn't support translucency.)
  virtual float GetRestoredCornerRadiusDip() const;

 private:
  const raw_ptr<BrowserFrameViewLayoutLinux> layout_;

  base::ScopedObservation<ui::LinuxUiTheme,
                          ui::WindowButtonOrderObserver,
                          &ui::LinuxUiTheme::AddWindowButtonOrderObserver,
                          &ui::LinuxUiTheme::RemoveWindowButtonOrderObserver>
      window_button_order_observation_{this};
};

#endif  // CHROME_BROWSER_UI_VIEWS_FRAME_BROWSER_FRAME_VIEW_LINUX_H_

redpajama_set_name: RedPajamaGithub


text:
import { ColorEditor } from '../ColorEditor';
import React from 'react';
import { shallow } from 'enzyme';
import { CirclePicker, TwitterPicker } from 'react-color';

describe('Color Editor', () => {
   let colorEditorWrapper;

   const props = {
      editorValue: 'black',
      onValueChanged: jest.fn(),
      extraProp: 'ext',
      secondProp: 'ext'
   };

   const render = (extraProps = {}) => shallow(<ColorEditor {...props} {...extraProps} />);
   const getDefaultPicker = () => colorEditorWrapper.find(CirclePicker);

   beforeEach(() => {
      colorEditorWrapper = render();
   });

   it('should render a the correct editor with the correct props', () => {
      const { width, color, onChangeComplete, extraProp, secondProp } = getDefaultPicker().props();

      const { editorValue: expectedColor, extraProp: expectedExtraProp, secondProp: expectedSecondProp } = props;

      expect(width).toBe(250);
      expect(color).toBe(expectedColor);
      expect(onChangeComplete).toBeDefined();
      expect(extraProp).toBe(expectedExtraProp);
      expect(secondProp).toBe(expectedSecondProp);
   });

   it('should render a custom renderer', () => {
      colorEditorWrapper = render({ Renderer: TwitterPicker });

      expect(colorEditorWrapper.find(TwitterPicker).length).toBe(1);
      expect(colorEditorWrapper.find(CirclePicker).length).toBe(0);
   });

   it('onChangeComplete should call onValueChanged with the correct params', () => {
      const selectedColor = 'red';
      const { onValueChanged } = props;
      getDefaultPicker().simulate('changeComplete', { hex: selectedColor });

      expect(onValueChanged).lastCalledWith(selectedColor);
   });
});


text:
'use strict';

/**
 * @ngdoc service
 * @name core.service:Menus
 *
 * @description
 * AngularJS Menus Service
 *
 * In the 0.3.x version, MEAN.JS has introduced a new AngularJS service that helps you manage your application menus.
 */

//Menu service used for managing  menus
angular.module('core').service('Menus', [

	function() {
		// Define a set of default roles
		this.defaultRoles = ['*'];

		// Define the menus object
		this.menus = {};

		// A private function for rendering decision
		var shouldRender = function(user) {
			if (user) {
				if (!!~this.roles.indexOf('*')) {
					return true;
				} else {
					for (var userRoleIndex in user.roles) {
						for (var roleIndex in this.roles) {
							if (this.roles[roleIndex] === user.roles[userRoleIndex]) {
								return true;
							}
						}
					}
				}
			} else {
				return this.isPublic;
			}

			return false;
		};

		// Validate menu existance
		this.validateMenuExistance = function(menuId) {
			if (menuId && menuId.length) {
				if (this.menus[menuId]) {
					return true;
				} else {
					throw new Error('Menu does not exists');
				}
			} else {
				throw new Error('MenuId was not provided');
			}

			return false;
		};

		/**
 		 * @ngdoc method
		 * @name core.service:Menus.getMenu
		 * @methodOf core.service:Menus
	 	 *
		 * @param {Number} menuId Indicates the menu identifier
		 * @return {Object} A menu object identified by the menuId argument
		 *
		 * @description
		 * Returns the menu object identified by the menuId argument.
		 */
		// Get the menu object by menu id
		this.getMenu = function(menuId) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Return the menu object
			return this.menus[menuId];
		};

		/**
		 * @ngdoc method
		 * @name core.service:Menus.addMenu
		 * @methodOf core.service:Menus
		 *
		 * @param {Number} menuId Indicates the menu identifier for future reference
		 * @param {Boolean} isPublic Indicates whether a menu should be displayed only to authenticated users
		 * @param {Array.<String>} [roles=['user']] An array indicating the roles that are allowed to view this menu
		 * @return {Object} The menu object.
		 *
		 * @description
		 * Creates a new menu object, which will be identified by the menuId argument.
		 */
		// Add new menu object by menu id
		this.addMenu = function(menuId, isPublic, roles) {
			// Create the new menu
			this.menus[menuId] = {
				isPublic: isPublic || false,
				roles: roles || this.defaultRoles,
				items: [],
				shouldRender: shouldRender
			};

			// Return the menu object
			return this.menus[menuId];
		};

		/**
		 * @ngdoc method
		 * @name core.service:Menus.removeMenu
		 * @methodOf core.service:Menus
		 *
		 * @param {Number} menuId Indicates the menu identifier
		 *
		 * @description
		 * Delete the menu object identified by the menuId argument.
		 */
		// Remove existing menu object by menu id
		this.removeMenu = function(menuId) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Return the menu object
			delete this.menus[menuId];
		};

		/**
		 * @ngdoc method
		 * @name core.service:Menus.addMenuItem
		 * @methodOf core.service:Menus
		 *
		 * @param {Number} menuId Indicates the menu identifier.
		 * @param {String} menuItemTitle A String title for the menu item.
		 * @param {String} menuItemURL The path this menu item will link to.
		 * @param {String} [menuItemType='item'] -
		 * @param {String} [menuItemUIRoute=menuItemURL] The UIRoute value, which is used to define the URL scheme where this menu item is marked as active.
		 * @param {Boolean} isPublic Indicates whether a menu item should be displayed only to authenticated users.
		 * @param {Array.<String>} [roles=['user']] An array indicating the roles that are allowed to view this menu item.
		 * @param {Number} [position=0] -
		 * @return {Object} The menu object.
		 *
		 * @description
		 * Creates a new menu item object.
		 */
		// Add menu item object
		this.addMenuItem = function(menuId, menuItemTitle, menuItemURL, menuItemType, menuItemUIRoute, isPublic, roles, position) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Push new menu item
			this.menus[menuId].items.push({
				title: menuItemTitle,
				link: menuItemURL,
				menuItemType: menuItemType || 'item',
				menuItemClass: menuItemType,
				uiRoute: menuItemUIRoute || ('/' + menuItemURL),
				isPublic: ((isPublic === null || typeof isPublic === 'undefined') ? this.menus[menuId].isPublic : isPublic),
				roles: ((roles === null || typeof roles === 'undefined') ? this.menus[menuId].roles : roles),
				position: position || 0,
				items: [],
				shouldRender: shouldRender
			});

			// Return the menu object
			return this.menus[menuId];
		};

		/**
		 * @ngdoc method
		 * @name core.service:Menus.addSubMenuItem
		 * @methodOf core.service:Menus
		 *
		 * @param {Number} menuId Indicates the menu identifier.
		 * @param {String} rootMenuItemURL Indicates the root menu item identifier.
		 * @param {String} menuItemTitle A String title for the menu item.
		 * @param {String} menuItemURL The path this menu item will link to.
		 * @param {String} [menuItemUIRoute=menuItemURL] The UIRoute value, which is used to define the URL scheme where this menu item is marked as active.
		 * @param {Boolean} isPublic Indicates whether a menu item should be displayed only to authenticated users.
		 * @param {Array.<String>} [roles=['user']] An array indicating the roles that are allowed to view this menu item.
		 * @param {Number} [position=0] -
		 * @return {Object} The menu object.
		 *
		 * @description
		 * Adds a submenu item to an existing item object.
		 */
		// Add submenu item object
		this.addSubMenuItem = function(menuId, rootMenuItemURL, menuItemTitle, menuItemURL, menuItemUIRoute, isPublic, roles, position) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Search for menu item
			for (var itemIndex in this.menus[menuId].items) {
				if (this.menus[menuId].items[itemIndex].link === rootMenuItemURL) {
					// Push new submenu item
					this.menus[menuId].items[itemIndex].items.push({
						title: menuItemTitle,
						link: menuItemURL,
						uiRoute: menuItemUIRoute || ('/' + menuItemURL),
						isPublic: ((isPublic === null || typeof isPublic === 'undefined') ? this.menus[menuId].items[itemIndex].isPublic : isPublic),
						roles: ((roles === null || typeof roles === 'undefined') ? this.menus[menuId].items[itemIndex].roles : roles),
						position: position || 0,
						shouldRender: shouldRender
					});
				}
			}

			// Return the menu object
			return this.menus[menuId];
		};

		/**
		 * @ngdoc method
		 * @name core.service:Menus.removeMenuItem
		 * @methodOf core.service:Menus
		 *
		 * @param {Number} menuId Indicates the menu identifier.
		 * @param {String} menuItemURL The path this menu item link to.
		 * @return {Object} The menu object.
		 *
		 * @description
		 * Remove specified menu item.
		 */
		// Remove existing menu object by menu id
		this.removeMenuItem = function(menuId, menuItemURL) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Search for menu item to remove
			for (var itemIndex in this.menus[menuId].items) {
				if (this.menus[menuId].items[itemIndex].link === menuItemURL) {
					this.menus[menuId].items.splice(itemIndex, 1);
				}
			}

			// Return the menu object
			return this.menus[menuId];
		};

		/**
	 	 * @ngdoc method
		 * @name core.service:Menus.removeSubMenuItem
		 * @methodOf core.service:Menus
		 *
		 * @param {Number} menuId Indicates the menu identifier.
		 * @param {String} submenuItemURL The path this submenu item link to.
		 * @return {Object} The menu object.
		 *
		 * @description
		 * Remove specified submenu item.
		 */
		// Remove existing menu object by menu id
		this.removeSubMenuItem = function(menuId, submenuItemURL) {
			// Validate that the menu exists
			this.validateMenuExistance(menuId);

			// Search for menu item to remove
			for (var itemIndex in this.menus[menuId].items) {
				for (var subitemIndex in this.menus[menuId].items[itemIndex].items) {
					if (this.menus[menuId].items[itemIndex].items[subitemIndex].link === submenuItemURL) {
						this.menus[menuId].items[itemIndex].items.splice(subitemIndex, 1);
					}
				}
			}

			// Return the menu object
			return this.menus[menuId];
		};

		//Adding the topbar menu
		this.addMenu('topbar');
	}
]);


text:
django-opendebates
=============

# Installation

Install python 2.7, virtualenv, postgres.

```
createdb opendebates
virtualenv --python=python2.7 ve
./ve/bin/pip install -r requirements.txt
./ve/bin/python opendebates/manage.py makemigrations registration
./ve/bin/python opendebates/manage.py syncdb
./ve/bin/python opendebates/manage.py load_zipcode_database ./zips.csv
```

Then you can start the development server:

```
./ve/bin/python opendebates/manage.py runserver 0.0.0.0:8000
```

## Site copy and content

We're relying on Django's i18n system for managing site copy.  An "English translation"
should be generated and used to provide installation-specific text, rather than updating
messages directly in the codebase.

To that end, all user-visible strings
in the Python and Django template files are wrapped in Django's i18n functions, and can
be collected into a .PO file with Django's built-in manage.py commands:

```
sudo apt-get install gettext
cd opendebates
../ve/bin/python manage.py makemessages -l en
```

This will give you an up-to-date file in
`opendebates/locale/en/LC_MESSAGES/django.po`
which you can edit with installation-appropriate text overrides.  To use it, then run:

```
../ve/bin/python manage.py compilemessages -l en
```

You can visit the view at `/test/` to confirm that text overrides are working properly.

## Deployment

There is a management command `manage.py update_trending_scores` --
in production, you'll want a cronjob
to run that every ten minutes (or more, or less) and may want to adjust
the "trending algorithm" which is expressed in SQL.

Deployment-specific environment variables can be stored in a `opendebates/.env` file.
See `opendebates/.env.sample` for relevant variables that you might want to set.

To install front-end packages and then collect static files:

```
./ve/bin/python /vagrant/opendebates/manage.py bower install
./ve/bin/python opendebates/manage.py collectstatic --noinput
```

Files will be collected into `opendebates/static/` -- in production mode (DJANGO_DEBUG=False)
all static files will be served from this directory.  Do not make edits to files directly
in `opendebates/static` -- instead, make edits to the source files (usually that's in opendebates/opendebates/static) and then re-run collectstatic
to update the served copies.

### Deployment on Heroku

Should be straightforward.  Only one catch -- run these as one command:

```
heroku run 'opendebates/manage.py makemigrations registration && opendebates/manage.py syncdb'
```

## Using Vagrant to create dev VM

### Installation
Install virtualbox. This will be fairly OS specific, but we recommend using some package manager (apt/aptitude, rpm, brew, etc). Unless you're on windows, in which case ???

Install vagrant: http://docs.vagrantup.com/v2/installation/index.html

Install vagrant plugin vagrant-ansible-local
   vagrant plugin install vagrant-ansible-local

### Setup
All you should need is `vagrant up`. This will bring up a VM with all of the appropriate setup/installation.

In order to get into the VM, you can use `vagrant ssh`. This will log you in as the 'vagrant' user, which has sudo priveleges. If you'd like root, you can use `sudo su -` which will log you in as root. All of the files in repo will be placed in /vagrant.

Therefore, in order to start the webserver, you can do the following:
```
/vagrant/ve/bin/python opendebates/manage.py runserver 0.0.0.0:8000
```

Similarly, to collect static files you can use:
```
/vagrant/ve/bin/python /vagrant/opendebates/manage.py bower install
/vagrant/ve/bin/python opendebates/manage.py collectstatic --noinput
```

HOWEVER, you don't actually need to ssh into the VM in order to run these commands!
```
vagrant ssh -c '/vagrant/ve/bin/python /vagrant/opendebates/manage.py runserver 0.0.0.0:8000'
```
or
```
vagrant ssh -c '/vagrant/ve/bin/python /vagrant/opendebates/manage.py bower install'
vagrant ssh -c '/vagrant/ve/bin/python /vagrant/opendebates/manage.py collectstatic --noinput'
```

You do not need to edit any of the server files in the virtual machine. It is perfectly fine to do all of your normal development work in this repo as you would normally.

### Create a Superuser
```
vagrant ssh -c '/vagrant/ve/bin/python /vagrant/opendebates/manage.py createsuperuser'
```
or if already inside the VM:
```
/vagrant/ve/bin/python manage.py createsuperuser
```

# Developing

## Front-End

One of the key principles we'd like to keep in mind across the site is separation of concerns.
We want to make each piece as much dedicated to one concern as possible.

One example where this is particularly relevant is javascript in django template files.
We want to keep javascript out of our django template files as much as possible.
There may be some situations in which it may be necessary to have some small amount of js, particularly if we need to pass python variables to the front end,
but if you find yourself doing any logic work in an inline javascript snippet in a django template file, please please put that into its own js file.

Similarly, we want to keep html templating out of any javascript files.
If you find yourself doing something like this:
```
$('.some-container').append('<h1>A header</h1><p>A message</p><p>Another message</p>');
```
Move that html into a javascript template!

### Structuring

We're using LESS compiled to CSS, Handlebars templates, and a handful of third-party libraries including jquery, lodash, momentjs, and bootstrap amongst some others.

We use django templates to hand off any server configs to javascript. We can do this by creating a javascript namespace which can be accessed from any other included JS files.

See /opendebates/templates/base.html for an example of how this works. Similarly, we can then access that namespace in any of our javascript files.
An example of loading that namespace is in /opendebates/static/js/base/helpers.js

With our javascript namespace, we can order all of our submodules, with their properties and functions, and any of their sub-modules.
Our namespace is `ODebates`, so we might have: `ODebates.paths`, `ODebates.configs`, `ODebates.login`, etc.

If we had a login page, we could have an object `ODebates.login`, which could then have a function `ODebates.login.init()`, an object `ODebates.login.helpers` for helpers that
are specific to that login page, `ODebates.login.handlers` for any handlers which are specific to that login page, etc.

### Bower

Bower is a front-end package manager:
http://bower.io/
https://github.com/nvbn/django-bower

It makes keeping track of front-end libraries/dependencies much simpler and less error-prone. Instead of randomly saving js or css files from 3rd party websites, bower lets us
keep all of our dependencies in one place, track versions and handle updates.

In our settings.py file, we have the following:
```
BOWER_INSTALLED_APPS = (
    'jquery',
    'lodash',
    'bootstrap',
    'moment',
    'handlebars',
)
```
These are bower packages with their names as they might appear here: http://bower.io/search/

If you'd like to add an additional package, search for it on bower, add a line here to our settings file, and then run:
`vagrant ssh -c '/vagrant/ve/bin/python /vagrant/opendebates/manage.py bower install'`
`vagrant ssh -c '/vagrant/ve/bin/python /vagrant/opendebates/manage.py collectstatic --noinput'`

In order to use one of these libraries in a django template, you can use the following:
```
  {% load static %}
  <script type="text/javascript" src='{% static 'jquery/dist/jquery.min.js' %}'></script>
  <script type="text/javascript" src='{% static 'handlebars/handlebars.min.js' %}'></script>
```

### LESS Stylesheets

We're using django-pipeline for LESS->CSS compilation.
http://django-pipeline.readthedocs.org/en/latest/index.html

In our settings.py file, there is a variable PIPELINE_CSS = {} which sets up the stylesheet pipeline.
An example might look like:
```
PIPELINE_CSS = {
    'base': {
        'source_filenames': (
          'less/base.less',
        ),
        'output_filename': 'css/base.css',
        'extra_context': {
            'media': 'screen,projection',
        },
    },
}
```

What this does is takes base.less, compiles it, minify/uglifies it (if not in DEBUG), and put the result into /static/css/base.css.
You can then load that stylesheet with the following:
```
  {% load pipeline %}
  {% stylesheet 'base' %}
```

Which leads us into
### Bootstrap

Ideally, we'd like to work with Bootstrap, not fight against it.
Bootstrap provides for the setting and accessing of a variety of LESS variables, which we would ideally match with our graphic design palette.

For example, in static/bower_components/bootstrap/less/modals.less, there is the following code:
```
// Actual modal
.modal-content {
  position: relative;
  background-color: @modal-content-bg;
  border: 1px solid @modal-content-fallback-border-color; //old browsers fallback (ie8 etc)
  border: 1px solid @modal-content-border-color;
  border-radius: @border-radius-large;
  .box-shadow(0 3px 9px rgba(0,0,0,.5));
  background-clip: padding-box;
  // Remove focus outline from opened modal
  outline: 0;
}
```
By setting `@modal-content-bg` in our variables.less file, we can change the modal background color in the most bootstrap-compatible (read: least hacky) way.

For any page that we'd like to import bootstrap styles (and our bootstrap variables), you can add the following to the top of the page:
`@import "bootstrap_import";`
### Handlebars

Similarly to how the css pipeline works, the javascript pipeline is set up like so:
```
PIPELINE_JS = {
    'base': {
        'source_filenames': (
          'js/base/*.js',
          'templates/base/*.handlebars',
        ),
        'output_filename': 'js/base.js',
    }
}
```

Then in the django template, we just need to call the following to load our compiled js
```
  {% load pipeline %}
  {% javascript 'base' %}
```

This will load any of the javascript files in static/js/base/ and will load and compile any handlebars templates in static/templates/base/

In our javascript, we could then access any of our named handlebars templates with `Handlebars.templates['template_name']` where template_name.handlebars
was a template file.

# Misc Vagrant+Ansible

## Useful Commands
see http://docs.vagrantup.com/v2/cli/index.html

`vagrant provision` - runs the ansible playbook set in the Vagrantfile
`vagrant ssh` - ssh into the VM
`vagrant reload` - reloads the Vagrantfile and makes any changes necessary. Adding `--provision` will run the ansible provisioner after reload

## Watch mode

The following will run the ansible provisioner in "watch" mode so that you can see if any changes would be made:
```
vagrant ssh -c "ansible-playbook /tmp/vagrant-ansible-local/django_server.yml --connection=local -i 'localhost,' --check --diff"
```


text:
Raphael.fn.pieChart = function (cx, cy, r, colors) {
    var paper = this,
        rad = Math.PI / 180,
        chart = this.set();
    function sector(cx, cy, r, startAngle, endAngle, params) {
        var x1 = cx + r * Math.cos(-startAngle * rad),
            x2 = cx + r * Math.cos(-endAngle * rad),
            y1 = cy + r * Math.sin(-startAngle * rad),
            y2 = cy + r * Math.sin(-endAngle * rad);
        return paper.path(["M", cx, cy, "L", x1, y1, "A", r, r, 0, +(endAngle - startAngle > 180), 0, x2, y2, "z"]).attr(params);
    }
    var angle = 0,
        total = 0,
        start = 0;
	for (var i = 0, ii = colors.length; i < ii; i++) {
		total += colors[i].size;
    }
    $.each(colors, function(i, item){
		var color = item.color,
			value = item.size,
			angleplus = 360 * value / total,
			popangle = angle + (angleplus / 2),
			ms = 500,
			delta = 30,
			bcolor = Raphael.hsb(start, 1, 1),
			p = sector(cx, cy, r, angle, angle + angleplus, {fill: color, stroke: "none", "stroke-width": 0});
		angle += angleplus;
		chart.push(p);
		start += .1;
    });
    return chart;
};

jQuery.fn.colorDisc = function(methodOrOptions){
	var methods = {
			init : function(colors){
				if(typeof colors == "undefined"){
					colors = ["red", "green", "blue"];
				}
				sectorColors = [];
				sectorSize = parseInt(360 / colors.length, 10);
				$.each(colors, function(i, value){
					sectorColors.push({
						size: sectorSize,
						color: value
					});
				});
				this.find("#colorDisc").remove();
				this.append("

");
				paper = Raphael(this.find('#colorDisc')[0], 400, 400).pieChart(200, 200, 200, sectorColors);
			},
			remove : function(){
				this.find("#colorDisc").remove();
			},
			speed : function(speed){
				var elem = this.find("#colorDisc");
				var currentSpeed 	= elem.css("-webkit-animation-duration");
				var newSpeed 		= parseFloat(currentSpeed) - 0.05;
				var newSpeed		= String(newSpeed).replace("-", "");
				if(speed != null){
					newSpeed = speed;
				}
				elem.removeClass("active");
				elem.attr("style", "-webkit-animation-duration:" + newSpeed + "s;" + "-moz-animation-duration: "+ newSpeed + "s;");
				setTimeout(function(){
					elem.addClass("active");
				}, 10);
			}
	};
	if(typeof methodOrOptions == "object" || !methodOrOptions){
		return methods.init.apply( this, arguments );
	}else if(typeof methodOrOptions == "string" && methods[ methodOrOptions ]){
		return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
	}
};


text:
The tracking issue for this feature is: [#58328]

------

The `#[ffi_const]` attribute applies clang's `const` attribute to foreign
functions declarations.

That is, `#[ffi_const]` functions shall have no effects except for its return
value, which can only depend on the values of the function parameters, and is
not affected by changes to the observable state of the program.

Applying the `#[ffi_const]` attribute to a function that violates these
requirements is undefined behaviour.

This attribute enables Rust to perform common optimizations, like sub-expression
elimination, and it can avoid emitting some calls in repeated invocations of the
function with the same argument values regardless of other operations being
performed in between these functions calls (as opposed to `#[ffi_pure]`
functions).

## Pitfalls

A `#[ffi_const]` function can only read global memory that would not affect
its return value for the whole execution of the program (e.g. immutable global
memory). `#[ffi_const]` functions are referentially-transparent and therefore
more strict than `#[ffi_pure]` functions.

A common pitfall involves applying the `#[ffi_const]` attribute to a
function that reads memory through pointer arguments which do not necessarily
point to immutable global memory.

A `#[ffi_const]` function that returns unit has no effect on the abstract
machine's state, and a `#[ffi_const]` function cannot be `#[ffi_pure]`.

A `#[ffi_const]` function must not diverge, neither via a side effect (e.g. a
call to `abort`) nor by infinite loops.

When translating C headers to Rust FFI, it is worth verifying for which targets
the `const` attribute is enabled in those headers, and using the appropriate
`cfg` macros in the Rust side to match those definitions. While the semantics of
`const` are implemented identically by many C and C++ compilers, e.g., clang,
[GCC], [ARM C/C++ compiler], [IBM ILE C/C++], etc. they are not necessarily
implemented in this way on all of them. It is therefore also worth verifying
that the semantics of the C toolchain used to compile the binary being linked
against are compatible with those of the `#[ffi_const]`.

[#58328]: https://github.com/rust-lang/rust/issues/58328
[ARM C/C++ compiler]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0491c/Cacgigch.html
[GCC]: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#index-const-function-attribute
[IBM ILE C/C++]: https://www.ibm.com/support/knowledgecenter/fr/ssw_ibm_i_71/rzarg/fn_attrib_const.htm


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $searchModel backend\models\SubsubSearchModel */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Subsub Models');
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a(Yii::t('app', 'Create Subsub Model'), ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            // ['class' => 'yii\grid\SerialColumn'],

            'id',
            'under_subcategory_name_am',
            'name_ru',
            'name_en',
            [
                'attribute' => 'subcategory_id',
                'value' => 'idSubcategory2.subcategory_name_am',
                'filter' => $arraySubcategory,
            ],
            // 'subcategory_id',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


text:
from pants.goal.products import UnionProducts
from pants.testutil.test_base import TestBase
from pants.util.ordered_set import OrderedSet

class UnionProductsTest(TestBase):
    def setUp(self):
        super().setUp()
        self.products = UnionProducts()

    def test_get_for_target(self):
        c = self.make_target("c")
        b = self.make_target("b", dependencies=[c])
        a = self.make_target("a", dependencies=[b, c])
        self.products.add_for_target(a, [1])
        self.products.add_for_target(b, [2])
        self.products.add_for_target(c, [3])

        self.assertEqual(self.products.get_for_targets(a.closure(bfs=True)), OrderedSet([1, 2, 3]))
        self.assertEqual(self.products.get_for_targets(b.closure(bfs=True)), OrderedSet([2, 3]))
        self.assertEqual(self.products.get_for_targets(c.closure(bfs=True)), OrderedSet([3]))
        self.assertEqual(self.products.get_for_target(a), OrderedSet([1]))
        self.assertEqual(self.products.get_for_target(b), OrderedSet([2]))
        self.assertEqual(self.products.get_for_target(c), OrderedSet([3]))

    def test_get_product_target_mappings_for_targets(self):
        b = self.make_target("b")
        a = self.make_target("a", dependencies=[b])
        self.products.add_for_target(a, [1, 3])
        self.products.add_for_target(b, [2, 3])

        self.assertEqual(self.products.get_for_targets(a.closure(bfs=True)), OrderedSet([1, 3, 2]))
        self.assertEqual(self.products.get_for_targets(b.closure(bfs=True)), OrderedSet([2, 3]))

        self.assertEqual(
            self.products.get_product_target_mappings_for_targets(a.closure(bfs=True)),
            [(1, a), (3, a), (2, b), (3, b)],
        )

    def test_copy(self):
        c = self.make_target("c")
        b = self.make_target("b", dependencies=[c])
        a = self.make_target("a", dependencies=[b, c])
        self.products.add_for_target(a, [1])
        self.products.add_for_target(b, [2])

        copied = self.products.copy()

        self.assertEqual(self.products.get_for_targets(a.closure(bfs=True)), OrderedSet([1, 2]))
        self.assertEqual(self.products.get_for_targets(b.closure(bfs=True)), OrderedSet([2]))
        self.assertEqual(copied.get_for_targets(a.closure(bfs=True)), OrderedSet([1, 2]))
        self.assertEqual(copied.get_for_targets(b.closure(bfs=True)), OrderedSet([2]))

        copied.add_for_target(c, [3])

        self.assertEqual(self.products.get_for_targets(a.closure(bfs=True)), OrderedSet([1, 2]))
        self.assertEqual(self.products.get_for_targets(b.closure(bfs=True)), OrderedSet([2]))
        self.assertEqual(self.products.get_for_targets(c.closure(bfs=True)), OrderedSet())
        self.assertEqual(copied.get_for_targets(a.closure(bfs=True)), OrderedSet([1, 2, 3]))
        self.assertEqual(copied.get_for_targets(b.closure(bfs=True)), OrderedSet([2, 3]))
        self.assertEqual(copied.get_for_targets(c.closure(bfs=True)), OrderedSet([3]))

    def test_remove_for_target(self):
        c = self.make_target("c")
        b = self.make_target("b", dependencies=[c])
        a = self.make_target("a", dependencies=[b, c])
        self.products.add_for_target(a, [1])
        self.products.add_for_target(b, [2])
        self.products.add_for_target(c, [3])

        self.products.remove_for_target(a, [1])

        self.assertEqual(self.products.get_for_targets(a.closure(bfs=True)), OrderedSet([2, 3]))
        self.assertEqual(self.products.get_for_targets(b.closure(bfs=True)), OrderedSet([2, 3]))
        self.assertEqual(self.products.get_for_targets(c.closure(bfs=True)), OrderedSet([3]))

    def test_empty_products(self):
        c = self.make_target("c")
        self.assertFalse(self.products.get_for_target(c))

    def test_non_empty_products(self):
        c = self.make_target("c")
        self.products.add_for_target(c, [3])
        self.assertTrue(self.products.get_for_target(c))

    def test_target_for_product_existing_product(self):
        c = self.make_target("c")
        self.products.add_for_target(c, [3])

        found_target = self.products.target_for_product(3)

        self.assertEqual(c, found_target)

    def test_target_for_product_nonexistent_product(self):
        c = self.make_target("c")
        self.products.add_for_target(c, [3])

        found_target = self.products.target_for_product(1000)

        self.assertIsNone(found_target)


text:
package main

import (
	"errors"
	"fmt"
	"github.com/dgruber/ubercluster/pkg/types"
	dtypes "github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/container"
)

// https://github.com/moby/moby/blob/master/api/types/container/config.go
func jobTemplateToContainerConfig(jt types.JobTemplate) (*container.Config, *container.HostConfig, error) {
	var cc container.Config
	var hc container.HostConfig

	cc.Image = jt.JobCategory
	cc.WorkingDir = jt.WorkingDirectory

	if len(jt.CandidateMachines) == 1 {
		cc.Hostname = jt.CandidateMachines[0]
	}

	if jt.RemoteCommand != "#nocommand#" {
		cmdSlice := []string{jt.RemoteCommand}
		cmdSlice = append(cmdSlice, jt.Args...)
		cc.Cmd = cmdSlice
	}

	hc.PublishAllPorts = true

	return &cc, &hc, nil
}

func pullImage(client DockerInterface, image string) error {
	_, err := client.ImagePull(image, dtypes.ImagePullOptions{})
	if err != nil {
		return fmt.Errorf("Error during pulling image: %s", err.Error())
	}
	return nil
}

func imageExists(client DockerInterface, image string) (bool, error) {
	summary, err := client.ImageList(dtypes.ImageListOptions{})
	if err != nil {
		return false, fmt.Errorf("Error during listing images: %s", summary)
	}
	for _, i := range summary {
		for _, tag := range i.RepoTags {
			if tag == image {
				return true, nil
			}
		}
	}
	return false, nil
}

func (p *Proxy) runTask(jt types.JobTemplate) (string, error) {
	if jt.JobCategory == "" {
		return "", errors.New("No job category (app) requested.")
	}

	cc, hc, err := jobTemplateToContainerConfig(jt)
	if err != nil {
		return "", fmt.Errorf("Can not run task (%s).", err.Error())
	}

	if p.config.AllowImagePull {
		exists, _ := imageExists(p.client, jt.JobCategory)
		if exists == false {
			fmt.Printf("Pulling image %s\n", jt.JobCategory)
			errPull := pullImage(p.client, jt.JobCategory)
			if errPull != nil {
				return "", errPull
			}
		}
	}

	resp, err := p.client.ContainerCreate(cc, hc, nil, "")
	if err != nil {
		return "", fmt.Errorf("Error during container creation: %s", err.Error())
	}

	err = p.client.ContainerStart(resp.ID, dtypes.ContainerStartOptions{})
	if err != nil {
		return "", fmt.Errorf("Error during staring container %s: %s", resp.ID, err.Error())
	}
	return resp.ID, nil
}


text:
import math
"""
    This prediction models need a minimum range of input values of 15-20 to be able to make future predictions.
"""

class Prediction_Models:

    def __init__(self, logger):
        self.logger = logger

    def average(self, x):
        assert len(x) > 0
        return float(sum(x)) / len(x)

    def correlation(self, x, y):
        assert len(x) == len(y)
        n = len(x)
        assert n > 0
        avg_x = self.average(x)
        avg_y = self.average(y)
        diffprod = 0
        xdiff2 = 0
        ydiff2 = 0
        for idx in range(n):
            xdiff = x[idx] - avg_x
            ydiff = y[idx] - avg_y
            diffprod += xdiff * ydiff
            xdiff2 += xdiff * xdiff
            ydiff2 += ydiff * ydiff

        return diffprod / math.sqrt(xdiff2 * ydiff2)

    def linear_regression(self, php_resp_time, num_predictions):
        forecast = []

        return forecast

    def vector_auto_regression(self, php_resp_time, cpu_load, num_predictions):
        # year = 1921     # year to be mapped with the values
        forecast = []   # predict array

        return forecast

    def linear_regression_ols(self, php_resp_time, num_predictions):
        forecast = []

        return forecast

    def multiple_regression(self, php_resp_time, req_rate, cpu_usage, num_predictions):
        forecast = []

        return forecast

    def auto_regression(self, php_resp_time, num_predictions):
        forecast = []

        return forecast

    def arma(self, php_resp_time, num_predictions):
        forecast = []

        return forecast

    def holtwinters(self, y, alpha, beta, gamma, c, debug=False):
        """
        y - time series data.
        alpha , beta, gamma - exponential smoothing coefficients
                                      for level, trend, seasonal components.
        c -  extrapolated future data points.
              4 quarterly
              7 weekly.
              12 monthly

        The length of y must be a an integer multiple  (> 2) of c.
        """
        # Compute initial b and intercept using the first two complete c periods.

        forecast = []

        return forecast

    def exponential_smoothing(self, php_resp_time, num_predictions):
        forecast = []

        return forecast


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!--
        List of Book Titles
    -->
    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.iosdevlog.a238listfragment.BookListFragment"
        android:id="@+id/fragmentTitles"
        tools:layout="@layout/fragment_book_list"/>
    <!--
        Description of selected book
    -->

    <fragment
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:name="com.iosdevlog.a238listfragment.BookDescFragment"
        android:id="@+id/fragmentDescription"
        tools:layout="@layout/fragment_book_desc"/>

</LinearLayout>


text:
#ifndef PHONON_MMF_VIDEOWIDGET_H
#define PHONON_MMF_VIDEOWIDGET_H

#include "abstractvideooutput.h"
#include "mmf_medianode.h"

#include <QtGui/QWidget>
#include <phonon/videowidget.h>
#include <phonon/videowidgetinterface.h>

QT_BEGIN_NAMESPACE

namespace Phonon
{
namespace MMF
{
#ifndef PHONON_MMF_VIDEO_SURFACES
class AncestorMoveMonitor;
#endif

class VideoWidget       :   public MediaNode
                        ,   public Phonon::VideoWidgetInterface
{
    Q_OBJECT
    Q_INTERFACES(Phonon::VideoWidgetInterface)

public:
    VideoWidget(QWidget* parent);
    ~VideoWidget();

#ifndef PHONON_MMF_VIDEO_SURFACES
    void setAncestorMoveMonitor(AncestorMoveMonitor *ancestorMoveMonitor);
#endif

    // VideoWidgetInterface
    virtual Phonon::VideoWidget::AspectRatio aspectRatio() const;
    virtual void setAspectRatio(Phonon::VideoWidget::AspectRatio aspectRatio);
    virtual qreal brightness() const;
    virtual void setBrightness(qreal brightness);
    virtual Phonon::VideoWidget::ScaleMode scaleMode() const;
    virtual void setScaleMode(Phonon::VideoWidget::ScaleMode scaleMode);
    virtual qreal contrast() const;
    virtual void setContrast(qreal constrast);
    virtual qreal hue() const;
    virtual void setHue(qreal hue);
    virtual qreal saturation() const;
    virtual void setSaturation(qreal saturation);
    virtual QWidget *widget();

protected:
    // MediaNode
    void connectMediaObject(MediaObject *mediaObject);
    void disconnectMediaObject(MediaObject *mediaObject);

private:
    QScopedPointer<AbstractVideoOutput>     m_videoOutput;

    qreal                                   m_brightness;
    qreal                                   m_contrast;
    qreal                                   m_hue;
    qreal                                   m_saturation;

};
}
}

QT_END_NAMESPACE

#endif


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Large Promo</title>
  <link href="http://fonts.googleapis.com/css?family=Patua+One" rel="stylesheet">
  <link href="../css/typography.css" rel="stylesheet">
  <link href="../css/promos.css" rel="stylesheet">

Large Promo

Product

Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum, Lorem Ipsum.


text:
name             "disks"
maintainer       "Travis CI Development Team"
license          "Apache v2.0"
description      "Installs/Configures disks"


text:
<!DOCTYPE html>

    <meta charset="utf-8">
      <title>The future of online is offline - Matt Andrews</title>
      <meta name="description" content="A presentation about the challenges of building single page apps">
      <meta name="author" content="Matt Andrews">
      <meta name="apple-mobile-web-app-capable" content="yes" />
      <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="css/reveal.min.css">
      <link rel="stylesheet" href="css/theme/ftlabs.css" id="theme">
      <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/3.2.1/css/font-awesome.min.css">

      <link rel="stylesheet" href="lib/css/zenburn.css">

The future of online is offline

Building modern web applications

              by Matt Andrews, FT Labs (mattandre.ws / @andrewsmatt)

              Good hacks and great performance, smart multivariate responsiveness, and web apps that deserve far more than the lowly title of 'page'.

              <video data-autoplay src="content/offline-demo.mov" width='1500' height='1000' />

FT App History

FT originally built native apps for iPhone & iPad

Early 2011: Apple launch App Store Subscriptions, FT launch HTML5 web app

August 2011: FT pulls native apps from iTunes

Now: iOS, Android, Windows, all major modern desktop browsers

Summary

No review / approval process & automatic updates

Instant install

One app, many platforms

Direct relationship with readers

Apple don't take 30% cut

Native-ish: homescreen icon, swiping, offline, fast (enough)

The catch?

              They're really difficult to make well :(

Offline challenges

Caching

Backwards compatibility

As a web developer it's really easy to forget how powerful the browser actually is - and how much work it does for you.  Unlike traditional software development when you make a webpage you normally don't need to worry about memory management or garbage collection or backwards compatability - even if you do break something, most mistakes can be fixed by the user simply clicking refresh.

Caching for offline

Naive approach

if device is online, load from the web

else load from cache

Browser even has handy method for checking connection: navigator.onLine

What does online mean anyway?

              At best, that the device is connected to a wired or wireless router

navigator.onLine doesn't work

Fun fact:

On Desktop Firefox navigator.onLine
is only false when File » Work Offline is ticked

              Who even uses that anyway?

So how do we know if we're online?

You don't need to know

Live with uncertainty

Always assume the device is offline, load from cache

Then try the network for new data in the background

(Also stops slow connections ruining your site)

For a page to load offline,
you need to use the HTML5 Application Cache

Manifest looks like this:

CACHE MANIFEST
# 2014-05 v1
/lib/fonts/BentonSansBold.ttf
/lib/img/startupscreen/splash-logo.png

NETWORK
*

And to use it you need to add an attribute to <html>

<DOCTYPE html>
<html manifest="mywebapp.manifest">

Sadly, it's not quite that easy

Leaks storage (workarounds exist)

Inflexible and unintuitive API

Makes browser susceptible to scary man in the middle attacks… whether you use it or not

Will soon be replaced by Service Worker

              Technically already available in Canary, behind a flag - but you can only install, uninstall and send messages to it right now - all the cool offline stuff not ready yet

                Even Chrome dev relations people will tell you the Application Cache is a douchebag.

But…

It does work

across 80%+* of browsers (iOS, Android, Chrome, Opera, IE10+)

Only Chrome and Firefox have committed to building Service Worker implementations

* http://caniuse.com/offline-apps

AppCache OK

Yes it's ugly for developers

But it enables amazing experiences for users

There are use cases where it works well

Unfortunately, building a newspaper app isn't one of them

Service Workers

The spec says:

Service Workers are a new browser feature that provide event-driven scripts that run independently of web pages […] They have access to domain-wide events such as network fetches. ServiceWorkers also have scriptable caches. Along with the ability to respond to network requests from certain web pages via script, this provides a way for applications to "go offline".

              https://github.com/slightlyoff/ServiceWorker/

A Service Worker:

is a javascript file that you write and can be 'installed' onto your website

lets you to do things with requests between browser and server

has special caches that you can reliably store content in

More code than AppCache - but you can read what it does!

// Install process
this.oninstalled = function(event) {
  var myCache = new Cache(
    '/lib/fonts/BentonSansBold.ttf',
    '/lib/img/startupscreen/splash-logo.png'
  );

  // The coast is only clear when all the resources are ready.
  event.waitUntil(myCache.ready());

  // Add Cache to the global so it can be used later during onfetch
  caches.set("my-cache", myCache);
};

// (scroll for more)

// Request handling
this.addEventListener("fetch", function(e) {
  e.respondWith(caches.match(e.request));
});

Backwards compatibility

Unlike native apps,
offline websites only download updates

when they're open

and only apply those updates on refresh

              And some users get stuck on old versions - we're still detecting API calls
from Javascript that hasn't been served for a year

App start events split by version of client side code

Guidance

Expect some users to get stuck, add tools to help users recover their apps

Test different versions of client side code against different backend versions

Add monitoring

Add buttons to recovery tools that appear after a CSS animation if JS fails

Version everything  - API endpoints, data formats

Client side database migrations are painful.  Store data in its simplest form (JSON better than HTML)

Summary

Offline websites are possible today, with enough persistence

… but expect some users to get stuck

Service Worker will make things better (but only on Chrome & Firefox)

Test, measure and monitor everything

Questions?

@andrewsmatt

Offline Web Workshop

I'm running a workshop at SmashingConf on
the Offline Web in September in Freiberg

Email: matthew.andrews@ft.com

Our open source: github.com/ftlabs

Jobs: labs.ft.com/jobs


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Bogus;

namespace PaginationLogic
{
    public class PaginationLogic
    {
        ItemDao _itemDao;

        public PaginationLogic()
        {
            _itemDao = new ItemDao();
        }

        public PaginationResults Paginate(int ps, int rp)
        {
            var _logger = LoggingFactory.Instance.GetMagicLogger();
            _logger.StartLogging();
            var elements = _itemDao.GetItems(GetFilters());
            int firstPage;
            int lastpage;
            int previousPage;
            int nextPage;

            if (elements != null && elements.Count > 0)
            {
                firstPage = 1;
            }
            else
            {
                firstPage = 0;
            }

            if (elements != null && elements.Count > 0 && ps > 0)
            {
                var total = elements.Count + ps;

                lastpage = total - 1 / ps;
            }
            else
            {
                lastpage = 0;
            }

            if (elements != null)
            {
                if (rp > 1 && elements.Count > 0)
                {
                    previousPage = rp - 1;
                }
                else
                {
                    previousPage = -1;
                }
            }
            else
            {
                previousPage = 0;
            }

            if (elements != null)
            {
                if (rp * ps <= elements.Count - 1)
                {
                    nextPage = rp + 1;
                }
                else
                {
                    nextPage = -1;
                }
            }
            else
            {
                nextPage = 0;
            }

            var results = new PaginationResults();
            results.FirstPage = firstPage;
            results.LastPage = lastpage;
            results.PreviousPage = previousPage;
            results.NextPage = nextPage;
            _logger.EndLogging();
            return results;
        }

        public static Filter GetFilters()
        {
            return new Filter
            {
                Availibility = true,
                RequiredQuality = ItemQuality.High
            };
        }
    }

    public class Filter
    {
        public string Name { get; set; }
        public ItemQuality RequiredQuality { get; set; }
        public bool Availibility { get; set; }
    }

    public class PaginationResults
    {
        public int FirstPage { get; set; }
        public int LastPage { get; set; }
        public int PreviousPage { get; set; }
        public int NextPage { get; set; }
        //public IEnumerable<Item> PageItems { get; set; }
    }

    public class ItemDao
    {
        public IList<Item> GetItems(Filter filter)
        {
            var quantity = new Random().Next(1, 50);
            var itemId = 1;
            var itemRules = new Faker<Item>()
                .RuleFor(a => a.ItemId, f => itemId++)
                .RuleFor(a => a.ItemName, f => f.Commerce.Product())
                .RuleFor(a => a.Available, f => f.PickRandom<bool>())
                .RuleFor(a => a.ItemQuality, f => f.PickRandom<ItemQuality>());
            return itemRules.Generate(quantity).ToList();
        }
    }

    public class Item
    {
        public int ItemId { get; set; }
        public string ItemName { get; set; }
        public ItemQuality ItemQuality { get; set; }
        public bool Available { get; set; }
    }

    public enum ItemQuality
    {
        Basic,
        Medium,
        High
    }
}


text:
using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class ShadowReceiver : MonoBehaviour {

	public GameObject plane;
	// Use this for initialization
	void Start () {

	}

	// Update is called once per frame
	void Update () {
		if (plane != null) {
			 GetComponent<Renderer>().sharedMaterial.SetMatrix("_World2Receiver", plane.GetComponent<Renderer>().worldToLocalMatrix);
		}
	}
}


text:
+

Configuracion de Modulos

Panel de Control

                     <button class="btn btn-default" type="button" onclick="location.href='index.php?menu=configuracion'">Regresar</button>

                  <?

                    if(isset($_GET['id']))
                    {
	                    $sql_query="SELECT * FROM permisologia WHERE id=".$_GET['id'];
	                    $result_set=query($sql_query);
	                    $fetched_row=fetch_array($result_set);
                    }
                 ?>

                <form method="post" action="index.php?menu=configuracion">

                    <input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">

                            Modulo

                            <select name="id_modulo">
                                <?  $id_perfil = $fetched_row['id_modulo'];
                                    $result=query("SELECT * FROM modulos");
                                    while ($row = fetch_array($result)){
                                    // hacemos uso de operador ternario para conocer el campo que se encuentra seleccionado
                                        echo '<option value="'.$row['id_modulo'].'" '.(($row['id_modulo'] == $id_modulo)? 'selected' : '').'>'.$row['nombre_vista'].'</option>';
                                    }?>
                            </select>

                            Tipo de Usuario

                            <select name="id_perfil">
                                <?  $id_perfil = $fetched_row['id_perfil'];
                                    $result=query("SELECT * FROM perfil");
                                    while ($row = fetch_array($result)){
                                    // hacemos uso de operador ternario para conocer el campo que se encuentra seleccionado
                                        echo '<option value="'.$row['id_perfil'].'" '.(($row['id_perfil'] == $id_perfil)? 'selected' : '').'>'.$row['descripcion'].'</option>';
                                    }?>
                            </select>

                                <input type="checkbox" name="bloquear_leer" <?=$fetched_row['bloquear_leer']=='1'? 'checked':'' ?>/>Bloquear Lectura
                                <input type="checkbox" name="bloquear_crear" <?=$fetched_row['bloquear_crear']=='1'? 'checked':'' ?>/>Bloquear Crear
                                <input type="checkbox" name="bloquear_editar" <?=$fetched_row['bloquear_editar']=='1'? 'checked':'' ?>/>Bloquear Editar
                                <input type="checkbox" name="bloquear_eliminar" <?=$fetched_row['bloquear_eliminar']=='1'? 'checked':'' ?>/>Bloquear Eliminar

                    <button type="submit" name="update" class="btn btn-primary">Update</button>

                </form>


text:
package org.motechproject.nms.rejectionhandler.domain;

import org.joda.time.DateTime;
import org.motechproject.mds.annotations.Entity;
import org.motechproject.mds.annotations.Field;

import javax.jdo.annotations.Unique;

@Entity(tableName = "nms_village_health_sub_facility_rejects")
@Unique(name = "UNIQUE_VILLAGE_HEALTH_SUB_FACILITY", members = { "villageCode", "healthSubFacilityCode" })
public class VillageHealthSubFacilityImportRejection {
    @Field
    private Long stateId;

    @Field
    private Long districtCode;

    @Field
    private Long villageCode;

    @Field
    private Long healthSubFacilityCode;

    @Field
    private DateTime execDate;

    @Field
    private Boolean accepted;

    @Field
    private String rejectionReason;

    public Long getStateId() {    return stateId;    }

    public void setStateId(Long stateId) {     this.stateId = stateId;    }

    public Long getDistrictCode() {    return districtCode;   }

    public void setDistrictCode(Long districtCode) {    this.districtCode = districtCode;    }

    public Long getVillageCode() {    return villageCode;    }

    public void setVillageCode(Long villageCode) {     this.villageCode = villageCode;    }

    public Long getHealthSubFacilityCode() {     return healthSubFacilityCode;   }

    public void setHealthSubFacilityCode(Long healthSubFacilityCode) {     this.healthSubFacilityCode = healthSubFacilityCode;    }

    public DateTime getExecDate() {     return execDate;    }

    public void setExecDate(DateTime execDate) {    this.execDate = execDate;   }

    public Boolean getAccepted() {     return accepted;    }

    public void setAccepted(Boolean accepted) {    this.accepted = accepted;   }

    public String getRejectionReason() {     return rejectionReason;   }

    public void setRejectionReason(String rejectionReason) {   this.rejectionReason = rejectionReason;    }

    public VillageHealthSubFacilityImportRejection() {
    }

    public VillageHealthSubFacilityImportRejection(Long stateId, Long districtCode, Long villageCode, Long healthSubFacilityCode, Boolean accepted, String rejectionReason) {
        this.stateId = stateId;
        this.districtCode = districtCode;
        this.villageCode = villageCode;
        this.healthSubFacilityCode = healthSubFacilityCode;
        this.accepted = accepted;
        this.rejectionReason = rejectionReason;
    }
}


text:
class PhoneNumber < ActiveRecord::Base
  TYPES = %w(fax mobile phone private secretary skype work dect)

  belongs_to :person

  has_paper_trail meta: { associated_id: :person_id, associated_type: "Person" }

  def to_s
    "Phone number"
  end
end


text:
package io.lumify.core.model.properties.types;

import io.lumify.core.model.PropertyJustificationMetadata;
import org.json.JSONObject;

public class PropertyJustificationMetadataLumifyProperty extends LumifyProperty<PropertyJustificationMetadata, String> {
    public PropertyJustificationMetadataLumifyProperty(final String key) {
        super(key);
    }

    @Override
    public String wrap(PropertyJustificationMetadata value) {
        return value.toJson().toString();
    }

    @Override
    public PropertyJustificationMetadata unwrap(Object value) {
        if (value == null) {
            return null;
        }
        return new PropertyJustificationMetadata(new JSONObject(value.toString()));
    }
}


text:
<?php

namespace frontend\assets;

use yii\web\AssetBundle;

/**
 * @author Cosmo <daixianceng@gmail.com>
 */
class CsshakeAsset extends AssetBundle
{
    // The files are not web directory accessible, therefore we need
    // to specify the sourcePath property. Notice the @vendor alias used.
    public $sourcePath = '@vendor/csshake/css';
    public $css = [
        'csshake.min.css',
    ];
}


text:
package io.mewbase.processors;

import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Before;
import org.junit.Test;

public class ConsumeMewbaseEventsTest {

    private TestRunner testRunner;

    @Before
    public void init() {
        testRunner = TestRunners.newTestRunner(ConsumeMewbaseEvents.class);
    }

    @Test
    public void testProcessor() {

    }

}


text: .. automodule:: mpi_array


text:
package eu.yals.exception;

import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang3.StringUtils;

/**
 * {@link RuntimeException} with message as technical message and custom message as message for user.
 *
 * @since 2.7
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class YalsException extends RuntimeException {

    private String messageToUser;

    /**
     * Creates empty exception without message to user.
     */
    public YalsException() {
    }

    /**
     * Creates exception wit message to user.
     *
     * @param message string with user-friendly message
     */
    public YalsException(final String message) {
        super(message);
    }

    /**
     * Checks if {@link YalsException} object has not-empty {@link #messageToUser}.
     *
     * @return true - when {@link #messageToUser} contains non-empty string, false - elsewhere
     */
    public boolean hasMessageToUser() {
        return StringUtils.isNotBlank(messageToUser);
    }
}


text:
package com.exxeta.iss.sonar.esql.tree.impl.declaration;

import java.util.Iterator;

import com.google.common.collect.Iterators;

import com.exxeta.iss.sonar.esql.api.tree.DecimalDataTypeTree;
import com.exxeta.iss.sonar.esql.api.tree.Tree;
import com.exxeta.iss.sonar.esql.api.visitors.DoubleDispatchVisitor;
import com.exxeta.iss.sonar.esql.tree.impl.EsqlTree;
import com.exxeta.iss.sonar.esql.tree.impl.lexical.InternalSyntaxToken;

public class DecimalDataTypeTreeImpl extends EsqlTree implements DecimalDataTypeTree{

	InternalSyntaxToken decimalKeyword;
	InternalSyntaxToken openParen;
	InternalSyntaxToken precision;
	InternalSyntaxToken comma;
	InternalSyntaxToken scale;
	InternalSyntaxToken closeParen;
	public DecimalDataTypeTreeImpl(InternalSyntaxToken openParen, InternalSyntaxToken precision,
			InternalSyntaxToken comma, InternalSyntaxToken scale, InternalSyntaxToken closeParen) {
		super();
		this.openParen = openParen;
		this.precision = precision;
		this.comma = comma;
		this.scale = scale;
		this.closeParen = closeParen;
	}

	public DecimalDataTypeTreeImpl(InternalSyntaxToken decimalKeyword) {
		super();
		this.decimalKeyword = decimalKeyword;
	}

	public DecimalDataTypeTreeImpl complete(InternalSyntaxToken decimalKeyword){
		this.decimalKeyword=decimalKeyword;
		return this;
	}

	@Override
	public InternalSyntaxToken decimalKeyword() {
		return decimalKeyword;
	}

	@Override
	public InternalSyntaxToken openParen() {
		return openParen;
	}

	@Override
	public InternalSyntaxToken precision() {
		return precision;
	}

	@Override
	public InternalSyntaxToken comma() {
		return comma;
	}

	@Override
	public InternalSyntaxToken scale() {
		return scale;
	}

	@Override
	public InternalSyntaxToken closeParen() {
		return closeParen;
	}

	@Override
	public void accept(DoubleDispatchVisitor visitor) {
		visitor.visitDecimalDataType(this);

	}

	@Override
	public Kind getKind() {
		return Kind.DECIMAL_DATA_TYPE;
	}

	@Override
	public Iterator<Tree> childrenIterator() {
		return Iterators.forArray(decimalKeyword, openParen, precision, comma, scale, closeParen);
	}

}


text:
namespace java.net
{
    internal partial class TwoStacksPlainDatagramSocketImpl : AbstractPlainDatagramSocketImpl
    {
        public TwoStacksPlainDatagramSocketImpl(){}
        protected override void bind(int prm1, InetAddress prm2){}
        protected override void bind0(int prm1, InetAddress prm2){}
        protected virtual void bind0(int prm1, InetAddress prm2, bool prm3){}
        protected override void close(){}
        protected override void connect0(InetAddress prm1, int prm2){}
        protected override void create(){}
        protected override void datagramSocketClose(){}
        protected override void datagramSocketCreate(){}
        protected override void disconnect0(int prm1){}
        public override global::System.Object getOption(int prm1){return default(global::System.Object);}
        protected override void join(InetAddress prm1, NetworkInterface prm2){}
        protected override void leave(InetAddress prm1, NetworkInterface prm2){}
        protected override int peek(InetAddress prm1){return default(int);}
        protected override int peekData(DatagramPacket prm1){return default(int);}
        protected override void receive(DatagramPacket prm1){}
        protected override void receive0(DatagramPacket prm1){}
        protected override void send(DatagramPacket prm1){}
        protected override void setTimeToLive(int prm1){}
        protected override void setTTL(byte prm1){}
        protected override global::System.Object socketGetOption(int prm1){return default(global::System.Object);}
        protected virtual void socketNativeSetOption(int prm1, global::System.Object prm2){}
        protected override void socketSetOption(int prm1, global::System.Object prm2){}
        public bool  IsClosed { get; private set;}
        public int  TimeToLive { get; set;}
        public byte  TTL { get; set;}
    }
}


text:
package nl.beehivejava.scriptj.util.builder;

import nl.beehivejava.scriptj.script.ScriptInformation;
import nl.beehivejava.scriptj.script.ScriptType;

/**
 * @author Lesley
 */
public final class ScriptInformationBuilder {

    String name;
    ScriptType type;

    ScriptInformationBuilder() {
        name = "name";
        type = ScriptType.JAVASCRIPT;
    }

    public ScriptInformationBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public ScriptInformationBuilder withScriptType(ScriptType type) {
        this.type = type;
        return this;
    }

    public ScriptInformation build() {
        return new ScriptInformation(name, type);
    }

}


text:
using FlatMate.Module.Account.DataAccess;
using FlatMate.Module.Common;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace FlatMate.Module.Account
{
    public class Module : FlatMateModule
    {
        public override void ConfigureServices(IServiceCollection service, IConfiguration configuration)
        {
            base.ConfigureServices(service, configuration);
            service.AddDbContext<AccountDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("FlatMate")));
        }
    }
}


text:
package weixin.popular.bean.paymch;

public class PapayEntrustweb {

	private String mch_id;

	private String appid;

	private String plan_id;

	private String contract_code;

	private String request_serial;

	private String contract_display_account;

	private String notify_url;

	private String version;

	private String timestamp;

	//以下字段为非必填项风控参数,建议商户填写,提高风险控制能力

	private String clientip;

	private String deviceid;

	private String mobile;

	private String email;

	private String qq;

	private String openid;

	private String creid;

	private String outerid;

	public String getMch_id() {
		return mch_id;
	}

	public void setMch_id(String mch_id) {
		this.mch_id = mch_id;
	}

	public String getAppid() {
		return appid;
	}

	public void setAppid(String appid) {
		this.appid = appid;
	}

	public String getPlan_id() {
		return plan_id;
	}

	public void setPlan_id(String plan_id) {
		this.plan_id = plan_id;
	}

	public String getContract_code() {
		return contract_code;
	}

	public void setContract_code(String contract_code) {
		this.contract_code = contract_code;
	}

	public String getRequest_serial() {
		return request_serial;
	}

	public void setRequest_serial(String request_serial) {
		this.request_serial = request_serial;
	}

	public String getContract_display_account() {
		return contract_display_account;
	}

	public void setContract_display_account(String contract_display_account) {
		this.contract_display_account = contract_display_account;
	}

	public String getNotify_url() {
		return notify_url;
	}

	public void setNotify_url(String notify_url) {
		this.notify_url = notify_url;
	}

	public String getVersion() {
		return version;
	}

	public void setVersion(String version) {
		this.version = version;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public void setTimestamp(String timestamp) {
		this.timestamp = timestamp;
	}

	public String getClientip() {
		return clientip;
	}

	public void setClientip(String clientip) {
		this.clientip = clientip;
	}

	public String getDeviceid() {
		return deviceid;
	}

	public void setDeviceid(String deviceid) {
		this.deviceid = deviceid;
	}

	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getQq() {
		return qq;
	}

	public void setQq(String qq) {
		this.qq = qq;
	}

	public String getOpenid() {
		return openid;
	}

	public void setOpenid(String openid) {
		this.openid = openid;
	}

	public String getCreid() {
		return creid;
	}

	public void setCreid(String creid) {
		this.creid = creid;
	}

	public String getOuterid() {
		return outerid;
	}

	public void setOuterid(String outerid) {
		this.outerid = outerid;
	}

}


text:
<?php

namespace Fdr\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Fdr\AdminBundle\Entity\TypePrestation;
use Fdr\AdminBundle\Form\TypePrestationType;

/**
 * TypePrestation controller.
 *
 */
class TypePrestationController extends Controller {

    /**
     * Lists all TypePrestation entities.
     *
     */
    public function indexAction(Request $request) {
        $emRole = $this->getDoctrine()->getManager();
        $roles = ($this->getUser()) ? $this->getUser()->getRoles() : array(null);
        $role = $emRole->getRepository('FdrAdminBundle:Role')->findOneByNomRole(substr(strtoupper($roles[0]), 5));
        $methodes = array('getAffTypePrestation', 'getCrTypePrestation', 'getUpTypePrestation', 'getDelTypePrestation');
        $this->get('entitie_manager')->ayantRoles($this, $role, $emRole, $methodes);
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('FdrAdminBundle:TypePrestation')->findBy(array(), array('id' => 'DESC'));

        //--
        $form = array();
        $search_form = $this->createSearchForm();

        foreach ($entities as $entity) {
            $form[$entity->getId()] = $this->createDeleteForm($entity->getId())->createView();
        }
        //--
        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate($entities, $request->query->get('page', 1), 10);
        return $this->render('FdrAdminBundle:TypePrestation:index.html.twig', array(
                    'entities' => $entities,
                    'form' => $form,
                    'search_form' => $search_form->createView(),
                    'pagination' => $pagination,
                    'role' => $role
        ));
    }

    public function rechercheAction(Request $request) {
        $emRole = $this->getDoctrine()->getManager();
        $roles = ($this->getUser()) ? $this->getUser()->getRoles() : array(null);
        $role = $emRole->getRepository('FdrAdminBundle:Role')->findOneByNomRole(substr(strtoupper($roles[0]), 5));
        $methodes = array('getAffTypePrestation', 'getCrTypePrestation', 'getUpTypePrestation', 'getDelTypePrestation');
        $this->get('entitie_manager')->ayantRoles($this, $role, $emRole, $methodes);
        //--
        $form = array();
        $search_form = $this->createSearchForm();
        $search_form->handleRequest($request);
        if ($search_form->isValid()) {
            //$par="libelle";
            $keyword = strtolower($search_form->get('libelle')->getData());
            $par = $search_form->get('par')->getData();
            $em = $this->getDoctrine()->getManager();
            $query = $em->createQuery('SELECT p FROM FdrAdminBundle:TypePrestation p WHERE p.' . $par . ' like :keyword ORDER BY p.' . $par . ' ASC')->setParameter('keyword', strtolower('%' . $keyword . '%'));
            $entities = $query->getResult();
            $paginator = $this->get('knp_paginator');
            $pagination = $paginator->paginate($entities, $request->query->get('page', 1), 10);
        } else {
            throw $this->createNotFoundException(' Erreur Dans la recherche ');
        }

        foreach ($entities as $entity) {
            $form[$entity->getId()] = $this->createDeleteForm($entity->getId())->createView();
        }
        //--
        return $this->render('FdrAdminBundle:TypePrestation:recherche.html.twig', array(
                    'entities' => $entities,
                    'form' => $form,
                    'search_form' => $search_form->createView(),
                    'keyword' => $keyword,
                    'par' => $par,
                    'pagination' => $pagination,
                    'role' => $role
        ));
    }

    /**
     * Creates a new TypePrestation entity.
     *
     */
    public function createAction(Request $request) {
        $emRole = $this->getDoctrine()->getManager();
        $roles = ($this->getUser()) ? $this->getUser()->getRoles() : array(null);
        $role = $emRole->getRepository('FdrAdminBundle:Role')->findOneByNomRole(substr(strtoupper($roles[0]), 5));
        $methodes = array('getCrTypePrestation');
        $this->get('entitie_manager')->ayantRoles($this, $role, $emRole, $methodes);
        $entity = new TypePrestation();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            $this->get('session')->getFlashBag()->add('accuseAjout', 'TypePrestation ayant id=' . $entity->getId() . ' a bien été ajouté');
            return $this->redirect($this->generateUrl('typeprestation_show', array('id' => $entity->getId())));
        }

        return $this->render('FdrAdminBundle:TypePrestation:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                    'role' => $role
        ));
    }

    /**
     * Creates a form to create a TypePrestation entity.
     *
     * @param TypePrestation $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(TypePrestation $entity) {
        $form = $this->createForm(new TypePrestationType(), $entity, array(
            'action' => $this->generateUrl('typeprestation_create'),
            'method' => 'POST',
        ));
        //--
        $form->add('submit', 'submit', array('label' => 'Enregistrer', 'attr' => array('class' => 'btn-default span2 offset5')));

        return $form;
    }

    /**
     * Displays a form to create a new TypePrestation entity.
     *
     */
    public function newAction() {
        $emRole = $this->getDoctrine()->getManager();
        $roles = ($this->getUser()) ? $this->getUser()->getRoles() : array(null);
        $role = $emRole->getRepository('FdrAdminBundle:Role')->findOneByNomRole(substr(strtoupper($roles[0]), 5));
        $methodes = array('getCrTypePrestation');
        $this->get('entitie_manager')->ayantRoles($this, $role, $emRole, $methodes);
        $entity = new TypePrestation();
        $form = $this->createCreateForm($entity);

        return $this->render('FdrAdminBundle:TypePrestation:new.html.twig', array(
                    'entity' => $entity,
                    'form' => $form->createView(),
                    'role' => $role
        ));
    }

    /**
     * Finds and displays a TypePrestation entity.
     *
     */
    public function showAction($id) {
        $emRole = $this->getDoctrine()->getManager();
        $roles = ($this->getUser()) ? $this->getUser()->getRoles() : array(null);
        $role = $emRole->getRepository('FdrAdminBundle:Role')->findOneByNomRole(substr(strtoupper($roles[0]), 5));
        $methodes = array('getAffTypePrestation');
        $this->get('entitie_manager')->ayantRoles($this, $role, $emRole, $methodes);
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FdrAdminBundle:TypePrestation')->find($id);

        if (!$entity) {
            $this->get('session')->getFlashBag()->add('notFoundException', 'Impossible de trouver type prestation ayant code=' . $id);
            return $this->redirect($this->generateUrl('typeprestation'));
        }

        $deleteForm = $this->createDeleteForm($id);

        //---
        $form = $this->createForm(new TypePrestationType(), $entity);
        //---

        return $this->render('FdrAdminBundle:TypePrestation:show.html.twig', array(
                    'entity' => $entity,
                    'delete_form' => $deleteForm->createView(),
                    //--
                    'form' => $form->createView(),
                    'role' => $role
                        //--
        ));
    }

    /**
     * Displays a form to edit an existing TypePrestation entity.
     *
     */
    public function editAction($id) {
        $emRole = $this->getDoctrine()->getManager();
        $roles = ($this->getUser()) ? $this->getUser()->getRoles() : array(null);
        $role = $emRole->getRepository('FdrAdminBundle:Role')->findOneByNomRole(substr(strtoupper($roles[0]), 5));
        $methodes = array('getUpTypePrestation');
        $this->get('entitie_manager')->ayantRoles($this, $role, $emRole, $methodes);
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FdrAdminBundle:TypePrestation')->find($id);

        if (!$entity) {
            $this->get('session')->getFlashBag()->add('notFoundException', 'Impossible de trouver type prestation ayant code=' . $id);
            return $this->redirect($this->generateUrl('typeprestation'));
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('FdrAdminBundle:TypePrestation:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                    'role' => $role
        ));
    }

    /**
     * Creates a form to edit a TypePrestation entity.
     *
     * @param TypePrestation $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createEditForm(TypePrestation $entity) {
        $form = $this->createForm(new TypePrestationType(), $entity, array(
            'action' => $this->generateUrl('typeprestation_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));
        //--
        $form->add('submit', 'submit', array('label' => 'Modifier', 'attr' => array('class' => 'btn-primary span2 offset5')));
        //--
        return $form;
    }

    /**
     * Edits an existing TypePrestation entity.
     *
     */
    public function updateAction(Request $request, $id) {
        $emRole = $this->getDoctrine()->getManager();
        $roles = ($this->getUser()) ? $this->getUser()->getRoles() : array(null);
        $role = $emRole->getRepository('FdrAdminBundle:Role')->findOneByNomRole(substr(strtoupper($roles[0]), 5));
        $methodes = array('getUpTypePrestation');
        $this->get('entitie_manager')->ayantRoles($this, $role, $emRole, $methodes);
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('FdrAdminBundle:TypePrestation')->find($id);

        if (!$entity) {
            $this->get('session')->getFlashBag()->add('notFoundException', 'Impossible de trouver type prestation ayant code=' . $id);
            return $this->redirect($this->generateUrl('typeprestation'));
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();
            $this->get('session')->getFlashBag()->add('accuseModification', 'TypePrestation a bien été modifié');

            return $this->redirect($this->generateUrl('typeprestation_edit', array('id' => $id)));
        }

        return $this->render('FdrAdminBundle:TypePrestation:edit.html.twig', array(
                    'entity' => $entity,
                    'edit_form' => $editForm->createView(),
                    'delete_form' => $deleteForm->createView(),
                    'role' => $role
        ));
    }

    /**
     * Deletes a TypePrestation entity.
     *
     */
    public function deleteAction(Request $request, $id) {
        $emRole = $this->getDoctrine()->getManager();
        $roles = ($this->getUser()) ? $this->getUser()->getRoles() : array(null);
        $role = $emRole->getRepository('FdrAdminBundle:Role')->findOneByNomRole(substr(strtoupper($roles[0]), 5));
        $methodes = array('getDelTypePrestation');
        $this->get('entitie_manager')->ayantRoles($this, $role, $emRole, $methodes);
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('FdrAdminBundle:TypePrestation')->find($id);

            if (!$entity) {
                $this->get('session')->getFlashBag()->add('notFoundException', 'Impossible de trouver type prestation ayant code=' . $id);
                return $this->redirect($this->generateUrl('typeprestation'));
            }

            $em->remove($entity);
            $em->flush();
            $this->get('session')->getFlashBag()->add('accuseSuppression', 'TypePrestation ayant id=' . $id . ' a bien été supprimé');
        }

        return $this->redirect($this->generateUrl('typeprestation'));
    }

    /**
     * Creates a form to delete a TypePrestation entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id) {
        return $this->createFormBuilder()
                        ->setAction($this->generateUrl('typeprestation_delete', array('id' => $id)))
                        ->setMethod('DELETE')
                        //--
                        ->add('supprimer', 'submit', array('label' => 'S', 'attr' => array('class' => 'btn-supp btn-danger', 'title' => 'Supprimer')))
                        //--
                        ->getForm()
        ;
    }

    private function createSearchForm() {
        return $this->createFormBuilder()
                        ->setAction($this->generateUrl('typeprestation_recherche', array()))
                        ->setMethod('GET')
                        //--
                        ->add('par', 'choice', array('choices' => array(
                                'id' => "Code",
                                'libelle' => 'Libelle',
                            ), 'placeholder' => "Rechercher par :"))
                        ->add('libelle', 'text', array('label' => ' ', 'attr' => array('class' => 'input-sm', 'title' => 'Rechercher', 'placeholder' => ' Par mot clè...?')))
                        ->add('submit', 'submit', array('label' => ' Rechercher ', 'attr' => array('class' => 'btn-default', 'title' => 'Rechercher')))
                        //--
                        ->getForm()
        ;
    }

}


text:
package client

import (
	"github.com/rancher/norman/types"
)

const (
	ProjectAlertGroupType                       = "projectAlertGroup"
	ProjectAlertGroupFieldAlertState            = "alertState"
	ProjectAlertGroupFieldAnnotations           = "annotations"
	ProjectAlertGroupFieldCreated               = "created"
	ProjectAlertGroupFieldCreatorID             = "creatorId"
	ProjectAlertGroupFieldDescription           = "description"
	ProjectAlertGroupFieldGroupIntervalSeconds  = "groupIntervalSeconds"
	ProjectAlertGroupFieldGroupWaitSeconds      = "groupWaitSeconds"
	ProjectAlertGroupFieldLabels                = "labels"
	ProjectAlertGroupFieldName                  = "name"
	ProjectAlertGroupFieldNamespaceId           = "namespaceId"
	ProjectAlertGroupFieldOwnerReferences       = "ownerReferences"
	ProjectAlertGroupFieldProjectID             = "projectId"
	ProjectAlertGroupFieldRecipients            = "recipients"
	ProjectAlertGroupFieldRemoved               = "removed"
	ProjectAlertGroupFieldRepeatIntervalSeconds = "repeatIntervalSeconds"
	ProjectAlertGroupFieldState                 = "state"
	ProjectAlertGroupFieldTransitioning         = "transitioning"
	ProjectAlertGroupFieldTransitioningMessage  = "transitioningMessage"
	ProjectAlertGroupFieldUUID                  = "uuid"
)

type ProjectAlertGroup struct {
	types.Resource
	AlertState            string            `json:"alertState,omitempty" yaml:"alertState,omitempty"`
	Annotations           map[string]string `json:"annotations,omitempty" yaml:"annotations,omitempty"`
	Created               string            `json:"created,omitempty" yaml:"created,omitempty"`
	CreatorID             string            `json:"creatorId,omitempty" yaml:"creatorId,omitempty"`
	Description           string            `json:"description,omitempty" yaml:"description,omitempty"`
	GroupIntervalSeconds  int64             `json:"groupIntervalSeconds,omitempty" yaml:"groupIntervalSeconds,omitempty"`
	GroupWaitSeconds      int64             `json:"groupWaitSeconds,omitempty" yaml:"groupWaitSeconds,omitempty"`
	Labels                map[string]string `json:"labels,omitempty" yaml:"labels,omitempty"`
	Name                  string            `json:"name,omitempty" yaml:"name,omitempty"`
	NamespaceId           string            `json:"namespaceId,omitempty" yaml:"namespaceId,omitempty"`
	OwnerReferences       []OwnerReference  `json:"ownerReferences,omitempty" yaml:"ownerReferences,omitempty"`
	ProjectID             string            `json:"projectId,omitempty" yaml:"projectId,omitempty"`
	Recipients            []Recipient       `json:"recipients,omitempty" yaml:"recipients,omitempty"`
	Removed               string            `json:"removed,omitempty" yaml:"removed,omitempty"`
	RepeatIntervalSeconds int64             `json:"repeatIntervalSeconds,omitempty" yaml:"repeatIntervalSeconds,omitempty"`
	State                 string            `json:"state,omitempty" yaml:"state,omitempty"`
	Transitioning         string            `json:"transitioning,omitempty" yaml:"transitioning,omitempty"`
	TransitioningMessage  string            `json:"transitioningMessage,omitempty" yaml:"transitioningMessage,omitempty"`
	UUID                  string            `json:"uuid,omitempty" yaml:"uuid,omitempty"`
}

type ProjectAlertGroupCollection struct {
	types.Collection
	Data   []ProjectAlertGroup `json:"data,omitempty"`
	client *ProjectAlertGroupClient
}

type ProjectAlertGroupClient struct {
	apiClient *Client
}

type ProjectAlertGroupOperations interface {
	List(opts *types.ListOpts) (*ProjectAlertGroupCollection, error)
	ListAll(opts *types.ListOpts) (*ProjectAlertGroupCollection, error)
	Create(opts *ProjectAlertGroup) (*ProjectAlertGroup, error)
	Update(existing *ProjectAlertGroup, updates interface{}) (*ProjectAlertGroup, error)
	Replace(existing *ProjectAlertGroup) (*ProjectAlertGroup, error)
	ByID(id string) (*ProjectAlertGroup, error)
	Delete(container *ProjectAlertGroup) error
}

func newProjectAlertGroupClient(apiClient *Client) *ProjectAlertGroupClient {
	return &ProjectAlertGroupClient{
		apiClient: apiClient,
	}
}

func (c *ProjectAlertGroupClient) Create(container *ProjectAlertGroup) (*ProjectAlertGroup, error) {
	resp := &ProjectAlertGroup{}
	err := c.apiClient.Ops.DoCreate(ProjectAlertGroupType, container, resp)
	return resp, err
}

func (c *ProjectAlertGroupClient) Update(existing *ProjectAlertGroup, updates interface{}) (*ProjectAlertGroup, error) {
	resp := &ProjectAlertGroup{}
	err := c.apiClient.Ops.DoUpdate(ProjectAlertGroupType, &existing.Resource, updates, resp)
	return resp, err
}

func (c *ProjectAlertGroupClient) Replace(obj *ProjectAlertGroup) (*ProjectAlertGroup, error) {
	resp := &ProjectAlertGroup{}
	err := c.apiClient.Ops.DoReplace(ProjectAlertGroupType, &obj.Resource, obj, resp)
	return resp, err
}

func (c *ProjectAlertGroupClient) List(opts *types.ListOpts) (*ProjectAlertGroupCollection, error) {
	resp := &ProjectAlertGroupCollection{}
	err := c.apiClient.Ops.DoList(ProjectAlertGroupType, opts, resp)
	resp.client = c
	return resp, err
}

func (c *ProjectAlertGroupClient) ListAll(opts *types.ListOpts) (*ProjectAlertGroupCollection, error) {
	resp := &ProjectAlertGroupCollection{}
	resp, err := c.List(opts)
	if err != nil {
		return resp, err
	}
	data := resp.Data
	for next, err := resp.Next(); next != nil && err == nil; next, err = next.Next() {
		data = append(data, next.Data...)
		resp = next
		resp.Data = data
	}
	if err != nil {
		return resp, err
	}
	return resp, err
}

func (cc *ProjectAlertGroupCollection) Next() (*ProjectAlertGroupCollection, error) {
	if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
		resp := &ProjectAlertGroupCollection{}
		err := cc.client.apiClient.Ops.DoNext(cc.Pagination.Next, resp)
		resp.client = cc.client
		return resp, err
	}
	return nil, nil
}

func (c *ProjectAlertGroupClient) ByID(id string) (*ProjectAlertGroup, error) {
	resp := &ProjectAlertGroup{}
	err := c.apiClient.Ops.DoByID(ProjectAlertGroupType, id, resp)
	return resp, err
}

func (c *ProjectAlertGroupClient) Delete(container *ProjectAlertGroup) error {
	return c.apiClient.Ops.DoResourceDelete(ProjectAlertGroupType, &container.Resource)
}


text:
<?php

namespace LoopbackSDKPHP\Client;

use LoopbackSDKPHP\Auth;
use LoopbackSDKPHP\LoopbackSDKPHP;
use GuzzleHttp\HandlerStack;
use Psr\Http\Message\RequestInterface;

/**
 * Class Client
 * @package LoopbackSDKPHP\Client
 */
class Client
{

    /**
     * @var string
     */
    protected $host;

    /**
     * @var string
     */
    protected $version;

    /**
     * @var Auth
     */
    protected $auth;

    /**
     * Client constructor.
     * @param string $host
     * @param string $version
     * @param array $guzzleOptions
     */
    public function __construct(
        Auth $auth,
        $host,
        $version = LoopbackSDKPHP::DEFAULT_API_VERSION,
        array $guzzleOptions = []
    ) {

        $this->auth = $auth;
        $this->host = $host;
        $this->version = $version;

        $stack = HandlerStack::create();
        $stack->push($auth->authMiddleware());
        $stack->push(static::versionMiddleware($version));

        $args = array_merge([
          'base_uri' => $host,
          'handler' => $stack
        ], $guzzleOptions);

        $this->guzzle = new \GuzzleHttp\Client($args);
    }

    /**
     * @return \GuzzleHttp\Client
     */
    public function getGuzzle()
    {
        return $this->guzzle;
    }

    public static function versionMiddleware($version)
    {
        return function (callable $handler) use ($version) {
            return function (RequestInterface $request, array $options) use ($handler, $version) {
                $prefix = $version ? "/$version" : '';
                $uri = $request->getUri();
                $uri = $uri->withPath($prefix . $uri->getPath());
                $request = $request->withUri($uri);
                return $handler($request, $options);
            };
        };
    }

}


text:
ENV_VERSION_TAG=""

if [[ -e ./src/common/common-bash.sh ]]; then
    source ./src/common/common-bash.sh .
fi

source ./properties.sh .

echo ""
amnt "--------------------------------------------------------"
amnt "Building new Docker image(${maintainer}/${imagename})"
docker build --rm -t $maintainer/$imagename .
last_status=$?
if [[ "${last_status}" == "0" ]]; then
    echo ""
    if [[ "${ENV_VERSION_TAG}" != "" ]]; then
        image_csum=$(docker images | grep "${maintainer}/${imagename} " | grep latest | awk '{print $3}')
        if [[ "${image_csum}" != "" ]]; then
            docker tag $image_csum $maintainer/$imagename:$ENV_VERSION_TAG
            last_status=$?
            if [[ "${last_status}" != "0" ]]; then
                err "Failed to tag image(${imagename}) with Tag(${ENV_VERSION_TAG})"
                lg ""
                exit 1
            else
                good "Build Successful Tagged Image(${imagename}) with Tag(${ENV_VERSION_TAG})"
            fi

            echo ""
            exit 0
        else
            lg ""
            err "Build failed to find latest image(${imagename}) with Tag(${ENV_VERSION_TAG})"
            echo ""
            exit 1
        fi
    else
        good "Build Successful"
        echo ""
        exit 0
    fi
    lg ""
else
    lg ""
    err "Build failed with exit code: ${last_status}"
    echo ""
    exit 1
fi

exit 0


text:
package com.bankonet;

import java.awt.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Scanner;

public class Menu {

	private static int iteration = 0;

	public static void IHM(){
		String choixUtilisateur = Menu.GestionMenu();
		Menu.GestionChoix(choixUtilisateur);
	}

	public static void AfficheMenu() {
		System.out.println("****APPLICATION CONSEILLER BANCAIRE***");
		System.out.println("0. Arrêter le programme");
		System.out.println("1. Ouvrir un compte courant");
		System.out.println("2. Lister tous les clients");
		System.out.println("Veuillez choisir une action.");
	}

	public static String GestionMenu(){
		Scanner sc = new Scanner(System.in);
		AfficheMenu();
		String choixUtilisateur = sc.nextLine();
		return choixUtilisateur;
	}

	public static void GestionChoix(String choixConseiller) {
		switch (choixConseiller) {
		case "0":
		System.out.println("Arrêt de l'application");
		//fin de l'application
			break;
		case "1":
		iteration++;
		Client client = RecupereClient();
		CompteCourant compteCourant = client.OuvreCompteCourant(iteration);
		SauvegardeFichier("clients.properties", client);
		SauvegardeFichier("comptes.properties", compteCourant);
		IHM();
			break;
		case "2":
		ListeClients();
		IHM();
		default:
			System.out.println("Veuillez entrer une information correcte!");
			GestionMenu();
			break;
		}
	}

	/**
	 * Méthode permettant de sauvegarder un objet dans un fichier
	 * @param fichierDeSauvegarde
	 * @param objetASauvegarder
	 */

	public static void SauvegardeFichier(String fichierDeSauvegarde, Object objetASauvegarder) {
		File file = new File(fichierDeSauvegarde);
		    try {
		    	ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream (file));
				oos.writeObject (objetASauvegarder);
				//oos.close();
			} catch (IOException e) {
				System.out.println("Erreur lors de l'écriture de l'objet :" + objetASauvegarder.toString() + "dans la fichier " + fichierDeSauvegarde);
				e.printStackTrace();
			}
	}

	/**
	* Méthode permettant récupérer les infos d'un fichier sérialisé
	* @param nomFichier (String) le nom du fichier à récupérer
	* @return listObjet (ArrayList): l'objet qui est renvoyé
	*/
	public static ArrayList RecupereInfoFichier (String nomFichier){
		ArrayList listObjet= new ArrayList();
		try
		{
		    ObjectInputStream ois = new ObjectInputStream (new FileInputStream (nomFichier));
	         byte[] buf = new byte[8];
	         int n = 0;
	         while ((n = ois.read(buf)) != -1) {
	    	listObjet.add(ois.readObject());
		    }
		    ois.close();
		}
		catch (ClassNotFoundException exception)
		{
		    System.out.println ("Impossible de lire l'objet : " + exception.getMessage());
		}
		catch (IOException exception)
		{
		    System.out.println ("Erreur lors de l'écriture : " + exception.getMessage());
		}
		return listObjet;
	}

	private static Client RecupereClient(){
		Scanner sc = new Scanner(System.in);
		System.out.println("Indiquer le nom du client: ");
		String nomClient = sc.nextLine();
		System.out.println("Indiquer le prenom du client: ");
		String prenomClient = sc.nextLine();
		System.out.println("Indiquer le login du client: ");
		String loginClient = sc.nextLine();
		System.out.println("Indiquer le mot de passe du client: ");
		String motDePasse = sc.nextLine();
		Client client = new Client(Civilite.MONSIEUR, nomClient, prenomClient, loginClient, motDePasse); //TODO à modifier lors de la gestion client
		return client;
	}

	private static void ListeClients() {
		ArrayList listClient = RecupereInfoFichier("clients.properties");
		int compteurObjet=0;
		for (Object object : listClient) {
			compteurObjet++;
			System.out.println(object);
		}
		System.out.println(compteurObjet);

	}

}