text:
"""
meerkat_auth.py

Registering root Flask app services for the Meerkat Authentication module.
"""
from flask import Flask, abort, g, redirect, render_template
from flask_babel import Babel
from raven.contrib.flask import Sentry
import os

# Create the Flask app
app = Flask(__name__)
babel = Babel(app)
config_object = os.getenv('CONFIG_OBJECT', 'meerkat_auth.config.Production')
app.config.from_object(config_object)
app.config.from_envvar('MEERKAT_AUTH_SETTINGS', silent=True)

# Set up sentry error monitoring
if app.config["SENTRY_DNS"]:
    sentry = Sentry(app, dsn=app.config["SENTRY_DNS"])
else:
    sentry = None

from meerkat_auth.views.users import users_blueprint
from meerkat_auth.views.roles import roles_blueprint
from meerkat_auth.views.auth import auth_blueprint

# Internationalisation for the backend
@babel.localeselector
def get_locale():
    return g.get("language", app.config["DEFAULT_LANGUAGE"])

# display something at /
@app.route("/")
def root():
    """Display something at /."""
    return redirect(app.config["DEFAULT_LANGUAGE"] + "/")

@app.route('/<language>/')
def index(language):
    """Display something at /<language>/."""
    g.language = language
    app.logger.warning(g.language)
    return render_template(
        'login.html',
        root=app.config['ROOT_URL']
    )

@users_blueprint.url_value_preprocessor
@roles_blueprint.url_value_preprocessor
def pull_lang_code(endpoint, values):
    if not values.get("language", ""):
        values["language"] = g.language
    if values["language"] not in app.config["SUPPORTED_LANGUAGES"]:
        abort(404, "Language not supported")
    else:
        g.language = values.pop('language')

@users_blueprint.url_defaults
@roles_blueprint.url_defaults
def add_language_code(endpoint, values):
    values.setdefault('language', app.config["DEFAULT_LANGUAGE"])

# Register the Blueprint modules for the backend
app.register_blueprint(users_blueprint, url_prefix='/<language>/users')
app.register_blueprint(roles_blueprint, url_prefix='/<language>/roles')
app.register_blueprint(auth_blueprint, url_prefix='/api')

# Handle errors
@app.errorhandler(401)
@app.errorhandler(403)
@app.errorhandler(404)
@app.errorhandler(410)
@app.errorhandler(418)
@app.errorhandler(500)
@app.errorhandler(501)
@app.errorhandler(502)
def error500(error):
    """
    Serves page for generic error.

    Args:
        error (int): The error code given by the error handler.
    """
    return render_template('error.html', error=error)

redpajama_set_name: RedPajamaGithub


text:
package com.shade.entities;

import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.Sound;
import org.newdawn.slick.geom.Circle;
import org.newdawn.slick.geom.Shape;
import org.newdawn.slick.state.StateBasedGame;

import com.shade.base.Entity;
import com.shade.base.Level;
import com.shade.base.util.State;
import com.shade.base.util.StateManager;
import com.shade.crash.CrashLevel;
import com.shade.crash.Repelable;
import com.shade.entities.bird.Bird;
import com.shade.entities.mushroom.Mushroom;
import com.shade.entities.util.Sizzle2;
import com.shade.entities.util.Sparkler;
import com.shade.lighting.LuminousEntity;

public class Player extends Linkable {

	public static final int INVINCIBLE_START = 3000;
	public static final float MIN_SPEED = 2.4f;
	public static final float MAX_SPEED = 3.6f;
	public static final float INITIAL_SPEED = MAX_SPEED / 2 + MIN_SPEED / 2;
	private static final int MUSHROOM_LIMIT = 3;
	private static final int PLAYER_HEIGHT = 3;

	private enum PlayerState {
		NORMAL, STUNNED
	};

	private StateManager manager;
	protected Image normal;
	private float luminosity;
	private Sound register, damage;
	private boolean impeded;
	private float mileage;
	protected int invincibleTimer, flipper, flipthreshold;
	private Sizzle2[] sizzles;
	private float speed;

	public Player(int x, int y) throws SlickException {
		initShape(x, y);
		initResources();
		initSizzles();
		initStates();
		invincibleTimer = INVINCIBLE_START;
		flipthreshold = 1;
		speed = INITIAL_SPEED;
	}

