text:
import React, { Component } from 'react';
import createHistory from 'history/createHashHistory';
import PropTypes from 'prop-types';
import { updateRoute } from '../actions';
import { countSlides } from './slides';

import theme from '../themes/default';
import Context from './context';

const history = createHistory();

export default class Controller extends Component {
  static propTypes = {
    children: PropTypes.node,
    history: PropTypes.object,
    store: PropTypes.object,
    theme: PropTypes.object,
  };

  constructor(props) {
    super(props);

    this.history = props.history || history;
  }

  state = {
    print: false,
  };

  componentDidMount() {
    this.unlisten = this.history.listen(this._updateRoute.bind(this));
    const location = this.history.location;
    const slideCount = countSlides(this.props.children.props.children);
    this.props.store.dispatch(
      updateRoute({
        location,
        slideCount,
      })
    );
  }

  shouldComponentUpdate(nextProps, nextState) {
    return this.props !== nextProps || this.state !== nextState;
  }

  componentWillUnmount() {
    this.unlisten();
  }

  _updateRoute(location) {
    this.setState(
      {
        print: location.search.indexOf('print') !== -1,
      },
      () => {
        const slideCount = countSlides(this.props.children.props.children);
        this.props.store.dispatch(
          updateRoute({
            location,
            slideCount,
          })
        );
      }
    );
  }

  render() {
    const styles = this.props.theme ? this.props.theme : theme();
    /*return (
      <History>
        {(history) => {
          const { action, location } = history;
          const printEnabled = location.search.indexOf("print") !== -1;
          return (
            <Context
              store={this.props.store}
              history={history}
              styles={printEnabled ? styles.print : styles.screen}
            >
              {this.props.children}
            </Context>
          );
        }}
      </History>*/

    return (
      <Context
        store={this.props.store}
        history={history}
        styles={this.state.print ? styles.print : styles.screen}
      >
        {this.props.children}
      </Context>
    );
  }
}


text:
<title> CS140 -- Lab 1</title>

 CS140 -- Lab 1

 CS140 -- Data Structures & Algorithms I

 Spring 2014

 James S. Plank

 This file:
     http://web.eecs.utk.edu/~plank/plank/classes/cs140/Labs/Lab1

 Lab Directory: /home/plank/cs140/Labs/Lab1

This lab has two programs to hand in: checkerboard.cpp and moonglow.cpp.
You can do this lab with only this information from
the
C++ review lecture notes.  In particular, you don't need stringstreams or any such
mess.  Just a good understanding of cin.

Checkerboard.cpp

A generalized checkerboard is a rectangular grid one that has four parameters:

 R: The number of rows.

 C: The number of columns.

 SC: The starting character.

 CS: The cycle size.

The grid is a (R * C) matrix, where the element in row r and column c,
contains the character SC + (r+c)%CS.  For example, here's a generalized checkerboard
with R=5, C=6, SC = 'a' and CS=4:

 a	 b	 c	 d	 a	 b

 b	 c	 d	 a	 b	 c

 c	 d	 a	 b	 c	 d

 d	 a	 b	 c	 d	 a

 a	 b	 c	 d	 a	 b

Your job is to write the program checkerboard.cpp, which reads five integers from
standard input.  The first four are the parameters R,
C, SC and CS, as defined above.  The fifth
parameter is a width W.

Your program should print out the specified checkerboard such that
each element of the grid is printed as a (W * W) square.  Here
are some examples:

UNIX> ./checkerboard
5 6 a 4 1
abcdab
bcdabc
cdabcd
dabcda
abcdab
UNIX> ./checkerboard
5 6 a 4 3
aaabbbcccdddaaabbb
aaabbbcccdddaaabbb
aaabbbcccdddaaabbb
bbbcccdddaaabbbccc
bbbcccdddaaabbbccc
bbbcccdddaaabbbccc
cccdddaaabbbcccddd
cccdddaaabbbcccddd
cccdddaaabbbcccddd
dddaaabbbcccdddaaa
dddaaabbbcccdddaaa
dddaaabbbcccdddaaa
aaabbbcccdddaaabbb
aaabbbcccdddaaabbb
aaabbbcccdddaaabbb
UNIX> checkerboard
4 40 J 20 3
JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]
JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]
JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]
KKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJ
KKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJ
KKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJ
LLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKK
LLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKK
LLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKK
MMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLL
MMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLL
MMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLLMMMNNNOOOPPPQQQRRRSSSTTTUUUVVVWWWXXXYYYZZZ[[[\\\]]]JJJKKKLLL
UNIX> ./checkerboard
4 40 0 2 3
000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111
000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111
000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111
111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000
111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000
111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000
000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111
000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111
000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111
111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000
111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000
111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000111000
UNIX>

Error checking: Your program should print the same output as mine on standard error if too
few arguments are given, or if they are not numbers.
It should exit silently if any of the parameters is less than or
equal to zero, and if the ASCII value of the starting character plus the cycle size is greater than 127.

Moonglow.cpp

Your sister Sheri is an Philosophy professor.  She recently gave a midterm
exam to 500 students in her intro class, and it was graded by her PhD
student, Moonglow (philosophy students have names like these),
who put each student's test scores into a text file with a
rather byzantine format.
Unfortunately, before Moonglow could convert those files to Excel for Sheri,
his wife Sunshine left him, got into their VW van with their child Starrlite
and drove home to the commune in northern California where they grew up.
That should not surprise you.  Moonglow of course followed her, and
since the commune is off the grid (duh), Sheri is stuck with 500 text
files that she doesn't know how to process.

Fortunately, you're in CS140, and Sheri has offered you a quarter of her
grant money to convert those files into a more palatable format.
$25 isn't a huge amount of money, but you love your sister, and this
shouldn't take you long, so you agree.  You are to write the program
moonglow.cpp which reads a file in Moonglow's format on standard
input, and prints a very simple output.

Here's Moonglow's format.  The text file is composed of words.  If a word is a number,
then that is a student's score on a question, so you add it to the student's exam score.
If the word is not a number, but is the word "NAME", then the next word is the student's
name (Moonglow only uses first names -- last names are corporate and impersonal).
If the word is "AVERAGE", then you start reading numbers until you read a word that
is not a number (or is the end of the file).  You average all of those numbers and add
that to the score.  Since Moonglow is a little scatterbrained, sometimes a number
does not follow "AVERAGE."  In that case, you ignore the "AVERAGE".

When you are done reading the file, your program should print the student's name, a space,
and the student's score.  Just use cout for this -- nothing exciting.

Error Checking

You don't have to check for errors, and you may assume that the input is in the correct
format.  That would cost Sheri more money.  However, this is a pretty flexible format.
The only things that you need to assume are:

 The input will specify exactly one student's name.

 That student's name won't be "AVERAGE" or "NAME."

Here are some examples:

UNIX> cat test-1.txt
NAME Fred
UNIX> ./moonglow < test-1.txt
Fred 0
UNIX> cat test-2.txt
NAME Dontonio
8.6
16.2
UNIX> ./moonglow < test-2.txt
Dontonio 24.8
UNIX> cat test-3.txt
I miss Starrlight!!
15 NAME
Frank
UNIX> ./moonglow < test-3.txt
Frank 15
UNIX> cat test-4.txt
AVERAGE 10 15 20 NAME Luther 10 Starrlite!!
UNIX> ./moonglow < test-4.txt
Luther 25
UNIX> cat test-5.txt
NAME Baby-Daisy
AVERAGE 3 4 5 6
AVERAGE 7 8 9
Where's Starrlite!!
UNIX> ./moonglow < test-5.txt
Baby-Daisy 12.5
UNIX> cat test-6.txt
Starrlite AVERAGE Starrlite!!! NAME
Starrlite
AVERAGE 55 Starrlite!!!  Starrlite
AVERAGE Starrlite 5 6 7
UNIX> ./moonglow < test-6.txt
Starrlite 73
UNIX>

Some comments on the examples.  First, the file doesn't have to have any scores, like
test-1.txt.  Second, you should use doubles and not
integers.  Third, the "NAME" can appear anywhere, and can be on a different line
than the name, as in
test-3.txt.   Last, the "AVERAGE" can have zero numbers
after it, as it does twice in
test-6.txt.   Thus, in the file, the score is 55,
from the second "AVERAGE", plus 5, 6 and 7, which equals 73.

The Gradescript

The grading programs are in
/home/plank/cs140/Labs/Lab1/gradescript and
/home/plank/cs140/Labs/Lab1/gradeall

The first 30 tests are for checkerboard.  The remaining 70 are for moonglow.

