text:
package fi.itsfactory.realtime.access;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.transcoders.SerializingTranscoder;
import net.rubyeye.xmemcached.utils.AddrUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;

import fi.itsfactory.realtime.access.siri.vm.VMResponseFilterV2;

public class MemcachedDatasourceV2 implements SiriDatasource {
	private static final Logger logger = LoggerFactory.getLogger(MemcachedDatasourceV2.class);

	private String cacheUrl;
	private String vmKey;
	private String gmKey;
	private SAXParser responseSAXParser;

	public MemcachedDatasourceV2(String cacheUrl, String vmKey, String gmKey) {
		this.cacheUrl = cacheUrl;
		this.vmKey = vmKey;
		this.gmKey = gmKey;

		responseSAXParser = null;
	}

	@Override
	public synchronized String getVehicleMonitoringData(String lineRef, String vehicleRef) {
        try {
            /*
             * Fetch the cached response. A backend process updates the (mem)cache(d) periodically (once per
             * second). cacheUrl and vmKey(the key the backend process uses to store the response) are
             * injected into this class in the constructor.
             */
            MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(cacheUrl));
            MemcachedClient memcachedClient = builder.build();
            //memcachedClient.setTranscoder(new SerializingTranscoder(100 * 1024 * 1024));
            String latestVM = memcachedClient.get(vmKey);

            memcachedClient.shutdown();

            if (responseSAXParser != null) { // init failed, don't even try
                if(!latestVM.startsWith("<!DOCTYPE html")){
                    /*
                     * If the client has specified either lineRef or vehicleRef, we have to filter the response.
                     * Since the backend system pushes one single document to the cache, which contains data for
                     * all vehicles, we have to parse the XML and filter our during parsing.
                     */
                    try {
                        VMResponseFilterV2 responseFilter = new VMResponseFilterV2(lineRef, vehicleRef);
                        responseSAXParser.parse(new ByteArrayInputStream(latestVM.getBytes()), responseFilter);
                        latestVM = responseFilter.getFilteredDocument();
                        return latestVM;
                    } catch (SAXException e) {
                        return null;
                    } catch (Throwable t) {
                        return null;
                    }
                }else {
                    return null;
                }
            } else {
                logger.error("Response parser not initialized properly, cannot process request since client requests filtering. "
                        + "Check the logs for startup exceptions.");
                return null;
            }
        } catch (IOException e) {
            logger.error("Cannot process request", e);
            return null;
        } catch (TransformerFactoryConfigurationError e) {
            logger.error("Cannot process request", e);
            return null;
        } catch (TimeoutException e) {
            logger.error("Cannot process request", e);
            return null;
        } catch (InterruptedException e) {
            logger.error("Cannot process request", e);
            return null;
        } catch (MemcachedException e) {
            logger.error("Cannot process request", e);
            return null;
        }
	}

	    public String getGeneralMessageData() {
	        try {
	            /*
	             * Fetch the cached response. A backend process updates the
	             * (mem)cache(d) periodically (once per second). cacheUrl and gmKey(the
	             * key the backend process uses to store the response) are injected into
	             * this class in the constructor.
	             */
	            MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(cacheUrl));
	            MemcachedClient memcachedClient = builder.build();
	            String latestVM = memcachedClient.get(gmKey);
	            memcachedClient.shutdown();
	            if(!latestVM.startsWith("<!DOCTYPE html")){
	                return latestVM;
	            }else{
	                return null;
	            }
	        } catch (IOException e) {
	            logger.error("Cannot process request", e);
	            return null;
	        } catch (TimeoutException e) {
                logger.error("Cannot process request", e);
                return null;
            } catch (InterruptedException e) {
                logger.error("Cannot process request", e);
                return null;
            } catch (MemcachedException e) {
                logger.error("Cannot process request", e);
                return null;
            }
	    }

	@Override
	public void initialize() {
		try {
			SAXParserFactory factory = SAXParserFactory.newInstance();
			factory.setNamespaceAware(true);
			responseSAXParser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {
			logger.error("Initialization failed", e);
		} catch (SAXException e) {
			logger.error("Initialization failed", e);
		}
	}

	@Override
	public void shutdown() {
		//No persistent resoures -nothing to do here.
	}

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="fr.micklewright.smsvote.ElectionVoteOverviewFragmentFragment">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:id="@+id/relativeLayout">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="26sp"
            android:text="@string/activity_election_posts"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_marginLeft="16dp"
            android:layout_marginStart="16dp"
            android:id="@+id/textView_election_voteOverview_title" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/activity_election_voteOverview_hint"
            android:layout_toRightOf="@+id/textView_election_voteOverview_title"
            android:layout_toEndOf="@+id/textView_election_voteOverview_title"
            android:layout_alignBottom="@id/textView_election_voteOverview_title"
            android:layout_marginLeft="20dp"
            android:layout_marginStart="20dp"/>
    </RelativeLayout>
    <ListView
        android:id="@+id/listView_posts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/relativeLayout"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>
</RelativeLayout>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_refresh"
        android:icon="@drawable/ic_refresh"
        android:title="Refresh"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/magnifier"
        android:title="Search"
        app:showAsAction="ifRoom"/>
</menu>


text:
package pl.letscode.tanks.events.server.json;

public class PlayerQuitDTO implements ServerData {

	private String name;
	private long tankId;

	public PlayerQuitDTO(String name, long tankId) {
		super();
		this.name = name;
		this.tankId = tankId;
	}
	public String getName() {
		return name;
	}
	public long getTankId() {
		return tankId;
	}

}


text:
class TestSSLErrorHandler : public SSLErrorHandler {
 public:
  TestSSLErrorHandler(Profile* profile,
                      content::WebContents* web_contents,
                      const net::SSLInfo& ssl_info)
      : SSLErrorHandler(web_contents,
                        net::ERR_CERT_COMMON_NAME_INVALID,
                        ssl_info,
                        GURL(),
                        0,
                        nullptr,
                        base::Callback<void(bool)>()),
        profile_(profile),
        captive_portal_checked_(false),
        suggested_url_exists_(false),
        suggested_url_checked_(false),
        ssl_interstitial_shown_(false),
        captive_portal_interstitial_shown_(false),
        common_name_mismatch_redirect_(false),
        is_overridable_error_(true) {}

  ~TestSSLErrorHandler() override {
  }

  using SSLErrorHandler::StartHandlingError;

  void SendCaptivePortalNotification(
      captive_portal::CaptivePortalResult result) {
    CaptivePortalService::Results results;
    results.previous_result = captive_portal::RESULT_INTERNET_CONNECTED;
    results.result = result;
    content::NotificationService::current()->Notify(
        chrome::NOTIFICATION_CAPTIVE_PORTAL_CHECK_RESULT,
        content::Source<Profile>(profile_),
        content::Details<CaptivePortalService::Results>(&results));
  }

  void SendSuggestedUrlCheckResult(
      const CommonNameMismatchHandler::SuggestedUrlCheckResult& result,
      const GURL& suggested_url) {
    CommonNameMismatchHandlerCallback(result, suggested_url);
  }

  bool IsTimerRunning() const {
    return get_timer().IsRunning();
  }

  int captive_portal_checked() const {
    return captive_portal_checked_;
  }

  int ssl_interstitial_shown() const {
    return ssl_interstitial_shown_;
  }

  int captive_portal_interstitial_shown() const {
    return captive_portal_interstitial_shown_;
  }

  void SetSuggestedUrlExists(bool suggested_url_exists) {
    suggested_url_exists_ = suggested_url_exists;
  }

  bool GetSuggestedUrl(const std::vector<std::string>& dns_names,
                       GURL* suggested_url) const override {
    if (!suggested_url_exists_)
      return false;
    *suggested_url = GURL("www.example.com");
    return true;
  }

  bool suggested_url_checked() const { return suggested_url_checked_; }

  bool common_name_mismatch_redirect() const {
    return common_name_mismatch_redirect_;
  }

  void set_non_overridable_error() { is_overridable_error_ = false; }

  void Reset() {
    captive_portal_checked_ = false;
    suggested_url_exists_ = false;
    suggested_url_checked_ = false;
    ssl_interstitial_shown_ = false;
    captive_portal_interstitial_shown_ = false;
    common_name_mismatch_redirect_ = false;
  }

 private:
  void CheckForCaptivePortal() override {
    captive_portal_checked_ = true;
  }

  void ShowSSLInterstitial() override { ssl_interstitial_shown_ = true; }

  void ShowCaptivePortalInterstitial(const GURL& landing_url) override {
    captive_portal_interstitial_shown_ = true;
  }

  void CheckSuggestedUrl(const GURL& suggested_url) override {
    suggested_url_checked_ = true;
  }

  void NavigateToSuggestedURL(const GURL& suggested_url) override {
    common_name_mismatch_redirect_ = true;
  }

  bool IsErrorOverridable() const override { return is_overridable_error_; }

  Profile* profile_;
  bool captive_portal_checked_;
  bool suggested_url_exists_;
  bool suggested_url_checked_;
  bool ssl_interstitial_shown_;
  bool captive_portal_interstitial_shown_;
  bool common_name_mismatch_redirect_;
  bool is_overridable_error_;

  DISALLOW_COPY_AND_ASSIGN(TestSSLErrorHandler);
};

class SSLErrorHandlerTest : public ChromeRenderViewHostTestHarness {
 public:
  SSLErrorHandlerTest()
      : field_trial_list_(NULL) {
  }

  void SetUp() override {
    ChromeRenderViewHostTestHarness::SetUp();
    SSLErrorHandler::SetInterstitialDelayTypeForTest(SSLErrorHandler::NONE);
    ssl_info_.cert =
        net::ImportCertFromFile(net::GetTestCertsDirectory(), "ok_cert.pem");
    ssl_info_.cert_status = net::CERT_STATUS_COMMON_NAME_INVALID;
    error_handler_.reset(new TestSSLErrorHandler(profile(),
                                                 web_contents(),
                                                 ssl_info_));
    // Enable finch experiment for captive portal interstitials.
    ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
                    "CaptivePortalInterstitial", "Enabled"));
    // Enable finch experiment for SSL common name mismatch handling.
    ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial(
                    "SSLCommonNameMismatchHandling", "Enabled"));
  }

  void TearDown() override {
    EXPECT_FALSE(error_handler()->IsTimerRunning());
    error_handler_.reset(NULL);
    ChromeRenderViewHostTestHarness::TearDown();
  }

  TestSSLErrorHandler* error_handler() { return error_handler_.get(); }

 private:
  net::SSLInfo ssl_info_;
  scoped_ptr<TestSSLErrorHandler> error_handler_;
  base::FieldTrialList field_trial_list_;
};