	public void initSizzles() {
		sizzles = new Sizzle2[8];
		for (int i = 0; i < sizzles.length; i++) {
			int x = (int) (Math.cos(Math.PI * 2 * i / 8) * getWidth() * 2 / 5);
			int y = (int) (Math.sin(Math.PI * 2 * i / 8) * getHeight() * 2 / 5);
			try {
				sizzles[i] = new Sizzle2(this,10, x, y, "entities/sparkle/puff.png");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void sizzle(Graphics g) {
		for (int i = 0; i < sizzles.length; i++) {
			sizzles[i].animate(g);
		}
	}

	private void initShape(int x, int y) {
		shape = new Circle(x, y, 18);
	}

	private void initResources() throws SlickException {
		normal = new Image("entities/player/player.png");
		register = new Sound("entities/player/register.ogg");
		damage = new Sound("entities/player/hit.ogg");
	}

	private void initStates() {
		manager = new StateManager();
		manager.add(new NormalState());
		manager.add(new StunnedState());
	}

	public void stun() {
		manager.enter(Player.PlayerState.STUNNED);
		damage.play();
	}

	private class NormalState implements State {

		public boolean isNamed(Object state) {
			return state == PlayerState.NORMAL;
		}

		public void enter() {

		}

		public int getRole() {
			// TODO Auto-generated method stub
			return 0;
		}

		public void onCollision(Entity obstacle) {
			if (obstacle.getRole() == Roles.BASKET.ordinal() && next != null) {
				Linkable m = next;
				next = null;
				Linkable l = (Linkable) obstacle;
				l.attach(m);
				register.play();
			}
			if (obstacle.getRole() == Roles.MONSTER.ordinal()) {
				manager.enter(Player.PlayerState.STUNNED);
				damage.play();
			}
			if (obstacle.getRole() == Roles.BIRD.ordinal()) {
				Bird b = (Bird) obstacle;
				if (b.isAttacking()) {
					manager.enter(Player.PlayerState.STUNNED);
					damage.play();
				}
			}

			if (obstacle.getRole() == Roles.SANDPIT.ordinal()) {
				impeded = true;
			}
		}

		public void render(StateBasedGame game, Graphics g) {
			double inverse = INVINCIBLE_START * 7 / 6 - invincibleTimer;
			if (Math.sin(inverse * inverse / (40000.0 * Math.PI)) > 0) {
				normal.drawCentered(getXCenter(), getYCenter());
			}
			if (invincibleTimer <= 0) {
				normal.drawCentered(getXCenter(), getYCenter());
				sizzle(g);
			}
		}

		public void update(StateBasedGame game, int delta) {
			testAndMove(game.getContainer().getInput(), delta);
			testAndWrap();
			for (int i = 0; i < sizzles.length; i++)
				sizzles[i].update(delta);
			impeded = false;
			if(invincibleTimer-delta<0&&invincibleTimer>0)
				for (int i = 0; i < sizzles.length; i++)
				sizzles[i].resetTimer();
			if (invincibleTimer > 0) {
				invincibleTimer -= delta;
			}
		}

		private void testAndMove(Input input, int delta) {
			xVelocity = 0;
			yVelocity = 0;
			if (input.isKeyDown(Input.KEY_LEFT)) {
				xVelocity--;
			}
			if (input.isKeyDown(Input.KEY_RIGHT)) {
				xVelocity++;
			}
			if (input.isKeyDown(Input.KEY_UP)) {
				yVelocity--;
			}
			if (input.isKeyDown(Input.KEY_DOWN)) {
				yVelocity++;
			}
			double mag = Math.sqrt(xVelocity * xVelocity + yVelocity
					* yVelocity);
			// make it uniform speed
			float sped = (impeded) ? speed / 2 : speed;
			xVelocity = (float) (1.0 * sped * xVelocity / mag);
			yVelocity = (float) (1.0 * sped * yVelocity / mag);
			if (mag != 0) {
				nudge(xVelocity, yVelocity);
				mileage += sped;
			} else {
				xVelocity = 0;
				yVelocity = 0;
			}
		}
	}

	public void setSpeed(float newSpeed) {
		speed = newSpeed;
	}

	private class StunnedState implements State {

		private int timer;
		private int failmer;

		public boolean isNamed(Object state) {
			return state == PlayerState.STUNNED;
		}

		public void enter() {
			scatterShrooms();
			for (int i = 0; i < sizzles.length; i++)
				sizzles[i].resetTimer();

			timer = 0;
			failmer = 0;
		}

		// HACK! TODO: KILL HACK!
		private void scatterShrooms() {
			Linkable la = next;
			while (la != null) {
				Mushroom m = (Mushroom) la;
				la = la.next;
				m.scatter();

			}
		}

		public int getRole() {
			// TODO Auto-generated method stub
			return PlayerState.STUNNED.ordinal();
		}

		public void onCollision(Entity obstacle) {

		}

		public void render(StateBasedGame game, Graphics g) {
			if (failmer % 5 > 2) {
				normal.drawCentered(getXCenter(), getYCenter());
			}

		}

		public void update(StateBasedGame game, int delta) {
			timer += delta;
			failmer++;
			if (timer > 800){
				manager.enter(PlayerState.NORMAL);
				invincibleTimer = 2000;
			}
		}

		private void testAndMove(Input input, int delta) {
			xVelocity = 0;
			yVelocity = 0;
			if (input.isKeyDown(Input.KEY_LEFT)) {
				xVelocity--;
			}
			if (input.isKeyDown(Input.KEY_RIGHT)) {
				xVelocity++;
			}
			if (input.isKeyDown(Input.KEY_UP)) {
				yVelocity--;
			}
			if (input.isKeyDown(Input.KEY_DOWN)) {
				yVelocity++;
			}
			double mag = Math.sqrt(xVelocity * xVelocity + yVelocity
					* yVelocity);
			// make it uniform speed
			float sped = (impeded) ? speed / 2 : speed;
			xVelocity = (float) (1.0 * sped * xVelocity / mag);
			yVelocity = (float) (1.0 * sped * yVelocity / mag);
			if (mag != 0) {
				nudge(xVelocity, yVelocity);
			} else {
				xVelocity = 0;
				yVelocity = 0;
			}
		}

	}

	@Override
	public void attach(Linkable l) {
		if (next == null) {
			super.attach(l);
			return;
		}
		int i = 1;
		Linkable head = next;
		while (head.next != null) {
			i++;
			head = head.next;
		}
		if (i < MUSHROOM_LIMIT) {
			super.attach(l);
		}
	}

	public Shape castShadow(float direction, float depth) {
		return null;
	}

	public float getLuminosity() {
		float max = 0;
		for (int i = 0; i < sizzles.length; i++) {
			max += sizzles[i].getLuminosity();
		}
		return invincibleTimer > 0 || manager.currentState().getRole()==PlayerState.STUNNED.ordinal() ? 0 : max;
	}

	public int getZIndex() {
		return PLAYER_HEIGHT;
	}

	public void setLuminosity(float l) {
		luminosity = l;
	}

	public void addToLevel(Level<?> l) {

	}

	public float totalMileage() {
		return mileage;
	}

	public boolean isStunned() {
		return manager.currentState().isNamed(PlayerState.STUNNED);
	}

	public int getRole() {
		return Roles.PLAYER.ordinal();
	}

	public void setSmokeCount(int count) {
		// smoky.changeCount(count);
	}

	public int getSmokeCount() {
		// return smoky.getCount();
		return 0;
	}

	public void onCollision(Entity obstacle) {
		manager.onCollision(obstacle);
		if (obstacle.getRole() == Roles.OBSTACLE.ordinal()) {
			Repelable b = (Repelable) obstacle;
			b.repel(this);
		}
		/*
		 * TODO: determine if we want the chest to be an obstacle. if
		 * (obstacle.getRole() == Roles.TREASURE.ordinal()) { Repelable b =
		 * (Repelable) obstacle; b.repel(this); }
		 */
	}

	public void removeFromLevel(Level<?> l) {
		CrashLevel level = (CrashLevel) l;
		try {
			level.add(new MockPlayer((int) getXCenter(), (int) getYCenter()));
		} catch (SlickException e) {
			e.printStackTrace();
		}
	}

	public void render(StateBasedGame game, Graphics g) {
		//ghost.animate(g);
		if (speed > MAX_SPEED - .4) {
			//smoky.animate(g);
		}
		manager.render(game, g);

	}

	public void update(StateBasedGame game, int delta) {
		manager.update(game, delta);

	}

	public int compareTo(LuminousEntity e) {
		return getZIndex() - e.getZIndex();
	}

}


text:
/**
 * Location Intelligence APIs
 * Incorporate our extensive geodata into everyday applications, business processes and workflows.
 *
 * OpenAPI spec version: 8.5.0
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package pb.locationintelligence.model;

import java.util.Objects;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

/**
 * GeoLocationState
 */
@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2020-04-16T15:55:12.092+05:30")
public class GeoLocationState   {
  @SerializedName("confidence")
  private String confidence = null;

  @SerializedName("value")
  private String value = null;

  public GeoLocationState confidence(String confidence) {
    this.confidence = confidence;
    return this;
  }

   /**
   * Get confidence
   * @return confidence
  **/
  @ApiModelProperty(example = "null", value = "")
  public String getConfidence() {
    return confidence;
  }

  public void setConfidence(String confidence) {
    this.confidence = confidence;
  }

  public GeoLocationState value(String value) {
    this.value = value;
    return this;
  }

   /**
   * Get value
   * @return value
  **/
  @ApiModelProperty(example = "null", value = "")
  public String getValue() {
    return value;
  }

  public void setValue(String value) {
    this.value = value;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    GeoLocationState geoLocationState = (GeoLocationState) o;
    return Objects.equals(this.confidence, geoLocationState.confidence) &&
        Objects.equals(this.value, geoLocationState.value);
  }

  @Override
  public int hashCode() {
    return Objects.hash(confidence, value);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class GeoLocationState {\n");

    sb.append("    confidence: ").append(toIndentedString(confidence)).append("\n");
    sb.append("    value: ").append(toIndentedString(value)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }
}


text:
<img src="icon.png" alt="Icon" data-linktype="relative-path" height="100" width="100">

# Eventbrite (Preview)

Eventbrite is a self-service ticketing platform used to create and discover local events.

# Actions

## Create event
Create a new Eventbrite event.

**Operation Id:** CreateEvent

#### Parameters
| Summary | Type | Description | Required |
|---------|------|-------------|----------|
| Name | string | The name of the event. | true |
| Description | string | The description on the event page. | true |
| Start | string | Start time (UTC format Ex. "2017-01-12T13:45:30Z"). | true |
| End | string | End time (UTC format Ex. 2017-01-12T16:45:30Z). | true |
| Start timezone | string | Timezone of the event. | true |
| End timezone | string | Timezone of the event. | true |
| Event currency | string | Currency for this Event's transactions. | true |
| Organizer | string | The ID of the organizer of this event. | false |
| Venue | string | A previously-created venue to associate with this event. | false |
| Category | string | The category of the event. | false |
| Password | string | Password needed to see the event in unlisted mode. | false |
| Capacity | string | Set specific capacity (if omitted, sums ticket capacities). | false |
| Shareable | boolean | If users can share the event on social media. | false |
| Invite Only | boolean | Only invited users can see the event page. | false |
| Online Event | boolean | Whether the event is online-only (no venue). | false |
| Listed | boolean | If the event is publicly listed and searchable. | false |
| Hide start date | boolean | Whether the start date should be hidden. | false |
| Hide end date | boolean | Whether the end date should be hidden. | false |
| Show Remaining | boolean | If the remaining number of tickets is publicly visible on the event page. | false |

#### Returns
| Summary | Type | Description |
|---------|------|-------------|
| [CreateEvent_Response](#createeventresponse) | object |  |

___

## Update event
Update an existing event.

**Operation Id:** UpdateEvent

#### Parameters
| Summary | Type | Description | Required |
|---------|------|-------------|----------|
| Event | string | Event to update. | true |
| Name | string | The name of the event. | false |
| Description | string | The description on the event page. | false |
| Start | string | Start time (UTC format Ex. "2017-01-12T13:45:30Z"). | false |
| End | string | End time (UTC format Ex. 2017-01-12T16:45:30Z). | false |
| Start timezone | string | Timezone of the event. | false |
| End timezone | string | Timezone of the event. | false |
| Event currency | string | Currency for this Event's transactions. | false |
| Organizer | string | The ID of the organizer of this event. | false |
| Venue | string | A previously-created venue to associate with this event. | false |
| Category | string | The category of the event. | false |
| Password | string | Password needed to see the event in unlisted mode. | false |
| Capacity | string | Set specific capacity (if omitted, sums ticket capacities). | false |
| Shareable | boolean | Set specific capacity (if omitted, sums ticket capacities). | false |
| Invite Only | boolean | Only invited users can see the event page. | false |
| Online Event | boolean | Whether the event is online-only (no venue). | false |
| Listed | boolean | If the event is publicly listed and searchable. | false |
| Hide start date | boolean | Whether the start date should be hidden. | false |
| Hide end date | boolean | Whether the start date should be hidden. | false |
| Show Remaining | boolean | If the remaining number of tickets is publicly visible on the event page. | false |

#### Returns
| Summary | Type | Description |
|---------|------|-------------|
| [CreateEvent_Response](#createeventresponse) | object |  |

___

# Triggers

## When an event is created
Triggers a flow when an organizer has a new event.

**Operation Id:** OnNewEvent

#### Parameters
| Summary | Type | Description | Required |
|---------|------|-------------|----------|
| Organizer | string | Organizer to trigger on new events. | true |

#### Returns
| Summary | Type | Description |
|---------|------|-------------|
| [GetEventsForOrganizer_Response](#geteventsfororganizerresponse) | array |  |

___

## When an order changes
Trigger a flow when an order changes.

**Operation Id:** OnOrderChanged

#### Parameters
| Summary | Type | Description | Required |
|---------|------|-------------|----------|
| Event | string | Event to trigger on changed order. | true |

#### Returns
| Summary | Type | Description |
|---------|------|-------------|
| [GetOrders_Response](#getordersresponse) | array |  |

___

## Objects

### GetOrganizers_Response

| Summary | Type | Description | Path |
|---------|------|-------------|------|
| Organizer | array of object |  | organizers |
| Id | string | The id of the organizer. | organizers.id |
| Name | string | The name of the organizer. | organizers.name |

### GetMyVenues_Response

| Summary | Type | Description | Path |
|---------|------|-------------|------|
| Venue | array of object |  | venues |
| Id | string | The id of the venue. | venues.id |
| Name | string | The name of the venue. | venues.name |

### GetEventsForOrganizer_Response

| Summary | Type | Description | Path |
|---------|------|-------------|------|
| Name | string | The name of the event (in text form). | name.text |
| Description | string | The description of the event (in text form). | description.text |
| Id | string | The id of the event. | id |
| URL | string | The URL of the event. | url |
| Timezone | string | The timezone of the start of the event. | start.timezone |
| local | date-time | The start date-time of the event in local time. | start.local |
| UTC | date-time | The start date-time of the event in UTC. | start.utc |
| Timezone | string | The timezone of the end of the event. | end.timezone |
| local | date-time | The end date-time of the event in local time. | end.local |
| UTC | date-time | The end date-time of the event in UTC. | end.utc |
| Created Date-Time | date-time | The date-time the event was created at. | created |
| Chaged Date-Time | date-time | The date-time the event was changed at. | changed |
| Capacity | int32 | The capacity of the event. | capacity |
| Is Online Event | boolean | A boolean indicating whether or not the event is online. | online_event |
| Organizer Id | string | The id of the organizer of the event. | organizer_id |
| Venue Id | string | The id of the venue of the event. | venue_id |
| Category Id | string | The id of the category of the event. | category_id |

### GetOrders_Response

| Summary | Type | Description | Path |
|---------|------|-------------|------|
| Id | string | The id of the order. | id |
| Name | string | The name of the order. | name |
| First Name | string | The first name on the order. | first_name |
| Last Name | string | The last name on the order. | last_name |
| Email | string | The email on the order. | email |
| Status | string | The status of the order. | status |

### GetMyEvents_Response

| Summary | Type | Description | Path |
|---------|------|-------------|------|
| events | array of object |  | events |
| Name | string | The name of the event (in text form). | events.name.text |
| Id | string | The id of the event. | events.id |

### GetCategories_Response

| Summary | Type | Description | Path |
|---------|------|-------------|------|
| categories | array of object |  | categories |
| Id | string | The id of the category. | categories.id |
| Name | string | The name of the category. | categories.name |

### CreateEvent_Response

| Summary | Type | Description | Path |
|---------|------|-------------|------|
| Name | string | The name of the event (in text form). | name.text |
| Description | string | The description of the event. | description.text |
| Id | string | The id of the event. | id |
| URL | string | The URL of the event. | url |
| Timezone | string | The timezone of the start of the event. | start.timezone |
| local | date-time | The start date-time of the event in local time. | start.local |
| UTC | date-time | The start date-time of the event in UTC. | start.utc |
| Timezone | string | The timezone of the end of the event. | end.timezone |
| local | date-time | The end date-time of the event in local time. | end.local |
| UTC | date-time | The end date-time of the event in UTC. | end.utc |
| Created Date-Time | date-time | The date-time the event was created at. | created |
| Chaged Date-Time | date-time | The date-time the event was changed at. | changed |
| Capacity | int32 | The capacity of the event. | capacity |
| Is Online Event | boolean | A boolean indicating whether or not the event is online. | online_event |
| Organizer Id | string | The id of the organizer of the event. | organizer_id |
| Venue Id | string | The id of the venue of the event. | venue_id |
| Category Id | string | The id of the category of the event. | category_id |

## Limits
| Name | Calls | Renewal Period |
|------|-------|----------------|
| API calls per connection | 100 | 60 seconds |
| Frequency of trigger polls | 1 | 120 seconds |


text:
layout: post
title:  "Import classes from a jar with Maven"
date:   2016-06-08 14:00:00 +0200
categories: maven java
---

Pour pouvoir importer des classes spécifiques d'un jar qui est une dépendance du projet, il faut utiliser la balise overlays du plugin maven maven-war-plugin.

```
  <overlays>
    <overlay>
        <groupId>monGroupId</groupId>
        <artifactId>monArtifactId</artifactId>
        <type>jar</type>
        <includes>
            <include>xx/yyyy/*</include>
        </includes>
        <targetPath>WEB-INF/classes</targetPath>
    </overlay>
  </overlays>
```

Tous les fichiers présents dans le répertoire xx/yyyy de la lib monArtifactId sera recopiée dans le répertoire WEB-INF/classes du package courant.


text:
<?php

/**
 * SampleShell
 */
namespace TestApp\Shell;

use Cake\Console\Shell;

class I18mShell extends Shell
{

    /**
     * main method
     *
     * @return void
     */
    public function main()
    {
        $this->out('This is the main method called from I18mShell');
    }
}


text:
require 'spec_helper'

describe 'DELETE /api/v1/cookbooks/:cookbook/versions/:version' do
  let(:user) { create(:user) }

  context 'the cookbook version exists' do
    before do
      share_cookbook('redis-test', user, custom_metadata: { version: '1.1.0' })
      share_cookbook('redis-test', user, custom_metadata: { version: '1.2.0' })
      unshare_cookbook_version('redis-test', '1.2.0', user)
    end

    it 'returns a 200' do
      expect(response.status.to_i).to eql(200)
    end

    it 'returns the destroyed cookbook version metadata' do
      expect(json_body.to_s).to match(/\"1.2.0\"/)
    end

    it 'destroys the cookbook version' do
      get '/api/v1/cookbooks/redis-test/versions/1.2.0'
      expect(response.status.to_i).to eql(404)
    end

    it "doesn't destroy other cookbook versions" do
      get '/api/v1/cookbooks/redis-test/versions/1.1.0'
      expect(json_body.to_s).to match(/\"1.1.0\"/)
    end
  end

  context "the cookbook version doesn't exist" do
    before { unshare_cookbook_version('redis-test', '1_1_0', user) }

    it 'returns a 404' do
      expect(response.status.to_i).to eql(404)
    end

    it 'returns a 404 message' do
      expect(json_body).to eql(error_404)
    end
  end
end


text:
define(
[
'angular',
'./bookmarksStorage',
'./booleanSearchEngine',
'./settings'
],
function(angular, bookmarksStorage, booleanSearchEngine, settings) { 'use strict';

// Creates new module 'dewey.filters'
var module = angular.module('dewey.services', []);

// Register bookmarksStorage service
module.factory('bookmarksStorage', bookmarksStorage);

// Register booleanSearchEngine service
module.factory('booleanSearchEngine', booleanSearchEngine);

// Register settings service
module.value('appSettings', settings);

});


text:
package org.jpublish.repository.db;

import java.io.StringReader;
import java.io.StringWriter;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.anthonyeden.lib.util.IOUtilities;
import com.anthonyeden.lib.util.ClassUtilities;
import com.anthonyeden.lib.config.Configuration;

import org.jpublish.JPublishContext;
import org.jpublish.view.ViewRenderer;
import org.jpublish.util.PathUtilities;
import org.jpublish.util.vfs.VFSFile;
import org.jpublish.repository.AbstractRepository;

/** Repository implementation which pulls content from a database.

Here is an example configuration connecting to a MySql database:

    <name>db_repository</name>
    <driver>org.gjt.mm.mysql.Driver</name>
    <url>jdbc:mysql://myserver.com/database</url>
    <username>username</username>
    <password>password</password>
    <content-query>select body from content where path = ?</content-query>
    <last-modified-query>select last_modified from content where path = ?</last-modified-query>
    <paths-query>select * from content where path like ?</paths-query>
    <delete-query>delete from content where path = ?</delete-query>

The database setup would be:

    create table content (
        path varchar(255) not null,
        body text not null,
        last_modified datetime not null
    );

Note: This implementation does not currently implement all of the
    required respository methods properly.  In particular, the
    makeDirectory() and removeDirectory() methods are
    not implemented, nor is the getVFSRoot() method implemented
    (it will through an UnsupportedOperationException).

*/

public class DBRepository extends AbstractRepository{

    private static final Log log = LogFactory.getLog(DBRepository.class);

    private String driver;
    private String url;
    private String username;
    private String password;

    private String contentQuery;
    private String lastModifiedQuery;
    private String pathsQuery;
    private String deleteQuery;

    /** Get the content from the given path.  Implementations of this method
        should NOT merge the content using view renderer.

        @param path The relative content path
        @return The content as a String
        @throws Exception Any Exception
    */

    public String get(String path) throws Exception{
        log.debug("Getting static content element.");

        Connection c = null;
        try{
            log.debug("Connecting to database.");
            c = DriverManager.getConnection(url, username, password);

            PreparedStatement s = c.prepareStatement(contentQuery);
            s.setString(1, path);

            log.debug("Executing query.");
            ResultSet r = s.executeQuery();
            if(r.next()){
                return r.getString(1);
            } else {
                throw new Exception("Path not found: " + path);
            }
        } finally {
            c.close();
        }
    }

    /** Get the content from the given path and merge it with
        the given context.

        @param path The content path
        @param context The current context
        @return The content as a String
        @throws Exception Any Exception
    */

    public String get(String path, JPublishContext context) throws Exception{
        if(log.isDebugEnabled())
            log.debug("Getting dynamic content element for path " + path);

        StringWriter writer = null;
        StringReader reader = null;

        try{
            writer = new StringWriter();
            reader = new StringReader(get(path));

            String name = PathUtilities.makeRepositoryURI(getName(), path);
            ViewRenderer renderer = siteContext.getViewRenderer();
            renderer.render(context, name, reader, writer);

            return writer.toString();
        } finally {
            IOUtilities.close(writer);
            IOUtilities.close(reader);
        }
    }

    /** Remove the content at the specified path.

        @param path The path
    */

    public void remove(String path) throws Exception{
        Connection c = null;
        try{
            c = DriverManager.getConnection(url, username, password);
            PreparedStatement s = c.prepareStatement(deleteQuery);
            s.setString(1, path);

            s.executeUpdate();
        } finally {
            c.close();
        }
    }

    /** Make the directory for the specified path.  Parent directories
        will also be created if they do not exist.

        @param path The directory path
    */

    public void makeDirectory(String path){
        throw new UnsupportedOperationException("Make directory not supported");
    }

    /** Remove the directory for the specified path.  The directory
        must be empty.

        @param path The path
        @throws Exception
    */

    public void removeDirectory(String path) throws Exception{
        throw new UnsupportedOperationException("Remove directory not supported");
    }

    /** Get the last modified time in milliseconds for the given path.

        @param path The content path
        @return The last modified time in milliseconds
        @throws Exception Any exception
    */

    public long getLastModified(String path) throws Exception{
        Connection c = null;
        try{
            log.debug("Connecting to database.");
            c = DriverManager.getConnection(url, username, password);

            PreparedStatement s = c.prepareStatement(lastModifiedQuery);
            s.setString(1, path);

            log.debug("Executing query.");
            ResultSet r = s.executeQuery();
            if(r.next()){
                return r.getLong(1);
            } else {
                throw new Exception("Path not found: " + path);
            }
        } finally {
            c.close();
        }
    }

    /** Get an Iterator of paths which are known to the repository.

        @return An iterator of paths
        @throws Exception
    */

    public Iterator getPaths() throws Exception{
        return getPaths("");
    }

    /** Get an Iterator of paths which are known to the repository, starting
        from the specified base path.

        @param base The base path
        @return An iterator of paths
        @throws Exception
    */

    public Iterator getPaths(String path) throws Exception{
        ArrayList paths = new ArrayList();
        Connection c = null;
        try{
            log.debug("Connecting to database.");
            c = DriverManager.getConnection(url, username, password);

            PreparedStatement s = c.prepareStatement(pathsQuery);
            s.setString(1, path + "%");

            log.debug("Executing query.");
            ResultSet r = s.executeQuery();
            while(r.next()){
                paths.add(r.getString("path"));
            }
        } finally {
            c.close();
        }

        return paths.iterator();
    }

    /** Get the Virtual File System root file.  The Virtual File System
        provides a datasource-independent way of navigating through all
        items known to the Repository.

        @return The root VFSFile
        @throws Exception
    */

    public VFSFile getVFSRoot() throws Exception{
        // NYI
        throw new UnsupportedOperationException();
    }

    public File pathToFile(String path) {
        return null;
    }

    /** Load the repository's configuration from the given configuration
        object.

        @param element The configuration object
        @throws Exception
    */

    public void loadConfiguration(Configuration configuration) throws Exception{
        this.name = configuration.getAttribute("name");
        setDriver(configuration.getChildValue("driver"));
        setURL(configuration.getChildValue("url"));
        setUsername(configuration.getChildValue("username"));
        setPassword(configuration.getChildValue("password"));

        setContentQuery(configuration.getChildValue("content-query"));
        setLastModifiedQuery(configuration.getChildValue("last-modified-query"));
        setPathsQuery(configuration.getChildValue("paths-query"));
        setDeleteQuery(configuration.getChildValue("delete-query"));
    }

    /** Set the driver class.

        @param driver The fully-qualified driver class
        @throws Exception Any Exception
    */

    protected void setDriver(String driver) throws Exception{
        this.driver = driver;
        ClassUtilities.loadClass(this.driver);
    }

    /** Set the URL.

        @param url The new URL
    */

    protected void setURL(String url){
        this.url = url;
    }

    /** Set the username.

        @param username The new username
    */

    protected void setUsername(String username){
        this.username = username;
    }

    /** Set the password.

        @param password The new password
    */

    protected void setPassword(String password){
        this.password = password;
    }

    /** Set the content query.  This query will pull the content body from
        the database.  The first column must be the content
        body.

        @param contentQuery The content query
    */

    protected void setContentQuery(String contentQuery){
        this.contentQuery = contentQuery;
    }

    /** Set the "last modified" query.  This query will pull the last modified
        timestamp from the database.  The first column must be the last
        modified timestamp.

        @param lastModifiedQuery The "last modified" query
    */

    protected void setLastModifiedQuery(String lastModifiedQuery){
        this.lastModifiedQuery = lastModifiedQuery;
    }

    /** Set the "getPaths()" query.  This query will pull a list of all paths
        from the database.

        @param pathQuery The "getPaths()" query
    */

    protected void setPathsQuery(String pathsQuery){
        this.pathsQuery = pathsQuery;
    }

    /** Set the query for deleting a piece of content from the repository.

        @param deleteQuery The new delete query
    */

    protected void setDeleteQuery(String deleteQuery){
        this.deleteQuery = deleteQuery;
    }

}


text:
***
A basic heroku app for deploying function delays.
***
``` sh
Steps for deploying the app:

$heroku login
$git clone https://github.com/ashumeow/heroku-load.git
$cd heroku-load
$heroku create
$git push heroku master
$heroku ps:scale web=1
$heroku open
```
```
Requirements:

JDK (Java Development Toolkit)
Java IDE: JetBrains 14.1.5
Gradle
Maven
Git 2.6.3
Heroku Toolbelt 3.42.21
```


text:
package com.jetlag.jcreator.agera.observable;

import com.google.android.agera.BaseObservable;

/**
 * Created by vince on 09/09/16.
 */
public class GalleryPicturesGetterObservable extends BaseObservable {
  public void retrievePics() {
    dispatchUpdate();
  }
}


text:
package com.satanko.weballgrade.data.dao.impl.hibernate;

import com.satanko.weballgrade.data.dao.TeacherDAO;
import com.satanko.weballgrade.data.model.Teacher;
import com.satanko.weballgrade.service.PreparedServerResponses;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.WebApplicationException;
import org.hibernate.SessionFactory;

/**
 * This class provides an implementation of the {@link TeacherDAO}
 * interface using the Hibernate Framework to perform interactions with a single database table.
 *
 * @author Julian Tropper (julian.tropper@gmail.com)
 * ATTENTION: If not otherwise specified, the author(s) of the class is/are also responsible for all methods.
 *
 * @version 1.0
 */
public class HibernateTeacherDAO implements TeacherDAO {

    /**
     * A field providing methods for interactions with the database via Hibernate

     * Additional Information ...jboss.org/wiki/SessionsAndTransactions
     *
     * @see AllGradeDBUtil
     */
    private SessionFactory sf = AllGradeDBUtil.getSessionFactory();

    /**
     * {@inheritDoc }
     */
    @Override
    public void updateTeachers(ArrayList<String> teachers) {
        try {
            sf.getCurrentSession().beginTransaction();
            for (int i = 0; i < teachers.size(); i++) {
                sf.getCurrentSession().saveOrUpdate(new Teacher(teachers.get(i)));
            }
            sf.getCurrentSession().getTransaction().commit();
        } catch (RuntimeException re) {
            sf.getCurrentSession().getTransaction().rollback();
            Logger.getLogger(HibernateStudentDAO.class.getName()).log(Level.SEVERE, re.getMessage());
            throw new WebApplicationException(PreparedServerResponses.ERROR_DATABASE);
        }
    }
}


text:
package org.geogit.cli.test.functional;

import java.io.File;

import org.geogit.api.InjectorBuilder;
import org.geogit.di.GeogitModule;
import org.geogit.metrics.MetricsModule;
import org.geogit.test.integration.je.JETestStorageModule;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.util.Modules;

public class CLITestInjectorBuilder extends InjectorBuilder {

    File workingDirectory;

    File homeDirectory;

    public CLITestInjectorBuilder(File workingDirectory, File homeDirectory) {
        this.workingDirectory = workingDirectory;
        this.homeDirectory = homeDirectory;
    }

    @Override
    public Injector build() {
        TestPlatform testPlatform = new TestPlatform(workingDirectory, homeDirectory);
        JETestStorageModule jeStorageModule = new JETestStorageModule();
        FunctionalTestModule functionalTestModule = new FunctionalTestModule(testPlatform);

        Injector injector = Guice.createInjector(Modules.override(new GeogitModule()).with(
                jeStorageModule, functionalTestModule, new MetricsModule()));
        return injector;
    }

}


text:
'use strict';

require('../../support/test-helper');

var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');

describe('histogram widgets', function () {
    it('should expose layer histogram', function (done) {
        var histogramMapConfig = {
            version: '1.5.0',
            layers: [
                {
                    type: 'mapnik',
                    options: {
                        sql: 'select * from populated_places_simple_reduced',
                        cartocss: '#layer { marker-fill: red; marker-width: 32; marker-allow-overlap: true; }',
                        cartocss_version: '2.3.0',
                        widgets: {
                            pop_max: {
                                type: 'histogram',
                                options: {
                                    column: 'pop_max'
                                }
                            }
                        }
                    }
                }
            ]
        };

        var testClient = new TestClient(histogramMapConfig);

        testClient.getWidget('pop_max', function (err, res) {
            if (err) {
                return done(err);
            }

            var histogram = JSON.parse(res.body);
            assert.ok(histogram.bins.length);

            testClient.drain(done);
        });
    });

    describe('filters', function () {
        describe('range', function () {
            var histogramMapConfig = {
                version: '1.5.0',
                layers: [
                    {
                        type: 'mapnik',
                        options: {
                            sql: 'select * from populated_places_simple_reduced',
                            cartocss: '#layer { marker-fill: red; marker-width: 32; marker-allow-overlap: true; }',
                            cartocss_version: '2.3.0',
                            widgets: {
                                country_places_histogram: {
                                    type: 'histogram',
                                    options: {
                                        column: 'pop_max'
                                    }
                                }
                            }
                        }
                    }
                ]
            };

            it('should expose an histogram', function (done) {
                var testClient = new TestClient(histogramMapConfig);
                testClient.getWidget('country_places_histogram', { own_filter: 0 }, function (err, res) {
                    if (err) {
                        return done(err);
                    }

                    var histogram = JSON.parse(res.body);
                    // notice min value
                    assert.deepStrictEqual(
                        histogram.bins[0],
                        { bin: 0, freq: 6497, min: 0, max: 742572, avg: 113511.16823149147 }
                    );

                    testClient.drain(done);
                });
            });

            it('should expose a filtered histogram', function (done) {
                var params = {
                    filters: {
                        layers: [
                            {
                                country_places_histogram: { min: 4000000 }
                            }
                        ]
                    }
                };
                var testClient = new TestClient(histogramMapConfig);
                testClient.getWidget('country_places_histogram', params, function (err, res) {
                    if (err) {
                        return done(err);
                    }

                    var histogram = JSON.parse(res.body);
                    // notice min value
                    assert.deepStrictEqual(histogram.bins[0], {
                        bin: 0,
                        freq: 62,
                        min: 4000000,
                        max: 9276403,
                        avg: 5815009.596774193
                    });

                    testClient.drain(done);
                });
            });

            it('should expose a filtered histogram using dataviews for filtering', function (done) {
                var params = {
                    filters: {
                        dataviews: {
                            country_places_histogram: { min: 4000000 }
                        }
                    }
                };
                var testClient = new TestClient(histogramMapConfig);
                testClient.getWidget('country_places_histogram', params, function (err, res) {
                    if (err) {
                        return done(err);
                    }

                    var histogram = JSON.parse(res.body);
                    // notice min value
                    assert.deepStrictEqual(histogram.bins[0], {
                        bin: 0,
                        freq: 62,
                        min: 4000000,
                        max: 9276403,
                        avg: 5815009.596774193
                    });

                    testClient.drain(done);
                });
            });
        });
    });
});


text:
/

    if (ehRequest->resource == LED.handle)
    {
        if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
        {
            // Create new LED instance
            char newLedUri[15] = "/a/led/";
            int newLedUriLength = strlen(newLedUri);
            snprintf (newLedUri + newLedUriLength, sizeof(newLedUri)-newLedUriLength, "%d", gCurrLedInstance);

            json = cJSON_CreateObject();

            cJSON_AddStringToObject(json,"href",gResourceUri);
            cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject());
            cJSON_AddStringToObject(format, "createduri", (char *) newLedUri);

            if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
            {
                OC_LOG (INFO, TAG, "Created new LED instance");
                gLedInstance[gCurrLedInstance].state = 0;
                gLedInstance[gCurrLedInstance].power = 0;
                gCurrLedInstance++;
                respPLPost_led = cJSON_Print(json);
            }

            cJSON_Delete(json);
        }
        else
        {
            respPLPost_led = constructJsonResponse(ehRequest);
        }
    }
    else
    {
        for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
        {
            if (ehRequest->resource == gLedInstance[i].handle)
            {
                if (i == 0)
                {
                    respPLPost_led = constructJsonResponse(ehRequest);
                    break;
                }
                else if (i == 1)
                {
                    respPLPost_led = constructJsonResponse(ehRequest);
                }
            }
        }
    }

    if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led)))
    {
        strcpy(payload, respPLPost_led);
        ehResult = OC_EH_OK;
    }
    else
    {
        OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small",
                maxPayloadSize);
        ehResult = OC_EH_ERROR;
    }

    free(respPLPost_led);

    return ehResult;
}

OCEntityHandlerResult
OCEntityHandlerCb (OCEntityHandlerFlag flag,
        OCEntityHandlerRequest *entityHandlerRequest)
{
    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);

    OCEntityHandlerResult ehResult = OC_EH_ERROR;
    OCEntityHandlerResponse response;
    char payload[MAX_RESPONSE_LENGTH] = {0};

    if (flag & OC_REQUEST_FLAG)
    {
        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
        if (entityHandlerRequest)
        {
            if (OC_REST_GET == entityHandlerRequest->method)
            {
                OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
                ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload));
            }
            else if (OC_REST_PUT == entityHandlerRequest->method)
            {
                OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
                ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload));
            }
            else if (OC_REST_POST == entityHandlerRequest->method)
            {
                OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
                ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload));
            }
            else
            {
                OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                        entityHandlerRequest->method);
                ehResult = OC_EH_ERROR;
            }

            if (ehResult == OC_EH_OK)
            {
                // Format the response.  Note this requires some info about the request
                response.requestHandle = entityHandlerRequest->requestHandle;
                response.resourceHandle = entityHandlerRequest->resource;
                response.ehResult = ehResult;
                response.payload = payload;
                response.payloadSize = strlen(payload);
                response.numSendVendorSpecificHeaderOptions = 0;
                memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
                memset(response.resourceUri, 0, sizeof(response.resourceUri));
                // Indicate that response is NOT in a persistent buffer
                response.persistentBufferFlag = 0;

                // Send the response
                if (OCDoResponse(&response) != OC_STACK_OK)
                {
                    OC_LOG(ERROR, TAG, "Error sending response");
                    ehResult = OC_EH_ERROR;
                }
            }
        }
    }
    return ehResult;
}

