text:
{% block meta %}
name: PublishObserverMsgState
description: >
  SMACH template that publishes a ROS message passed via a userdata input_key
  to a topic by using a message publisher observer object that is set to
  subscribe to and observe another topic which determines the publication rate.
  If the message type is not specified, attempts will be made to infer it from
  the message data.
language: Python
framework: SMACH
type: None
tags: [core]
includes: []
extends:
- State
variables:
- - input_keys:
      description: >
        Other than the 'msg' input_key, which specifies the ROS message to be
        published, remaining input_keys are assumed to be used by the
        optionally specified callback functions.
      type: list of str
- - output_keys:
      description: >
        Other than the 'topic' output_key, which specifies the ROS topic to
        which the message should be published, remaining output_keys are
        assumed to be used by the optionally specified callback functions.
      type: list of str
- - callbacks:
      description:
        Either callback function names or backtick-wrapped lambda functions
        for possible modifications to the message publishing procedure.
      type: dict of str
- action:
    description: >
      The action that the state should perform. The options are 'add', 'remove'
      and 'remove_all', which will add the specified message publication topic,
      remove the specified message publication topic, and remove all currently
      published topics respectively.
    type: str
input_keys:
- msg:
    description: >
      The ROS message to be published.

      In case the intended content of the message is specified in list form,
      parsers will be applied for known message types in an attempt to convert
      the list input into a corresponding ROS message type.
      Parsers for the following message types are currently operational:
      geometry_msgs/PointStamped,
      geometry_msgs/PoseStamped,
      geometry_msgs/PoseArray,
      geometry_msgs/PointCloud, and
      geometry_msgs/PointCloud2.

      E.g. if msg is specified as [1.0, 2.0, 3.0], then it should be parsed
      and converted to a geometry_msgs/PointStamped type, whereas if it is
      specified as [[1.0, 2.0, 3.0], [0.0, 0.0, 0.0, 1.0]], then it should be
      parsed and converted to a geometry_msgs/PoseStamped type.
    type:
      - genpy.message.Message
      - list
- topic:
    description:
      The name of the topic to which the message should be published.
    type: str
- - msg_type:
      description: >
        The specified type of the ROS message to be published. The options are
        the possible types of the 'msg' input_key specified as a str.
      type: str
- - frame_id:
      description:
        The id of a specific tf frame to which the published message should be attached.
      type: str
output_keys:
- msg:
    description: >
      See input_keys_description.
    type:
      - genpy.message.Message
      - list
- topic:
    description:
      See input_keys description.
    type: str
{% endblock meta %}

{% from "Utils.tpl.py" import import_module, render_transitions, render_remapping, render_input_keys, render_output_keys, render_init_callbacks, render_execute_callbacks, render_callbacks %}

{% if sub_topic is not defined %}{% set sub_topic = 'tf' %}{% endif %}

{% extends "State.tpl.py" %}

{% include "ParsePointStamped.tpl.py" %}
{% include "ParsePoseStamped.tpl.py" %}
{% include "ParsePoseArray.tpl.py" %}
{% include "ParsePointCloud.tpl.py" %}
{% include "ParsePointCloud2.tpl.py" %}
{% include "MsgPublisherObserver.tpl.py" %}

{% block imports %}
{{ super() }}
{{ import_module(defined_headers, 'roslib') }}
{% endblock imports %}

{% block class_defs %}
{{ super() }}
{% if 'class_PublishObserverMsgState' not in defined_headers %}
class PublishObserverMsgState(smach.State):
    def __init__(self, name, msg_pub_observer, action, input_keys = ['msg', 'topic'], output_keys = ['msg', 'topic'], callbacks = None):
        smach.State.__init__(self, input_keys=input_keys, output_keys=output_keys, outcomes=['succeeded', 'aborted'])

        # Save the state name
        self._name = name

        # Save the MsgPublisherObserver object reference
        self._msg_pub_observer= msg_pub_observer

        # Save the action
        self._action = action

        # Set up dict of parsing functions for certain message types/classes.
        self._msg_parsers = {"<class 'geometry_msgs.msg._Point.Point'>": parse_pointstamped,
                             "<class 'geometry_msgs.msg._PointStamped.PointStamped'>": parse_pointstamped,
                             "<class 'geometry_msgs.msg._Pose.Pose'>": parse_posestamped,
                             "<class 'geometry_msgs.msg._PoseStamped.PoseStamped'>": parse_posestamped,
                             "<class 'geometry_msgs.msg._PoseArray.PoseArray'>": parse_posearray,
                             "<class 'sensor_msgs.msg._PointCloud.PointCloud'>": parse_pointcloud,
                             "<class 'sensor_msgs.msg._PointCloud2.PointCloud2'>": parse_pointcloud2}

        {{ render_init_callbacks() }}

    def _parse_msg(self, msg, msg_type=None):
        # First try using a known parser for a specified msg_type.
        try:
            assert msg_type
            msg_class = str(roslib.message.get_message_class(msg_type))
            published_msg = self._msg_parsers[msg_class](msg)
            return published_msg
        except:
            pass

        # Next, try to select a known parser by checking the type of message.
        try:
            msg_class = str(type(msg))
            published_msg = self._msg_parsers[msg_class](msg)
            return published_msg
        except:
            pass

        # Next, try each message type parser in succession and see if something sticks.
        for _, parser in self._msg_parsers.items():
            try:
                published_msg = parser(msg)
                return published_msg
            except:
                pass

        # Finally, if none of the above stuck, just return the original message.
        return msg

    def execute(self, userdata):

        {{ render_execute_callbacks() }}

        # Parse msg
        if self._action != 'remove_all':
            try:
                if 'msg_type' in self._input_keys:
                    published_msg = self._parse_msg(userdata.msg, msg_type=userdata.msg_type)
                else:
                    published_msg = self._parse_msg(userdata.msg)
            except Exception as e:
                rospy.logerr('Failed to parse message: '.format(repr(e)))
                return 'aborted'

        # Get topic if it's specified as an input key
        if 'topic' in self._input_keys:
            topic = userdata.topic
        # Otherwise, construct it from the state name
        else:
            topic = 'smacha/' + self._name.lower()

        # Add or remove the message + publisher
        outcome = 'aborted'
        if self._action == 'add':
            if 'frame_id' in self._input_keys:
                outcome = self._msg_pub_observer.add(published_msg, topic, frame_id=userdata.frame_id)
            else:
                outcome = self._msg_pub_observer.add(published_msg, topic)
        elif self._action == 'remove':
            outcome = self._msg_pub_observer.remove(topic)
        elif self._action == 'remove_all':
            outcome = self._msg_pub_observer.remove_all()

        # Set topic output key if specified
        if self._action == 'add' and outcome == 'succeeded':
            for output_key in ['topic', 'output_topic', 'topic_output']:
                if output_key in self._output_keys:
                    setattr(userdata, output_key, topic)

        # Set msg output key if specified
        if self._action == 'add' and outcome == 'succeeded':
            for output_key in ['msg', 'output_msg', 'msg_output']:
                if output_key in self._output_keys:
                    setattr(userdata, output_key, published_msg)

        return outcome
{% do defined_headers.append('class_PublishObserverMsgState') %}{% endif %}
{% endblock class_defs %}