#if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)

TEST_F(SSLErrorHandlerTest,
       ShouldShowSSLInterstitialOnTimerExpired) {
  EXPECT_FALSE(error_handler()->IsTimerRunning());
  error_handler()->StartHandlingError();

  EXPECT_TRUE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->captive_portal_checked());
  EXPECT_FALSE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->captive_portal_interstitial_shown());

  error_handler()->Reset();
  base::MessageLoop::current()->RunUntilIdle();

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_FALSE(error_handler()->captive_portal_checked());
  EXPECT_TRUE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->captive_portal_interstitial_shown());
}

TEST_F(SSLErrorHandlerTest,
       ShouldShowCustomInterstitialOnCaptivePortalResult) {
  EXPECT_FALSE(error_handler()->IsTimerRunning());
  error_handler()->StartHandlingError();

  EXPECT_TRUE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->captive_portal_checked());
  EXPECT_FALSE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->captive_portal_interstitial_shown());
  // Fake a captive portal result.
  error_handler()->Reset();
  error_handler()->SendCaptivePortalNotification(
      captive_portal::RESULT_BEHIND_CAPTIVE_PORTAL);
  base::MessageLoop::current()->RunUntilIdle();

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_FALSE(error_handler()->captive_portal_checked());
  EXPECT_FALSE(error_handler()->ssl_interstitial_shown());
  EXPECT_TRUE(error_handler()->captive_portal_interstitial_shown());
}

TEST_F(SSLErrorHandlerTest,
       ShouldShowSSLInterstitialOnNoCaptivePortalResult) {
  EXPECT_FALSE(error_handler()->IsTimerRunning());
  error_handler()->StartHandlingError();

  EXPECT_TRUE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->captive_portal_checked());
  EXPECT_FALSE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->captive_portal_interstitial_shown());
  // Fake a "connected to internet" result for the captive portal check.
  // This should immediately trigger an SSL interstitial without waiting for
  // the timer to expire.
  error_handler()->Reset();
  error_handler()->SendCaptivePortalNotification(
      captive_portal::RESULT_INTERNET_CONNECTED);
  base::MessageLoop::current()->RunUntilIdle();

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_FALSE(error_handler()->captive_portal_checked());
  EXPECT_TRUE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->captive_portal_interstitial_shown());
}

TEST_F(SSLErrorHandlerTest, ShouldNotCheckSuggestedUrlIfNoSuggestedUrl) {
  error_handler()->SetSuggestedUrlExists(false);
  error_handler()->StartHandlingError();

  EXPECT_TRUE(error_handler()->captive_portal_checked());
  EXPECT_TRUE(error_handler()->IsTimerRunning());
  EXPECT_FALSE(error_handler()->suggested_url_checked());
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->ssl_interstitial_shown());
}

TEST_F(SSLErrorHandlerTest, ShouldNotCheckCaptivePortalIfSuggestedUrlExists) {
  EXPECT_FALSE(error_handler()->IsTimerRunning());
  error_handler()->SetSuggestedUrlExists(true);
  error_handler()->StartHandlingError();

  EXPECT_TRUE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->suggested_url_checked());
  EXPECT_FALSE(error_handler()->captive_portal_checked());
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->ssl_interstitial_shown());
}

TEST_F(SSLErrorHandlerTest, ShouldNotHandleNameMismatchOnNonOverridableError) {
  error_handler()->set_non_overridable_error();
  error_handler()->SetSuggestedUrlExists(true);
  error_handler()->StartHandlingError();

  EXPECT_FALSE(error_handler()->suggested_url_checked());
  EXPECT_TRUE(error_handler()->captive_portal_checked());
  EXPECT_TRUE(error_handler()->IsTimerRunning());
  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->ssl_interstitial_shown());
}

#else  // #if !defined(ENABLE_CAPTIVE_PORTAL_DETECTION)

TEST_F(SSLErrorHandlerTest,
       ShouldShowSSLInterstitialOnCaptivePortalDetectionDisabled) {
  EXPECT_FALSE(error_handler()->IsTimerRunning());
  error_handler()->SetSuggestedUrlExists(false);
  error_handler()->StartHandlingError();
  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_FALSE(error_handler()->captive_portal_checked());
  EXPECT_TRUE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->captive_portal_interstitial_shown());
}

#endif  // defined(ENABLE_CAPTIVE_PORTAL_DETECTION)

TEST_F(SSLErrorHandlerTest,
       ShouldShowSSLInterstitialOnTimerExpiredWhenSuggestedUrlExists) {
  error_handler()->SetSuggestedUrlExists(true);
  error_handler()->StartHandlingError();

  EXPECT_TRUE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->suggested_url_checked());
  EXPECT_FALSE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->common_name_mismatch_redirect());

  base::RunLoop().RunUntilIdle();

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->common_name_mismatch_redirect());
}

TEST_F(SSLErrorHandlerTest, ShouldRedirectOnSuggestedUrlCheckResult) {
  error_handler()->SetSuggestedUrlExists(true);
  error_handler()->StartHandlingError();

  EXPECT_TRUE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->suggested_url_checked());
  EXPECT_FALSE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->common_name_mismatch_redirect());
  // Fake a valid suggested URL check result.
  // The URL returned by |SuggestedUrlCheckResult| can be different from
  // |suggested_url|, if there is a redirect.
  error_handler()->SendSuggestedUrlCheckResult(
      CommonNameMismatchHandler::SuggestedUrlCheckResult::
          SUGGESTED_URL_AVAILABLE,
      GURL("https://random.example.com"));

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_FALSE(error_handler()->ssl_interstitial_shown());
  EXPECT_TRUE(error_handler()->common_name_mismatch_redirect());
}

TEST_F(SSLErrorHandlerTest, ShouldShowSSLInterstitialOnInvalidUrlCheckResult) {
  error_handler()->SetSuggestedUrlExists(true);
  error_handler()->StartHandlingError();

  EXPECT_TRUE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->suggested_url_checked());
  EXPECT_FALSE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->common_name_mismatch_redirect());
  // Fake an Invalid Suggested URL Check result.
  error_handler()->SendSuggestedUrlCheckResult(
      CommonNameMismatchHandler::SuggestedUrlCheckResult::
          SUGGESTED_URL_NOT_AVAILABLE,
      GURL());

  EXPECT_FALSE(error_handler()->IsTimerRunning());
  EXPECT_TRUE(error_handler()->ssl_interstitial_shown());
  EXPECT_FALSE(error_handler()->common_name_mismatch_redirect());
}


text:
namespace BlockchainSharp.Compilers
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using BlockchainSharp.Vm;

    public class SimpleCompiler
    {
        private BytecodeCompiler compiler = new BytecodeCompiler();
        private string[] lines;
        private int nlines;
        private int cline;

        public SimpleCompiler(string text)
        {
            if (text == null)
                this.lines = new string[0];
            else
                this.lines = text.Split('\n', '\r');

            this.nlines = this.lines.Length;
            this.cline = 0;
        }

        public byte[] Compile()
        {
            while (this.cline < this.nlines)
                this.ProcessLine(this.lines[this.cline++]);

            return this.compiler.ToBytes();
        }

        private void ProcessLine(string line)
        {
            int p = line.IndexOf("#");

            if (p >= 0)
                line = line.Substring(0, p);

            line = line.Trim();

            if (line.Length == 0)
                return;

            var words = line.Split(' ', '\t');

            if (words.Length == 0)
                return;

            var verb = words[0].ToLower();

            if (verb == "add")
                this.compiler.Add();
            else if (verb == "subtract")
                this.compiler.Subtract();
            else if (verb == "multiply")
                this.compiler.Multiply();
            else if (verb == "divide")
                this.compiler.Divide();
            else if (verb == "dup")
                this.compiler.Dup(int.Parse(words[1]));
            else if (verb == "push")
                this.compiler.Push(int.Parse(words[1]));
            else if (verb == "swap")
                this.compiler.Swap(int.Parse(words[1]));
            else if (verb == "equal" || verb == "eq")
                this.compiler.Equal();
            else if (verb == "iszero")
                this.compiler.IsZero();
            else if (verb == "and")
                this.compiler.And();
            else if (verb == "or")
                this.compiler.Or();
            else if (verb == "not")
                this.compiler.Not();
            else if (verb == "xor")
                this.compiler.Xor();
            else if (verb == "pop")
                this.compiler.Pop();
            else if (verb == "lessthan" || verb == "lt")
                this.compiler.LessThan();
            else if (verb == "greaterthan" || verb == "gt")
                this.compiler.GreaterThan();
            else if (verb == "sload")
                this.compiler.SLoad();
            else if (verb == "sstore")
                this.compiler.SStore();
            else if (verb == "mstore")
                this.compiler.MStore();
            else if (verb == "mload")
                this.compiler.MLoad();
            else if (verb == "mstore8")
                this.compiler.MStore8();
            else if (verb == "jump")
                this.compiler.Jump();
            else if (verb == "jumpi")
                this.compiler.JumpI();
            else if (verb == "pc")
                this.compiler.Pc();
            else if (verb == "stop")
                this.compiler.Stop();
        }
    }
}


text:
<?php

namespace frontend\modules\student\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\TrainingScheduleTrainer;

/**
 * TrainingScheduleTrainerSearch represents the model behind the search form about `frontend\models\TrainingScheduleTrainer`.
 */
class TrainingScheduleTrainerSearch extends TrainingScheduleTrainer
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'training_schedule_id', 'type', 'trainer_id', 'cost', 'status', 'created_by', 'modified_by'], 'integer'],
            [['hours'], 'number'],
            [['reason', 'created', 'modified'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params,$training_class_id=NULL)
    {
        $query = TrainingScheduleTrainer::find()
				->leftjoin('training_schedule','training_schedule.id=training_schedule_trainer.training_schedule_id')
				->where(['training_class_id'=>$training_class_id]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'training_schedule_id' => $this->training_schedule_id,
            'type' => $this->type,
            'trainer_id' => $this->trainer_id,
            'hours' => $this->hours,
            'cost' => $this->cost,
            'status' => $this->status,
            'created' => $this->created,
            'created_by' => $this->created_by,
            'modified' => $this->modified,
            'modified_by' => $this->modified_by,
        ]);

        $query->andFilterWhere(['like', 'reason', $this->reason]);

        return $dataProvider;
    }
}