redpajama_set_name: RedPajamaGithub


text:
package goryachev.swing;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.util.ArrayList;
import javax.swing.CellRendererPane;
import javax.swing.Icon;
import javax.swing.SwingUtilities;

public abstract class AbstractAnimatedIcon
	implements CAnimator.Client, Icon
{
	public abstract Image generateFrame(Component c, int frame);

	//

	private ArrayList<Repaint> repaints = new ArrayList();
	private int frame;
	private int frameCount;
	private int period;
	private boolean startAnimator = true;
	private CAnimator animator;

	public AbstractAnimatedIcon(int frameCount, int period)
	{
		this.frameCount = frameCount;
		this.period = period;
	}

	public void paintIcon(Component c, Graphics g, int x, int y)
	{
		Image image = generateFrame(c, frame);
		g.drawImage(image, x, y, null);

		if(startAnimator)
		{
			animator = new CAnimator(this, period);
			startAnimator = false;
		}

		registerRepaint(c,x,y);
	}

	public void stopAnimation()
	{
		if(animator != null)
		{
			animator.stop();
		}
	}

	public void startAnimation()
	{
		if(animator == null)
		{
			// may not work!
			startAnimator = true;
		}
	}

	// remember the component being repainted and location of the paint area (the size of this icon)
	// in case of cell renderers, the component in question is actually the parent of a CellRendererPane
	// when the animation timer is fired, all the memorized repaints are fired again, and either of two
	// possible thing happen:
	// 1. the animated icon is still at the old location and the paintComponent() will be issued, repeating the process, or
	// 2. the animated icon is not there and no repaint would come to this icon
	// no special care is taken to eliminate duplicate repaints.
	protected void registerRepaint(Component c, int x, int y)
	{
		Component actual = findActualComponent(c);
		if(actual != null)
		{
			Point p = SwingUtilities.convertPoint(c, x, y, actual);
			c = actual;
			x = p.x;
			y = p.y;
		}
		repaints.add(new Repaint(c, x, y, getIconWidth(), getIconHeight()));
	}

	private Component findActualComponent(Component c)
	{
		Component actual = SwingUtilities.getAncestorOfClass(CellRendererPane.class, c);
		if((actual != null) && (actual.getParent() != null))
		{
			c = findActualComponent(actual.getParent());
		}
		return c;
	}

	public void nextFrame()
	{
		if(++frame >= frameCount)
		{
			frame = 0;
		}

		if(repaints.size() > 0)
		{
			for(Repaint r: repaints)
			{
				r.repaint();
			}

			repaints.clear();
		}
	}

	public int currentFrame()
	{
		return frame;
	}

	public int getFrameCount()
	{
		return frameCount;
	}

	public int getPeriod()
	{
		return period;
	}

	//

	public static class Repaint
	{
		public Component component;
		public int x;
		public int y;
		public int width;
		public int height;

		public Repaint(Component c, int x, int y, int w, int h)
		{
			this.component = c;
			this.x = x;
			this.y = y;
			this.width = w;
			this.height = h;
		}

		public void repaint()
		{
			component.repaint(x, y, width, height);
		}
	}
}


text:
function temp_schedule = compute_cooling_schedule(init_temp, final_temp, anneal_rate)

temp_schedule = [];
i = 1;
temp_schedule(i)=init_temp;
while temp_schedule(i) > final_temp
  i = i + 1;
  temp_schedule(i)=temp_schedule(i-1)*anneal_rate;
end


text:
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you 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.