{% block main_def %}
{{ super() }}
{% if sub_topic + '_msg_pub_observer' not in defined_headers %}
{{ sub_topic }}_msg_pub_observer = MsgPublisherObserver(sub_topic='{{ sub_topic }}')
{% do defined_headers.append(sub_topic + '_msg_pub_observer') %}{% endif %}
{% endblock main_def %}

{% block header %}
{{ super() }}
{#
 # By using this bit of trickery, we ensure that the mandatory userdata variable
 # 'topic' gets defined as an empty string before any other userdata
 # variables are defined (these are rendered via the 'header_userdata' block
 # usually, which is rendered after the 'header' block). This allows for the
 # specification of 'topic' to be omitted in the SMACHA script state
 # definitions when the 'action' variable is set to 'remove_all'.
 #}
{% if mandatory_userdata is not defined %}{% set mandatory_userdata = dict() %}{% endif %}
{% if action == 'remove_all' and 'topic' not in mandatory_userdata.keys() %}{% set _dummy = mandatory_userdata.update({'topic':''}) %}{% endif %}
{% if mandatory_userdata is defined %}{{ render_userdata(parent_sm_name, mandatory_userdata) }}{% endif %}
{% endblock header %}

{% block body %}
smach.{{ parent_type }}.add('{{ name }}',
        {{ '' | indent(23, true) }}{{ class_name }}('{{ name }}', {{ sub_topic }}_msg_pub_observer, '{{ action }}'{% if input_keys is defined %}, {{ render_input_keys(input_keys, indent=0) }}{% endif %}{% if output_keys is defined %}, {{ render_output_keys(output_keys, indent=0) }}{% endif %}{% if callbacks is defined %}, {{ render_callbacks(name, uuid, callbacks, indent=0) }}{% endif %}){% if transitions is defined %},
{{ render_transitions(transitions) }}{% endif %}{% if remapping is defined %},
{{ render_remapping(remapping) }}{% endif %})
{% endblock body %}


text:
angular.module('todoApp', [])
  .controller('TodoListController', function ($scope, $http) {
    $scope.datasearch = []
    $scope.players = []
    $scope.login = 1

    $http.get('/profile').then(function (response) {
      $scope.name = response.data.displayName
      $scope.photo = response.data.photos[0].value
      $scope.login = 2
    }, function (response) {
      console.log(response)
    })

    $scope.logout = function () {
      $scope.login = 1
    }

    $scope.start = function () {
      $scope.login = 3
    }

    $scope.post = function () {
      console.log('test')
      var value = {message: $scope.text}
      $http.post('/post', value).then(function (response) {
        $scope.datasearch = response.data
      }, function (response) {
        console.log(response)
      })
    }

    $scope.addPlayer = function (data) {
      console.log(data)
      var temp = {name: data.name, picture: data.picture.data.url, score: 0}
      $scope.players.push(temp)
      $scope.$apply()
    }

    $scope.addscore = function (index) {
      $scope.players[index].score++
    }

    $scope.delscore = function (index) {
      $scope.players[index].score--
    }

    $scope.endgame = function () {
      $scope.players = []
      $scope.login = 2
      $scope.datasearch = []
      $scope.text = ''
    }
    $scope.delPlayer = function (index) {
      $scope.players.splice(index, 1)
      $scope.$apply()
    }

    $scope.sortdata = function () {
      $scope.players.score.sort()
      console.log($scope.players)
    }
  })

redpajama_set_name: RedPajamaGithub


text:
/*
 * Do not modify this file. This file is generated from the codepipeline-2015-07-09.normal.json service model.
 */
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

using Amazon.Runtime;
using Amazon.Runtime.Internal;

namespace Amazon.CodePipeline.Model
{
    /// <summary>
    /// Represents the output of a get third party job details action.
    /// </summary>
    public partial class GetThirdPartyJobDetailsResponse : AmazonWebServiceResponse
    {
        private ThirdPartyJobDetails _jobDetails;

        /// <summary>
        /// Gets and sets the property JobDetails.
        /// <para>
        /// The details of the job, including any protected values defined for the job.
        /// </para>
        /// </summary>
        public ThirdPartyJobDetails JobDetails
        {
            get { return this._jobDetails; }
            set { this._jobDetails = value; }
        }

        // Check to see if JobDetails property is set
        internal bool IsSetJobDetails()
        {
            return this._jobDetails != null;
        }

    }
}


text:
package org.apache.camel.component.jsonvalidator;

import org.apache.camel.Exchange;
import org.apache.camel.ValidationException;

public class DefaultJsonValidationErrorHandler implements JsonValidatorErrorHandler {

    @Override
    public void reset() {
        // Do nothing since we do not keep state
    }

    @Override
    public void handleErrors(Exchange exchange, org.everit.json.schema.Schema schema, Exception e) throws ValidationException {
        if (e instanceof org.everit.json.schema.ValidationException) {
            throw new JsonValidationException(exchange, schema, (org.everit.json.schema.ValidationException)e);
        } else {
            throw new JsonValidationException(exchange, schema, e);
        }
    }

}


text:
(function () {
  'use strict';

  // Checkins controller
  angular
    .module('checkins')
    .controller('CheckinsController', CheckinsController);

  CheckinsController.$inject = ['$scope', '$state', '$window', 'Authentication', 'checkinResolve'];

  function CheckinsController ($scope, $state, $window, Authentication, checkin) {
    var vm = this;

    vm.authentication = Authentication;
    vm.checkin = checkin;
    vm.error = null;
    vm.form = {};
    vm.remove = remove;
    vm.save = save;

    // Remove existing Checkin
    function remove() {
      if ($window.confirm('Are you sure you want to delete?')) {
        vm.checkin.$remove($state.go('checkins.list'));
      }
    }

    // Save Checkin
    function save(isValid) {
      if (!isValid) {
        $scope.$broadcast('show-errors-check-validity', 'vm.form.checkinForm');
        return false;
      }

      // TODO: move create/update logic to service
      if (vm.checkin._id) {
        vm.checkin.$update(successCallback, errorCallback);
      } else {
        vm.checkin.$save(successCallback, errorCallback);
      }

      function successCallback(res) {
        $state.go('checkins.view', {
          checkinId: res._id
        });
      }

      function errorCallback(res) {
        vm.error = res.data.message;
      }
    }
  }
}());


text:
require 'open3'

class StartUpTest < Minitest::Test
  def test_should_not_print_to_stdout_when_logging_available
    ruby = 'require "newrelic_rpm"; NewRelic::Agent.manual_start; NewRelic::Agent.shutdown'
    cmd = "bundle exec ruby -e '#{ruby}'"

    _sin, sout, serr = Open3.popen3(cmd)
    output = sout.read + serr.read

    expected_noise = [
      "JRuby limited openssl loaded. http://jruby.org/openssl\n",
      "gem install jruby-openssl for full support.\n",
      "fatal: Not a git repository (or any of the parent directories): .git\n",
      /Exception\: java\.lang.*\n/]

    expected_noise.each {|noise| output.gsub!(noise, "")}

    assert_equal '', output.chomp
  end

  def test_instrumentation_loads_clean_even_without_dependencies
    output = `bundle exec ruby script/loading.rb`

    problems = output.scan(/ERROR : .*/)
    assert_empty problems
  end

  def test_after_fork_does_not_blow_away_manual_start_settings
    NewRelic::Agent.manual_start(:app_name => 'my great app')

    NewRelic::Agent.after_fork

    assert_equal('my great app', NewRelic::Agent.config[:app_name])
  end
end


text:
package com.dremio.services.fabric.api;

import org.apache.arrow.memory.BufferAllocator;

import com.dremio.exec.rpc.ResponseSender;
import com.dremio.exec.rpc.RpcConfig;
import com.dremio.exec.rpc.RpcException;
import com.google.protobuf.ByteString;
import com.google.protobuf.MessageLite;

import io.netty.buffer.ByteBuf;

/**
 * An interface that allows application developers to express a pseudo-wire protocol.
 */
public interface FabricProtocol {

  /**
   * Returns a unique protocol id. In a particular fabric instance, each protocol must implement its own protocol id.
   * @return A unique id.
   */
  public int getProtocolId();

  /**
   * Returns the allocator that should be associated with this protocol.
   * @return An allocator.
   */
  public BufferAllocator getAllocator();

  /**
   * The REQUEST <> RESPONSE configuration that should be used for this
   * protocol. Note that Executor and Timeout options are ignored if set since
   * those are a purview of the actual wire protocol.
   *
   * @return A communication configuration.
   */
  public RpcConfig getConfig();

  /**
   * Returns the default response id for a particular incoming message type.
   * @param rpcType The number associated with the EnumLite that was used to send the message.
   * @return A default instance of the expected Message type.
   * @throws RpcException
   */
  public MessageLite getResponseDefaultInstance(int rpcType) throws RpcException;

  /**
   * How this protocol will handle incoming REQUEST messages.
   * @param connection The connection associated with the message.
   * @param rpcType The incoming message type received.
   * @param pBody The serialized protobuf body associated with the message.
   * @param dBody The optional collection of bytes associated with a message.
   * @param sender An callback handler than can be used to return the response.
   * @throws RpcException
   */
  public void handle(final PhysicalConnection connection, final int rpcType, final ByteString pBody, final ByteBuf dBody, final ResponseSender sender) throws RpcException;

}


text:
<?php

require __DIR__ . "/../vendor/autoload.php";

use \max\mailchimp\Lista;
/**
* Teste de cadastro de membros em uma lista
*/
class TestLista extends PHPUnit_Framework_TestCase
{

	public function testRecuperaLista(){

		$lista = new Lista();
		$lista_data = $lista->get();

		file_put_contents('log.txt',print_r($lista->getLastResponse(),true));

		$this->assertNotEmpty($lista_data);
	}

}


text:
QUIT_NO_CASE = re.compile('quit', re.IGNORECASE)
command = input('Type Command:')
if QUIT_NO_CASE.match(command):
  print("Quiting...")

# Dissect multiple pieces from a string, using re.split.
PHONE_NUMBER_REG = re.compile('(\d+)-(\d+)-(\d+)')
# 0: area code, 1: extension1, 2: extension2
items = PHONE_NUMBER_REG.split(phone_number)


text:
require File.expand_path("../boot", __FILE__)

require "rails/all"

Bundler.require(*Rails.groups)

module ConfigService
  class Application < Rails::Application
    config.active_record.raise_in_transactional_callbacks = true
  end
end


text:
package com.google.apps.easyconnect.easyrp.client.basic.util;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * Utilities to handle federated and dasher account.

 * Currently only following sites are recognized as federated domains: Gmail, AOL domains, LiveID
 * domains, Yahoo domains;

 *
 * @author guibinkong@google.com (Guibin Kong)
 */
public class IdpUtils {
  private static final String EMAIL_REGEX = "\\w+(\\.\\w+)*@(\\w+(\\.\\w+)+)";
  private static final String USERNAME_REGEX = "\\w+(\\.\\w+)*";

  /**
   * Checks if a user name is valid.
   *
   * @param username the user name to be checked
   * @return ture for valid, false otherwise
   */
  public static boolean isValidUsername(String username) {
    if (Strings.isNullOrEmpty(username)) {
      return false;
    }
    return username.matches(USERNAME_REGEX);
  }

  /**
   * Checks if a email is valid.
   *
   * @param email the email address to be checked
   * @return ture for valid, false otherwise
   */
  public static boolean isValidEmail(String email) {
    if (Strings.isNullOrEmpty(email)) {
      return false;
    }
    return email.matches(EMAIL_REGEX);
  }

  /**
   * Parses an email, and return its domain. If no '@' found, the whole string will be recognized as
   * domain.
   *
   * @param email the email to be parsed
   * @return domain part of the email
   */
  public static String getDomain(String email) {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(email));
    if (email.indexOf("@") < 0) {
      return email.toLowerCase();
    }
    Preconditions.checkArgument(isValidEmail(email));
    return email.split("@")[1].toLowerCase();
  }
}