text:
#include "PtySky.h"

#include <QtToolbox/CollapsibleWidget.moc.h>
#include <QtToolbox/SingleSlidingValue.moc.h>
#include <QtToolbox/ColorPicker/QuickColorPicker.moc.h>
#include <QtToolbox/ComboBox.moc.h>

#include <Universe/World.h>

#include <QGridLayout>
#include <QCheckBox>

#include <EPI/GUI/Widget/CustomLine.moc.h>

namespace EPI
{
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
PtySky::PtySky(const Ptr<Universe::World>& pWorld, const Core::String& title):
    PropertyNode(title, true, false, CONTENT),
    _skyTexture(pWorld->getSkyTexture()),
    _color(pWorld->getSkyColor()),
    _glow(pWorld->getSkyGlow()),
    _horizon(pWorld->getSkyHorizon()),
    _angle(pWorld->getSkyAngle()),
    _roof(pWorld->getSkyRoof()),
    _sphericity(pWorld->getSkySphericity()),
    _atInfinity(pWorld->getSkyAtInfinity()),
    _isProcedural(pWorld->isSkyProcedural()),
    _model(pWorld->getSkyModel()),
    _skyColor(pWorld->getSkyBackColor()),
    _sunColor(pWorld->getSkySunColor()),
    _intensity(pWorld->getSkySunIntensity()),
    _pWorld(pWorld)
{
    updateProperty();
}
//-----------------------------------------------------------------------------
PtySky::~PtySky()
{
}
//-----------------------------------------------------------------------------
Ptr<PropertyWidget> PtySky::internalCreatePropertyWidget(const Ptr<PropertyWidgetDataProxy>& pDataProxy, QWidget * parent)
{
    Ptr<PtyWidgetSky> pPW (new PtyWidgetSky(pDataProxy, parent));
    return pPW;
}
//-----------------------------------------------------------------------------
void PtySky::updateProperty()
{
    _skyTexture     = _pWorld->getSkyTexture();
    _color          = _pWorld->getSkyColor();
    _glow           = _pWorld->getSkyGlow();
    _horizon        = _pWorld->getSkyHorizon();
    _angle          = _pWorld->getSkyAngle();
    _roof           = _pWorld->getSkyRoof();
    _sphericity     = _pWorld->getSkySphericity();
    _atInfinity     = _pWorld->getSkyAtInfinity();
    _isProcedural   = _pWorld->isSkyProcedural();
    _model          = _pWorld->getSkyModel();
    _skyColor       = _pWorld->getSkyBackColor();
    _sunColor       = _pWorld->getSkySunColor();
    _intensity      = _pWorld->getSkySunIntensity();
}
//-----------------------------------------------------------------------------
void PtySky::updateData()
{
    _pWorld->setSkyTexture(_skyTexture);
    _pWorld->setSkyColor(_color);
    _pWorld->setSkyGlow(_glow);
    _pWorld->setSkyHorizon(_horizon);
    _pWorld->setSkyAngle(_angle);
    _pWorld->setSkyRoof(_roof);
    _pWorld->setSkySphericity(_sphericity);
    _pWorld->setSkyAtInfinity(_atInfinity);
    _pWorld->setSkyProcedural(_isProcedural);
    _pWorld->setSkyModel(_model);
    _pWorld->setSkyBackColor(_skyColor);
    _pWorld->setSkySunColor(_sunColor);
    _pWorld->setSkySunIntensity(_intensity);
}
//-----------------------------------------------------------------------------
Ptr<Property> PtySky::clone() const
{
    return Ptr<Property>(new PtySky( *this ));
}
//-----------------------------------------------------------------------------
void PtySky::internalCopy(const Ptr<Property>& pSrc)
{
    Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(pSrc);

    _skyTexture     = pPtySky->_skyTexture;
    _color          = pPtySky->_color;
    _glow           = pPtySky->_glow;
    _horizon        = pPtySky->_horizon;
    _angle          = pPtySky->_angle;
    _roof           = pPtySky->_roof;
    _sphericity     = pPtySky->_sphericity;
    _atInfinity     = pPtySky->_atInfinity;
    _isProcedural   = pPtySky->_isProcedural;
    _pWorld         = pPtySky->_pWorld;
    _model          = pPtySky->_model;
    _skyColor       = pPtySky->_skyColor;
    _sunColor       = pPtySky->_sunColor;
    _intensity      = pPtySky->_intensity;

    updateData();
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
PtyWidgetSky::PtyWidgetSky(const Ptr<PropertyWidgetDataProxy>& data, QWidget * parent):
    PropertyWidget(data, parent)
{
    setupUi();
}
//-----------------------------------------------------------------------------
PtyWidgetSky::~PtyWidgetSky()
{
}
//-----------------------------------------------------------------------------
void PtyWidgetSky::setupUi()
{
    _layout = new QGridLayout(this);
        _layout->setContentsMargins(0, 0, 0, 0);
        _layout->setAlignment(Qt::AlignTop | Qt::AlignLeft);

    _groupBox   = new QtToolbox::CollapsibleWidget(this, "Sky", false);
        _groupBox->setStyle(QtToolbox::CW_TITLE_1);
        _groupBox->setAlignmentTitle(Qt::AlignCenter);

    QGridLayout* layoutGroupBox = new QGridLayout(NULL);
        layoutGroupBox->setContentsMargins(0, 0, 0, 0);
        _groupBox->setLayout(layoutGroupBox);

    _skyTexture = new CustomLine(_groupBox, "Texture");
        _skyTexture->pushAuthorizedDropMimeData("asset/texture");
        _skyTexture->setReadOnly(true);
    _color      = new QtToolbox::QuickColorPicker(_groupBox, "Color", Qt::white, false);
    _glow       = new QtToolbox::QuickColorPicker(_groupBox, "Glow", Qt::white, false);
    _horizon    = new QtToolbox::SingleSlidingDouble(_groupBox, "Horizon", -1.0, 0.99);
    _angle      = new QtToolbox::SingleSlidingDouble(_groupBox, "Angle", 0, Core::rad2deg(d_PI_MUL_2));
    _roof       = new QtToolbox::SingleSlidingDouble(_groupBox, "Roof", 0.0, 5000.0);
    _sphericity = new QtToolbox::SingleSlidingDouble(_groupBox, "Sphericity", 0.0, 1.0);
    _atInfinity = new QCheckBox("At infinity", _groupBox);
    _atInfinity->setChecked(true);
    _isProcedural = new QCheckBox("Is procedural", _groupBox);
    _isProcedural->setChecked(true);
    _model      = new QtToolbox::ComboBox(_groupBox, "Model");
    _skyColor   = new QtToolbox::QuickColorPicker(_groupBox, "Sky color", Qt::white, false);
    _sunColor   = new QtToolbox::QuickColorPicker(_groupBox, "Sun color", Qt::white, false);
    _intensity  = new QtToolbox::SingleSlidingDouble(_groupBox, "Intensity", 1.0, 4.0);

    _model->addItem("Foggy");
    _model->addItem("Cloudy");
    _model->addItem("Clear sky");

    layoutGroupBox->addWidget(_skyTexture,  0,  0,  Qt::AlignCenter);
    layoutGroupBox->addWidget(_color,       1,  0,  Qt::AlignCenter);
    layoutGroupBox->addWidget(_glow,        2,  0,  Qt::AlignCenter);
    layoutGroupBox->addWidget(_horizon,     3,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_angle,       4,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_roof,        5,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_sphericity,  6,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_atInfinity,  7,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_isProcedural,8,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_model,       9,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_skyColor,   10,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_sunColor,   11,  0,  Qt::AlignLeft);
    layoutGroupBox->addWidget(_intensity,  12,  0,  Qt::AlignLeft);

    _layout->addWidget(_groupBox);

    getWidgetsForUndoRedo().push_back(_skyTexture);
    getWidgetsForUndoRedo().push_back(_color);
    getWidgetsForUndoRedo().push_back(_glow);
    getWidgetsForUndoRedo().push_back(_horizon);
    getWidgetsForUndoRedo().push_back(_angle);
    getWidgetsForUndoRedo().push_back(_roof);
    getWidgetsForUndoRedo().push_back(_sphericity);
    getWidgetsForUndoRedo().push_back(_atInfinity);
    getWidgetsForUndoRedo().push_back(_isProcedural);
    getWidgetsForUndoRedo().push_back(_model);
    getWidgetsForUndoRedo().push_back(_skyColor);
    getWidgetsForUndoRedo().push_back(_sunColor);
    getWidgetsForUndoRedo().push_back(_intensity);

    PropertyWidget::setupUi();
}
//-----------------------------------------------------------------------------
void PtyWidgetSky::readProperty()
{
    Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(getDataProxy()->getProperty());

    _skyTexture->setText(Core::String8(pPtySky->_skyTexture).c_str());
    _color->setColorLinear(pPtySky.get()->_color.r, pPtySky.get()->_color.g, pPtySky.get()->_color.b, pPtySky.get()->_color.a);
    _glow->setColorLinear(pPtySky.get()->_glow.r, pPtySky.get()->_glow.g, pPtySky.get()->_glow.b, pPtySky.get()->_glow.a);
    _horizon->setSingleValue(pPtySky->_horizon);
    _angle->setSingleValue(Core::rad2deg(pPtySky->_angle));
    _roof->setSingleValue(pPtySky->_roof);
    _sphericity->setSingleValue(pPtySky->_sphericity);
    _atInfinity->setChecked(pPtySky->_atInfinity);
    _isProcedural->setChecked(pPtySky->_isProcedural);
    _skyColor->setColorLinear(pPtySky->_skyColor);
    _sunColor->setColorLinear(pPtySky->_sunColor);
    _model->selectIndex(int(pPtySky->_model));
    _intensity->setSingleValue(pPtySky->_intensity);
}
//-----------------------------------------------------------------------------
void PtyWidgetSky::writeProperty(QWidget* pWidget)
{
    Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(getDataProxy()->getProperty());

    pPtySky->_skyTexture = Core::String(_skyTexture->text().toStdString().c_str());
    _color->getColorLinear(pPtySky.get()->_color.r, pPtySky.get()->_color.g, pPtySky.get()->_color.b, pPtySky.get()->_color.a);
    _glow->getColorLinear(pPtySky.get()->_glow.r, pPtySky.get()->_glow.g, pPtySky.get()->_glow.b, pPtySky.get()->_glow.a);
    _horizon->getSingleValue(pPtySky->_horizon);
    double angle = 0.0;
    _angle->getSingleValue(angle);
    pPtySky->_angle = Core::deg2rad(angle);
    _roof->getSingleValue(pPtySky->_roof);
    _sphericity->getSingleValue(pPtySky->_sphericity);
    pPtySky->_atInfinity = _atInfinity->isChecked();
    pPtySky->_isProcedural = _isProcedural->isChecked();
    _skyColor->getColorLinear(pPtySky->_skyColor);
    _sunColor->getColorLinear(pPtySky->_sunColor);
    pPtySky->_model = Renderer::ELightingModel(_model->selectedIndex());
    _intensity->getSingleValue(pPtySky->_intensity);
}
//-----------------------------------------------------------------------------
} // namespace EPI


text:
package com.alibaba.json.bvt.issue_2700;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import junit.framework.TestCase;

public class Issue2787 extends TestCase {
    public void test_for_issue() throws Exception {
        Model m = new Model();
        String str = JSON.toJSONString(m, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty);
        assertEquals("{\"value\":[]}", str);
    }