/* SIGINT handler: set gQuitFlag to 1 for graceful termination */
void handleSigInt(int signum)
{
    if (signum == SIGINT)
    {
        gQuitFlag = 1;
    }
}

int main(int argc, char* argv[])
{
    struct timespec timeout;

    OC_LOG(DEBUG, TAG, "OCServer is starting...");

    if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
    {
        OC_LOG(ERROR, TAG, "OCStack init error");
        return 0;
    }

    /*
     * Read DTLS PSK credentials from persistent storage and
     * set in the OC stack.
     */
    if (SetCredentials(CRED_FILE) != OC_STACK_OK)
    {
        OC_LOG(ERROR, TAG, "SetCredentials failed");
        return 0;
    }
    /*
     * Declare and create the example resource: LED
     */
    createLEDResource(gResourceUri, &LED, false, 0);

    timeout.tv_sec  = 0;
    timeout.tv_nsec = 100000000L;

    // Break from loop with Ctrl-C
    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
    signal(SIGINT, handleSigInt);
    while (!gQuitFlag)
    {
        if (OCProcess() != OC_STACK_OK)
        {
            OC_LOG(ERROR, TAG, "OCStack process error");
            return 0;
        }
        nanosleep(&timeout, NULL);
    }

    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");

    if (OCStop() != OC_STACK_OK)
    {
        OC_LOG(ERROR, TAG, "OCStack process error");
    }

    return 0;
}