text:
<!DOCTYPE html>

Both words below should be in the the right column.

            right
column


text:
import * as React from "react";
import { RegimenProps } from "../interfaces";
import { t } from "i18next";
import { ColorPicker } from "../../ui";
import { Row, Col } from "../../ui/index";
import { editRegimen } from "../actions";

function write({ dispatch, regimen }: RegimenProps):
  React.EventHandler<React.FormEvent<{}>> {
  if (regimen) {
    return (event: React.FormEvent<HTMLInputElement>) => {
      dispatch(editRegimen(regimen, { name: event.currentTarget.value }));
    };
  } else {
    throw new Error("Regimen is required");
  }
}

export function RegimenNameInput({ regimen, dispatch }: RegimenProps) {
  let value = (regimen && regimen.body.name) || "";
  return (
    <Row>
      <Col xs={11}>
        <input
          placeholder={t("Regimen Name")}
          type="text"
          onChange={write({ dispatch, regimen })}
          value={value}
        />
      </Col>
      <ColorPicker
        current={(regimen && regimen.body.color) || "gray"}
        onChange={(color) => dispatch(editRegimen(regimen, { color }))}
      />
    </Row>
  );
}


text:
'use strict';

describe('Controller: WeatherCtrl', function () {

  // load the controller's module
  beforeEach(module('infoSystemApp'));

  var WeatherCtrl, scope;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    WeatherCtrl = $controller('WeatherCtrl', {
      $scope: scope
    });
  }));

  it('should ...', function () {
    expect(1).toEqual(1);
  });
});


text:
package de.apoth.anderoids.graphics;

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

import de.apoth.anderoids.logic.GameLogic;
import de.apoth.anderoids.logic.GameModes;
import de.apoth.anderoids.resource.Position;
import de.apoth.anderoids.logic.ShipTypes;
import de.apoth.anderoids.logic.events.Event;
import de.apoth.anderoids.logic.events.MovePerspectiveEvent;
import de.apoth.anderoids.logic.input.AccelerometerSystem;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;;

public class SpaceView extends SurfaceView implements SurfaceHolder.Callback
{
	SpaceThread myThread;
	private static Random randy = new Random();
	long passedTime;

	private static Rect screenRect;
	private static int starRadius;
	Integer mySpaceShipID = 0;//the perspective follows this object
	private static final int amountStars = 120;
	ArrayList<Star> stars;
	private GraphicSpaceship mySpaceship;
	private Matrix middleOffset = new Matrix();

	SpaceView(Context context) {super(context);}