    public static class Model {
        public int[] value;
    }
}


text:
require 'spec_helper'
require 'whois/record/parser/whois.nic.fr.rb'

describe Whois::Record::Parser::WhoisNicFr, "property_nameservers_with_ipv4_and_ipv6.expected" do

  subject do
    file = fixture("responses", "whois.nic.fr/pm/property_nameservers_with_ipv4_and_ipv6.txt")
    part = Whois::Record::Part.new(:body => File.read(file))
    described_class.new(part)
  end

  describe "#nameservers" do
    it do
      subject.nameservers.should be_a(Array)
      subject.nameservers.should have(3).items
      subject.nameservers[0].should be_a(Whois::Record::Nameserver)
      subject.nameservers[0].name.should == "ns1.nic.fr"
      subject.nameservers[0].ipv4.should == "192.93.0.1"
      subject.nameservers[0].ipv6.should == "2001:660:3005:1::1:1"
      subject.nameservers[1].should be_a(Whois::Record::Nameserver)
      subject.nameservers[1].name.should == "ns2.nic.fr"
      subject.nameservers[1].ipv4.should == "192.93.0.4"
      subject.nameservers[1].ipv6.should == "2001:660:3005:1::1:2"
      subject.nameservers[2].should be_a(Whois::Record::Nameserver)
      subject.nameservers[2].name.should == "ns3.nic.fr"
      subject.nameservers[2].ipv4.should == "192.134.0.49"
      subject.nameservers[2].ipv6.should == "2001:660:3006:1::1:1"
    end
  end
end


text:
<?php
namespace observr\Subject\Emitter {
    interface EmitterInterface {
        public function getName();

        /**
         * Emit state
         */
        public function emit($e = null);

        /**
         * Alias for bind
         * @see bind
         */
        public function on(callable $callable);

        /**
         * adds callback to main event
         * @param callable $callable
         * @return \observr\Source
         */
        public function bind(callable $callable);

        /**
         * removes callback from main event
         * @param callable $callable
         * @return observr\Source
         */
        public function unbind(callable $callable);

        /**
         * creates source map
         * @param callable $callable
         * @return \observr\Source\Map
         */
        public function map(callable $callable);

        /**
         * creates source filter
         * @param callable $callable
         * @return \observr\Source\Filter
         */
        public function filter(callable $callable);