int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower)
{
    if (!uri)
    {
        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
        return -1;
    }

    ledResource->state = resourceState;
    ledResource->power= resourcePower;
    OCStackResult res = OCCreateResource(&(ledResource->handle),
            "core.led",
            OC_RSRVD_INTERFACE_DEFAULT,
            uri,
            OCEntityHandlerCb,
            OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
    OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));

    return 0;
}


text:
package state

import (
	"github.com/lastbackend/lastbackend/pkg/distribution/types"
	"github.com/lastbackend/lastbackend/pkg/log"
	"strings"
	"sync"
)

const logImagePrefix = "state:images:>"

type ImageState struct {
	lock   sync.RWMutex
	images map[string]*types.Image
}

func (s *ImageState) GetImages() map[string]*types.Image {
	log.V(logLevel).Debugf("%s get images", logImagePrefix)
	return s.images
}

func (s *ImageState) SetImages(images map[string]*types.Image) {
	log.V(logLevel).Debugf("%s set images: %d", logImagePrefix, len(images))
	for _, image := range images {
		for _, tag := range image.Meta.Tags {
			s.images[tag] = image
		}

	}
}

func (s *ImageState) GetImage(tag string) *types.Image {
	log.V(logLevel).Debugf("%s get image: %s", logImagePrefix, tag)
	s.lock.Lock()
	defer s.lock.Unlock()

	if len(strings.Split(tag, ":")) == 1 {
		tag += ":latest"
	}

	image, ok := s.images[tag]
	if !ok {
		return nil
	}
	return image
}