	public SpaceView(Context context, ShipTypes shipType, GameModes gameMode)
	{
		super(context);
		passedTime = 0;
		screenRect = new Rect();
		getWindowVisibleDisplayFrame(screenRect);
		starRadius = screenRect.height()+screenRect.width();//arbitrary but functioning
		BitmapManager.setup(this);
		this.stars = generateStars();

		this.mySpaceship = new GraphicSpaceship(shipType);
		resetMiddleMatrix();
		//this.mySpaceship

		myThread = new SpaceThread(getHolder(), this);
		getHolder().addCallback(this);
	}
	private void resetMiddleMatrix() {
		Position p = getScreenCenterPosition();
		this.middleOffset.setTranslate(p.getX(), p.getY());
	}

	@Override
	protected void onDraw(Canvas canvas)
	{
        Matrix mat = new Matrix();
        //positions are set relative to position of spaceship
        mat.postTranslate(getScreenCenterPosition().getX() / 2,
                getScreenCenterPosition().getY() / 2);
		GraphicSpaceship s=this.mySpaceship;
		s.setAngle(s.getAngle() + 0.01f);
		canvas.drawColor(Color.BLACK);
		this.drawBackground(canvas, mat);
		this.drawSpaceship(canvas, mat);
		//resetMiddleMatrix();//TODO see if this is really necessary
	}
	/**
	 * draws stars, smoke, and debris
	 * @param canvas
	 */
	private void drawBackground(Canvas canvas, Matrix mat) {
        Matrix m = new Matrix();
		for(Star s : this.stars)
		{
			s.draw(canvas, mat);
		}
	}
	private void drawSpaceship(Canvas canvas, Matrix mat)
	{
		Matrix m = new Matrix(mat);
		m.setRotate(this.mySpaceship.getAngle()*360);
		//m.postTranslate(getScreenCenterPosition().getX(),
		//		getScreenCenterPosition().getY());
		this.mySpaceship.draw(canvas, m);

	}
	protected void updateObjects(List<Event> changes)
	{
        for (Event ev: changes)
        {
            if(ev.getClass() == MovePerspectiveEvent.class)
            {
                Position delta = ((MovePerspectiveEvent) ev).getDistance();
                this.middleOffset.preTranslate(delta.getX(),delta.getY());
                this.moveStars(delta);
            }
        }
		//die ersten zwei nachrichten abfragen
		//die erste ist immer die TimeChangeMessage
		//die zweite immer die LogicStepCountMessage

		//die objekte, deren position absolut gesetzt wurde,
		//sollten ihre position nicht durch schwung*numTicks aendern
		//sie muessen also markiert werden

	}

    private void moveStars(Position delta) {
        for(Star s : this.stars)
        {
            s.move(delta);
			if(isOutsideVisibility(s))
			{
				repositionStar(s);
			}
        }
    }

	private void repositionStar(Star s) {
		Position p = s.pos;
		s.pos = new Position(-p.getX(),-p.getY());
	}

	private boolean isOutsideVisibility(Star s)
	{
		float starDist = s.pos.getX() + s.pos.getY();
		starDist *= starDist;

		starDist = (float)Math.sqrt((double)starDist);
		return starDist > starRadius;
	}

	public void surfaceCreated(SurfaceHolder holder) {

		myThread.setRunning(true);
		myThread.start();
	}
	public void surfaceDestroyed(SurfaceHolder holder)
	{
		boolean retry = true;
		myThread.setRunning(false);
		while(retry)
		{
			try
			{
				myThread.join();
				retry = false;
			} catch (InterruptedException e)
			{
				//pass
			}
		}
	}
	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	@SuppressLint("WrongCall")
	class SpaceThread extends Thread
	{
		private SpaceView _panel;
		private SurfaceHolder _surfaceHolder;
		private boolean _run = false;
		private AccelerometerSystem myAccelerometerSystem = null;

		public SpaceThread(SurfaceHolder surfaceHolder, SpaceView panel) {
			_surfaceHolder = surfaceHolder;
			_panel = panel;

			AccelerometerSystem.checkForAccelerometer(panel.getContext());
			this.myAccelerometerSystem = new AccelerometerSystem(panel.getContext());
		}
		public void setRunning(boolean run) {
			_run = run;
		}

		@Override
		public void run()
		{
			Canvas c = null;
			while(_run)
			{
				//TODO measure time it took the device to render a frame and adjust gamelogic stepsize
				GameLogic.get().elapseTime();
				GameLogic.get().setDeviceAngle(this.myAccelerometerSystem.getDeviceAngle());
				GameLogic.get().executeEventsUntilNow();

				//GameLogic.get().getMySpaceShipID();
				_panel.updateObjects(GameLogic.get().getVisibleChanges(_panel.mySpaceShipID));

				try
				{
					c = _surfaceHolder.lockCanvas(null);
					synchronized(_surfaceHolder)
					{
						_panel.onDraw(c);
					}
				}
				finally
				{
					if(c != null)
						_surfaceHolder.unlockCanvasAndPost(c);
				}
/*				c = _surfaceHolder.lockCanvas();
				_panel.onDraw(c);
				_surfaceHolder.unlockCanvasAndPost(c);*/
			}

			// cleanup when the activity is closed due to game end
			myAccelerometerSystem.deactivateSystem(getContext());
		}

	}/* class SpaceThread ends here */

	private static ArrayList<Star> generateStars() {
        Position center = getScreenCenterPosition();
        ArrayList<Star> retu = new ArrayList<Star>();
        float radius = getStarRadius() * 2;
        System.out.println(radius);
        for (int i = 0; i < amountStars; i++) {
            //TODO evenly distribute points in sphere
            Position starPos = new Position(
                    (randy.nextFloat() * radius) -getStarRadius(),
                    (randy.nextFloat() * radius) - getStarRadius());
            //starPos.subtract(center);
            //distance should lie between 0.7 and 0.8
            float distance = randy.nextFloat();
            distance /= 10.0f;
            distance += 0.7f;
            Star toAdd = new Star(
                    starPos,
                    distance,
                    randy.nextInt() % BitmapManager.getNumStarPics());
            Log.d("star",starPos.toString());
            retu.add(toAdd);
        }
        return retu;
    }

	public static int getStarRadius()
	{
		return (screenRect.height() + screenRect.width())/2;

	}
	public static Position getScreenCenterPosition()
	{
		Position retu = new Position(
				screenRect.centerX(),
				screenRect.centerY());
		return retu;
	}

	public void joinThread()
	{
		this.myThread.setRunning(false);
		try {
			this.myThread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}


text:
import { defineMessages } from 'react-intl';

const messages = defineMessages({
  'DownloadButton.downloadFor': {
    id: 'DownloadButton.downloadFor',
    defaultMessage: 'Download for',
  },
  'DownloadButton.or': {
    id: 'DownloadButton.or',
    defaultMessage: 'or',
  },
  'DownloadButton.others': {
    id: 'DownloadButton.others',
    defaultMessage: 'Download for other platforms',
  },
});

export default messages;


text:
#include "qstandardgestures_p.h"
#include "qgesture.h"
#include "qgesture_p.h"
#include "qevent.h"
#include "qwidget.h"
#include "qabstractscrollarea.h"
#include <qgraphicssceneevent.h>
#include "qdebug.h"

#ifndef QT_NO_GESTURES

QT_BEGIN_NAMESPACE

QPanGestureRecognizer::QPanGestureRecognizer()
{
}

QGesture *QPanGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
#if defined(Q_OS_WIN) && !defined(QT_NO_NATIVE_GESTURES)
        // for scroll areas on Windows we want to use native gestures instead
        if (!qobject_cast<QAbstractScrollArea *>(target->parent()))
            static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
#else
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
#endif
    }
    return new QPanGesture;
}

