text:
    Here we demonstrate more form editing improvements. Thanks again to Faserline  www.faserline.com

    In this demo:

    Navigation with up and down keys when in edit and view mode;

	submit the cahnges pressing the Enter key;

	check if something is changed in the form and ask the user to confirm. Try to change something in edit mode and submit.

Java Scrpt code
<XMP>
jQuery("#navgrid4").jqGrid({
   	url:'editing.php?q=1',
	datatype: "xml",
   	colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Closed','Ship via','Notes'],
   	colModel:[
   		{name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10}},
   		{name:'invdate',index:'invdate', width:80,
			editable:true,
			editoptions:{size:12,
				dataInit:function(el){
					$(el).datepicker({dateFormat:'yy-mm-dd'});
				},
				defaultValue: function(){
					var currentTime = new Date();
					var month = parseInt(currentTime.getMonth() + 1);
					month = month <= 9 ? "0"+month : month;
					var day = currentTime.getDate();
					day = day <= 9 ? "0"+day : day;
					var year = currentTime.getFullYear();
					return year+"-"+month + "-"+day;
				}
			},
			formoptions:{ rowpos:2, elmprefix:"(*)",elmsuffix:"  yyyy-mm-dd" },
			editrules:{required:true}
		},
   		{name:'name',index:'name', width:90,editable:true,editoptions:{size:25}, formoptions:{ rowpos:1, label: "Name", elmprefix:"(*)"},editrules:{required:true}},
   		{name:'amount',index:'amount', width:60, align:"right",editable:true,editoptions:{size:10}, formoptions:{ rowpos:5,elmprefix:"    "}},
   		{name:'tax',index:'tax', width:60, align:"right",editable:true,editoptions:{size:10},formoptions:{ rowpos:6,elmprefix:"    "}},
   		{name:'total',index:'total', width:60,align:"right",editable:true,editoptions:{size:10}, formoptions:{ rowpos:7,elmprefix:"    " }},
		{name:'closed',index:'closed',width:55,align:'center',editable:true,edittype:"checkbox",editoptions:{value:"Yes:No",defaultValue:"Yes"}, formoptions:{ rowpos:4,elmprefix:"    " }},
		{name:'ship_via',index:'ship_via',width:70,
			editable: true,
			edittype:"select",
			editoptions:{dataUrl:'test.txt', defaultValue:'Intime'},
			formoptions:{ rowpos:3,elmprefix:"    " }
		},
   		{name:'note',index:'note', width:100, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"20"}, formoptions:{ rowpos:8,elmprefix:"    " }}
   	],
   	rowNum:10,
   	rowList:[10,20,30],
   	pager: '#pagernav4',
   	sortname: 'id',
    viewrecords: true,
    sortorder: "desc",
    caption:"Navigator Example",
    editurl:"someurl.php",
	height:210
});
jQuery("#navgrid4").jqGrid('navGrid','#pagernav4',
{view:true}, //options
{jqModal:true,checkOnUpdate:true,savekey: [true,13], navkeys: [true,38,40], checkOnSubmit : true, reloadAfterSubmit:false, closeOnEscape:true, bottominfo:"Fields marked with (*) are required"}, // edit options
{jqModal:true,checkOnUpdate:true,savekey: [true,13], navkeys: [true,38,40], checkOnSubmit : true, reloadAfterSubmit:false, closeOnEscape:true,bottominfo:"Fields marked with (*) are required"}, // add options
{reloadAfterSubmit:false,jqModal:false, closeOnEscape:true}, // del options
{closeOnEscape:true}, // search options
{navkeys: [true,38,40], height:250,jqModal:false,closeOnEscape:true} // view options
);
</XMP>


text:
/**
 * CONGA handlebars helper plugins for AEM.
 */
package io.wcm.devops.conga.plugins.aem.handlebars.helper;

redpajama_set_name: RedPajamaGithub


text:
export default function getOwnPropertyDescriptors(O){
	let obj = ToObject(O);
	ReturnIfAbrupt(obj);
	let keys = obj[Symbol.for('[[OwnPropertyKeys]]')]();
	ReturnIfAbrupt(keys);
	let descriptors = ObjectCreate(ObjectPrototype);
	let gotAllNames = false;
	while(gotAllNames === false){
		let next = IteratorStep(keys);
		ReturnIfAbrupt(next);
		if(next === false) gotAllNames = true;
		else {
			let nextKey = IteratorValue(next);
			nextKey = ToPropertyKey(nextKey);
			ReturnIfAbrupt(nextKey);
			let desc = obj[Symbol.for('[[GetOwnProperty]]')](nextKey);
			ReturnIfAbrupt(desc);
			let descriptor = FromPropertyDescriptor(desc);
			ReturnIfAbrupt(descriptor);
			let status = CreateDataProperty(descriptors, nextKey, descriptor);
			Assert(status/*is not an abrupt completion*/);
		}
	}
	return descriptors;
}


text:
package com.smartlogic.ses.client;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;

import java.util.Map;

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

public class TestHintsXML extends SESServerMockTestCase {
  protected final Log logger = LogFactory.getLog(getClass());
  private static SESClient sesClient;

  @Override
  public void setUp() {
    wireMockRule.start();
    if (sesClient == null) {
      sesClient = ConfigUtil.getSESClient();
    }
  }

  @Override
  public void tearDown() {
    wireMockRule.stop();
  }

  public void testMarshal() throws Exception {
    wireMockRule.stubFor(
        get(urlEqualTo("/ses?TBDB=IPSV&template=service.xml&service=PREFIX&term_prefix=appo"))
            .willReturn(aResponse().withHeader("Content-Type", "text/xml")
                .withBody(readFileToString("src/test/resources/ses/sesResponsePrefixAppo.xml"))));

    Map<String, TermHint> termHints = sesClient.getTermHints("appo");

    XMLifier<TermHint> xmlifier = new XMLifier<>(TermHint.class);
    TermHint startTh = termHints.values().iterator().next();
    String savedXml = xmlifier.objectAsXML(startTh);
    TermHint newTh = xmlifier.objectFromXML(savedXml);

    assertEquals("Values arrays are not the same size", startTh.getValues().getValues().size(),
        newTh.getValues().getValues().size());
    assertEquals("Term IDs do not match", startTh.getId(), newTh.getId());
    assertEquals("Term names do not match", startTh.getName(), newTh.getName());
  }

  public void testUnmarshall() throws Exception {
    XMLifier<TermHint> xmlifier = new XMLifier<>(TermHint.class);
    TermHint termHint =
        xmlifier.objectFromXML(readFileToString("src/test/resources/ses/termHintSerialized.xml"));

    assertEquals("TermHint values", "intments procedure",
        termHint.getValues().getValues().get(0).getPostEm());
  }

}


text:
<?php

namespace App\Http\Controllers\Admin\Flat;

use App\Models\Flat;
use Illuminate\Http\Request;
use App\Queries\SearchFlats;
use App\Http\Controllers\Controller;
use App\Jobs\Flat\{CreateFlat, DeleteFlat, UpdateFlat};
use App\Http\Requests\{CreateFlatRequest, UpdateFlatRequest};

class FlatController extends Controller
{
    public function __construct()
    {
        $this->middleware('admin.auth');
    }

    public function index()
    {
        $search = request('search');
        $flats = $search ? SearchFlats::get($search) : Flat::feedPaginated();

        return view('admin.flats.index', compact('flats', 'search'));
    }

    public function create()
    {
        return view('admin.flats.create');
    }

    public function store(CreateFlatRequest $request)
    {
        $this->dispatchNow(CreateFlat::fromRequest($request));
        $this->success('flat.created');

        return redirect()->route('admin.flats.index');
    }

    public function edit(Flat $flat)
    {
        return view('admin.flats.edit', compact('flat'));
    }

    public function update(Flat $flat, UpdateFlatRequest $request)
    {
        $this->dispatchNow(UpdateFlat::fromRequest($flat, $request));
        $this->success('flat.updated');

        return redirect()->route('admin.flats.index');
    }

    public function delete(Flat $flat)
    {
        $this->dispatchNow(new DeleteFlat($flat));
        $this->success('flat.deleted');

        return redirect()->route('admin.flats.index');
    }
}


text:
package org.arabidopsis.ahocorasick;

import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import org.testng.annotations.Test;

/**
 * Quick and dirty code: measures the amount of time it takes to construct an AhoCorasick tree out of all the words in
 * <tt>/usr/share/dict/words</tt>.
 */
public class TestTimeTrial {
    @Test(timeOut = 10000)
    public void timeTrial() throws IOException {
        long startTime = System.currentTimeMillis();
        AhoCorasick tree = new AhoCorasick();
        BufferedReader reader = new BufferedReader
                (new InputStreamReader(new FileInputStream("/usr/share/dict/words")));
        String line;
        while ((line = reader.readLine()) != null) {
            tree.add(line, null);
        }
        tree.prepare();
        long endTime = System.currentTimeMillis();
        System.out.println("endTime - startTime = " + (endTime - startTime) + " milliseconds");
    }
}


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\UserBundle\Event;

use Sylius\Component\User\Model\UserInterface;
use Symfony\Component\EventDispatcher\Event;

/** @psalm-suppress DeprecatedClass */
class UserEvent extends Event
{
    /** @var UserInterface */
    private $user;

    public function __construct(UserInterface $user)
    {
        $this->user = $user;
    }

    public function getUser(): UserInterface
    {
        return $this->user;
    }
}


text:
import Phaser   from '../../helper/phaser-helper';
import {gridMap} from '../../helper/math-helper';

export default class SpriteGrid extends Phaser.Group {
    constructor(game, x, y, n, m, cellWidth, cellHeight, SpriteClass) {
        super(game);
        this.addMultiple(gridMap(n, m, i => j => {
            const cellX = x + cellWidth  * i;
            const cellY = y + cellHeight * j;
            const frame = SpriteClass.FrameMap(i, j);
            return new SpriteClass(this.game, cellX, cellY, frame);
        }));
    }
}


text:
<!--- Copyright 2002-2014 CS Systèmes d'Information
  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.
-->

Integration in other languages
==============================

The Orekit library can be accessed from other languages, for integration into existing
software or for quick prototyping in a scripting language such as Jython, Python or
Matlab. This allows for direct interaction with the different objects, either from a
script or directly at the command prompt, and quick access to plotting tools.