func (s *ImageState) AddImage(tag string, image *types.Image) {
	log.V(logLevel).Debugf("%s add image: %s", logImagePrefix, image.Meta.Name)
	s.SetImage(tag, image)
}

func (s *ImageState) SetImage(tag string, image *types.Image) {
	log.V(logLevel).Debugf("%s set image: %s", logImagePrefix, image.Meta.Name)
	s.lock.Lock()
	defer s.lock.Unlock()

	s.images[image.SelfLink()] = image

	for _, i := range image.Meta.Tags {
		s.images[i] = image
	}
}

func (s *ImageState) DelImage(link string) {
	log.V(logLevel).Debugf("%s del image: %s", logImagePrefix, link)
	s.lock.Lock()
	defer s.lock.Unlock()
	if _, ok := s.images[link]; ok {
		delete(s.images, link)
	}
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**result** | [**\Voximplant\Model\ScenarioInfoType[]**](ScenarioInfoType.md) |  | [optional]
**total_count** | **int** | The total found scenario count. | [optional]
**count** | **int** | The returned scenario count. | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
<?php

namespace Google\Cloud\Logging\Tests\Snippet;

use Google\Cloud\Core\Iterator\ItemIterator;
use Google\Cloud\Core\Testing\Snippet\SnippetTestCase;
use Google\Cloud\Core\Testing\TestHelpers;
use Google\Cloud\Logging\Connection\ConnectionInterface;
use Google\Cloud\Logging\Logger;
use Google\Cloud\Logging\LoggingClient;
use Google\Cloud\Logging\Metric;
use Google\Cloud\Logging\PsrLogger;
use Google\Cloud\Logging\Sink;
use Prophecy\Argument;

/**
 * @group logging
 */
class LoggingClientTest extends SnippetTestCase
{
    private $connection;
    private $client;

    public function set_up()
    {
        $this->connection = $this->prophesize(ConnectionInterface::class);
        $this->client = TestHelpers::stub(LoggingClient::class);
        $this->client->___setProperty('connection', $this->connection->reveal());
    }

    public function testClass()
    {
        $snippet = $this->snippetFromClass(LoggingClient::class);
        $res = $snippet->invoke('logging');

        $this->assertInstanceOf(LoggingClient::class, $res->returnVal());
    }

    public function testCreateSink()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'createSink');
        $snippet->addLocal('logging', $this->client);

        $this->connection->createSink(Argument::any())
            ->shouldBeCalled()
            ->willReturn([]);

        $res = $snippet->invoke('sink');
        $this->assertInstanceOf(Sink::class, $res->returnVal());
    }

    public function testSink()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'sink');
        $snippet->addLocal('logging', $this->client);

        $res = $snippet->invoke();
        $this->assertEquals('my-sink', $res->output());
    }

    public function testSinks()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'sinks');
        $snippet->addLocal('logging', $this->client);

        $this->connection->listSinks(Argument::any())
            ->shouldBeCalled()
            ->willReturn([
                'sinks' => [
                    ['name' => 'Sink 1'],
                    ['name' => 'Sink 2'],
                ]
            ]);

        $this->client->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke('sinks');
        $this->assertInstanceOf(ItemIterator::class, $res->returnVal());
        $this->assertEquals('Sink 1', explode(PHP_EOL, $res->output())[0]);
        $this->assertEquals('Sink 2', explode(PHP_EOL, $res->output())[1]);
    }

    public function testCreateMetric()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'createMetric');
        $snippet->addLocal('logging', $this->client);

        $this->connection->createMetric(Argument::any())
            ->shouldBeCalled()
            ->willReturn([]);

        $this->client->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke('metric');
        $this->assertInstanceOf(Metric::class, $res->returnVal());
    }

    public function testMetric()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'metric');
        $snippet->addLocal('logging', $this->client);

        $res = $snippet->invoke('metric');
        $this->assertInstanceOf(Metric::class, $res->returnVal());
    }

    public function testMetrics()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'metrics');
        $snippet->addLocal('logging', $this->client);

        $this->connection->listMetrics(Argument::any())
            ->shouldBeCalled()
            ->willReturn([
                'metrics' => [
                    ['name' => 'Metric 1'],
                    ['name' => 'Metric 2'],
                ]
            ]);

        $this->client->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke('metrics');
        $this->assertInstanceOf(ItemIterator::class, $res->returnVal());
        $this->assertEquals('Metric 1', explode(PHP_EOL, $res->output())[0]);
        $this->assertEquals('Metric 2', explode(PHP_EOL, $res->output())[1]);
    }

    public function testEntries()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'entries');
        $snippet->addLocal('logging', $this->client);

        $this->connection->listEntries(Argument::any())
            ->shouldBeCalled()
            ->willReturn([
                'entries' => [
                    ['textPayload' => 'Entry 1'],
                    ['textPayload' => 'Entry 2'],
                ]
            ]);

        $this->client->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke('entries');
        $this->assertInstanceOf(ItemIterator::class, $res->returnVal());
        $this->assertEquals('Entry 1', explode(PHP_EOL, $res->output())[0]);
        $this->assertEquals('Entry 2', explode(PHP_EOL, $res->output())[1]);
    }

    public function testEntriesWithFilter()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'entries', 1);
        $snippet->addLocal('logging', $this->client);

        $this->connection->listEntries(Argument::that(function ($arg) {
            return strpos($arg['filter'], 'logName') !== false;
        }))
            ->shouldBeCalled()
            ->willReturn([
                'entries' => [
                    ['textPayload' => 'Entry 1'],
                    ['textPayload' => 'Entry 2'],
                ]
            ]);

        $this->client->___setProperty('connection', $this->connection->reveal());

        $res = $snippet->invoke('entries');
        $this->assertInstanceOf(ItemIterator::class, $res->returnVal());
        $this->assertEquals('Entry 1', explode(PHP_EOL, $res->output())[0]);
        $this->assertEquals('Entry 2', explode(PHP_EOL, $res->output())[1]);
    }

    public function testPsrLogger()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'psrLogger');
        $snippet->addLocal('logging', $this->client);

        $res = $snippet->invoke('psrLogger');
        $this->assertInstanceOf(PsrLogger::class, $res->returnVal());
    }

    public function testPsrBatchLogger()
    {
        $snippet = $this->snippetFromMethod(
            LoggingClient::class,
            'psrLogger',
            1
        );
        $snippet->addLocal('logging', $this->client);

        $res = $snippet->invoke('psrLogger');
        $this->assertInstanceOf(PsrLogger::class, $res->returnVal());
    }

    public function testLogger()
    {
        $snippet = $this->snippetFromMethod(LoggingClient::class, 'logger');
        $snippet->addLocal('logging', $this->client);

        $res = $snippet->invoke('logger');
        $this->assertInstanceOf(Logger::class, $res->returnVal());
    }
}


text:
package org.apache.accumulo.shell.commands;

import java.io.IOException;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeSet;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.TableExistsException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.admin.NewTableConfiguration;
import org.apache.accumulo.core.client.admin.TimeType;
import org.apache.accumulo.core.clientImpl.Tables;
import org.apache.accumulo.core.conf.IterConfigUtil;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.constraints.VisibilityConstraint;
import org.apache.accumulo.core.iterators.IteratorUtil.IteratorScope;
import org.apache.accumulo.shell.Shell;
import org.apache.accumulo.shell.Shell.Command;
import org.apache.accumulo.shell.ShellUtil;
import org.apache.accumulo.shell.Token;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.hadoop.io.Text;

public class CreateTableCommand extends Command {
  private Option createTableOptCopySplits;
  private Option createTableOptCopyConfig;
  private Option createTableOptSplit;
  private Option createTableOptTimeLogical;
  private Option createTableOptTimeMillis;
  private Option createTableNoDefaultIters;
  private Option createTableOptEVC;
  private Option base64Opt;
  private Option createTableOptFormatter;
  private Option createTableOptInitProp;
  private Option createTableOptLocalityProps;
  private Option createTableOptIteratorProps;
  private Option createTableOptOffline;