QGestureRecognizer::Result QPanGestureRecognizer::recognize(QGesture *state,
                                                            QObject *,
                                                            QEvent *event)
{
    QPanGesture *q = static_cast<QPanGesture *>(state);
    QPanGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result;
    switch (event->type()) {
    case QEvent::TouchBegin: {
        result = QGestureRecognizer::MayBeGesture;
        QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
        d->lastOffset = d->offset = QPointF();
        break;
    }
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture) {
            if (ev->touchPoints().size() == 2) {
                QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
                QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
                d->lastOffset = d->offset;
                d->offset =
                        QPointF(p1.pos().x() - p1.startPos().x() + p2.pos().x() - p2.startPos().x(),
                              p1.pos().y() - p1.startPos().y() + p2.pos().y() - p2.startPos().y()) / 2;
            }
            result = QGestureRecognizer::FinishGesture;
        } else {
            result = QGestureRecognizer::CancelGesture;
        }
        break;
    }
    case QEvent::TouchUpdate: {
        if (ev->touchPoints().size() >= 2) {
            QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
            QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
            d->lastOffset = d->offset;
            d->offset =
                    QPointF(p1.pos().x() - p1.startPos().x() + p2.pos().x() - p2.startPos().x(),
                          p1.pos().y() - p1.startPos().y() + p2.pos().y() - p2.startPos().y()) / 2;
            if (d->offset.x() > 10  || d->offset.y() > 10 ||
                d->offset.x() < -10 || d->offset.y() < -10) {
                q->setHotSpot(p1.startScreenPos());
                result = QGestureRecognizer::TriggerGesture;
            } else {
                result = QGestureRecognizer::MayBeGesture;
            }
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QPanGestureRecognizer::reset(QGesture *state)
{
    QPanGesture *pan = static_cast<QPanGesture*>(state);
    QPanGesturePrivate *d = pan->d_func();

    d->lastOffset = d->offset = QPointF();
    d->acceleration = 0;

    QGestureRecognizer::reset(state);
}

//
// QPinchGestureRecognizer
//

QPinchGestureRecognizer::QPinchGestureRecognizer()
{
}

QGesture *QPinchGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    return new QPinchGesture;
}

QGestureRecognizer::Result QPinchGestureRecognizer::recognize(QGesture *state,
                                                              QObject *,
                                                              QEvent *event)
{
    QPinchGesture *q = static_cast<QPinchGesture *>(state);
    QPinchGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result;

    switch (event->type()) {
    case QEvent::TouchBegin: {
        result = QGestureRecognizer::MayBeGesture;
        break;
    }
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture) {
            result = QGestureRecognizer::FinishGesture;
        } else {
            result = QGestureRecognizer::CancelGesture;
        }
        break;
    }
    case QEvent::TouchUpdate: {
        d->changeFlags = 0;
        if (ev->touchPoints().size() == 2) {
            QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
            QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);

            d->hotSpot = p1.screenPos();
            d->isHotSpotSet = true;

            QPointF centerPoint = (p1.screenPos() + p2.screenPos()) / 2.0;
            if (d->isNewSequence) {
                d->startPosition[0] = p1.screenPos();
                d->startPosition[1] = p2.screenPos();
                d->lastCenterPoint = centerPoint;
            } else {
                d->lastCenterPoint = d->centerPoint;
            }
            d->centerPoint = centerPoint;

            d->changeFlags |= QPinchGesture::CenterPointChanged;

            if (d->isNewSequence) {
                d->scaleFactor = 1.0;
                d->lastScaleFactor = 1.0;
            } else {
                d->lastScaleFactor = d->scaleFactor;
                QLineF line(p1.screenPos(), p2.screenPos());
                QLineF lastLine(p1.lastScreenPos(),  p2.lastScreenPos());
                d->scaleFactor = line.length() / lastLine.length();
            }
            d->totalScaleFactor = d->totalScaleFactor * d->scaleFactor;
            d->changeFlags |= QPinchGesture::ScaleFactorChanged;

            qreal angle = QLineF(p1.screenPos(), p2.screenPos()).angle();
            if (angle > 180)
                angle -= 360;
            qreal startAngle = QLineF(p1.startScreenPos(), p2.startScreenPos()).angle();
            if (startAngle > 180)
                startAngle -= 360;
            const qreal rotationAngle = startAngle - angle;
            if (d->isNewSequence)
                d->lastRotationAngle = 0.0;
            else
                d->lastRotationAngle = d->rotationAngle;
            d->rotationAngle = rotationAngle;
            d->totalRotationAngle += d->rotationAngle - d->lastRotationAngle;
            d->changeFlags |= QPinchGesture::RotationAngleChanged;

            d->totalChangeFlags |= d->changeFlags;
            d->isNewSequence = false;
            result = QGestureRecognizer::TriggerGesture;
        } else {
            d->isNewSequence = true;
            if (q->state() == Qt::NoGesture)
                result = QGestureRecognizer::Ignore;
            else
                result = QGestureRecognizer::FinishGesture;
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QPinchGestureRecognizer::reset(QGesture *state)
{
    QPinchGesture *pinch = static_cast<QPinchGesture *>(state);
    QPinchGesturePrivate *d = pinch->d_func();

    d->totalChangeFlags = d->changeFlags = 0;

    d->startCenterPoint = d->lastCenterPoint = d->centerPoint = QPointF();
    d->totalScaleFactor = d->lastScaleFactor = d->scaleFactor = 1;
    d->totalRotationAngle = d->lastRotationAngle = d->rotationAngle = 0;

    d->isNewSequence = true;
    d->startPosition[0] = d->startPosition[1] = QPointF();

    QGestureRecognizer::reset(state);
}

//
// QSwipeGestureRecognizer
//

QSwipeGestureRecognizer::QSwipeGestureRecognizer()
{
}

QGesture *QSwipeGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    return new QSwipeGesture;
}

QGestureRecognizer::Result QSwipeGestureRecognizer::recognize(QGesture *state,
                                                              QObject *,
                                                              QEvent *event)
{
    QSwipeGesture *q = static_cast<QSwipeGesture *>(state);
    QSwipeGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result;

    switch (event->type()) {
    case QEvent::TouchBegin: {
        d->velocityValue = 1;
        d->time.start();
        d->started = true;
        result = QGestureRecognizer::MayBeGesture;
        break;
    }
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture) {
            result = QGestureRecognizer::FinishGesture;
        } else {
            result = QGestureRecognizer::CancelGesture;
        }
        break;
    }
    case QEvent::TouchUpdate: {
        if (!d->started)
            result = QGestureRecognizer::CancelGesture;
        else if (ev->touchPoints().size() == 3) {
            QTouchEvent::TouchPoint p1 = ev->touchPoints().at(0);
            QTouchEvent::TouchPoint p2 = ev->touchPoints().at(1);
            QTouchEvent::TouchPoint p3 = ev->touchPoints().at(2);

            if (d->lastPositions[0].isNull()) {
                d->lastPositions[0] = p1.startScreenPos().toPoint();
                d->lastPositions[1] = p2.startScreenPos().toPoint();
                d->lastPositions[2] = p3.startScreenPos().toPoint();
            }
            d->hotSpot = p1.screenPos();
            d->isHotSpotSet = true;

            int xDistance = (p1.screenPos().x() - d->lastPositions[0].x() +
                             p2.screenPos().x() - d->lastPositions[1].x() +
                             p3.screenPos().x() - d->lastPositions[2].x()) / 3;
            int yDistance = (p1.screenPos().y() - d->lastPositions[0].y() +
                             p2.screenPos().y() - d->lastPositions[1].y() +
                             p3.screenPos().y() - d->lastPositions[2].y()) / 3;

            const int distance = xDistance >= yDistance ? xDistance : yDistance;
            int elapsedTime = d->time.restart();
            if (!elapsedTime)
                elapsedTime = 1;
            d->velocityValue = 0.9 * d->velocityValue + distance / elapsedTime;
            d->swipeAngle = QLineF(p1.startScreenPos(), p1.screenPos()).angle();

            static const int MoveThreshold = 50;
            if (xDistance > MoveThreshold || yDistance > MoveThreshold) {
                // measure the distance to check if the direction changed
                d->lastPositions[0] = p1.screenPos().toPoint();
                d->lastPositions[1] = p2.screenPos().toPoint();
                d->lastPositions[2] = p3.screenPos().toPoint();
                QSwipeGesture::SwipeDirection horizontal =
                        xDistance > 0 ? QSwipeGesture::Right : QSwipeGesture::Left;
                QSwipeGesture::SwipeDirection vertical =
                        yDistance > 0 ? QSwipeGesture::Down : QSwipeGesture::Up;
                if (d->verticalDirection == QSwipeGesture::NoDirection)
                    d->verticalDirection = vertical;
                if (d->horizontalDirection == QSwipeGesture::NoDirection)
                    d->horizontalDirection = horizontal;
                if (d->verticalDirection != vertical || d->horizontalDirection != horizontal) {
                    // the user has changed the direction!
                    result = QGestureRecognizer::CancelGesture;
                }
                result = QGestureRecognizer::TriggerGesture;
            } else {
                if (q->state() != Qt::NoGesture)
                    result = QGestureRecognizer::TriggerGesture;
                else
                    result = QGestureRecognizer::MayBeGesture;
            }
        } else if (ev->touchPoints().size() > 3) {
            result = QGestureRecognizer::CancelGesture;
        } else { // less than 3 touch points
            if (d->started && (ev->touchPointStates() & Qt::TouchPointPressed))
                result = QGestureRecognizer::CancelGesture;
            else if (d->started)
                result = QGestureRecognizer::Ignore;
            else
                result = QGestureRecognizer::MayBeGesture;
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QSwipeGestureRecognizer::reset(QGesture *state)
{
    QSwipeGesture *q = static_cast<QSwipeGesture *>(state);
    QSwipeGesturePrivate *d = q->d_func();

    d->verticalDirection = d->horizontalDirection = QSwipeGesture::NoDirection;
    d->swipeAngle = 0;

    d->lastPositions[0] = d->lastPositions[1] = d->lastPositions[2] = QPoint();
    d->started = false;
    d->velocityValue = 0;
    d->time.invalidate();

    QGestureRecognizer::reset(state);
}

//
// QTapGestureRecognizer
//

QTapGestureRecognizer::QTapGestureRecognizer()
{
}

QGesture *QTapGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    return new QTapGesture;
}

QGestureRecognizer::Result QTapGestureRecognizer::recognize(QGesture *state,
                                                            QObject *,
                                                            QEvent *event)
{
    QTapGesture *q = static_cast<QTapGesture *>(state);
    QTapGesturePrivate *d = q->d_func();

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);

    QGestureRecognizer::Result result = QGestureRecognizer::CancelGesture;

    switch (event->type()) {
    case QEvent::TouchBegin: {
        d->position = ev->touchPoints().at(0).pos();
        q->setHotSpot(ev->touchPoints().at(0).screenPos());
        result = QGestureRecognizer::TriggerGesture;
        break;
    }
    case QEvent::TouchUpdate:
    case QEvent::TouchEnd: {
        if (q->state() != Qt::NoGesture && ev->touchPoints().size() == 1) {
            QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
            QPoint delta = p.pos().toPoint() - p.startPos().toPoint();
            enum { TapRadius = 40 };
            if (delta.manhattanLength() <= TapRadius) {
                if (event->type() == QEvent::TouchEnd)
                    result = QGestureRecognizer::FinishGesture;
                else
                    result = QGestureRecognizer::TriggerGesture;
            }
        }
        break;
    }
    case QEvent::MouseButtonPress:
    case QEvent::MouseMove:
    case QEvent::MouseButtonRelease:
        result = QGestureRecognizer::Ignore;
        break;
    default:
        result = QGestureRecognizer::Ignore;
        break;
    }
    return result;
}

void QTapGestureRecognizer::reset(QGesture *state)
{
    QTapGesture *q = static_cast<QTapGesture *>(state);
    QTapGesturePrivate *d = q->d_func();

    d->position = QPointF();

    QGestureRecognizer::reset(state);
}

//
// QTapAndHoldGestureRecognizer
//

QTapAndHoldGestureRecognizer::QTapAndHoldGestureRecognizer()
{
}

QGesture *QTapAndHoldGestureRecognizer::create(QObject *target)
{
    if (target && target->isWidgetType()) {
        static_cast<QWidget *>(target)->setAttribute(Qt::WA_AcceptTouchEvents);
    }
    return new QTapAndHoldGesture;
}

QGestureRecognizer::Result
QTapAndHoldGestureRecognizer::recognize(QGesture *state, QObject *object,
                                        QEvent *event)
{
    QTapAndHoldGesture *q = static_cast<QTapAndHoldGesture *>(state);
    QTapAndHoldGesturePrivate *d = q->d_func();

    if (object == state && event->type() == QEvent::Timer) {
        q->killTimer(d->timerId);
        d->timerId = 0;
        return QGestureRecognizer::FinishGesture | QGestureRecognizer::ConsumeEventHint;
    }

    const QTouchEvent *ev = static_cast<const QTouchEvent *>(event);
    const QMouseEvent *me = static_cast<const QMouseEvent *>(event);
#ifndef QT_NO_GRAPHICSVIEW
    const QGraphicsSceneMouseEvent *gsme = static_cast<const QGraphicsSceneMouseEvent *>(event);
#endif

    enum { TapRadius = 40 };

    switch (event->type()) {
#ifndef QT_NO_GRAPHICSVIEW
    case QEvent::GraphicsSceneMousePress:
        d->position = gsme->screenPos();
        q->setHotSpot(d->position);
        if (d->timerId)
            q->killTimer(d->timerId);
        d->timerId = q->startTimer(QTapAndHoldGesturePrivate::Timeout);
        return QGestureRecognizer::MayBeGesture; // we don't show a sign of life until the timeout
#endif
    case QEvent::MouseButtonPress:
        d->position = me->globalPos();
        q->setHotSpot(d->position);
        if (d->timerId)
            q->killTimer(d->timerId);
        d->timerId = q->startTimer(QTapAndHoldGesturePrivate::Timeout);
        return QGestureRecognizer::MayBeGesture; // we don't show a sign of life until the timeout
    case QEvent::TouchBegin:
        d->position = ev->touchPoints().at(0).startScreenPos();
        q->setHotSpot(d->position);
        if (d->timerId)
            q->killTimer(d->timerId);
        d->timerId = q->startTimer(QTapAndHoldGesturePrivate::Timeout);
        return QGestureRecognizer::MayBeGesture; // we don't show a sign of life until the timeout
#ifndef QT_NO_GRAPHICSVIEW
    case QEvent::GraphicsSceneMouseRelease:
#endif
    case QEvent::MouseButtonRelease:
    case QEvent::TouchEnd:
        return QGestureRecognizer::CancelGesture; // get out of the MayBeGesture state
    case QEvent::TouchUpdate:
        if (d->timerId && ev->touchPoints().size() == 1) {
            QTouchEvent::TouchPoint p = ev->touchPoints().at(0);
            QPoint delta = p.pos().toPoint() - p.startPos().toPoint();
            if (delta.manhattanLength() <= TapRadius)
                return QGestureRecognizer::MayBeGesture;
        }
        return QGestureRecognizer::CancelGesture;
    case QEvent::MouseMove: {
        QPoint delta = me->globalPos() - d->position.toPoint();
        if (d->timerId && delta.manhattanLength() <= TapRadius)
            return QGestureRecognizer::MayBeGesture;
        return QGestureRecognizer::CancelGesture;
    }
#ifndef QT_NO_GRAPHICSVIEW
    case QEvent::GraphicsSceneMouseMove: {
        QPoint delta = gsme->screenPos() - d->position.toPoint();
        if (d->timerId && delta.manhattanLength() <= TapRadius)
            return QGestureRecognizer::MayBeGesture;
        return QGestureRecognizer::CancelGesture;
    }
#endif
    default:
        return QGestureRecognizer::Ignore;
    }
}

void QTapAndHoldGestureRecognizer::reset(QGesture *state)
{
    QTapAndHoldGesture *q = static_cast<QTapAndHoldGesture *>(state);
    QTapAndHoldGesturePrivate *d = q->d_func();

    d->position = QPointF();
    if (d->timerId)
        q->killTimer(d->timerId);
    d->timerId = 0;

    QGestureRecognizer::reset(state);
}

QT_END_NAMESPACE

#endif // QT_NO_GESTURES


text:
<?php

$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully";

$sql = "SELECT * FROM   GameCenter.User WHERE name = '". $_POST['login']."' AND password = '". $_POST['password']. "'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo ('{
                    "id":'.$row["idd"]).'
                }';
    }
} else {
//    echo "0 results";
}
//print ('aaa');
$conn->close();


