text:
package io.shick.jsoup.gson;

import io.shick.jsoup.WhitelistConfiguration;
import io.shick.jsoup.WhitelistConfigurationParser;
import io.shick.jsoup.WhitelistConfigurationParserFactory;

import java.text.ParseException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

/**
 *
GsonParser class.

 * @todo Document Me
 * @author Trever Shick - trever@shick.io
 */
public class GsonParser implements WhitelistConfigurationParser {
  /**
   * {@inheritDoc}
   */
  @Override
  public WhitelistConfiguration parse(CharSequence value) throws ParseException {
    try {
      return gson().fromJson(value.toString(), GsonWhitelistConfiguration.class);
    }
    catch (JsonSyntaxException jse) {
      throw new ParseException(jse.getMessage(), 0);
    }
  }

  private Gson gson() {
    return new GsonBuilder().create();
  }

  static {
    WhitelistConfigurationParserFactory.register("gson", GsonParser::new);
  }
}


text:
require 'svnx/add/options'
require 'svnx/base/command'

module Svnx::Add
  class Command < Svnx::Base::Command
    noncaching
  end
end

redpajama_set_name: RedPajamaGithub


text:
require "beta_invites/engine"

module BetaInvites
  mattr_accessor :user_class

  def self.user_class
    @@user_class.constantize
  end
end


text:
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from matplotlib.externals import six

from matplotlib import cbook
import sys
import types

class Substitution(object):
    """
    A decorator to take a function's docstring and perform string
    substitution on it.

    This decorator should be robust even if func.__doc__ is None
    (for example, if -OO was passed to the interpreter)

    Usage: construct a docstring.Substitution with a sequence or
    dictionary suitable for performing substitution; then
    decorate a suitable function with the constructed object. e.g.

    sub_author_name = Substitution(author='Jason')

    @sub_author_name
    def some_function(x):
        "%(author)s wrote this function"

    # note that some_function.__doc__ is now "Jason wrote this function"

    One can also use positional arguments.

    sub_first_last_names = Substitution('Edgar Allen', 'Poe')

    @sub_first_last_names
    def some_function(x):
        "%s %s wrote the Raven"
    """
    def __init__(self, *args, **kwargs):
        assert not (len(args) and len(kwargs)), \
                "Only positional or keyword args are allowed"
        self.params = args or kwargs

    def __call__(self, func):
        func.__doc__ = func.__doc__ and func.__doc__ % self.params
        return func

    def update(self, *args, **kwargs):
        "Assume self.params is a dict and update it with supplied args"
        self.params.update(*args, **kwargs)

    @classmethod
    def from_params(cls, params):
        """
        In the case where the params is a mutable sequence (list or
        dictionary) and it may change before this class is called, one may
        explicitly use a reference to the params rather than using *args or
        **kwargs which will copy the values and not reference them.
        """
        result = cls()
        result.params = params
        return result

class Appender(object):
    """
    A function decorator that will append an addendum to the docstring
    of the target function.

    This decorator should be robust even if func.__doc__ is None
    (for example, if -OO was passed to the interpreter).

    Usage: construct a docstring.Appender with a string to be joined to
    the original docstring. An optional 'join' parameter may be supplied
    which will be used to join the docstring and addendum. e.g.

    add_copyright = Appender("Copyright (c) 2009", join='\n')

    @add_copyright
    def my_dog(has='fleas'):
        "This docstring will have a copyright below"
        pass
    """
    def __init__(self, addendum, join=''):
        self.addendum = addendum
        self.join = join

    def __call__(self, func):
        docitems = [func.__doc__, self.addendum]
        func.__doc__ = func.__doc__ and self.join.join(docitems)
        return func

def dedent(func):
    "Dedent a docstring (if present)"
    func.__doc__ = func.__doc__ and cbook.dedent(func.__doc__)
    return func

def copy(source):
    "Copy a docstring from another source function (if present)"
    def do_copy(target):
        if source.__doc__:
            target.__doc__ = source.__doc__
        return target
    return do_copy

# create a decorator that will house the various documentation that
#  is reused throughout matplotlib
interpd = Substitution()

def dedent_interpd(func):
    """A special case of the interpd that first performs a dedent on
    the incoming docstring"""
    if isinstance(func, types.MethodType) and not six.PY3:
        func = func.im_func
    return interpd(dedent(func))

def copy_dedent(source):
    """A decorator that will copy the docstring from the source and
    then dedent it"""
    # note the following is ugly because "Python is not a functional
    # language" - GVR. Perhaps one day, functools.compose will exist.
    #  or perhaps not.
    #  http://mail.python.org/pipermail/patches/2007-February/021687.html
    return lambda target: dedent(copy(source)(target))


text:
layout: sidebar-right
category: fiction
title: Fiction
breadcrumb: new-suggestions
pagination:
  enabled: true
  category: fiction
---

{% include post-listing.html %}


text:
<resources>
    <string name="app_name" translatable="false">Rugs</string>

    <string name="pref_hue_key" translatable="false">hue</string>
    <string name="pref_saturation_key" translatable="false">saturation</string>
    <string name="pref_bright_key" translatable="false">bright</string>
    <string name="pref_init_key" translatable="false">initialized</string>

</resources>


text:
Firefox OS

Linux kernel + Firefox

 All Apps are JavaScript Web Apps.
 Works offline.


text:
module.exports = {
    after: require("./after"),
    apply: require("./apply"),
    ary: require("./ary"),
    attempt: require("./attempt"),
    before: require("./before"),
    call: require("./call"),
    debounce: require("./debounce"),
    delay: require("./delay"),
    iterate: require("./iterate"),
    memoize: require("./memoize"),
    mock: require("./mock"),
    negate: require("./negate"),
    once: require("./once"),
    parallel: require("./parallel"),
    throttle: require("./throttle"),
    waterfall: require("./waterfall"),
    wrap: require("./wrap")
};


text:
<?php
/*
 * Miuview API
 * download class
 *
 * Creator: Mihkel Oviir
 * 08.2011
 *
 */

class download {

	public function __construct(){
		global $func,$album,$item;

		if(!empty($album) && !empty($item) && file_exists(PATH_ALBUMS.$album.'/'.$item) && $i=$func->getType(PATH_ALBUMS.$album.'/'.$item)){
			$is = getimagesize(PATH_ALBUMS.$album.'/'.$item);
			$this->downloadFile(PATH_ALBUMS.$album.'/',$item,$is['mime']);
		}
	}

	// Return the requested graphic file to the browser
	private function downloadFile($path,$file,$type){
		header("Cache-Control: public");
		header("Content-Description: File Transfer");
		header("Content-Disposition: attachment; filename=$file");
		header("Content-Type: Content-type: $type");
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".filesize($path.$file));
		readfile($path.$file);
	}

}
?>


text:
// Copyright © 2017 Kenneth Martin, Susham Yerabolu, Henry Cooney, Matthew Hawkins, Dakota Sanchez, Chris Kim
// [This program is licensed under the "MIT License"]
// Please see the file COPYING in the source
// distribution of this software for license terms.

import org.junit.Assert;
import org.junit.Test;

import edu.pdx.cs510.agile.team3.FTP.*;
/**
 * Created by henry on 7/22/17.
 *
 * A example use of JUnit
 */
public class JUnitTest {
    @Test
    public void jUnitTest() {
        Assert.assertEquals("FAIL - this test should never fail!", 0, 0);
        //Assert.assertEquals("OK - this test should always FAIL!", 0, 1);
        System.out.println("I'm a test output. If JUnit is working, you should see me.");
    }
}


text:
import { useEffect } from 'react';

// useDocumentTitle is a simple hook to set the document.title of the page.
//
// Note that there's a noticeable delay, around ~500ms, between
// when the parent component renders and when the document.title
// is updated. It's not terrible... but it is a little bit annoying.
//
// Unfortunately, neither React hooks nor react-router offer
// a mechanism to hook into the "componentWillMount" stage before the
// first render. This problem seems to be common even in libraries
// like react-helmet; see https://github.com/nfl/react-helmet/issues/189.
//
// Other approaches that still, unfortunately, exhibit the lag:
//
//  - Setting document.title directly in component functions
//  - Setting document.title in a Route component's render prop
//  - Setting document.title on history.listen events
//
export const useDocumentTitle = (title: string) => {
    // Update document.title whenever the `title` argument changes.
    useEffect(() => {
        document.title = `${title} | VTAdmin`;
    }, [title]);

    // Restore the default document title on unmount.
    // (While one may think this might be the source of the aforementioned delay
    // (and that idea wouldn't be far off since this indeed double-updates the title)
    // that is not the case as the lag happens even without this.)
    useEffect(() => {
        return () => {
            document.title = 'VTAdmin';
        };
    }, []);
};


text:
from __future__ import annotations

import discord

from discord.ext import commands
from typing import TYPE_CHECKING, Optional
from utils.checks import is_staff
from textwrap import wrap

if TYPE_CHECKING:
    from kurisu import Kurisu
    from utils.context import KurisuContext, GuildContext