        /**
         * Alias for getName
         * @return string
         */
        public function __toString();
    }
}


text:
#include <Screen.h>
#include <Roster.h>
#include <Node.h>
#include <NodeInfo.h>
#include <Bitmap.h>
#include <Region.h>
#include <Messenger.h>
#include <MessageRunner.h>
#include <File.h>
#include <Font.h>
#include <Alert.h>

#include <ClassInfo.h>

#include <locale/Locale.h>

#include "PanelWindow.h"
#include "PanelWindowView.h"
#include "InnerPanel.h"
#include "BarApp.h"

#include "ResourceSet.h"
#include "icons.h"

#include "tracker_private.h"

#include <stdio.h>
#include <strings.h>
#include <malloc.h>

#include <Debug.h>

#include <Catalog.h>
#include <Locale.h>

#define B_TRANSLATION_CONTEXT "panel-window"

#define _MNITEM_W 4
#define _MNITEM_H 4
#define TASK_BAR_MIME_SIG "application/x-vnd.Be-TSKB "

TPanelWindow::TPanelWindow()
	: BWindow( BRect( 0, 0, 24, 24 ), "Dock", B_NO_BORDER_WINDOW_LOOK, B_FLOATING_ALL_WINDOW_FEEL, B_NOT_MOVABLE | B_NOT_CLOSABLE | B_NOT_ZOOMABLE | B_NOT_MINIMIZABLE | B_NOT_RESIZABLE | B_WILL_ACCEPT_FIRST_CLICK | B_AVOID_FOCUS, B_ALL_WORKSPACES ),
	 fPreferencesWindow(NULL)
{
	fAutoHide = false;
	fHideEffectDelay = kWindowHidderAnimationStaleSpeed;

	fIsVisible = true;

	fHidderTimer = 0;

	fAlmostHidding = false;
	fHidderAnimationCurrentFrame = kWindowHidderNumberFrames;
	SetShowHideLimit( 0.f );

	BMessage msg;
	BFile settings( "/boot/home/config/settings/dock_settings", B_READ_ONLY );

	fTeamListView = 0;

	if ( msg.Unflatten( &settings ) == B_OK && msg.FindInt32("SettingsVersion") > 0 )
	{
		BMessage dock_settings, *dockb = 0;
		if ( msg.FindMessage( "dock", &dock_settings ) == B_OK )
			dockb = &dock_settings;

		fTeamListView = (TPanelWindowView*)TPanelWindowView::Instantiate( dockb );
	}
	else
	{
		// first time using
		(new BAlert( B_TRANSLATE("First Time"), B_TRANSLATE("This is your first time running Dockbert so we'll give you a small introduction to it.\nBy now there should be a small window in the bottom of your screen with some icons, that's Dockbert.\nWe'll now give you a small info about each icon, from left to right:\n- The trash, drag files to it to move them to trash, left clicking it opens the trash window, right clicking shows you a handy menu\n-The workspaces, left click to forward a workspace, right click to backward a workspace, the middle button gives you a list of the workspaces\n-The clock, right click it for options\n-The Tracker, right click the tracker for the tracker menu, with some useful options\n-The Be menu, right click it to see the Be Menu\n-the other two icons are shortcuts, read the readme for aditional information"), B_TRANSLATE("Ok thanks!")))->Go(0);
	}

	if ( !fTeamListView )
		fTeamListView = new TPanelWindowView();

	AddChild( fTeamListView );

	// force resize
	fTeamListView->ChangedSize(0);

	ResizeTo( fTeamListView->Bounds().Width(), fTeamListView->Bounds().Height() );

	if ( fTeamListView->WhereAmI() == kLocationTop || fTeamListView->WhereAmI() == kLocationBottom )
	{
		if ( Bounds().Height() < 40 )
			ResizeBy( 0, 40 - Bounds().Height() );
	}
	else
	{
		if ( Bounds().Width() < 40 )
			ResizeBy( 0, 40 - Bounds().Width() );
	}

/*	BMessenger self(this);
	BList teamList;
	TBarApp::Subscribe(self, &teamList);

	int32 count = teamList.CountItems();
	for (int i = 0; i < count; i++) {
		BarTeamInfo *barInfo = (BarTeamInfo *)teamList.ItemAt(i);

		if ( ( barInfo->flags & B_BACKGROUND_APP ) == 0 && strcasecmp( barInfo->sig, TASK_BAR_MIME_SIG ) != 0 )
			fTeamListView->AddTeam( barInfo->teams, barInfo->icon, barInfo->name, barInfo->sig );
	}*/

	BList teamList;
	be_roster->GetAppList( &teamList );

	int32 count = teamList.CountItems();
	for ( int i=0; i < count; i++ )
	{
		app_info appinfo;
		if ( be_roster->GetRunningAppInfo( (team_id)teamList.ItemAt(i), &appinfo ) == B_OK
			 && ( appinfo.flags & B_BACKGROUND_APP ) == 0
			 && strcasecmp( appinfo.signature, TASK_BAR_MIME_SIG ) )
			fTeamListView->AddTeam( appinfo.team, appinfo.signature, appinfo.ref );
	}

	CenterCorrectly();

	Show();

	rename_thread( Thread(), THREAD_NAME );
}

TPanelWindow::~TPanelWindow()
{
	if ( fHidderTimer )
		delete fHidderTimer;
	SaveSettings();
}

void TPanelWindow::MessageReceived( BMessage *message )
{
	switch ( message->what )
	{
	case B_ENTERED_VIEW:
		ShowHide(true);
		break;
	case B_EXITED_VIEW:
		ShowHide(false);
		break;
	case B_SOME_APP_LAUNCHED:
		{
			BList *teams = NULL;
			message->FindPointer("teams", (void **)&teams);

			BBitmap *icon = NULL;
			message->FindPointer("icon", (void **)&icon);

			const char *sig;
			if (message->FindString("sig", &sig) == B_OK
				&&strcasecmp(sig, TASK_BAR_MIME_SIG) == 0) {
				delete teams;
				delete icon;
				break;
			}

			uint32 flags;
			if (message->FindInt32("flags", ((int32*) &flags)) == B_OK
				&& (flags & B_BACKGROUND_APP) != 0) {
				delete teams;
				delete icon;
				break;
			}

			const char *name = NULL;
			message->FindString("name", &name);

			fTeamListView->AddTeam(teams, icon, strdup(name), strdup(sig));
			break;
		}
	case B_SOME_APP_QUIT:
		{
			team_id team = -1;
			message->FindInt32("team", &team);
			fTeamListView->RemoveTeam(team);

			break;
		}
	case kDockbertPreferences:
            ShowPreferencesWindow();
            break;
	case msg_AddTeam:
		{
			const char *sig = message->FindString("sig");
			team_id team = message->FindInt32("team");

			BList *list = new BList;
			list->AddItem( (void*) team );

			fTeamListView->AddTeam(list, 0, 0, strdup(sig));

			break;
		}
	case msg_RemoveTeam:
		{
			team_id team = message->FindInt32("team");
			fTeamListView->RemoveTeam(team);

			break;
		}
	case kPanelWindowViewTimer:
		{
			fTeamListView->MessageReceived( message );
			break;
		}
	case kPanelWindowHidderTimer:
		{
			if ( !DoShowHideFrame() )
			{
				delete fHidderTimer;
				fHidderTimer = 0;
			}
			break;
		}
	case kPrepareWindowHidder:
		{
			fTeamListView->DebugCall( 15, "TPanelWindow::MessageReceived(): kPrepareWindowHidder" );
			bigtime_t time = fHiddingPipe.Pop();
			bigtime_t now = system_time();
			if ( (time <= now) && fAlmostHidding )
			{
				fIsVisible = false;
				fAlmostHidding = false;
				if ( fHidderTimer )
					delete fHidderTimer;
				fHidderTimer = new MESSAGERUNNER(  BMessenger(this),
									new BMessage(kPanelWindowHidderTimer),
									kWindowHidderAnimationSpeed );
			}
			else
				fTeamListView->DebugCall( 15, "\tkPrepareWindowHidder was invalid" );
			break;
		}
	case 'sett':
	{
		fTeamListView->MessageReceived( message );
		break;
	}
	case 'nmcl':
	{
		fTeamListView->MessageReceived(message);
		break;
	}
	case 'flsh':
	{
		fTeamListView->MessageReceived(message);
		break;
	}
	case kInnelPanelTimerMessage:
	{
		void *ptr;
		if ( message->FindPointer( "panel_target", &ptr ) == B_OK )
		{
			TInnerPanel *panel = static_cast<TInnerPanel*> ( ptr );
			if ( panel )
			{
				panel->TimerFrame();
			}
		}
		break;
	}
	default:
		BWindow::MessageReceived(message);
		break;
	}
}

void TPanelWindow::FrameResized(float /* width */, float /* height */ )
{
	CenterCorrectly();
}

void TPanelWindow::WorkspaceActivated(int32 /* workspace */, bool flag)
{
	if (flag) CenterCorrectly();
	fTeamListView->WorkspaceChanged();
}

extern property_info _dock_property_list[];

// do DockView's detection here so we dont have to specify another specifier
BHandler *TPanelWindow::ResolveSpecifier( BMessage *message, int32 index, BMessage *specifier, int32 what, const char *property )
{
	BPropertyInfo prop_info( _dock_property_list );
	if ( prop_info.FindMatch( message, index, specifier, what, property ) >= 0 )
		return fTeamListView;
	if ( !strcasecmp( property, "tab" ) )
		return fTeamListView;

	return BWindow::ResolveSpecifier( message, index, specifier, what, property );
}

status_t TPanelWindow::GetSupportedSuites( BMessage *message )
{
	fTeamListView->GetDockbertSuites( message );
	return BWindow::GetSupportedSuites( message );
}

void TPanelWindow::ScreenChanged( BRect /* frame */, color_space /* mode */ )
{
	CenterCorrectly();
}

void TPanelWindow::CenterCorrectly()
{
	int loc = fTeamListView->WhereAmI();

	BRect screenFrame( BScreen(B_MAIN_SCREEN_ID).Frame() );
	BPoint mpt;

	if ( loc == kLocationTop || loc == kLocationBottom )
	{
		mpt.x = screenFrame.Width() /2 - Frame().Width() /2;
		if ( loc == kLocationTop )
			mpt.y = 0;
		else
			mpt.y = screenFrame.Height() - Frame().Height();
	}
	else if ( loc == kLocationLeft || loc == kLocationRight )
	{
		mpt.y = screenFrame.Height() / 2 - Frame().Height() / 2;
		if ( loc == kLocationLeft )
			mpt.x = 0;
		else
			mpt.x = screenFrame.Width() - Frame().Width();
	}

	if ( fAutoHide )
	{
		if ( loc == kLocationTop )
		{
			mpt.y = Frame().Height() * kWindowHidderFrames[fHidderAnimationCurrentFrame] - Frame().Height();
			if ( mpt.y < 1 )
				mpt.y = 1;
		}
		else if ( loc == kLocationBottom )
		{
			mpt.y = Frame().Height() * kWindowHidderFrames[kWindowHidderNumberFrames-fHidderAnimationCurrentFrame] - Frame().Height() + screenFrame.Height();
			if ( mpt.y > (screenFrame.Height()-1) )
				mpt.y = screenFrame.Height()-1;
		}
		else if ( loc == kLocationLeft )
		{
			mpt.x = Frame().Width() * kWindowHidderFrames[fHidderAnimationCurrentFrame] - Frame().Width();
			if ( mpt.x < 1 )
				mpt.x = 1;
		}
		else if ( loc == kLocationRight )
		{
			mpt.x = Frame().Width() * kWindowHidderFrames[kWindowHidderNumberFrames-fHidderAnimationCurrentFrame] - Frame().Width() + screenFrame.Width();
			if ( mpt.x > (screenFrame.Width()-1) )
				mpt.x = screenFrame.Width()-1;
		}

	}

	MoveTo( mpt );
}

void TPanelWindow::ShowHide(bool flag)
{
	fTeamListView->DebugCall( 15, "TPanelWindow::ShowHide( fAutoHide:%s, flag:%s, fIsVisible: %s, fAlmostHidding: %s )", fAutoHide?"true":"false", flag?"true":"false", fIsVisible?"true":"false", fAlmostHidding?"true":"false" );

	if (fAutoHide)
	{
		if ( !flag )
		{
			if ( fIsVisible )
			{
				fAlmostHidding = true;
				new MESSAGERUNNER( BMessenger(this), new BMessage(kPrepareWindowHidder), fHideEffectDelay, 1 );
				bigtime_t time = system_time()+fHideEffectDelay;
				fHiddingPipe.Push(time);
			}
		}
		else
		{
			fHiddingPipe.Pop();
			fAlmostHidding = false;
			fIsVisible = true;
			if ( fHidderTimer )
				delete fHidderTimer;
			fHidderTimer = new MESSAGERUNNER(  BMessenger(this),
								new BMessage(kPanelWindowHidderTimer),
								kWindowHidderAnimationSpeed );
		}
	}
}

void TPanelWindow::SaveSettings()
{
	BMessage msg;
	BMessage dock_settings;

	Lock();

	if ( fTeamListView->Archive( &dock_settings ) == B_OK )
		msg.AddMessage( "dock", &dock_settings );

	BFile settings( "/boot/home/config/settings/dock_settings", B_READ_WRITE | B_CREATE_FILE);

	msg.AddInt32( "SettingsVersion", 1 );

	msg.Flatten( &settings );
	printf("Save settings\n");

	Unlock();
}

bool TPanelWindow::DoShowHideFrame()
{
	int loc = fTeamListView->WhereAmI();

	BRect screenFrame( BScreen(B_MAIN_SCREEN_ID).Frame() );
	BPoint mpt;

	if ( fIsVisible )
		fHidderAnimationCurrentFrame++;
	else
		fHidderAnimationCurrentFrame--;

	if ( fHidderAnimationCurrentFrame < fLastShowHideFrame || fHidderAnimationCurrentFrame > kWindowHidderNumberFrames )
	{
		if ( fHidderAnimationCurrentFrame < fLastShowHideFrame )
			fHidderAnimationCurrentFrame = fLastShowHideFrame;
		if ( fHidderAnimationCurrentFrame > kWindowHidderNumberFrames )
			fHidderAnimationCurrentFrame = kWindowHidderNumberFrames;
		return false;
	}

	if ( loc == kLocationTop )
	{
		mpt.x = Frame().left;
		mpt.y = Frame().Height() * kWindowHidderFrames[fHidderAnimationCurrentFrame] - Frame().Height();
		if ( mpt.y < 1 )
			mpt.y = 1;
	}
	else if ( loc == kLocationBottom )
	{
		mpt.x = Frame().left;
		mpt.y = Frame().Height() * kWindowHidderFrames[kWindowHidderNumberFrames-fHidderAnimationCurrentFrame] - Frame().Height() + screenFrame.Height();
		if ( mpt.y > (screenFrame.Height()-1) )
			mpt.y = screenFrame.Height()-1;
	}
	else if ( loc == kLocationLeft )
	{
		mpt.x = Frame().Width() * kWindowHidderFrames[fHidderAnimationCurrentFrame] - Frame().Width();
		mpt.y = Frame().top;
		if ( mpt.x < 1 )
			mpt.x = 1;
	}
	else if ( loc == kLocationRight )
	{
		mpt.x = Frame().Width() * kWindowHidderFrames[kWindowHidderNumberFrames-fHidderAnimationCurrentFrame] - Frame().Width() + screenFrame.Width();
		mpt.y = Frame().top;
		if ( mpt.x > (screenFrame.Width()-1) )
			mpt.x = screenFrame.Width()-1;
	}

	MoveTo( mpt );

	return true;
}

void TPanelWindow::ForceHide()
{
	ShowHide(false);
}

void TPanelWindow::DockChangedPlaces( int32 prev )
{
	int32 loc = fTeamListView->WhereAmI();

	if ( (loc == kLocationTop || loc == kLocationBottom) && ( prev == kLocationLeft || prev == kLocationRight ) )
	{
		ResizeTo( Bounds().Height(), Bounds().Width() );
	}
	if ( (loc == kLocationLeft || loc == kLocationRight) && ( prev == kLocationTop || prev == kLocationBottom ) )
	{
		ResizeTo( Bounds().Height(), Bounds().Width() );
	}

	CenterCorrectly();
}

void TPanelWindow::SetAutoHide( bool b )
{
	if ( fAutoHide != b )
	{
		if ( b )
			fAutoHide = true;
		ShowHide(!b);
		if ( !b )
			fAutoHide = false;
	}
}

void TPanelWindow::SetHideEffectDelay( int newvalue )
{
	fHideEffectDelay = newvalue;
}

void TPanelWindow::SetShowHideLimit( float f )
{
	fLastShowHideFrame = (int) ((float)kWindowHidderNumberFrames * f);
}

TMessageRunner::TMessageRunner( BMessenger messenger, BMessage *message, bigtime_t interval, int count )
	: fMessenger(messenger), fMessage(message), fInterval(interval), fCount(count)
{
	fThreadID = spawn_thread( _thread_instance, "TMessageRunner", B_NORMAL_PRIORITY, this );
	resume_thread( fThreadID );
}

TMessageRunner::~TMessageRunner()
{
	lock.Lock();
	kill_thread(fThreadID);
	delete fMessage;
}

status_t TMessageRunner::InitCheck()
{
	return fThreadID >= 0 ? B_OK : B_ERROR;
}

void TMessageRunner::SetInterval( bigtime_t delta )
{
	fInterval = delta;
}

void TMessageRunner::Loop()
{
	while ( fCount == -1 || fCount > 0 )
	{
		snooze( fInterval );
		lock.Lock();
		fMessenger.SendMessage( fMessage );
		lock.Unlock();
		if ( fCount != -1 )
			fCount--;
	}
}

int32 TMessageRunner::_thread_instance( void *p )
{
	((TMessageRunner*)p)->Loop();
	return 0;
}

void
TPanelWindow::ShowPreferencesWindow()
{
       if (fPreferencesWindow)
               fPreferencesWindow->Activate();
       else {
               fPreferencesWindow = new PreferencesWindow(BRect(0, 0, 320, 240));
               fPreferencesWindow->Show();
       }
}


text:
import React from 'react';
import Relay from 'react-relay';

import 'babel/polyfill';
import styles from './Button.css';
import Spinner from '../Spinner/Spinner';

class Button extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    let content = this.props.loading ? <Spinner /> : (
        {this.props.text}
       )
    return (

        {content}

    );
  }
}