text:
<?php namespace Muvuca\Model;

abstract class AbstractModel {

	protected $id;
	protected $active;

	public function __construct($nameValue = []) {
		foreach ($nameValue as $name => $value) {
			$this->__set($name, $value);
		}
	}

	/**
	 * Return the attribute $name or null if it doesn't exist
	 */
	public function __get($name) {
		if (property_exists($this, $name)) {
			if (property_exists($this, $name . 'Id') && !$this->$name) {
				$this->lazyLoad($name);
			}
			if (substr($name, -1) == 's') {
				$columns = $this->getTableColumns();
				if (!in_array($name, $columns)) {
					$class = $this->getModelClass(rtrim($name, 's'));
					if (class_exists($class)) {
						$this->$name = $class::getAllByForeignId(
							$this->getTableName(get_class($this)),
							$this->id
						);
					}
				}
			}
			return $this->$name;
		} else {
			$methodName = 'get' . ucfirst($name);
			if (method_exists($this, $methodName)) {
				return $this->$methodName();
			}
		}

		return null;
	}

	protected function getModelClass($name) {
		return (new \ReflectionClass($this))->getNamespaceName() . '\\' . ucfirst($name) . 'Model';
	}

	protected function lazyLoad($name) {
		$class = $this->getModelClass($name);
		$this->$name = $class::getById($this->{$name . 'Id'});
	}