"""

import sys
from resource_management import *

from postgresql_service import postgresql_service

class PostgreSQLServer(Script):

  def install(self, env):
    self.install_packages(env)
    self.configure(env)

  def configure(self, env):
    import params
    env.set_params(params)

    # init the database, the ':' makes the command always return 0 in case the database has
    # already been initialized when the postgresql server colocates with ambari server
    Execute(format("service {postgresql_daemon_name} initdb || :"))

    # update the configuration files
    self.update_pghda_conf(env)
    self.update_postgresql_conf(env)

    # Reload the settings and start the postgresql server for the changes to take effect
    # Note: Don't restart the postgresql server because when Ambari server and the hive metastore on the same machine,
    # they will share the same postgresql server instance. Restarting the postgresql database may cause the ambari server database connection lost
    postgresql_service(postgresql_daemon_name=params.postgresql_daemon_name, action = 'reload')

    # ensure the postgresql server is started because the add hive metastore user requires the server is running.
    self.start(env)

    # create the database and hive_metastore_user
    File(params.postgresql_adduser_path,
         mode=0755,
         content=StaticFile(format("{postgresql_adduser_file}"))
    )

    cmd = format("bash -x {postgresql_adduser_path} {postgresql_daemon_name} {hive_metastore_user_name} {hive_metastore_user_passwd!p} {db_name}")

    Execute(cmd,
            tries=3,
            try_sleep=5,
            path='/usr/sbin:/sbin:/usr/local/bin:/bin:/usr/bin'
    )

  def start(self, env):
    import params
    env.set_params(params)

    postgresql_service(postgresql_daemon_name=params.postgresql_daemon_name, action = 'start')

  def stop(self, env):
    import params
    env.set_params(params)

    postgresql_service(postgresql_daemon_name=params.postgresql_daemon_name, action = 'stop')

  def status(self, env):
    import status_params
    postgresql_service(postgresql_daemon_name=status_params.postgresql_daemon_name, action = 'status')

  def update_postgresql_conf(self, env):
    import params
    env.set_params(params)

    # change the listen_address to *
    Execute(format("sed -i '/^[[:space:]]*listen_addresses[[:space:]]*=.*/d' {postgresql_conf_path}"))
    Execute(format("echo \"listen_addresses = '*'\" | tee -a {postgresql_conf_path}"))

    # change the standard_conforming_string to off
    Execute(format("sed -i '/^[[:space:]]*standard_conforming_strings[[:space:]]*=.*/d' {postgresql_conf_path}"))
    Execute(format("echo \"standard_conforming_strings = off\" | tee -a {postgresql_conf_path}"))

  def update_pghda_conf(self, env):
    import params
    env.set_params(params)

    # trust hive_metastore_user and postgres locally
    Execute(format("sed -i '/^[[:space:]]*local[[:space:]]*all[[:space:]]*all.*$/s/^/#/' {postgresql_pghba_conf_path}"))
    Execute(format("sed -i '/^[[:space:]]*local[[:space:]]*all[[:space:]]*postgres.*$/d' {postgresql_pghba_conf_path}"))
    Execute(format("sed -i '/^[[:space:]]*local[[:space:]]*all[[:space:]]*\"{hive_metastore_user_name}\".*$/d' {postgresql_pghba_conf_path}"))
    Execute(format("echo \"local   all   postgres   trust\" | tee -a {postgresql_pghba_conf_path}"))
    Execute(format("echo \"local   all   \\\"{hive_metastore_user_name}\\\" trust\" | tee -a {postgresql_pghba_conf_path}"))

    # trust hive_metastore_user and postgres via local interface
    Execute(format("sed -i '/^[[:space:]]*host[[:space:]]*all[[:space:]]*all.*$/s/^/#/' {postgresql_pghba_conf_path}"))
    Execute(format("sed -i '/^[[:space:]]*host[[:space:]]*all[[:space:]]*postgres.*$/d' {postgresql_pghba_conf_path}"))
    Execute(format("sed -i '/^[[:space:]]*host[[:space:]]*all[[:space:]]*\"{hive_metastore_user_name}\".*$/d' {postgresql_pghba_conf_path}"))
    Execute(format("echo \"host    all   postgres         0.0.0.0/0       trust\" | tee -a {postgresql_pghba_conf_path}"))
    Execute(format("echo \"host    all   \\\"{hive_metastore_user_name}\\\"         0.0.0.0/0       trust\" | tee -a {postgresql_pghba_conf_path}"))

if __name__ == "__main__":
  PostgreSQLServer().execute()


text:
using System.Collections.Specialized;
using Dadata.Model;

namespace Dadata
{
    public class SuggestClientSync : ClientBaseSync, ISuggestClientSync
    {
        protected const string BASE_URL = "https://suggestions.dadata.ru/suggestions/api/4_1/rs";

        public SuggestClientSync(string token, string baseUrl = BASE_URL) : base(token, baseUrl) { }

        #region Address

        public SuggestResponse<Address> SuggestAddress(string query, int count = 5)
        {
            var request = new SuggestAddressRequest(query, count);
            return SuggestAddress(request);
        }

        public SuggestResponse<Address> SuggestAddress(SuggestAddressRequest request)
        {
            return Execute<SuggestResponse<Address>>(method: SuggestionsMethod.Suggest, entity: SuggestionsEntity.Address, request: request);
        }

        public SuggestResponse<Address> FindAddress(string query)
        {
            var request = new FindAddressRequest(query);
            return FindAddress(request);
        }

        public SuggestResponse<Address> FindAddress(FindAddressRequest request)
        {
            return Execute<SuggestResponse<Address>>(method: SuggestionsMethod.Find, entity: SuggestionsEntity.Address, request: request);
        }

        public SuggestResponse<Address> Geolocate(double lat, double lon, int radius_meters = 100, int count = 5)
        {
            var request = new GeolocateRequest(lat, lon, radius_meters, count);
            return Geolocate(request);
        }

        public SuggestResponse<Address> Geolocate(GeolocateRequest request)
        {
            return Execute<SuggestResponse<Address>>(method: SuggestionsMethod.Geolocate, entity: SuggestionsEntity.Address, request: request);
        }

        public IplocateResponse Iplocate(string ip, string language = "ru")
        {
            var parameters = new NameValueCollection();
            parameters.Add("ip", ip);
            parameters.Add("language", language);
            return ExecuteGet<IplocateResponse>(method: SuggestionsMethod.Iplocate, entity: SuggestionsEntity.Address, parameters: parameters);
        }

        #endregion

        #region Bank

        public SuggestResponse<Bank> SuggestBank(string query, int count = 5)
        {
            var request = new SuggestBankRequest(query, count);
            return SuggestBank(request);
        }

        public SuggestResponse<Bank> SuggestBank(SuggestBankRequest request)
        {
            return Execute<SuggestResponse<Bank>>(method: SuggestionsMethod.Suggest, entity: SuggestionsEntity.Bank, request: request);
        }

        public SuggestResponse<Bank> FindBank(string query)
        {
            var request = new FindBankRequest(query);
            return FindBank(request);
        }

        public SuggestResponse<Bank> FindBank(FindBankRequest request)
        {
            return Execute<SuggestResponse<Bank>>(method: SuggestionsMethod.Find, entity: SuggestionsEntity.Bank, request: request);
        }

        #endregion

        #region Email

        public SuggestResponse<Email> SuggestEmail(string query, int count = 5)
        {
            var request = new SuggestRequest(query, count);
            return SuggestEmail(request);
        }

        public SuggestResponse<Email> SuggestEmail(SuggestRequest request)
        {
            return Execute<SuggestResponse<Email>>(method: SuggestionsMethod.Suggest, entity: SuggestionsEntity.Email, request: request);
        }

        #endregion

        #region Fias

        public SuggestResponse<FiasAddress> SuggestFias(string query, int count = 5)
        {
            var request = new SuggestAddressRequest(query, count);
            return SuggestFias(request);
        }

        public SuggestResponse<FiasAddress> SuggestFias(SuggestAddressRequest request)
        {
            return Execute<SuggestResponse<FiasAddress>>(method: SuggestionsMethod.Suggest, entity: SuggestionsEntity.Fias, request: request);
        }

        public SuggestResponse<FiasAddress> FindFias(string query)
        {
            var request = new SuggestRequest(query);
            return FindFias(request);
        }

        public SuggestResponse<FiasAddress> FindFias(SuggestRequest request)
        {
            return Execute<SuggestResponse<FiasAddress>>(method: SuggestionsMethod.Find, entity: SuggestionsEntity.Fias, request: request);
        }

        #endregion

        #region Name

        public SuggestResponse<Fullname> SuggestName(string query, int count = 5)
        {
            var request = new SuggestNameRequest(query, count);
            return SuggestName(request);
        }

        public SuggestResponse<Fullname> SuggestName(SuggestNameRequest request)
        {
            return Execute<SuggestResponse<Fullname>>(method: SuggestionsMethod.Suggest, entity: SuggestionsEntity.Name, request: request);
        }

        #endregion

        #region Party

        public SuggestResponse<Party> SuggestParty(string query, int count = 5)
        {
            var request = new SuggestPartyRequest(query, count);
            return SuggestParty(request);
        }

        public SuggestResponse<Party> SuggestParty(SuggestPartyRequest request)
        {
            return Execute<SuggestResponse<Party>>(method: SuggestionsMethod.Suggest, entity: SuggestionsEntity.Party, request: request);
        }

        public SuggestResponse<Party> FindParty(string query)
        {
            var request = new FindPartyRequest(query);
            return FindParty(request);
        }

        public SuggestResponse<Party> FindParty(FindPartyRequest request)
        {
            return Execute<SuggestResponse<Party>>(method: SuggestionsMethod.Find, entity: SuggestionsEntity.Party, request: request);
        }

        public SuggestResponse<Party> FindAffiliated(string query)
        {
            var request = new FindAffiliatedRequest(query);
            return FindAffiliated(request);
        }

        public SuggestResponse<Party> FindAffiliated(FindAffiliatedRequest request)
        {
            return Execute<SuggestResponse<Party>>(method: SuggestionsMethod.FindAffiliated, entity: SuggestionsEntity.Party, request: request);
        }

        #endregion
    }
}


text:
package io.cloudslang.engine.queue.services;

import io.cloudslang.score.facade.entities.Execution;
import io.cloudslang.score.events.ScoreEvent;

/**
 * User:
 * Date: 30/07/2014
 *
 * A factory to create {@link io.cloudslang.score.events.ScoreEvent}
 *
 */
public interface ScoreEventFactory {

    /**
     *
     * Creates a {@link io.cloudslang.score.events.ScoreEvent}
     * for finished execution state
     *
     * @param execution the execution to create the event from
     * @return {@link io.cloudslang.score.events.ScoreEvent} of the finished state
     */
	public ScoreEvent createFinishedEvent(Execution execution);

    /**
     *
     * Creates a {@link io.cloudslang.score.events.ScoreEvent}
     * for failed branch execution state
     *
     * @param execution the execution to create the event from
     * @return {@link io.cloudslang.score.events.ScoreEvent} of the failed branch state
     */
	public ScoreEvent createFailedBranchEvent(Execution execution);

    /**
     *
     * Creates a {@link io.cloudslang.score.events.ScoreEvent}
     * for failure execution state
     *
     * @param execution the execution to create the event from
     * @return {@link io.cloudslang.score.events.ScoreEvent} of the failure state
     */
	public ScoreEvent createFailureEvent(Execution execution);

    /**
     *
     * Creates a {@link io.cloudslang.score.events.ScoreEvent}
     * for no worker execution state
     *
     * @param execution the execution to create the event from
     * @return {@link io.cloudslang.score.events.ScoreEvent} of the no worker state
     */
	public ScoreEvent createNoWorkerEvent(Execution execution, Long pauseId);

    /**
     *
     * Creates a {@link io.cloudslang.score.events.ScoreEvent}
     * for finished branch execution state
     *
     * @param execution the execution to create the event from
     * @return {@link io.cloudslang.score.events.ScoreEvent} of the finished branch state
     */
    public ScoreEvent createFinishedBranchEvent(Execution execution);

 /**
     *
     * Creates a {@link io.cloudslang.score.events.ScoreEvent}
     * for excepted branch execution state
     *
     * @param execution the execution to create the event from
     * @return {@link io.cloudslang.score.events.ScoreEvent} of the excepted branch state
     */
//    public ScoreEvent createExceptedBranchEvent(Execution execution);

    /**
     * Creates a {@link io.cloudslang.score.events.ScoreEvent}
     * for excepted branch execution state
     *
     * @param execution the execution to create the event from
     * @param exceptionMessage
     * @return {@link io.cloudslang.score.events.ScoreEvent} of the excepted branch state
     */
    public ScoreEvent createCorruptedMessageEvent(Execution execution, String exceptionMessage);
}


text:
/*************** Adapters & Serializers ****************/

ASTool.AnnotationsStore = Em.Object.extend({
	iframeBinding: 'ASTool.iframe',

	findAll: function() {
		var annotatedElements = this.get('iframe').findAnnotatedElements();
		var annotationJSONs = [];
		var annotations = [];
		annotatedElements.each(function(i, element) {
			var annotationJSON = $.parseJSON($(element).attr('data-scrapy-annotate'));
			if (!annotationJSON['id']) {
				// This looks like an old Austoscraping project annotation as it doesn't have
				// an assigned id. Create one for it.
				annotationJSON['id'] = ASTool.shortGuid();
				$(element).attr('data-scrapy-annotate', JSON.stringify(annotationJSON));
			}
			annotationJSONs.pushObject(annotationJSON);
		}.bind(this));
		this._findIgnoresParentAnnotation();
		return annotationJSONs.map(function(annotationJSON) {
			return ASTool.Annotation.create(annotationJSON);
		});
	},

	_findIgnoresParentAnnotation: function() {
		var ignoredElements = this.get('iframe').findIgnoredElements();
		ignoredElements.each(function(index, ignoredElement) {
			var ignore;
			var attributeName;
			if ($(ignoredElement).attr('data-scrapy-ignore')) {
				attributeName = 'data-scrapy-ignore';
			} else {
				attributeName = 'data-scrapy-ignore-beneath';
			}
			ignore = $.parseJSON($(ignoredElement).attr(attributeName));
			if (!ignore['id']) {
				ignore = {};
				$(ignoredElement).parents().each(function(index, parent) {
					if ($(parent).attr('data-scrapy-annotate')) {
						ignore['id'] = $.parseJSON($(parent).attr('data-scrapy-annotate'))['id']
						$(ignoredElement).attr(attributeName, JSON.stringify(ignore));
						return false;
					}
				});
			}
		});
	},

	_prepareToSave: function() {
		var ignoredElements = this.get('iframe').findIgnoredElements();
		ignoredElements.removeAttr('data-scrapy-ignore');
		ignoredElements.removeAttr('data-scrapy-ignore-beneath');
		var annotatedElements = this.get('iframe').findAnnotatedElements();
		annotatedElements.each(function(i, element) {
			$(element).attr('data-scrapy-annotate', null);
		}.bind(this));
	},

	saveAll: function(annotations) {
		this._prepareToSave();
		annotations.forEach(function(annotation) {
			annotation.get('ignores').forEach(function(ignore) {
				var attrName = ignore.get('ignoreBeneath') ? 'data-scrapy-ignore-beneath' : 'data-scrapy-ignore';
				$(ignore.get('element')).attr(attrName, 'true');
			});
			$(annotation.get('element')).attr('data-scrapy-annotate',
				JSON.stringify(annotation.serialize()));
		}.bind(this));
	},
});

/*************************** Models **************************/

ASTool.SimpleModel = Em.Object.extend(Em.Copyable, {
	idBinding: 'name',
	name: null,
	serializedProperties: null,
	serializedRelations: null,

	copy: function() {
		return Em.run(this.constructor, 'create', this);
	},

	serialize: function() {
		var serialized = this.getProperties(this.get('serializedProperties'));
		if (!Em.isEmpty(this.get('serializedRelations'))) {
			this.get('serializedRelations').forEach(function(relation) {
				serialized[relation] = this.get(relation).map(function(relatedObject) {
					return relatedObject.serialize();
				});
			}.bind(this));
		}
		return serialized;
	},
});

ASTool.Template = ASTool.SimpleModel.extend({
	serializedProperties: ['page_id', 'default', 'scrapes',
		'page_type', 'url', 'annotated_body', 'original_body',
		'extractors', 'name'],
	page_id: '',
	scrapes: 'default',
	page_type: 'item',
	url: '',
	annotated_body: '',
	original_body: '',
	extractors: null,
}),

ASTool.Spider = ASTool.SimpleModel.extend({
	serializedProperties: ['start_urls',
		'start_urls', 'links_to_follow', 'follow_patterns',
		'exclude_patterns', 'respect_nofollow',
		'init_requests'],
	serializedRelations: ['templates'],
	start_urls: null,
	links_to_follow: 'patterns',
	follow_patterns: null,
	exclude_patterns: null,
	respect_nofollow: true,
	templates: null,
	init_requests: null,

	init: function() {
		if (this.get('init_requests') == null) {
			this.set('init_requests', []);
		}
	},

	performLogin: function(key, performLogin) {
		if (arguments.length > 1) {
			if (performLogin) {
				this.get('init_requests').setObjects([{ type: 'login' }]);
			} else {
				this.get('init_requests').setObjects([]);
			}
		}
		return !Ember.isEmpty(this.get('init_requests'));
	}.property('init_requests'),

	loginUrl: function(key, loginUrl) {
		var reqs = this.get('init_requests');
		if (arguments.length > 1) {
			reqs[0]['loginurl'] = loginUrl;
		}
		return reqs.length ? reqs[0]['loginurl'] : null;
	}.property('init_requests'),

	loginUser: function(key, loginUser) {
		var reqs = this.get('init_requests');
		if (arguments.length > 1) {
			reqs[0]['username'] = loginUser;
		}
		return reqs.length ? reqs[0]['username'] : null;
	}.property('init_requests'),

	loginPassword: function(key, loginPassword) {
		var reqs = this.get('init_requests');
		if (arguments.length > 1) {
			reqs[0]['password'] = loginPassword;
		}
		return reqs.length ? reqs[0]['password'] : null;
	}.property('init_requests'),
}),

ASTool.Annotation = ASTool.SimpleModel.extend({

	init: function() {
		this._super();
		var ignoredElements = this.get('iframe').findIgnoredElements(this.get('id')).toArray();
		var ignores = ignoredElements.map(function(element) {
			var attributeName = $(element).attr('data-scrapy-ignore') ? 'data-scrapy-ignore' : 'data-scrapy-ignore-beneath';
			var name = $.parseJSON($(element).attr(attributeName))['name'];
			return ASTool.Ignore.create({element: element,
										 name: name,
										 ignoreBeneath: attributeName == 'data-scrapy-ignore-beneath'});
		});
		this.set('ignores', ignores);
		if (this.get('required') == null) {
			this.set('required', []);
		}
		if (this.get('annotations') == null) {
			this.set('annotations', {});
		}
	},

	idBinding: null,

	serializedProperties: ['id', 'variant', 'annotations', 'required', 'generated'],

	name: function() {
		var annotations = this.get('annotations');
		if (annotations && Object.keys(annotations).length) {
			var name = '';
			Object.keys(annotations).forEach(function(key) {
				name += (name.length ? ', ' : '') + key + '  >  ';
				name += annotations[key];
			});
			return name;
		} else {
			return 'No mappings';
		}
	}.property('annotations'),

	variant: 0,

	annotations: null,

	required: null,

	generated: false,

	ignores: null,

	iframeBinding: 'ASTool.iframe',

	addMapping: function(attribute, itemField) {
		this.get('annotations')[attribute] = itemField;
		this.notifyPropertyChange('annotations');
	},

	removeMapping: function(attribute) {
		this.removeRequired(this.get('annotations')[attribute]);
		delete this.get('annotations')[attribute];
		this.notifyPropertyChange('annotations');
	},

	removeMappings: function() {
		this.set('annotations', {});
		this.set('required', []);
		this.notifyPropertyChange('annotations');
	},

	addRequired: function(field) {
		this.get('required').pushObject(field);
	},

	removeRequired: function(field) {
		this.get('required').removeObject(field);
	},

	addIgnore: function(element) {
		var ignore = ASTool.Ignore.create({element: element});
		this.get('ignores').pushObject(ignore);
	},

	removeIgnore: function(ignore) {
		this.get('ignores').removeObject(ignore);
	},

	removeIgnores: function() {
		this.get('ignores').setObjects([]);
	},

	partialText: function() {
		if (this.get('element') && this.get('generated')) {
			return $(this.get('element')).text();
		} else {
			return '';
		}
	}.property('element'),

	selectedElement: null,

	element: function() {
		if (this.get('selectedElement')) {
			return this.get('selectedElement');
		} else {
			var annotatedElement = this.get('iframe').findAnnotatedElement(this.get('id'));
			if (annotatedElement.length) {
				return annotatedElement.get(0);
			} else {
				return null;
			}
		}
	}.property('selectedElement'),

	path: function() {
		if (this.get('element')) {
			return $(this.get('element')).getUniquePath();
		} else {
			return '';
		}
	}.property('element'),

	ancestorPaths: function() {
		if (!this.get('element')) {
			return [];
		}
		var path = this.get('path');
		var splitted = path.split('>');
		var result = [];
		var selector = '';
		splitted.forEach(function(pathElement, i) {
			var ancestorPath = {};
			selector += (selector ? '>' : '') + pathElement;
			ancestorPath['path'] = selector;
			var element = this.get('iframe').find(selector).get(0);
			ancestorPath['element'] = element;
			ancestorPath['label'] = element.tagName.toLowerCase();
			result.pushObject(ancestorPath);
		}.bind(this));
		return result;
	}.property('path'),

	childPaths: function() {
		if (!this.get('element')) {
			return [];
		}
		var result = [];
		if (this.get('element')) {
			var path = this.get('path');
			var children = this.get('element').children;
			children = Array.prototype.slice.call(children);
			children.forEach(function(child, i) {
				var childPath = {};
				childPath['label'] = child.tagName.toLowerCase();
				childPath['path'] = path + '>' + ':eq(' + i + ')';
				childPath['element'] = child;
				result.pushObject(childPath);
			});
		}
		return result;
	}.property('path'),

	attributes: function() {
		if (this.get('element')) {
			return $(this.get('element')).getAttributeList();
		} else {
			return [];
		}
	}.property('element'),

	unmappedAttributes: function() {
		unmapped = this.get('attributes').filter(
			function(attribute, index, self) {
				return !this.get('annotations')[attribute.get('name')];
			}.bind(this));
		return unmapped;
	}.property('attributes.@each', 'annotations'),

	_mappedAttributes: function(filter) {
		mapped = [];
		if (this.get('annotations')) {
			this.get('attributes').forEach(function(attribute) {
				var mappedTo = this.get('annotations')[attribute.get('name')];
				if (filter(mappedTo)) {
					attribute.set('mappedField', mappedTo);
					mapped.addObject(attribute);
				}
			}.bind(this));
		}
		return mapped;
	},

	mappedAttributes: function() {
		return this._mappedAttributes(function(fieldName) {
			return fieldName && fieldName.indexOf('_sticky') != 0;
		});
	}.property('attributes.@each', 'annotations'),

	stickyAttributes: function() {
		return this._mappedAttributes(function(fieldName) {
			return fieldName && fieldName.indexOf('_sticky') == 0;
		});
	}.property('attributes.@each', 'annotations'),
});

ASTool.Item = ASTool.SimpleModel.extend({
	serializedRelations: ['fields'],
	serializedProperties: ['name'],
	fields: null,
});

ASTool.ItemField = ASTool.SimpleModel.extend({
	serializedProperties: ['name', 'type', 'required', 'vary'],
	type: 'text',
	required: false,
	vary: false,
});

ASTool.Attribute = ASTool.SimpleModel.extend({
	value: null,
	mappedField: null,
	annotation: null,
});

ASTool.Ignore = ASTool.SimpleModel.extend({
	element: null,
	ignoreBeneath: false,
	highlighted: false,
});

ASTool.Extractor = ASTool.SimpleModel.extend({

	serializedProperties: function() {
		var serializedProperties = ['name'];
		if (this.get('regular_expression')) {
			serializedProperties.pushObject('regular_expression');
		} else {
			serializedProperties.pushObject('type_extractor');
		}
		return serializedProperties;
	}.property('regular_expression', 'type_extractor'),

	regular_expression: null,
	type_extractor: null,
});

ASTool.ExtractedItem = Em.Object.extend({
	definition: null,
	extracted: null,

	fields: function() {
		var fields = [];
		var item = this.get('extracted');
		Object.keys(item).forEach(function(key) {
			var fieldDefinition = this.get('definition.fields').findBy('name', key);
			if (fieldDefinition) {
				fields.pushObject(ASTool.ExtractedField.create(
					{ name: key, type: fieldDefinition.get('type'), value: item[key] }));
			}
		}.bind(this));
		return fields;
	}.property('extracted', 'definition'),

	variants: function() {
		var variants = [];
		var item = this.get('extracted');
		if (!Em.isEmpty(item['variants'])) {
			item.variants.forEach(function(variant) {
				var fields = [];
				Object.keys(variant).forEach(function(key) {
					fields.pushObject(ASTool.ExtractedField.create(
						{ name: key, type: 'variant', value: variant[key] }));
				}.bind(this))
				variants.pushObject(ASTool.ExtractedVariant.create({ fields: fields }));
			}.bind(this))
		};
		return variants;
	}.property('extracted', 'definition'),
});

ASTool.ExtractedVariant = Em.Object.extend({
	fields: null,
});

ASTool.ExtractedField = Em.Object.extend({
	name: null,
	type: null,
	value: null,
});


text:
import {ARTICLES_LOADED} from '../actions/index.js';

export default function(state={articles: []}, action) {
  switch (action.type) {
    case ARTICLES_LOADED:
      return { articles: action.articles};
      break;
    default:
      return state;
  }
}


text:
<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Qanda Website Controller.
 *
 * @package Qanda
 * @subpackage Website
 */

/**
 * Qanda Website Controller Extending All Application Controllers
 *
 * @since 1.0.0
 * @package Qanda
 * @subpackage Website
 * @uses Template_Controller Extends class
 */
class Website_Controller extends Template_Controller
{
    //-- Global Variables
    public $template; // In application/views folder
    protected $settings;
    public $user;

    /**
     * Website Controller Constructor
     */
	public function __construct()
	{
        //-- Load Settings
        $this->settings = ORM::factory('setting');
        $this->settings->autoload();

        //-- Set Theme Template
        $this->template = 'themes/'.$this->settings->get('current_theme').'/master';

        //-- Initiate Template_Controller constructor
		parent::__construct();

        //-- Enable Session on All Pages
        //$this->session = Session::instance(); // Not used

        //-- Template Head
        $this->head = Head::instance();
        $this->head->css->append_file('media/themes/'.$this->settings->get('current_theme').'/css/layout');
        $this->head->title->set($this->settings->get('site_name'));
        $this->template->head = $this->head;

        //-- Set User
        $this->user = ORM::factory('user');
        $authentic = Auth::factory();
        if ($authentic->logged_in())
        {
            $this->user = $authentic->get_user();
        }

        //-- Template Global Variables
        $this->template->set_global('theme_url', 'themes/'.$this->settings->get('current_theme').'/');
        $this->template->set_global('current_version', $this->settings->get('version'));
        $this->template->set_global('current_user', $this->user);
	}

    //----------------------- PUBLIC METHODS --------------------------//

    //----------------------- STATIC METHODS --------------------------//

    /**
     * Create Log Record
     *
     * @param string $activity
     * @param string $object_type
     * @param int $object_id
     * @static
     * @uses Activity_Model::log()
     */
    protected function log_activity($activity, $object_type, $object_id)
    {
        //-- Log User View Activity
        if($this->user->is_logged_in())
        {
            ORM::factory('activity')->log($this->user->id, $activity, $object_type, $object_id);
        }
    }

    //----------------------- PRIVATE METHODS --------------------------//

}//END class


text:
package org.apache.usergrid.services.notifications;

import org.apache.usergrid.batch.JobExecution;
import org.apache.usergrid.persistence.entities.Notification;
import org.apache.usergrid.persistence.queue.LegacyQueueMessage;
import rx.Observable;

import java.util.List;

/**
 * Manages Queues for Applications
 */
public interface ApplicationQueueManager {

    String DEFAULT_QUEUE_PROPERTY = "usergrid.notifications.listener.queue";

    String NOTIFIER_ID_POSTFIX = ".notifier.id";

    String DEFAULT_QUEUE_NAME = "push"; //keep this short as AWS limits queue name size to 80 chars

    /**
     * send notification to queue
     *
     * @param notification
     * @param jobExecution
     * @throws Exception
     */
    void queueNotification(Notification notification, JobExecution jobExecution) throws Exception;

    /**
     * send notifications to providers
     *
     * @param messages
     * @param queuePath
     * @return
     */
    Observable sendBatchToProviders(List<LegacyQueueMessage> messages, String queuePath);

    /**
     * stop processing and send message to providers to stop
     */
    void stop();

    /**
     * check for inactive devices, apple and google require this
     *
     * @throws Exception
     */
    void asyncCheckForInactiveDevices() throws Exception;
}


text:
package com.havrylyuk.thenounproject.ui.collection_detail;

import com.havrylyuk.thenounproject.data.DataManager;
import com.havrylyuk.thenounproject.data.remote.helper.BaseViewSubscriber;
import com.havrylyuk.thenounproject.data.remote.helper.CompositeDisposableHelper;
import com.havrylyuk.thenounproject.data.remote.helper.error.ErrorHandlerHelper;
import com.havrylyuk.thenounproject.data.remote.model.NounIcon;
import com.havrylyuk.thenounproject.data.remote.model.response.IconsResponse;
import com.havrylyuk.thenounproject.ui.base.BasePresenter;

import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.functions.Consumer;

/**
 * Created by Igor Havrylyuk on 20.05.2017.
 */

public class CollectionDetailPresenter<V extends CollectionDetailMvpView> extends BasePresenter<V>
    implements CollectionDetailMvpPresenter<V> {

    @Inject
    public CollectionDetailPresenter(CompositeDisposableHelper compositeDisposableHelper,
                                   DataManager dataManager) {
      super(compositeDisposableHelper, dataManager);
    }

    @Override
    public void getCollectionIconsById(String id) {
        if (getMvpView().isNetworkConnected()){
            getCompositeDisposableHelper().addDisposable(getDataManager()
                    .getCollectionIcons(Integer.parseInt(id) , new HashMap<String, String>())
                    .compose(getCompositeDisposableHelper().<IconsResponse>applySchedulers())
                    .subscribeWith(
                            new IconsObserver(getMvpView(), getDataManager().getErrorHandlerHelper())));
        } else {
            getCompositeDisposableHelper().addDisposable(getDataManager()
                    .getCollectionIcons(id)
                    .compose(getCompositeDisposableHelper().<List<NounIcon>>applySchedulers())
                    .subscribe(new Consumer<List<NounIcon>>() {
                        @Override public void accept(List<NounIcon> icons) throws Exception {
                            if (icons != null && icons.size() > 0) {
                                getMvpView().showIcons(icons);
                            } else {
                                getMvpView().showEmptyView();
                            }
                        }
                    }));
        }
    }

    public class IconsObserver extends BaseViewSubscriber<CollectionDetailMvpView, IconsResponse> {

    public IconsObserver(CollectionDetailMvpView view, ErrorHandlerHelper errorHandlerHelper) {
        super(view, errorHandlerHelper);
    }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            getMvpView().showEmptyView();
        }

        @Override
        public void onNext(IconsResponse iconsResponse) {
          super.onNext(iconsResponse);
          if (iconsResponse.getIcons().isEmpty()) {
               getMvpView().showEmptyView();
          } else {
            getMvpView().showIcons(iconsResponse.getIcons());
          }
        }
  }
}


text:
NSString * const kWPCardReaderIdentifierEmpty = @"";

@implementation WPUserDefaultsHelper

+ (void) storeConfigHash:(NSString *)currentHash forKey:(NSString *)key
{
    if (key == nil || [key length] <= 1) {
        return;
    }

    // fetch hashes
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *configHashes = [defaults objectForKey:WEPAY_CONFIG_HASH_KEY];
    if (configHashes == nil) {
        configHashes = @{};
    }

    // update hash
    NSMutableDictionary *updatedConfig = [configHashes mutableCopy];
    [updatedConfig setValue:currentHash forKey:key];

    [defaults setObject:updatedConfig forKey:WEPAY_CONFIG_HASH_KEY];
    [defaults synchronize];
}

+ (NSString *) getStoredConfigHashForKey:(NSString *)key
{
    // fetch saved hashes
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *configHashes = [defaults objectForKey:WEPAY_CONFIG_HASH_KEY];
    if (configHashes == nil) {
        configHashes = @{};
    }

    // extract hash for current key
    return [configHashes objectForKey:key];
}

+ (void) rememberCardReaderWithIdentifier:(NSString *)name
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *entry = [defaults objectForKey:WEPAY_REMEMBERED_CARDREADER_KEY];

    if (!name) {
        name = kWPCardReaderIdentifierEmpty;
    }

    entry = name;

    [defaults setObject:entry forKey:WEPAY_REMEMBERED_CARDREADER_KEY];

    if (![defaults synchronize]) {
        WPLog(@"Failed to immediately save card reader with name %@. It may be written to disk at a later time.", name);
    }
}

+ (NSString *) getRememberedCardReader
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *entry = [defaults objectForKey:WEPAY_REMEMBERED_CARDREADER_KEY];

    if (entry && [entry isEqualToString:kWPCardReaderIdentifierEmpty])
    {
        // Since we can't actually store nil, we need to fake it on lookup.
        entry = nil;
    }

    return entry;
}

+ (void) forgetRememberedCardReader
{
    [self rememberCardReaderWithIdentifier:kWPCardReaderIdentifierEmpty];
}

@end


text:
<?php

namespace Drupal\Tests\serialization\Unit\Normalizer;

use Drupal\serialization\Normalizer\ContentEntityNormalizer;
use Drupal\Tests\UnitTestCase;

/**
 * @coversDefaultClass \Drupal\serialization\Normalizer\ContentEntityNormalizer
 * @group serialization
 */
class ContentEntityNormalizerTest extends UnitTestCase {

  /**
   * The mock entity manager.
   *
   * @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $entityManager;

  /**
   * The mock serializer.
   *
   * @var \Symfony\Component\Serializer\SerializerInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected $serializer;

  /**
   * The normalizer under test.
   *
   * @var \Drupal\serialization\Normalizer\ContentEntityNormalizer
   */
  protected $contentEntityNormalizer;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    $this->entityManager = $this->getMock('Drupal\Core\Entity\EntityManagerInterface');
    $this->contentEntityNormalizer = new ContentEntityNormalizer($this->entityManager);
    $this->serializer = $this->getMockBuilder('Symfony\Component\Serializer\Serializer')
      ->disableOriginalConstructor()
      ->setMethods(['normalize'])
      ->getMock();
    $this->contentEntityNormalizer->setSerializer($this->serializer);
  }

  /**
   * @covers ::supportsNormalization
   */
  public function testSupportsNormalization() {
    $content_mock = $this->getMock('Drupal\Core\Entity\ContentEntityInterface');
    $config_mock = $this->getMock('Drupal\Core\Entity\ConfigEntityInterface');
    $this->assertTrue($this->contentEntityNormalizer->supportsNormalization($content_mock));
    $this->assertFalse($this->contentEntityNormalizer->supportsNormalization($config_mock));
  }

  /**
   * Tests the normalize() method.
   *
   * @covers ::normalize
   */
  public function testNormalize() {
    $this->serializer->expects($this->any())
      ->method('normalize')
      ->with($this->containsOnlyInstancesOf('Drupal\Core\Field\FieldItemListInterface'), 'test_format', ['account' => NULL])
      ->will($this->returnValue('test'));

    $definitions = [
      'field_1' => $this->createMockFieldListItem(),
      'field_2' => $this->createMockFieldListItem(FALSE),
    ];
    $content_entity_mock = $this->createMockForContentEntity($definitions);

    $normalized = $this->contentEntityNormalizer->normalize($content_entity_mock, 'test_format');

    $this->assertArrayHasKey('field_1', $normalized);
    $this->assertEquals('test', $normalized['field_1']);
    $this->assertArrayNotHasKey('field_2', $normalized);
  }

  /**
   * Tests the normalize() method with account context passed.
   *
   * @covers ::normalize
   */
  public function testNormalizeWithAccountContext() {
    $mock_account = $this->getMock('Drupal\Core\Session\AccountInterface');

    $context = [
      'account' => $mock_account,
    ];

    $this->serializer->expects($this->any())
      ->method('normalize')
      ->with($this->containsOnlyInstancesOf('Drupal\Core\Field\FieldItemListInterface'), 'test_format', $context)
      ->will($this->returnValue('test'));

    // The mock account should get passed directly into the access() method on
    // field items from $context['account'].
    $definitions = [
      'field_1' => $this->createMockFieldListItem(TRUE, $mock_account),
      'field_2' => $this->createMockFieldListItem(FALSE, $mock_account),
    ];
    $content_entity_mock = $this->createMockForContentEntity($definitions);

    $normalized = $this->contentEntityNormalizer->normalize($content_entity_mock, 'test_format', $context);

    $this->assertArrayHasKey('field_1', $normalized);
    $this->assertEquals('test', $normalized['field_1']);
    $this->assertArrayNotHasKey('field_2', $normalized);
  }

  /**
   * Creates a mock content entity.
   *
   * @param $definitions
   *
   * @return \PHPUnit_Framework_MockObject_MockObject
   */
  public function createMockForContentEntity($definitions) {
    $content_entity_mock = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityBase')
      ->disableOriginalConstructor()
      ->setMethods(['getFields'])
      ->getMockForAbstractClass();
    $content_entity_mock->expects($this->once())
      ->method('getFields')
      ->will($this->returnValue($definitions));

    return $content_entity_mock;
  }

  /**
   * Creates a mock field list item.
   *
   * @param bool $access
   *
   * @return \Drupal\Core\Field\FieldItemListInterface|\PHPUnit_Framework_MockObject_MockObject
   */
  protected function createMockFieldListItem($access = TRUE, $user_context = NULL) {
    $mock = $this->getMock('Drupal\Core\Field\FieldItemListInterface');
    $mock->expects($this->once())
      ->method('access')
      ->with('view', $user_context)
      ->will($this->returnValue($access));

    return $mock;
  }

}


text:
Standard Probability Distributions
======================================================================

Functions for several probability distributions are provided as part of R.
Some distribution are available in the global space. Additional distributions
are available through some packages.

Each distribution has a name in R (e.g. norm, beta, t, f, etc.).
For each distribution following functions are provided:

* Probability Density (Mass) Function (dnorm, dbeta, dt, df, etc.)
* Cumulative Distribution Function (pnorm, pbeta, , pt, pf, etc.)
* Quantile or Inverse Cumulative Distribution Function (qnorm, qbeta, qt, qf, etc.)
* Random Number Generator for the given distribution (rnorm, rbeta, rt, rf, etc.)

.. list-table::
    :header-rows: 1

    * - Distribution
      - R name
      - Additional arguments
    * - beta
      - beta
      - shape1, shape2, ncp
    * - binomial
      - binom
      - size, prob
    * - Cauchy
      - cauchy
      - location, scale
    * - chi-squared
      - chisq
      - df, ncp
    * - exponential
      - exp
      - rate
    * - F
      - f
      - df1, df2, ncp
    * - gamma
      - gamma
      - shape, scale
    * - geometric
      - geom
      - prob
    * - hypergeometric
      - hyper
      - m, n, k
    * - log-normal
      - lnorm
      - meanlog, sdlog
    * - logistic
      - logis
      - location, scale
    * - negative binomial
      - nbinom
      - size, prob
    * - normal
      - norm
      - mean, sd
    * - Poisson
      - pois
      - lambda
    * - signed rank
      - signrank
      - n
    * - Student's t
      - t
      - df, ncp
    * - uniform
      - unif
      - min, max
    * - Weibull
      - weibull
      - shape, scale
    * - Wilcoxon
      - wilcox
      - m, n


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Function register_observer</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Boost.Test">
<link rel="up" href="../../../header/boost/test/framework_hpp.html" title="Header <boost/test/framework.hpp>">
<link rel="prev" href="deregister_test_unit.html" title="Function deregister_test_unit">
<link rel="next" href="deregister_observer.html" title="Function deregister_observer">

Home
Libraries
People
FAQ
More

Function register_observer

boost::unit_test::framework::register_observer — Observer lifetime should exceed the the testing execution timeframe.

Synopsis

// In header: <boost/test/framework.hpp>

void register_observer(test_observer & to);

Description

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

Parameters:

<colgroup>
<col align="left" valign="top">
<col>
</colgroup>

to

test observer object to add

Copyright © 2001-2016 Boost.Test contributors

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
using Fineness.Framework.Interfaces;
using UnityEngine;

public class FrameUpdateComponent : MonoBehaviour, IUpdate {

    public IUpdate UpdateTarget;
    public GameObject Owner;

    private NoticeManager mNoticeManager;

	// Use this for initialization
	void Start () {
        if (mNoticeManager == null)
            mNoticeManager = NoticeManager.Instance;
    }

	// Update is called once per frame
	void Update ()
    {
        OnUpdate(FTimeUtils.FrameDeltaTime());
    }

    void FixedUpdate()
    {
        OnFixedUpdate(FTimeUtils.FixedDeltaTime());
    }

    void OnDestroy()
    {
        Destroy(Owner);
        UpdateTarget = null;
        mNoticeManager = null;
        Owner = null;
    }

    #region 刷帧函数
    /// 开始刷帧
    public virtual void AddUpdate()
    {
        if (UpdateTarget != null)
            UpdateTarget.AddUpdate();
    }

    /// 结束刷帧
    public virtual void RemoveUpdate()
    {
        if (UpdateTarget != null)
            UpdateTarget.RemoveUpdate();
    }

    /// 帧更新
    public virtual void OnUpdate(int dTime)
    {
        if (UpdateTarget != null)
            UpdateTarget.OnUpdate(dTime);
    }

    /// 帧后更新
    public virtual void OnLateUpdate()
    {
        if (UpdateTarget != null)
            UpdateTarget.OnLateUpdate();
    }

    /// 固定更新
    public virtual void OnFixedUpdate(int dTime)
    {
        if (UpdateTarget != null)
            UpdateTarget.OnFixedUpdate(dTime);
    }

    /// 是否每帧更新
    public virtual bool IsUpdate
    {
        get
        {
            return true;
        }
    }

    /// 是否固定时间更新
    public virtual bool IsFixedUpdate
    {
        get
        {
            return true;
        }
    }

    /// 是否刷帧后更新
    public virtual bool IsLateUpdate
    {
        get
        {
            return true;
        }
    }
    #endregion

    #region 可控刷帧功能
    /// 是否加入了刷帧队列
    public bool IsFrameUpdate
    {
        set
        {
        }
        get
        {
            return true;
        }
    }
    #endregion
}


text:
"""