[Integration in Jython](./integration-in-Jython.html)
[Integration in Matlab](./integration-in-Matlab.html)
[Integration in Python (external link to Orekit forge)](https://www.orekit.org/forge/projects/orekit-python-wrapper/wiki)


text:
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * Smarty Class
 *
 * @package		CodeIgniter
 * @subpackage	Libraries
 * @category	Smarty
 * @author		Kepler Gelotte
 * @link		http://www.coolphptools.com/codeigniter-smarty
 */
 //注意这个地方的路径必须能够找到和你的Smarty安装路径一致
require_once( BASEPATH.'libs/smarty/libs/Smarty.class.php' );

class CI_Smarty extends Smarty {

	function CI_Smarty()
	{
		parent::Smarty();

		$this->compile_dir = APPPATH . "views/templates_c";
		$this->template_dir = APPPATH . "views/templates";
		//如下四行是配置config和cache目录,还有模板的起止标志
		$this->config_dir = APPPATH . "config";
		$this->cache_dir = APPPATH . "cache";
		$this->left_delimiter = "{";
		$this->right_delimiter = "}";

		$this->assign( 'APPPATH', APPPATH );
		$this->assign( 'BASEPATH', BASEPATH );

		log_message('debug', "Smarty Class Initialized");
	}

	function __construct()
	{
		parent::__construct();

		$this->compile_dir = APPPATH . "views/templates_c";
		$this->template_dir = APPPATH . "views/templates";
		//如下四行是配置config和cache目录,还有模板的起止标志
		$this->config_dir = APPPATH . "config";
		$this->cache_dir = APPPATH . "cache";
		$this->left_delimiter = "{";
		$this->right_delimiter = "}";
		$this->assign( 'APPPATH', APPPATH );
		$this->assign( 'BASEPATH', BASEPATH );

		// Assign CodeIgniter object by reference to CI
		if ( method_exists( $this, 'assignByRef') )
		{
			$ci =& get_instance();
			$this->assignByRef("ci", $ci);
		}

		log_message('debug', "Smarty Class Initialized");
	}

	/**
	 *  Parse a template using the Smarty engine
	 *
	 * This is a convenience method that combines assign() and
	 * display() into one step.
	 *
	 * Values to assign are passed in an associative array of
	 * name => value pairs.
	 *
	 * If the output is to be returned as a string to the caller
	 * instead of being output, pass true as the third parameter.
	 *
	 * @access	public
	 * @param	string
	 * @param	array
	 * @param	bool
	 * @return	string
	 */
	function view($template, $data = array(), $return = FALSE)
	{
		foreach ($data as $key => $val)
		{
			$this->assign($key, $val);
		}

		if ($return == FALSE)
		{
			$CI =& get_instance();
			if (method_exists( $CI->output, 'set_output' ))
			{
				$CI->output->set_output( $this->fetch($template) );
			}
			else
			{
				$CI->output->final_output = $this->fetch($template);
			}
			return;
		}
		else
		{
			return $this->fetch($template);
		}
	}
}
// END Smarty Class


text:
import Ice
Ice.updateModule("dried_ice")

# Modules:
import DI_hello_world_ice

# Submodules:
import example


text:
package org.apache.isis.viewer.html.image;

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

import org.apache.isis.core.commons.lang.Resources;

public class ImageProviderResourceBased extends ImageProviderAbstract {

    /**
     * Is an array since easy to maintain
     */
    public final static String[] DEFAULT_LOCATIONS = { "images", "src/main/resources", "src/main/java" };

    /**
     * Is a list since easy to inject.
     */
    private List<String> locations = new ArrayList<String>();

    /**
     * Initializes {@link #locations} with {@link #DEFAULT_LOCATIONS}, but can
     * be overridden using {@link #setLocations(List)}.
     */
    public ImageProviderResourceBased() {
        locations.addAll(Arrays.asList(DEFAULT_LOCATIONS));
    }

    @Override
    protected String findImage(final String className, final String[] extensions) {

        for (final String location : locations) {
            for (final String extension : extensions) {
                final String candidate = location + "/" + className + "." + extension;
                if (Resources.getResourceAsFile(candidate) != null) {
                    return candidate;
                }
            }
        }
        return null;
    }

    /**
     * Optionally inject the locations where the provider will search.
     *
     * <p>
     * If not specified, will use the locations in {@link #DEFAULT_LOCATIONS}.
     */
    public void setLocations(final List<String> locations) {
        this.locations = locations;
    }

}


text:
title: Developer Documentation
---

This part of Spree's documentation covers the technical aspects of Spree. If you're building a Spree store, this is the documentation for you.

## Where to start?

The best place to start is the [Getting Started guide](/developer/getting_started/installation.html).

## I want to learn how Spree works

This wisdom can be found reading [Internals section](/developer/internals/).

## I want to customize my Spree Store

You will find all the required information in the [Customization section](/developer/customization/storefront.html).

## I want to contribute to Spree

Awesome! Please see [Contributing](/developer/contributing/) for details.


text:
<!--- This file is automatically generated by make gen-cli-docs; changes should be made in the go CLI command code (under cmd/kops) -->

## kops toolbox bundle

Bundle cluster information

### Synopsis

Creates a bundle for enrolling a bare metal machine.

```
kops toolbox bundle [flags]
```

### Examples

```
  # Bundle
  kops toolbox bundle --name k8s-cluster.example.com
```

### Options

```
  -h, --help            help for bundle
      --target string   machine to target (IP address)
```

### Options inherited from parent commands

```
      --alsologtostderr                  log to standard error as well as files
      --config string                    config file (default is $HOME/.kops.yaml)
      --log_backtrace_at traceLocation   when logging hits line file:N, emit a stack trace (default :0)
      --log_dir string                   If non-empty, write log files in this directory
      --logtostderr                      log to standard error instead of files (default false)
      --name string                      Name of cluster. Overrides KOPS_CLUSTER_NAME environment variable
      --state string                     Location of state storage. Overrides KOPS_STATE_STORE environment variable
      --stderrthreshold severity         logs at or above this threshold go to stderr (default 2)
  -v, --v Level                          log level for V logs
      --vmodule moduleSpec               comma-separated list of pattern=N settings for file-filtered logging
```

### SEE ALSO

* [kops toolbox](kops_toolbox.md)	 - Misc infrequently used commands.


text:
MEMBER_FETCH {
  SELECT Id, Name, IsActive, DispositionFK  FROM Member WHERE Id=?
}

MEMBER_LIST {
  SELECT Id, Name, IsActive, DispositionFK FROM Member ORDER BY Name
}

MEMBER_ADD {
  INSERT INTO Member(Name, IsActive, DispositionFK) VALUES (?,?,?)
}

MEMBER_CHANGE {
  UPDATE Member SET Name=?, IsActive=?, DispositionFK=? WHERE Id=?
}

MEMBER_DELETE {
  DELETE FROM Member WHERE Id=?
}

COUNT_ACTIVE_MEMBERS {
  SELECT COUNT(*) FROM Member WHERE IsActive=1
}


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v1.0.5-master-437a308
 */md-sidenav.md-THEME_NAME-theme{background-color:'{{background-color}}'}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/chromeos_camera/dmabuf_utils.h"

#include <unistd.h>

#include <utility>

#include "base/files/scoped_file.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/time/time.h"
#include "media/base/color_plane_layout.h"
#include "media/base/video_frame.h"
#include "media/base/video_frame_layout.h"
#include "media/gpu/buffer_validation.h"
#include "mojo/public/cpp/system/platform_handle.h"
#include "ui/gfx/geometry/rect.h"

namespace chromeos_camera {

bool VerifyMjpegBufferHandle(const gfx::GpuMemoryBufferHandle& gmb_handle) {
  if (gmb_handle.native_pixmap_handle.planes[0].offset != 0u) {
    DLOG(ERROR) << "Invalid DMA buf plane offset";
    return false;
  }
  // For MJPEG, we expect the byte size to be at least as large as the stride
  // (see b/142105578).
  if (base::strict_cast<uint64_t>(
          gmb_handle.native_pixmap_handle.planes[0].stride) >
      gmb_handle.native_pixmap_handle.planes[0].size) {
    DLOG(ERROR) << "Invalid DMA buf plane stride or size";
    return false;
  }
  const auto dma_buf_fd = gmb_handle.native_pixmap_handle.planes[0].fd.get();
  const off_t data_size = lseek(dma_buf_fd, /*offset=*/0, SEEK_END);
  if (data_size == static_cast<off_t>(-1)) {
    PLOG(ERROR) << "Failed to get the size of the dma-buf";
    return false;
  }
  if (lseek(dma_buf_fd, /*offset=*/0, SEEK_SET) == static_cast<off_t>(-1)) {
    PLOG(ERROR) << "Failed to reset the file offset of the dma-buf";
    return false;
  }
  if (!base::IsValueInRangeForNumericType<uint64_t>(data_size) ||
      base::checked_cast<uint64_t>(data_size) <
          gmb_handle.native_pixmap_handle.planes[0].size) {
    DLOG(ERROR) << "Invalid DMA buf plane size";
    return false;
  }
  return true;
}

scoped_refptr<media::VideoFrame> ConstructVideoFrame(
    std::vector<mojom::DmaBufPlanePtr> dma_buf_planes,
    media::VideoPixelFormat pixel_format,
    const gfx::Size& coded_size) {
  const size_t num_planes = media::VideoFrame::NumPlanes(pixel_format);
  if (num_planes != dma_buf_planes.size()) {
    DLOG(ERROR) << "The number of DMA buf planes does not match the format";
    return nullptr;
  }
  if (coded_size.IsEmpty()) {
    DLOG(ERROR) << "Invalid coded size: " << coded_size.width() << ", "
                << coded_size.height();
    return nullptr;
  }
  const gfx::Rect visible_rect(coded_size);

  gfx::GpuMemoryBufferHandle gmb_handle;
  gmb_handle.type = gfx::GpuMemoryBufferType::NATIVE_PIXMAP;
  gmb_handle.native_pixmap_handle.planes.resize(num_planes);
  for (size_t i = 0; i < num_planes; ++i) {
    mojo::PlatformHandle handle =
        mojo::UnwrapPlatformHandle(std::move(dma_buf_planes[i]->fd_handle));
    if (!handle.is_valid()) {
      DLOG(ERROR) << "Invalid DMA buf file descriptor";
      return nullptr;
    }
    if (dma_buf_planes[i]->stride <= 0) {
      DLOG(ERROR) << "Invalid DMA buf stride";
      return nullptr;
    }
    gmb_handle.native_pixmap_handle.planes[i].stride =
        base::checked_cast<uint32_t>(dma_buf_planes[i]->stride);
    gmb_handle.native_pixmap_handle.planes[i].offset =
        base::strict_cast<uint64_t>(dma_buf_planes[i]->offset);
    gmb_handle.native_pixmap_handle.planes[i].size =
        base::strict_cast<uint64_t>(dma_buf_planes[i]->size);
    gmb_handle.native_pixmap_handle.planes[i].fd = handle.TakeFD();
  }
  if (pixel_format == media::PIXEL_FORMAT_MJPEG) {
    if (!VerifyMjpegBufferHandle(gmb_handle)) {
      return nullptr;
    }
  } else {
    if (!media::VerifyGpuMemoryBufferHandle(pixel_format, coded_size,
                                            gmb_handle)) {
      return nullptr;
    }
  }

  std::vector<base::ScopedFD> dma_buf_fds(num_planes);
  std::vector<media::ColorPlaneLayout> planes(num_planes);
  for (size_t i = 0; i < num_planes; ++i) {
    dma_buf_fds[i] = std::move(gmb_handle.native_pixmap_handle.planes[i].fd);
    planes[i] = media::ColorPlaneLayout(
        dma_buf_planes[i]->stride,
        base::strict_cast<size_t>(dma_buf_planes[i]->offset),
        base::strict_cast<size_t>(dma_buf_planes[i]->size));
  }
  const absl::optional<media::VideoFrameLayout> layout =
      media::VideoFrameLayout::CreateWithPlanes(pixel_format, coded_size,
                                                std::move(planes));
  if (!layout) {
    DLOG(ERROR) << "Failed to create video frame layout";
    return nullptr;
  }

  return media::VideoFrame::WrapExternalDmabufs(
      *layout,                 // layout
      visible_rect,            // visible_rect
      coded_size,              // natural_size
      std::move(dma_buf_fds),  // dmabuf_fds
      base::TimeDelta());      // timestamp
}

}  // namespace chromeos_camera


text:
from twitter import *

import cmath

# create twitter API object
consumer_key = "O5Z1KINSBaDEQgTBB3FA"
consumer_secret = "kf42pzVoDrmP4hoe9LNQW5t765J2zEspqdHQhotw"
access_key = "2172397754-TrCNJSgVarJIMnYb6uLXFzfI76zI7m8cfy5zIvL"
access_secret = "FNiDwwbgs0WiElgaJ2hVECnsyavUKIQ3IP7JNr4BkiOhx"

# create twitter API object
auth = OAuth(access_key, access_secret, consumer_key, consumer_secret)
twitter = Twitter(auth = auth)

# request my home timeline
# twitter API docs: https://dev.twitter.com/docs/api/1/get/statuses/home_timeline
statuses = twitter.statuses.home_timeline(count = 50)

# loop through each of my statuses, and print its content
# for status in statuses:
# 	print "(%s) @%s %s" % (status["created_at"], status["user"]["screen_name"], status["text"])
#

# query = twitter.search.tweets(geocode = "51.474144,-0.035401")

#query = twitter.search.tweets(geocode = "38.95,-92.33,1mi")
#tweets = []
#for result in query["statuses"]:
#    print "(%s) @%s %s" % (result["created_at"], result["id"], result["geo"])
#    tweets.append(result)

def tweetsFromGeo(latitude, longitude, radius="1m"):
    geocode = "%s,%s,%s" % (latitude, longitude, radius)
    query = twitter.search.tweets(geocode = "38.95,-92.33,1mi", count=50)
    tweets = []
    for result in query["statuses"]:
        tweets.append(result)
    return tweets

if __name__ == "__main__":

    latitude = float("38.95")
    longitude = float("-92.33")
    tweets = tweetsFromGeo(latitude, longitude)

    data = []

    for tweet in tweets:
        if tweet["geo"] is None:
            continue
        coords = tweet["geo"]["coordinates"]
        dx = latitude-coords[0]
        dy = longitude-coords[1]
        comp = complex(dx*69, dy*69)
        p = cmath.polar(comp)
        polar = [int(p[0]*100),p[1]]
        tweet =	{
            "id":tweet["id"],
            "text":tweet["text"],
            "source":tweet["source"],
            "user":	{
                "id":tweet["user"]["id"],
                "screen_name":tweet["user"]["screen_name"],
                "profile_image_url":tweet["user"]["profile_image_url"]
                },
            "polar":polar
            }
        data.append(tweet)

    print data


text:
var invaders = function(game) {
   Phaser.State.call(this);
}

invaders.prototype = Object.create(Phaser.State);
invaders.prototype.constructor = invaders;

invaders.prototype = {
   // {{{ INIT
   init: function(config) {
      var self = this;
      console.log("Running the game...");
      console.log(self.config);

      // Others
      difficulty = config.difficulty;
      currentDifficulty = config.difficulty;

      $('body, footer, .nav-wrapper, .footer-copyright').removeClass('blue');
      $('body, footer, .nav-wrapper, .footer-copyright').removeClass('green');
      $('body, footer, .nav-wrapper, .footer-copyright').removeClass('yellow');
      $('body, footer, .nav-wrapper, .footer-copyright').removeClass('red');
      $('body, footer, .nav-wrapper, .footer-copyright').removeClass('black');
      $('body, footer, .nav-wrapper, .footer-copyright').removeClass('toto');

      if (difficulty == OHGOD) {
            $('body, footer, .nav-wrapper, .footer-copyright').toggleClass('red');
      }

      self.current_level = config.current_level;
      self.current_bonus_level = config.current_bonus_level;
      self.in_bonus_level = config.is_bonus;
      self.in_boss_level = config.is_boss;
      self.score = config.score;
      self.lives = 1;
      self.coins = 0;
      self.power = config.power;
      self.cooldown_reduction = config.cooldown_reduction;
      self.init_x = config.init_x;
      self.init_y = config.init_y;
      self.special_available = config.special_available;

      ENEMY_DEFAULT_FIRE_PROBA = 0.004 + difficulty*0.0015;
      POWERUP_CHANCE = 0.05 - difficulty*0.01;
      POWERUP_CHANCE_IN_BONUS = 2*POWERUP_CHANCE;
      COINS_FOR_POWERUP = 50 + difficulty*25;
      MAX_POWER = (difficulty < OHGOD ? 7 : 5);

      console.log("DIFFICULTY = " + difficulty);
      console.log("FIRE PROBA = " + ENEMY_DEFAULT_FIRE_PROBA);
      console.log("POWERUP CHANCE = " + POWERUP_CHANCE);
      console.log("IN BONUS = " + POWERUP_CHANCE_IN_BONUS);
      console.log("COIN CHANCE = " + COIN_CHANCE);
      console.log("IN BONUS = " + COIN_CHANCE_IN_BONUS);
      console.log("COINS FOR BONUS = " + COINS_FOR_POWERUP);
      console.log("MAX POWER = " + MAX_POWER);

      self.READY = false;
   },
   // }}}
   // {{{ CREATE
   create: function() {
      var self = this;
      //Create the background

      self.background = game.add.tileSprite(0, 0, game.width, game.height, 'space');
      self.background.tint = (difficulty == OHGOD ? 0xff1111 : 0x3355ee);

      // Weapons
      self.weapons = [];

      //Audio
      self.mute = false;
      self.gameoversound = true;
      self.introduction_sound = true;

      self.left = false;
      self.lostAlife = false;
      self.mute_wait = 0;
      self.just_end_bonus = false;
      self.wait_next_level = true;
      self.clear_nofiretime = 0;
      self.shield_time = 0;
      self.shots_cooldown = 0;
      self.special_cooldown = 0;

      self.explosions = self.game.add.group();
      self.explosions.enableBody = true;

      self.enemies = self.game.add.physicsGroup();

      self.bonusships = self.game.add.group();
      self.bonusships.enableBody = true;

      self.items = self.game.add.group();
      self.items.enableBody = true;

      self.shield = self.game.add.sprite(0, 0, 'shield');
      self.shield.anchor.setTo(0.5, 0.5);
      self.shield.smoothed = false;

      self.scorePool = 0;
      self.game.scorePoolTimer = self.game.time.events;
      self.game.scorePoolTimer.loop(10, function() {
         self.scorePoolNotRunning = false;
         self.scorePool -= 25;
         self.score += 25;
      }, self);
      self.game.scorePoolTimer.stop(false);
      self.scorePoolNotRunning = true;

      // Weapons
      self.weapons.push(self.game.add.existing(new Weapon1B(self)));
      self.weapons.push(self.game.add.existing(new Weapon2B(self)));
      self.weapons.push(self.game.add.existing(new Weapon3B(self)));
      self.weapons.push(self.game.add.existing(new Weapon4B(self)));
      self.weapons.push(self.game.add.existing(new Weapon5B(self)));
      self.weapons.push(self.game.add.existing(new Weapon6B(self)));
      self.weapons.push(self.game.add.existing(new Weapon7B(self)));

      //Create the player's ship
      console.log("\tCreating player...");
      self.createPlayer();
      console.log("\t-*- Player created -*-");
      self.game.camera.follow(self.player);

      self.player.addChild(self.shield);

      //All inputs
      self.cursors = self.game.input.keyboard.createCursorKeys();
      self.fire_btn = self.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
      self.special_btn = self.game.input.keyboard.addKey(Phaser.Keyboard.SHIFT);
      self.mute_btn = self.game.input.keyboard.addKey(Phaser.Keyboard.M);
      self.pause_btn = self.game.input.keyboard.addKey(Phaser.Keyboard.P);
      self.restart_btn = self.game.input.keyboard.addKey(Phaser.Keyboard.R);

      //mute_btn.onUp.add(muteGame, self)
      self.pause_btn.onDown.add(self.pauseGame, self);

      //Ingame Text
      var style_white = {font: '32px Minecraftia', fill:'#ffffff'};
      var style_blue  = {font: '16px Minecraftia', fill:'#00aaff'};
      var style_blue_small  = {font: '12px Minecraftia', fill:'#00aaff'};
      var style_green  = {font: '16px Minecraftia', fill:'#44ff44'};
      var style_yellow  = {font: '16px Minecraftia', fill:'#ffee00'};

      self.text_middle = self.game.add.text(self.game.world.width/2, self.game.world.height/2, '', style_white);
      self.text_middle.fixedToCamera = true;
      self.text_middle.anchor.setTo(0.5);

      self.text_pause = self.game.add.text(self.game.world.width/2, self.game.world.height/1.5, '', style_white);
      self.text_pause.fixedToCamera = true;
      self.text_pause.anchor.setTo(0.5);
      //self.text_pause.alpha = 0;

      self.text_hint = self.game.add.text(self.game.world.width/2, self.game.world.height - 100, '', style_blue_small);
      self.text_hint.fixedToCamera = true;
      self.text_hint.anchor.setTo(0.5);
      self.text_hint.alpha = 0;

      self.text_score = self.game.add.text(16, 5, '', style_blue);
      self.text_score.fixedToCamera = true;

      self.text_lives = self.game.add.text(48, 42, self.lives, style_blue);
      self.text_lives.anchor.setTo(0.5);
      self.text_lives.smoothed = false;

      self.text_power = self.game.add.text(92, 42, self.power, style_blue);
      self.text_power.anchor.setTo(0.5);
      self.text_power.smoothed = false;

      self.text_coold = self.game.add.text(136, 42, self.cooldown_reduction, style_blue);
      self.text_coold.anchor.setTo(0.5);
      self.text_coold.smoothed = false;

      self.text_specs = self.game.add.text(180, 42, self.special_available, style_blue);
      self.text_specs.anchor.setTo(0.5);
      self.text_specs.smoothed = false;

      self.game.add.sprite(20, 29, 'powerups', 12);
      self.game.add.sprite(64, 29, 'powerups', 39);
      self.game.add.sprite(108, 29, 'powerups', 7);
      self.game.add.sprite(152, 29, 'powerups', 27);

      self.text_level = self.game.add.text(self.game.world.width/2, game.world.height/2 + 40, '', style_blue);
      self.text_level.fixedToCamera = true;
      self.text_level.anchor.setTo(0.5);

      self.text_ship = self.game.add.text(self.player.body.x - 20, self.player.body.y-20, '', style_green);
      self.text_ship.anchor.setTo(0.5);
      self.text_ship.alpha = 0;

      self.text_coin = self.game.add.text(self.player.body.x, self.player.body.y-20, '', style_yellow);
      self.text_coin.anchor.setTo(0.5);
      self.text_coin.alpha = 0;

      if (difficulty < OHGOD) {
         self.music = self.game.add.audio('ambient');
      } else {
         self.music = self.game.add.audio('ambient_ohgod');
      }
      self.music.loop = true;

      self.music_boss = self.game.add.audio('boss');
      self.music_boss.loop = true;

      self.music_bonus = self.game.add.audio('bonus_loop');
      self.music_bonus.loop = true;

      if (!self.mute && !self.music.isPlaying){
         self.music.play();
      }

      //Create all sounds
      self.pickup_sd = self.game.add.audio('pickup');
      self.pickup_sd.volume = 0.5;
      self.pickupcoin_sd = self.game.add.audio('pickup_coin');
      self.pickupcoin_sd.volume = 0.5;
      self.hellyeah_sd = self.game.add.audio('hellyeah');
      self.playerhit_sd = self.game.add.audio('explode');
      self.hitenemy_sd = self.game.add.audio('hitenemy');
      self.hitenemy_sd.volume = 0.1;
      self.killenemy_sd = self.game.add.audio('killenemy');
      self.killenemy_sd.volume = 0.1;
      self.fire_sd = self.game.add.audio('fire');
      self.fire_sd.volume = 0.1;
      self.firespecial_sd = self.game.add.audio('firespecial');
      self.firespecial_sd.volume = 0.1;
      self.enemyfire_sd = self.game.add.audio('enemyfire');
      self.enemyfire_sd.volume = 0.1;
      self.wave_sd = self.game.add.audio('wave');
      self.intro_sd = self.game.add.audio('intro');
      self.win_sd = self.game.add.audio('win');
      self.gameover_sd = self.game.add.audio('gameover');

      self.speed = START_SPEED;
      self.speedup = SPEEDUP_INIT;
      self.accel = SPEEDUP_ACCEL;

      console.log("\tLoading level " + self.current_level + " ...");
      self.text_level.fill = '#00aaff';
      self.text_middle.text = "ARE YOU READY ?";

      self.text_middle.alpha = 0;
      self.text_level.alpha = 0;

      self.game.add.tween(self.text_middle).to( { alpha: 1 }, 1000, Phaser.Easing.Quadratic.In, true);
      self.game.add.tween(self.text_level).to( { alpha: 1 }, 1000, Phaser.Easing.Quadratic.In, true);

      self.wait_next_level = true;
      self.timer = game.time.create(true);
      self.timer.add(3000, function(){
         self.game.add.tween(self.text_middle).to( { alpha: 0 }, 1000, Phaser.Easing.Quadratic.Out, true);
         self.game.add.tween(self.text_level).to( { alpha: 0 }, 1000, Phaser.Easing.Quadratic.Out, true);
         self.game.add.tween(self.text_hint).to( { alpha: 0 }, 1000, Phaser.Easing.Quadratic.In, true);
         console.log("\tCreating enemies...");
         self.createEnemies(levels[0], 10, 10);
         //self.createEnemies(self.only(101)); //DO NOT UNCOMMENT THIS I BEG YOU
         console.log("\t-*- Enemies created -*-");
         self.wait_next_level = false;
      });
      self.timer.start();

         //Set a delay for the bonus ship to come (15 to 40 secs)
         //if (!self.in_boss_level) {
            var delayForBonus = Math.random()*25*1000 + 15000;
            self.bonusShip(delayForBonus);
         //}      console.log("\t-*- Level loaded -*-");
      self.enemies.setAll('body.velocity.x', self.speed);

      //self.game.saveCpu.renderOnFPS = 60;
      self.READY = true;
   },

   // }}}
   // {{{ UPDATE
   update: function() {
      var self = this;
      if (self.READY) {
         if (currentDifficulty != difficulty) {
            currentDifficulty = difficulty;
            self.restart(self.current_level);
         }

         if (self.scorePool > 0 && self.scorePoolNotRunning)
            self.game.scorePoolTimer.start(1);
         else if (self.scorePool == 0) {
            self.game.scorePoolTimer.stop(false);
            self.scorePoolNotRunning = true;
         }

         //Check collisions for everything
         self.game.physics.arcade.collide(self.weapon, self.enemies, self.hitEnemy, null, self);
         self.game.physics.arcade.collide(self.player, self.enemies, self.playerHit, function() {return self.shield_time == 0 && !self.lostAlife;}, self);

         self.text_score.text = 'Niveau ' + (self.current_level+1) + '    Score: ' + ('000000000' + Math.round(self.score)).slice(-10);

         //self.text_stats.text = '        ' + self.lives + '        ' + self.power + '        '+ self.cooldown_reduction + '        ' + self.special_available;
         self.text_lives.text = self.lives;
         self.text_specs.fill = (self.lives > 1 ? '#00aaff' : '#ff0000');

         self.text_power.text = self.power;
         self.text_power.fill = (self.power == MAX_POWER ? '#ffff00' : '#00aaff');

         self.text_coold.text = self.cooldown_reduction;
         self.text_coold.fill = (self.cooldown_reduction == MAX_CDR ? '#ffff00' : '#00aaff');

         self.text_specs.text = self.special_available;
         self.text_specs.fill = (self.special_available > 0 ? '#00aaff' : '#aaaaaa');

         //background.tilePosition.y += current_level/5 + 1;
         self.background.tilePosition.y += 1 + (14*self.in_bonus_level); //FIXME

         //All controls are disabled when the player dies
         if (!self.lostAlife) {
            //Mute button
            if (self.mute_btn.isDown) {
               if (self.mute_wait == 0) {
                  self.muteGame();
               }
            };

            //Control the player
            self.player.body.velocity.x = 0;
            self.player.body.velocity.y = 0;
            //if (!player.touched) {
            //player.body.velocity.y = 0;
            //};
            if (self.cursors.up.isDown && difficulty < OHGOD) {
               self.player.body.velocity.y = -PLAYER_SPEED;
               self.player.body.velocity.x = 0;
               //player.animations.play('left');
            } else if (self.cursors.down.isDown  && difficulty < OHGOD) {
               self.player.body.velocity.y = PLAYER_SPEED;
               self.player.body.velocity.x = 0;
               //player.animations.play('right');
            }

            if (self.cursors.left.isDown) {
               self.player.body.velocity.x = -PLAYER_SPEED;
               //player.body.velocity.y = 0;
               self.player.animations.play('left');
            } else if (self.cursors.right.isDown) {
               self.player.body.velocity.x = PLAYER_SPEED;
               //player.body.velocity.y = 0;
               self.player.animations.play('right');
            } else if (!self.lostAlife) {
               self.player.animations.play('idle');
            }

            //Fire shots
            if (self.fire_btn.isDown) {
               self.weapon.fire(self.player);
            }

            //Fire super special shots
            if (self.special_btn.isDown) {
               if (self.special_available > 0 && self.special_cooldown === 0) {
                  self.weapon.fireSpecial(self.player);
                  self.special_available--;
                  self.special_cooldown = 100;
               }
            }

            //Shield decay over time
            if (self.shield_time > 0) {
               self.shield_time--;
            } else {
               self.shield_time = 0;
            }
            self.shield.alpha = Math.min(self.shield_time/60.0, 0.75); //Fade the shield sprite with time

            //When a clear powerup is collected, enemies can't fire for a while
            if (self.clear_nofiretime > 0) {
               self.clear_nofiretime--;
            } else {
               self.clear_nofiretime = 0;
            }

            if (self.shots_cooldown > 0) {
               self.shots_cooldown--;
            } else {
               self.shots_cooldown = 0;
            }

            if (self.special_cooldown > 0) {
               self.special_cooldown--;
            } else {
               self.special_cooldown = 0;
            }

         } else {
            //When the player dies
            //console.log("DEAD ?");
            self.player.body.velocity.x = 0;
            self.player.animations.play('dead');
            //enemies.setAll('body.velocity.x', 0);
            if (self.lives == 0) {
               if (self.restart_btn.isDown) {
                  //self.restart(0);
                  self.music.stop();
                  self.music_boss.stop();
                  self.gameover_sd.stop(); // FIXME
                  this.game.stateTransition.to("GameTitle", true, false);
               }
            }
         };

         if (self.mute_wait > 0) {
            self.mute_wait--;
         } else {
            self.mute_wait = 0;
         }

         //Move the enemies
         self.enemies.forEachAlive(function(enemy){
            if (self.left) {
               self.enemies.setAll('body.velocity.x', -self.speed);
            } else {
               self.enemies.setAll('body.velocity.x', self.speed);
            }
            if (enemy.body.position.x < 10) {
               self.left = false;
               if (!self.in_boss_level) {
                  self.enemies.addAll('body.position.x', 10);
                  self.enemies.addAll('body.position.y', enemy.body.height);
               }
            } else if (enemy.body.position.x >= self.game.world.width - 25) {
               self.left = true;
               if (!self.in_boss_level) {
                  self.enemies.addAll('body.position.x', -10);
                  self.enemies.addAll('body.position.y', enemy.body.height);
               }
            }
            if (enemy.position.y > self.game.world.height && !self.in_boss_level) {
               self.levelFailed();
            }
         });

         //When the level is beaten
         self.living_e_shots = 0;
         self.enemies.forEach(function(e, cpt) {
            self.living_e_shots += e.livingShots();
         }, self);

         if (self.enemies.countLiving() < 10 && self.enemies.length > 0) {
           //pop more enemies
           self.speed /= 2;
           self.createEnemies([[1,2,3,4,5,6,7,8,9,10]], 200, 0);
           console.log("aadfobfqob")
         }

         self.explosions.forEachAlive(function(expl) {
            //game.debug.body(expl);
            if (expl.alpha < 0.2) {
               expl.kill();
            }
         });

         self.bonusships.forEachAlive(function(bship) {
            if (bship.x > self.game.world.height + bship.body.width*2 || bship.x < -bship.body.width*2) {
               bship.outOfBounds = true;
               bship.kill();
            }
         });
      }
   },
   // }}}

   // {{{ CREATEPLAYER
   createPlayer: function() {
      var self = this;
      self.player = self.game.add.sprite(self.init_x,self.init_y,'ship');
      self.game.physics.arcade.enable(self.player);

      self.player.body.collideWorldBounds = true;
      self.player.body.immovable = false;
      self.lostAlife = false;
      self.touched = false;

      self.player.anchor.setTo(0.5,0.5);

      self.player.animations.add('idle', [0,1],6,true);
      self.player.animations.add('left', [2,3],6,true);
      self.player.animations.add('right', [4,5],6,true);
      self.player.animations.add('dead', [6],6,true);

      self.weapon = self.weapons[self.power-1];
   },
   // }}}

   // {{{ LOADLEVEL
   // Load a level and its enemies
   // }}}

   // {{{ PAUSEGAME
   pauseGame: function() {
      var self = this;
      if (self.lives > 0) {
         if (!self.game.paused) {
            console.log("\tGame paused !");
            if (!self.mute) {
               self.pickupcoin_sd.play();
            }
            self.text_pause.alpha = 1;
            self.text_pause.text = "PAUSE";
            self.game.paused = true;
            self.music.pause();
            self.music_boss.pause();
         } else {
            console.log("\tGame resumed !");
            self.text_pause.alpha = 0;
            self.text_pause.text = "";
            self.game.paused = false;
            if (!self.mute) {
               self.pickupcoin_sd.play();
               if (self.in_boss_level) {
                  self.music_boss.resume();
               } else {
                  self.music.resume();
               }
            }
         }
      }
   },
   // }}}

   // {{{ BONUSSHIP
   // Prepares a bonus ship to appear after 'delay' seconds
   bonusShip: function(delay) {
      var self = this;
      console.log('\tbonus ship dans %.2f s',delay/1000);

      self.timer = self.game.time.create(true);
      self.timer.add(delay, function(){
         var bship = self.bonusships.getFirstDead();
         var x = -6;

         if (bship === null || bship === undefined) {
            bship = new BonusShip(self, x, 15, 'bonusship', 0, 1000, 10, [0,1,2,3], 12);
            self.bonusships.add(bship);
         }
         else{
            bship.revive();
            bship.outOfBounds = false;
            bship.reset(x, 15);
            if (Math.random() < 0.5) {
               bship.x = -16;
               bship.body.velocity.x = 90;
            } else {
               bship.x = game.world.width + 7;
               bship.body.velocity.x = -90;
            }
         }
      });
      self.timer.start();
   },
   // }}}

   // {{{ CREATEENEMIES
   // Creates an array of enemies at a set position
   createEnemies: function(array, x, y) {
      var self = this;
      for (var i = 0; i < array.length; i++) {
         for (var j = 0; j < array[i].length; j++) {
            if (array[i][j] > 0) {
               var xx = x+j*25;
               var yy = y+i*25;

               switch (array[i][j]) {
                  default:
                     break;
                  case 1: //ORANGE : normal
                     if (difficulty == OHGOD)
                        self.enemies.add(new Green(self, xx, yy, 'enemy'));
                     else
                        self.enemies.add(new Orange(self, xx, yy, 'enemy'));
                     break;
                  case 2: //RED : fires multiple shots
                     if (difficulty == OHGOD)
                        self.enemies.add(new DarkRed(self, xx, yy, 'enemy'));
                     else
                        self.enemies.add(new Red(self, xx, yy, 'enemy'));
                     break;
                  case 3: //GREEN : fires fast shots
                     if (difficulty == OHGOD)
                        self.enemies.add(new DarkGreen(self, xx, yy, 'enemy'));
                     else
                        self.enemies.add(new Green(self, xx, yy, 'enemy'));
                     break;
                  case 4: //PURPLE : fires twice as often
                     self.enemies.add(new Purple(self, xx, yy, 'enemy'));
                     break;
                  case 5: //GRAY : takes 2 hits
                     self.enemies.add(new Gray(self, xx, yy, 'enemy'));
                     break;
                  case 6: //YELLOW : Fires 5 shots when killed
                     self.enemies.add(new Yellow(self, xx, yy, 'enemy'));
                     break;
                  case 7: //CYAN : fires gravity-affected shots
                     self.enemies.add(new Cyan(self, xx, yy, 'enemy'));
                     break;
                  case 8: //PINK : takes 3 hits, fires more often
                     self.enemies.add(new Pink(self, xx, yy, 'enemy'));
                     break;
                  case 9: //BLUE : fires in random directions
                     self.enemies.add(new Blue(self, xx, yy, 'enemy'));
                     break;
                  case 10: //BROWN : explodes when killed
                     self.enemies.add(new Brown(self, xx, yy, 'enemy'));
                     break;
                  case 11: //DARK GREEN : Fires REALLY FAST shots
                     self.enemies.add(new DarkGreen(self, xx, yy, 'enemy'));
                     break;
                  case 12: //DARK RED : Fires in a circle
                     self.enemies.add(new DarkRed(self, xx, yy, 'enemy'));
                     break;
                  case 13: //BLACK : Sometimes moves down when firing
                     self.enemies.add(new Black(self, xx, yy, 'enemy'));
                     break;
                  case 14: //WHITE : COMING SOON
                     self.enemies.add(new White(self, xx, yy, 'enemy'));
                     break;
                  case 15: //DARK CYAN : Fires revolving shots
                     self.enemies.add(new DarkCyan(self, xx, yy, 'enemy'));
                     break;
                  case 16: //MAGENTA : Fires growing shots, takes 2 hits
                     self.enemies.add(new Magenta(self, xx, yy, 'enemy'));
                     break;
                  case 101: // OTTERFUCKER !!! BOSS #1
                     self.enemies.add(new Boulimique(self, xx, yy, 'boulimique'));
                     break;
                  case 102: // OTTERFUCKER !!! BOSS #2
                     self.enemies.add(new GrosSac(self, xx, yy, 'boulimique'));
                     break
               }
            }
         }
      }
      self.enemies.forEachAlive(function(e) {
         if (e.body.y < 10) {
            game.add.tween(e).to( {y: 100}, 1500, Phaser.Easing.Quadratic.Out, true);
         }
      });
      self.game.world.bringToTop(self.enemies);
   },
   // }}}

   // {{{ HITENEMY
   // When an enemy is hit by a player shot or an explosion
   hitEnemy: function(shot, enemy) {
      var self = this;
      var amount = shot.power;

      if (shot.key != 'explosion')  {
         shot.kill();
      }

      enemy.damage(amount);

      if (enemy.alive && !self.mute) {
         self.hitenemy_sd.play();
      }
   },
   // }}}

   // {{{ CREATEEXPLOSION
   // Generates an explosion at the given coordinates
   createExplosion: function(x,y, pow, rad=40) {
      var self = this;
      var expl = self.explosions.getFirstDead();
      if (expl === null || expl == undefined) {
         expl = self.game.add.sprite(x, y, 'explosion');
         self.explosions.add(expl);
      }
      else {
         expl.revive();
         expl.reset(x,y);
      }
      expl.alpha = 1;
      expl.scale.setTo(1);
      expl.power = pow;
      self.game.physics.arcade.enable(expl);
      expl.anchor.setTo(0.5);
      expl.smoothed = false;
      expl.body.immovable = true;
      expl.checkWorldBounds = true;
      expl.outOfBoundsKill = true;
      if (!self.mute) {
         self.playerhit_sd.play();
      }
      self.enemies.forEachAlive( function(e, rad) {
         if (self.game.physics.arcade.distanceBetween(expl, e) < rad) {
            self.hitEnemy(expl, e);
         }
      }, self, rad);
      self.game.add.tween(expl).to( { alpha: 0}, 2000, Phaser.Easing.Quintic.Out, true);
      self.game.add.tween(expl.scale).to( {x: 2, y: 2 }, 1500, Phaser.Easing.Quintic.Out, true);
   },
   // }}}

   // {{{ PLAYERHIT
   // When the player is hit by enemy fire or an enemy
   playerHit: function(player, shot) {
      var self = this;
      shot.kill();
      if (!self.lostAlife && !player.touched && !self.shield_time) {
         console.log("TOUCHÉ !!!");
         self.playerhit_sd.play();
         self.lostAlife = true;
         player.touched = true;
         player.body.collideWorldBounds = false;
         player.body.velocity.y = 125;
         self.createExplosion(player.body.center.x, player.body.center.y, 20);
         //var tween_death = game.add.tween(player.body).to( { y: game.world.height+10 }, 1000, Phaser.Easing.Linear.None, true);

         if (!self.in_bonus_level) {
            //Player stats are halved
            if (difficulty == EASY) {
               if (self.power > 2) {
                  self.power /= 2;
                  self.power = Math.ceil(self.power);
               }
               else {
                  self.power = 2;
               }
            } else {
               if (self.power > 1) {
                  self.power /= 2;
                  self.power = Math.floor(self.power);
               }
            }
            self.weapon = self.weapons[self.power-1];

            if (self.cooldown_reduction > 0) {
               self.cooldown_reduction /= 2;
               self.cooldown_reduction = Math.floor(self.cooldown_reduction);
               self.weapon.fireRate = self.weapon.baseFireRate * (1-self.cooldown_reduction/100.0);
            }
            self.special_available = 1;
            self.coins /= 2;
            self.coins = Math.floor(self.coins);
            self.lives--;

            if (self.lives > 0) {
               self.timer = self.game.time.create(true);
               self.timer.add(1500, function(){
                  player.body.collideWorldBounds = true;
                  //player.y = 550;
                  console.log("replace player");
                  self.game.add.tween(player.body).to( { y: 600 }, 500, Phaser.Easing.Quadratic.In, true);
                  self.lostAlife = false;
                  self.shield_time = 180;
                  player.addChild(self.shield);
                  self.shield.anchor.setTo(0.5, 0.5);
                  self.shield.smoothed = false;
               });
               self.timer.add(3000, function(){
                  player.touched = false;
               });
               self.timer.start();
            } else { //GAME OVER
               self.gameOver();
            }
         } else {
            //If you die in a bonus level, no penalty
            self.timer = self.game.time.create(true);
            self.timer.add(1500, function(){
               player.body.collideWorldBounds = true;
               self.game.add.tween(player.body).to( { y: 600 }, 500, Phaser.Easing.Quadratic.In, true);
               self.lostAlife = false;
               self.enemies.removeAll(true);
               self.current_bonus_level--;
            });
            self.timer.add(3000, function(){
               player.touched = false;
            });
            self.timer.start();
         }
      }
   },
   // }}}

   // {{{ LEVELFAILED
   // When the level is failed by letting enemies go too low
   levelFailed: function() {
      var self = this;
      if (!self.lostAlife) {
         self.playerhit_sd.play();
         self.lostAlife = true;
         self.player.touched = true;
         self.player.body.collideWorldBounds = false;
         self.player.body.velocity.y = 125;
         self.createExplosion(self.player.body.center.x, self.player.body.center.y, 20);
         //var tween_death = game.add.tween(player.body).to( { y: game.world.height+10 }, 1000, Phaser.Easing.Linear.None, true);

         self.lives--;
         if (difficulty == EASY) {
            if (self.power > 2) {
               self.power /= 2;
               self.power = Math.ceil(self.power);
            }
         } else {
            if (self.power > 1) {
               self.power /= 2;
               self.power = Math.floor(self.power);
            }
         }
         if (self.cooldown_reduction > 0) {
            self.cooldown_reduction /= 2;
            self.cooldown_reduction = Math.floor(self.cooldown_reduction);
            self.weapon.fireRate = self.weapon.baseFireRate * (1-self.cooldown_reduction/100.0);
         }
         self.special_available = 1;
         self.coins /= 2;
         self.coins = Math.floor(self.coins);
         self.current_level--;

         if (self.lives > 0) {
            self.timer = self.game.time.create(true);
            self.timer.add(3000, function(){
               self.player.body.collideWorldBounds = true;
               self.enemies.removeAll(true);
               self.lostAlife = false;
               self.player.alpha = 0.5;
            });
            self.timer.add(4000, function(){
               self.player.touched = false;
               self.player.alpha = 1;
               self.shield_time = 240;
            });
            self.timer.start();
         } else { //GAME OVER
            self.gameOver();
         }
      }
   },
   // }}}

   gameOver: function() {
      var self = this;

      self.text_middle.alpha = 1;
      self.text_middle.text = 'GAME OVER';
      self.text_level.alpha = 1;
      self.text_level.text = 'Presser R pour recommencer';
      self.music.stop();
      self.music_boss.stop();
      self.music_bonus.stop();
      self.gameover_sd.play();

      //this.game.state.start("GameOver");
   },

   // {{{ MUTEGAME
   muteGame: function() {
      var self = this;
      if (!self.mute) {
         self.mute = true;
         self.music.pause()
            self.music_bonus.pause();
      } else {
         self.mute = false;
         if (self.in_bonus_level) {
            self.music_bonus.resume();
         } else {
            self.music.resume();
         }
      }

      console.log('mute is ' + self.mute);
      self.mute_wait = 30;
   },
   // }}}

   // {{{ ONLYN
   // Generates a level with only one type of enemy
   only: function(n) {
      return [[0,0,n,n,n,n,n,n,0,0],
      [0,n,n,n,n,n,n,n,n,0],
      [n,n,n,n,n,n,n,n,n,n],
      [n,n,n,n,n,n,n,n,n,n]];

   },
   // }}}

   // {{{ RESTART
   // Restarts the game from zero
   restart: function(level) {
      var self = this;
      self.items.removeAll();
      self.bonusships.removeAll();
      self.enemies.removeAll(true);
      self.player.kill();
      self.music.stop();;
      self.music_boss.stop();
      self.music_bonus.stop();
      var config = {
         is_boss: false,
         is_bonus: false,
         score: 0,
         lives: 3,
         power: self.difficulty == EASY ? 2 : 1,
         init_x: 300,
         init_y: 600,
         difficulty: self.difficulty,
         current_level: 0,
         special_available: 1,
         cooldown_reduction: 0,
         current_bonus_level: 0,
      };
      this.game.state.start("Game", true, false, config);
   },
   // }}}

   givePoints: function(amount) { //GROS WIP
      var self = this;
      self.scorePool += amount;
   }
}


text:
'use strict';

/**
 * @ngdoc service
 * @name Agenda
 * @description
 * # Agenda
 * Factory in the mission-control app.
 */
angular.module('mission-control')
  .factory('Agenda', function ($resource, SSE_API_URLS) {
    return $resource(SSE_API_URLS.base + SSE_API_URLS.agenda);
  });


text:
class AddFirstConfirmationReminderSentToUsers < ActiveRecord::Migration
  def change
    add_column :users, :first_confirmation_reminder_sent, :boolean, null: false, default: false
    add_index :users, [:confirmed_at, :confirmation_sent_at, :first_confirmation_reminder_sent, :invitation_sent_at], name: 'index_users_on_first_reminder_fields'
  end
end


text:
[![npm version](https://img.shields.io/npm/v/primer-marketing.svg)](https://www.npmjs.org/package/primer-marketing)
[![Build Status](https://travis-ci.org/primer/primer.svg?branch=master)](https://travis-ci.org/primer/primer)

> Primer marketing is one of 3 meta-packages that belong to the Primer framework. Primer marketing contains packages that are used on GitHub marketing websites.

This repository is a compilation of [several CSS packages](https://github.com/primer/primer). You can break it down into smaller sections using npm.

## Install

This repository is distributed with [npm][npm]. After [installing npm][install-npm], you can install `primer` with this command. **You must have npm >=3.0 installed to be able to satisfy the dependency paths**

```
$ npm install --save primer-marketing
```

## Usage

The source files included are written in [Sass][sass] (`scss`) You can simply point your sass `include-path` at your `node_modules` directory and import it like this.

```scss
@import "primer-marketing/index.scss";
```

You can also import specific portions of the module by importing those partials from the `/lib/` folder. _Make sure you import any requirements along with the modules._

## Build

For a compiled **css** version of this module, a npm script is included that will output a CSS version to `build/build.css` The built CSS file is also included in the npm package.

```
$ npm run build
```

## Documentation

You can read more about primer in the [docs][docs].

## License

[MIT](./LICENSE) © [GitHub](https://github.com/)

[primer]: https://github.com/primer/primer
[docs]: http://primer.github.io/
[npm]: https://www.npmjs.com/
[install-npm]: https://docs.npmjs.com/getting-started/installing-node
[sass]: http://sass-lang.com/


text:
package it.fadeout.omirl.business.config;

import java.util.ArrayList;

import it.fadeout.omirl.viewmodels.SensorLink;

public class SensorLinkConfig {
	String code;
	String description;
	String imageLinkOn;
	String imageLinkOff;
	String imageLinkInv;
	int count;
	String legendLink;
	String mesUnit;
	String filePath;
	String columnName;
	boolean isVisible = true;
	boolean isClickable = true;
	private ArrayList<LegendStepConfig> legends = new ArrayList<LegendStepConfig>();
	int accessLevel;

	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getImageLinkOn() {
		return imageLinkOn;
	}
	public void setImageLinkOn(String imageLinkOn) {
		this.imageLinkOn = imageLinkOn;
	}
	public String getImageLinkOff() {
		return imageLinkOff;
	}
	public void setImageLinkOff(String imageLinkOff) {
		this.imageLinkOff = imageLinkOff;
	}
	public String getImageLinkInv() {
		return imageLinkInv;
	}
	public void setImageLinkInv(String imageLinkInv) {
		this.imageLinkInv = imageLinkInv;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public String getLegendLink() {
		return legendLink;
	}
	public void setLegendLink(String legendLink) {
		this.legendLink = legendLink;
	}
	public String getMesUnit() {
		return mesUnit;
	}
	public void setMesUnit(String mesUnit) {
		this.mesUnit = mesUnit;
	}

	public String getFilePath() {
		return filePath;
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	public String getColumnName() {
		return columnName;
	}
	public void setColumnName(String columnName) {
		this.columnName = columnName;
	}

	public SensorLink getSensorLink() {
		SensorLink oSensorLink = new SensorLink();
		oSensorLink.setActive(false);
		oSensorLink.setCode(code);
		oSensorLink.setCount(count);
		oSensorLink.setDescription(description);
		oSensorLink.setImageLinkInv(imageLinkInv);
		oSensorLink.setImageLinkOff(imageLinkOff);
		oSensorLink.setImageLinkOn(imageLinkOn);
		oSensorLink.setLegendLink(legendLink);
		oSensorLink.setMesUnit(mesUnit);
		oSensorLink.setClickable(isClickable);
		oSensorLink.setVisible(isVisible);
		oSensorLink.setLegends(legends);
		return oSensorLink;
	}
	public boolean getIsVisible() {
		return isVisible;
	}
	public void setIsVisible(boolean isVisible) {
		this.isVisible = isVisible;
	}
	public boolean getIsClickable() {
		return isClickable;
	}
	public void setIsClickable(boolean isClickable) {
		this.isClickable = isClickable;
	}
	public ArrayList<LegendStepConfig> getLegends() {
		return legends;
	}
	public void setLegends(ArrayList<LegendStepConfig> legends) {
		this.legends = legends;
	}
	public int getAccessLevel() {
		return accessLevel;
	}
	public void setAccessLevel(int accessLevel) {
		this.accessLevel = accessLevel;
	}
	public void setVisible(boolean isVisible) {
		this.isVisible = isVisible;
	}
	public void setClickable(boolean isClickable) {
		this.isClickable = isClickable;
	}

}


text:
L.Util.extend(L.LineUtil, {

	/**
	 * Snap to all layers
	 *
	 * @param <Latlng> latlng - original position
	 * @param <Number> id - leaflet unique id
	 * @param <Object> opts - snapping options
	 *
	 * @return <Latlng> closest point
	*/
	snapToLayers: function (latlng, id, opts) {
		var i, j, keys, feature, res, sensitivity, vertexonly, layers, minDist, minPoint, map;

		sensitivity = opts.sensitivity || 10;
		vertexonly = opts.vertexonly || false;
		layers = opts.layers || [];
		minDist = Infinity;
		minPoint = latlng;
		minPoint._feature = null; // containing layer

    if (!opts || !opts.layers || !opts.layers.length) {
      return minPoint;
    }

		map = opts.layers[0]._map; // @todo check for undef

		for (i = 0; i < opts.layers.length; i++) {
			keys = Object.keys(opts.layers[i]._layers);
			for (j = 0; j < keys.length; j++) {
				feature = opts.layers[i]._layers[keys[j]];

				// Don't even try snapping to itself!
				if (id === feature._leaflet_id) { continue; }

				// GeometryCollection
				if (feature._layers) {
					var newLatlng = this.snapToLayers(latlng, id, {
						'sensitivity': sensitivity,
						'vertexonly': vertexonly,
						'layers': [feature]
					});
					// What if this is the same?
					res = {'minDist': latlng.distanceTo(newLatlng), 'minPoint': newLatlng};

				// Marker
        } else if (feature instanceof L.Marker) {
					res = this._snapToLatlngs(latlng, [feature.getLatLng()], map, sensitivity, vertexonly, minDist);

				// Polyline
				} else if (feature instanceof L.Polyline) {
					res = this._snapToLatlngs(latlng, feature.getLatLngs(), map, sensitivity, vertexonly, minDist);

				// MultiPolyline
				} else if (feature instanceof L.MultiPolyline) {
					console.error('Snapping to MultiPolyline is currently unsupported', feature);
					res = {'minDist': minDist, 'minPoint': minPoint};

				// Polygon
				} else if (feature instanceof L.Polygon) {
					res = this._snapToPolygon(latlng, feature, map, sensitivity, vertexonly, minDist);

				// MultiPolygon
				} else if (feature instanceof L.MultiPolygon) {
					res = this._snapToMultiPolygon(latlng, feature, map, sensitivity, vertexonly, minDist);

				// Unknown
				} else {
					console.error('Unsupported snapping feature', feature);
					res = {'minDist': minDist, 'minPoint': minPoint};
				}

				if (res.minDist < minDist) {
					minDist = res.minDist;
					minPoint = res.minPoint;
					minPoint._feature = feature;
				}

			}
		}

		return minPoint;
	},

	/**
	 * Snap to Polygon
	 *
	 * @param <Latlng> latlng - original position
	 * @param <L.Polygon> feature -
	 * @param <L.Map> map -
	 * @param <Number> sensitivity -
	 * @param <Boolean> vertexonly -
	 * @param <Number> minDist -
	 *
	 * @return <Object> minDist and minPoint
	*/
	_snapToPolygon: function (latlng, polygon, map, sensitivity, vertexonly, minDist) {
		var res, keys, latlngs, i, minPoint;

		minPoint = null;

		latlngs = polygon.getLatLngs();
		latlngs.push(latlngs[0]);
		res = this._snapToLatlngs(latlng, polygon.getLatLngs(), map, sensitivity, vertexonly, minDist);
		if (res.minDist < minDist) {
			minDist = res.minDist;
			minPoint = res.minPoint;
		}

		keys = Object.keys(polygon._holes);
		for (i = 0; i < keys.length; i++) {
			latlngs = polygon._holes[keys[i]];
			latlngs.push(latlngs[0]);
			res = this._snapToLatlngs(latlng, polygon._holes[keys[i]], map, sensitivity, vertexonly, minDist);
			if (res.minDist < minDist) {
				minDist = res.minDist;
				minPoint = res.minPoint;
			}
		}

		return {'minDist': minDist, 'minPoint': minPoint};
	},

	/**
	 * Snap to MultiPolygon
	 *
	 * @param <Latlng> latlng - original position
	 * @param <L.Polygon> feature -
	 * @param <L.Map> map -
	 * @param <Number> sensitivity -
	 * @param <Boolean> vertexonly -
	 * @param <Number> minDist -
	 *
	 * @return <Object> minDist and minPoint
	*/
	_snapToMultiPolygon: function (latlng, multipolygon, map, sensitivity, vertexonly, minDist) {
		var i, keys, res, minPoint;

		minPoint = null;

		keys = Object.keys(multipolygon._layers);
		for (i = 0; i < keys.length; i++) {
			res = this._snapToPolygon(latlng, multipolygon._layers[keys[i]], map, sensitivity, vertexonly, minDist);

			if (res.minDist < minDist) {
				minDist = res.minDist;
				minPoint = res.minPoint;
			}
		}

		return {'minDist': minDist, 'minPoint': minPoint};
	},

	/**
	 * Snap to <Array> of <Latlang>
	 *
	 * @param <LatLng> latlng - cursor click
	 * @param <Array> latlngs - array of <L.LatLngs> to snap to
	 * @param <Object> opts - snapping options
	 * @param <Boolean> isPolygon - if feature is a polygon
	 *
	 * @return <Object> minDist and minPoint
	*/
	_snapToLatlngs: function (latlng, latlngs, map, sensitivity, vertexonly, minDist) {
		var i, tmpDist, minPoint, p, p1, p2, d2;

		p = map.latLngToLayerPoint(latlng);
		p1 = minPoint = null;

		for (i = 0; i < latlngs.length; i++) {
			p2 = map.latLngToLayerPoint(latlngs[i]);

			if (!vertexonly && p1 !== null) {
				tmpDist = L.LineUtil.pointToSegmentDistance(p, p1, p2);
				if (tmpDist < minDist && tmpDist <= sensitivity) {
					minDist = tmpDist;
					minPoint = map.layerPointToLatLng(L.LineUtil.closestPointOnSegment(p, p1, p2));
				}
			} else if ((d2 = p.distanceTo(p2)) && d2 <= sensitivity && d2 < minDist) {
				minDist = d2;
				minPoint = latlngs[i];
			}

			p1 = p2;
		}

		return {'minDist': minDist, 'minPoint': minPoint};
	}

});


text:
Course Section Search (Proxy)

<form method="get" action="section.json">
{% include 'proxy/sws/student/v5/includes/term.html' %}
{% include 'proxy/sws/student/v5/includes/course.html' %}
{% include 'proxy/sws/student/v5/includes/reg_id.html' %}

<input class="search_by" id="search_by_instructor" name="search_by" value="Instructor" checked="checked" type="radio">
Instructor
<input class="search_by" id="search_by_delegate" name="search_by" value="GradeSubmissionDelegate" type="radio">
Grade Submission Delegate

Include secondary sections: <input class="include_secondaries" id="include_secondaries" name="include_secondaries" type="checkbox">

Delete flag: <input class="delete_flag" id="delete_flag" name="delete_flag" value="{{search.delete_flag}}" size="15" type="text">

{% include 'proxy/sws/student/v5/includes/page_size.html' %}
<input value="Search" type="submit">
</form>


text:
class SendAdminFinancials
  include Sidekiq::Worker
  sidekiq_options unique: :until_executed

  def perform(type, *args)
    send(type.to_sym, *args)
  end

  def daily
    time = Time.now.yesterday.beginning_of_day
    date_str = time.strftime("#{ActiveSupport::Inflector.ordinalize(time.day)} %B %Y")

    signups        = scope(User, time).to_a.count
    invoice_totals = scope(Invoice, time).to_a.sum(&:total_cost)
    wallet_charges = scope(Charge, time).where('source_type = ? OR source_type = ?', 'CreditNote', 'PaymentReceipt').to_a.sum(&:amount)
    cc_charges = scope(PaymentReceipt, time).where(pay_source: :billing_card).to_a.sum(&:net_cost)
    paypal_charges = scope(PaymentReceipt, time).where(pay_source: :paypal).to_a.sum(&:net_cost)
    manual_credits = scope(CreditNote, time).to_a.sum(&:manual_credits_total_cost)
    trial_credits  = scope(CreditNote, time).to_a.sum(&:trial_credits_total_cost)

    data = {
      date: date_str,
      signups: signups,
      invoices: invoice_totals,
      wallet_charges: wallet_charges,
      cc_charges: cc_charges,
      paypal_charges: paypal_charges,
      manual_credits: manual_credits,
      trial_credits: trial_credits
    }

    AdminMailer.financials(data).deliver_now
  end

  def monthly_csv
    start_date = (Date.today - 1.month).beginning_of_month.beginning_of_day
    end_date   = Date.today.beginning_of_month.beginning_of_day

    AdminMailer.monthly_csv(start_date, end_date).deliver_now
  end

  def periodic_csv(start_date, end_date, report, admin_id)
    start_date = Date.strptime start_date, '%Y-%m-%d'
    end_date   = Date.strptime end_date, '%Y-%m-%d'

    AdminMailer.periodic_csv(start_date, end_date, report, admin_id).deliver_now
  end

  # List of all servers and their market cost vs selling price
  def cost_analysis
    AdminMailer.cost_analysis.deliver_now
  end

  def scope(klass, time)
    klass.where('created_at > ? AND created_at < ?', time.beginning_of_day, time.end_of_day)
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Cynoglossum coelestinum Lindl.

### Remarks
null


text:
package functionly.ast;

import java.util.List;

public class StatementsBlock implements Visitable {

    private final List<AbstractStatement> statements;

    public StatementsBlock(List<AbstractStatement> statements) {
        this.statements = statements;
    }

    public List<AbstractStatement> getStatements() {
        return statements;
    }

    @Override
    public void accept(ASTVisitor visitor) {
        visitor.visit(this);
    }

}


text: from .LoginMod import LoginMod


text:
Настройка компонент
- Маршрутизация SMS

#TEMPLATE config_default

Настройка VAS-платформы

С помощью этого интерфейса можно настроить поведение компонент VAS-платформы Nibelite.
Возможности интерфейса зависят от установленных модулей.


text:
package workshop.microservices.weblog.resource.internal;

import javax.ws.rs.core.Response;

/**
 * Created by schulzst on 26.05.2015.
 */
public class UnknownArticleIdException extends BlogResourceException {
    public UnknownArticleIdException(String articleId) {
        super(Response.Status.NOT_FOUND,
                new ErrorMessage(ErrorCode.UNKNOWN_ARTICLE_ID, "No article with id " + articleId + " found"));
    }
}


text:
import subprocess
from unittest import mock

from tempest.lib.cli import base as cli_base
from tempest.lib import exceptions
from tempest.tests import base

class TestExecute(base.TestCase):

    @mock.patch('subprocess.Popen', autospec=True)
    def test_execute_success(self, mock_popen):
        mock_popen.return_value.returncode = 0
        mock_popen.return_value.communicate.return_value = (
            "__init__.py", "")
        result = cli_base.execute("/bin/ls", action="tempest",
                                  flags="-l -a")
        args, kwargs = mock_popen.call_args
        # Check merge_stderr == False
        self.assertEqual(subprocess.PIPE, kwargs['stderr'])
        # Check action and flags are passed
        args = args[0]
        # We just tests that all pieces are passed through, we cannot make
        # assumptions about the order
        self.assertIn("/bin/ls", args)
        self.assertIn("-l", args)
        self.assertIn("-a", args)
        self.assertIn("tempest", args)
        # The result is mocked - checking that the mock was invoked correctly
        self.assertIsInstance(result, str)
        self.assertIn("__init__.py", result)

    @mock.patch('subprocess.Popen', autospec=True)
    def test_execute_failure(self, mock_popen):
        mock_popen.return_value.returncode = 1
        mock_popen.return_value.communicate.return_value = (
            "No such option --foobar", "")
        result = cli_base.execute("/bin/ls", action="tempest.lib",
                                  flags="--foobar", merge_stderr=True,
                                  fail_ok=True)
        args, kwargs = mock_popen.call_args
        # Check the merge_stderr
        self.assertEqual(subprocess.STDOUT, kwargs['stderr'])
        # Check action and flags are passed
        args = args[0]
        # We just tests that all pieces are passed through, we cannot make
        # assumptions about the order
        self.assertIn("/bin/ls", args)
        self.assertIn("--foobar", args)
        self.assertIn("tempest.lib", args)
        # The result is mocked - checking that the mock was invoked correctly
        self.assertIsInstance(result, str)
        self.assertIn("--foobar", result)

    @mock.patch('subprocess.Popen', autospec=True)
    def test_execute_failure_raise_exception(self, mock_popen):
        mock_popen.return_value.returncode = 1
        mock_popen.return_value.communicate.return_value = (
            "No such option --foobar", "")
        self.assertRaises(exceptions.CommandFailed, cli_base.execute,
                          "/bin/ls", action="tempest", flags="--foobar",
                          merge_stderr=True)

    def test_execute_with_prefix(self):
        result = cli_base.execute("env", action="",
                                  prefix="env NEW_VAR=1")
        self.assertIsInstance(result, str)
        self.assertIn("NEW_VAR=1", result)

class TestCLIClient(base.TestCase):

    @mock.patch.object(cli_base, 'execute')
    def test_execute_with_prefix(self, mock_execute):
        cli = cli_base.CLIClient(prefix='env LAC_ALL=C')
        cli.glance('action')
        self.assertEqual(mock_execute.call_count, 1)
        self.assertEqual(mock_execute.call_args[1],
                         {'prefix': 'env LAC_ALL=C'})

    @mock.patch.object(cli_base, 'execute')
    def test_execute_with_domain_name(self, mock_execute):
        cli = cli_base.CLIClient(
            user_domain_name='default',
            project_domain_name='default'
        )
        cli.glance('action')
        self.assertEqual(mock_execute.call_count, 1)
        self.assertIn('--os-user-domain-name default',
                      mock_execute.call_args[0][2])
        self.assertIn('--os-project-domain-name default',
                      mock_execute.call_args[0][2])
        self.assertNotIn('--os-user-domain-id',
                         mock_execute.call_args[0][2])
        self.assertNotIn('--os-project-domain-id',
                         mock_execute.call_args[0][2])

    @mock.patch.object(cli_base, 'execute')
    def test_execute_with_domain_id(self, mock_execute):
        cli = cli_base.CLIClient(
            user_domain_id='default',
            project_domain_id='default'
        )
        cli.glance('action')
        self.assertEqual(mock_execute.call_count, 1)
        self.assertIn('--os-user-domain-id default',
                      mock_execute.call_args[0][2])
        self.assertIn('--os-project-domain-id default',
                      mock_execute.call_args[0][2])
        self.assertNotIn('--os-user-domain-name',
                         mock_execute.call_args[0][2])
        self.assertNotIn('--os-project-domain-name',
                         mock_execute.call_args[0][2])

    @mock.patch.object(cli_base, 'execute')
    def test_execute_with_default_api_version(self, mock_execute):
        cli = cli_base.CLIClient()
        cli.openstack('action')
        self.assertEqual(mock_execute.call_count, 1)
        self.assertNotIn('--os-identity-api-version ',
                         mock_execute.call_args[0][2])

    @mock.patch.object(cli_base, 'execute')
    def test_execute_with_empty_api_version(self, mock_execute):
        cli = cli_base.CLIClient(identity_api_version='')
        cli.openstack('action')
        self.assertEqual(mock_execute.call_count, 1)
        self.assertNotIn('--os-identity-api-version ',
                         mock_execute.call_args[0][2])

    @mock.patch.object(cli_base, 'execute')
    def test_execute_with_explicit_api_version(self, mock_execute):
        cli = cli_base.CLIClient(identity_api_version='0.0')
        cli.openstack('action')
        self.assertEqual(mock_execute.call_count, 1)
        self.assertIn('--os-identity-api-version 0.0 ',
                      mock_execute.call_args[0][2])


text:
package sorcer.core.provider.exertmonitor.lease;

import java.net.UnknownHostException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.ExportException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.jini.core.lease.Lease;
import net.jini.core.lease.LeaseDeniedException;
import net.jini.core.lease.UnknownLeaseException;
import net.jini.id.ReferentUuid;
import net.jini.id.Uuid;
import net.jini.id.UuidFactory;
import net.jini.jeri.BasicILFactory;
import net.jini.jeri.BasicJeriExporter;
import net.jini.jeri.tcp.TcpServerEndpoint;

import com.sun.jini.landlord.Landlord;
import com.sun.jini.landlord.LeaseFactory;
import com.sun.jini.landlord.LeasedResource;
import sorcer.core.provider.exertmonitor.MonitorSession;
import sorcer.util.Sorcer;

import static sorcer.util.StringUtils.*;

public class MonitorLandlord implements Landlord, Runnable, ReferentUuid, Remote {

	public static interface MonitorLeasedResource extends LeasedResource {

		public void leaseCancelled();

		public void setTimeout(long timeoutDuration);

		public long getTimeout();

		public void timedOut();

	}

	private transient LeaseFactory lFactory;
    private transient Uuid landlordUuid;
    private transient Landlord proxy;
	private volatile boolean run = true;

	static transient final String LOGGER = "sorcer.core.provider.monitor.lease.MonitorLandlord";
	static transient final Logger logger = LoggerFactory.getLogger(LOGGER);

	// A simple leasing policy...10 minute leases.
	protected static final int DEFAULT_MAX_LEASE = 1000 * 60 * 1;

    protected int maxLease = DEFAULT_MAX_LEASE;

	protected static final int DEFAULT_SLEEP_TIME = 1000 * 3;

	public static Hashtable resources;

	public MonitorLandlord() throws ExportException {
		resources = new Hashtable();
		landlordUuid = UuidFactory.generate();
		export();
		this.lFactory = new LeaseFactory(proxy, landlordUuid);
	}

	public void export() throws ExportException {
        BasicJeriExporter exporter = null;
        try {
            exporter = new BasicJeriExporter(
                    TcpServerEndpoint.getInstance(Sorcer.getLocalHost().getHostAddress(), 0), new BasicILFactory());
        } catch (UnknownHostException e) {
            logger.warn("Could not resolve hostAddress - starting on default interface");
            exporter = new BasicJeriExporter(
                    TcpServerEndpoint.getInstance(0), new BasicILFactory());
        }
        proxy = (Landlord) exporter.export(this);
		Thread llt = new Thread(this, tName("MonitorLandlord.checkLeases"));
		llt.setDaemon(true);
		llt.start();
	}

	public Object getServiceProxy() {
		return proxy;
	}

	public Lease newLease(LeasedResource resource) {
		resources.put(resource.getCookie(), resource);
		return lFactory
				.newLease(resource.getCookie(), resource.getExpiration());
	}

	// Change the maximum lease time from the default.
	public void setMaxLease(int maxLease) {
		this.maxLease = maxLease;
	}

	// Apply the policy to a requested duration
	// to get an actual expiration time.
	public long getExpiration(long request) {
		if (request > maxLease || request == Lease.ANY)
			return System.currentTimeMillis() + maxLease;
		else
			return System.currentTimeMillis() + request;
	}

	// Cancel the lease represented by 'cookie'
	public void cancel(Uuid cookie) throws UnknownLeaseException,
			RemoteException {

		MonitorLeasedResource resource;
		resource = (MonitorLeasedResource) resources.get(cookie);
		if (resource != null) {
			resource.leaseCancelled();
			return;
		}

		throw new UnknownLeaseException(cookie.toString());
	}

	// Cancel a set of leases
	public Map cancelAll(Uuid[] cookies) throws RemoteException {
		Map exceptionMap = null;

		for (int i = 0; i < cookies.length; i++) {
			try {
				cancel(cookies[i]);
			} catch (UnknownLeaseException ex) {
				if (exceptionMap == null) {
					exceptionMap = new HashMap();
				}
				exceptionMap.put(cookies[i], ex);
			}
		}
		return exceptionMap;
	}

	// Renew the lease specified by 'cookie'
	public long renew(Uuid cookie, long extension)
			throws UnknownLeaseException, LeaseDeniedException, RemoteException {

		MonitorLeasedResource resource;
		resource = (MonitorLeasedResource) resources.get(cookie);
		if (resource != null) {
			long expiration = getExpiration(extension);
			resource.setExpiration(expiration);
			// logger.info("Lease renewd for resource ="+resource+
			// " next lease duration="+ (expiration -
			// System.currentTimeMillis()));

			return expiration - System.currentTimeMillis();
		}
		throw new UnknownLeaseException(cookie.toString());
	}

	// Renew a set of leases.
	public Landlord.RenewResults renewAll(Uuid[] cookies, long[] extensions)
			throws RemoteException {
		long[] granted = new long[cookies.length];
		Exception[] denied = null;

		for (int i = 0; i < cookies.length; i++) {
			try {
				granted[i] = renew(cookies[i], extensions[i]);
			} catch (Exception ex) {
				if (denied == null) {
					denied = new Exception[cookies.length + 1];
				}
				denied[i + 1] = ex;
			}
		}

		Landlord.RenewResults results = new Landlord.RenewResults(granted,
				denied);
		logger.info( "leases renewed Landlord.RenewResults="
				+ results);
		return results;
	}

	public void run() {
		long timeToSleep = DEFAULT_SLEEP_TIME;
		while (run) {
			long nextWakeup = System.currentTimeMillis() + timeToSleep;
			try {
				Thread.sleep(timeToSleep);
			} catch (InterruptedException ex) {
			}

			long currentTime = System.currentTimeMillis();
			// see if we're at the next wakeup time
			if (currentTime >= nextWakeup) {
				nextWakeup = currentTime + DEFAULT_SLEEP_TIME;
				// notify
				checkLeasesAndTimeouts();
			}
			timeToSleep = nextWakeup - System.currentTimeMillis();
		}
	}

	public void checkLeasesAndTimeouts() {
		// logger.info("Checking for leases and time outs");
		MonitorLeasedResource resource;
		Uuid cookie;
		long now = System.currentTimeMillis();
		for (Enumeration e = resources.keys(); e.hasMoreElements();) {
			cookie = (Uuid) e.nextElement();
			resource = (MonitorLeasedResource) resources.get(cookie);
            String name = (((MonitorSession)resource).getRuntimeExertion()!=null ?
                    ((MonitorSession)resource).getRuntimeExertion().getName() : " NOT EXERTION");
            SimpleDateFormat sdf = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
            logger.info("Checking lease: " + name + " " + sdf.format(Math.min(resource.getTimeout(), resource.getExpiration()))
			+ (resource.getExpiration()<resource.getTimeout() ? " E" : " T"));

			if (resource.getExpiration() < now) {
				logger.info( "Lease cancelled for resource ="
						+ resource);
				resource.leaseCancelled();
				resources.remove(resource.getCookie());
			} else if (resource.getTimeout() < now) {
				logger.info( "Timeout for resource =" + resource
						+ " resource.getTimeout()=" + resource.getTimeout()
						+ " now=" + now + " resource.getTimeout()-now="
						+ (resource.getTimeout() - now));
				resource.timedOut();
				resources.remove(resource.getCookie());
			}
		}

	}

	public void remove(LeasedResource lr) {
		logger.info( "Removing landlord resource =" + lr);
		resources.remove(lr.getCookie());
	}

	public Hashtable getResources() {
		return resources;
	}

	public Uuid getReferentUuid() {
		return landlordUuid;
	}

	public void terminate() {
		run = false;
	}
}


text:
export const environment: any = {
  production: false,

  service: {
    // some service calls here that corresponds to dev env
    api: 'http://localhost:8000/api',
  }
};


text:
function SewageBase() {
	this.bgDefaultColor = "#000000";
	this.label = "";
	this.shape = null;
	this.text = null;
	this.width = 1;
	this.height = 1;
	this.dirtyWidth = 0;
	this.dirtyHeight = 0;
	this.currency = "gold";
	this.price = 0;
	this.capacity = 0;
}

SewageBase.prototype = new StructureBase();