	/**
	 * Verify if the attribute $name exists. If so, then verifies for a proper validator
	 * to run against the supplied $value. If no validator is found then it's assumed that
	 * there's no need to validate the supplied $value and therefore it is assigned to the
	 * attribute $name
	 */
	public function __set($name, $value) {
		// Don't allow to set IDs because they are generated automatically by the database.
		if (property_exists($this, $name)) {
			$validateMethod = 'validate' . ucfirst($name);
			if (!method_exists($this, $validateMethod) ||
				 method_exists($this, $validateMethod) && $this->$validateMethod($value)) {
				if (property_exists($this, $name . 'Id') && property_exists($value, 'id')) {
					$this->{$name . 'Id'} = $value->id;
				}
				$this->$name = $value;
			}
		}
	}

	/**
	 * Singleton: http://www.phptherightway.com/pages/Design-Patterns.html#singleton
	 */
	protected static function getDb() {
        static $db = null;

		if ($db === null) {
			try {
				$db = new \PDO('sqlite:db/cinema.sqlite3');
			} catch(\PDOException $e) {
				die('An error occured while trying to connect to the database.');
			}
		}
		return $db;
	}

	protected static function getTableName($class) {
		return strtolower(preg_replace("/^.*\\\\(.*)Model$/", '$1', $class));
	}

	protected function getTableColumns() {
		$db = self::getDb();

		$class = get_called_class();
		$table = $this->getTableName($class);

		$result = $db->query("PRAGMA table_info(" . $table . ")");
		$result->setFetchMode(\PDO::FETCH_ASSOC);
		$columns = [];
		foreach ($result as $row) {
			$columns[] = $row;
		}
		return $columns;
	}

	/**
	 * Get all instances of the calling Class
	 */
	public static function getAll() {
		$db = self::getDb();

		$class = get_called_class();
		$table = self::getTableName($class);

		$objects = [];
		foreach ($db->query('SELECT * FROM ' . $table) as $row) {
			$objects[] = new $class($row);
		}
		return $objects;
	}

	/**
	 * Get all instances of the calling Class
	 */
	public static function getAllByForeignId($foreignTable, $foreignId) {
		$db = self::getDb();

		$class = get_called_class();
		$table = self::getTableName($class);

		$objects = [];
		$query = 'SELECT * FROM ' . $table . ' WHERE ' . $foreignTable . 'Id=' . $foreignId;
		foreach ($db->query($query) as $row) {
			$objects[] = new $class($row);
		}
		return $objects;
	}

	/**
	 * Get a instance of the calling Class with the given $id
	 */
	public static function getById($id) {
		$db = self::getDb();

		$class = get_called_class();
		$table = self::getTableName($class);

		$stmt = $db->prepare('SELECT * FROM ' . $table . ' WHERE id=?');
		if ($stmt->execute(array($id))) {
			return new $class($stmt->fetch());
		}
		return null;
	}

	public function save() {
		$db = self::getDb();

		$class = get_called_class();
		$table = $this->getTableName($class);
		$columns = $this->getTableColumns();

		$fields = [];
		$placeHolders = [];
		$values = [];
		foreach ($columns as $column) {
			$fields[$column['name']] = $column['name'];
			$placeHolders[$column['name']] = ':' . $column['name'];
			$values[$column['name']] = $this->$column['name'];
		}
		$query = 'INSERT OR REPLACE INTO ' . $table . '(' . implode(', ', $fields) . ') VALUES ('. implode(', ', $placeHolders) . ')';
		$stmt = $db->prepare($query);
		foreach ($fields as $field) {
			$stmt->bindParam($placeHolders[$field], $values[$field]);
		}
		$res = $stmt->execute();
		$this->id = $db->lastInsertId();
		return $this->id;
	}