Copyright 2015, Institute e-Austria, Timisoara, Romania
    http://www.ieat.ro/
Developers:
 * Gabriel Iuhasz, iuhasz.gabriel@info.uvt.ro

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.
"""
from flask import Flask
from flask import jsonify
from flask import send_file
from flask import request
from flask.ext.restplus import Resource, fields
from flask import abort
import os
import jinja2
import sys
import subprocess
import platform
import requests
import json
import psutil
import logging
from logging.handlers import RotatingFileHandler

from pyLogstash import *
from jsonvalidation import *
from jsonschema import *
from app import *

#directory location

tmpDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates')
pidDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'pid')
logDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'log')
cfgDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config')
credDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'credentials')
lockDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lock')
logstashDir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'logstash')

# app = Flask("dmon-logstash")
# app.config['RESTPLUS_VALIDATE'] = True
# api = Api(app, version='0.0.1', title='DICE Monitoring Logstash API',
#           description="RESTful API for the DICE Monitoring Platform  Logstash agent (dmon-logstash)",
#           )
#
# # changes the descriptor on the Swagger WUI and appends to api /dmon and then /v1
# agent = api.namespace('agent', description='dmon logstash operations')

lsConfig = api.model('LS Configuration options', {
    'UDPPort': fields.String(required=True, default='25826', description='Port of UDP plugin from Logstash Server'),
    'ESCluster': fields.String(required=True, default='esCore', description='Name of ES cluster'),
    'EShostIP': fields.String(required=True, default='localhost', description='ES endpoint IP'),
    'EShostPort': fields.String(required=True, default='9200', description='ES endpoint Port'),
    'LSWorkers': fields.String(required=True, default='2', description='Number of workers'),
    'LSHeap': fields.String(required=True, default='512m', description='Size of JVM Heap'),
    'StormRestIP': fields.String(required=False, default='none', description='Storm REST API endpoint IP'),
    'StormRestPort': fields.String(required=False, default='none', description='Storm REST API endpoint Port'),
    'StormTopologyID': fields.String(required=False, default='none', description='Storm Topology')
})

lsagent = pyLogstashInstance()
valid = LSValidation()

@agent.route('/v1/host')
class NodeInfo(Resource):
    def get(self):
        mType = platform.uname()
        response = jsonify({'System': mType[0],
                            'Node': mType[1],
                            'Release': mType[2],
                            'Version': mType[3],
                            'Machine': mType[4],
                            'Processor': mType[5]})
        response.status_code = 200
        return response

@agent.route('/v1/cert')
class LSCertificates(Resource):
    def get(self):
        dirContent = os.listdir(credDir)
        app.logger.info('[%s] : [INFO] Credential DIR Content  %s',
                        datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(dirContent))
        #print str(dirContent)
        if not dirContent:
            response = jsonify({'Status': 'Env Error',
                                'Message': 'Credential folder empty'})
            response.status_code = 404
            app.logger.warning('[%s]: [WARN] Credential folder empty',
                               datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
            return response
        pubFile = []
        privateFile = []
        for f in dirContent:
            print str(os.path.splitext(f)[1])
            if os.path.splitext(f)[1] == '.crt':
                pubFile.append(f)
                app.logger.info('[%s] : [INFO] Public Key files found: %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(pubFile))
                #print str(pubFile)
            if os.path.splitext(f)[1] == '.key':
                privateFile.append(f)
                app.logger.info('[%s] : [INFO] Private Key files found: %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(privateFile))
                #print str(privateFile)

        response = jsonify({'certificates': pubFile,
                            'keys': privateFile})
        response.status_code = 200
        return response

    def post(self):
        try:
            lsagent.generateCertificate('logstash', 'logstash')  #TODO: allow for renaming of old certificates ans save the new ones with default "logstash"
        except Exception as inst:
            app.logger.error('[%s] : [ERROR] Can not Generate Certificate, error %s with %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), type(inst), inst.args)

        return "Send new certificate!" #TODO: sending new certificates

@agent.route('/v1/cert/type/<ctype>/name/<cname>')
class LSCertificateGet(Resource):
    def get(self, ctype, cname):
        ctypeList = ['crt', 'key']
        certN = cname + '.' + ctype
        if not os.path.isfile(os.path.join(credDir, certN)):
            app.logger.error('[%s] : [ERROR] File not found, %s',
                             datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), cname)
            return "not found files"
        if ctype not in ctypeList:
            app.logger.error('[%s] : [ERROR] Unsupported file type used for credential, %s',
                             datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), ctype)
            response = jsonify({'Status': 'Value Error',
                                'Supported': ctypeList})
            response.status_code = 400
            return response

        certFile = open(os.path.join(credDir, cname + '.' + ctype), 'r')
        return send_file(certFile, mimetype='application/x-x509-ca-cert', as_attachment=True)

@agent.route('/v1/logstash')
class LSStatus(Resource):
    def get(self):

        if not os.path.isfile(os.path.join(pidDir, 'logstash.pid')):
            response = jsonify({'Status': 'Env Error',
                                'Message': 'PID file not found!'})
            response.status_code = 404
            app.logger.warning('[%s]: [WARN] NO Logstash PID file found',
                               datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
            return response
        status = lsagent.check()

        if not status:
            response = jsonify({'Status': 'Stopped',
                                'Message': 'No LS instance found'})
            response.status_code = 200
            app.logger.info('[%s]: [INFO] No running Logstash instance found',
                            datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
            return response
        else:
            response = jsonify({'Status': 'Running',
                                'Message': 'PID ' + status})
            response.status_code = 200
            app.logger.info('[%s]: [INFO] Logstash instance running with PID %s',
                               datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(status))
            return response

@agent.route('/v1/logstash/config')
class LSController(Resource):
    def get(self):
        conf = os.path.isfile(os.path.join(cfgDir, 'logstash.conf'))
        if not conf:
            response = jsonify({'Status': 'Env Error',
                                'Message': 'No config found!'})
            response.status_code = 404
            app.logger.warning('[%s] : [WARN] Logstash configuration not found',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
            return response

        confFile = open(os.path.join(cfgDir, 'logstash.conf'), 'r')

        return send_file(confFile, mimetype='text/plain', as_attachment=True)

    @api.expect(lsConfig)
    def post(self):
        sslCert = os.path.join(credDir, 'logstash.crt')
        sslKey = os.path.join(credDir, 'logstash.key')

        if not os.path.isfile(sslCert) or not os.path.isfile(sslKey):
            response = jsonify({'Status': 'Credential Error',
                                'Message': 'Missing keys'})
            response.status_code = 404
            app.logger.warning('[%s] : [WARN] Logstash missing credentials',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
            return response
        if not request.json:
            app.logger.error('[%s] : [ERROR] Invalid content-type: %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(request.content_type))
            abort(400)

        try:
            valid.validate(request.json)
        except ValidationError:
            response = jsonify({'Status': 'json error',
                                'Message': 'Malformed json'})
            response.status_code = 404
            app.logger.error('[%s] : [ERROR] Malformed JSON',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
            return response

        if not 'StormRestIP' in request.json:
            StormRestIP = 'none'
        else:
            StormRestIP = request.json['StormRestIP']

        if not 'StormRestPort' in request.json:
            StormRestPort = 'none'
        else:
            StormRestPort = request.json['StormRestPort']
        StormTopologyID = 'none'
        if not 'StormTopologyID' in request.json:
            if not request.json['StormRestIP']:
                StormTopologyID = 'none'
            else:
                if request.json['StormTopologyID'] == 'none':
                    StormTopologyID = 'none'
                else:
                    # Get first topology from storm and use this for monitoring
                    stormTopologyURL = 'http://' + StormRestIP + ':' + StormRestPort + '/api/v1/topology/'
                    listTopologies = requests.get(stormTopologyURL + 'summary')
                    plainText = listTopologies.text
                    jsonPayload = json.loads(plainText)
                    topology = jsonPayload['topologies'][0]['encodedId'] #TODO: get list of topologies instead of just the first one
                    #getTopology = request.get(stormTopologyURL + topology)
                    StormTopologyID = topology

        confdict = {"sslcert": sslCert, "sslkey": sslKey, "udpPort": request.json['UDPPort'],
                    "ESCluster": request.json['ESCluster'], "EShostIP": request.json['EShostIP'], "EShostPort": request.json['EShostPort'],
                    "StormRestIP": StormRestIP, "StormRestPort": StormRestPort, "StormTopologyID": StormTopologyID}
        app.logger.info('[%s] : [INFO] Configuration content: %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(confdict))
        lsagent.generateConfig(confdict)
        pid = lsagent.check()
        if not pid:
            lsagent.start(heap=request.json['LSHeap'], worker=request.json['LSWorkers'])
        else:
            subprocess.call(['kill', '-9', str(pid)])
            lsagent.start(heap=request.json['LSHeap'], worker=request.json['LSWorkers'])

        response = jsonify({'Status': 'Done',
                            'Message': 'LS config loaded'})
        app.logger.info('[%s] : [INFO] Configuration loaded: %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
        response.status_code = 200
        return response

@agent.route('/v1/logstash/start')
class LSControllerStart(Resource):
    def post(self):
        pid = lsagent.check()
        if pid:
            response = jsonify({'Status': 'Running',
                                'Message': 'Logstash instance already running!'})
            response.status_code = 200
            app.logger.info('[%s] : [INFO] Logstash instance already running at: %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(pid))
            return response
        lsagent.start()
        pidVal = lsagent.readPid()

        if pidVal == 'none':
            msg2 = 'Error fetching PID!'
            app.logger.error('[%s] : [ERROR] Error fetching PID from file',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
        else:
            msg2 = pidVal
        response = jsonify({'Status': 'Started',
                            'Message': 'Logstash instance started!',
                            'PID': msg2})
        response.status_code = 201
        app.logger.info('[%s] : [INFO] Logstash instance started with PID: %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(msg2))
        return response

@agent.route('/v1/logstash/stop')
class LSControllerStop(Resource):
    def post(self):
        pid = lsagent.check()
        if not pid:
            response = jsonify({'Status': 'Not Found',
                                'Message': 'LS instance not found'})
            response.status_code = 404
            app.logger.warning('[%s] : [WARN] No running Logstash instance found',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
            return response
        else:
            process = psutil.Process(pid)
            for proc in process.children(recursive=True):
                proc.kill()
            process.kill()
            subprocess.call(['kill', '-9', str(pid)]) #TODO: check for more elegant solution not sigkill(9) but sigterm(15)
            app.logger.info('[%s] : [INFO] Killed Logstash instance with PID: %s',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'), str(pid))
            response = jsonify({'Status': 'Done',
                                'Message': 'LS Instance stopped'})
            response.status_code = 200
            return response

@agent.route('/v1/logstash/deploy')
class LSControllerDeploy(Resource):
    def post(self):
        lsagent.deploy()
        response = jsonify({'Status': 'Done',
                            'Message': 'Logstash installed!'})
        response.status_code = 201
        app.logger.info('[%s] : [INFO] Logstash deployed',
                                datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
        return response

@agent.route('/v1/logstash/log')
class LSControllerLog(Resource):
    def get(self):
        lslog = os.path.join(logDir, 'logstash.log')

        if not os.path.isfile(lslog):
            response = jsonify({'Status': 'Env Error',
                                'Message': 'No log file found'})
            response.status_code = 404
            return response

        sizeMB = os.path.getsize(lslog) >> 20
        if sizeMB > 10:
            response = jsonify({'Status': 'Size Warning',
                                'Message': 'Log file to big!'})
            response.status_code = 413
            return response

        logCont = open(lslog, 'r')
        return send_file(logCont, mimetype='text/plain', as_attachment=True)

if __name__ == '__main__':
    handler = RotatingFileHandler(logDir + '/dmon-logstash.log', maxBytes=10000000, backupCount=5)
    handler.setLevel(logging.INFO)
    app.logger.addHandler(handler)
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.DEBUG)
    log.addHandler(handler)
    app.run(host='0.0.0.0', port=5003, debug=True)