class Modwatch(commands.Cog):
    """
    User watch management commands.
    """

    def __init__(self, bot: Kurisu):
        self.bot: Kurisu = bot
        self.emoji = discord.PartialEmoji.from_str('👀')
        self.configuration = bot.configuration
        self.logs = bot.logs

    async def cog_check(self, ctx: KurisuContext):
        if ctx.guild is None:
            raise commands.NoPrivateMessage()
        return True

    @is_staff("Helper")
    @commands.command()
    async def watch(self, ctx: GuildContext, member: discord.Member, *, reason: Optional[str]):
        """Adds a member to the watchlist."""
        if member.id in self.configuration.watch_list:
            await ctx.send("User is already being watched!")
            return
        await self.configuration.set_watch(member.id, True)
        await ctx.send(f"{member.mention} is now being watched.")
        await self.logs.post_action_log(ctx.author, member, 'watch', reason=reason)

    @is_staff("Helper")
    @commands.command()
    async def unwatch(self, ctx: GuildContext, member: discord.Member):
        """Removes a member from the watchlist."""
        if member.id not in self.configuration.watch_list:
            await ctx.send("This user was not being watched.")
            return
        await self.configuration.set_watch(member.id, False)
        await ctx.send(f"{member.mention} is no longer being watched.")
        await self.logs.post_action_log(ctx.author, member, 'unwatch')

    @is_staff("Helper")
    @commands.command()
    async def listwatch(self, ctx: GuildContext):
        """List the members in the watchlist."""
        lines = []
        for user_id in self.configuration.watch_list:
            member = ctx.guild.get_member(user_id)
            lines.append(f"{f'{member.name}' if member else f'<@{user_id}>'} ({user_id})")
        messages = wrap('\n'.join(lines), 1810, break_long_words=False, replace_whitespace=False)
        if not messages:
            await ctx.send("The watchlist is empty!")
            return
        if (n_messages := len(messages)) > 1:
            for n, message in enumerate(messages, start=1):
                await ctx.author.send(f"**Watchlist contents {n}/{n_messages}**\n{message}")
        else:
            await ctx.author.send(f"**Watchlist contents**\n{messages[0]}")

    @is_staff("OP")
    @commands.command()
    async def watch_cleanup(self, ctx: GuildContext):
        """Removes members that aren't in the server from the watchlist."""
        removed = 0
        for user_id in self.configuration.watch_list:
            if not ctx.guild.get_member(user_id):
                await self.configuration.set_watch(user_id, False)
                removed += 1
        await ctx.send(f"Watch list cleanup complete. Removed {removed} entries.")

async def setup(bot):
    await bot.add_cog(Modwatch(bot))


text:
#include <iostream>
#include <memory>
#include <math.h>
#include <vector>
#include <string.h>
#include <map>

#define EXPORT_FCNS
#include "kni_wrapper/kni_wrapper.h"

//#include <pthread.h>
#include <sstream>
/////////////////////////////////////////////////////////////////////////////////////////////////
// KNI internal types
static std::auto_ptr< CLMBase > katana;
static std::auto_ptr< CCdlSocket > device;
static std::auto_ptr< CCplSerialCRC > protocol;
/////////////////////////////////////////////////////////////////////////////////////////////////
// A map containing movement vectors accessible by a string name:
std::map< std::string, std::vector< TMovement > > movements;
// A vector for storing encoders
std::vector< int > encoders;
// The number of motors, initialized in initKatana()
int numberOfMotors;
// variables to store communication data
byte packet[32];   // comm packet
byte buffer[256];  // comm readbuf
byte size = 0;     // comm readbuf size
/////////////////////////////////////////////////////////////////////////////////////////////////