	public function delete() {
		$db = self::getDb();
		$stmt = $db->prepare('UPDATE ' . $this->getTableName($class) . ' SET active=0 WHERE id=?');
		$stmt->execute(array($this->id));
	}

}


text:
<?php

namespace MediaWiki\Site;

use FormatJson;
use Http;
use UtfNormal\Validator;

/**
 * Service for normalizing a page name using a MediaWiki api.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 * http://www.gnu.org/copyleft/gpl.html
 *
 * @since 1.27
 *
 * @license GNU GPL v2+
 * @author John Erling Blad < jeblad@gmail.com >
 * @author Daniel Kinzler
 * @author Jeroen De Dauw < jeroendedauw@gmail.com >
 * @author Marius Hoch
 */
class MediaWikiPageNameNormalizer {

	/**
	 * Returns the normalized form of the given page title, using the
	 * normalization rules of the given site. If the given title is a redirect,
	 * the redirect weill be resolved and the redirect target is returned.
	 *
	 * @note This actually makes an API request to the remote site, so beware
	 *   that this function is slow and depends on an external service.
	 *
	 * @see Site::normalizePageName
	 *
	 * @since 1.27
	 *
	 * @param string $pageName
	 * @param string $apiUrl
	 *
	 * @return string
	 * @throws \MWException
	 */
	public function normalizePageName( $pageName, $apiUrl ) {

		// Check if we have strings as arguments.
		if ( !is_string( $pageName ) ) {
			throw new \MWException( '$pageName must be a string' );
		}

		// Go on call the external site

		// Make sure the string is normalized into NFC (due to T42017)
		// but do nothing to the whitespaces, that should work appropriately.
		// @see https://phabricator.wikimedia.org/T42017
		$pageName = Validator::cleanUp( $pageName );

		// Build the args for the specific call
		$args = [
			'action' => 'query',
			'prop' => 'info',
			'redirects' => true,
			'converttitles' => true,
			'format' => 'json',
			'titles' => $pageName,
			// @todo options for maxlag and maxage
			// Note that maxlag will lead to a long delay before a reply is made,
			// but that maxage can avoid the extreme delay. On the other hand
			// maxage could be nice to use anyhow as it stops unnecessary requests.
			// Also consider smaxage if maxage is used.
		];

		$url = wfAppendQuery( $apiUrl, $args );

		// Go on call the external site
		// @todo we need a good way to specify a timeout here.
		$ret = Http::get( $url, [], __METHOD__ );

		if ( $ret === false ) {
			wfDebugLog( "MediaWikiSite", "call to external site failed: $url" );
			return false;
		}

		$data = FormatJson::decode( $ret, true );

		if ( !is_array( $data ) ) {
			wfDebugLog( "MediaWikiSite", "call to <$url> returned bad json: " . $ret );
			return false;
		}

		$page = static::extractPageRecord( $data, $pageName );

		if ( isset( $page['missing'] ) ) {
			wfDebugLog( "MediaWikiSite", "call to <$url> returned a marker for a missing page title! "
				. $ret );
			return false;
		}

		if ( isset( $page['invalid'] ) ) {
			wfDebugLog( "MediaWikiSite", "call to <$url> returned a marker for an invalid page title! "
				. $ret );
			return false;
		}

		if ( !isset( $page['title'] ) ) {
			wfDebugLog( "MediaWikiSite", "call to <$url> did not return a page title! " . $ret );
			return false;
		}

		return $page['title'];
	}

	/**
	 * Get normalization record for a given page title from an API response.
	 *
	 * @param array $externalData A reply from the API on a external server.
	 * @param string $pageTitle Identifies the page at the external site, needing normalization.
	 *
	 * @return array|bool A 'page' structure representing the page identified by $pageTitle.
	 */
	private static function extractPageRecord( $externalData, $pageTitle ) {
		// If there is a special case with only one returned page
		// we can cheat, and only return
		// the single page in the "pages" substructure.
		if ( isset( $externalData['query']['pages'] ) ) {
			$pages = array_values( $externalData['query']['pages'] );
			if ( count( $pages ) === 1 ) {
				return $pages[0];
			}
		}
		// This is only used during internal testing, as it is assumed
		// a more optimal (and lossfree) storage.
		// Make initial checks and return if prerequisites are not meet.
		if ( !is_array( $externalData ) || !isset( $externalData['query'] ) ) {
			return false;
		}
		// Loop over the tree different named structures, that otherwise are similar
		$structs = [
			'normalized' => 'from',
			'converted' => 'from',
			'redirects' => 'from',
			'pages' => 'title'
		];
		foreach ( $structs as $listId => $fieldId ) {
			// Check if the substructure exist at all.
			if ( !isset( $externalData['query'][$listId] ) ) {
				continue;
			}
			// Filter the substructure down to what we actually are using.
			$collectedHits = array_filter(
				array_values( $externalData['query'][$listId] ),
				function ( $a ) use ( $fieldId, $pageTitle ) {
					return $a[$fieldId] === $pageTitle;
				}
			);
			// If still looping over normalization, conversion or redirects,
			// then we need to keep the new page title for later rounds.
			if ( $fieldId === 'from' && is_array( $collectedHits ) ) {
				switch ( count( $collectedHits ) ) {
					case 0:
						break;
					case 1:
						$pageTitle = $collectedHits[0]['to'];
						break;
					default:
						return false;
				}
			} elseif ( $fieldId === 'title' && is_array( $collectedHits ) ) {
				// If on the pages structure we should prepare for returning.

				switch ( count( $collectedHits ) ) {
					case 0:
						return false;
					case 1:
						return array_shift( $collectedHits );
					default:
						return false;
				}
			}
		}
		// should never be here
		return false;
	}

}


text:
package com.geeksforgeeks.SegmentTree;

import java.util.Arrays;

/**
 * Created by Vaidehi on 12/1/16.
 */
public class SegmentTree {

    public int[] createSegmentTree(int[] input){
        int[] segmentTree;
        /*
            Height of the segment tree = Ceil(log(n) to the base 2)
         */
        int heightST = (int)Math.ceil(Math.log10(input.length)/Math.log10(2));
        /*
            Total elements in the segment tree is 2*(2^height -1)
         */
        int sizeST = (int)(2*(Math.pow(2, heightST) - 1));
        segmentTree = new int[sizeST];
        constructSegmentTree(segmentTree, input, 0, input.length - 1, 0);
        return segmentTree;

    }

    private void constructSegmentTree(int[] segmentTree, int[] input, int low, int high, int indexST){
        /*
            Leaf nodes of the segment tree are always the elements of the input array
         */
        if(low == high){
            segmentTree[indexST] = input[low];
            return;
        }

        int mid  = (low + high)/2;
        int leftChild = 2*indexST + 1;
        int rightChild = 2*indexST + 2;
        constructSegmentTree(segmentTree, input, low, mid, leftChild);
        constructSegmentTree(segmentTree, input, mid + 1, high, rightChild);
        segmentTree[indexST] = Math.min(segmentTree[leftChild], segmentTree[rightChild]);
    }

    public static void main(String[] args){
        SegmentTree segmentTree = new SegmentTree();
        System.out.println(Arrays.toString(segmentTree.createSegmentTree(new int[]{-1, 3,4,0,2,1})));
    }

}