export default Relay.createContainer(Button, {
  fragments: {}
});


text:
 My Account

                <form method="post" name="userform">

                        Name
                        <input type="text" id="name" class="form-control" ng-model="vm.user.name" disabled="true" />

                        Username
                        <input type="text" id="username" class="form-control" ng-model="vm.user.username"
                            disabled="true" ng-required="true" />

                        Password
                        <input type="password" id="password" class="form-control" ng-model="vm.user.password"
                            ng-required="true" />

                        <button class="btn btn-primary" ng-click="vm.saveUser(userform)">Update</button>

                </form>


text:
var settings = require('./settings')();

casper.test.begin('Testing Map (User Frontend)', 1, function(test) {
    casper.start(settings.frontendUrl);

    casper.waitUntilVisible('cg-map', function then(){
        test.assertVisible('cg-map', 'Map is visible');
        // TODO: Add meaningful tests here.
    }, function timeout() {
        test.fail('Could not find element with tag "cg-map"');
    });

    casper.run(function(){
        test.done();
    })
});


text:
const jsf = require('json-schema-faker');

const faker = require('faker');

const data = require('./lib/shemas');
const server = require('./lib/server');
const config = require('./lib/config');
const { ok, notFound } = require('./lib/responces');

jsf.extend('faker', () => faker);

// TODO: в роутер
const response = (req) => {
  const parsedUrl = data.parseUrl(req.url);
  // FIXME: гавно
  const shema = data.getAllShemas().filter(el => parsedUrl.indexOf(el.path) !== -1)[0];

  if (!shema) {
    return Promise.resolve(null);
  }

  return jsf.resolve(shema)
    .then(res => JSON.stringify(res, null, 2));
};
// TODO: в роутер
const isFavicon = req => req.url === '/favicon.ico';

server.start(config, (req, res) => {
  if (req.method === 'OPTIONS' || isFavicon(req)) {
    return ok(res);
  }
  return response(req)
    .then((json) => {
      if (!json) {
        if (server.isProxy()) {
          return server.proxyReq(req, res)
            .catch(error => notFound(res, error));
        }
        return notFound(res);
      }
      return ok(res, json);
    });
});


text:
---
layout: post
title: Generating BitStamp Signature in PHP
author: Fred Muya
---

This post will describe how to create the signature required by the BitStamp API for private calls to the API.

