text:
package org.coderswithoutborders.deglancer.presenter;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.Time;
import android.view.Gravity;
import android.widget.Toast;

import com.google.firebase.analytics.FirebaseAnalytics;

import org.coderswithoutborders.deglancer.R;
import org.coderswithoutborders.deglancer.bus.RxBus;
import org.coderswithoutborders.deglancer.bus.events.DebugStageEvent;
import org.coderswithoutborders.deglancer.func_debug.view.ITargetSetView;
import org.coderswithoutborders.deglancer.func_debug.view.TargetSetView;
import org.coderswithoutborders.deglancer.interactor.DatabaseInteractor;
import org.coderswithoutborders.deglancer.interactor.IDatabaseInteractor;
import org.coderswithoutborders.deglancer.interactor.IInitialStartupInteractor;
import org.coderswithoutborders.deglancer.interactor.IStageInteractor;
import org.coderswithoutborders.deglancer.model.Stage;
import org.coderswithoutborders.deglancer.model.Target;
import org.coderswithoutborders.deglancer.utils.ToastUtils;
import org.coderswithoutborders.deglancer.view.IMainActivityView;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
import timber.log.Timber;

/**
 * Created by chris.teli on 3/21/2016.
 */
public class MainActivityPresenter implements IMainActivityPresenter {

    private CompositeSubscription mSubscriptions;

    private IInitialStartupInteractor mInitialStartupInteractor;
    private IStageInteractor mStageInteractor;
    private IDatabaseInteractor mDatabaseInteractor;
    private RxBus mBus;

    private IMainActivityView mView;

    private FirebaseAnalytics mFirebaseAnalytics;

    public MainActivityPresenter(IInitialStartupInteractor initialStartupInteractor, IStageInteractor stageInteractor, IDatabaseInteractor databaseInteractor, RxBus bus) {
        mInitialStartupInteractor = initialStartupInteractor;
        mStageInteractor = stageInteractor;
        mDatabaseInteractor = databaseInteractor;
        mBus = bus;

        mSubscriptions = new CompositeSubscription();
    }

    @Override
    public void setView(IMainActivityView view) {
        mView = view;

        if (mSubscriptions == null || mSubscriptions.isUnsubscribed()) {
            mSubscriptions = new CompositeSubscription();
        } else if (!mSubscriptions.isUnsubscribed()) {
            mSubscriptions.unsubscribe();
            mSubscriptions = new CompositeSubscription();
        }

        mSubscriptions.add(mBus.toObserverable().subscribe((event) -> {

        }));
    }

    @Override
    public void clearView() {
        mView = null;

        if (!mSubscriptions.isUnsubscribed())
            mSubscriptions.unsubscribe();
    }

    @Override
    public void init() {
        mInitialStartupInteractor.captureInitialDataIfNotCaptured();

        mStageInteractor.getCurrentStage()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(stage -> {
                    if (mView != null) {
                        // mView.setStageText(stage.getStage() + "-" + stage.getDay() + "-" + stage.getHour());
                        mView.setIntroText(stage.getStage(), stage.getDay());
                    }
                }, error -> {
                    //TODO - Handle error
                    String here = "";
                });
    }

    @Override
    public boolean isPreTestRun() {
        if (mDatabaseInteractor.isPreTestRun()) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public int whatStage() {

        Stage stage = mStageInteractor.getCurrentStageSynchronous();

        switch (stage.getStage()) {
            case 1:
                return 1;
            case 2:
                return 2;
            case 3:
                return 3;
            case 4:
                return 4;
            case 5:
                return 5;
            case 6:
                return 6;
        }

        return 0;

    }

    @Override
    public int whatTarget() {
        Target myTarget = mDatabaseInteractor.getTargetForStage(4);
        if (myTarget == null) {
            return -1;
        } else {
            return myTarget.getTarget();
        }
    }

    @Override
    public void debugClicked() {
        mStageInteractor.getCurrentStage()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(stage -> {
                    if (mView != null) {
                        switch (stage.getStage()) {
                            case 1:
                                mView.showStage1View(stage);
                                break;

                            case 2:
                                mView.showStage2View(stage);
                                break;

                            case 3:
                                mView.showStage3View(stage);
                                break;

                            case 4:
                                mView.showStage4View(stage);
                                break;

                            case 5:
                                mView.showStage5View(stage);
                                break;

                            case 6:
                                mView.showStage6View(stage);
                                break;
                        }
                    }
                }, error -> {
                    //TODO - Handle error
                    String here = "";
                });
    }

    @Override
    public void snoozeClicked(Context context) {
        ToastUtils.setSnooze(context);
        Toast toast = Toast.makeText(context, context.getString(R.string.tvSnoozedText), 3);
        toast.setGravity(Gravity.BOTTOM, 0, 30);
        toast.show();

        mFirebaseAnalytics = FirebaseAnalytics.getInstance(context);
        Bundle fbAnalyticsBundle = new Bundle();
        fbAnalyticsBundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "snooze_notification");
        fbAnalyticsBundle.putString(FirebaseAnalytics.Param.VIRTUAL_CURRENCY_NAME, "Snooze notification");
        fbAnalyticsBundle.putLong(FirebaseAnalytics.Param.VALUE, 2L);
        mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SPEND_VIRTUAL_CURRENCY, fbAnalyticsBundle);

    }

    // Adjust start time if app has been updated from pre-V16
    public void adjustStartTime(Context context) {

        final String SP_NAME = "InitialStartupSP";
        final String SP_KEY_INITIAL_SETUP_DONE = "InitialSetupDone";
        final String SP_KEY_INITIAL_START_TIME = "InitialStartTime";
        final String SP_KEY_INITIAL_TIMEZONE = "InitialTimezone";
        final String SP_KEY_INITIAL_START_TIME_ZERO_HOUR = "InitialStartTimeZeroHour";

        SharedPreferences mPrefs;
        mPrefs = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
        Boolean initialSetupDone = mPrefs.getBoolean(SP_KEY_INITIAL_SETUP_DONE, false);
        if (!initialSetupDone) {
            Timber.d("Initial startup. Skipping.");
            return;
        } else {
            Timber.d("Adjusting...");
            Long initialZeroHour = mPrefs.getLong(SP_KEY_INITIAL_START_TIME_ZERO_HOUR, -1);
            if (Long.valueOf(initialZeroHour) == Long.valueOf(-1)) {
                Long initialStartTime = mPrefs.getLong(SP_KEY_INITIAL_START_TIME, 0);
                String userTimezone = mPrefs.getString(SP_KEY_INITIAL_TIMEZONE, "-1");
                if (userTimezone == "-1") {
                    Timber.d("Gotta specify timezone first");
                    userTimezone = Time.getCurrentTimezone();
                }
                Timber.d("Timezone: " + userTimezone);
                Timber.d("Initial start time: " + Long.toString(initialStartTime));
                DateTime startTimeBeginning = new DateTime(Long.valueOf(initialStartTime), DateTimeZone.UTC);
                DateTime todayStart = startTimeBeginning.withTimeAtStartOfDay();
                Timber.d("Beginning of the day: " + Long.toString(todayStart.getMillis()));
                Timber.d("Now overriding");
                initialStartTime = todayStart.getMillis();
                SharedPreferences.Editor editor;
                editor = mPrefs.edit();
                editor.putLong(SP_KEY_INITIAL_START_TIME, initialStartTime);
                editor.putLong(SP_KEY_INITIAL_START_TIME_ZERO_HOUR, initialStartTime);
                editor.putString(SP_KEY_INITIAL_TIMEZONE, userTimezone);
                editor.apply();
                Timber.d("Initial start time now: " + Long.toString(initialStartTime));
            } else {
                Timber.d("Start time adjusted, no need.");
            }

        }
    }

}


text:
> Compiles C programs according to the ISO C standard.

- Compile source file(s) and create an executable:

`c99 {{file.c}}`

- Compile source file(s) and create an executable with a custom name:

`c99 -o {{executable_name}} {{file.c}}`

- Compile source file(s) and create object file(s):

`c99 -c {{file.c}}`

- Compile source file(s), link with object file(s), and create an executable:

`c99 {{file.c}} {{file.o}}`

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.cxx;

import com.facebook.buck.rules.AbstractBuildRule;
import com.facebook.buck.rules.AddToRuleKey;
import com.facebook.buck.rules.BuildContext;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildableContext;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.step.Step;
import com.facebook.buck.step.fs.MkdirStep;
import com.facebook.buck.step.fs.RmStep;
import com.google.common.collect.ImmutableList;

import java.nio.file.Path;

import javax.annotation.Nullable;

public class Yacc extends AbstractBuildRule {

  @AddToRuleKey
  private final Tool yacc;
  @AddToRuleKey
  private final ImmutableList<String> flags;
  @AddToRuleKey(stringify = true)
  private final Path outputPrefix;
  @AddToRuleKey
  private final SourcePath input;

  public Yacc(
      BuildRuleParams params,
      SourcePathResolver resolver,
      Tool yacc,
      ImmutableList<String> flags,
      Path outputPrefix,
      SourcePath input) {
    super(params, resolver);
    this.yacc = yacc;
    this.flags = flags;
    this.outputPrefix = outputPrefix;
    this.input = input;
  }

  public static Path getHeaderOutputPath(Path outputPrefix) {
    return YaccStep.getHeaderOutputPath(outputPrefix);
  }

  public static Path getSourceOutputPath(Path outputPrefix) {
    return YaccStep.getSourceOutputPath(outputPrefix);
  }

  @Override
  public ImmutableList<Step> getBuildSteps(
      BuildContext context,
      BuildableContext buildableContext) {

    // Cache the output source and header.
    buildableContext.recordArtifact(YaccStep.getHeaderOutputPath(outputPrefix));
    buildableContext.recordArtifact(YaccStep.getSourceOutputPath(outputPrefix));

    return ImmutableList.of(
        new MkdirStep(outputPrefix.getParent()),
        new RmStep(getHeaderOutputPath(outputPrefix), /* shouldForceDeletion */ true),
        new RmStep(getSourceOutputPath(outputPrefix), /* shouldForceDeletion */ true),
        new YaccStep(
            yacc.getCommandPrefix(getResolver()),
            flags,
            outputPrefix,
            getResolver().getPath(input)));
  }