  @Override
  public int execute(final String fullCommand, final CommandLine cl, final Shell shellState)
      throws AccumuloException, AccumuloSecurityException, TableExistsException,
      TableNotFoundException, IOException {

    final String testTableName = cl.getArgs()[0];
    NewTableConfiguration ntc = new NewTableConfiguration();

    if (!testTableName.matches(Tables.VALID_NAME_REGEX)) {
      shellState.getReader()
          .println("Only letters, numbers and underscores are allowed for use in table names.");
      throw new IllegalArgumentException();
    }

    final String tableName = cl.getArgs()[0];
    if (shellState.getAccumuloClient().tableOperations().exists(tableName)) {
      throw new TableExistsException(null, tableName, null);
    }

    final boolean decode = cl.hasOption(base64Opt.getOpt());

    // Prior to 2.0, if splits were provided at table creation the table was created separately
    // and then the addSplits method was called. Starting with 2.0, the splits will be
    // stored on the file system and created before the table is brought online.
    if (cl.hasOption(createTableOptSplit.getOpt())) {
      ntc = ntc.withSplits(new TreeSet<>(
          ShellUtil.scanFile(cl.getOptionValue(createTableOptSplit.getOpt()), decode)));
    } else if (cl.hasOption(createTableOptCopySplits.getOpt())) {
      final String oldTable = cl.getOptionValue(createTableOptCopySplits.getOpt());
      if (!shellState.getAccumuloClient().tableOperations().exists(oldTable)) {
        throw new TableNotFoundException(null, oldTable, null);
      }
      ntc = ntc.withSplits(
          new TreeSet<>(shellState.getAccumuloClient().tableOperations().listSplits(oldTable)));
    }

    if (cl.hasOption(createTableOptCopyConfig.getOpt())) {
      final String oldTable = cl.getOptionValue(createTableOptCopyConfig.getOpt());
      if (!shellState.getAccumuloClient().tableOperations().exists(oldTable)) {
        throw new TableNotFoundException(null, oldTable, null);
      }
    }

    TimeType timeType = TimeType.MILLIS;
    if (cl.hasOption(createTableOptTimeLogical.getOpt())) {
      timeType = TimeType.LOGICAL;
    }

    Map<String,String> props = ShellUtil.parseMapOpt(cl, createTableOptInitProp);

    // Set iterator if supplied
    if (cl.hasOption(createTableOptIteratorProps.getOpt())) {
      ntc = attachIteratorToNewTable(cl, shellState, ntc);
    }

    // Set up locality groups, if supplied
    if (cl.hasOption(createTableOptLocalityProps.getOpt())) {
      ntc = setLocalityForNewTable(cl, ntc);
    }

    // set offline table creation property
    if (cl.hasOption(createTableOptOffline.getOpt())) {
      ntc = ntc.createOffline();
    }

    // create table.
    shellState.getAccumuloClient().tableOperations().create(tableName,
        ntc.setTimeType(timeType).setProperties(props));

    shellState.setTableName(tableName); // switch shell to new table context

    if (cl.hasOption(createTableNoDefaultIters.getOpt())) {
      for (String key : IterConfigUtil.generateInitialTableProperties(true).keySet()) {
        shellState.getAccumuloClient().tableOperations().removeProperty(tableName, key);
      }
    }

    // Copy options if flag was set
    if (cl.hasOption(createTableOptCopyConfig.getOpt())) {
      if (shellState.getAccumuloClient().tableOperations().exists(tableName)) {
        final Iterable<Entry<String,String>> configuration = shellState.getAccumuloClient()
            .tableOperations().getProperties(cl.getOptionValue(createTableOptCopyConfig.getOpt()));
        for (Entry<String,String> entry : configuration) {
          if (Property.isValidTablePropertyKey(entry.getKey())) {
            shellState.getAccumuloClient().tableOperations().setProperty(tableName, entry.getKey(),
                entry.getValue());
          }
        }
      }
    }

    if (cl.hasOption(createTableOptEVC.getOpt())) {
      try {
        shellState.getAccumuloClient().tableOperations().addConstraint(tableName,
            VisibilityConstraint.class.getName());
      } catch (AccumuloException e) {
        Shell.log.warn("{} while setting visibility constraint, but table was created",
            e.getMessage(), e);
      }
    }

    // Load custom formatter if set
    if (cl.hasOption(createTableOptFormatter.getOpt())) {
      final String formatterClass = cl.getOptionValue(createTableOptFormatter.getOpt());

      shellState.getAccumuloClient().tableOperations().setProperty(tableName,
          Property.TABLE_FORMATTER_CLASS.toString(), formatterClass);
    }
    return 0;
  }

  /**
   * Add supplied locality groups information to a NewTableConfiguration object.
   *
   * Used in conjunction with createtable shell command to allow locality groups to be configured
   * upon table creation.
   */
  private NewTableConfiguration setLocalityForNewTable(CommandLine cl, NewTableConfiguration ntc) {
    HashMap<String,Set<Text>> localityGroupMap = new HashMap<>();
    String[] options = cl.getOptionValues(createTableOptLocalityProps.getOpt());
    for (String localityInfo : options) {
      final String[] parts = localityInfo.split("=", 2);
      if (parts.length < 2)
        throw new IllegalArgumentException("Missing '=' or there are spaces between entries");
      final String groupName = parts[0];
      final HashSet<Text> colFams = new HashSet<>();
      for (String family : parts[1].split(","))
        colFams.add(new Text(family.getBytes(Shell.CHARSET)));
      // check that group names are not duplicated on usage line
      if (localityGroupMap.put(groupName, colFams) != null)
        throw new IllegalArgumentException(
            "Duplicate locality group name found. Group names must be unique");
    }
    ntc.setLocalityGroups(localityGroupMap);
    return ntc;
  }

  /**
   * Add supplied iterator information to NewTableConfiguration object.
   *
   * Used in conjunction with createtable shell command to allow an iterator to be configured upon
   * table creation.
   */
  private NewTableConfiguration attachIteratorToNewTable(final CommandLine cl,
      final Shell shellState, NewTableConfiguration ntc) {
    EnumSet<IteratorScope> scopeEnumSet;
    IteratorSetting iteratorSetting;
    if (shellState.iteratorProfiles.isEmpty())
      throw new IllegalArgumentException("No shell iterator profiles have been created.");
    String[] options = cl.getOptionValues(createTableOptIteratorProps.getOpt());
    for (String profileInfo : options) {
      String[] parts = profileInfo.split(":", 2);
      String profileName = parts[0];
      // The iteratorProfiles.get calls below will throw an NPE if the profile does not exist
      // This can occur when the profile actually does not exist or if there is
      // extraneous spacing in the iterator profile argument list causing the parser to read a scope
      // as a profile.
      try {
        iteratorSetting = shellState.iteratorProfiles.get(profileName).get(0);
      } catch (NullPointerException ex) {
        throw new IllegalArgumentException("invalid iterator argument. Either"
            + " profile does not exist or unexpected spaces in argument list.", ex);
      }
      // handle case where only the profile is supplied. Use all scopes by default if no scope args
      // are provided.
      if (parts.length == 1) {
        // add all scopes to enum set
        scopeEnumSet = EnumSet.allOf(IteratorScope.class);
      } else {
        // user provided scope arguments exist, parse them
        List<String> scopeArgs = Arrays.asList(parts[1].split(","));
        // there are only three allowable scope values
        if (scopeArgs.size() > 3)
          throw new IllegalArgumentException("Too many scope arguments supplied");
        // handle the 'all' argument separately since it is not an allowable enum value for
        // IteratorScope
        // if 'all' is used, it should be the only scope provided
        if (scopeArgs.contains("all")) {
          if (scopeArgs.size() > 1)
            throw new IllegalArgumentException("Cannot use 'all' in conjunction with other scopes");
          scopeEnumSet = EnumSet.allOf(IteratorScope.class);
        } else {
          // 'all' is not involved, examine the scope arguments and populate iterator scope EnumSet
          scopeEnumSet = validateScopes(scopeArgs);
        }
      }
      ntc.attachIterator(iteratorSetting, scopeEnumSet);
    }
    return ntc;
  }

  /**
   * Validate that the provided scope arguments are valid iterator scope settings. Checking for
   * duplicate entries and invalid scope values.
   *
   * Returns an EnumSet of scopes to be set.
   */
  private EnumSet<IteratorScope> validateScopes(final List<String> scopeList) {
    EnumSet<IteratorScope> scopes = EnumSet.noneOf(IteratorScope.class);
    for (String scopeStr : scopeList) {
      try {
        IteratorScope scope = IteratorScope.valueOf(scopeStr);
        if (!scopes.add(scope))
          throw new IllegalArgumentException("duplicate scope arguments found");
      } catch (IllegalArgumentException ex) {
        throw new IllegalArgumentException("illegal scope arguments: " + ex.getMessage(), ex);
      }
    }
    return scopes;
  }

  @Override
  public String description() {
    return "creates a new table, with optional aggregators, iterators, locality"
        + " groups and optionally pre-split";
  }

  @Override
  public String usage() {
    return getName() + " <tableName>";
  }

  @Override
  public Options getOptions() {
    final Options o = new Options();

    createTableOptCopyConfig =
        new Option("cc", "copy-config", true, "table to copy configuration from");
    createTableOptCopySplits =
        new Option("cs", "copy-splits", true, "table to copy current splits from");
    createTableOptSplit = new Option("sf", "splits-file", true,
        "file with a newline-separated list of rows to split the table with");
    createTableOptTimeLogical = new Option("tl", "time-logical", false, "use logical time");
    createTableOptTimeMillis = new Option("tm", "time-millis", false, "use time in milliseconds");
    createTableNoDefaultIters = new Option("ndi", "no-default-iterators", false,
        "prevent creation of the normal default iterator set");
    createTableOptEVC = new Option("evc", "enable-visibility-constraint", false,
        "prevent users from writing data they cannot read. When enabling this,"
            + " consider disabling bulk import and alter table.");
    createTableOptFormatter = new Option("f", "formatter", true, "default formatter to set");
    createTableOptInitProp =
        new Option("prop", "init-properties", true, "user defined initial properties");
    createTableOptCopyConfig.setArgName("table");
    createTableOptCopySplits.setArgName("table");
    createTableOptSplit.setArgName("filename");
    createTableOptFormatter.setArgName("className");
    createTableOptInitProp.setArgName("properties");

    createTableOptLocalityProps =
        new Option("l", "locality", true, "create locality groups at table creation");
    createTableOptLocalityProps.setArgName("group=col_fam[,col_fam]");
    createTableOptLocalityProps.setArgs(Option.UNLIMITED_VALUES);

    createTableOptIteratorProps = new Option("i", "iter", true,
        "initialize" + " iterator at table creation using profile. If no scope supplied, all"
            + " scopes are activated.");
    createTableOptIteratorProps.setArgName("profile[:[all]|[scan[,]][minc[,]][majc]]");
    createTableOptIteratorProps.setArgs(Option.UNLIMITED_VALUES);

    createTableOptOffline = new Option("o", "offline", false, "create table in offline mode");

    // Splits and CopySplits are put in an optionsgroup to make them
    // mutually exclusive
    final OptionGroup splitOrCopySplit = new OptionGroup();
    splitOrCopySplit.addOption(createTableOptSplit);
    splitOrCopySplit.addOption(createTableOptCopySplits);

    final OptionGroup timeGroup = new OptionGroup();
    timeGroup.addOption(createTableOptTimeLogical);
    timeGroup.addOption(createTableOptTimeMillis);

    base64Opt = new Option("b64", "base64encoded", false, "decode encoded split points");
    o.addOption(base64Opt);

    o.addOptionGroup(splitOrCopySplit);
    o.addOptionGroup(timeGroup);
    o.addOption(createTableOptSplit);
    o.addOption(createTableOptCopyConfig);
    o.addOption(createTableNoDefaultIters);
    o.addOption(createTableOptEVC);
    o.addOption(createTableOptFormatter);
    o.addOption(createTableOptInitProp);
    o.addOption(createTableOptLocalityProps);
    o.addOption(createTableOptIteratorProps);
    o.addOption(createTableOptOffline);

    return o;
  }