DLLEXPORT int initKatana(char *configFile, char *ipaddress)
{
  try
  {
    int port = 5566;
    device.reset(new CCdlSocket(ipaddress, port));
    protocol.reset(new CCplSerialCRC());
    protocol->init(device.get());
    katana.reset(new CLMBase());
    katana->create(configFile, protocol.get());
    numberOfMotors = katana->getNumberOfMotors();
    for (int i = 0; i < numberOfMotors; i++)
    {
      encoders.push_back(0);
    }
    // MessageBox(NULL, "Katana successfully initiated!",TEXT(""),MB_OK);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int calibrate(int axis)
{
  try
  {
    katana->calibrate();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int moveMot(int axis, int enc, int speed, int accel)
{
  try
  {
    // set speed
    katana->setMotorVelocityLimit(axis - 1, speed);
    // set acceleration
    katana->setMotorAccelerationLimit(axis - 1, accel);
    // move
    katana->moveMotorToEnc(axis - 1, enc);
  }
  catch (...)
  {
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int waitForMot(int axis, int targetpos, int tolerance)
{
  try
  {
    katana->waitForMotor((short)axis - 1, targetpos, tolerance, 0, TM_ENDLESS);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int moveMotAndWait(int axis, int targetpos, int tolerance)
{
  try
  {
    katana->moveMotorToEnc(axis - 1, targetpos);
    waitForMot(axis, targetpos, tolerance);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int motorOn(int axis)
{
  try
  {
    katana->switchMotorOn(axis - 1);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int motorOff(int axis)
{
  try
  {
    katana->switchMotorOff(axis - 1);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int allMotorsOff()
{
  try
  {
    katana->switchRobotOff();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int allMotorsOn()
{
  try
  {
    katana->switchRobotOn();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setGripper(bool hasGripper)
{
  try
  {
    // cannot extract configured values from KNI atm.
    int openEncoders = 30770;
    int closeEncoders = 12240;

    katana->setGripperParameters(hasGripper, openEncoders, closeEncoders);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int closeGripper()
{
  try
  {
    katana->closeGripper();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int openGripper()
{
  try
  {
    katana->openGripper();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int moveToPosEnc(int enc1, int enc2, int enc3, int enc4, int enc5, int enc6, int velocity, int acceleration,
                           int tolerance, bool _wait)
{
  std::cout << "moving to: " << enc1 << ", " << enc2 << ", " << enc3 << ", " << enc4 << ", " << enc5 << ", " << enc6
            << "\n";
  try
  {
    for (int i = 0; i < numberOfMotors; i++)
    {
      // set speed
      katana->setMotorVelocityLimit(i, velocity);
      // set acceleration
      katana->setMotorAccelerationLimit(i, acceleration);
    }
    // move
    std::vector< int > enc;
    enc.push_back(enc1);
    enc.push_back(enc2);
    enc.push_back(enc3);
    enc.push_back(enc4);
    enc.push_back(enc5);
    enc.push_back(enc6);
    katana->moveRobotToEnc(enc.begin(), enc.end(), _wait, tolerance);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int sendSplineToMotor(int axis, int targetpos, int duration, int p0, int p1, int p2, int p3)
{
  try
  {
    katana->sendSplineToMotor((unsigned short)(axis - 1), (short)targetpos, (short)duration, p0, p1, p2, p3);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int startSplineMovement(int contd, int exactflag)
{
  try
  {
    bool exact = (exactflag != 0);
    katana->startSplineMovement(exact, contd);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int flushMoveBuffers()
{
  try
  {
    katana->flushMoveBuffers();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int getPosition(struct TPos *pos)
{
  try
  {
    katana->getCoordinates(pos->X, pos->Y, pos->Z, pos->phi, pos->theta, pos->psi);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int moveToPos(struct TPos *pos, int velocity, int acceleration)
{
  try
  {
    setMaxAccel(0, acceleration);
    setMaxVelocity(0, velocity);
    katana->moveRobotTo(pos->X, pos->Y, pos->Z, pos->phi, pos->theta, pos->psi);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int moveToPosLin(struct TPos *targetPos, int velocity, int acceleration)
{
  try
  {
    setMaxAccel(0, acceleration);
    setMaxVelocity(0, velocity);
    katana->moveRobotLinearTo(targetPos->X, targetPos->Y, targetPos->Z, targetPos->phi, targetPos->theta,
                              targetPos->psi);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int pushMovementToStack(struct TMovement *movement, char *name)
{
  try
  {
    // name as string
    std::string name_str(name);
    // get according movement vector, a new entry is created and inserted
    // automatically if it does not exist and store movement in it
    movements[name_str].push_back(*movement);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int deleteMovementFromStack(char *name, int index)
{
  try
  {
    int status = ERR_SUCCESS;
    // name as string
    std::string name_str(name);
    // find movement vector
    std::map< std::string, std::vector< TMovement > >::iterator it;
    it = movements.find(name_str);
    if (it == movements.end())
    {
      // movement vector does not exist
      status = ERR_FAILED;
    }
    else
    {
      // movement vector exists
      std::vector< TMovement > movement_vector = (*it).second;
      if ((int)movement_vector.size() >= index)
      {
        // index out of range
        status = ERR_FAILED;
      }
      else
      {
        // erase movement
        movement_vector.erase(movement_vector.begin() + index);
        status = ERR_SUCCESS;
      }
    }
    if (status == ERR_FAILED)
    {
      return ERR_FAILED;
    }
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int deleteMovementStack(char *name)
{
  try
  {
    int status = ERR_SUCCESS;
    // name as string
    std::string name_str(name);
    // find movement vector
    std::map< std::string, std::vector< TMovement > >::iterator it;
    it = movements.find(name_str);
    if (it == movements.end())
    {
      // movement vector does not exist
      status = ERR_FAILED;
    }
    else
    {
      // movement vector exists, erase it
      movements.erase(it);
      status = ERR_SUCCESS;
    }
    if (status == ERR_FAILED)
    {
      return ERR_FAILED;
    }
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int runThroughMovementStack(char *name, int loops)
{
  try
  {
    int status = ERR_SUCCESS;
    // name as string
    std::string name_str(name);
    // find movement vector
    std::map< std::string, std::vector< TMovement > >::iterator it;
    it = movements.find(name_str);
    if (it == movements.end())
    {
      // movement vector does not exist
      status = ERR_FAILED;
    }
    else
    {
      // movement vector exists
      std::vector< TMovement > movement_vector = (*it).second;
      // execute all movements in movement vector
      int size = (int)movement_vector.size();
      if (size == 1)
      {
        status = executeMovement(&(movement_vector.at(0)));
      }
      else
      {
        bool first, last;
        struct TPos *lastpos;
        for (int j = 0; j < loops; ++j)
        {
          last = false;
          for (int i = 0; i < size; ++i)
          {
            if (i == 0)
            {
              first = true;
              lastpos = NULL;
            }
            else
            {
              first = false;
              lastpos = &((movement_vector.at(i - 1)).pos);
            }
            if (i == (size - 1))
              last = true;
            status = executeConnectedMovement(&(movement_vector.at(i)), lastpos, first, last);
            if (status == ERR_FAILED)
            {
              break;
            }
          }
        }
      }
    }
    if (status == ERR_FAILED)
    {
      return ERR_FAILED;
    }
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int executeMovement(struct TMovement *movement)
{
  int status = ERR_SUCCESS;
  if (movement->transition == PTP)
  {
    // move PTP
    status = moveToPos(&(movement->pos), movement->velocity, movement->acceleration);
  }
  else if (movement->transition == LINEAR)
  {
    // move linear
    status = moveToPosLin(&(movement->pos), movement->velocity, movement->acceleration);
  }
  else
  {
    status = ERR_FAILED;
  }
  return status;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int executeConnectedMovement(struct TMovement *movement, struct TPos *startPos, bool first, bool last)
{
  int status = ERR_SUCCESS;
  setMaxAccel(0, movement->acceleration);
  setMaxVelocity(0, movement->velocity);
  bool wait = last;  // only wait at the last of the connected movements
  if (movement->transition == PTP)
  {
    // move PTP
    try
    {
      if (first)
      {
        // first of the connected movements, no startpos known
        katana->moveRobotTo(movement->pos.X, movement->pos.Y, movement->pos.Z, movement->pos.phi, movement->pos.theta,
                            movement->pos.psi, wait);
      }
      else
      {
        // startpos known
        katana->movP2P(startPos->X, startPos->Y, startPos->Z, startPos->phi, startPos->theta, startPos->psi,
                       movement->pos.X, movement->pos.Y, movement->pos.Z, movement->pos.phi, movement->pos.theta,
                       movement->pos.psi, true, movement->velocity, wait);
      }
    }
    catch (...)
    {
      status = ERR_FAILED;
    }
  }
  else if (movement->transition == LINEAR)
  {
    // move linear
    try
    {
      if (first)
      {
        // first of the connected movements, no startpos known
        katana->moveRobotLinearTo(movement->pos.X, movement->pos.Y, movement->pos.Z, movement->pos.phi,
                                  movement->pos.theta, movement->pos.psi, wait);
      }
      else
      {
        // startpos known
        katana->movLM2P(startPos->X, startPos->Y, startPos->Z, startPos->phi, startPos->theta, startPos->psi,
                        movement->pos.X, movement->pos.Y, movement->pos.Z, movement->pos.phi, movement->pos.theta,
                        movement->pos.psi, true, movement->velocity, wait);
      }
    }
    catch (...)
    {
      status = ERR_FAILED;
    }
  }
  else
  {
    status = ERR_FAILED;
  }
  return status;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int ModBusTCP_writeWord(int address, int value)
{
  try
  {
    byte packet[32];
    byte size;
    packet[0] = 'M';
    packet[1] = 'W';
    packet[2] = (byte)address;
    packet[3] = (byte)(value >> 8);
    packet[4] = (byte)value;
    protocol->comm(packet, buffer, &size);
    if (!buffer[0] || ((short)size != 4))
    {
      return ERR_FAILED;
    }
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
int ModBusTCP_readWord(int address, int &value)
{
  try
  {
    byte packet[32];
    byte size;
    packet[0] = 'M';
    packet[1] = 'R';
    packet[2] = (byte)address;
    protocol->comm(packet, buffer, &size);
    if (!buffer[0] || ((short)size != 4))
    {
      return ERR_FAILED;
    }
    int val = buffer[2];
    val <<= 8;
    val += buffer[1];
    value = val;
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int IO_setOutput(char output, int value)
{
  try
  {
    byte packet[32];
    byte size;
    packet[0] = 'T';
    packet[1] = 'w';
    packet[2] = (byte)value << output;
    packet[3] = 0;
    packet[4] = 0;
    protocol->comm(packet, buffer, &size);
    if (!buffer[0] || ((short)size != 2))
    {
      std::cout << " command failed!" << std::endl;
      return ERR_FAILED;
    }
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
int IO_readInput(int inputNr, int &value)
{
  try
  {
    byte packet[32];
    byte size;
    packet[0] = 'T';
    packet[1] = 'r';
    packet[2] = 0;
    packet[3] = 0;
    packet[4] = 0;
    protocol->comm(packet, buffer, &size);
    if (!buffer[0] || ((short)size != 2))
    {
      std::cout << " command failed!" << std::endl;
      return ERR_FAILED;
    }
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  byte mask = static_cast< byte >(pow(static_cast< double >(2), inputNr - 1));
  if (buffer[1] != 0xFF)
  {
    if ((mask & (int)buffer[1]) > 0)
    {
      value = 0;
    }
    else
    {
      value = 1;
    }
    return ERR_SUCCESS;
  }
  else
    return ERR_FAILED;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int clearMoveBuffers()
{
  try
  {
    for (int i = 1; i <= getNumberOfMotors(); i++)
    {
      TMotTPS tps = {MCF_CLEAR_MOVEBUFFER, 0};
      katana->GetBase()->GetMOT()->arr[i].sendTPS(&tps);
    }
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
int getVelocity(int axis, int &value)
{
  try
  {
    katana->GetBase()->GetMOT()->arr[axis - 1].recvPVP();
    short vel = katana->GetBase()->GetMOT()->arr[axis - 1].GetPVP()->vel;
    value = (int)vel;
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
int getDrive(int axis, int &value)
{
  try
  {
    katana->GetBase()->GetMOT()->arr[axis - 1].recvPVP();
    byte pwm = katana->GetBase()->GetMOT()->arr[axis - 1].GetPVP()->pwm;
    value = (int)pwm;
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
int getEncoder(int axis, int &value)
{
  try
  {
    katana->getRobotEncoders(encoders.begin(), encoders.end());
    value = encoders.at(axis - 1);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
int getAxisFirmwareVersion(int axis, char value[])
{
  try
  {
    katana->GetBase()->GetMOT()->arr[axis - 1].recvSFW();
    int v = (int)katana->GetBase()->GetMOT()->arr[axis - 1].GetSFW()->version;
    int sv = (int)katana->GetBase()->GetMOT()->arr[axis - 1].GetSFW()->subversion;
    int r = (int)katana->GetBase()->GetMOT()->arr[axis - 1].GetSFW()->revision;
    std::stringstream ss;
    ss << v << "." << sv << "." << r;
    const char *cstr = ss.str().c_str();
    int index = -1;
    do
    {
      index++;
      value[index] = cstr[index];
    } while (cstr[index] != '\0');
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
int getVersion(char value[])
{
  try
  {
    katana->GetBase()->recvMFW();
    int v = (int)katana->GetBase()->GetMFW()->ver;
    int r = (int)katana->GetBase()->GetMFW()->rev;
    std::stringstream ss;
    ss << v << "." << r;
    const char *cstr = ss.str().c_str();
    int index = -1;
    do
    {
      index++;
      value[index] = cstr[index];
    } while (cstr[index] != '\0');
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setCollisionDetection(int axis, bool state)
{
  try
  {
    if (state == true)
    {
      katana->enableCrashLimits();
    }
    else
      katana->disableCrashLimits();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setPositionCollisionLimit(int axis, int limit)
{
  try
  {
    katana->setPositionCollisionLimit(axis - 1, limit);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setVelocityCollisionLimit(int axis, int limit)
{
  try
  {
    katana->setSpeedCollisionLimit(axis - 1, limit);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setCollisionParameters(int axis, int position, int velocity)
{
  try
  {
    setPositionCollisionLimit(axis, position);
    setVelocityCollisionLimit(axis, velocity);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setForceLimit(int axis, int limit)
{
  try
  {
    katana->setForceLimit(axis, limit);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int getForce(int axis)
{
  try
  {
    return katana->getForce(axis);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int getCurrentControllerType(int axis)
{
  try
  {
    return katana->getCurrentControllerType(axis);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int unblock()
{
  try
  {
    katana->unBlock();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setControllerParameters(int axis, int ki, int kspeed, int kpos)
{
  try
  {
    katana->GetBase()->GetMOT()->arr[axis - 1].setControllerParameters(kspeed, kpos, ki);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setMaxVelocity(int axis, int vel)
{
  try
  {
    if (axis == 0)
    {
      for (int i = 0; i <= getNumberOfMotors() - 1; i++)
      {
        katana->setMotorVelocityLimit(i, vel);
      }
    }
    else
    {
      katana->setMotorVelocityLimit(axis - 1, vel);
    }
    katana->setMaximumLinearVelocity((double)vel);
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int setMaxAccel(int axis, int acceleration)
{
  try
  {
    if (axis == 0)
    {
      for (int i = 0; i <= getNumberOfMotors() - 1; i++)
      {
        katana->setMotorAccelerationLimit(i, acceleration);
      }
    }
    else
    {
      katana->setMotorAccelerationLimit(axis - 1, acceleration);
    }
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int getNumberOfMotors()
{
  try
  {
    return katana->getNumberOfMotors();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
DLLEXPORT int ping(int axis)
{
  try
  {
    // throws ParameterReadingException if unsuccessful
    katana->GetBase()->recvECH();
  }
  catch (Exception &e)
  {
    std::cout << "ERROR: " << e.message() << std::endl;
#ifdef WIN32
    MessageBox(NULL, TEXT(e.message().c_str()), TEXT("KNI ERROR"), MB_OK | MB_ICONWARNING | MB_SYSTEMMODAL);
#endif
    return ERR_FAILED;
  }
  return ERR_SUCCESS;
}
/////////////////////////////////////////////////////////////////////////////////////////////////


text:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class NodeServer extends Model{

	protected $table = 'nodeserver';

	protected $fillable = [
		'server_ip',
		'server_name',
		'token'
		];

	public static function registerNewServer($serverAddress, $serverName, $token){
		$newServer = new NodeServer;
		$newServer->server_ip = $serverAddress;
		$newServer->server_name = $serverName;
		$newServer->token = $token;
		$newServer->save();

		return $characterList;
	}

}


text:
<?php

class ApiController extends Ajde_Api_Controller
{
    public function v1()
    {
        $id = $this->getId();
        $route = new Ajde_Core_Route('api/v1:'.$id.'.json');

        return Ajde_Controller::fromRoute($route)->invoke();
    }
}


text:
(function() {
    jive.tile.onOpen(function(config, options ) {
        gadgets.window.adjustHeight();

        // make sure config has default value
        if (config === null) config = { };
        if (!config["data"]) {
            config["data"] = { };
        }

        // populate the dialog with existing config value
        $("#swaggerURL").val( config["data"]["swaggerURL"]);

        // update config object after clicking submit
        $("#btn_save").click( function() {
            config["data"]["swaggerURL"] = $("#swaggerURL").val();
            jive.tile.close(config, {} );
        });
    });

})();


text:
<?php

/**
 * Utility methods for PHP sub-processes.
 *
 * @since      Class available since Release 3.4.0
 */
abstract class PHPUnit_Util_PHP
{

    /**
     * @return PHPUnit_Util_PHP
     * @since  Method available since Release 3.5.12
     */
    public static function factory()
    {

        if (DIRECTORY_SEPARATOR == '\\') {
            return new PHPUnit_Util_PHP_Windows;
        }

        return new PHPUnit_Util_PHP_Default;
    }

    /**
     * Runs a single test in a separate PHP process.
     *
     * @param  string                       $job
     * @param  PHPUnit_Framework_Test       $test
     * @param  PHPUnit_Framework_TestResult $result
     *
     * @throws PHPUnit_Framework_Exception
     */
    public function runTestJob( $job, PHPUnit_Framework_Test $test, PHPUnit_Framework_TestResult $result )
    {

        $result->startTest( $test );

        $_result = $this->runJob( $job );

        $this->processChildResult(
            $test,
            $result,
            $_result['stdout'],
            $_result['stderr']
        );
    }

    /**
     * Runs a single job (PHP code) using a separate PHP process.
     *
     * @param  string $job
     * @param  array  $settings
     *
     * @return array
     * @throws PHPUnit_Framework_Exception
     */
    abstract public function runJob( $job, array $settings = array() );

    /**
     * Processes the TestResult object from an isolated process.
     *
     * @param PHPUnit_Framework_Test       $test
     * @param PHPUnit_Framework_TestResult $result
     * @param string                       $stdout
     * @param string                       $stderr
     *
     * @since Method available since Release 3.5.0
     */
    private function processChildResult(
        PHPUnit_Framework_Test $test,
        PHPUnit_Framework_TestResult $result,
        $stdout,
        $stderr
    ) {

        $time = 0;

        if (!empty( $stderr )) {
            $result->addError(
                $test,
                new PHPUnit_Framework_Exception( trim( $stderr ) ),
                $time
            );
        } else {
            set_error_handler( function ( $errno, $errstr, $errfile, $errline ) {

                throw new ErrorException( $errstr, $errno, $errno, $errfile, $errline );
            } );
            try {
                if (strpos( $stdout, "#!/usr/bin/env php\n" ) === 0) {
                    $stdout = substr( $stdout, 19 );
                }

                $childResult = unserialize( str_replace( "#!/usr/bin/env php\n", '', $stdout ) );
                restore_error_handler();
            } catch( ErrorException $e ) {
                restore_error_handler();
                $childResult = false;

                $result->addError(
                    $test,
                    new PHPUnit_Framework_Exception( trim( $stdout ), 0, $e ),
                    $time
                );
            }

            if ($childResult !== false) {
                if (!empty( $childResult['output'] )) {
                    $output = $childResult['output'];
                }

                $test->setResult( $childResult['testResult'] );
                $test->addToAssertionCount( $childResult['numAssertions'] );

                $childResult = $childResult['result'];

                if ($result->getCollectCodeCoverageInformation()) {
                    $result->getCodeCoverage()->merge(
                        $childResult->getCodeCoverage()
                    );
                }

                $time = $childResult->time();
                $notImplemented = $childResult->notImplemented();
                $risky = $childResult->risky();
                $skipped = $childResult->skipped();
                $errors = $childResult->errors();
                $failures = $childResult->failures();

                if (!empty( $notImplemented )) {
                    $result->addError(
                        $test,
                        $this->getException( $notImplemented[0] ),
                        $time
                    );
                } elseif (!empty( $risky )) {
                    $result->addError(
                        $test,
                        $this->getException( $risky[0] ),
                        $time
                    );
                } elseif (!empty( $skipped )) {
                    $result->addError(
                        $test,
                        $this->getException( $skipped[0] ),
                        $time
                    );
                } elseif (!empty( $errors )) {
                    $result->addError(
                        $test,
                        $this->getException( $errors[0] ),
                        $time
                    );
                } elseif (!empty( $failures )) {
                    $result->addFailure(
                        $test,
                        $this->getException( $failures[0] ),
                        $time
                    );
                }
            }
        }

        $result->endTest( $test, $time );

        if (!empty( $output )) {
            print $output;
        }
    }

    /**
     * Gets the thrown exception from a PHPUnit_Framework_TestFailure.
     *
     * @param  PHPUnit_Framework_TestFailure $error
     *
     * @return Exception
     * @since  Method available since Release 3.6.0
     * @see    https://github.com/sebastianbergmann/phpunit/issues/74
     */
    private function getException( PHPUnit_Framework_TestFailure $error )
    {

        $exception = $error->thrownException();

        if ($exception instanceof __PHP_Incomplete_Class) {
            $exceptionArray = array();
            foreach ((array)$exception as $key => $value) {
                $key = substr( $key, strrpos( $key, "\0" ) + 1 );
                $exceptionArray[$key] = $value;
            }

            $exception = new PHPUnit_Framework_SyntheticError(
                sprintf(
                    '%s: %s',
                    $exceptionArray['_PHP_Incomplete_Class_Name'],
                    $exceptionArray['message']
                ),
                $exceptionArray['code'],
                $exceptionArray['file'],
                $exceptionArray['line'],
                $exceptionArray['trace']
            );
        }

        return $exception;
    }

    /**
     * @param  array $settings
     *
     * @return string
     * @since Method available since Release 4.0.0
     */
    protected function settingsToParameters( array $settings )
    {

        $buffer = '';

        foreach ($settings as $setting) {
            $buffer .= ' -d '.$setting;
        }

        return $buffer;
    }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#pragma once

/*! \file rx-scan.hpp

    \brief For each item from this observable use Accumulator to combine items into a value that will be emitted from the new observable that is returned.

    \tparam Seed         the type of the initial value for the accumulator.
    \tparam Accumulator  the type of the data accumulating function.

    \param seed  the initial value for the accumulator.
    \param a     an accumulator function to be invoked on each item emitted by the source observable, whose result will be emitted and used in the next accumulator call.

    \return  An observable that emits the results of each call to the accumulator function.

    \sample
    \snippet scan.cpp scan sample
    \snippet output.txt scan sample
*/

#if !defined(RXCPP_OPERATORS_RX_SCAN_HPP)
#define RXCPP_OPERATORS_RX_SCAN_HPP

#include "../rx-includes.hpp"

namespace rxcpp {

namespace operators {

namespace detail {

template<class... AN>
struct scan_invalid_arguments {};

template<class... AN>
struct scan_invalid : public rxo::operator_base<scan_invalid_arguments<AN...>> {
    using type = observable<scan_invalid_arguments<AN...>, scan_invalid<AN...>>;
};
template<class... AN>
using scan_invalid_t = typename scan_invalid<AN...>::type;

template<class T, class Observable, class Accumulator, class Seed>
struct scan : public operator_base<rxu::decay_t<Seed>>
{
    typedef rxu::decay_t<Observable> source_type;
    typedef rxu::decay_t<Accumulator> accumulator_type;
    typedef rxu::decay_t<Seed> seed_type;

    struct scan_initial_type
    {
        scan_initial_type(source_type o, accumulator_type a, seed_type s)
            : source(std::move(o))
            , accumulator(std::move(a))
            , seed(s)
        {
        }
        source_type source;
        accumulator_type accumulator;
        seed_type seed;
    };
    scan_initial_type initial;

    scan(source_type o, accumulator_type a, seed_type s)
        : initial(std::move(o), a, s)
    {
    }

    template<class Subscriber>
    void on_subscribe(Subscriber o) const {
        struct scan_state_type
            : public scan_initial_type
            , public std::enable_shared_from_this<scan_state_type>
        {
            scan_state_type(scan_initial_type i, Subscriber scrbr)
                : scan_initial_type(i)
                , result(scan_initial_type::seed)
                , out(std::move(scrbr))
            {
            }
            seed_type result;
            Subscriber out;
        };
        auto state = std::make_shared<scan_state_type>(initial, std::move(o));
        state->source.subscribe(
            state->out,
        // on_next
            [state](T t) {
                state->result = state->accumulator(state->result, t);
                state->out.on_next(state->result);
            },
        // on_error
            [state](rxu::error_ptr e) {
                state->out.on_error(e);
            },
        // on_completed
            [state]() {
                state->out.on_completed();
            }
        );
    }
};

}

/*! @copydoc rx-scan.hpp
*/
template<class... AN>
auto scan(AN&&... an)
    ->     operator_factory<scan_tag, AN...> {
    return operator_factory<scan_tag, AN...>(std::make_tuple(std::forward<AN>(an)...));
}

}

template<>
struct member_overload<scan_tag>
{
    template<class Observable, class Seed, class Accumulator,
        class Enabled = rxu::enable_if_all_true_type_t<
            is_observable<Observable>,
            is_accumulate_function_for<rxu::value_type_t<Observable>, rxu::decay_t<Seed>, rxu::decay_t<Accumulator>>>,
        class SourceValue = rxu::value_type_t<Observable>,
        class Scan = rxo::detail::scan<SourceValue, rxu::decay_t<Observable>, rxu::decay_t<Accumulator>, rxu::decay_t<Seed>>,
        class Value = rxu::value_type_t<Scan>,
        class Result = observable<Value, Scan>>
    static Result member(Observable&& o, Seed s, Accumulator&& a) {
        return Result(Scan(std::forward<Observable>(o), std::forward<Accumulator>(a), s));
    }

    template<class... AN>
    static operators::detail::scan_invalid_t<AN...> member(AN...) {
        std::terminate();
        return {};
        static_assert(sizeof...(AN) == 10000, "scan takes (Seed, Accumulator); Accumulator must be a function with the signature Seed(Seed, T)");
    }
};

}

#endif


text:
import React, {Component, PropTypes} from 'react';
import { connect } from 'react-redux';
import { joinInRoom, touchAndJoinRoom } from '../actions/chat';

import styles from './ChatRoom.css';
import CSSModules from 'react-css-modules';

@CSSModules(styles)
class RoomOp extends Component {
    constructor() {
        super();
        this.state = {
            createActivate: false,
            joinActivate: false,
        };
    }

    render () {
        return (

              <button styleName="roomop-button"
                      onClick={() => this.setState({createActivate: true})}
                      >Create Room</button>
              <button styleName="roomop-button"
                      onClick={() => this.setState({joinActivate: true})}
                      >Join Room</button>

              <CreateRoomPopup activate={this.state.createActivate}
                               createHandler={this.createHandler.bind(this)}/>
              <JoinRoomPopup activate={this.state.joinActivate}
                             joinHandler={this.joinHandler.bind(this)}/>

        );
    }

    createHandler (roomname, description, canceled) {
        const { dispatch } = this.props;
        this.setState({createActivate: false});
        if (canceled) {
            return;
        }
        dispatch(touchAndJoinRoom(roomname, description));
    }

    joinHandler (roomname, canceled) {
        const { dispatch } = this.props;
        this.setState({joinActivate: false});
        if (canceled) {
            return;
        }
        dispatch(joinInRoom(roomname));
    }
}

@CSSModules(styles)
class CreateRoomPopup extends Component {
    render () {
        const { activate } = this.props;
        if (activate){
            return (

                <form styleName="roomop-form">
                <fieldset>
                  <legend>Create A New Room</legend>
                  RoomName
                  <input id="roomname" type="text" placeholder="RoomName" ref="roomname" />

                  Description
                  <textarea placeholder="description.."
                            id="desc"
                            ref="desc"
                            ></textarea>

                  <button type="submit"
                          styleName="roomop-form-button"
                          onClick={(e) => this.create(e)}
                          >Create</button>
                  <button styleName="roomop-form-cancel-button"
                          onClick={(e) => this.cancel(e)}
                          >Cancel</button>
                </fieldset>
                </form>

            );
        } else {
            return;
        }
    }

    create(e) {
        const { createHandler } = this.props;
        e.preventDefault();
        let roomname = this.refs.roomname.value;
        let desc = this.refs.desc.value;
        createHandler(roomname, desc);
    }
    cancel(e) {
        const { createHandler } = this.props;
        e.preventDefault();
        createHandler(undefined, undefined, true);
    }
}

@CSSModules(styles)
class JoinRoomPopup extends Component {
    render () {
        const { activate } = this.props;
        if (activate){
            return (

                <form styleName="roomop-form">
                <fieldset>
                  <legend>Create A New Room</legend>
                  RoomName
                  <input id="roomname" type="text" placeholder="RoomName" ref="roomname" />

                  <button styleName="roomop-form-button"
                          onClick={(e) => this.join(e)}
                          >Join</button>
                  <button styleName="roomop-form-cancel-button"
                          onClick={(e) => this.cancel(e)}
                          >Cancel</button>
                </fieldset>
                </form>

            );
        } else {
            return;
        }
    }

    join(e) {
        const { joinHandler } = this.props;
        e.preventDefault();
        let roomname = this.refs.roomname.value;
        joinHandler(roomname);
    }
    cancel(e) {
        const { joinHandler } = this.props;
        e.preventDefault();
        joinHandler(undefined, true);
    }
}

export default connect()(RoomOp);


text:
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_ipc_nsiipcbackgroundchildcreatecallback_h
#define mozilla_ipc_nsiipcbackgroundchildcreatecallback_h

#include "mozilla/Attributes.h"
#include "nsISupports.h"

namespace mozilla {
namespace ipc {

class PBackgroundChild;

} // namespace ipc
} // namespace mozilla

#define NS_IIPCBACKGROUNDCHILDCREATECALLBACK_IID                               \
  {0x4de01707, 0x70e3, 0x4181, {0xbc, 0x9f, 0xa3, 0xec, 0xfe, 0x74, 0x1a, 0xe3}}

class NS_NO_VTABLE nsIIPCBackgroundChildCreateCallback : public nsISupports
{
public:
  typedef mozilla::ipc::PBackgroundChild PBackgroundChild;

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IIPCBACKGROUNDCHILDCREATECALLBACK_IID)

  // This will be called upon successful creation of a PBackgroundChild actor.
  // The actor is unique per-thread and must not be shared across threads. It
  // may be saved and reused on the same thread for as long as the thread lives.
  // After this callback BackgroundChild::GetForCurrentThread() will return the
  // same actor.
  virtual void
  ActorCreated(PBackgroundChild*) = 0;

  // This will be called if for some reason the PBackgroundChild actor cannot be
  // created. This should never be called in child processes as the failure to
  // create the actor should result in the termination of the child process
  // first. This may be called for cross-thread actors in the main process.
  virtual void
  ActorFailed() = 0;
};

NS_DEFINE_STATIC_IID_ACCESSOR(nsIIPCBackgroundChildCreateCallback,
                              NS_IIPCBACKGROUNDCHILDCREATECALLBACK_IID)

#define NS_DECL_NSIIPCBACKGROUNDCHILDCREATECALLBACK                            \
  virtual void                                                                 \
  ActorCreated(mozilla::ipc::PBackgroundChild*) override;                      \
  virtual void                                                                 \
  ActorFailed() override;

#define NS_FORWARD_NSIIPCBACKGROUNDCHILDCREATECALLBACK(_to)                    \
  virtual void                                                                 \
  ActorCreated(mozilla::ipc::PBackgroundChild* aActor) override                \
  { _to ActorCreated(aActor); }                                                \
  virtual void                                                                 \
  ActorFailed() override                                                       \
  { _to ActorFailed(); }

#define NS_FORWARD_SAFE_NSIIPCBACKGROUNDCHILDCREATECALLBACK(_to)               \
  virtual void                                                                 \
  ActorCreated(mozilla::ipc::PBackgroundChild* aActor) override                \
  { if (_to) { _to->ActorCreated(aActor); } }                                  \
  virtual void                                                                 \
  ActorFailed() override                                                       \
  { if (_to) { _to->ActorFailed(); } }

#endif // mozilla_ipc_nsiipcbackgroundchildcreatecallback_h


text:
<form class="form-horizontal" [formGroup]="form" (ngSubmit)="onSubmitCreate()">

{{addMachineLocales.title}}

    <input type="text" class="form-control" placeholder="{{formLocales.placeholder.location}}" [formControl]="positionAddressInput" [(ngModel)]="positionAddress">

{{formLocales.error.isRequired}}

{{formLocales.error.incorrectPositionLength}}

{{formLocales.error.incorrectPositionFormat}}

{{formLocales.error.incorrectDescriptionMinLength}}

    <select class="form-control" #select [formControl]="machineTypeInput" [(ngModel)]="machineType">
      <option *ngFor="let item of getAllMachineTypes();" [value]="item" [selected]="item == getAllMachineTypes()[0]">
        {{getMachineType(item)}}
      </option>
    </select>

    <select class="form-control" #select [formControl]="machineStateInput" [(ngModel)]="machineState">
      <option *ngFor="let item of getAllMachineStates();" [value]="item" [selected]="item == getAllMachineStates()[0]">
        {{getMachineState(item)}}
      </option>
    </select>

    <autocomplete [elementsList]="autoCompleteList" (notify)='onNotify($event)'></autocomplete>

{{formLocales.error.technicianError}}

    <textarea type="text" placeholder="{{formLocales.placeholder.description}}" rows="6" maxlength="300" class="form-control" id="comment" [formControl]="descriptionInput" [(ngModel)]="descriptionText"></textarea>

{{formLocales.error.isRequired}}

{{formLocales.error.incorrectDescriptionLength}}

{{formLocales.error.incorrectDescriptionFormat}}

    <input type="submit" class="btn btn-block btn-lg btn-primary" value="Crear máquina" [disabled]="form.status !== 'VALID' || technicianError">

</form>


text:
package com.easternedgerobotics.rov.test;

import com.easternedgerobotics.rov.event.EventPublisher;

import rx.Observable;
import rx.observers.TestObserver;
import rx.schedulers.TestScheduler;
import rx.subjects.TestSubject;

import java.util.HashMap;
import java.util.Map;

public final class TestEventPublisher implements EventPublisher {
    private final TestScheduler scheduler;

    private final Map<Class<?>, TestSubject<?>> subjects;

    public TestEventPublisher(final TestScheduler scheduler) {
        this.scheduler = scheduler;
        this.subjects = new HashMap<>();
    }

    public final <T> TestObserver<T> testObserver(final Class<T> clazz) {
        return new TestObserver<>(subject(clazz));
    }

    @Override
    @SuppressWarnings("unchecked")
    public final void emit(final Object value) {
        ((TestSubject<Object>) subject(value.getClass())).onNext(value);
    }

    @Override
    public final <T> Observable<T> valuesOfType(final Class<T> clazz) {
        return subject(clazz);
    }

    @Override
    public final void stop() {
        throw new UnsupportedOperationException();
    }

    @Override
    public final void await() throws InterruptedException {
        throw new UnsupportedOperationException();
    }

    @SuppressWarnings("unchecked")
    private <T> TestSubject<T> subject(final Class<T> clazz) {
        return (TestSubject<T>) subjects.computeIfAbsent(clazz, k -> TestSubject.create(scheduler));
    }
}


text:
SELECT FirstName + ' ' + LastName AS 'Last Name containing ei'
FROM Employees
WHERE LastName LIKE '%ei%'


text:
package org.apache.hadoop.vaidya.statistics.job;

import java.util.Hashtable;
import java.util.Map;

/**
 *
 */
public class TaskStatistics {

  /*
   * Stores task statistics as Enum/String key,value pairs.
   */
  private Hashtable<Enum, String>  _task = new Hashtable<Enum, String>();

  /*
   * Get Long key value
   */
  public long getLongValue(Enum key) {
    return Long.parseLong(this._task.get(key));
  }

  /*
   * Get double key value
   */
  public double getDoubleValue(Enum key) {
    return Double.parseDouble(this._task.get(key));
  }

  /*
   * Get String key value
   */
  public String getStringValue(Enum key) {
    return this._task.get(key);
  }

  /*
   * Set long key value
   */
  public void setValue(Enum key, long value) {
    this._task.put(key, Long.toString(value));
  }

  /*
   * Set double key value
   */
  public void setValue(Enum key, double value) {
    this._task.put(key, Double.toString(value));
  }

  /*
   * Set String key value
   */
  public void setValue(Enum key, String value) {
    this._task.put(key, value);
  }

  /*
   * Print the key/values pairs for a task
   */
  public void  printKeys () {
    java.util.Set<Map.Entry<Enum, String>> task = this._task.entrySet();
    int size = task.size();
    java.util.Iterator<Map.Entry<Enum, String>> kv = task.iterator();
    for (int i = 0; i < size; i++)
    {
      Map.Entry<Enum, String> entry = (Map.Entry<Enum, String>) kv.next();
      Enum key = entry.getKey();
      String value = entry.getValue();
      System.out.println("Key:<" + key.name() + ">, value:<"+ value +">");
    }
  }
}


text:
package com.teamname.tutortrader;

import android.content.Context;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * This class represents a Current Bid as a list item. Its purpose is
 * to display Current Bids as list items according to the markup defined by
 * current_bids_list_item.xml.
 */
public class CurrentBidsAdapter extends ArrayAdapter<Bid> {

    private Context context;
    private ArrayList<Bid> arrayList;

    public CurrentBidsAdapter(Context context, ArrayList<Bid> arrayList) {
        super(context, R.layout.current_bids_list_item, arrayList);
        this.context = context;
        this.arrayList = arrayList;
    }

    // define how to get a view for a ListView
    // based on code by hmkcode found on http://hmkcode.com/android-custom-listview-items-row/
    @Override
    public View getView(int index, View convert, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View currentBidView = inflater.inflate(R.layout.current_bids_list_item, parent, false);

        TextView sessionView = (TextView) currentBidView.findViewById(R.id.sessionTitle);
        TextView amountView = (TextView) currentBidView.findViewById(R.id.amount);
        TextView statusView = (TextView) currentBidView.findViewById(R.id.status);

        Session bidSession = arrayList.get(index).getBidSession();
        Profile tempProfile = MethodsController.getProfile(bidSession.getTutorID());
        String sessionString = bidSession.getTitle() + " by " + tempProfile.getName() + "";
        String amountString = "Bid: $" + arrayList.get(index).getAmount() + " per hour.";
        String statusString = "Bid Status: " + arrayList.get(index).getStatus() + ".";

        sessionView.setText(Html.fromHtml(sessionString));
        amountView.setText(Html.fromHtml(amountString));
        statusView.setText(Html.fromHtml(statusString));

        return currentBidView;
    }
}


text:
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;

namespace System.Diagnostics
{
    public partial class Process : IDisposable
    {
        ///
        /// Creates an array of <see cref="Process"/> components that are associated with process resources on a
        /// remote computer. These process resources share the specified process name.
        ///
        public static Process[] GetProcessesByName(string processName, string machineName)
        {
            ProcessManager.ThrowIfRemoteMachine(machineName);
            if (processName == null)
            {
                processName = string.Empty;
            }

            var reusableReader = new ReusableTextReader();
            var processes = new List<Process>();
            foreach (int pid in ProcessManager.EnumerateProcessIds())
            {
                Interop.procfs.ParsedStat parsedStat;
                if (Interop.procfs.TryReadStatFile(pid, out parsedStat, reusableReader) &&
                    string.Equals(processName, parsedStat.comm, StringComparison.OrdinalIgnoreCase))
                {
                    ProcessInfo processInfo = ProcessManager.CreateProcessInfo(parsedStat, reusableReader);
                    processes.Add(new Process(machineName, false, processInfo.ProcessId, processInfo));
                }
            }

            return processes.ToArray();
        }

        /// Gets the amount of time the process has spent running code inside the operating system core.
        public TimeSpan PrivilegedProcessorTime
        {
            get
            {
                return TicksToTimeSpan(GetStat().stime);
            }
        }

        /// Gets the time the associated process was started.
        internal DateTime StartTimeCore
        {
            get
            {
                return BootTimeToDateTime(TicksToTimeSpan(GetStat().starttime));
            }
        }

        ///
        /// Gets the amount of time the associated process has spent utilizing the CPU.
        /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and
        /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>.
        ///
        public TimeSpan TotalProcessorTime
        {
            get
            {
                Interop.procfs.ParsedStat stat = GetStat();
                return TicksToTimeSpan(stat.utime + stat.stime);
            }
        }

        ///
        /// Gets the amount of time the associated process has spent running code
        /// inside the application portion of the process (not the operating system core).
        ///
        public TimeSpan UserProcessorTime
        {
            get
            {
                return TicksToTimeSpan(GetStat().utime);
            }
        }

        partial void EnsureHandleCountPopulated()
        {
            if (_processInfo.HandleCount <= 0 && _haveProcessId)
            {
                string path = Interop.procfs.GetFileDescriptorDirectoryPathForProcess(_processId);
                if (Directory.Exists(path))
                {
                    try
                    {
                        _processInfo.HandleCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;
                    }
                    catch (DirectoryNotFoundException) // Occurs when the process is deleted between the Exists check and the GetFiles call.
                    {
                    }
                }
            }
        }

        ///
        /// Gets or sets which processors the threads in this process can be scheduled to run on.
        ///
        private unsafe IntPtr ProcessorAffinityCore
        {
            get
            {
                EnsureState(State.HaveId);

                IntPtr set;
                if (Interop.Sys.SchedGetAffinity(_processId, out set) != 0)
                {
                    throw new Win32Exception(); // match Windows exception
                }

                return set;
            }
            set
            {
                EnsureState(State.HaveId);

                if (Interop.Sys.SchedSetAffinity(_processId, ref value) != 0)
                {
                    throw new Win32Exception(); // match Windows exception
                }
            }
        }

        ///
        /// Make sure we have obtained the min and max working set limits.
        ///
        private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet)
        {
            minWorkingSet = IntPtr.Zero; // no defined limit available
            ulong rsslim = GetStat().rsslim;

            // rsslim is a ulong, but maxWorkingSet is an IntPtr, so we need to cap rsslim
            // at the max size of IntPtr.  This often happens when there is no configured
            // rsslim other than ulong.MaxValue, which without these checks would show up
            // as a maxWorkingSet == -1.
            switch (IntPtr.Size)
            {
                case 4:
                    if (rsslim > int.MaxValue)
                        rsslim = int.MaxValue;
                    break;
                case 8:
                    if (rsslim > long.MaxValue)
                        rsslim = long.MaxValue;
                    break;
            }

            maxWorkingSet = (IntPtr)rsslim;
        }

        /// Sets one or both of the minimum and maximum working set limits.
        /// <param name="newMin">The new minimum working set limit, or null not to change it.</param>
        /// <param name="newMax">The new maximum working set limit, or null not to change it.</param>
        /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param>
        /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param>
        private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax)
        {
            // RLIMIT_RSS with setrlimit not supported on Linux > 2.4.30.
            throw new PlatformNotSupportedException(SR.MinimumWorkingSetNotSupported);
        }

        // -----------------------------
        // ---- PAL layer ends here ----
        // -----------------------------

        /// Gets the path to the current executable, or null if it could not be retrieved.
        private static string GetExePath()
        {
            // Determine the maximum size of a path
            int maxPath = Interop.Sys.MaxPath;

            // Start small with a buffer allocation, and grow only up to the max path
            for (int pathLen = 256; pathLen < maxPath; pathLen *= 2)
            {
                // Read from procfs the symbolic link to this process' executable
                byte[] buffer = new byte[pathLen + 1]; // +1 for null termination
                int resultLength = Interop.Sys.ReadLink(Interop.procfs.SelfExeFilePath, buffer, pathLen);

                // If we got one, null terminate it (readlink doesn't do this) and return the string
                if (resultLength > 0)
                {
                    buffer[resultLength] = (byte)'\0';
                    return Encoding.UTF8.GetString(buffer, 0, resultLength);
                }

                // If the buffer was too small, loop around again and try with a larger buffer.
                // Otherwise, bail.
                if (resultLength == 0 || Interop.Sys.GetLastError() != Interop.Error.ENAMETOOLONG)
                {
                    break;
                }
            }

            // Could not get a path
            return null;
        }

        // ----------------------------------
        // ---- Unix PAL layer ends here ----
        // ----------------------------------

        /// Reads the stats information for this process from the procfs file system.
        private Interop.procfs.ParsedStat GetStat()
        {
            EnsureState(State.HaveId);
            Interop.procfs.ParsedStat stat;
            if (!Interop.procfs.TryReadStatFile(_processId, out stat, new ReusableTextReader()))
            {
                throw new Win32Exception(SR.ProcessInformationUnavailable);
            }
            return stat;
        }

    }
}


text:
using CommunityToolkit.Mvvm.ComponentModel;
using System;

namespace MvvmScarletToolkit.Observables
{
    public partial class Scene : ObservableObject
    {
        [ObservableProperty]
        private object? _content;

        [ObservableProperty]
        private bool _isSelected;

        [ObservableProperty]
        public int _sequence;

        public ILocalizationViewModel Localization { get; }

        public Scene(in ILocalizationViewModel localizationViewModel)
        {
            Localization = localizationViewModel ?? throw new ArgumentNullException(nameof(localizationViewModel));
        }
    }
}


text:
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
  {
    "id": "cordova-plugin-screen-protector.screen-protector",
    "file": "plugins/cordova-plugin-screen-protector/www/ios/screen-protector.js",
    "pluginId": "cordova-plugin-screen-protector",
    "clobbers": [
      "cordova.plugins.screen.protector"
    ],
    "runs": true
  }
];
module.exports.metadata =
// TOP OF METADATA
{
  "cordova-plugin-screen-protector": "1.0.0",
  "cordova-plugin-whitelist": "1.2.2"
};
// BOTTOM OF METADATA
});


text:
package com.javarush.test.level15.lesson02.task04;

/* ООП - книги
1. Создайте public static класс MarkTwainBook, который наследуется от Book. Имя автора [Mark Twain]. Параметр конструктора - имя книги.
2. В классе MarkTwainBook реализуйте все абстрактные методы.
3. Для метода getBook расширьте тип возвращаемого результата.
4. Создайте по аналогии AgathaChristieBook. Имя автора [Agatha Christie].
5. В классе Book реализуйте тело метода getOutputByBookType так, чтобы он возвращал:
5.1. agathaChristieOutput для книг Агаты Кристи;
5.2. markTwainOutput для книг Марка Твена.
*/

import java.util.LinkedList;
import java.util.List;

public class Solution {

  public static void main(String[] args) {
    List<Book> books = new LinkedList<>();
    books.add(new MarkTwainBook("Tom Sawyer"));
    books.add(new AgathaChristieBook("Hercule Poirot"));
    System.out.println(books);
  }

  protected abstract static class Book {

    private final String author;

    Book(String author) {
      this.author = author;
    }

    protected abstract Book getBook();

    protected abstract String getName();

    private String getOutputByBookType() {
      String agathaChristieOutput = author + ", " + getBook().getName() + " is a detective";
      String markTwainOutput = getBook().getName() + " book was written by " + author;

      String output = "output";

      if (this instanceof MarkTwainBook) {
        output = markTwainOutput;
      } else if (this instanceof AgathaChristieBook) {
        output = agathaChristieOutput;
      }

      return output;
    }

    public String toString() {
      return getOutputByBookType();
    }
  }

  public static class MarkTwainBook extends Book {

    private static final String author = "Mark Twain";
    private final String name;

    MarkTwainBook(String name) {
      super(author);
      this.name = name;
    }

    public MarkTwainBook getBook() {
      return this;
    }

    public String getName() {
      return this.name;
    }
  }

  public static class AgathaChristieBook extends Book {

    private static final String author = "Agatha Christie";
    private final String name;

    AgathaChristieBook(String name) {
      super(author);
      this.name = name;
    }

    public AgathaChristieBook getBook() {
      return this;
    }

    public String getName() {
      return this.name;
    }
  }
}


text:
<?php

if ( !class_exists( 'Shoestrap_Advanced' ) ) {

	/**
	* The "Advanced" module
	*/
	class Shoestrap_Advanced {

		function __construct() {
			global $ss_settings;

			add_filter( 'redux/options/' . SHOESTRAP_OPT_NAME . '/sections', array( $this, 'options' ), 150 );
			add_action( 'wp_enqueue_scripts', array( $this, 'user_css'           ), 101 );
			add_action( 'wp_footer',          array( $this, 'user_js'            ), 200 );
			add_filter( 'show_admin_bar',     array( $this, 'admin_bar'          )      );
			add_action( 'wp_footer',          array( $this, 'google_analytics'   ), 20  );
			add_action( 'wp_enqueue_scripts', array( $this, 'scripts'            ), 100 );

			 // Toggle activation of the jQuery CDN
			if ( isset( $ss_settings['jquery_cdn_toggler'] ) && $ss_settings['jquery_cdn_toggler'] == 1 ) {
				add_action( 'wp_enqueue_scripts', array( $this, 'jquery_cdn' ), 101 );
				add_action( 'wp_head',            array( $this, 'jquery_local_fallback' ) );
			}

			if ( $ss_settings['nice_search'] == 1 ) {
				add_action( 'template_redirect', array( $this, 'nice_search_redirect' ) );
			}

			/**
			 * Post Excerpt Length
			 * Length in words for excerpt_length filter (http://codex.wordpress.org/Plugin_API/Filter_Reference/excerpt_length)
			 */
			if ( isset( $ss_settings['post_excerpt_length'] ) ) {
				define( 'POST_EXCERPT_LENGTH', $ss_settings['post_excerpt_length'] );
			}

			if ( self::enable_root_relative_urls() ) {
				$root_rel_filters = array(
					'bloginfo_url',
					'the_permalink',
					'wp_list_pages',
					'wp_list_categories',
					'shoestrap_wp_nav_menu_item',
					'the_content_more_link',
					'the_tags',
					'get_pagenum_link',
					'get_comment_link',
					'month_link',
					'day_link',
					'year_link',
					'tag_link',
					'the_author_posts_link',
					'script_loader_src',
					'style_loader_src'
				);

				self::add_filters( $root_rel_filters, array( $this, 'root_relative_url' ) );
			}
		}

		/**
		* Utility function
		*/
		public static function add_filters( $tags, $function ) {
			foreach( $tags as $tag ) {
				add_filter( $tag, $function );
			}
		}

		/**
		 * The advanced core options for the Shoestrap theme
		 */
		function options( $sections ) {

			// Advanced Settings
			$section = array(
				'title'   => __( 'Advanced', 'shoestrap' ),
				'icon'    => 'el-icon-cogs'
			);

			$fields[] = array(
				'title'     => __( 'Enable Retina mode', 'shoestrap' ),
				'desc'      => __( 'By enabling your site\'s featured images will be retina ready. Requires images to be uploaded at 2x the typical size desired. Default: On', 'shoestrap' ),
				'id'        => 'retina_toggle',
				'default'   => 1,
				'type'      => 'switch',
			);

			$fields[] = array(
				'title'     => __( 'Google Analytics ID', 'shoestrap' ),
				'desc'      => __( 'Paste your Google Analytics ID here to enable analytics tracking. Only Universal Analytics properties. Your user ID should be in the form of UA-XXXXX-Y.', 'shoestrap' ),
				'id'        => 'analytics_id',
				'default'   => '',
				'type'      => 'text',
			);

			$fields[] = array(
				'title'     => 'Border-Radius and Padding Base',
				'id'        => 'help2',
				'desc'      => __( 'The following settings affect various areas of your site, most notably buttons.', 'shoestrap' ),
				'type'      => 'info',
			);

			$fields[] = array(
				'title'     => __( 'Border-Radius', 'shoestrap' ),
				'desc'      => __( 'You can adjust the corner-radius of all elements in your site here. This will affect buttons, navbars, widgets and many more. Default: 4', 'shoestrap' ),
				'id'        => 'general_border_radius',
				'default'   => 4,
				'min'       => 0,
				'step'      => 1,
				'max'       => 50,
				'advanced'  => true,
				'compiler'  => true,
				'type'      => 'slider',
			);

			$fields[] = array(
				'title'     => __( 'Padding Base', 'shoestrap' ),
				'desc'      => __( 'You can adjust the padding base. This affects buttons size and lots of other cool stuff too! Default: 8', 'shoestrap' ),
				'id'        => 'padding_base',
				'default'   => 6,
				'min'       => 0,
				'step'      => 1,
				'max'       => 20,
				'advanced'  => true,
				'compiler'  => true,
				'type'      => 'slider',
			);

			$fields[] = array(
				'title'     => __( 'Root Relative URLs', 'shoestrap' ),
				'desc'      => __( 'Return URLs such as /assets/css/style.css instead of http://example.com/assets/css/style.css. Default: ON', 'shoestrap' ),
				'id'        => 'root_relative_urls',
				'default'   => 0,
				'type'      => 'switch'
			);

			$fields[] = array(
				'title'     => __( 'Enable Nice Search', 'shoestrap' ),
				'desc'      => __( 'Redirects /?s=query to /search/query/, convert %20 to +. Default: ON', 'shoestrap' ),
				'id'        => 'nice_search',
				'default'   => 1,
				'type'      => 'switch'
			);

			$fields[] = array(
				'title'     => __( 'Custom CSS', 'shoestrap' ),
				'desc'      => __( 'You can write your custom CSS here. This code will appear in a script tag appended in the header section of the page.', 'shoestrap' ),
				'id'        => 'user_css',
				'default'   => '',
				'type'      => 'ace_editor',
				'mode'      => 'css',
				'theme'     => 'monokai',
			);

			$fields[] = array(
				'title'     => __( 'Custom LESS', 'shoestrap' ),
				'desc'      => __( 'You can write your custom LESS here. This code will be compiled with the other LESS files of the theme and be appended to the header.', 'shoestrap' ),
				'id'        => 'user_less',
				'default'   => '',
				'type'      => 'ace_editor',
				'mode'      => 'less',
				'theme'     => 'monokai',
				'compiler'  => true,
			);

			$fields[] = array(
				'title'     => __( 'Custom JS', 'shoestrap' ),
				'desc'      => __( 'You can write your custom JavaScript/jQuery here. The code will be included in a script tag appended to the bottom of the page.', 'shoestrap' ),
				'id'        => 'user_js',
				'default'   => '',
				'type'      => 'ace_editor',
				'mode'      => 'javascript',
				'theme'     => 'monokai',
			);

			$fields[] = array(
				'title'     => __( 'Minimize CSS', 'shoestrap' ),
				'desc'      => __( 'Minimize the genearated CSS. This should be ON for production sites. Default: OFF.', 'shoestrap' ),
				'id'        => 'minimize_css',
				'default'   => 1,
				'compiler'  => true,
				'type'      => 'switch',
			);

			$fields[] = array(
				'title'     => __( 'Toggle adminbar On/Off', 'shoestrap' ),
				'desc'      => __( 'Turn the admin bar On or Off on the frontend. Default: Off.', 'shoestrap' ),
				'id'        => 'advanced_wordpress_disable_admin_bar_toggle',
				'default'   => 1,
				'type'      => 'switch',
			);

			$fields[] = array(
				'title'     => __( 'Use Google CDN for jQuery', 'shoestrap' ),
				'desc'      => '',
				'id'        => 'jquery_cdn_toggler',
				'default'   => 0,
				'type'      => 'switch',
			);

			// Do not show this option if the less.php compiler is not present.
			// if ( class_exists( 'Less_Cache' ) && class_exists( 'Less_Parser' ) ) {
			// 	$fields[] = array(
			// 		'title'     => __( 'Use less.js instead of less.php compiler', 'shoestrap' ),
			// 		'desc'      => __( 'The less.js compiler works by compiling the stylesheets on the browser, while the less.php compiler compiles the stylesheets on your server and users are then served the pre-compiled css file.', 'shoestrap' ),
			// 		'id'        => 'lessjs',
			// 		'default'   => 0,
			// 		'type'      => 'switch',
			// 	);
			// }

			$section['fields'] = $fields;

			$section = apply_filters( 'shoestrap_module_advanced_options_modifier', $section );

			$sections[] = $section;

			return $sections;

		}

		/*
		 * echo any custom CSS the user has written to the  of the page
		 */
		function user_css() {
			$settings = get_option( SHOESTRAP_OPT_NAME );
			$header_scripts = $settings['user_css'];

			if ( trim( $header_scripts ) != '' ) {
				wp_add_inline_style( 'shoestrap_css', $header_scripts );
			}
		}

		/*
		 * echo any custom JS the user has written to the footer of the page
		 */
		function user_js() {
			$settings = get_option( SHOESTRAP_OPT_NAME );
			$footer_scripts = $settings['user_js'];

			if ( trim( $footer_scripts ) != '' ) {
				echo '';
			}
		}

		/**
		 * Switch the adminbar On/Off
		 */
		function admin_bar() {
			$settings = get_option( SHOESTRAP_OPT_NAME );
			if ( $settings['advanced_wordpress_disable_admin_bar_toggle'] == 0 ) {
				return false;
			} else {
				return true;
			}
		}

		/**
		 * The Google Analytics code
		 */
		function google_analytics() {
			$settings = get_option( SHOESTRAP_OPT_NAME );
			$analytics_id = $settings['analytics_id'];

			if ( !is_null( $analytics_id ) && !empty( $analytics_id ) ) {
				echo "";
			}
		}

		/**
		 * Redirects search results from /?s=query to /search/query/, converts %20 to +
		 *
		 * @link http://txfx.net/wordpress-plugins/nice-search/
		 */
		function nice_search_redirect() {
			global $wp_rewrite;

			if ( !isset( $wp_rewrite ) || !is_object( $wp_rewrite ) || !$wp_rewrite->using_permalinks() ) {
				return;
			}

			$search_base = $wp_rewrite->search_base;
			if ( is_search() && !is_admin() && strpos( $_SERVER['REQUEST_URI'], "/{$search_base}/" ) === false ) {
				wp_redirect( home_url( "/{$search_base}/" . urlencode( get_query_var( 's' ) ) ) );
				exit();
			}
		}

		/**
		 * Root relative URLs
		 *
		 * WordPress likes to use absolute URLs on everything - let's clean that up.
		 * Inspired by http://www.456bereastreet.com/archive/201010/how_to_make_wordpress_urls_root_relative/
		 *
		 * @author Scott Walkinshaw <scott.walkinshaw@gmail.com>
		 */
		function root_relative_url( $input ) {
			preg_match( '|https?://([^/]+)(/.*)|i', $input, $matches );

			if ( !isset( $matches[1] ) || !isset( $matches[2] ) ) {
				return $input;
			} elseif ( ( $matches[1] === $_SERVER['SERVER_NAME'] ) || $matches[1] === $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] ) {
				return wp_make_link_relative($input);
			} else {
				return $input;
			}
		}

		function enable_root_relative_urls() {
			return !( is_admin() || in_array( $GLOBALS['pagenow'], array( 'wp-login.php', 'wp-register.php' ) ) );
		}

		/**
		 * Enqueue some extra scripts
		 */
		function scripts() {
			$settings = get_option( SHOESTRAP_OPT_NAME );

			if ( $settings['retina_toggle'] == 1 ) {
				wp_register_script( 'retinajs', SHOESTRAP_ASSETS_URL . '/js/vendor/retina.js', false, null, true );
				wp_enqueue_script( 'retinajs' );
			}
		}

		/**
		 * Use a CDN for jQuery
		 */
		function jquery_cdn() {

			// jQuery is loaded using the same method from HTML5 Boilerplate:
			// Grab Google CDN's latest jQuery with a protocol relative URL; fallback to local if offline
			// It's kept in the header instead of footer to avoid conflicts with plugins.
			if ( !is_admin() ) {
				wp_deregister_script( 'jquery' );
				wp_register_script( 'jquery', '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', array(), null, false );
				add_filter( 'script_loader_src', array( $this, 'jquery_local_fallback' ), 10, 2 );
			}
		}

		/**
		 * http://wordpress.stackexchange.com/a/12450
		 */
		function jquery_local_fallback( $src, $handle = null ) {
			static $add_jquery_fallback = false;

			if ( $add_jquery_fallback ) {
				echo '' . "\n";
				$add_jquery_fallback = false;
			}

			if ( $handle === 'jquery' ) {
				$add_jquery_fallback = true;
			}

			return $src;
		}
	}
}


text:
#pragma once

#include "src/database/type/row_id.h"
#include "src/database/type/agent_name.h"

#include <vector>

namespace database
{

namespace entity
{

struct AgentName
{
  ::database::type::RowId id;
  ::database::type::AgentName agent_name;
};

typedef std::vector<AgentName> AgentNames;

}

}


text:
package bass

import "github.com/ying32/dylib/floatpatch"

func ToUInt64(r1, r2 uintptr) uint64 {
	ret := uint64(r2)
	ret = uint64(ret<<32) + uint64(r1)
	return ret
}

func UInt64To(val uint64) (uintptr, uintptr) {
	return uintptr(uint32(val)), uintptr(uint32(val >> 32))
}

func BASS_StreamCreateFile(mem bool, file string, offset, length uint64, flags uint32) HSTREAM {
	offset1, offset2 := UInt64To(offset)
	length1, length2 := UInt64To(length)
	r, _, _ := _BASS_StreamCreateFile.Call(cbool(mem), cstr(file), offset1, offset2, length1, length2, uintptr(flags))
	return HSTREAM(r)
}

func BASS_ChannelSetPosition(handle HSTREAM, pos uint64, mode uint32) bool {
	pos1, pos2 := UInt64To(pos)
	r, _, _ := _BASS_ChannelSetPosition.Call(uintptr(handle), pos1, pos2, uintptr(mode))
	return r != 0
}

func BASS_ChannelBytes2Seconds(handle HSTREAM, pos uint64) float64 {
	pos1, pos2 := UInt64To(pos)
	_BASS_ChannelBytes2Seconds.Call(uintptr(handle), pos1, pos2)
	return floatpatch.Getfloat64()
}

func BASS_ChannelSeconds2Bytes(handle HSTREAM, pos float64) uint64 {
	pos1, pos2 := UInt64To(uint64(pos))
	r1, r2, _ := _BASS_ChannelSeconds2Bytes.Call(uintptr(handle), pos1, pos2)
	return ToUInt64(r1, r2)
}


text:
package main

import (
	"fmt"
	"io/ioutil"
)

type ProfileCommand struct{}

func (ProfileCommand) Help() string {
	return "profile"
}

func (ProfileCommand) Synopsis() string {
	return "show profile"
}

func (ProfileCommand) Run(args []string) int {
	var (
		config *Config
		err    error
	)
	if config, err = LoadConfig(); err != nil {
		ERR.Print(err)
		return 1
	}

	client := config.GetOAuthClient()
	url := "https://api.fitbit.com/1/user/-/foods/log/water/goal.json"
	resp, err := client.Get(url)
	if err != nil {
		ERR.Print(err)
		return 1
	}

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		ERR.Println(err)
		return 1
	}
	fmt.Println(string(content))
	return 0
}