In the BitStamp [docs](https://www.bitstamp.net/api/){:target="_blank"}, they've shown how to do this in Python:

{% highlight python %}
import hmac, hashlib
message = nonce + customer_id + api_key
signature = hmac.new(API_SECRET, msg=message, digestmod=hashlib.sha256).hexdigest().upper()
{% endhighlight %}

In PHP, this is made possible by the [`hash_hmac`](http://php.net/manual/en/function.hash-hmac.php){:target="_blank"} function.

This is the function I'm using to do this in PHP

{% highlight php %}
<?php

/**
 * Generates the signature required by Bitstamp API
 */
function generateBitstampSignature($nonce)
{
    $customerID = '123456';
    $bitstampApiKey = 'apikey';
    $bitstampApiSecret = 'apisecret';
    $message = $nonce . $customerID . $bitstampApiKey;

    return strtoupper(hash_hmac('sha256', $message, $bitstampApiSecret));
}
{% endhighlight %}

I hope this saves someone a few seconds somewhere ;)


text:
package com.lightplus;

import android.content.Context;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.RelativeLayout.LayoutParams;

import com.nineoldandroids.view.ViewPropertyAnimator;

public class LightControlFragment extends Fragment {
	private final static String EXTRA_MODE = "mode";
	private final static String EXTRA_ON = "on";
	int mCurrentMode;
	boolean mOn;
	TransitionDrawable mDrawable;
	ImageButton mBulb;

	// Empty constructor required
	public LightControlFragment() {
	}

	/**
	 * Create a new instance, providing the current light mode as an argument.
	 */
	static LightControlFragment newInstance(Context cxt, int mode, boolean on) {
		LightControlFragment fragment = (LightControlFragment) LightControlFragment.instantiate(cxt,
				LightControlFragment.class.getName());

		Bundle args = new Bundle();
		args.putInt(EXTRA_MODE, mode);
		args.putBoolean(EXTRA_ON, on);
		fragment.setArguments(args);

		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		mCurrentMode = getArguments().getInt(EXTRA_MODE);
		mOn = getArguments().getBoolean(EXTRA_ON);

		switch (mCurrentMode) {
		case R.id.mode_viewfinder:
			return inflater.inflate(R.layout.viewfinder, container, false);
		default:
		case R.id.mode_blackout:
			return inflater.inflate(R.layout.black, container, false);
		}
	}

	@Override
	public void onResume() {

		switch (mCurrentMode) {
		case R.id.mode_blackout:
			mBulb = (ImageButton) getActivity().findViewById(R.id.button_black);
			Animation fadeOut = AnimationUtils.loadAnimation(getActivity(), R.anim.fade_out);
			mBulb.startAnimation(fadeOut);
			break;
		case R.id.mode_viewfinder:
			mBulb = (ImageButton) getActivity().findViewById(R.id.button_bulb);

			break;
		}

		mDrawable = (TransitionDrawable) mBulb.getDrawable();
		mDrawable.setCrossFadeEnabled(true);
		if (mOn) {
			mDrawable.startTransition(0);
		}

		PreviewSurface surface = (PreviewSurface) getActivity().findViewById(R.id.surface);
		if (mCurrentMode == R.id.mode_viewfinder) {
			surface.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		} else {
			surface.setLayoutParams(new LayoutParams(1, 1));
		}

		super.onResume();
	}

	@Override
	public void onStop() {
		stopLightControl();
		super.onStop();
	}

	@Override
	public void onDestroyView() {
		stopLightControl();
		super.onDestroyView();
	}

	private void stopLightControl() {
		switch (mCurrentMode) {
		case R.id.mode_viewfinder:
			// kill any ongoing transition so it's not still finishing when we resume
			mDrawable.resetTransition();
			break;
		}
	}

	public void toggleLightControl(boolean on) {
		if (on) {
			mDrawable.startTransition(200);
		} else {
			mDrawable.reverseTransition(200);
		}
	}

	public void animHideButton(int height) {
		ViewPropertyAnimator animator = ViewPropertyAnimator.animate(mBulb);
		animator.translationY(height).setDuration(400);

	}

	public void animShowButton() {
		ViewPropertyAnimator animator = ViewPropertyAnimator.animate(mBulb);
		animator.translationY(0).setDuration(400);

	}

}


text:
package com.whamu2.android.aichat.db;

import android.content.ContentValues;
import android.content.Context;

import com.tencent.wcdb.Cursor;
import com.tencent.wcdb.SQLException;
import com.tencent.wcdb.database.SQLiteDatabase;
import com.whamu2.android.aichat.bean.MinuteItem;

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

/**
 * @author Suming
 * @date 2017/11/2 11:00
 * @Description ChatOperateHelper : 聊天数据库操作辅助类
 */

public final class ChatDBFunction {
    private static final String TAG = ChatDBFunction.class.getSimpleName();

    /**
     * CHAT_LIST 列定义
     */
    private final String[] DB_COLUMNS = new String[]{"id", "category", "content", "type", "date"};
    private ChatDatabaseHelper mDatabaseHelper;

    public ChatDBFunction(Context c) {
        mDatabaseHelper = new ChatDatabaseHelper(c);
    }

    /**
     * 是否已有数据
     *
     * @params
     * @date 2017/11/2 11:14
     */
    public boolean hasDB() {
        int index = 0;
        Cursor cursor = null;
        SQLiteDatabase db = null;
        try {
            db = mDatabaseHelper.getReadableDatabase();
            cursor = db.query(ChatDatabaseHelper.TABLE_NAME, new String[]{"COUNT(id)"}, null, null, null, null, null);
            if (cursor.moveToFirst()) {
                index = cursor.getInt(0);
            }
            if (index > 0) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (null != cursor) {
                cursor.close();
            }
            if (null != db) {
                db.close();
            }
        }
        return false;
    }

    /**
     * 初始化表
     *
     * @params [id, category, content, type]
     * @date 2017/11/2 14:30
     */
    public void initializeTable(int id, int category, String content, String type, long date) {
        SQLiteDatabase db = null;

        try {
            db = mDatabaseHelper.getWritableDatabase();
            db.beginTransaction();
            db.execSQL("insert into " +
                    ChatDatabaseHelper.TABLE_NAME +
                    " (id, category, content, type) values (" + id + ", " + category + ", " + content + ", " + type + "," + date + ")");

            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
    }

    /**
     * 查询数据库中所有数据
     *
     * @params
     * @date 2017/11/2 11:17
     */
    public List<MinuteItem> getAllMessage() {
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = mDatabaseHelper.getReadableDatabase();
            cursor = db.query(ChatDatabaseHelper.TABLE_NAME, DB_COLUMNS, null, null, null, null, null);

            if (cursor.getCount() > 0) {
                List<MinuteItem> data = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    data.add(parseItem(cursor));
                }
                return data;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return new ArrayList<>();
    }

    /**
     * 查询一条数据
     *
     * @params [id]
     * @date 2017/11/2 11:56
     */
    public MinuteItem getTargetItem(int id) {
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = mDatabaseHelper.getReadableDatabase();
            // select * from CHAT_LIST where id = ?
            cursor = db.query(ChatDatabaseHelper.TABLE_NAME, DB_COLUMNS,
                    "id = ?",
                    new String[]{String.valueOf(id)},
                    null, null, null);
            MinuteItem item = null;
            while (cursor.moveToNext()) {
                item = parseItem(cursor);
            }
            return item;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return null;
    }

    /**
     * 获取实体类
     *
     * @params [cursor]
     * @date 2017/11/2 11:22
     */
    private MinuteItem parseItem(Cursor cursor) {
        MinuteItem item = new MinuteItem();
        item.setId(cursor.getInt(cursor.getColumnIndex("id")));
        item.setCategory(cursor.getInt(cursor.getColumnIndex("category")));
        item.setContent(cursor.getString(cursor.getColumnIndex("content")));
        item.setType(cursor.getString(cursor.getColumnIndex("type")));
        item.setDate(cursor.getLong(cursor.getColumnIndex("date")));
        return item;
    }

    /**
     * 新增一条数据
     *
     * @params [id, category, content, type]
     * @date 2017/11/2 11:23
     */
    public boolean insertMessage(int id, int category, String content, String type, long date) {
        SQLiteDatabase db = null;

        try {
            db = mDatabaseHelper.getWritableDatabase();
            db.beginTransaction();

            // insert into CHAT_LIST (category, content, type) values (?, ?, ?);
            ContentValues contentValues = new ContentValues();
            contentValues.put("id", id);
            contentValues.put("category", category);
            contentValues.put("content", content);
            contentValues.put("type", type);
            contentValues.put("date", date);
            db.insertOrThrow(ChatDatabaseHelper.TABLE_NAME, null, contentValues);

            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    /**
     * 删除一条数据
     *
     * @params [id]
     * @date 2017/11/2 11:41
     */
    public boolean deleteMessage(int id) {
        SQLiteDatabase db = null;

        try {
            db = mDatabaseHelper.getWritableDatabase();
            db.beginTransaction();

            // delete from CHAT_LIST where id = ?
            db.delete(ChatDatabaseHelper.TABLE_NAME, "id = ?", new String[]{String.valueOf(id)});
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    /**
     * 修改一条数据
     *
     * @params [id, content, type]
     * @date 2017/11/2 11:41
     */
    public boolean updateMessage(int id, String content, String type, long date) {
        SQLiteDatabase db = null;
        try {
            db = mDatabaseHelper.getWritableDatabase();
            db.beginTransaction();

            // update CHAT_LIST set content = ? where type = ?
            ContentValues contentValues = new ContentValues();
            contentValues.put("content", content);
            contentValues.put("type", type);
            contentValues.put("date", date);
            db.update(ChatDatabaseHelper.TABLE_NAME, contentValues, "id = ?", new String[]{String.valueOf(id)});
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    /**
     * 统计查询
     *
     * @params [category]
     * @date 2017/11/2 11:47
     */
    public List<MinuteItem> getTarget(String category) {
        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = mDatabaseHelper.getReadableDatabase();

            // select * from CHAT_LIST where category = ?
            cursor = db.query(ChatDatabaseHelper.TABLE_NAME, DB_COLUMNS,
                    "category = ?",
                    new String[]{category},
                    null, null, null);

            if (cursor.getCount() > 0) {
                List<MinuteItem> data = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    MinuteItem order = parseItem(cursor);
                    data.add(order);
                }
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return new ArrayList<>();
    }

    /**
     * 统计查询
     *
     * @params [category]
     * @date 2017/11/2 11:52
     */
    public int getTargetCount(String category) {
        int count = 0;

        SQLiteDatabase db = null;
        Cursor cursor = null;

        try {
            db = mDatabaseHelper.getReadableDatabase();
            // select count(id) from CHAT_LIST where category = ?
            cursor = db.query(ChatDatabaseHelper.TABLE_NAME,
                    new String[]{"COUNT(id)"},
                    "category = ?",
                    new String[]{category},
                    null, null, null);

            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return count;
    }

    /**
     * 分页查询
     *
     * @param limit  默认查询的数量
     * @param offset 跳过的行数
     * @return List<MinuteItem>
     */
    public List<MinuteItem> findLimit(int limit, int offset) {
        SQLiteDatabase db = null;
        Cursor cursor = null;
        try {
            db = mDatabaseHelper.getReadableDatabase();
            cursor = db.query(ChatDatabaseHelper.TABLE_NAME, DB_COLUMNS,
                    "limit = ?, offset = ?",
                    new String[]{String.valueOf(limit), String.valueOf(offset)},
                    null, null, null);
//        String sql = "select * from note order by _id desc limit ? offset ?";
//        cursor = db.rawQuery(sql, new String[]{String.valueOf(limit), String.valueOf(offset)});
            if (cursor.getCount() > 0) {
                List<MinuteItem> data = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    data.add(parseItem(cursor));
                }
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null) {
                db.close();
            }
        }
        return new ArrayList<>();
    }
}


text:
  <meta charset="utf-8">
  <title>Design Geschichte InfoVis</title>

Loading…


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Observ. mycol. (Lipsiae) 1: 100 (1796)

#### Original name
Russula sardonia var. citrina Pers., 1796

### Remarks
null


text:
import Modes from "../src/Modes.js";
export default Modes;


text:
package org.apache.asterix.dataflow.data.nontagged.serde;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import org.apache.asterix.om.base.AMutableYearMonthDuration;
import org.apache.asterix.om.base.AYearMonthDuration;
import org.apache.asterix.om.base.temporal.ADurationParserFactory;
import org.apache.asterix.om.base.temporal.ADurationParserFactory.ADurationParseOption;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.exceptions.HyracksDataException;

public class AYearMonthDurationSerializerDeserializer implements ISerializerDeserializer<AYearMonthDuration> {

    private static final long serialVersionUID = 1L;

    public static final AYearMonthDurationSerializerDeserializer INSTANCE = new AYearMonthDurationSerializerDeserializer();

    @SuppressWarnings("unchecked")
    private static final ISerializerDeserializer<AYearMonthDuration> yearMonthDurationSerde = AqlSerializerDeserializerProvider.INSTANCE
            .getSerializerDeserializer(BuiltinType.AYEARMONTHDURATION);
    private static final AMutableYearMonthDuration aYearMonthDuration = new AMutableYearMonthDuration(0);

    @Override
    public AYearMonthDuration deserialize(DataInput in) throws HyracksDataException {
        try {
            return new AYearMonthDuration(in.readInt());
        } catch (IOException e) {
            throw new HyracksDataException(e);
        }
    }

    @Override
    public void serialize(AYearMonthDuration instance, DataOutput out) throws HyracksDataException {
        try {
            out.writeInt(instance.getMonths());
        } catch (IOException e) {
            throw new HyracksDataException();
        }
    }

    public void parse(String durationString, DataOutput out) throws HyracksDataException {
        try {
            ADurationParserFactory.parseDuration(durationString, 0, durationString.length(), aYearMonthDuration,
                    ADurationParseOption.All);
            yearMonthDurationSerde.serialize(aYearMonthDuration, out);
        } catch (Exception e) {
            throw new HyracksDataException(e);
        }
    }

    public static int getYearMonth(byte[] data, int offset) {
        return AInt32SerializerDeserializer.getInt(data, offset);
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
StudyAgentChild
</TITLE>

<META NAME="keywords" CONTENT="gov.nih.nci.cabig.caaers.domain.StudyAgentChild interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

gov.nih.nci.cabig.caaers.domain

Interface StudyAgentChild

All Known Implementing Classes:
StudyAgentINDAssociation

public interface StudyAgentChild

The Interface StudyAgentChild.

Method Summary

 StudyAgent
getStudyAgent()

          Gets the study agent.

 void
setStudyAgent(StudyAgent agent)

          Sets the study agent.

Method Detail

setStudyAgent

void setStudyAgent(StudyAgent agent)

Sets the study agent.

Parameters:
agent - the new study agent

getStudyAgent

StudyAgent getStudyAgent()

Gets the study agent.

Returns:
the study agent

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?php
class UsersAddon extends CakeTestModel {
/**
 * Name
 *
 * @var string
 * @access public
 */
	public $name = 'UsersAddon';

/**
 * The return value of beforeSave() for the test model to test callbacks
 *
 * @var string
 * @access public
 */
	public $beforeSaveFalse = false;

/**
 * Behaviors to load with this model
 *
 * @var array $actsAs
 * @access public
 */
	public $actsAs = array(
		'Utils.List' => array(
			'positionColumn' => 'position',
			'scope' => 'user_id'));

/**
 * beforeSave callback
 *
 * @return boolean
 */
	public function beforeSave() {
		return $this->beforeSaveFalse;
	}

}

class ListTest extends CakeTestCase {
/**
 * Holds the instance of the model
 *
 * @var mixed $UsersAddon
 * @access public
 */
	public $UsersAddon = null;

/**
 * Fixtures associated with this test case
 *
 * @var array
 * @access public
 */
	public $fixtures = array('plugin.utils.users_addon');

/**
 * Method executed before each test
 *
 * @access public
 */
	public function startTest() {
		$this->UsersAddon = ClassRegistry::init('UsersAddon');
		$this->UsersAddon->Behaviors->attach('Utils.List', array(
			'positionColumn' => 'position',
			'scope' => 'user_id'));
	}

/**
 * Method executed after each test
 *
 * @return void
 * @access public
 */
	public function endTest() {
		unset($this->UsersAddon);
		ClassRegistry::flush();
	}

/**
 * Test for moving an item one step up
 *
 * @return void
 * @access public
 */
	public function testMoveUp() {
		$result = $this->UsersAddon->moveUp('149e7472-a9ab-11dd-be1d-00e018bfb339');
		$this->assertTrue($result);

		$result = $this->UsersAddon->moveUp('non-existing-uuid');
		$this->assertFalse($result);
	}

/**
 * Test for moving an item one step down
 *
 * @return void
 * @access public
 */
	public function testMoveDown() {
		$result = $this->UsersAddon->moveDown('149e7472-a9ab-11dd-be1d-00e018bfb339');
		$this->assertTrue($result);

		$result = $this->UsersAddon->moveDown('non-existing-uuid');
		$this->assertFalse($result);
	}

/**
 * Test for inserting an item at certain position
 *
 * @return void
 * @access public
 */
	public function testInsertAt() {
		$result = $this->UsersAddon->insertAt(1, '1857670e-a9ab-11dd-b579-00e018bfb339');
		$this->assertTrue($result);
	}

/**
 * Test to move an item to the bottom of the list
 *
 * @return void
 * @access public
 */
	public function testMoveToBottom() {
		$this->UsersAddon->moveToBottom('0fab7f82-a9ab-11dd-8943-00e018bfb339');
		$result = $this->UsersAddon->read('position', '0fab7f82-a9ab-11dd-8943-00e018bfb339');
		$this->assertEqual($result['UsersAddon']['position'], 3);
	}

/**
 * Test to move an item to the top of the list
 *
 * @return void
 * @access public
 */
	public function testMoveToTop() {
		$this->UsersAddon->moveToTop('1857670e-a9ab-11dd-b579-00e018bfb339');
		$result = $this->UsersAddon->read('position', '1857670e-a9ab-11dd-b579-00e018bfb339');
		$this->assertEqual($result['UsersAddon']['position'], 1);
	}

/**
 * Test to check if an item is the first in the list
 *
 * @return void
 * @access public
 */
	public function testIsFirst() {
		$result = $this->UsersAddon->isFirst('0fab7f82-a9ab-11dd-8943-00e018bfb339');
		$this->assertTrue($result);

		$result = $this->UsersAddon->isFirst('1857670e-a9ab-11dd-b579-00e018bfb339');
		$this->assertFalse($result);
	}

/**
 * Test to check if an item is the last in the list
 *
 * @return void
 * @access public
 */
	public function testIsLast() {
		$result = $this->UsersAddon->isLast('1857670e-a9ab-11dd-b579-00e018bfb339');
		$this->assertTrue($result);

		$result = $this->UsersAddon->isLast('0fab7f82-a9ab-11dd-8943-00e018bfb339');
		$this->assertFalse($result);
	}

/**
 * Test to disable/enabled callbacks
 *
 * @return void
 * @access public
 */
	public function testCallbacks() {
		$this->UsersAddon->Behaviors->detach('Utils.List');
		$this->UsersAddon->Behaviors->attach('Utils.List', array(
			'positionColumn' => 'position',
			'scope' => 'user_id',
			'callbacks' => false,
			'validate' => false));
		$this->UsersAddon->beforeSaveFalse = false;
		$result = $this->UsersAddon->moveDown('149e7472-a9ab-11dd-be1d-00e018bfb339');
		$this->assertTrue($result);
	}

}
?>


text:
/**
 *
 */
package com.icss.hit.component;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Administrator
 *
 */
public class StrutsActionFilter implements Filter{

    public void init(FilterConfig config) throws ServletException {

    }

    public void destroy() {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {

    	HttpServletRequest re = (HttpServletRequest)request;
        HttpServletResponse rp = (HttpServletResponse)response;
        String url = re.getRequestURI();

        HttpSession session = re.getSession();
        // ÅųýµÇ½ÑéÖ¤Ò³
        if(url.indexOf("Login.do") > -1
        		|| url.indexOf("login.jsp") > -1
        		|| url.indexOf("newFolder.jsp") > -1
        		|| url.indexOf("progressbar.jsp") > -1
        		|| url.indexOf("progressdetail.jsp") > -1){
        	chain.doFilter(request, response);
        }
        else if( url.indexOf(".do") > -1 && session.getAttribute("UserId") == null ){
        	request.getRequestDispatcher("login.jsp").forward(request, response);
        }
        else if(url.indexOf(".jsp") > -1 ){
        	request.getRequestDispatcher("login.jsp").forward(request, response);
        }else{
        	chain.doFilter(request, response);
        }
    }
}


text:
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   FragTrap.cpp                                       :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: ncoden <ncoden@student.42.fr>              +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2015/06/18 11:38:14 by ncoden            #+#    #+#             */
/*   Updated: 2015/06/22 13:24:20 by ncoden           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include <string>
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include "FragTrap.hpp"

unsigned int const	FragTrap::_maxHitPoints = 100;
unsigned int const	FragTrap::_maxEnergyPoints = 100;
unsigned int const	FragTrap::_armorDamageReduction = 5;

unsigned int const	FragTrap::meleeAttackDamage = 30;
unsigned int const	FragTrap::rangedAttackDamage = 20;

int						FragTrap::_attack_number = 5;
unsigned int (FragTrap::*FragTrap::_attacks[])(std::string const &target) = {
	&FragTrap::clapInTheBox,
	&FragTrap::laserInferno,
	&FragTrap::torgueFiesta,
	&FragTrap::pirateShipMode,
	&FragTrap::oneShotWonder
};

FragTrap::FragTrap(std::string name): _name(name)
{
	srand(time(NULL));
	this->_hitPoints = _maxHitPoints;
	this->_energyPoints = _maxEnergyPoints;
	this->_level = 1;
	std::cout << "Booting sequence complete. Hello! I am your new steward bot. Designation: " << _name
		<< ", Hyperion Robot, Class C. Please adjust factory settings to meet your needs before deployment."
		<< std:: endl;
}

FragTrap::FragTrap(FragTrap const &src)
{
	*this = src;
	std::cout << "Booting sequence complete. Hello! I am your new steward bot. Designation: " << _name
		<< ", Hyperion Robot, Class C. Please adjust factory settings to meet your needs before deployment."
		<< std:: endl;
}

FragTrap::~FragTrap(void)
{
	std::cout << "I'M DEAD I'M DEAD OHMYGOD I'M DEAD!" << std::endl;
}

FragTrap		&FragTrap::operator=(FragTrap const	&rhs)
{
	if (this != &rhs)
	{
		this->_name = rhs._name;
		this->_hitPoints = rhs._hitPoints;
		this->_energyPoints = rhs._energyPoints;
		this->_level = rhs._level;
	}
	return (*this);
}

void			FragTrap::rangedAttack(std::string const &target)
{
	std::cout << "FR4G-TP <" << this->_name
		<< "> attacks <" << target
		<< "> at range, causing <"
		<< this->rangedAttackDamage << "> points of damage !" << std::endl;
}

void			FragTrap::meleeAttack(std::string const	&target)
{
	std::cout << "FR4G-TP <" << this->_name
		<< "> attacks <" << target
		<< "> at range, causing <" << this->meleeAttackDamage
		<< "> points of damage !" << std::endl;
}

void			FragTrap::takeDamage(unsigned int amount)
{
	if (this->_hitPoints == 0)
		std::cout << "Just stop already, I'm DEAD !!!!!!!" << std::endl;
	amount -= _armorDamageReduction;
	if (amount > this->_hitPoints)
		amount = this->_hitPoints;
	this->_hitPoints -= amount;
	std::cout << "FR4G-TP <" << _name
		<< "> took " << amount
		<< " damage and now has " << this->_hitPoints
		<< " hitPoints." << std::endl;
}

void			FragTrap::beRepaired(unsigned int amount)
{
	if (this->_energyPoints >= amount)
	{
		if (this->_hitPoints + amount > 100)
			amount = 100 - this->_hitPoints;
		this->_energyPoints -= amount;
		this->_hitPoints += amount;
		std::cout << "FR4G-TP <" << this->_name
			<< "> was repaired for " << amount
			<< " hitPoints and lost the same energy amount, he now has " << this->_hitPoints
			<< " hitPoints and " <<	this->_energyPoints
			<< " energy points" << std::endl;
	}
	else
		std::cout << "I'M GOING TO BE FULL HEALTH !!!!!! Oh shit, out of energy .." << std::endl;
}

unsigned int	FragTrap::vaulthunter_dot_exe(std::string const &target)
{
	int			random;

	if (this->_energyPoints >= 25)
	{
		this->_energyPoints -= 25;
		random = rand() % _attack_number;
		return ((this->*_attacks[random])(target));
	}
	else
		std::cout << "I'm out of fuel for the big random attack !" << std::endl;
	return (0);
}

unsigned int	FragTrap::clapInTheBox(std::string const &target)
{
	std::cout << "FR4G-TP <" << this->_name
		<< "> use the random attack ClapInTheBox, he hold a bomb and rush like a kamikaze on <" << target
		<< ">" << std::endl;
	return (30);
}

unsigned int	FragTrap::laserInferno(std::string const &target)
{
	std::cout << "FR4G-TP <" << this->_name
		<< "> use the random attack LaserInferno, he now shoots laser from his eyes <"
		<< target << ">" << std::endl;
	return (50);
}

unsigned int	FragTrap::torgueFiesta(std::string const &target)
{
	std::cout << "FR4G-TP <" << this->_name
		<< "> use the random attack torgueFiesta, NOW GO BLOW SOME SH*T UP ON <"
		<< target << ">" << std::endl;
	std::cout << "DID YOU KNOW THAT NINETY-SEVEN PERCENT OF ALL LIVING THINGS ON PANDORA AREN'T EXPLODING RIGHT NOW? THAT'S BULLSH*T, BUY TORGUE!" << std::endl;
	return (50);
}

unsigned int	FragTrap::pirateShipMode(std::string const &target)
{
	std::cout << "FR4G-TP <" << this->_name
		<< "> use the random attack pirateShipMode on <"
		<< target << ">, that's a shitty attack."
		<< std::endl;
	return(15);
}

unsigned int	FragTrap::oneShotWonder(std::string const &target)
{
	std::cout << "FR4G-TP <" << this->_name
		<< "> use the random attack oneShotWonder on <"
		<< target << ">, meat confetti!"
		<< std::endl;
	return(70);
}

std::string		&FragTrap::getName(void)
{
	return (this->_name);
}


text:
@interface UIImage (momentOrientation)
- (id)imageAdjustedToMatchScreenOrientation;
@end