  @Override
  public int numArgs() {
    return 1;
  }

  @Override
  public void registerCompletion(final Token root,
      final Map<Command.CompletionSet,Set<String>> special) {
    registerCompletionForNamespaces(root, special);
  }
}


text:
<?php

namespace Dev42\Carrom\Core\SearchBundle\SearchEngine\Vehicle;

/**
 * Interface that says what is a basic color
 *
 * @author André Simões <sou@oand.re>
 */
interface VehicleColor {

    /**
     * Get vehicle color
     *
     * @return string
     */
    public function getName();

    /**
     * Set vehicle color
     *
     * @param string $color
     * @return self
     */
    public function setName($color);

}


text:
module ApplicationHelper

  def breadcrumbs(sep = "/", include_home = true)
     levels = request.path.split('?')[0].split('/')
     levels.delete_at(0)

     #links = "You are here: "
     links  = content_tag('a', "START", :href => root_path ) if include_home

     nocrumb = ["collections", "albums", "photos", "tags", "new", "edit", "tags"]

     levels.each_with_index do |level, index|
       level = level.gsub(/^[0-9]+\-/,"") #if levels[index-1] == "photos"
       level = level.gsub("-", " ")
       if index+1 == levels.length
         #links += " #{sep} #{level.upcase}" unless nocrumb.include?(level)
       elsif !nocrumb.include?(level)
         links += " " + sep + " "
         links += content_tag('a', level.upcase, :href => '/'+levels[0..index].join('/'))
       end
     end

     content_tag("div", links, :id => "breadcrumb")
   end
end


text:
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.

import { IDisposable } from '@lumino/disposable';
import { ISignal, Signal } from '@lumino/signaling';
import { IObservable } from './modeldb';

/**
 * A string which can be observed for changes.
 */
export interface IObservableString extends IDisposable, IObservable {
  /**
   * The type of the Observable.
   */
  type: 'String';

  /**
   * A signal emitted when the string has changed.
   */
  readonly changed: ISignal<this, IObservableString.IChangedArgs>;

  /**
   * The value of the string.
   */
  text: string;

  /**
   * Insert a substring.
   *
   * @param index - The starting index.
   *
   * @param text - The substring to insert.
   */
  insert(index: number, text: string): void;

  /**
   * Remove a substring.
   *
   * @param start - The starting index.
   *
   * @param end - The ending index.
   */
  remove(start: number, end: number): void;

  /**
   * Set the ObservableString to an empty string.
   */
  clear(): void;

  /**
   * Dispose of the resources held by the string.
   */
  dispose(): void;
}

/**
 * The namespace for `IObservableString` associate interfaces.
 */
export namespace IObservableString {
  /**
   * The change types which occur on an observable string.
   */
  export type ChangeType =
    /**
     * Text was inserted.
     */
    | 'insert'

    /**
     * Text was removed.
     */
    | 'remove'

    /**
     * Text was set.
     */
    | 'set';

  /**
   * The changed args object which is emitted by an observable string.
   */
  export interface IChangedArgs {
    /**
     * The type of change undergone by the list.
     */
    type: ChangeType;

    /**
     * The starting index of the change.
     */
    start: number;

    /**
     * The end index of the change.
     */
    end: number;

    /**
     * The value of the change.
     *
     * ### Notes
     * If `ChangeType` is `set`, then
     * this is the new value of the string.
     *
     * If `ChangeType` is `insert` this is
     * the value of the inserted string.
     *
     * If `ChangeType` is remove this is the
     * value of the removed substring.
     */
    value: string;
  }
}

/**
 * A concrete implementation of [[IObservableString]]
 */
export class ObservableString implements IObservableString {
  /**
   * Construct a new observable string.
   */
  constructor(initialText: string = '') {
    this._text = initialText;
  }

  /**
   * The type of the Observable.
   */
  get type(): 'String' {
    return 'String';
  }

  /**
   * A signal emitted when the string has changed.
   */
  get changed(): ISignal<this, IObservableString.IChangedArgs> {
    return this._changed;
  }

  /**
   * Set the value of the string.
   */
  set text(value: string) {
    if (value.length === this._text.length && value === this._text) {
      return;
    }
    this._text = value;
    this._changed.emit({
      type: 'set',
      start: 0,
      end: value.length,
      value: value
    });
  }

  /**
   * Get the value of the string.
   */
  get text(): string {
    return this._text;
  }

  /**
   * Insert a substring.
   *
   * @param index - The starting index.
   *
   * @param text - The substring to insert.
   */
  insert(index: number, text: string): void {
    this._text = this._text.slice(0, index) + text + this._text.slice(index);
    this._changed.emit({
      type: 'insert',
      start: index,
      end: index + text.length,
      value: text
    });
  }

  /**
   * Remove a substring.
   *
   * @param start - The starting index.
   *
   * @param end - The ending index.
   */
  remove(start: number, end: number): void {
    const oldValue: string = this._text.slice(start, end);
    this._text = this._text.slice(0, start) + this._text.slice(end);
    this._changed.emit({
      type: 'remove',
      start: start,
      end: end,
      value: oldValue
    });
  }

  /**
   * Set the ObservableString to an empty string.
   */
  clear(): void {
    this.text = '';
  }

  /**
   * Test whether the string has been disposed.
   */
  get isDisposed(): boolean {
    return this._isDisposed;
  }

  /**
   * Dispose of the resources held by the string.
   */
  dispose(): void {
    if (this._isDisposed) {
      return;
    }
    this._isDisposed = true;
    Signal.clearData(this);
    this.clear();
  }

  private _text = '';
  private _isDisposed: boolean = false;
  private _changed = new Signal<this, IObservableString.IChangedArgs>(this);
}


text:
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import *
from builtins import object
from past.utils import old_div
import math
import re
###########################################################
## Google map python wrapper V0.1

## Extended to allow for marker titels
##
############################################################