  @Nullable
  @Override
  public Path getPathToOutput() {
    return null;
  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>pyec.config — PyEC 0.2.1 documentation</title>

    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="top" title="PyEC 0.2.1 documentation" href="../../index.html" />
    <link rel="up" title="Module code" href="../index.html" />

Navigation

          index

          modules |

PyEC 0.2.1 documentation »

Module code »

Source code for pyec.config

from numpy import *
import copy

[docs]class Config(object):
   def __get__(self, key):
      if not self.__dict__.has_key(key):
         return None
      return self.__dict__[key]

   def __set__(self, key, val):
      self.__dict__[key] = val

[docs]   def encode(self, x):
      return x

[docs]class ConfigBuilder(object):
   def __init__(self, algcls):
      self.cfg = Config()
      self.cfg.stopAt = 1e300
      self.cfg.scale = 0.5
      self.cfg.center = 0.5
      self.cfg.recording = False
      self.cfg.bounded = True
      self.cfg.segment = 'test'
      self.cfg.activeField = 'point'
      self.cfg.binaryPartition = False
      self.cfg.topologize = False
      self.cfg.subpopulations = False
      self.cfg.layered = False
      self.cfg.varInit = None
      self.cfg.sort = True
      self.dimension = 5
      self.cfg.fitness = ""
      self.algcls = algcls

[docs]   def postConfigure(self,cfg):
      pass

[docs]   def configure(self, generations, populationSize, dimension=1, function=None):
      cfg = copy.copy(self.cfg)
      cfg.generations = generations
      cfg.populationSize = populationSize
      cfg.dim = dimension
      self.dimension = dimension
      if function: cfg.function = function
      self.postConfigure(cfg)
      return self.algcls(cfg)

Quick search

    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          modules |

PyEC 0.2.1 documentation »

Module code »

        © Copyright 2012, Alan J Lockett.
      Created using Sphinx 1.1.3.


text:
package ossadmin

import (
	. "aliyun-openapi-go-sdk/core"
	"strconv"
)

type GetImgVpcInfoRequest struct {
	RpcRequest
	OwnerId              int
	ResourceOwnerAccount string
	ResourceOwnerId      int
	OwnerAccount         string
	Region               string
	VpcId                string
	Label                string
}

func (r *GetImgVpcInfoRequest) SetOwnerId(value int) {
	r.OwnerId = value
	r.QueryParams.Set("OwnerId", strconv.Itoa(value))
}
func (r *GetImgVpcInfoRequest) GetOwnerId() int {
	return r.OwnerId
}
func (r *GetImgVpcInfoRequest) SetResourceOwnerAccount(value string) {
	r.ResourceOwnerAccount = value
	r.QueryParams.Set("ResourceOwnerAccount", value)
}
func (r *GetImgVpcInfoRequest) GetResourceOwnerAccount() string {
	return r.ResourceOwnerAccount
}
func (r *GetImgVpcInfoRequest) SetResourceOwnerId(value int) {
	r.ResourceOwnerId = value
	r.QueryParams.Set("ResourceOwnerId", strconv.Itoa(value))
}
func (r *GetImgVpcInfoRequest) GetResourceOwnerId() int {
	return r.ResourceOwnerId
}
func (r *GetImgVpcInfoRequest) SetOwnerAccount(value string) {
	r.OwnerAccount = value
	r.QueryParams.Set("OwnerAccount", value)
}
func (r *GetImgVpcInfoRequest) GetOwnerAccount() string {
	return r.OwnerAccount
}
func (r *GetImgVpcInfoRequest) SetRegion(value string) {
	r.Region = value
	r.QueryParams.Set("Region", value)
}
func (r *GetImgVpcInfoRequest) GetRegion() string {
	return r.Region
}
func (r *GetImgVpcInfoRequest) SetVpcId(value string) {
	r.VpcId = value
	r.QueryParams.Set("VpcId", value)
}
func (r *GetImgVpcInfoRequest) GetVpcId() string {
	return r.VpcId
}
func (r *GetImgVpcInfoRequest) SetLabel(value string) {
	r.Label = value
	r.QueryParams.Set("Label", value)
}
func (r *GetImgVpcInfoRequest) GetLabel() string {
	return r.Label
}

func (r *GetImgVpcInfoRequest) Init() {
	r.RpcRequest.Init()
	r.SetVersion(Version)
	r.SetAction("GetImgVpcInfo")
	r.SetProduct(Product)
}

type GetImgVpcInfoResponse struct {
	requestId string `xml:"requestId" json:"requestId"`
	vip       string `xml:"vip" json:"vip"`
	vpcId     string `xml:"vpcId" json:"vpcId"`
}

func GetImgVpcInfo(req *GetImgVpcInfoRequest, accessId, accessSecret string) (*GetImgVpcInfoResponse, error) {
	var pResponse GetImgVpcInfoResponse
	body, err := ApiHttpRequest(accessId, accessSecret, req)
	if err != nil {
		return nil, err
	}
	ApiUnmarshalResponse(req.GetFormat(), body, &pResponse)
	return &pResponse, err
}


text:
  Rebecques est
       un village
       localisé dans le département des Pas-de-Calais en Nord-Pas-de-Calais. Elle comptait 423 habitants en 2008.

Le parc de logements, à Rebecques, se décomposait en 2011 en zero appartements et 180 maisons soit
 un marché plutôt équilibré.

À proximité de Rebecques sont localisées les communes de
Heuringhem à 5 km, 1 311 habitants,
Blessy localisée à 3 km, 780 habitants,
Westrehem localisée à 5 km, 225 habitants,
Mametz localisée à 1 km, 1 875 habitants,
Enguinegatte localisée à 4 km, 374 habitants,
Estrée-Blanche localisée à 5 km, 911 habitants,
 entre autres. De plus, Rebecques est située à seulement 26 km de Béthune.

Si vous envisagez de emmenager à Rebecques, vous pourrez aisément trouver une maison à vendre.

La commune offre quelques  équipements, elle propose entre autres un terrain de sport.


text:
<?xml version="1.0" encoding="UTF-8"?>
<npc name="Alesar" script="Alesar.lua" walkinterval="2000" floorchange="0">
  <health now="100" max="100" />
  <look type="80" head="0" body="0" legs="0" feet="0" addons="0" />
  <parameters>
    <parameter key="message_greet" value="What do you want from me, |PLAYERNAME|?" />
	<parameter key="module_shop" value="1" /> <!-- added shop module to show the icon in npc (10:36 +) -->
		<parameter key="shop_sellable" value="0,0,0;"/>
		<parameter key="shop_buyable" value="0,0,0;"/>
  </parameters>
</npc>


text:
Laningndierlerystem.md
ARITHATIC.md
Laningndierlerystem.md
ARITHATIC.md


text:
module CloudFormer
  module Lambda
    class Version < Resource

      aws_property :code_sha256, type: String
      aws_property :description, type: String
      aws_property :function_name, type: String, required: true
    end
  end
end


text:
<ion-header>

  <ion-toolbar>
    <ion-title>Block Buttons</ion-title>
  </ion-toolbar>

</ion-header>

<ion-content padding style="text-align:center">

    a[ion-button][block]
    <button ion-button block>button[ion-button][block]</button>

    <ion-icon name="help-circle"></ion-icon> a[ion-button][block] icon
    <button ion-button block icon-left><ion-icon name="help-circle"></ion-icon> button[ion-button][block] icon</button>

    a[ion-button][block][outline][secondary]
    <button ion-button block outline color="secondary">button[ion-button][block][outline][secondary]</button>

    a[ion-button][block][clear][dark]
    <button ion-button block clear color="dark">button[ion-button][clear][block][dark]</button>

    a[ion-button][block][round]
    <button ion-button block round>button[ion-button][block][round]</button>

    a[ion-button][block][round][outline]
    <button ion-button block round outline>button[ion-button][block][round][outline]</button>

    <button ion-button [block]="blockButton" (click)="toggleBlock()">Toggle Block</button>

</ion-content>


text:
// Generated by xsd compiler for ios/objective-c
// DO NOT CHANGE!

#import <Foundation/Foundation.h>
#import "PicoClassSchema.h"
#import "PicoPropertySchema.h"
#import "PicoConstants.h"
#import "PicoBindable.h"
#import "Finding_BaseFindingServiceResponse.h"

@class Finding_CategoryHistogramContainer;
@class Finding_AspectHistogramContainer;
@class Finding_ConditionHistogramContainer;

/**

 Response container for the findItemsByImage call.

 @ingroup FindingServicePortType
*/
@interface Finding_FindItemsByImageResponse : Finding_BaseFindingServiceResponse {

@private
    Finding_CategoryHistogramContainer *_categoryHistogramContainer;
    Finding_AspectHistogramContainer *_aspectHistogramContainer;
    Finding_ConditionHistogramContainer *_conditionHistogramContainer;

}

/**

 Response container for category histograms. Only returned when one or
 more category histograms are returned. A category histogram is not
 returned if there are no matching items or if the search is
 restricted to a single leaf category.

 Note:
  The category IDs returned for items in search results are for the
  leaf categories in which the items are listed. If you use these
  category IDs as input, the response will not return a category
  histogram.

 Note:
  When searching the eBay Motors site, category histograms may not be
  available for some parent categories. In these cases, aspect
  histograms should be used to refine search results. This behavior is
  consistent with eBay Motors site search behavior.

 type : class Finding_CategoryHistogramContainer
*/
@property (nonatomic, retain) Finding_CategoryHistogramContainer *categoryHistogramContainer;

/**

 Response container for aspect histograms.

 type : class Finding_AspectHistogramContainer
*/
@property (nonatomic, retain) Finding_AspectHistogramContainer *aspectHistogramContainer;

/**

 Response container for condition histograms.
 These can be returned for any category (parent or leaf).

 Not returned when Condition is specified in itemFilter.
 That is, only returned when you have not yet narrowed
 your search based on specific conditions.

 Only returned when you search the eBay US site (as of
 February 2011). International items in US search results
 are included in the histogram counts.

 type : class Finding_ConditionHistogramContainer
*/
@property (nonatomic, retain) Finding_ConditionHistogramContainer *conditionHistogramContainer;

@end


text:
/**
 *
 */
package com.mathtabolism.util;

import javax.persistence.Embeddable;

import com.mathtabolism.util.nutrition.Calorie;
import com.mathtabolism.util.nutrition.Carbohydrate;
import com.mathtabolism.util.nutrition.Fat;
import com.mathtabolism.util.nutrition.Protein;

/**
 *
 * @author mlaursen
 */
@Embeddable
public class DailyIntakeTotal {

  private Calorie calories;
  private Fat fat;
  private Carbohydrate carbohydrates;
  private Protein protein;

  public DailyIntakeTotal() {
  }

  /**
   *
   * @return
   */
  public Calorie getCalories() {
    return calories;
  }

  /**
   *
   * @param calories
   */
  public void setCalories(Calorie calories) {
    this.calories = calories;
  }

  /**
   *
   * @return
   */
  public Fat getFat() {
    return fat;
  }

  /**
   *
   * @param fat
   */
  public void setFat(Fat fat) {
    this.fat = fat;
  }

  /**
   *
   * @return
   */
  public Carbohydrate getCarbohydrates() {
    return carbohydrates;
  }

  /**
   *
   * @param carbohydrates
   */
  public void setCarbohydrates(Carbohydrate carbohydrates) {
    this.carbohydrates = carbohydrates;
  }

  /**
   *
   * @return
   */
  public Protein getProtein() {
    return protein;
  }

  /**
   *
   * @param protein
   */
  public void setProtein(Protein protein) {
    this.protein = protein;
  }

}


text:
; variables for simple ASCII keyboard driver
; (c) 2018-2022 Carlos J. Santisteban
; last modified 20180825-1335

ak_get	.byt	0		; single-char buffer
ak_ddra	.byt	0		; old config
ak_rmod	.byt	0		; raw and coocked modifier combo
ak_cmod	.byt	0
ak_tof	.byt	0		; tabke offset from modifiers
ak_scod	.byt	0		; last scancode


text:
package eventize;

import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebDriver;
import com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.util.regex.Pattern;
import static org.apache.commons.lang3.StringUtils.join;

public class CreateEvents_JUnit_web {
	private Selenium selenium;

	@Before
	public void setUp() throws Exception {
		WebDriver driver = new FirefoxDriver();
		String baseUrl = "http://events-2016.appspot.com/";
		selenium = new WebDriverBackedSelenium(driver, baseUrl);
	}

	@Test
	public void testCreateEvents_JUnit_web() throws Exception {
		selenium.open("/");
		selenium.click("link=inputLogin using your gmail account");
		selenium.waitForPageToLoad("30000");
		selenium.type("id=Email", "harshithachidanand");
		selenium.click("id=next");
		selenium.type("id=Passwd", "");
		selenium.click("id=next");
		selenium.waitForPageToLoad("30000");
		selenium.type("id=eventName", "New events");
		selenium.type("id=eventTagline", "New is awesome");
		selenium.click("//table[@id='eventDate_table']/tbody/tr[3]/td[6]/div");
		selenium.click("css=button.btn-flat.picker__close");
		selenium.type("id=eventTime", "9:00AM");
		selenium.type("id=duration", "2 hours");
		selenium.click("css=input.select-dropdown.active");
		selenium.click("css=li.active > span");
		selenium.click("css=input.select-dropdown.active");
		selenium.click("css=#select-options-815bcc23-dabb-d8e7-0c54-cc604715e2d4 > li.active > span");
		selenium.click("css=input.select-dropdown.active");
		selenium.click("css=#select-options-091efa9b-6d5f-ef96-ae17-69722f5ba9b7 > li.active > span");
		selenium.click("css=input.select-dropdown.active");
		selenium.click("css=#select-options-7ed503fc-e8cb-c3b8-0752-c157b27088ea > li.active > span");
		selenium.type("id=capacity", "90");
		selenium.type("id=location", "HFH");
		selenium.type("id=description", "yep! come n see what new");
		selenium.type("id=createrName", "Harshitha");
		selenium.type("id=createrEmail", "har@gmail.com");
		selenium.click("name=action");
		selenium.waitForPageToLoad("30000");
		selenium.click("//ul[@id='nav-mobile']/li[3]/a");
		selenium.waitForPageToLoad("30000");
		selenium.click("link=call_madeSignout");
		selenium.waitForPageToLoad("30000");
	}

	@After
	public void tearDown() throws Exception {
		selenium.stop();
	}
}


text:
'use strict';

// Basic template description.
exports.description = 'Create a webapp structure based on ray-grunt-template.';

// Template-specific notes to be displayed before question prompts.
exports.notes = '';

// Template-specific notes to be displayed after question prompts.
exports.after = 'You should now install project dependencies with _npm ' +
  'install_. After that, you may execute project tasks with _grunt_. For ' +
  'more information about installing and configuring Grunt, please see ' +
  'the Getting Started guide:' +
  '\n\n' +
  'http://gruntjs.com/getting-started';

// Any existing file or directory matching this wildcard will cause a warning.
exports.warnOn = '*';

// The actual init template.
exports.template = function(grunt, init, done) {

  init.process({}, [
    // Prompt for these values.
    init.prompt('name'),
    init.prompt('description'),
    init.prompt('version'),
    init.prompt('licenses'),
    init.prompt('author_name'),
    init.prompt('author_email')
  ], function(err, props) {
    props.devDependencies = {
      "grunt": "~0.4.2",
      "grunt-browser-sync": "^2.0.0",
      "grunt-contrib-watch": "~0.5.3",
      "grunt-contrib-uglify": "~0.3.2",
      "grunt-contrib-cssmin": "~0.8.0",
      "grunt-contrib-jshint": "~0.8.0",
      "grunt-contrib-copy": "~0.7.0",
      "grunt-contrib-concat": "~0.5.0",
      "grunt-processhtml": "~0.3.3",
      "grunt-contrib-less": "~0.11.4",
      "grunt-contrib-clean": "~0.6.0",
      "grunt-contrib-imagemin" : "~0.9.2",
      "grunt-includes": "~0.4.5"
    };

    // Files to copy (and process).
    var files = init.filesToCopy(props);

    // Add properly-named license files.
    init.addLicenseFiles(files, props.licenses);

    // Actually copy (and process) files.
    init.copyAndProcess(files, props);

    // Generate package.json file.
    init.writePackageJSON('package.json', props);

    // All done!
    done();
  });

};


text:
"""
.. module: lemur.authorities.models
    :platform: unix
    :synopsis: This module contains all of the models need to create an authority within Lemur.
    :copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
    :license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, String, Text, func, ForeignKey, DateTime, PassiveDefault, Boolean
from sqlalchemy.dialects.postgresql import JSON

from lemur.database import db
from lemur.plugins.base import plugins
from lemur.models import roles_authorities

class Authority(db.Model):
    __tablename__ = 'authorities'
    id = Column(Integer, primary_key=True)
    owner = Column(String(128), nullable=False)
    name = Column(String(128), unique=True)
    body = Column(Text())
    chain = Column(Text())
    active = Column(Boolean, default=True)
    plugin_name = Column(String(64))
    description = Column(Text)
    options = Column(JSON)
    date_created = Column(DateTime, PassiveDefault(func.now()), nullable=False)
    roles = relationship('Role', secondary=roles_authorities, passive_deletes=True, backref=db.backref('authority'), lazy='dynamic')
    user_id = Column(Integer, ForeignKey('users.id'))
    authority_certificate = relationship("Certificate", backref='root_authority', uselist=False, foreign_keys='Certificate.root_authority_id')
    certificates = relationship("Certificate", backref='authority', foreign_keys='Certificate.authority_id')

    def __init__(self, **kwargs):
        self.owner = kwargs['owner']
        self.roles = kwargs.get('roles', [])
        self.name = kwargs.get('name')
        self.description = kwargs.get('description')
        self.authority_certificate = kwargs['authority_certificate']
        self.plugin_name = kwargs['plugin']['slug']

    @property
    def plugin(self):
        return plugins.get(self.plugin_name)

    def __repr__(self):
        return "Authority(name={name})".format(name=self.name)


text:
<?php

namespace Hifone\Handlers\Events\Notification;

use Carbon\Carbon;
use Hifone\Models\Notification;
use Hifone\Models\Reply;
use Hifone\Models\Thread;
use Hifone\Models\User;

abstract class AbstractNotificationHandler
{
    protected $notifiedUsers = [];

    protected function notify($type, User $fromUser, User $toUser, Thread $thread = null, Reply $reply = null)
    {
        $target_id = $thread ? $thread->id : 0;

        if ($this->isNotified($fromUser->id, $toUser->id, $target_id, $type)) {
            return;
        }

        $nowTimestamp = Carbon::now()->toDateTimeString();

        $data = [
            'from_user_id' => $fromUser->id,
            'user_id' => $toUser->id,
            'thread_id' => $target_id,
            'reply_id' => $reply ? $reply->id : 0,
            'body' => $reply ? $reply->body : '',
            'type' => $type,
            'created_at' => $nowTimestamp,
            'updated_at' => $nowTimestamp,
        ];

        $toUser->increment('notification_count', 1);

        Notification::insert([$data]);
    }

    /**
     * Create a notification.
     *
     * @param [type] $type     currently have 'at', 'new_reply', 'follow', 'append'
     * @param User $fromUser come from who
     * @param array $users to who, array of users
     * @param Thread $thread cuurent context
     * @param Reply $reply the content
     *
     * @return [type] none
     */
    protected function batchNotify($type, User $fromUser, $users, $thread_id, $reply_id = 0, $content = null)
    {
        $nowTimestamp = Carbon::now()->toDateTimeString();
        $data = [];

        foreach ($users as $toUser) {
            $data[] = [
                'from_user_id' => $fromUser->id,
                'user_id' => $toUser->id,
                'thread_id' => $thread_id,
                'reply_id' => $reply_id,
                'body' => $content,
                'type' => $type,
                'created_at' => $nowTimestamp,
                'updated_at' => $nowTimestamp,
            ];

            $toUser->increment('notification_count', 1);
        }

        if (count($data)) {
            Notification::insert($data);
        }
    }

    protected function isNotified($from_user_id, $user_id, $thread_id, $type)
    {
        return Notification::fromwhom($from_user_id)
            ->toWhom($user_id)
            ->atThread($thread_id)
            ->withType($type)->get()->count();
    }

    // in case of a user get a lot of the same notification
    protected function removeDuplication($users)
    {
        $notYetNotifyUsers = [];
        foreach ($users as $follow) {
            $user = (!$follow instanceof User) ? $follow->user : $follow;

            if (!in_array($user->id, $this->notifiedUsers)) {
                $notYetNotifyUsers[] = $user;
                $this->notifiedUsers[] = $user->id;
            }
        }

        return $notYetNotifyUsers;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;

namespace AutoTest.TestRunners.XUnit.Tests.TestResource
{
    public class Class2
    {
        [Fact]
        public void Anothger_passing_test()
        {
            Assert.Equal(1, 1);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Moody.DevelopmentBasics.GangOfFour.CreationalPatterns
{
    public class FactoryPattern
    {

        /*
        Description:
        Objects are not created by using the new() Method. Instead they are given back by subclasses of a ( abstract )
        factory method

        The Upper or abstract does not know which Objects are Created by its Factory Method. This allows simplier
        code-entensions, but also forces the implementation of subclasses

        The client has no responsibillity for creating the objects

        */

        public abstract class Food
        {
            public decimal Calories { get; set; }
        }

        public abstract class FoodFactory
        {
            public abstract T CreateFood<T>() where T : Food;
        }

        public class Burger : Food
        {

            public string Name { get; set; }

        }

        public class BurgerFactory : FoodFactory
        {
            public override T CreateFood<T>()
            {
                return Activator.CreateInstance<T>();
            }
        }

        public static void Starter()
        {
            var bFactory = new BurgerFactory();
            Burger burger = bFactory.CreateFood<Burger>();

        }

    }
}


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

package org.chromium.components.page_info;

import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.FragmentManager;

import org.chromium.components.browser_ui.site_settings.SingleWebsiteSettings;
import org.chromium.components.browser_ui.site_settings.SiteDataCleaner;
import org.chromium.components.browser_ui.site_settings.SiteSettingsCategory;
import org.chromium.components.browser_ui.site_settings.Website;
import org.chromium.components.browser_ui.site_settings.WebsiteAddress;
import org.chromium.components.browser_ui.site_settings.WebsitePermissionsFetcher;
import org.chromium.components.browser_ui.site_settings.WebsitePreferenceBridge;
import org.chromium.components.content_settings.CookieControlsBridge;
import org.chromium.components.content_settings.CookieControlsEnforcement;
import org.chromium.components.content_settings.CookieControlsObserver;
import org.chromium.components.embedder_support.util.Origin;

import java.util.Collection;

/**
 * Class for controlling the page info cookies section.
 */
public class PageInfoCookiesController
        implements PageInfoSubpageController, CookieControlsObserver {
    private final PageInfoMainController mMainController;
    private final PageInfoRowView mRowView;
    private final PageInfoControllerDelegate mDelegate;
    private final String mFullUrl;
    private final String mTitle;
    private CookieControlsBridge mBridge;
    private PageInfoCookiesPreference mSubPage;

    private int mAllowedCookies;
    private int mBlockedCookies;
    private int mStatus;
    private boolean mIsEnforced;
    private Website mWebsite;

    public PageInfoCookiesController(PageInfoMainController mainController, PageInfoRowView rowView,
            PageInfoControllerDelegate delegate) {
        mMainController = mainController;
        mRowView = rowView;
        mDelegate = delegate;
        mFullUrl = mainController.getURL().getSpec();
        mTitle = mRowView.getContext().getResources().getString(R.string.cookies_title);
        mBridge = mDelegate.createCookieControlsBridge(this);

        PageInfoRowView.ViewParams rowParams = new PageInfoRowView.ViewParams();
        rowParams.visible = delegate.isSiteSettingsAvailable();
        rowParams.title = mTitle;
        rowParams.iconResId = R.drawable.permission_cookie;
        rowParams.decreaseIconSize = true;
        rowParams.clickCallback = this::launchSubpage;
        mRowView.setParams(rowParams);
    }

    private void launchSubpage() {
        mMainController.recordAction(PageInfoAction.PAGE_INFO_COOKIES_DIALOG_OPENED);
        mMainController.launchSubpage(this);
    }

    @Override
    public String getSubpageTitle() {
        return mTitle;
    }

    @Override
    public View createViewForSubpage(ViewGroup parent) {
        assert mSubPage == null;

        FragmentManager fragmentManager = mDelegate.getFragmentManager();
        // If the activity is getting destroyed or saved, it is not allowed to modify fragments.
        if (fragmentManager.isStateSaved()) return null;

        mSubPage = new PageInfoCookiesPreference();
        mSubPage.setSiteSettingsDelegate(mDelegate.getSiteSettingsDelegate());
        fragmentManager.beginTransaction().add(mSubPage, null).commitNow();

        PageInfoCookiesPreference.PageInfoCookiesViewParams params =
                new PageInfoCookiesPreference.PageInfoCookiesViewParams();
        params.thirdPartyCookieBlockingEnabled = mDelegate.cookieControlsShown();
        params.onCheckedChangedCallback = this::onCheckedChangedCallback;
        params.onClearCallback = this::onClearCookiesClicked;
        params.onCookieSettingsLinkClicked = mDelegate::showCookieSettings;
        params.disableCookieDeletion = isDeletionDisabled();
        params.hostName = mMainController.getURL().getHost();
        mSubPage.setParams(params);
        mSubPage.setCookiesCount(mAllowedCookies, mBlockedCookies);
        mSubPage.setCookieBlockingStatus(mStatus, mIsEnforced);

        SiteSettingsCategory storageCategory = SiteSettingsCategory.createFromType(
                mMainController.getBrowserContext(), SiteSettingsCategory.Type.USE_STORAGE);
        new WebsitePermissionsFetcher(mMainController.getBrowserContext())
                .fetchPreferencesForCategory(storageCategory, this::onStorageFetched);

        return mSubPage.requireView();
    }

    private void onStorageFetched(Collection<Website> result) {
        String origin = Origin.createOrThrow(mFullUrl).toString();
        WebsiteAddress address = WebsiteAddress.create(origin);

        mWebsite = SingleWebsiteSettings.mergePermissionAndStorageInfoForTopLevelOrigin(
                address, result);
        if (mSubPage != null) {
            mSubPage.setStorageUsage(mWebsite.getTotalUsage());
        }
    }

    private void onCheckedChangedCallback(boolean state) {
        if (mBridge != null) {
            mMainController.recordAction(state ? PageInfoAction.PAGE_INFO_COOKIES_BLOCKED_FOR_SITE
                                               : PageInfoAction.PAGE_INFO_COOKIES_ALLOWED_FOR_SITE);
            mBridge.setThirdPartyCookieBlockingEnabledForSite(state);
        }
    }

    private void onClearCookiesClicked() {
        mMainController.recordAction(PageInfoAction.PAGE_INFO_COOKIES_CLEARED);
        clearData();
    }

    @Override
    public void clearData() {
        if (isDeletionDisabled()) return;
        if (mWebsite == null) return;

        new SiteDataCleaner().clearData(
                mMainController.getBrowserContext(), mWebsite, mMainController::exitSubpage);
    }

    @Override
    public void updateRowIfNeeded() {}

    @Override
    public void onSubpageRemoved() {
        assert mSubPage != null;
        FragmentManager fragmentManager = mDelegate.getFragmentManager();
        PageInfoCookiesPreference subPage = mSubPage;
        mSubPage = null;
        // If the activity is getting destroyed or saved, it is not allowed to modify fragments.
        if (fragmentManager == null || fragmentManager.isStateSaved()) return;
        fragmentManager.beginTransaction().remove(subPage).commitNow();
    }

    @Override
    public void onCookiesCountChanged(int allowedCookies, int blockedCookies) {
        mAllowedCookies = allowedCookies;
        mBlockedCookies = blockedCookies;
        String subtitle = blockedCookies > 0
                ? mRowView.getContext().getResources().getQuantityString(
                        R.plurals.cookie_controls_blocked_cookies, blockedCookies, blockedCookies)
                : null;

        mRowView.updateSubtitle(subtitle);

        if (mSubPage != null) {
            mSubPage.setCookiesCount(allowedCookies, blockedCookies);
        }
    }

    @Override
    public void onCookieBlockingStatusChanged(int status, int enforcement) {
        mStatus = status;
        mIsEnforced = enforcement != CookieControlsEnforcement.NO_ENFORCEMENT;
        if (mSubPage != null) {
            mSubPage.setCookieBlockingStatus(mStatus, mIsEnforced);
        }
    }

    private boolean isDeletionDisabled() {
        return WebsitePreferenceBridge.isCookieDeletionDisabled(mMainController.getBrowserContext(), mFullUrl);
    }

    void onUiClosing() {
        if (mBridge != null) {
            mBridge.onUiClosing();
        }
    }

    void destroy() {
        mBridge.destroy();
        mBridge = null;
    }
}


text:
var teamHelper = require('../helpers/teamHelper.js');

module.exports = function() {
  return new RosterResource();
};

function RosterResource() {
  return this;
};

RosterResource.prototype.players = function(teamKey, cb) {
  var self = this;

  this
    .api('http://fantasysports.yahooapis.com/fantasy/v2/team/' + teamKey + '/roster/players?format=json')
    .then(function(data) {
      var team = teamHelper.mapTeam(data.fantasy_content.team[0]);
      var roster = teamHelper.mapRoster(data.fantasy_content.team[1].roster);

      team.roster = roster;

      cb(null, team);
    }, function(e) {
      // self.err(e, cb);
      cb(e, null);
    });
};

// todo: need to add date, week
// https://developer.yahoo.com/fantasysports/guide/roster-resource.html#roster-resource-desc


text: Web interface: http://connectionscience.github.io/hangout-collaboration-scoring/


text:
package com.dangdang.ddframe.job.lite.console.service.impl;

import com.dangdang.ddframe.job.lite.console.domain.GlobalConfiguration;
import com.dangdang.ddframe.job.lite.console.domain.RegistryCenterConfiguration;
import com.dangdang.ddframe.job.lite.console.domain.RegistryCenterConfigurations;
import com.dangdang.ddframe.job.lite.console.repository.ConfigurationsXmlRepository;
import com.dangdang.ddframe.job.lite.console.repository.impl.ConfigurationsXmlRepositoryImpl;
import com.dangdang.ddframe.job.lite.console.service.RegistryCenterConfigurationService;
import com.google.common.base.Optional;

/**
 * 注册中心配置服务实现类.
 *
 * @author zhangliang
 */
public final class RegistryCenterConfigurationServiceImpl implements RegistryCenterConfigurationService {

    private ConfigurationsXmlRepository configurationsXmlRepository = new ConfigurationsXmlRepositoryImpl();

    @Override
    public RegistryCenterConfigurations loadAll() {
        return loadGlobal().getRegistryCenterConfigurations();
    }

    @Override
    public RegistryCenterConfiguration load(final String name) {
        GlobalConfiguration configs = loadGlobal();
        RegistryCenterConfiguration result = find(name, configs.getRegistryCenterConfigurations());
        setActivated(configs, result);
        return result;
    }

    @Override
    public RegistryCenterConfiguration find(final String name, final RegistryCenterConfigurations configs) {
        for (RegistryCenterConfiguration each : configs.getRegistryCenterConfiguration()) {
            if (name.equals(each.getName())) {
                return each;
            }
        }
        return null;
    }

    private void setActivated(final GlobalConfiguration configs, final RegistryCenterConfiguration toBeConnectedConfig) {
        RegistryCenterConfiguration activatedConfig = findActivatedRegistryCenterConfiguration(configs);
        if (!toBeConnectedConfig.equals(activatedConfig)) {
            if (null != activatedConfig) {
                activatedConfig.setActivated(false);
            }
            toBeConnectedConfig.setActivated(true);
            configurationsXmlRepository.save(configs);
        }
    }

    @Override
    public Optional<RegistryCenterConfiguration> loadActivated() {
        return Optional.fromNullable(findActivatedRegistryCenterConfiguration(loadGlobal()));
    }

    private RegistryCenterConfiguration findActivatedRegistryCenterConfiguration(final GlobalConfiguration configs) {
        for (RegistryCenterConfiguration each : configs.getRegistryCenterConfigurations().getRegistryCenterConfiguration()) {
            if (each.isActivated()) {
                return each;
            }
        }
        return null;
    }

    @Override
    public boolean add(final RegistryCenterConfiguration config) {
        GlobalConfiguration configs = loadGlobal();
        boolean result = configs.getRegistryCenterConfigurations().getRegistryCenterConfiguration().add(config);
        if (result) {
            configurationsXmlRepository.save(configs);
        }
        return result;
    }

    @Override
    public void delete(final String name) {
        GlobalConfiguration configs = loadGlobal();
        RegistryCenterConfiguration toBeRemovedConfig = find(name, configs.getRegistryCenterConfigurations());
        if (null != toBeRemovedConfig) {
            configs.getRegistryCenterConfigurations().getRegistryCenterConfiguration().remove(toBeRemovedConfig);
            configurationsXmlRepository.save(configs);
        }
    }

    private GlobalConfiguration loadGlobal() {
        GlobalConfiguration result = configurationsXmlRepository.load();
        if (null == result.getRegistryCenterConfigurations()) {
            result.setRegistryCenterConfigurations(new RegistryCenterConfigurations());
        }
        return result;
    }
}


text:
import { RedBlackTreeStructure, isNone } from '../internals';

/**
 * Determines whether or not a given key exists in the tree
 *
 * @export
 * @template K The type of keys in the tree
 * @template V The type of values in the tree
 * @param {K} key The key to look for
 * @param {RedBlackTreeStructure<K, V>} tree The input tree
 * @returns {boolean} True if the there is an entry for the specified key, otherwise false
 */
export function has<K, V = null> (key: K, tree: RedBlackTreeStructure<K, V>): boolean {
  var node = tree._root,
      compare = tree._compare,
      done = false,
      found = false;
  do {
    if(isNone(node)) {
      done = true;
    }
    else {
      var c = compare(key, node.key);
      if(c === 0) {
        done = true;
        found = true;
      }
      else if(c > 0) {
        node = node._right;
      }
      else {
        node = node._left;
      }
    }
  } while(!done);
  return found;
}


text:
package se.lth.cs.palcom.updaterservice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import ist.palcom.resource.descriptor.Command;
import ist.palcom.resource.descriptor.DeviceID;
import ist.palcom.resource.descriptor.Group;
import ist.palcom.resource.descriptor.PRDService;
import ist.palcom.resource.descriptor.ServiceID;
import se.lth.cs.palcom.common.NoSuchDeviceException;
import se.lth.cs.palcom.common.PalComVersion;
import se.lth.cs.palcom.common.TreeUpdateException;
import se.lth.cs.palcom.communication.connection.Connection;
import se.lth.cs.palcom.communication.connection.Readable;
import se.lth.cs.palcom.communication.connection.Writable;
import se.lth.cs.palcom.device.AbstractDevice;
import se.lth.cs.palcom.device.DeviceProperties;
import se.lth.cs.palcom.discovery.ResourceException;
import se.lth.cs.palcom.discovery.proxy.PalcomDevice;
import se.lth.cs.palcom.discovery.proxy.PalcomService;
import se.lth.cs.palcom.discovery.proxy.PalcomServiceList;
import se.lth.cs.palcom.filesystem.HostFileSystems;
import se.lth.cs.palcom.logging.Logger;
import se.lth.cs.palcom.palcomstarter.PalComStarter;
import se.lth.cs.palcom.service.AbstractSimpleService;
import se.lth.cs.palcom.service.ServiceTools;
import se.lth.cs.palcom.service.command.CommandServiceProtocol;
import se.lth.cs.palcom.service.distribution.UnicastDistribution;
import se.lth.cs.palcom.updatedistributionservice.UpdateDistributionService;

/**
 * Service that can either act by monitoring or by being monitored. When monitoring, can also update all its monitored
 * devices by communicating with and getting updates from an {@link UpdateDistributionService}.
 * @author Christian Hernvall
 *
 */
public class UpdaterService extends AbstractSimpleService {

	public static final DeviceID CREATOR = new DeviceID("X:mojo");
	public static final ServiceID SERVICE_VERSION = new ServiceID(CREATOR, "UP1.0.0", CREATOR, "UP1.0.0");
	public static final String SERVICE_NAME = "UpdaterService";

	public static final String COMMAND_IN_UPDATE_DEVICE_TYPES = "update single device type";
	static final String COMMAND_IN_STOP_MONITORED_DEVICES = "stop all monitored devices";
	public static final String COMMAND_IN_UPDATE_DATA = "updateData";
	public static final String COMMAND_IN_CHECK_UPDATE_SERVER_CONFIRM = "I hear you!";
	static final String COMMAND_IN_ABORT_UPDATE = "abort update!";
	static final String COMMAND_IN_KILL = "kill";
	static final String COMMAND_IN_INITIATE_STAGE_TWO = "initiate updating stage two";

	static final String COMMAND_IN_DISABLE_MONITORING = "disable monitor";
	static final String COMMAND_IN_ENABLE_MONITORING = "enable monitor";
	static final String COMMAND_IN_LIST_MONITORED_DEVICES = "list all monitored devices";
	static final String COMMAND_IN_KILL_DEVICE_BY_INDEX = "kill device by index";
	static final String COMMAND_IN_START_DEVICE_BY_INDEX = "start device by index";
	static final String COMMAND_IN_RESTART_DEVICE_BY_INDEX = "restart device by index";
	static final String COMMAND_IN_RESET_UPDATE_ABORTED_COUNTER = "reset update aborted counter";

	public static final String COMMAND_OUT_UPDATE_CONTENT_REQUEST = "gief the jar!";
	public static final String COMMAND_OUT_CHECK_UPDATE_SERVER = "do you hear me?";
	static final String COMMAND_OUT_KILL = COMMAND_IN_KILL;
	public static final String COMMAND_OUT_CHECK_LATEST_VERSION = "latest version?";
	static final String COMMAND_OUT_LIST_MONITORED_DEVICES = "list of all monitored devices";
	public static final String COMMAND_OUT_BENCHMARK_END = "benchmark end";
	static final String COMMAND_OUT_INITIATE_STAGE_TWO = COMMAND_IN_INITIATE_STAGE_TWO;

	public static final String PARAM_VALUE_SEPARATOR = ",,,";
	public static final String PARAM_NO_ENTRY = "no entry";
	public static final String PARAM_IMPLEMENTATION = "implementation";
	public static final String PARAM_VERSION = "version";
	public static final String PARAM_DEVICE_TYPE = "device type";
	public static final String PARAM_UPDATE_CONTENT = "jar content";
	static final String PARAM_SERVICEINSTANCEID = "serviceInstanceID";
	static final String PARAM_MONITORED_DEVICES = "monitored devices";
	static final String PARAM_MONITORED_DEVICE_INDEX = "monitored device index";

	static final String NAMESPACE_UPDATERSERVICE_MONITORED_DEVICE_NAMES = "monitoredDeviceNames";
	static final String NAMESPACE_MONITORED_DEVICE = "monitoredDevice-";
	static final String NAMESPACE_UPDATERSERVICE_DEVICE_TYPE_VERSION = "deviceTypeVersion";
	static final String NAMESPACE_UPDATERSERVICE_GENERAL = "general";

	static final String KEY_MONITORED_DEVICE_ID = "ID";
	static final String KEY_MONITORED_DEVICE_TYPE = "type";
	static final String KEY_UPDATE_SERVER_DEVICE_ID = "updateServerDeviceID";
	static final String KEY_UPDATE_ABORTED = "updateAborted";

	private static final String PROPERTY_MONITORED_DEVICE_ENABLED = "enabled";

	static final String UPDATE_PROTOCOL_KILL = "kill";
	static final String UPDATE_PROTOCOL_KILL_ACK = "kill ack";
	static final String UPDATE_PROTOCOL_ABORT = "abort!";
	static final String UPDATE_PROTOCOL_CHECK_SOCKET = "socket working?";
	static final String UPDATE_PROTOCOL_CHECK_SOCKET_CONFIRM = "socket working!";
	static final String UPDATE_PROTOCOL_CHECK_UPDATE_SERVER = "update server hear you?";
	static final String UPDATE_PROTOCOL_CHECK_UPDATE_SERVER_CONFIRM = "update server hear me!";
	static final String UPDATE_PROTOCOL_FINISH_DEVICE_STARTUP_CHECK = "finish device startup check";
	static final String UPDATE_PROTOCOL_FINISH_DEVICE_STARTUP_CHECK_ACK = "finish device startup check ACK";
	static final String UPDATE_PROTOCOL_STAGE_TWO = "update stage two";
	static final String UPDATE_PROTOCOL_FINISH_STAGE_TWO = "finish stage two";
	static final String UPDATE_PROTOCOL_FINISH_STAGE_TWO_ACK = "finish stage two ACK";

	static final String MSG_SHUT_DOWN_THREAD = "shut down thread";

	static final String PALCOMSTARTER_DEVICE_TYPE = "PalComStarter";

	static final int UPDATE_ABORTED_DELAY_SECONDS = 30;
	static final int UPDATE_ABORTED_MANY_TIMES = 3;
	static final int UPDATE_ABORTED_MANY_TIMES_DELAY_SECONDS = 24*60*60;
	static final int PALCOMSTARTER_SOCKET_PORT = 13370;
	static final int MONITORED_DEVICE_SOCKET_PORT = 13371;

	enum UpdateState {
		NONE, UPDATING_INITIAL, UPDATING_WAITING_FOR_JAR, UPDATING_KILLING_CURRENT, UPDATING_STARTING_NEW, UPDATING_FALLBACK_TIMER_CHECK_SOCKET, UPDATING_STAGE_TWO, STARTUP, UPDATING_FALLBACK_TIMER_CHECK_UPDATE_SERVER, UPDATING_SENDING_JAR, UPDATING_DONT_DISTURB, UPDATING_STAGE_THREE,
	}

	private UpdateState updateState = UpdateState.NONE;

	private MonitoringThread monitor;
	private LinkedBlockingQueue<Command> commandBuffer;
	private SocketListenerThread socketListener;
	private SocketSender socketSender;
	private UpdateServerConnectionListener updateServerConnectionListener;
	private boolean isMonitor = false;
	private boolean continueUpdateStageThree = false;
	String updateServerDeviceID;
	DeviceProperties monitoringProperties;
	Integer updateAborted = 0;
	Long updateAbortedDelay = 0L;

	public UpdaterService(AbstractDevice container) {
		this(container, ServiceTools.getNextInstance(SERVICE_VERSION));
	}

	public UpdaterService(AbstractDevice container, boolean continueUpdateStageThree) {
		super(container, SERVICE_VERSION, "P1", "v0.0.1", "UpdaterService",
				ServiceTools.getNextInstance(SERVICE_VERSION), "Updates PalCom devices",
				new UnicastDistribution(true));
		this.continueUpdateStageThree = continueUpdateStageThree;
		log("Continue updating stage three: " + continueUpdateStageThree, Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
		configureService();
	}

	public UpdaterService(AbstractDevice container, String instance) {
		super(container, SERVICE_VERSION, "P1", "v0.0.1", "UpdaterService",
				instance, "Updates PalCom devices",
				new UnicastDistribution(true));
		configureService();
	}

	private void configureService() {
		if (container instanceof PalComStarter)
			isMonitor = true;
		if (isMonitor) {
			try {
				monitoringProperties = new DeviceProperties(new DeviceID("monitoring"), HostFileSystems.getGlobalRoot(), null, "Monitoring properties. Generated " + new Date());
				String[] monitoredDeviceNames = monitoringProperties.getKeys(NAMESPACE_UPDATERSERVICE_MONITORED_DEVICE_NAMES);
				socketListener = new SocketListenerThread(this, PALCOMSTARTER_SOCKET_PORT);
				socketSender = new SocketSender(this, MONITORED_DEVICE_SOCKET_PORT);
				monitor = new MonitoringThread(this, socketListener, socketSender);
				for (String deviceName: monitoredDeviceNames) {
					if (!monitoringProperties.getProperty(NAMESPACE_UPDATERSERVICE_MONITORED_DEVICE_NAMES, deviceName).equals(PROPERTY_MONITORED_DEVICE_ENABLED)){
						continue;
					}
					String deviceSpecificNamespace = NAMESPACE_MONITORED_DEVICE + deviceName;
					String monitoredDeviceID = monitoringProperties.getProperty(deviceSpecificNamespace, KEY_MONITORED_DEVICE_ID);
					String monitoredDeviceType = monitoringProperties.getProperty(deviceSpecificNamespace, KEY_MONITORED_DEVICE_TYPE);
					if (monitoredDeviceType == null) {
						log("ERROR: Device type is not specified in the configuration: " + deviceSpecificNamespace + "@" + KEY_MONITORED_DEVICE_TYPE, Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
						log("Will not monitor device with name: " + deviceName, Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
						continue;
					}
					String monitoredDeviceVersion = monitoringProperties.getProperty(NAMESPACE_UPDATERSERVICE_DEVICE_TYPE_VERSION, monitoredDeviceType);
					if (monitoredDeviceVersion == null) {
						log("ERROR: Device version is not specified in the configuration: " + deviceSpecificNamespace + "@" + KEY_MONITORED_DEVICE_TYPE, Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
						log("Will not monitor device with name: " + deviceName, Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
						continue;
					}
					if (monitoredDeviceID == null) {
						// The device is lacking its device ID which means that it is not installed yet.
						/**TODO Generate a new device if it is missing its device ID.
						 * This should probably be done using another thread or another service
						 * because it includes downloading an executable and a configuration for
						 * the new device, followed by the installation.
						 */
						log("ERROR: Device ID is not specified in the configuration: " + deviceSpecificNamespace + "@" + KEY_MONITORED_DEVICE_TYPE, Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
						log("Will not monitor device with name: " + deviceName, Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
						continue;
					}
					monitor.addNewMonitoredDevice(monitoredDeviceID, deviceName, monitoredDeviceType, monitoredDeviceVersion);
				}
				updateServerDeviceID = monitoringProperties.getProperty(NAMESPACE_UPDATERSERVICE_GENERAL, KEY_UPDATE_SERVER_DEVICE_ID);
				if (updateServerDeviceID == null) {
					log("UpdateServer device ID is not set in configuration: " + NAMESPACE_UPDATERSERVICE_GENERAL + "@" + KEY_UPDATE_SERVER_DEVICE_ID, Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
					log("Will not be able to communicate with or receive updates from Update Server.", Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
				}
				updateServerConnectionListener = new UpdateServerConnectionListener(this, monitor);
			} catch (IOException e) {
				log("Could not access monitoring.properties. UpdateServer and monitored devices unknown. Reason: ", Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
				e.printStackTrace();
			}
		} else { // This means that this service is running on a monitored device, not a PalComStarter. Reverse the ports.
			socketListener = new SocketListenerThread(this, MONITORED_DEVICE_SOCKET_PORT);
			socketSender = new SocketSender(this, PALCOMSTARTER_SOCKET_PORT);
		}

		commandBuffer = new LinkedBlockingQueue<Command>();

		CommandServiceProtocol sp = getProtocolHandler();

		// General UpdaterService commands
		Command killInCmd = new Command(COMMAND_IN_KILL, "Kill device", Command.DIRECTION_IN);

		Command checkUpdateServerCmd = new Command(COMMAND_OUT_CHECK_UPDATE_SERVER, "Ping update server to test connection", Command.DIRECTION_OUT);
		sp.addCommand(checkUpdateServerCmd);

		Command checkUpdateServerConfirmCmd = new Command(COMMAND_IN_CHECK_UPDATE_SERVER_CONFIRM, "Confirm the \"do you hear me?\" request", Command.DIRECTION_IN);

		Command abortUpdateCmd = new Command(COMMAND_IN_ABORT_UPDATE, "Abort update", Command.DIRECTION_IN);

		Group automaticCmdGroup = new Group("automaticGroup", "Automatic commands that is used during the update process. Do not touch unless you need to do something manually!");

		// Monitor specific commands
		if(isMonitor) {
			Command updateCmd = new Command(COMMAND_IN_UPDATE_DEVICE_TYPES, "Starts update procedure.", Command.DIRECTION_IN);
			updateCmd.addParam(PARAM_DEVICE_TYPE, "text/plain");
			updateCmd.addParam(PARAM_VERSION, "text/plain");

			Command killAllMonitoredDevicesCmd = new Command(COMMAND_IN_STOP_MONITORED_DEVICES, "Kill the monitored devices.", Command.DIRECTION_IN);

			Command updateDataCmd = new Command(COMMAND_IN_UPDATE_DATA, "Update data for the updating process", Command.DIRECTION_IN);
			updateDataCmd.addParam(PARAM_VERSION, "text/plain");
			updateDataCmd.addParam(PARAM_UPDATE_CONTENT, "application/x-jar");

			Command killOutCmd = new Command(COMMAND_OUT_KILL, "kill", Command.DIRECTION_OUT);
			sp.addCommand(killOutCmd);

			Command updateContentRequestCmd = new Command(COMMAND_OUT_UPDATE_CONTENT_REQUEST, "Request update content from update server.", Command.DIRECTION_OUT);
			updateContentRequestCmd.addParam(PARAM_DEVICE_TYPE, "text/plain");
			updateContentRequestCmd.addParam(PARAM_VERSION, "text/plain");
			sp.addCommand(updateContentRequestCmd);

			Command checkLatestVersionCmd = new Command(COMMAND_OUT_CHECK_LATEST_VERSION, "Request latest version info from Update Server.", Command.DIRECTION_OUT);
			checkLatestVersionCmd.addParam(PARAM_DEVICE_TYPE, "text/plain");
			sp.addCommand(checkLatestVersionCmd);

			Command initiateStageTwoCmdOut = new Command(COMMAND_OUT_INITIATE_STAGE_TWO, "Initiates updating stage two.", Command.DIRECTION_OUT);
			sp.addCommand(initiateStageTwoCmdOut);

			Command disableMonitoringCmd = new Command(COMMAND_IN_DISABLE_MONITORING, "Disable monitoring of devices.", Command.DIRECTION_IN);

			Command enableMonitoringCmd = new Command(COMMAND_IN_ENABLE_MONITORING, "Enable monitoring of devices.", Command.DIRECTION_IN);

			Command listMonitoredDevicesCmd = new Command(COMMAND_IN_LIST_MONITORED_DEVICES, "Lists all monitored devices.", Command.DIRECTION_IN);

			Command listMonitoredDevicesReplyCmd = new Command(COMMAND_OUT_LIST_MONITORED_DEVICES, "Reply with all monitored devices.", Command.DIRECTION_OUT);
			listMonitoredDevicesReplyCmd.addParam(PARAM_MONITORED_DEVICES, "text/plain");
			sp.addCommand(listMonitoredDevicesReplyCmd);

			Command killSingleDeviceCmd = new Command(COMMAND_IN_KILL_DEVICE_BY_INDEX, "Stop a single device by identified by index.", Command.DIRECTION_IN);
			killSingleDeviceCmd.addParam(PARAM_MONITORED_DEVICE_INDEX, "text/plain");

			Command startSingleDeviceCmd = new Command(COMMAND_IN_START_DEVICE_BY_INDEX, "Start a single device by identified by index.", Command.DIRECTION_IN);
			startSingleDeviceCmd.addParam(PARAM_MONITORED_DEVICE_INDEX, "text/plain");

			Command restartSingleDeviceCmd = new Command(COMMAND_IN_RESTART_DEVICE_BY_INDEX, "Restart a single device by identified by index.", Command.DIRECTION_IN);
			restartSingleDeviceCmd.addParam(PARAM_MONITORED_DEVICE_INDEX, "text/plain");

			Command resetUpdateAbortedCounterCmd = new Command(COMMAND_IN_RESET_UPDATE_ABORTED_COUNTER, "Resets the update aborted counter, so that we can try to update again.", Command.DIRECTION_IN);

			Group managementCmdGroup = new Group("managementGroup", "Manual management commands.");
			managementCmdGroup.addCommand(enableMonitoringCmd);
			managementCmdGroup.addCommand(disableMonitoringCmd);
			managementCmdGroup.addCommand(killAllMonitoredDevicesCmd);
			managementCmdGroup.addCommand(listMonitoredDevicesCmd);
			managementCmdGroup.addCommand(killSingleDeviceCmd);
			managementCmdGroup.addCommand(startSingleDeviceCmd);
			managementCmdGroup.addCommand(restartSingleDeviceCmd);
			managementCmdGroup.addCommand(resetUpdateAbortedCounterCmd);
			sp.addGroup(managementCmdGroup);

			automaticCmdGroup.addCommand(updateCmd);
			automaticCmdGroup.addCommand(updateDataCmd);

			Command benchmarkEndCmd = new Command(COMMAND_OUT_BENCHMARK_END, "benchmark end", Command.DIRECTION_OUT);
			sp.addCommand(benchmarkEndCmd);
		} else {
			// Monitored device specific commands
			Command initiateStageTwoCmdIn = new Command(COMMAND_IN_INITIATE_STAGE_TWO, "Initiates updating stage two.", Command.DIRECTION_IN);
			automaticCmdGroup.addCommand(initiateStageTwoCmdIn);
		}
		automaticCmdGroup.addCommand(abortUpdateCmd);
		automaticCmdGroup.addCommand(killInCmd);
		automaticCmdGroup.addCommand(checkUpdateServerConfirmCmd);
		sp.addGroup(automaticCmdGroup);
	}

	public void start() {
		socketListener.start();
		if (isMonitor) {
			log("UpdaterService is running as a monitoring device / PalComStarter.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
			new PalComStarterStartThread().start();
		} else {
			log("UpdaterService is running as a monitored device.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
			new MonitoredDeviceStartThread().start();
		}
	}

	void stopDevice() {
		log("Stopping device.", Logger.CMP_SERVICE, Logger.LEVEL_INFO);
		stopUpdaterService();
		System.exit(0);
	}

	private void stopUpdaterService() {
		stop();
	}

	private void stopHelperThreads() {
		socketListener.stopThread();
		try {
			socketListener.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if(isMonitor) {
			monitor.stopThread();
			try {
				monitor.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void stop() {
		stopHelperThreads();
		super.stop();
	}

	public void setAsFullyOperational() {
		setStatus(PRDService.FULLY_OPERATIONAL);
		super.start();
	}

	protected void connectionOpened(Connection conn) {
	}

	protected void connectionClosed(Connection conn) {
	}

	public static String toUTF8String(byte[] data) {
		try {
			return new String(data, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.err.println("UTF-8 must be supported!");
			System.exit(0);
		}
		return null;
	}

	protected void invoked(Readable conn, Command command) {
		if (conn instanceof Writable) {
			if (command.getID().equals(COMMAND_IN_KILL)) {
				stopDevice();
			}
			if (command.getID().equals(COMMAND_IN_ABORT_UPDATE)) {
				addCommandToBuffer(command);
				return;
			}
			switch (updateState) {
			case STARTUP:
				if (command.getID().equals(COMMAND_IN_CHECK_UPDATE_SERVER_CONFIRM)) {
					addCommandToBuffer(command);
				}
				break;
			case NONE:
				if (isMonitor) {
					if (command.getID().equals(COMMAND_IN_UPDATE_DEVICE_TYPES)) {
						updateState = UpdateState.UPDATING_INITIAL;
						// We are now in the updating state. Commands that could interrupt the procedure are ignored
						log("Got new update from UpdateServer", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
						String deviceTypes = toUTF8String(command.findParam(PARAM_DEVICE_TYPE).getData());
						String newVersions = toUTF8String(command.findParam(PARAM_VERSION).getData());
						if (deviceTypes == null) {
							log("Device types is null. Will not update.", Logger.CMP_SERVICE, Logger.LEVEL_ERROR);
						} else if (newVersions == null) {
							log("Versions is null. Will not update.", Logger.CMP_SERVICE, Logger.LEVEL_ERROR);
						} else {
							String[] splitDeviceTypes = deviceTypes.split(PARAM_VALUE_SEPARATOR);
							String[] splitNewVersions = newVersions.split(PARAM_VALUE_SEPARATOR);
							if (splitDeviceTypes.length < 1) {
								log("There are no device types. Will not update.", Logger.CMP_SERVICE, Logger.LEVEL_ERROR);
							} else if (splitNewVersions.length < 1) {
								log("There are no versions. Will not update.", Logger.CMP_SERVICE, Logger.LEVEL_ERROR);
							} else {
								new UpdateStageOneThread(this, monitor, socketListener, socketSender, (Writable) conn, splitDeviceTypes, splitNewVersions).start();
							}
						}
					} else if (command.getID().equals(COMMAND_IN_STOP_MONITORED_DEVICES)) {
						monitor.killAllMonitoredDevices(true);
					} else if (command.getID().equals(COMMAND_IN_DISABLE_MONITORING)) {
						monitor.disable();
					} else if (command.getID().equals(COMMAND_IN_ENABLE_MONITORING)) {
						monitor.enable();
					} else if (command.getID().equals(COMMAND_IN_LIST_MONITORED_DEVICES)) {
						Command reply = getProtocolHandler().findCommand(COMMAND_OUT_LIST_MONITORED_DEVICES);
						String listOfMonitoredDevices = monitor.getListOfMonitoredDevices();
						reply.findParam(PARAM_MONITORED_DEVICES).setData(listOfMonitoredDevices.getBytes());
						sendTo((Writable) conn, reply);
					} else if (command.getID().equals(COMMAND_IN_KILL_DEVICE_BY_INDEX)) {
						int index = Integer.valueOf(toUTF8String(command.findParam(PARAM_MONITORED_DEVICE_INDEX).getData()));
						monitor.killMonitoredDeviceByIndex(index, true);
					} else if (command.getID().equals(COMMAND_IN_START_DEVICE_BY_INDEX)) {
						int index = Integer.valueOf(toUTF8String(command.findParam(PARAM_MONITORED_DEVICE_INDEX).getData()));
						monitor.startMonitoredDeviceByIndex(index);
					} else if (command.getID().equals(COMMAND_IN_RESTART_DEVICE_BY_INDEX)) {
						int index = Integer.valueOf(toUTF8String(command.findParam(PARAM_MONITORED_DEVICE_INDEX).getData()));
						monitor.restartMonitoredDeviceByIndex(index);
					} else if (command.getID().equals(COMMAND_IN_RESET_UPDATE_ABORTED_COUNTER)) {
						updateAborted = 0;
						monitoringProperties.getProperty(NAMESPACE_UPDATERSERVICE_GENERAL, KEY_UPDATE_ABORTED);
						log("\"Update Aborted\"-counter reset.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
					} else {
						log("Received unknown command: " + command.getID(), Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
					}
				} else { // is not monitor
					if (command.getID().equals(COMMAND_IN_INITIATE_STAGE_TWO)) {
						updateState = UpdateState.UPDATING_STAGE_TWO;
						socketListener.reopenSocket();
						new UpdateStageTwoThread(this, socketListener, socketSender).start();
					} else {
						log("Received unknown command: " + command.getID(), Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
					}
				}
				break;
			case UPDATING_WAITING_FOR_JAR:
				if (command.getID().equals(COMMAND_IN_UPDATE_DATA)) {
					addCommandToBuffer(command);
				}
				break;
			case UPDATING_STAGE_TWO:
				if (command.getID().equals(COMMAND_IN_CHECK_UPDATE_SERVER_CONFIRM)) {
					addCommandToBuffer(command);
				}
				break;
			case UPDATING_STAGE_THREE:
				if (command.getID().equals(COMMAND_IN_CHECK_UPDATE_SERVER_CONFIRM)) {
					addCommandToBuffer(command);
				}
				break;
			case UPDATING_DONT_DISTURB:
				// dont get any message
				break;
			default:
				Logger.log("We got a command (" + command.getID() + ") in an unknown state (" + updateState + ").", Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
				break;
			}
		}
	}

	private void addCommandToBuffer(Command command) {
		try {
			commandBuffer.put(command);
		} catch (InterruptedException e) {
			Logger.log("Could not add command (" + command.getID() + ") to commandBuffer.", Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
		}
	}

	Command getCommandFromBuffer(String cmdID) {
		Command cmd;
		while(true) {
			try {
				cmd = commandBuffer.take();
				if (cmd.getID().equals(cmdID)) {
					return cmd;
				}
			} catch (InterruptedException e) {
				Logger.log("Could not take command (" + cmdID + ") from commandBuffer.", Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
			}
		}
	}

	Command getCommandFromBuffer(String cmdID, int maxWaitInSeconds) {
		Command cmd = null;
		long stopTimeMillis = System.currentTimeMillis() + maxWaitInSeconds*1000;
		while(true) {
			try {
				long currentTimeMillis = System.currentTimeMillis();
				if (stopTimeMillis < currentTimeMillis) {
					return cmd;
				}
				cmd = commandBuffer.poll(stopTimeMillis - currentTimeMillis, TimeUnit.MILLISECONDS);
				if (cmd == null) {
					return cmd;
				}
				if (cmd.getID().equals(cmdID)) {
					return cmd;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	boolean saveJar(byte[] content, String jarPath) {
		File jarFile = new File(jarPath);
		if (jarFile.exists()) {
			jarFile.delete();
		}
		try {
			jarFile.createNewFile();
			FileOutputStream os = new FileOutputStream(jarFile);
			os.write(content);
			os.flush();
			os.close();
		} catch (IOException e) {
			log("Could not save jar: " + jarPath, Logger.CMP_SERVICE, Logger.LEVEL_ERROR);
			return false;
		}
		return true;
	}

	// +----------------------------------------------------------------------------------------------+
	// |                          MonitoredDeviceStart Thread                                         |
	// +----------------------------------------------------------------------------------------------+
	/**
	 * Runs on devices when they are started. Right now just handshakes with monitor to see if socket
	 * communication is working. In later implementations they could also try to talk with the update
	 * server to see that tunnels work.
	 */
	private class MonitoredDeviceStartThread extends Thread {
		@Override
		public void run(){
			log("MonitoredDeviceStart Thread started. Performing startup check...", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
			updateState = UpdateState.STARTUP;
			while (true) {
				String msg = socketListener.getMsg();
				if (msg.equals(UPDATE_PROTOCOL_CHECK_SOCKET)) {
					socketSender.sendMsg(UPDATE_PROTOCOL_CHECK_SOCKET_CONFIRM, SocketSender.TRY_FOREVER);
					setAsFullyOperational();
				} else if (msg.equals(UPDATE_PROTOCOL_CHECK_UPDATE_SERVER)) {
					// Get UpdateServer's deviceID in order to connect to it
					String updateServerDeviceID = socketListener.getMsg();
					Writable writableConnToUpdateServer = getWritableConnectionToService(new DeviceID(updateServerDeviceID), UpdateDistributionService.SERVICE_NAME, -1);

					// request response from update server in order to test Palcom tunnel/communication
					Command confirmRequestCmd = getProtocolHandler().findCommand(COMMAND_OUT_CHECK_UPDATE_SERVER);
					log("Sending confirmation request to update server", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
					sendTo(writableConnToUpdateServer, confirmRequestCmd);

					// wait for response from server
					log("Waiting for confirmation from update server.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
					getCommandFromBuffer(COMMAND_IN_CHECK_UPDATE_SERVER_CONFIRM);

					log("Got response from update server!", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
					socketSender.sendMsg(UPDATE_PROTOCOL_CHECK_UPDATE_SERVER_CONFIRM, SocketSender.TRY_FOREVER);
				} else if (msg.equals(UPDATE_PROTOCOL_FINISH_DEVICE_STARTUP_CHECK)) {
					socketListener.closeSocket();
					// Send ACK when socketListeners socket is closed. Otherwise it will block the
					// port for next monitored device.
					socketSender.sendMsg(UPDATE_PROTOCOL_FINISH_DEVICE_STARTUP_CHECK_ACK, SocketSender.TRY_FOREVER);
					log("MonitoredDeviceStart Thread startup check finished.", Logger.CMP_SERVICE, Logger.LEVEL_INFO);
					updateState = UpdateState.NONE;
					break;
				} else if (msg.equals(UPDATE_PROTOCOL_STAGE_TWO)) {
					updateState = UpdateState.UPDATING_STAGE_TWO;
					new UpdateStageTwoThread(getUpdaterService(), socketListener, socketSender).start();
					break;
				}
			}
			log("MonitoredDeviceStart Thread done. Thread killed.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
		}
	}

	// +----------------------------------------------------------------------------------------------+
	// |                          PalComStarterStart Thread                                           |
	// +----------------------------------------------------------------------------------------------+
	/**
	 * Runs on PalcomStarter when it is started. Right now just handshakes with monitor to see if socket
	 * communication is working. In later implementations it could also try to talk with the update
	 * server to see that tunnels work.
	 */
	private class PalComStarterStartThread extends Thread {
		@Override
		public void run() {
			log("PalComStarter Start Thread started.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
			setAsFullyOperational();
			if (continueUpdateStageThree) {
				// We are in the middle of an update. Let's carry on with it!
				updateState = UpdateState.UPDATING_STAGE_THREE;
				UpdateStageThreeThread updateStageThreeThread = new UpdateStageThreeThread(getUpdaterService(), socketListener, socketSender);
				updateStageThreeThread.start();
				while (true) {
					try {
						updateStageThreeThread.join();
						break;
					} catch (InterruptedException e) {
						log("Got interrupted while waiting for UpdateStageThree Thread. Things will go BAD if we continue so I will try to join again...", Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
					}
				}
			}
			updateState = UpdateState.NONE;
			updateServerConnectionListener.addUpdateServerListener();
			// Startup update check
			String tmp = monitoringProperties.getProperty(NAMESPACE_UPDATERSERVICE_GENERAL, KEY_UPDATE_ABORTED);
			if (tmp != null) { // then update was aborted last time so we need to remember it
				updateAborted = Integer.valueOf(tmp);
				log("Update was just aborted (total " + updateAborted + " times)", Logger.CMP_SERVICE, Logger.LEVEL_INFO);
				if (updateAborted > UPDATE_ABORTED_MANY_TIMES) {
					updateAbortedDelay = System.currentTimeMillis() + UPDATE_ABORTED_MANY_TIMES_DELAY_SECONDS*1000;
				} else {
					updateAbortedDelay = System.currentTimeMillis() + UPDATE_ABORTED_DELAY_SECONDS*1000;
				}
				log("Will wait " + (updateAbortedDelay/1000) + " seconds before trying to update again.", Logger.CMP_SERVICE, Logger.LEVEL_INFO);
				Timer t = new Timer();
				t.schedule(new TimerTask() {
					@Override
					public void run() {
						updateServerConnectionListener.checkLatestVersion();
					}
				}, UPDATE_ABORTED_DELAY_SECONDS*1000);
			} else {
				updateServerConnectionListener.checkLatestVersion();
			}
			monitor.start();
			log("PalComStarter startup check complete.", Logger.CMP_SERVICE, Logger.LEVEL_INFO);
			log("PalComStarter Start Thread done. Thread killed.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
		}
	}

	/**
	 * @param deviceID
	 * @param serviceName
	 * @param maxSecondsToWait if -1 it will try forever
	 * @return
	 */
	Writable getWritableConnectionToService(DeviceID deviceID, String serviceName, int maxSecondsToWait) {
		long timeBetweenReadyChecks = 100; // milliseconds
		Writable writableConn = null;
		PalcomDevice pd = container.getDiscoveryManager().getDevice(deviceID);
		long timeToStop = System.currentTimeMillis() + maxSecondsToWait*1000;
		while (!pd.isReady()) {
			if (maxSecondsToWait != -1 && System.currentTimeMillis() > timeToStop) {
				return null;
			}
			try {
				Thread.sleep(timeBetweenReadyChecks);
			} catch (InterruptedException e) {
				return null;
			}
		}
		log("Device with ID " + deviceID + " is ready.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
		PalcomServiceList psl = pd.getServiceList();
		PalcomService ps = null;
		try {
			for (int i = 0; i < psl.getNumService(); ++i) {
				ps = (PalcomService) psl.getService(i);
				if(ps.getName().equals(serviceName)) {
					log("Service with name " + serviceName + " found.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
					break;
				} else {
					ps = null;
				}
			}
		} catch (ResourceException e) {/* handled below */}
		if (ps == null) {
			log("Did not find service with name " + serviceName + " on device with ID " + deviceID + ".", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
			return null;
		}
		while (!ps.isReady()) {
			if (maxSecondsToWait != -1 && System.currentTimeMillis() > timeToStop) {
				return null;
			}
			try {
				Thread.sleep(5*1000);
			} catch (InterruptedException e) {
				return null;
			}
		}
		try {
			Connection conn = ps.connectTo(getConnectionHandler(), getLocalAddress(), 5000, PalComVersion.DEFAULT_SERVICE_INTERACTION_PROTOCOL);
			try {
				conn.open();
				log("Successfully connected to " + serviceName + " on " + deviceID, Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
				if (conn instanceof Writable) {
					writableConn = (Writable) conn;
				}
			} catch (IllegalStateException e) {
				log("Connection to " + serviceName + " is already open.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
			} catch (NoSuchDeviceException e) {
				log("Device " + deviceID + "cannot be found.", Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
			} catch (IOException e) {
				// Auto-generated catch block
				e.printStackTrace();
			}
		} catch (TreeUpdateException e) {
			// Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// Auto-generated catch block
			e.printStackTrace();
		} catch (ResourceException e) {
			// Auto-generated catch block
			e.printStackTrace();
		}
		return writableConn;
	}

	void log(String msg, int component, int logLevel) {
		// Uncommment this to use standard logging
//		Logger.log(msg, component, logLevel);

		// Uncomment this to see color coded log messages.
//		boolean linuxColorCoding = true;
//		saneLog(msg, component, logLevel, linuxColorCoding, false);

		// Uncomment this and set log level to Logger.NONE in order to see what is happening when debugging.
		boolean linuxColorCoding = true;
		saneLog(msg, component, logLevel, linuxColorCoding, true);
	}

	private void saneLog(String msg, int component, int logLevel, boolean linuxColorCoding, boolean stripped) {
		String red = "";
		String green = "";
		String resetColor = "";

		// Using color coding for linux terminal
		if (linuxColorCoding) {
			red = "\033[31m";
			green = "\033[32m";
			resetColor = "\033[0m";
		}

		String extraInfo;
		DeviceProperties dp;
		try {
			dp = new DeviceProperties(new DeviceID("monitoring"), HostFileSystems.getGlobalRoot(), null, "Monitoring properties. Generated " + new Date());
			if (isMonitor) {
				extraInfo = red + container.getName() + "(" + dp.getProperty(NAMESPACE_UPDATERSERVICE_DEVICE_TYPE_VERSION, PALCOMSTARTER_DEVICE_TYPE) + ")";
			} else {
				extraInfo = green + container.getName() + "(" + dp.getProperty(NAMESPACE_UPDATERSERVICE_DEVICE_TYPE_VERSION, "TheThing") + ")";
			}
		} catch (IOException e) {
			if (isMonitor) {
				extraInfo = red + container.getName();
			} else {
				extraInfo = green + container.getName();
			}
		}
		String print = extraInfo + ": " + resetColor + msg;
		if (stripped) {
			System.err.println(print);
		} else {
			Logger.log(print, component, logLevel);
		}
	}

	synchronized void setUpdateState(UpdateState state) {
		updateState = state;
	}
	boolean sendPalComMessage(Writable conn, Command cmd) {
		int status = super.sendTo(conn, cmd);
		switch (status) {
		case SEND_BUFFER_FULL:
			log("Send buffer full.", Logger.CMP_SERVICE, Logger.LEVEL_WARNING);
			return false;
		case SEND_ERROR:
			log("Send error.", Logger.CMP_SERVICE, Logger.LEVEL_ERROR);
			return false;
		case SEND_OK:
			log("Successfully sent command " + cmd.getID(), Logger.CMP_SERVICE, Logger.LEVEL_DEBUG);
			return true;
		default:
			break;
		}
		return false;
	}

	Command getCommand(String cmdID) {
		return getProtocolHandler().findCommand(cmdID);
	}

	UpdaterService getUpdaterService() {
		return this;
	}
}


text:
Basic Usage
===========

The usage of this component bases on a few classes cooperation.
Create an **Archetype** with given **Attributes** as an *ArrayCollection*.
To create an **Archetype** we can use its Builder class, which will use
your **AttributeValues** repository.

Archetype
---------

.. code-block:: php

    <?php

    use Doctrine\Common\Collections\ArrayCollection;
    use Sylius\Component\Attribute\Model\Attribute;
    use Sylius\Component\Archetype\Model\Archetype;
    use Sylius\Component\Archetype\Builder\ArchetypeBuilder;

    $archetype = new Archetype();

    // Before you can start using the new archetype please set its current and fallback locales.
    $archetype->setCurrentLocale('en');
    $archetype->setFallbackLocale('en');

    // Let's create an attribute for our archetype
    $attribute = new Attribute();
    $attribute->setName('Mug material');
    $attribute->setType('text');

    // And then let's add it to a collection
    $attributes = new ArrayCollection();
    $attributes->add($attribute);

    $archetype->setName('Mug');
    $archetype->setAttributes($attributes);
    $archetype->getName(); // returns 'Mug'
    $archetype->getAttributes(); // returns $attributes

ArchetypeBuilder
----------------

.. code-block:: php

    /**
     * @param RepositoryInterface $attributeValueRepository
     */
    $builder = new ArchetypeBuilder($attributeValueRepository);

    /**
     * @var ArchetypeSubjectInterface $subject
     */
    $subject = /* ... */;

    $builder->build($subject);

.. note::

    You can find more information about this class in `Sylius API ArchetypeBuilder`_.

.. _Sylius API ArchetypeBuilder: http://api.sylius.org/Sylius/Component/Archetype/Builder/ArchetypeBuilder.html


text:
activity Java::com.gretz.helloworld.HelloWorldActivity

setup do |activity|
  start = Time.now
  loop do
    @text_view = activity.findViewById(42)
    break if @text_view || (Time.now - start > 60)
    sleep 1
  end
  assert @text_view
end

test('initial setup') do |activity|
  assert_equal 'What hath Matz wrought?', @text_view.text
end

test('button changes text') do |activity|
  button = activity.findViewById(43)
  button.performClick
  assert_equal 'What hath Matz wrought!', @text_view.text
end


text:
namespace base {
template <typename T>
struct DefaultSingletonTraits;
}

namespace sessions {
class TabRestoreService;
}

namespace ios {
class ChromeBrowserState;
}

// Singleton that owns all TabRestoreServices and associates them with
// ChromeBrowserStates.
class IOSChromeTabRestoreServiceFactory
    : public BrowserStateKeyedServiceFactory {
 public:
  static sessions::TabRestoreService* GetForBrowserState(
      ios::ChromeBrowserState* browser_state);

  static IOSChromeTabRestoreServiceFactory* GetInstance();

  // Returns the default factory used to build TabRestoreService. Can be
  // registered with SetTestingFactory to use the TabRestoreService instance
  // during testing.
  static TestingFactoryFunction GetDefaultFactory();

 private:
  friend struct base::DefaultSingletonTraits<IOSChromeTabRestoreServiceFactory>;

  IOSChromeTabRestoreServiceFactory();
  ~IOSChromeTabRestoreServiceFactory() override;

  // BrowserStateKeyedServiceFactory:
  scoped_ptr<KeyedService> BuildServiceInstanceFor(
      web::BrowserState* context) const override;
  bool ServiceIsNULLWhileTesting() const override;

  DISALLOW_COPY_AND_ASSIGN(IOSChromeTabRestoreServiceFactory);
};

#endif  // IOS_CHROME_BROWSER_SESSIONS_IOS_CHROME_TAB_RESTORE_SERVICE_FACTORY_H_


text:
const moment = require('moment')

module.exports = {
    timeFormat: function(t, type){
        switch (type){
            case 1:
                return moment(t).format('hh:mm MM/DD/YYYY');
                break;
            case 2:
                break;
        }
    },
    timeFormat: function(t){
        return moment(t).format('YYYY-MM-DD HH:mm');
    },
    stringSub: function(str, length){
        return str.substring(0, length);
    }
}


text:
package mongodb

import (
	mgo "gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"

	"github.com/tsuru/tsuru/db"
	dbStorage "github.com/tsuru/tsuru/db/storage"
	"github.com/tsuru/tsuru/types/app"
)

type PlanService struct{}

type plan struct {
	Name     string `bson:"_id"`
	Memory   int64
	Swap     int64
	CpuShare int
	Default  bool
}

func plansCollection(conn *db.Storage) *dbStorage.Collection {
	return conn.Collection("plans")
}

func (s *PlanService) Insert(p app.Plan) error {
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	if p.Default {
		_, err = plansCollection(conn).UpdateAll(bson.M{"default": true}, bson.M{"$unset": bson.M{"default": false}})
		if err != nil {
			return err
		}
	}
	err = plansCollection(conn).Insert(plan(p))
	if err != nil && mgo.IsDup(err) {
		return app.ErrPlanAlreadyExists
	}
	return err
}

func (s *PlanService) FindAll() ([]app.Plan, error) {
	return s.findByQuery(nil)
}

func (s *PlanService) FindDefault() (*app.Plan, error) {
	plans, err := s.findByQuery(bson.M{"default": true})
	if err != nil {
		return nil, err
	}
	if len(plans) > 1 {
		return nil, app.ErrPlanDefaultAmbiguous
	}
	if len(plans) == 0 {
		return nil, nil
	}
	return &plans[0], err
}

func (s *PlanService) findByQuery(query bson.M) ([]app.Plan, error) {
	conn, err := db.Conn()
	if err != nil {
		return nil, err
	}
	defer conn.Close()
	var plans []plan
	err = plansCollection(conn).Find(query).All(&plans)
	if err != nil {
		return nil, err
	}
	appPlans := make([]app.Plan, len(plans))
	for i, p := range plans {
		appPlans[i] = app.Plan(p)
	}
	return appPlans, nil
}

func (s *PlanService) FindByName(name string) (*app.Plan, error) {
	var p plan
	conn, err := db.Conn()
	if err != nil {
		return nil, err
	}
	defer conn.Close()
	err = plansCollection(conn).FindId(name).One(&p)
	if err != nil {
		if err == mgo.ErrNotFound {
			err = app.ErrPlanNotFound
		}
		return nil, err
	}
	plan := app.Plan(p)
	return &plan, nil
}

func (s *PlanService) Delete(p app.Plan) error {
	conn, err := db.Conn()
	if err != nil {
		return err
	}
	defer conn.Close()
	err = plansCollection(conn).RemoveId(p.Name)
	if err == mgo.ErrNotFound {
		return app.ErrPlanNotFound
	}
	return err
}


text:
PhysicsDemos
============

An application that demonstrates multiple principles of introductory physics concepts.

####Instructions to Run PhysicsDemos

To run with maven, type the following into the command line while inside the project directory:

```
$ mvn package
```

```
$ java -jar target/demo-1.0-SNAPSHOT.jar
```

Click on a demo to run it or 'Quit' to close the application.
Use the up and down arrows to look through the demos.
Pressing escape when a demo is running returns to the menu.

####Some of the demos include:

Fireworks - click anywhere to see velocity and acceleration of particles in three dimensions

Launcher - see four particles launched from the left of the screen. Click to trace the paths of the particles. Particles are attracted to the mouse if they are close enough.

Rain - lots of particles fall from the top of the screen. Your mouse is hydrophobic and pushes the particles away.

Meteor - A particle launches from the top of the screen. Click two points in the window to create a wall there that the particle will bounce off of.

Rocket - Drag the sliders to adjust fuel amount and mass of the rocket. Press space to launch a new rocket.

Cylinder - Drag the sliders to adjust the mass of the cylinder and box. Press space or adjust the sliders to reset the box.

PeriodicWave - Drag the sliders to adjust amplitude and period for red and blue waves. Press '1' or '2' to reverse the wave direction. Press 'q' or 'a' to phase shift either wave to the left. Press 'w' or 's' to phase shift to the right.

Gravitation - Press space to spawn a particle and click and drag the mouse to create a new gravity source.


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.04.27 at 05:36:21 PM CEST
//

package org.aleroddepaz.soapuimodel;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for SoapUIActions complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="SoapUIActions">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="action" type="{http://eviware.com/soapui/config}SoapUIAction" maxOccurs="unbounded" minOccurs="0"/>
 *         <element name="actionGroup" type="{http://eviware.com/soapui/config}SoapUIActionGroup" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SoapUIActions", propOrder = {
    "action",
    "actionGroup"
})
public class SoapUIActions {

    protected List<SoapUIAction> action;
    protected List<SoapUIActionGroup> actionGroup;

    /**
     * Gets the value of the action property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the action property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getAction().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link SoapUIAction }
     *
     *
     */
    public List<SoapUIAction> getAction() {
        if (action == null) {
            action = new ArrayList<SoapUIAction>();
        }
        return this.action;
    }

    /**
     * Gets the value of the actionGroup property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the actionGroup property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getActionGroup().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link SoapUIActionGroup }
     *
     *
     */
    public List<SoapUIActionGroup> getActionGroup() {
        if (actionGroup == null) {
            actionGroup = new ArrayList<SoapUIActionGroup>();
        }
        return this.actionGroup;
    }

}


text:
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include "windef.h"
#include "winbase.h"
#include "wine/winbase16.h"
#include "wine/debug.h"

WINE_DEFAULT_DEBUG_CHANNEL(dll);

/***********************************************************************
 *		BootTask (WIN32S16.2)
 */
void WINAPI BootTask16(void)
{
	MESSAGE("BootTask(): should only be used by WIN32S.EXE.\n");
}

/***********************************************************************
 *           StackLinearToSegmented       (WIN32S16.43)
 *
 * Written without any docu.
 */
SEGPTR WINAPI StackLinearToSegmented16(WORD w1, WORD w2)
{
	FIXME("(%d,%d):stub.\n",w1,w2);
	return 0;
}

/***********************************************************************
 *           UTSelectorOffsetToLinear       (WIN32S16.48)
 *
 * rough guesswork, but seems to work (I had no "reasonable" docu)
 */
LPVOID WINAPI UTSelectorOffsetToLinear16(SEGPTR sptr)
{
        return MapSL(sptr);
}

/***********************************************************************
 *           UTLinearToSelectorOffset       (WIN32S16.49)
 *
 * FIXME: I don't know if that's the right way to do linear -> segmented
 */
SEGPTR WINAPI UTLinearToSelectorOffset16(LPVOID lptr)
{
    return (SEGPTR)lptr;
}

/***********************************************************************
 *           ContinueDebugEvent       (WIN32S16.5)
 */
BOOL WINAPI ContinueDebugEvent16(DWORD pid, DWORD tid, DWORD status)
{
    return ContinueDebugEvent(pid, tid, status);
}

/***********************************************************************
 *           ReadProcessMemory       (WIN32S16.6)
 */
BOOL WINAPI ReadProcessMemory16(HANDLE process, LPCVOID addr, LPVOID buffer,
				DWORD size, LPDWORD bytes_read)
{
    return ReadProcessMemory(process, addr, buffer, size, (SIZE_T *)bytes_read);
}

/***********************************************************************
 *           GetLastError       (WIN32S16.10)
 */
DWORD WINAPI GetLastError16(void)
{
    return GetLastError();
}

/***********************************************************************
 *           CloseHandle	(WIN32S16.11)
 */
BOOL WINAPI CloseHandle16(HANDLE handle)
{
    return CloseHandle(handle);
}

/***********************************************************************
 *           GetExitCodeThread	(WIN32S16.13)
 */
BOOL WINAPI GetExitCodeThread16(HANDLE hthread, LPDWORD exitcode)
{
    return GetExitCodeThread(hthread, exitcode);
}

/***********************************************************************
 *           VirtualQueryEx	(WIN32S16.18)
 */
DWORD WINAPI VirtualQueryEx16(HANDLE handle, LPCVOID addr,
			      PMEMORY_BASIC_INFORMATION info, DWORD len)
{
    return VirtualQueryEx(handle, addr, info, len);
}

/***********************************************************************
 *           VirtualProtectEx	(WIN32S16.19)
 */
BOOL WINAPI VirtualProtectEx16(HANDLE handle, LPVOID addr, DWORD size,
			       DWORD new_prot, LPDWORD old_prot)
{
    return VirtualProtectEx(handle, addr, size, new_prot, old_prot);
}


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

/**
 * Controlador principal que verifica si los usuarios estan logeados
 **/
class MY_Controller extends CI_Controller {

	var $user;

	function __construct()
	{
		parent::__construct();
		if (!$this->ion_auth->logged_in())
		{
			//redirect them to the login page
			redirect('auth/login', 'refresh');
		}else{
			$this->user=$this->ion_auth->user()->row();
		}
	}

}