class maps(object):

	def __init__(self, centerLat, centerLng, zoom ):
		self.center = (float(centerLat),float(centerLng))
		self.zoom = int(zoom)
		self.grids = None
		self.paths = []
		self.points = []
		self.radpoints = []
		self.gridsetting = None
		self.coloricon = 'http://chart.apis.google.com/chart?cht=mm&chs=12x16&chco=FFFFFF,XXXXXX,000000&ext=.png'

	def setgrids(self,slat,elat,latin,slng,elng,lngin):
		self.gridsetting = [slat,elat,latin,slng,elng,lngin]

	def addpoint(self, lat, lng, color = '#FF0000', title=''):
		self.points.append((lat,lng,color[1:], title))
	#def addpointcoord(self, coord):
	#	self.points.append((coord[0],coord[1]))

	def addradpoint(self, lat,lng,rad,color = '#0000FF'):
		self.radpoints.append((lat,lng,rad,color, title))

	def addpath(self,path,color = '#FF0000', _id = ''):
		path.append(color)
		path.append(_id)
		self.paths.append(path)

	#create the html file which inlcude one google map and all points and paths
	def draw(self, htmlfile):
		f = open(htmlfile,'w')
		f.write('\n')
		f.write('\n')
		f.write('<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />\n')
		f.write('<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>\n')
		f.write('')
		f.write('<title>Google Maps - pygmaps </title>\n')
		f.write('')
		f.write('\n')
		f.write('\n')
		f.write('\n')
		f.write('\n')
		f.write('\n')
		f.write('\n')
		f.write('\t

\n')
		f.write('\n')
		f.write('\n')
		f.close()

	def drawgrids(self, f):
		if self.gridsetting == None:
			return
		slat = self.gridsetting[0]
		elat = self.gridsetting[1]
		latin = self.gridsetting[2]
		slng = self.gridsetting[3]
		elng = self.gridsetting[4]
		lngin = self.gridsetting[5]
		self.grids = []

		r = [slat+float(x)*latin for x in range(0, int(old_div((elat-slat),latin)))]
		for lat in r:
			self.grids.append([(lat+old_div(latin,2.0),slng+old_div(lngin,2.0)),(lat+old_div(latin,2.0),elng+old_div(lngin,2.0))])

		r = [slng+float(x)*lngin for x in range(0, int(old_div((elng-slng),lngin)))]
		for lng in r:
			self.grids.append([(slat+old_div(latin,2.0),lng+old_div(lngin,2.0)),(elat+old_div(latin,2.0),lng+old_div(lngin,2.0))])

		for line in self.grids:
			self.drawPolyline(f,line,strokeColor = "#000000")
	def drawpoints(self,f):
		for point in  self.points:
			self.drawpoint(f,point[0],point[1],point[2],point[3])

	def drawradpoints(self, f):
		for rpoint in self.radpoints:
			path = self.getcycle(rpoint[0:3])
			self.drawPolygon(f,path,strokeColor = rpoint[3])

	def getcycle(self,rpoint):
		cycle = []
		lat = rpoint[0]
		lng = rpoint[1]
		rad = rpoint[2] #unit: meter
		d = old_div((old_div(rad,1000.0)),6378.8);
		lat1 = (old_div(math.pi,180.0))* lat
		lng1 = (old_div(math.pi,180.0))* lng

		r = [x*30 for x in range(12)]
		for a in r:
			tc = (old_div(math.pi,180.0))*a;
			y = math.asin(math.sin(lat1)*math.cos(d)+math.cos(lat1)*math.sin(d)*math.cos(tc))
			dlng = math.atan2(math.sin(tc)*math.sin(d)*math.cos(lat1),math.cos(d)-math.sin(lat1)*math.sin(y))
			x = ((lng1-dlng+math.pi) % (2.0*math.pi)) - math.pi
			cycle.append( ( float(y*(old_div(180.0,math.pi))),float(x*(old_div(180.0,math.pi))) ) )
		return cycle

	def drawpaths(self, f, paths):
		c = 0
		for path in paths:
			#print path
			self.drawPolyline(f,path[:-2], strokeColor = path[-2], polylineLabel = path[-1])
			c += 1

	#############################################
	# # # # # # Low level Map Drawing # # # # # #
	#############################################

	def write_polyline_infowindow_js(self, f):
		f.write('function addPolylineInfoWindow(o, polylineLabel){var n=new google.maps.InfoWindow({content:""});eventPolygonMouseover=google.maps.event.addListener(o,"click",function(o){var e=new google.maps.Marker({position:o.latLng});console.log("fired"),n.setPosition(o.latLng),n.setContent(polylineLabel),n.open(map,e)})}')

	def write_marker_infowindow_js(self, f):
		f.write('function addMarkerInfoWindow(o, title){var n=new google.maps.InfoWindow({content: title});eventMarkerMouseover=google.maps.event.addListener(o,"click",function(){n.open(map,o)})}')

	def drawmap(self, f):
		f.write('\t\tvar centerlatlng = new google.maps.LatLng(%f, %f);\n' % (self.center[0],self.center[1]))
		f.write('\t\tvar myOptions = {\n')
		f.write('\t\t\tzoom: %d,\n' % (self.zoom))
		f.write('\t\t\tcenter: centerlatlng,\n')
		f.write('\t\t\tmapTypeId: google.maps.MapTypeId.ROADMAP\n')
		f.write('\t\t};\n')
		f.write('\t\tvar map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);\n')
		f.write('\n')

	def drawpoint(self,f,lat,lon,color, title=None):
		f.write('\t\tvar latlng = new google.maps.LatLng(%f, %f);\n'%(lat,lon))
		f.write('\t\tvar img = new google.maps.MarkerImage(\'%s\');\n' % (self.coloricon.replace('XXXXXX',color)))
		f.write('\t\tvar marker = new google.maps.Marker({\n')
		f.write('\t\tposition: latlng,\n')
		f.write('\t\tmap: map,\n')
		f.write('\t\ttitle: "'+re.escape(str(title))+'"\n')
		f.write('\t\t});\n')
		f.write('\n')
		if title is not None:
			f.write('addMarkerInfoWindow(marker,"' + title + '");\n\n')

	def drawPolyline(self,f,path,\
			clickable = True, \
			geodesic = True,\
			strokeColor = "#FF0000",\
			strokeOpacity = 1.0,\
			strokeWeight = 2,\
			polylineLabel = None
			):
		f.write('var PolylineCoordinates = [\n')
		for (i, coordinate) in enumerate(path):
			f.write('new google.maps.LatLng(%f, %f), // %d \n' % (coordinate[0],coordinate[1], i))
		f.write('];\n')
		f.write('\n')

		f.write('var Path = new google.maps.Polyline({\n')
		f.write('clickable: %s,\n' % (str(clickable).lower()))
		f.write('geodesic: %s,\n' % (str(geodesic).lower()))
		f.write('path: PolylineCoordinates,\n')
		f.write('strokeColor: "%s",\n' %(strokeColor))
		f.write('strokeOpacity: %f,\n' % (strokeOpacity))
		f.write('strokeWeight: %d\n' % (strokeWeight))
		f.write('});\n')
		f.write('\n')
		f.write('Path.setMap(map);\n')
		f.write('\n\n')
		if polylineLabel is not None:
			f.write('addPolylineInfoWindow(Path,"' + polylineLabel + '");\n\n')

	def drawPolygon(self,f,path,\
			clickable = False, \
			geodesic = True,\
			fillColor = "#000000",\
			fillOpacity = 0.0,\
			strokeColor = "#FF0000",\
			strokeOpacity = 1.0,\
			strokeWeight = 1
			):
		f.write('var coords = [\n')
		for coordinate in path:
			f.write('new google.maps.LatLng(%f, %f),\n' % (coordinate[0],coordinate[1]))
		f.write('];\n')
		f.write('\n')

		f.write('var polygon = new google.maps.Polygon({\n')
		f.write('clickable: %s,\n' % (str(clickable).lower()))
		f.write('geodesic: %s,\n' % (str(geodesic).lower()))
		f.write('fillColor: "%s",\n' %(fillColor))
		f.write('fillOpacity: %f,\n' % (fillOpacity))
		f.write('paths: coords,\n')
		f.write('strokeColor: "%s",\n' %(strokeColor))
		f.write('strokeOpacity: %f,\n' % (strokeOpacity))
		f.write('strokeWeight: %d\n' % (strokeWeight))
		f.write('});\n')
		f.write('\n')
		f.write('polygon.setMap(map);\n')
		f.write('\n\n')

if __name__ == "__main__":

	########## CONSTRUCTOR: pygmaps(latitude, longitude, zoom) ##############################
	# DESC:		initialize a map  with latitude and longitude of center point
	#		and map zoom level "15"
	# PARAMETER1:	latitude (float) latittude of map center point
	# PARAMETER2:	longitude (float) latittude of map center point
	# PARAMETER3:	zoom (int)  map zoom level 0~20
	# RETURN:	the instant of pygmaps
	#========================================================================================
	mymap = pygmaps(37.428, -122.145, 16)

	########## FUNCTION: setgrids(start-Lat, end-Lat, Lat-interval, start-Lng, end-Lng, Lng-interval) ######
	# DESC:		set grids on map
	# PARAMETER1:	start-Lat (float), start (minimum) latittude of the grids
	# PARAMETER2:	end-Lat (float), end (maximum) latittude of the grids
	# PARAMETER3:	Lat-interval (float)  grid size in latitude
	# PARAMETER4:	start-Lng (float), start (minimum) longitude of the grids
	# PARAMETER5:	end-Lng (float), end (maximum) longitude of the grids
	# PARAMETER6:	Lng-interval (float)  grid size in longitude
	# RETURN:	no returns
	#========================================================================================
	mymap.setgrids(37.42, 37.43, 0.001, -122.15, -122.14, 0.001)

	########## FUNCTION:  addpoint(latitude, longitude, [color])#############################
	# DESC:		add a point into a map and dispaly it, color is optional default is red
	# PARAMETER1:	latitude (float) latitude of the point
	# PARAMETER2:	longitude (float) longitude of the point
	# PARAMETER3:	color (string) color of the point showed in map, using HTML color code
	#		HTML COLOR CODE:  http://www.computerhope.com/htmcolor.htm
	#		e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00"
	# RETURN:	no return
	#========================================================================================
	mymap.addpoint(37.427, -122.145, "#0000FF")

	########## FUNCTION:  addradpoint(latitude, longitude, radius, [color])##################
	# DESC: 	add a point with a radius (Meter) - Draw cycle
	# PARAMETER1:	latitude (float) latitude of the point
	# PARAMETER2:	longitude (float) longitude of the point
	# PARAMETER3:	radius (float), radius  in meter
	# PARAMETER4:	color (string) color of the point showed in map, using HTML color code
	#		HTML COLOR CODE:  http://www.computerhope.com/htmcolor.htm
	#		e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00"
	# RETURN:	no return
	#========================================================================================
	mymap.addradpoint(37.429, -122.145, 95, "#FF0000")

	########## FUNCTION:  addpath(path,[color])##############################################
	# DESC:		add a path into map, the data struceture of Path is a list of points
	# PARAMETER1:	path (list of coordinates) e.g. [(lat1,lng1),(lat2,lng2),...]
	# PARAMETER2:	color (string) color of the point showed in map, using HTML color code
	#		HTML COLOR CODE:  http://www.computerhope.com/htmcolor.htm
	#		e.g. red "#FF0000", Blue "#0000FF", Green "#00FF00"
	# RETURN:	no return
	#========================================================================================
	path = [(37.429, -122.145),(37.428, -122.145),(37.427, -122.145),(37.427, -122.146),(37.427, -122.146)]
	mymap.addpath(path,"#00FF00")

	########## FUNCTION:  addpath(file)######################################################
	# DESC:		create the html map file (.html)
	# PARAMETER1:	file (string) the map path and file
	# RETURN:	no return, generate html file in specified directory
	#========================================================================================
	mymap.draw('./mymap.html')


text:
@implementation UIView (Frame_DQExt)

- (CGFloat)left_DQExt
{
    return self.frame.origin.x;
}

- (void)setLeft_DQExt:(CGFloat)left
{
    self.x_DQExt = left;
}

- (CGFloat)top_DQExt {
    return self.frame.origin.y;
}

- (void)setTop_DQExt:(CGFloat)top
{
    self.y_DQExt = top;
}

- (CGFloat)right_DQExt
{
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setRight_DQExt:(CGFloat)right
{
    self.x_DQExt = right - self.width_DQExt;
}

- (CGFloat)bottom_DQExt
{
    return self.frame.origin.y + self.frame.size.height;
}

- (void)setBottom_DQExt:(CGFloat)bottom
{
    self.y_DQExt = bottom - self.height_DQExt;
}

- (CGFloat)centerX_DQExt
{
    return self.center.x;
}

- (void)setCenterX_DQExt:(CGFloat)centerX
{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

- (CGFloat)centerY_DQExt
{
    return self.center.y;
}

- (void)setCenterY_DQExt:(CGFloat)centerY
{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

- (CGFloat)x_DQExt
{
    return self.frame.origin.x;
}

- (void)setX_DQExt:(CGFloat)x
{
    CGRect tempFrame = self.frame;
    tempFrame.origin.x = x;
    self.frame = tempFrame;
}

- (CGFloat)y_DQExt
{
    return self.frame.origin.y;
}

- (void)setY_DQExt:(CGFloat)y
{
    CGRect tempFrame = self.frame;
    tempFrame.origin.y  = y;
    self.frame = tempFrame;
}

- (CGFloat)width_DQExt
{
    return self.frame.size.width;
}

- (void)setWidth_DQExt:(CGFloat)width
{
    CGRect tempFrame = self.frame;
    tempFrame.size.width = width;
    self.frame = tempFrame;
}

- (CGFloat)height_DQExt
{
    return self.frame.size.height;
}

- (void)setHeight_DQExt:(CGFloat)height
{
    CGRect tempFrame = self.frame;
    tempFrame.size.height = height;
    self.frame = tempFrame;
}

- (CGPoint)orgin_DQExt
{
    return self.frame.origin;
}

- (void)setOrgin_DQExt:(CGPoint)orgin
{
    CGRect frame = self.frame;
    frame.origin = orgin;
    self.frame = frame;
}

- (CGSize)size_DQExt
{
    return self.frame.size;
}

- (void)setSize_DQExt:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (CGPoint)midPoint_DQExt
{
    return CGPointMake(self.width_DQExt * 0.5, self.height_DQExt * 0.5);
}

- (CGFloat)midX_DQExt
{
    return self.width_DQExt * 0.5;
}

- (CGFloat)midY_DQExt
{
    return self.height_DQExt * 0.5;
}

@end