text:
<?php
namespace DF\Auth;

use \Entity\User;

class Instance
{
    protected $_adapter;
    protected $_session;
    protected $_user = NULL;
    protected $_masqueraded_user = NULL;

    public function __construct()
    {
        $this->_session = $this->getSession();
    }

    public function getSession()
    {
        $class_name = strtolower(str_replace(array('\\', '_'), array('', ''), get_called_class()));
        return \DF\Session::get('auth_'.$class_name.'_user');
    }

    public function login()
    {
        if ($this->isLoggedIn() || php_sapi_name() == 'cli')
            return true;
        else
            return $this->authenticate();
    }

    public function authenticate()
    {
        return false;
    }

    public function logout($destination = NULL, $unset_session = true)
    {
        unset($this->_session->identity);
        unset($this->_session->user_id);
        unset($this->_session->masquerade_user_id);

        if ($unset_session)
            @session_unset();

        if (method_exists($this->_adapter, 'logout'))
            $this->_adapter->logout($destination);
    }

    public function isLoggedIn()
    {
        if (DF_IS_COMMAND_LINE)
            return false;

        $user = $this->getUser();
        return ($user instanceof User);
    }

    public function getLoggedInUser($real_user_only = FALSE)
    {
        if ($this->isMasqueraded() && !$real_user_only)
            return $this->getMasquerade();
        else
            return $this->getUser();
    }

    public function getUser()
    {
        if ($this->_user === NULL)
        {
            $user_id = (int)$this->_session->user_id;

            if ($user_id == 0)
            {
                $this->_user = FALSE;
                return false;
            }

            $user = User::find($user_id);
            if ($user instanceof User)
            {
                $this->_user = $user;
            }
            else
            {
                unset($this->_session->user_id);
                $this->_user = FALSE;
                $this->logout();

                throw new \DF\Exception('Invalid user!');
            }
        }

        return $this->_user;
    }

    public function setUser(User $user)
    {
        // Prevent any previous identity from being used.
        unset($this->_session->identity);

        session_regenerate_id(TRUE);

        $this->_session->user_id = $user->id;

        $this->_user = $user;
        return true;
    }

    public function getAdapter()
    {
        return $this->_adapter;
    }
    public function setAdapter($adapter)
    {
        $this->_adapter = $adapter;
    }
    public function setAdapterOptions($options)
    {
        if (method_exists($this->_adapter, 'setOptions'))
            $this->_adapter->setOptions($options);
    }

    public function exists($response = null)
    {
        $user_id = (int)$this->_session->user_id;
        $user = User::find($user_id);
        return ($user instanceof User);
    }

    public function getIdentity()
    {
        return $this->_session->identity;
    }
    public function setIdentity($identity)
    {
        $this->_session->identity = $identity;
    }
    public function clearIdentity()
    {
        unset($this->_session->identity);
    }

    /**
     * Masquerading
     */

    public function masqueradeAsUser($user_info)
    {
        if (!($user_info instanceof User))
            $user_info = User::getRepository()->findOneByUsername($user_info);

        $this->_session->masquerade_user_id = $user_info->id;
        $this->_masqueraded_user = $user_info;
    }

    public function endMasquerade()
    {
        unset($this->_session->masquerade_user_id);
        $this->_masqueraded_user = null;
    }

    public function getMasquerade()
    {
        return $this->_masqueraded_user;
    }

    public function isMasqueraded()
    {
        if (!$this->isLoggedIn())
        {
            $this->_masqueraded_user = FALSE;
            return NULL;
        }

        if ($this->_masqueraded_user === NULL)
        {
            if (!$this->_session->masquerade_user_id)
            {
                $this->_masqueraded_user = FALSE;
            }
            else
            {
                $mask_user_id = (int)$this->_session->masquerade_user_id;
                if ($mask_user_id != 0)
                    $user = User::find($mask_user_id);
                else
                    $user = NULL;

                if ($user instanceof User)
                {
                    $this->_masqueraded_user = $user;
                }
                else
                {
                    unset($this->_session->user_id);
                    unset($this->_session->masquerade_user_id);

                    $this->_masqueraded_user = FALSE;
                }
            }
        }

        return $this->_masqueraded_user;
    }
}


text:
using System;
using JetBrains.Annotations;
using SpeedSlidingTrainer.Core.Model;

namespace SpeedSlidingTrainer.Application.Events
{
    public sealed class SolveCompleted
    {
        public SolveCompleted([NotNull] SolveStatistics statistics)
        {
            if (statistics == null)
            {
                throw new ArgumentNullException(nameof(statistics));
            }

            this.Statistics = statistics;
        }

        [NotNull]
        public SolveStatistics Statistics { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE OverloadedStrings #-}
module FinishCmd (
  finishCmd, finishCmdOpts
  ) where

-- standard libraries

import Data.Text (Text)
import qualified Data.Text as T
import Text.Printf
-- import System.Exit
-- import Control.Monad
import Data.Time
import Data.Maybe (mapMaybe, isJust, fromJust)
-- import Data.Either (either)
--
-- -- friends
import GetOpt
import Time
import Errors
import RecordSet
import ParseOpts
--
import Record (Record)
import qualified Record as R

--
-- | Flags for the "start" command
--
data FinishCmdFlag =
    FinishCmdTime UTCTime

--
-- Given a UTCTime (to determine what day it is) and a TimeZone returns option descriptions
-- for the start command
--
finishCmdOpts :: ZonedTime -> [OptDescr (Either String FinishCmdFlag)]
finishCmdOpts zt =
    [ Option "t" ["time"] (OptArg timeToFinishCmd "time") "finish at time" ]
  where
    timeToFinishCmd :: Maybe String -> Either String FinishCmdFlag
    timeToFinishCmd = maybe (Left "You have not provided a time argument.")
                            (either Left (Right . FinishCmdTime) . parseTimeFlag zt)

finishCmd :: ZonedTime -> [String] -> IO ()
finishCmd zt args = do
  let (opts, nonOpts, errors) = getOptEither Permute (finishCmdOpts zt) args
  exitWithErrorIf' (length errors > 0) (unlines errors)
  exitWithErrorIf (length nonOpts > 0) (printf "Unknown parameters '%s'" (show nonOpts))
  rs <- readRecordSet
  exitWithErrorIf (not . R.isCurrent $ rs) "There is no current task. Run 'task start'."
  let current = fromJust . R.current $ rs
  finish        <- getFinishTime opts
  exitWithErrorIf (R.crecStart current >= finish)
                  (printf "Finish time is the same as or before start time")
  rs' <- R.finishCurrent rs finish
  writeRecordSet rs'
  printf "Finishing current task '%s' at '%s'\n" (T.unpack $ R.crecDescr current)
         (prettyTime (zonedTimeZone zt) finish)

getFinishTime :: [FinishCmdFlag] -> IO UTCTime
getFinishTime flags
  | null utcTimes = getCurrentTime
  | otherwise     = return . head $ utcTimes
  where
    utcTimes            = mapMaybe f flags
    f (FinishCmdTime t) = Just t


text:
package com.vaadin.tests.integration;

import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.server.ClassResource;
import com.vaadin.server.LegacyApplication;
import com.vaadin.server.Resource;
import com.vaadin.ui.Label;
import com.vaadin.ui.LegacyWindow;
import com.vaadin.ui.Table;

public class IntegrationTestApplication extends LegacyApplication {

    @Override
    public void init() {
        LegacyWindow window = new LegacyWindow("Vaadin Application");
        setMainWindow(window);

        final Table table = new Table();
        table.addContainerProperty("icon", Resource.class, null);
        table.setItemIconPropertyId("icon");
        table.addContainerProperty("country", String.class, null);
        table.setRowHeaderMode(Table.ROW_HEADER_MODE_ICON_ONLY);
        table.setImmediate(true);
        table.setSelectable(true);
        table.setVisibleColumns(new Object[] { "country" });
        window.addComponent(table);

        Item item = table.addItem("FI");
        item.getItemProperty("icon").setValue(new ClassResource("fi.gif"));
        item.getItemProperty("country").setValue("Finland");
        item = table.addItem("SE");
        item.getItemProperty("icon").setValue(new FlagSeResource());
        item.getItemProperty("country").setValue("Sweden");

        final Label selectedLabel = new Label();
        table.addValueChangeListener(new ValueChangeListener() {
            @Override
            public void valueChange(ValueChangeEvent event) {
                selectedLabel.setValue(String.valueOf(table.getValue()));
            }
        });
        window.addComponent(selectedLabel);
    }
}


text:
class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :username, unique: true, null: false
      t.string :email, unique: true, null: false
      t.string :password_digest, null: false
      t.boolean :admin, default: false, null: false

      t.timestamps
    end
  end
end


text:
class GithubOrgReports::Models::Commit < Baza::Model
  has_one :User
  has_one :PullRequest
  has_many [
    [:CommitOrganizationLink, :commit_id]
  ]

  def scan
    hash = ob.data[:github_org_reports].scan_for_time_and_orgs(self[:text])

    #Parse organizations.
    hash[:orgs].each do |org|
      link = self.ob.get_or_add(:CommitOrganizationLink, {
        :organization_id => org.id,
        :commit_id => self.id
      })

      link[:time] = hash[:orgs_time][org.id][:secs]
    end

    #Parse time.
    self[:time] = hash[:secs]

    return nil
  end
end


text:
require 'spec_helper'

describe Ublisherp do

  let :section do
    Section.create!(name: "A section")
  end

  let :content_item do
    ContentItem.create!(section: section)
  end

  let :inherited_content_item do
    InheritedContentItem.create!(section: section)
  end

  let :tag do
    Tag.create!(name: "Cheese")
  end

  describe Ublisherp::Publishable do
    it 'caches the publisher' do
      pub = content_item.publisher.class
      expect(pub).to be Ublisherp::Publisher
    end

    it 'delegates #publish! to publisher' do
      content_item.publisher.should_receive(:publish!).once
      content_item.publish!
    end
  end

  describe Ublisherp::Publisher do

    let :publisher do
      content_item.publisher
    end

    def all_key_score
      $redis.zscore Ublisherp::RedisKeys.key_for_all(content_item),
                    Ublisherp::RedisKeys.key_for(content_item)
    end

    it 'sets something in a redis key for the content item' do
      expect($redis.get(Ublisherp::RedisKeys.key_for(content_item))).to be_nil

      content_item.publish!

      expect(
        $redis.get(Ublisherp::RedisKeys.key_for(content_item))).to eq(
        Ublisherp::Serializer.dump(content_item.as_publishable_with_associations)
      )
    end

    it 'adds something to the classes all sorted set when published' do
      expect(all_key_score).to be_nil

      content_item.publish!

      expect(all_key_score).to_not be_nil
    end

    it 'removes an item from redis when it is unpublished' do
      content_item.publish!
      content_item.unpublish!

      expect($redis.get(Ublisherp::RedisKeys.key_for(content_item))).to be_nil
    end

    it 'removes something to the classes all sorted set when unpublished' do
      content_item.publish!
      content_item.unpublish!

      expect(all_key_score).to be_nil
    end

    it 'adds an unpublished key to the gone_keys set' do
      content_item.publish!
      content_item.unpublish!

      expect($redis.sismember(
        Ublisherp::RedisKeys.gone,
        Ublisherp::RedisKeys.key_for(content_item))).to be_true
    end

    it "unpublishes dependent associations on unpublish" do
      content_item.publish!
      ci2 = content_item.dup
      ci2.save!
      ci2.publish!
      expect($redis.get(Ublisherp::RedisKeys.key_for(content_item))).
        to be_present
      expect($redis.get(Ublisherp::RedisKeys.key_for(ci2))).
        to be_present

      section.unpublish!
      expect($redis.get(Ublisherp::RedisKeys.key_for(content_item))).
        to_not be_present
      expect($redis.get(Ublisherp::RedisKeys.key_for(ci2))).
        to_not be_present
    end

    it 'runs after callbacks on publish' do
      content_item.should_receive(:before_publish_callback_test)
      content_item.should_receive(:before_first_publish_callback_test)
      content_item.should_receive(:after_publish_callback_test)
      content_item.should_receive(:after_first_publish_callback_test)
      content_item.should_receive(:before_add_to_stream_callback_test).
        at_least(:once)
      content_item.should_receive(:before_add_to_type_stream_callback_test).
        at_least(:once)
      content_item.should_receive(:after_add_to_stream_callback_test).
        at_least(:once)
      content_item.should_receive(:after_add_to_type_stream_callback_test).
        at_least(:once)
      content_item.should_receive(:before_first_add_to_stream_callback_test).
        at_least(:once)
      content_item.should_receive(
        :before_first_add_to_type_stream_callback_test).at_least(:once)
      content_item.should_receive(:after_first_add_to_stream_callback_test).
        at_least(:once)
      content_item.should_receive(:after_first_add_to_type_stream_callback_test).
        at_least(:once)
      content_item.should_not_receive(:after_remove_from_stream_callback_test)
      content_item.should_not_receive(
        :after_remove_from_type_stream_callback_test)
      content_item.publish!
    end

    it "only runs 'first' callbacks on first publish" do
      content_item.publish!
      content_item.should_not_receive(:before_first_publish_callback_test)
      content_item.should_not_receive(:after_first_publish_callback_test)
      content_item.should_not_receive(:before_first_add_to_stream_callback_test)
      content_item.should_not_receive(
        :before_first_add_to_type_stream_callback_test)
      content_item.should_not_receive(:after_first_add_to_stream_callback_test)
      content_item.should_not_receive(
        :after_first_add_to_type_stream_callback_test)
      content_item.publish!
    end

    it 'runs before callbacks on unpublish' do
      content_item.should_receive(:before_unpublish_callback_test)
      content_item.should_receive(:before_unpublish_commit_callback_test)
      content_item.should_receive(:after_unpublish_callback_test)
      content_item.unpublish!
    end

    it 'also publishes associated objects
        declared with publishes_associations' do
      content_item.tags << tag
      content_item.save!
      content_item.publish!

      expect($redis.get(Ublisherp::RedisKeys.key_for(tag))).to_not be_nil
      expect($redis.get(Ublisherp::RedisKeys.key_for(section))).to_not be_nil
    end

    it "unpublishes multiple missing associated objects when a new one is published" do

      tag2 = Tag.create!(name: "Bread")
      tag3 = Tag.create!(name: "Peaches")
      tag4 = Tag.create!(name: "Herring")
      tag5 = Tag.create!(name: "Ostrich")

      content_item.tags = [tag, tag2, tag3]
      content_item.save!
      content_item.publish!

      expect(Set.new($redis.smembers(
        Ublisherp::RedisKeys.key_for_associations(content_item, :tags)))).to \
        eq(Set.new([tag, tag2, tag3].map { |t|
          Ublisherp::RedisKeys.key_for(t)
        }))

      content_item.tags = [tag3, tag4, tag5]
      content_item.save!
      content_item.publish!

      expect(Set.new($redis.smembers(
        Ublisherp::RedisKeys.key_for_associations(content_item, :tags)))).to \
        eq(Set.new([tag3, tag4, tag5].map { |t|
          Ublisherp::RedisKeys.key_for(t)
        }))
    end

    it 'publishes a content item to a tag stream' do
      content_item.tags << tag
      content_item.save!
      content_item.publish!

      wrong_stream_key = Ublisherp::RedisKeys.key_for_stream_of(content_item,
                                                                :all)
      content_key = Ublisherp::RedisKeys.key_for(content_item)
      expect($redis.zcard(wrong_stream_key)).to eq(0)

      [tag, section].each do |o|
        stream_key = Ublisherp::RedisKeys.key_for_stream_of(o, :all)
        expect($redis.zrange(stream_key, 0, -1)).to eq([content_key])
      end
    end

    it 'adds each stream to the "in_streams" set for each item' do
      content_item.tags << tag
      content_item.save!

      stream_set_key = Ublisherp::RedisKeys.key_for_streams_set(content_item)

      expect($redis.scard(stream_set_key)).to eq(0)

      content_item.publish!

      stream_keys = [[tag, :all], [section, :all],
                     [section, :visible_content_items],
                     [section, :if_stream_in], [section, :unless_stream_in],
                     [section, :content_items]].map do |o|
        Ublisherp::RedisKeys.key_for_stream_of *o
      end
      stream_keys.concat [[ContentItem, :all], [ContentItem, :visible]].map { |o|
        Ublisherp::RedisKeys.key_for_type_stream_of *o
      }

      expect($redis.smembers(stream_set_key)).to match_array(stream_keys)
    end

    it 'unpublishes a content item from a tag stream
        and its "in streams" key' do
      content_item.tags << tag
      content_item.save!
      content_item.publish!
      content_item.unpublish!

      content_key = Ublisherp::RedisKeys.key_for(content_item)
      stream_set_key = Ublisherp::RedisKeys.key_for_streams_set(content_item)

      [[tag, :all], [section, :all], [section, :visible_content_items]].each do |o|
        stream_key = Ublisherp::RedisKeys.key_for_stream_of(*o)
        expect($redis.zrange(stream_key, 0, -1)).to eq([])
        expect($redis.scard(stream_set_key)).to eq(0)
      end
    end

    it "unpublishes from a stream when the item should no longer be in it" do
      expect(content_item.visible?).to be_true
      content_item.publish!

      content_key = Ublisherp::RedisKeys.key_for(content_item)
      stream_key = Ublisherp::RedisKeys.key_for_stream_of(section, :visible_content_items)
      streams_set_key = Ublisherp::RedisKeys.key_for_streams_set(content_item)

      expect($redis.zrange(stream_key, 0, -1)).to eq([content_key])
      expect($redis.sismember(streams_set_key, stream_key)).to be_true

      content_item.visible = false
      content_item.save!
      content_item.should_receive(:after_remove_from_stream_callback_test)
      content_item.publish!

      expect($redis.zrange(stream_key, 0, -1)).to eq([])
      expect($redis.sismember(streams_set_key, stream_key)).to be_false
    end

    it 'tracks associations and unpublishes itself from old ones' do

      t1 = Tag.new name: 'Tag 1'
      t2 = Tag.new name: 'Tag 2'

      content_item.tags << t1
      content_item.tags << t2
      content_item.save!

      content_item.publish!

      t1_stream_key =  Ublisherp::RedisKeys.key_for_stream_of(t1, :all)
      t2_stream_key = Ublisherp::RedisKeys.key_for_stream_of(t2, :all)
      section_stream_key = Ublisherp::RedisKeys.key_for_stream_of(section, :all)

      expect($redis.zcount(t1_stream_key,  '-inf', '+inf')).to eq(1)
      expect($redis.zcount(t2_stream_key, '-inf', '+inf')).to eq(1)
      expect($redis.zcount(section_stream_key, '-inf', '+inf')).to eq(1)

      content_item.tags = []
      content_item.tags << t2
      content_item.section = nil
      content_item.save!
      content_item.publish!

      expect($redis.zcount(t1_stream_key,  '-inf', '+inf')).to eq(0)
      expect($redis.zcount(t2_stream_key, '-inf', '+inf')).to eq(1)
      expect($redis.zcount(section_stream_key, '-inf', '+inf')).to eq(0)
    end

    it 'uses the given stream score if defined' do
      content_item.tags << tag
      content_item.save!

      score_should = content_item.ublisherp_stream_score

      content_item.publish!

      stream_key = Ublisherp::RedisKeys.key_for_stream_of(tag, :all)
      stream = $redis.zrangebyscore(stream_key, '-inf', '+inf', withscores: true)

      expect(stream.first.last).to eq(score_should)
    end

    it 'indexes a content item by its slug' do
      content_item.slug = 'a-crazy-badger'
      content_item.save!
      content_item.publish!
      content_item_key = Ublisherp::RedisKeys.key_for(content_item)

      index_key1 = Ublisherp::RedisKeys.key_for_index(content_item, :slug)
      expect($redis.smembers(index_key1)).to match_array([content_item_key])

      content_item.slug = 'a-hungry-snake'
      content_item.save!
      index_key2 = Ublisherp::RedisKeys.key_for_index(content_item, :slug)
      content_item.publish!

      expect($redis.smembers(index_key1)).to match_array([])
      expect($redis.smembers(index_key2)).to match_array([content_item_key])

      content_item.unpublish!
      expect($redis.smembers(index_key1)).to eq([])
      expect($redis.smembers(index_key2)).to eq([])
    end

    it 'also publishes an inherited model to the right stream' do
      inherited_content_item.save!
      inherited_content_item.publish!

      ici_key = Ublisherp::RedisKeys.key_for(inherited_content_item)
      stream_key = Ublisherp::RedisKeys.key_for_stream_of(section, :inherited_content_items)

      expect($redis.zrange(stream_key, 0, -1)).to match_array([ici_key])
    end

    it 'has the correct publishable associations for subclasses' do
      content_item.publish_association_attrs.to_a.
        should match_array(%i[section tags])
      inherited_content_item.publish_association_attrs.to_a.
        should match_array(%i[region section tags])
    end

    it "publishes a type stream of content items" do
      content_item.save!
      content_item.publish!
      content_item_key = Ublisherp::RedisKeys.key_for(content_item)

      stream_key = Ublisherp::RedisKeys.key_for_type_stream_of(ContentItem, :all)
      expect($redis.zrange(stream_key, 0, -1)).to eq([content_item_key])
    end

    it "publishes a visible content item to the visible content item type stream" do
      content_item.visible = true
      content_item.save!
      content_item.publish!
      content_item_key = Ublisherp::RedisKeys.key_for(content_item)

      stream_key = Ublisherp::RedisKeys.key_for_type_stream_of(ContentItem,
                                                               :visible)
      expect($redis.zrange(stream_key, 0, -1)).to eq([content_item_key])
    end

    it "publishes a visible content item to the visible content item type stream" do
      content_item.visible = false
      content_item.save!
      content_item.publish!
      content_item_key = Ublisherp::RedisKeys.key_for(content_item)

      stream_key = Ublisherp::RedisKeys.key_for_type_stream_of(ContentItem,
                                                               :visible)
      expect($redis.zrange(stream_key, 0, -1)).to eq([])
    end

  end
end


text:
from __future__ import unicode_literals

from django.db import models, migrations
import organizations.base
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Account',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(help_text='The name of the organization', max_length=200)),
                ('is_active', models.BooleanField(default=True)),
                ('monthly_subscription', models.IntegerField(default=1000)),
            ],
            options={
                'ordering': ['name'],
                'abstract': False,
            },
            bases=(organizations.base.UnicodeMixin, models.Model),
        ),
        migrations.CreateModel(
            name='AccountOwner',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('organization', models.OneToOneField(related_name='owner', to='accounts.Account')),
            ],
            options={
                'abstract': False,
            },
            bases=(organizations.base.UnicodeMixin, models.Model),
        ),
        migrations.CreateModel(
            name='AccountUser',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('user_type', models.CharField(default=b'', max_length=1)),
                ('organization', models.ForeignKey(related_name='organization_users', to='accounts.Account')),
                ('user', models.ForeignKey(related_name='accounts_accountuser', to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'ordering': ['organization', 'user'],
                'abstract': False,
            },
            bases=(organizations.base.UnicodeMixin, models.Model),
        ),
        migrations.AddField(
            model_name='accountowner',
            name='organization_user',
            field=models.OneToOneField(to='accounts.AccountUser'),
        ),
        migrations.AddField(
            model_name='account',
            name='users',
            field=models.ManyToManyField(related_name='accounts_account', through='accounts.AccountUser', to=settings.AUTH_USER_MODEL),
        ),
        migrations.AlterUniqueTogether(
            name='accountuser',
            unique_together=set([('user', 'organization')]),
        ),
    ]


text:
/*
For the purposes of this challenge, we define a binary search tree to be a binary tree with the following ordering properties:

The  value of every node in a node's left subtree is less than the data value of that node.
The  value of every node in a node's right subtree is greater than the data value of that node.
Given the root node of a binary tree, can you determine if it's also a binary search tree?

Complete the function in your editor below, which has  parameter: a pointer to the root of a binary tree. It must return a boolean denoting whether or not the binary tree is a binary search tree. You may have to write one or more helper functions to complete this challenge.

Note: We do not consider a binary tree to be a binary search tree if it contains duplicate values.

Input Format

You are not responsible for reading any input from stdin. Hidden code stubs will assemble a binary tree and pass its root node to your function as an argument.

Constraints

Output Format

You are not responsible for printing any output to stdout. Your function must return true if the tree is a binary search tree; otherwise, it must return false. Hidden code stubs will print this result as a Yes or No answer on a new line.

Sample Input

tree

Sample Output

Yes
Explanation

The tree in the diagram satisfies the ordering property for a Binary Search Tree, so we print Yes.
*/

/* Hidden stub code will pass a root argument to the function below. Complete the function to solve the challenge. Hint: you may want to write one or more helper functions.

The Node class is defined as follows:
    class Node {
        int data;
        Node left;
        Node right;
     }
*/
    boolean checkBST(Node root) {
        if (root == null) {
            return true;
        }

        return checkNode(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }

boolean checkNode(Node root, int min, int max) {
    if (root.left == null && root.right == null) {
            return true;
        }

        boolean left = root.left == null;
        boolean right = root.right == null;

        if (right || left) {
            return false;
        }

        if (root.data > root.left.data && root.left.data > min) {
            left = checkNode(root.left, min, root.data);
        }

        if (root.data < root.right.data && root.right.data < max) {
            right = checkNode(root.right, root.data, max);
        }

        return left && right;
}


text:
This template deploys a **SQL SERVER 2014 SP1 Virtual Machine** solution with all necessary components. It also enable Auto Patching feature.

`Tags: SQL Server, Auto Patching, SQL Server 2014 Enterprise`

## Solution overview and deployed resources

This is an overview of the solution

This template will create a SQL Server 2014 Enterprise edition with Auto Patching feature enabled:

+	A Virtual Network
+	Two Storage Accounts one is used for SQL Server VM, one for SQL Server VM Autobackup
+ 	One public IP address
+	One network interface
+	One network security group

## SQL Server IaaS Agent

A component that will be installed on the VM when features are enabled and this component is called SQL Server IaaS Agent. It is built in the form of Azure VM Extension meaning all the Azure VM Extension concepts are applicable making it perfect tool for the management of SQL in Azure VMs on scale. You can push this IaaS Agent to a number of VMs at once, you can configure, and you can remove or disable it as well.

## Auto Patching

Many customers told us that they would like to move their patching schedules off business hours. This feature enables you to do exactly this – define the maintenance window that would keep your patch installs in the range you have specified.

When you look on the settings available for the Automated Patching you could find you are familiar with those, because they mimic settings available from the Windows Update Agent (service that drives patching of your Windows machine). Settings are simple and powerful at the same time. All that you need to define to make sure patches are applied when you want is: day of the week, start of the maintenance window, and duration of the maintenance window. It relies on the Windows Update and the Microsoft Update infrastructure and installs any update that matches the 'Important' category for the machine.

This feature allows you to patch your Azure Virtual Machines in effective and predictable way even when those VMs are not joined to any domain and not controlled by any patching infrastructure

## Notable Parameters

|Name|Description|Example|
|:---|:---------------------|:---------------|
|sqlAutopatchingDayOfWeek|Patches installed day. Sunday to Saturday for a specific day; Everyday for daily Patches or Never to disable Auto Patching|Monday|
|sqlAutopatchingStartHour|Begin updates hour|22|
|sqlAutopatchingWindowDuration|Patches must be installed within this duration minutes.|60|


text:
  <md-toolbar class="md-tall md-accent">

#{{vm.currentPlayer.jerseyNumber}} {{vm.currentPlayer.name}}

        {{vm.currentPlayer.teamAbbr}} {{vm.currentPlayer.position}} | BYE {{vm.currentPlayer.byeWeek}}
        {{vm.currentPlayer.injuryGameStatus | limitTo:1}}

      <md-icon>announcement</md-icon>
      <md-icon>message</md-icon>

  </md-toolbar>
  <content layout="column" layout-padding>

Player Videos

    <md-grid-list
            md-cols-sm="4" md-cols-md="8" md-cols-gt-md="10"
            md-row-height="4:3"
            md-gutter="12px" md-gutter-gt-sm="8px">
      <md-grid-tile
              md-rowspan="1"
              md-colspan="1"
              ng-repeat="video in vm.currentPlayer.videos"
              ng-style="{ 'background-image': 'url(' + video.mediumPhotoUrl + ')' }"
              ng-click="vm.playVideo(video)">
        <md-tooltip>
          {{video.title}}
        </md-tooltip>
        <md-icon>play_circle_filled</md-icon>
      </md-grid-tile>
    </md-grid-list>
  </content>


text:
<?php

namespace Kunstmaan\GeneratorBundle\Command;

use Kunstmaan\GeneratorBundle\Generator\SearchPageGenerator;
use Kunstmaan\GeneratorBundle\Helper\GeneratorUtils;
use Kunstmaan\GeneratorBundle\Helper\Sf4AppBundle;
use Sensio\Bundle\GeneratorBundle\Command\GenerateDoctrineCommand;
use Sensio\Bundle\GeneratorBundle\Command\Validators;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\Kernel;

/**
 * Generates a SearchPage based on the KunstmaanNodeSearchBundle
 */
class GenerateSearchPageCommand extends GenerateDoctrineCommand
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setDefinition(
                array(
                    new InputOption('namespace', '', InputOption::VALUE_REQUIRED, 'The namespace to generate the SearchPage in. This option is deprecated when using this bundle with symfony 4.'),
                    new InputOption('prefix', '', InputOption::VALUE_OPTIONAL, 'The prefix to be used in the table names of the generated entities'),
                    new InputOption('createpage', null, InputOption::VALUE_NONE, 'If set, the task will generate data fixtures to populate your database with a search page'),
                )
            )
            ->setDescription('Generates a SearchPage based on KunstmaanNodeSearchBundle')
            ->setHelp(<<<'EOT'
The <info>kuma:generate:searchpage</info> command generates a SearchPage using the KunstmaanNodeSearchBundle and KunstmaanSearchBundle

<info>php bin/console kuma:generate:searchpage --namespace=Namespace/NamedBundle</info>

Use the <info>--prefix</info> option to add a prefix to the table names of the generated entities

<info>php bin/console kuma:generate:searchpage --namespace=Namespace/NamedBundle --prefix=demo_</info>

Add the <info>--createpage</info> option to create data fixtures to populate your database with a search page

<info>php bin/console kuma:generate:article --namespace=Namespace/NamedBundle --createpage</info>
EOT
            )
            ->setName('kuma:generate:searchpage');
    }

    /**
     * Executes the command.
     *
     * @param InputInterface  $input  An InputInterface instance
     * @param OutputInterface $output An OutputInterface instance
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $questionHelper = $this->getQuestionHelper();
        $questionHelper->writeSection($output, 'Search Page Generation');

        $prefix = $input->getOption('prefix');
        $createPage = $input->getOption('createpage');
        if (Kernel::VERSION_ID < 40000) {
            GeneratorUtils::ensureOptionsProvided($input, ['namespace']);

            $namespace = Validators::validateBundleNamespace($input->getOption('namespace'));
            $bundle = strtr($namespace, ['\\' => '']);

            $bundle = $this
                ->getApplication()
                ->getKernel()
                ->getBundle($bundle);
        } else {
            $bundle = new Sf4AppBundle($this->getContainer()->getParameter('kernel.project_dir'));
        }

        $rootDir = $this->getApplication()->getKernel()->getRootDir();

        $generator = $this->getGenerator($this->getApplication()->getKernel()->getBundle('KunstmaanGeneratorBundle'));
        $generator->generate($bundle, $prefix, $rootDir, $createPage, $output);

        $output->writeln(array(
                'Make sure you update your database first before you test the pagepart:',
                '    Directly update your database:          <comment>bin/console doctrine:schema:update --force</comment>',
                '    Create a Doctrine migration and run it: <comment>bin/console doctrine:migrations:diff && bin/console doctrine:migrations:migrate</comment>', )
        );

        if ($createPage) {
            $output->writeln('    New DataFixtures were created. You can load them via: <comment>bin/console doctrine:fixtures:load --fixtures=src/'.str_replace('\\', '/', $bundle->getNamespace()).'/DataFixtures/ORM/SearchPageGenerator/ --append</comment>');
        }

        $output->writeln('');

        return 0;
    }

    protected function interact(InputInterface $input, OutputInterface $output)
    {
        $questionHelper = $this->getQuestionHelper();
        $questionHelper->writeSection($output, 'Welcome to the SearchPage generator');

        $inputAssistant = GeneratorUtils::getInputAssistant($input, $output, $questionHelper, $this->getApplication()->getKernel(), $this->getContainer());

        if (Kernel::VERSION_ID >= 40000) {
            $inputAssistant->askForPrefix();

            return;
        }

        $inputAssistant->askForNamespace(array(
            '',
            'This command helps you to generate a SearchPage.',
            'You must specify the namespace of the bundle where you want to generate the SearchPage in.',
            'Use <comment>/</comment> instead of <comment>\\ </comment>for the namespace delimiter to avoid any problem.',
            '',
        ));

        $inputAssistant->askForPrefix();
    }

    protected function createGenerator()
    {
        return new SearchPageGenerator($this->getContainer()->get('filesystem'), '/searchpage', $this->getContainer()->getParameter('kernel.project_dir'));
    }
}


text:
package eu.ydp.empiria.player.client.module.object.impl;

public interface Video extends Media {
    public void setWidth(int width);

    public void setHeight(int height);

    public void setPoster(String url);
}


text:
package api;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import utils.APIUtils;

@Path("payment")
@Produces(MediaType.APPLICATION_JSON)
public class PaymentResource
{
	@Context
	HttpServletRequest request;

	@POST
	@Consumes(MediaType.WILDCARD)
	public String createPayment(String x)
	{
		try
		{
			//READ JSON
			JSONObject jsonObject = (JSONObject) JSONValue.parse(x);
			String amount = (String) jsonObject.get("amount");
			String fee = (String) jsonObject.get("fee");
			String sender = (String) jsonObject.get("sender");
			String recipient = (String) jsonObject.get("recipient");

			return APIUtils.processPayment(amount, fee, sender, recipient,x, request );
		}
		catch(NullPointerException e)
		{
			//JSON EXCEPTION
			//e.printStackTrace();
			throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_JSON);
		}
		catch(ClassCastException e)
		{
			//JSON EXCEPTION
			throw ApiErrorFactory.getInstance().createError(ApiErrorFactory.ERROR_JSON);
		}
	}

}


text:
if [ "$(basename "$PWD")" != 'nodenv' ]; then
  echo "Bootstrapping nodenv..."
  git clone https://github.com/nodenv/nodenv
  git clone https://github.com/nodenv/node-build nodenv/plugins/node-build
  git clone https://github.com/nodenv/nodenv-aliases nodenv/plugins/nodenv-aliases
  git clone https://github.com/nodenv/nodenv-package-json-engine nodenv/plugins/nodenv-package-json-engine
  git clone https://github.com/momo-lab/xxenv-latest nodenv/plugins/xxenv-latest
  echo "Building native extensions..."
  nodenv/src/configure
  make -C nodenv/src
fi


text:
package org.apache.solr.spelling;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.core.WhitespaceAnalyzer;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.spell.DirectSpellChecker;
import org.apache.lucene.search.spell.StringDistance;
import org.apache.lucene.search.spell.SuggestMode;
import org.apache.lucene.search.spell.SuggestWord;
import org.apache.lucene.search.spell.SuggestWordFrequencyComparator;
import org.apache.lucene.search.spell.SuggestWordQueue;
import org.apache.solr.common.params.ShardParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.SpellingParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.core.SolrCore;
import org.apache.solr.schema.FieldType;
import org.apache.solr.search.SolrIndexSearcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Spellchecker implementation that uses {@link DirectSpellChecker}
 *

 * Requires no auxiliary index or data structure.
 *

 * Supported options:
 *

 *
field: Used as the source of terms.
 *
distanceMeasure: Sets {@link DirectSpellChecker#setDistance(StringDistance)}.
 *       Note: to set the default {@link DirectSpellChecker#INTERNAL_LEVENSHTEIN}, use "internal".
 *
accuracy: Sets {@link DirectSpellChecker#setAccuracy(float)}.
 *
maxEdits: Sets {@link DirectSpellChecker#setMaxEdits(int)}.
 *
minPrefix: Sets {@link DirectSpellChecker#setMinPrefix(int)}.
 *
maxInspections: Sets {@link DirectSpellChecker#setMaxInspections(int)}.
 *
comparatorClass: Sets {@link DirectSpellChecker#setComparator(Comparator)}.
 *       Note: score-then-frequency can be specified as "score" and frequency-then-score
 *       can be specified as "freq".
 *
thresholdTokenFrequency: sets {@link DirectSpellChecker#setThresholdFrequency(float)}.
 *
minQueryLength: sets {@link DirectSpellChecker#setMinQueryLength(int)}.
 *
maxQueryFrequency: sets {@link DirectSpellChecker#setMaxQueryFrequency(float)}.
 *

 * @see DirectSpellChecker
 */
public class DirectSolrSpellChecker extends SolrSpellChecker {
  private static final Logger LOG = LoggerFactory.getLogger(DirectSolrSpellChecker.class);

  // configuration params shared with other spellcheckers
  public static final String COMPARATOR_CLASS = AbstractLuceneSpellChecker.COMPARATOR_CLASS;
  public static final String SCORE_COMP = AbstractLuceneSpellChecker.SCORE_COMP;
  public static final String FREQ_COMP = AbstractLuceneSpellChecker.FREQ_COMP;
  public static final String STRING_DISTANCE = AbstractLuceneSpellChecker.STRING_DISTANCE;
  public static final String ACCURACY = AbstractLuceneSpellChecker.ACCURACY;
  public static final String THRESHOLD_TOKEN_FREQUENCY = IndexBasedSpellChecker.THRESHOLD_TOKEN_FREQUENCY;

  public static final String INTERNAL_DISTANCE = "internal";
  public static final float DEFAULT_ACCURACY = 0.5f;
  public static final float DEFAULT_THRESHOLD_TOKEN_FREQUENCY = 0.0f;

  public static final String MAXEDITS = "maxEdits";
  public static final int DEFAULT_MAXEDITS = 2;

  // params specific to this implementation
  public static final String MINPREFIX = "minPrefix";
  public static final int DEFAULT_MINPREFIX = 1;

  public static final String MAXINSPECTIONS = "maxInspections";
  public static final int DEFAULT_MAXINSPECTIONS = 5;

  public static final String MINQUERYLENGTH = "minQueryLength";
  public static final int DEFAULT_MINQUERYLENGTH = 4;

  public static final String MAXQUERYFREQUENCY = "maxQueryFrequency";
  public static final float DEFAULT_MAXQUERYFREQUENCY = 0.01f;

  private DirectSpellChecker checker = new DirectSpellChecker();

  @Override
  public String init(NamedList config, SolrCore core) {
    LOG.info("init: " + config);
    String name = super.init(config, core);

    Comparator<SuggestWord> comp = SuggestWordQueue.DEFAULT_COMPARATOR;
    String compClass = (String) config.get(COMPARATOR_CLASS);
    if (compClass != null) {
      if (compClass.equalsIgnoreCase(SCORE_COMP))
        comp = SuggestWordQueue.DEFAULT_COMPARATOR;
      else if (compClass.equalsIgnoreCase(FREQ_COMP))
        comp = new SuggestWordFrequencyComparator();
      else //must be a FQCN
        comp = (Comparator<SuggestWord>) core.getResourceLoader().newInstance(compClass, Comparator.class);
    }

    StringDistance sd = DirectSpellChecker.INTERNAL_LEVENSHTEIN;
    String distClass = (String) config.get(STRING_DISTANCE);
    if (distClass != null && !distClass.equalsIgnoreCase(INTERNAL_DISTANCE))
      sd = core.getResourceLoader().newInstance(distClass, StringDistance.class);

    float minAccuracy = DEFAULT_ACCURACY;
    Float accuracy = (Float) config.get(ACCURACY);
    if (accuracy != null)
      minAccuracy = accuracy;

    int maxEdits = DEFAULT_MAXEDITS;
    Integer edits = (Integer) config.get(MAXEDITS);
    if (edits != null)
      maxEdits = edits;

    int minPrefix = DEFAULT_MINPREFIX;
    Integer prefix = (Integer) config.get(MINPREFIX);
    if (prefix != null)
      minPrefix = prefix;

    int maxInspections = DEFAULT_MAXINSPECTIONS;
    Integer inspections = (Integer) config.get(MAXINSPECTIONS);
    if (inspections != null)
      maxInspections = inspections;

    float minThreshold = DEFAULT_THRESHOLD_TOKEN_FREQUENCY;
    Float threshold = (Float) config.get(THRESHOLD_TOKEN_FREQUENCY);
    if (threshold != null)
      minThreshold = threshold;

    int minQueryLength = DEFAULT_MINQUERYLENGTH;
    Integer queryLength = (Integer) config.get(MINQUERYLENGTH);
    if (queryLength != null)
      minQueryLength = queryLength;

    float maxQueryFrequency = DEFAULT_MAXQUERYFREQUENCY;
    Float queryFreq = (Float) config.get(MAXQUERYFREQUENCY);
    if (queryFreq != null)
      maxQueryFrequency = queryFreq;

    checker.setComparator(comp);
    checker.setDistance(sd);
    checker.setMaxEdits(maxEdits);
    checker.setMinPrefix(minPrefix);
    checker.setAccuracy(minAccuracy);
    checker.setThresholdFrequency(minThreshold);
    checker.setMaxInspections(maxInspections);
    checker.setMinQueryLength(minQueryLength);
    checker.setMaxQueryFrequency(maxQueryFrequency);
    checker.setLowerCaseTerms(false);

    return name;
  }

  @Override
  public void reload(SolrCore core, SolrIndexSearcher searcher) throws IOException {}

  @Override
  public void build(SolrCore core, SolrIndexSearcher searcher) throws IOException {}

  @Override
  public SpellingResult getSuggestions(SpellingOptions options)
      throws IOException {
    LOG.debug("getSuggestions: " + options.tokens);

    SpellingResult result = new SpellingResult();
    float accuracy = (options.accuracy == Float.MIN_VALUE) ? checker.getAccuracy() : options.accuracy;

    for (Token token : options.tokens) {
      String tokenText = token.toString();
      Term term = new Term(field, tokenText);
      int freq = options.reader.docFreq(term);
      int count = (options.alternativeTermCount != null && freq > 0) ? options.alternativeTermCount: options.count;
      SuggestWord[] suggestions = checker.suggestSimilar(term, count,options.reader, options.suggestMode, accuracy);
      result.addFrequency(token, freq);

      // If considering alternatives to "correctly-spelled" terms, then add the
      // original as a viable suggestion.
      if (options.alternativeTermCount != null && freq > 0) {
        boolean foundOriginal = false;
        SuggestWord[] suggestionsWithOrig = new SuggestWord[suggestions.length + 1];
        for (int i = 0; i < suggestions.length; i++) {
          if (suggestions[i].string.equals(tokenText)) {
            foundOriginal = true;
            break;
          }
          suggestionsWithOrig[i + 1] = suggestions[i];
        }
        if (!foundOriginal) {
          SuggestWord orig = new SuggestWord();
          orig.freq = freq;
          orig.string = tokenText;
          suggestionsWithOrig[0] = orig;
          suggestions = suggestionsWithOrig;
        }
      }
      if(suggestions.length==0 && freq==0) {
        List<String> empty = Collections.emptyList();
        result.add(token, empty);
      } else {
        for (SuggestWord suggestion : suggestions) {
          result.add(token, suggestion.string, suggestion.freq);
        }
      }
    }
    return result;
  }

  @Override
  public float getAccuracy() {
    return checker.getAccuracy();
  }
  @Override
  public StringDistance getStringDistance() {
    return checker.getDistance();
  }
}


text:
package com.cloudera.flume.agent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cloudera.flume.agent.durability.WALCompletionNotifier;
import com.cloudera.flume.conf.FlumeConfiguration;
import com.cloudera.flume.conf.FlumeSpecException;
import com.cloudera.flume.conf.FlumeConfigData;
import com.cloudera.flume.handlers.endtoend.AckListener.Empty;
import com.cloudera.util.Clock;
import com.google.common.base.Preconditions;

/**
 * This manages heartbeating the node with the master, notifications of
 * configuration updates, and spawning/decommissioning of logical nodes.
 *
 * TODO (jon) rename to HeartbeatManager
 */
public class LivenessManager {
  static final Logger LOG = LoggerFactory.getLogger(LivenessManager.class);
  final long BACKOFF_MILLIS;

  MasterRPC master;
  LogicalNodeManager nodesman;
  HeartbeatThread t;
  final WALAckManager ackcheck;
  final WALCompletionNotifier walman;

  class RetryAckListener extends Empty {
    @Override
    public void end(String group) throws IOException {
      walman.toAcked(group);
    }

    @Override
    public void expired(String group) throws IOException {
      walman.retry(group);
    }
  };

  /**
   * Create a liveness manager with the specified managers.
   *
   * LogicalNodeManager is necessary for tracking physical/logical node
   * mappings. MasterRPC is the connection to the master, WALCompletionNotifier
   * is necessary for check on acks
   */
  public LivenessManager(LogicalNodeManager nodesman, MasterRPC master,
      WALCompletionNotifier walman) {
    Preconditions.checkNotNull(nodesman);
    Preconditions.checkNotNull(master);
    BACKOFF_MILLIS = FlumeConfiguration.get().getHeartbeatBackoff();
    this.walman = walman;
    this.nodesman = nodesman;
    this.master = master;
    this.t = new HeartbeatThread();
    this.ackcheck = new WALAckManager(master, new RetryAckListener(),
        FlumeConfiguration.get().getAgentAckedRetransmit());
  }

  /**
   * Checks against the master to get new physical nodes or to learn about
   * decommissioned logical nodes
   *
   * Invariant: There is always at least logical per physical node. When there
   * is one, it has the same name as the physical node.
   */
  public void checkLogicalNodes() throws IOException, InterruptedException {
    // TODO (jon) Make this a single batched rpc call instead of
    // multiple calls

    String physNode = nodesman.getPhysicalNodeName();
    // get logical nodes list for this node.
    List<String> lns = master.getLogicalNodes(physNode);
    if (!lns.contains(physNode)) {
      // physical node node present? make sure it stays around.
      lns = new ArrayList<String>(lns); // copy the unmodifiable list
      lns.add(physNode);
    }
    for (String ln : lns) {
      // a logical node is not present? spawn it.
      if (nodesman.get(ln) == null) {
        try {
          nodesman.spawn(ln, "null", "null");
        } catch (FlumeSpecException e) {
          LOG.error("This should never happen", e);
        }
      }
    }
    // Update the Chokeinformation for the ChokeManager

    FlumeNode.getInstance().getChokeManager().updateChokeLimitMap(
        master.getChokeMap(physNode));

    nodesman.decommissionAllBut(lns);
  }

  /**
   * Checks registered nodes to see if they need a new configuraiton.
   */
  public void checkLogicalNodeConfigs() throws IOException {
    // TODO (jon) batch all these rpc requests into one multi-part rpc
    // request.

    for (LogicalNode nd : nodesman.getNodes()) {
      boolean needsCfg = master.heartbeat(nd);
      if (needsCfg) {
        final FlumeConfigData data = master.getConfig(nd);
        if (data == null) {
          LOG.debug("Logical Node '" + nd.getName()
              + "' not configured on master");
        }
        final LogicalNode node = nd;
        // TODO This is quite gross, but prevents heartbeat from blocking
        new Thread("SpawningLogicalNode " + nd.getName()) {
          public void run() {
            node.checkConfig(data);
          }
        }.start();
      }
    }
  }

  /**
   * All the core functionality of a heartbeat accessible without having to be
   * in the heartbeat thread.
   */
  public void heartbeatChecks() throws IOException, InterruptedException {
    // these will call ensure open on the master
    checkLogicalNodes();

    checkLogicalNodeConfigs();

    // check for end to end acks.
    ackcheck.checkAcks(); // check for acks on master

    // check local ack ages. If too old, retry those event groups.
    ackcheck.checkRetry();

  }

  /**
   * This thread periodically contacts the master with a heartbeat.
   */
  class HeartbeatThread extends Thread {
    volatile boolean done = false;
    long backoff = BACKOFF_MILLIS;
    long backoffLimit = FlumeConfiguration.get().getNodeHeartbeatBackoffLimit();
    long heartbeatPeriod = FlumeConfiguration.get().getConfigHeartbeatPeriod();
    CountDownLatch stopped = new CountDownLatch(1);

    HeartbeatThread() {
      super("Heartbeat");
    }

    public void run() {
      try {
        while (!done) {
          try {
            heartbeatChecks();
            backoff = BACKOFF_MILLIS; // was successful, reset backoff

            Clock.sleep(heartbeatPeriod);

          } catch (Exception e) {
            backoff *= 2; // sleep twice as long
            backoff = backoff > backoffLimit ? backoffLimit : backoff;

            LOG.warn("Connection to master(s) failed, " + e.getMessage()
                + ". Backing off for " + backoff + " ms ");
            LOG.debug("Current master is " + master.toString(), e);

            try {
              master.close();
            } catch (IOException e1) {
              LOG.error("Failed when attempting to close master", e1);
            }

            Clock.sleep(backoff);
          }
        }

      } catch (InterruptedException e) {
        LOG.error("Heartbeat interrupted, this is not expected!", e);
      }
      stopped.countDown();
    }

  };

  /**
   * Starts the heartbeat thread and then returns.
   */
  public void start() {
    t.start();
  }

  public void stop() {
    CountDownLatch stopped = t.stopped;
    t.done = true;
    try {
      stopped.await();
    } catch (InterruptedException e) {
      LOG.error("Problem waiting for livenessManager to stop", e);
    }
  }

  public WALAckManager getAckChecker() {
    return ackcheck;
  }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

use kartik\date\DatePicker;
?>

    <?php $form = ActiveForm::begin(['action' => ['/promocode/promo-code/create-widget']]); ?>

                    <?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>

                    <?= $form->field($model, 'description')->textarea(); ?>

                    <?php
                    function KeyPromoGen(){
                        $key = md5(time());
                        $new_key = '';

                        for($i=1; $i <= 4; $i ++ ){
                            $new_key .= $key[$i];
                        }
                        return strtoupper($new_key);
                    }
                    if($model->isNewRecord) {
                        $code = KeyPromoGen();
                        $date = '';
                        $params = ['value' => $code];
                    } else {
                        $params = [];
                        if ($model->date_elapsed) {
                            $date = date('d.m.Y',strtotime($model->date_elapsed));
                        } else {
                            $date = '';
                        }
                    }
                    echo $form->field($model, 'code')->textInput($params) ?>

                    <?= $form->field($model, 'status')->dropDownList([
                        '1' => 'Активен',
                        '0' => 'Отключен',
                    ]);
                    ?>

                    <?= $form->field($model, 'type')->dropDownList([
                        'percent' => 'Процент скидки',
                        'quantum' => 'Сумма скидки',
                        'cumulative' => 'Накопительная скидка'
                    ],
                        [
                            'prompt' => 'Выберите тип скидки промокода:',
                            'class' => 'form-control promo-code-discount-type',
                        ])->hint('Выберите тип предоставляемой промокодом скидки')->label('Тип скидки промокода')
                    ?>

                    <?= $form->field($model, 'discount')->textInput()->hint('Задайте процент или сумму') ?>

            <div class="col-md-12 promocode-cumulative-form form-group <?= (empty($conditions) || ($model->type != 'cumulative')) ? 'hidden' : '' ?>">

                        <?php if (isset($conditions)) { ?>
                            <?php foreach ($conditions as $condition) { ?>

                                    <input class="form-control" name="Conditions[<?= $condition['id']?>][sumStart]" type="text" value="<?= $condition['sum_start'] ?>" placeholder="От"> -
                                    <input class="form-control" name="Conditions[<?= $condition['id']?>][sumStop]" type="text" value="<?= $condition['sum_stop'] ?>" placeholder="До">
                                    <input class="form-control" name="Conditions[<?= $condition['id']?>][percent]" type="text" style="width: 50px" value="<?= $condition['value'] ?>" placeholder="%">
                                        <span class="btn glyphicon glyphicon-remove remove-condition-btn" style="color: red;"
                                              data-role="remove-row"
                                              data-href="ajax-delete-condition"
                                              data-condition="<?= $condition['id']?>">

                            <?php }
                        } else { ?>

                                <input class="form-control" name="Conditions[C0][sumStart]" type="text"placeholder="От"> -
                                <input class="form-control" name="Conditions[C0][sumStop]" type="text"placeholder="До">
                                <input class="form-control" name="Conditions[C0][percent]" type="text" style="width: 50px"placeholder="%">

                        <?php } ?>

                        <button class="btn btn-primary add-cumulative-row">

                        </button>

                    <?= $form->field($model, 'date_elapsed')->widget(DatePicker::classname(), [
                        'language' => 'ru',
                        'type' => DatePicker::TYPE_COMPONENT_PREPEND,
                        'options' => [
                            'placeholder' => 'Дата истечения промокода',
                            'value' => $date,
                        ],
                        'removeButton' => false,
                        'pluginOptions' => [
                            'autoclose'=>true,
                            'format' => 'd.m.yyyy',
                        ],
                    ])->label('Дата истечения промокода')->hint('Выберите дату истечения срока действия промокода')
                    ?>

                    <?= $form->field($model, 'amount')->textInput()->label('Количество использований')->hint('Здесь задается количество использований промокода')
                    ?>

                <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success', 'data-role' => 'sendForm']) ?>

    <?php ActiveForm::end(); ?>


text:
layout:   post
author:   josh
title:    "Announcing cucumber-electron"
date:     2017-01-23 09:00:00
nav:      blog
---

# Announcing cucumber-electron

There's a new way to run cucumber-js 2.0.0 for anyone building browser
applications. It's called
[cucumber-electron](https://github.com/cucumber/cucumber-electron) and it's
available as an npm module that acts as a drop-in replacement for
cucumber-js itself, supporting the same features and command line options.

Cucumber-electron runs cucumber-js in [Electron](http://electron.atom.io/),
a framework for building desktop applications in web technologies. By running
features this way, your step definitions can `require` npm modules including
server-side libraries and node.js core modules _and_ use a browser DOM to
render HTML, all in the same (chromium renderer) process, with no transpile step.

This approach is a compelling alternative to using a frameworks like Selenium
WebDriver, which automate real browsers like Chrome and Firefox, or even tools
like PhantomJS which automate a headless virtual browser. Because there is only
one process, scenarios run much faster and debugging failures is significantly
simpler. It's also possible to write synchronous step definitions for
manipulating and asserting about the DOM, which tend to be more reliable and
easier to write than their asynchronous equivalents. Finally, cucumber-electron
can be launched in "headed mode" and the familiar chromium developer tools can
be used for interactive debugging of your web app.

![Screenshot](https://gist.github.com/joshski/a5c35da27f752ca542c2ac61b64b08c1/raw/3807cb18da8a4e6ea72b293ec738326bad11d0ee/cucumber-electron-screenshot.png "cucumber-electron screenshot")

It's already being used to drive the development of a few substantial projects
including [bbc-a11y](https://github.com/bbc/bbc-a11y), an accessibility linting
tool for web apps.

Try it on your web app project and let us know how you get on!


text:
package com.turlir.abakgists.gist;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.arellomobile.mvp.presenter.InjectPresenter;
import com.google.android.material.snackbar.Snackbar;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.turlir.abakgists.R;
import com.turlir.abakgists.base.BaseActivity;
import com.turlir.abakgists.model.GistModel;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import timber.log.Timber;

public class GistActivity extends BaseActivity implements GistView {

    private static final String EXTRA_GIST = "EXTRA_GIST";

    public static Intent getStartIntent(Context cnt, String id) {
        return new Intent(cnt, GistActivity.class).putExtra(EXTRA_GIST, id);
    }

    @InjectPresenter
    GistPresenter _presenter;

    @BindView(R.id.gist_act_root)
    ViewGroup root;

    @BindView(R.id.content_group)
    View content;

    @BindView(R.id.error)
    View error;

    @BindView(R.id.tv_login)
    TextView tvLogin;

    @BindView(R.id.iv_avatar)
    ImageView avatar;

    @BindView(R.id.et_desc)
    EditText desc;

    @BindView(R.id.et_note)
    EditText note;

    @BindView(R.id.btn_save)
    View btnSave;

    private ViewTreeObserver.OnGlobalLayoutListener mKeyboardListener =
            new ViewTreeObserver.OnGlobalLayoutListener() {
        static final int THRESHOLD = 200;
        @Override
        public void onGlobalLayout() {
            int heightDiff = root.getRootView().getHeight() - root.getHeight();
            if (heightDiff > dpToPx(getResources(), THRESHOLD)) {
                btnSave.setVisibility(View.GONE);
            } else {
                btnSave.setVisibility(View.VISIBLE);
            }
        }
        private float dpToPx(Resources res, float valueInDp) {
            DisplayMetrics metrics = res.getDisplayMetrics();
            return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gist);
        ButterKnife.bind(this);

        if (savedInstanceState == null) {
            String id = getIntent().getStringExtra(EXTRA_GIST);
            _presenter.load(id);
        }
        root.getViewTreeObserver().addOnGlobalLayoutListener(mKeyboardListener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.gist_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.gist_menu_delete:
                new AlertDialog.Builder(this)
                        .setTitle(R.string.last_chance)
                        .setMessage(R.string.do_you_want_to_delete)
                        .setPositiveButton(R.string.delete, (dialog, which) -> {
                            dialog.dismiss();
                            _presenter.delete();
                        })
                        .setNegativeButton(android.R.string.cancel, (dialog, which) -> {
                            dialog.dismiss();
                        })
                        .create()
                        .show();
                return true;
            default:
                return false;
        }
    }

    @Override
    public void onBackPressed() {
        if (!_presenter.isChange(desc.getText().toString(), note.getText().toString())) {
            super.onBackPressed();
        } else {
            new AlertDialog.Builder(this)
                    .setTitle(R.string.there_changes)
                    .setMessage(R.string.save_quest)
                    .setPositiveButton(R.string.save, (dialog, which) -> {
                        onClickSave();
                        dialog.dismiss();
                    })
                    .setNegativeButton(android.R.string.cancel, (dialog, which) -> {
                        dialog.dismiss();
                        super.onBackPressed();
                    })
                    .create()
                    .show();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        root.getViewTreeObserver().removeOnGlobalLayoutListener(mKeyboardListener);
    }

    @OnClick(R.id.btn_save)
    public void onClickSave() {
        if (_presenter.isChange(desc.getText().toString(), note.getText().toString())) {
            Timber.i("Внесены изменения, обновление БД");
            _presenter.transact(desc.getText().toString(), note.getText().toString());
        } else {
            Timber.i("Изменения не внесены");
        }
    }

    @OnClick(R.id.btn_web)
    public void onClickWeb() {
        Uri link = _presenter.insteadWebLink();
        startActivity(
                new Intent(Intent.ACTION_VIEW)
                        .setData(link)
        );
    }

    @Override
    public void onLoadSuccess(GistModel model) {
        applyContent(model);
    }

    @Override
    public void onLoadFailure() {
        supportStartPostponedEnterTransition();
        content.setVisibility(View.INVISIBLE);
        error.setVisibility(View.VISIBLE);
    }

    public void deleteSuccess() {
        finish();
    }

    public void deleteFailure() {
        Snackbar.make(root, R.string.fail_delete_gist, Snackbar.LENGTH_LONG).show();
    }

    public void updateSuccess() {
        super.onBackPressed();
    }

    private void applyContent(GistModel content) {
        Picasso.with(GistActivity.this)
                .load(content.ownerAvatarUrl)
                .fit()
                .error(R.drawable.ic_github)
                .placeholder(R.drawable.ic_github)
                .networkPolicy(NetworkPolicy.OFFLINE)
                .priority(Picasso.Priority.HIGH)
                .into(avatar);

        tvLogin.setText(content.login(getResources()));

        desc.setText(content.description);
        note.setText(content.note);

        supportStartPostponedEnterTransition();
    }
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Class de.general.json.JObject</title>
<meta name="date" content="2014-08-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
de.general.json.JObject

Uses of JObject in de.general.json

Methods in de.general.json that return JObject

Modifier and Type
Method and Description

JObject
JsonSerializer.deserialize(java.lang.String text)

JObject[]
JObject.getPropertyObjectList(java.lang.String propertyName)

Convenience method to retrieve data from a property referring to a string value.

JObject[]
JObject.getPropertyObjectList(java.lang.String[] propertyNamePath)

Convenience method to retrieve data from a property referring to a string value.

Methods in de.general.json with parameters of type JObject

Modifier and Type
Method and Description

static java.lang.String[]
JUtils.getStrArrayByPath(JObject obj,
                 java.lang.String path)

This method returns an array of Strings representing the information stored at the specified path within
 the specified object.

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
#include "config.h"

#include <stdarg.h>

#include "windef.h"
#include "winbase.h"
#include "wingdi.h"
#include "winuser.h"
#include "objbase.h"
#include "wine/debug.h"

#include "dplay8.h"
#include "dpnet_private.h"

WINE_DEFAULT_DEBUG_CHANNEL(dpnet);

HRESULT DPNET_CreateDirectPlay8Server(LPCLASSFACTORY iface, LPUNKNOWN punkOuter, REFIID riid, LPVOID *ppobj) {
  WARN("(%p, %s, %p): stub.\n", punkOuter, debugstr_guid(riid), ppobj);
  return CLASS_E_CLASSNOTAVAILABLE;
}


text:
from rx import Observer
from rx.internal import extensionmethod
from rx.internal.exceptions import ReEntracyException, CompletedException

class CheckedObserver(Observer):

    def __init__(self, observer):
        self._observer = observer
        self._state = 0  # 0 - idle, 1 - busy, 2 - done

    def on_next(self, value):
        self.check_access()
        try:
            self._observer.on_next(value)
        finally:
            self._state = 0

    def on_error(self, err):
        self.check_access()
        try:
            self._observer.on_error(err)
        finally:
            self._state = 2

    def on_completed(self):
        self.check_access()
        try:
            self._observer.on_completed()
        finally:
            self._state = 2

    def check_access(self):
        """Checks access to the observer for grammar violations.

        OnNext* (OnError | OnCompleted)?
        """

        if self._state == 1:
            raise ReEntracyException()
        if self._state == 2:
            raise CompletedException()
        if self._state == 0:
            self._state = 1

@extensionmethod(Observer)
def checked(self):
    """Checks access to the observer for grammar violations. This includes
    checking for multiple OnError or OnCompleted calls, as well as
    reentrancy in any of the observer methods. If a violation is detected,
    an Error is thrown from the offending observer method call.

    Returns an observer that checks callbacks invocations against the
    observer grammar and, if the checks pass, forwards those to the
    specified observer."""

    return CheckedObserver(self)


text:
EXEC sp_rename @objname = 'DataLog.PhenonmenonUOMID', @newname = 'PhenomenonUOMID', @objtype = 'COLUMN'
EXEC sp_rename @objname = 'Observation.PhenonmenonOfferingID', @newname = 'PhenomenonOfferingID', @objtype = 'COLUMN'
EXEC sp_rename @objname = 'Observation.PhenonmenonUOMID', @newname = 'PhenomenonUOMID', @objtype = 'COLUMN'
EXEC sp_rename @objname = 'Progress.PhenonmenonOfferingID', @newname = 'PhenomenonOfferingID', @objtype = 'COLUMN'
EXEC sp_rename @objname = 'SensorProcedure', @newname = 'Sensor'
EXEC sp_rename @objname = 'DataLog.SensorProcedureID', @newname = 'SensorID', @objtype = 'COLUMN'
EXEC sp_rename @objname = 'Observation.SensorProcedureID', @newname = 'SensorID', @objtype = 'COLUMN'
EXEC sp_rename @objname = 'Progress.SensorProcedureID', @newname = 'SensorID', @objtype = 'COLUMN'
--drop view [vSensorProcedure]
EXEC sp_rename @objname = 'DataSourceTransformation.SensorProcedureID', @newname = 'SensorID', @objtype = 'COLUMN'

drop index Sensor.ix_sensor_datasourceid
alter table Sensor alter column DataSourceID uniqueidentifier not null
drop table DataSource_Organisation
alter table DataSource drop constraint FK_DataSource_StationID
alter table DataSource drop column StationID


text:
package util

import (
	"fmt"
	"strings"
)

// OrderedMapAndRemovalListFromArray creates a list of key-value pair using MapFromArrayAllowingSingles, and a list of removal entries
func OrderedMapAndRemovalListFromArray(arr []string, delimiter string) (*OrderedMap, []string, error) {
	orderedMap := NewOrderedMap()
	removalList := []string{}

	for _, pairStr := range arr {
		pairSlice := strings.SplitN(pairStr, delimiter, 2)
		if len(pairSlice) == 0 || (len(pairSlice) == 1 && !strings.HasSuffix(pairSlice[0], "-")) {
			return nil, nil, fmt.Errorf("argument requires a value that contains the %q character; got %q", delimiter, pairStr)
		}
		key := pairSlice[0]
		if len(pairSlice) == 2 {
			value := pairSlice[1]
			orderedMap.Set(key, value)
		} else {
			// error cases are already filtered out from above part
			removalList = append(removalList, key[:len(key)-1])
		}
	}

	return orderedMap, removalList, nil
}

func MapFromArrayAllowingSingles(arr []string, delimiter string) (map[string]string, error) {
	return mapFromArray(arr, delimiter, true)
}

func MapFromArray(arr []string, delimiter string) (map[string]string, error) {
	return mapFromArray(arr, delimiter, false)
}

func Add(original *map[string]string, toAdd map[string]string, toRemove []string) map[string]string {
	for k, v := range toAdd {
		(*original)[k] = v
	}
	for _, k := range toRemove {
		delete(*original, k)
	}
	return *original
}

func ParseMinusSuffix(m map[string]string) []string {
	stringToRemove := []string{}
	for key := range m {
		if strings.HasSuffix(key, "-") {
			stringToRemove = append(stringToRemove, key[:len(key)-1])
			delete(m, key)
		}
	}
	return stringToRemove
}

// StringMap is a map which key and value are strings
type StringMap map[string]string

// Merge to merge a map to a StringMap
func (m StringMap) Merge(toMerge map[string]string) StringMap {
	for k, v := range toMerge {
		m[k] = v
	}
	return m
}

// Remove to remove from StringMap
func (m StringMap) Remove(toRemove []string) StringMap {
	for _, k := range toRemove {
		delete(m, k)
	}
	return m
}

// AddedAndRemovalListsFromArray returns a list of added entries and a list of removal entries
func AddedAndRemovalListsFromArray(m []string) ([]string, []string) {
	stringToRemove := []string{}
	stringToAdd := []string{}
	for _, key := range m {
		if strings.HasSuffix(key, "-") {
			stringToRemove = append(stringToRemove, key[:len(key)-1])
		} else {
			stringToAdd = append(stringToAdd, key)
		}
	}
	return stringToAdd, stringToRemove
}

// mapFromArray takes an array of strings where each item is a (key, value) pair
// separated by a delimiter and returns a map where keys are mapped to their respective values.
// If allowSingles is true, values without a delimiter will be added as keys pointing to empty strings
func mapFromArray(arr []string, delimiter string, allowSingles bool) (map[string]string, error) {
	if len(arr) == 0 {
		return nil, nil
	}

	returnMap := map[string]string{}
	for _, pairStr := range arr {
		pairSlice := strings.SplitN(pairStr, delimiter, 2)
		if len(pairSlice) <= 1 {
			if len(pairSlice) == 0 || !allowSingles {
				return nil, fmt.Errorf("Argument requires a value that contains the %q character; got %q", delimiter, pairStr)
			}
			returnMap[pairSlice[0]] = ""
		} else {
			if pairSlice[0] == "" {
				return nil, fmt.Errorf("The key is empty")
			}
			if _, ok := returnMap[pairSlice[0]]; ok {
				return nil, fmt.Errorf("The key %q has been duplicate in %v", pairSlice[0], arr)
			}
			returnMap[pairSlice[0]] = pairSlice[1]
		}
	}
	return returnMap, nil
}


text:
namespace Halley
{
	class IRenderTargetOpenGL
	{
	public:
		virtual ~IRenderTargetOpenGL() {}

		virtual bool isScreenRenderTarget() const = 0;
	};

	class TextureRenderTargetOpenGL final : public TextureRenderTarget, public IRenderTargetOpenGL
	{
	public:
		~TextureRenderTargetOpenGL() override;

		bool isScreenRenderTarget() const override { return false; }

		void onBind(Painter&) override;
		void onUnbind(Painter&) override;

	private:
		void init();
		void deInit();

		GLuint fbo = 0;
	};

	class ScreenRenderTargetOpenGL final : public ScreenRenderTarget, public IRenderTargetOpenGL
	{
	public:
		ScreenRenderTargetOpenGL(Rect4i rect) : ScreenRenderTarget(rect) {}

		bool isScreenRenderTarget() const override { return true; }

		bool getProjectionFlipVertical() const override;
		bool getViewportFlipVertical() const override;

		void onBind(Painter&) override;
	};
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>pl.korpacz</groupId>
    <artifactId>Spring.Camel</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>Spring.Camel</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.data.version>1.5.0.BUILD-SNAPSHOT</spring.data.version>
        <spring.version>4.1.0.BUILD-SNAPSHOT</spring.version>
        <hibernate.version>4.3.5.Final</hibernate.version>
        <camel.version>2.13.1</camel.version>
    </properties>

    <dependencies>
       <!--    <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-</artifactId>
            <version>${camel.version}</version>
        </dependency>-->
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-quartz</artifactId>
            <version>${camel.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-core</artifactId>
            <version>${camel.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jaxb</artifactId>
            <version>${camel.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-spring</artifactId>
            <version>${camel.version}</version>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.xml.bind</groupId>
            <artifactId>jaxb-api</artifactId>
            <version>2.2.11</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.bind</groupId>
            <artifactId>jaxb-impl</artifactId>
            <version>2.2.7</version>
        </dependency>

        <!-- Spring 4 dependencies jaxb-impl.jar-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-logging</artifactId>
                    <groupId>commons-logging</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- persistence -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>${spring.data.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>1.7.0.BUILD-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons-core</artifactId>
            <version>${spring.data.version}</version>
        </dependency>
        <!-- persistence -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- validation -->

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.1.1.Final</version>
        </dependency>

        <!-- Logging -->

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.0.13</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jul-to-slf4j</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>1.7.5</version>
        </dependency>
        <!-- <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.3</version>
            <scope>provided</scope>
        </dependency>-->
        <!-- file upload multipart-->

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <profiles>
        <profile>
            <!-- Configuration for building development tests -->
            <id>postgres</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                    <resource>
                        <directory>src/main/filters/postgre</directory>
                    </resource>
                </resources>

            </build>
            <dependencies>
                <dependency>
                    <groupId>postgresql</groupId>
                    <artifactId>postgresql</artifactId>
                    <version>9.3-1101-jdbc4</version>
                </dependency>

                <dependency>
                    <groupId>net.sf</groupId>
                    <artifactId>log4jdbc</artifactId>
                    <version>1.2</version>
                </dependency>

                <dependency>
                    <groupId>commons-dbcp</groupId>
                    <artifactId>commons-dbcp</artifactId>
                    <version>1.4</version>
                </dependency>
            </dependencies>
        </profile>
        <profile>

            <id>h2</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <resources>
                    <resource>
                        <directory>src/main/resources</directory>
                    </resource>
                    <resource>
                        <directory>src/main/filters/h2</directory>
                    </resource>
                </resources>

            </build>
            <dependencies>
                <dependency>
                    <groupId>com.h2database</groupId>
                    <artifactId>h2</artifactId>
                    <version>1.4.178</version>
                </dependency>

                <dependency>
                    <groupId>com.googlecode.flyway</groupId>
                    <artifactId>flyway-core</artifactId>
                    <version>2.3.1</version>
                </dependency>

                <dependency>
                    <groupId>c3p0</groupId>
                    <artifactId>c3p0</artifactId>
                    <version>0.9.1.2</version>
                </dependency>
            </dependencies>
        </profile>
    </profiles>
    <repositories>
        <repository>
            <id>com.springsource.repository.bundles.milestone</id>
            <name>SpringSource Enterprise Bundle Repository - SpringSource Milestone Releases</name>
            <url>http://repository.springsource.com/maven/bundles/milestone</url>
        </repository>

        <repository>
            <id>com.springsource.repository.bundles.external</id>
            <name>SpringSource Enterprise Bundle Repository - External Releases</name>
            <url>http://repository.springsource.com/maven/bundles/external</url>
        </repository>
    </repositories>
</project>


text:
using System;
using System.IO;
using System.Runtime.InteropServices;

namespace ThirdParty.iOS4Unity
{
    public class NSData : NSObject
    {
        private static readonly IntPtr _classHandle;

        static NSData()
        {
            _classHandle = ObjC.GetClass("NSData");
        }

        public override IntPtr ClassHandle
        {
            get { return _classHandle; }
        }

        private class UnmanagedMemoryStreamWithRef : UnmanagedMemoryStream
        {
#pragma warning disable 414
            private NSData _data;
#pragma warning restore 414

            public unsafe UnmanagedMemoryStreamWithRef(NSData source)
                : base((byte*)((void*)source.Bytes), (long)((ulong)source.Length))
            {
                _data = source;
            }

            protected override void Dispose(bool disposing)
            {
                _data = null;

                base.Dispose(disposing);
            }
        }

        internal NSData(IntPtr handle)
            : base(handle)
        {
        }

        public unsafe static NSData FromArray(byte[] buffer)
        {
            if (buffer.Length == 0)
            {
                return NSData.FromBytes(IntPtr.Zero, 0);
            }
            fixed (void* ptr = &buffer[0])
            {
                return NSData.FromBytes((IntPtr)ptr, (uint)buffer.Length);
            }
        }

        public static NSData FromBytes(IntPtr bytes, uint size)
        {
            return Runtime.GetNSObject<NSData>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("dataWithBytes:length:"), bytes, size));
        }

        public static NSData FromData(NSData source)
        {
            return Runtime.GetNSObject<NSData>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("dataWithData:"), source.Handle));
        }

        public static NSData FromBytesNoCopy(IntPtr bytes, uint size)
        {
            return Runtime.GetNSObject<NSData>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("dataWithBytesNoCopy:length:"), bytes, size));
        }

        public static NSData FromBytesNoCopy(IntPtr bytes, uint size, bool freeWhenDone)
        {
            return Runtime.GetNSObject<NSData>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("dataWithBytesNoCopy:length:freeWhenDone:"), bytes, size, freeWhenDone));
        }

        public static NSData FromFile(string path, NSDataReadingOptions mask, out NSError error)
        {
#if !XAMARIN
            path = Path.Combine(UnityEngine.Application.streamingAssetsPath, path);
#endif

            IntPtr errorHandle;
            var data = Runtime.GetNSObject<NSData>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("dataWithContentsOfFile:options:error:"), path, (uint)mask, out errorHandle));
            error = errorHandle == IntPtr.Zero ? null : Runtime.GetNSObject<NSError>(errorHandle);
            return data;
        }

        public static NSData FromFile(string path)
        {
#if !XAMARIN
            path = Path.Combine(UnityEngine.Application.streamingAssetsPath, path);
#endif

            return Runtime.GetNSObject<NSData>(ObjC.MessageSendIntPtr(_classHandle, Selector.GetHandle("dataWithContentsOfFile:"), path));
        }

        public static NSData FromUrl(string url)
        {
            return Runtime.GetNSObject<NSData>(ObjC.MessageSendIntPtr_NSUrl(_classHandle,Selector.GetHandle( "dataWithContentsOfURL:"), url));
        }

        public static NSData FromUrl(string url, NSDataReadingOptions mask, out NSError error)
        {
            IntPtr errorHandle;
            var data = Runtime.GetNSObject<NSData>(ObjC.MessageSendIntPtr_NSUrl(_classHandle, Selector.GetHandle("dataWithContentsOfURL:options:error:"), url, (uint)mask, out errorHandle));
            error = errorHandle == IntPtr.Zero ? null : Runtime.GetNSObject<NSError>(errorHandle);
            return data;
        }

        public IntPtr Bytes
        {
            get { return ObjC.MessageSendIntPtr(Handle, Selector.GetHandle("bytes")); }
        }

        public uint Length
        {
            get { return ObjC.MessageSendUInt(Handle, Selector.GetHandle("length")); }
            set { throw new NotImplementedException("Not available on NSData, only available on NSMutableData"); }
        }

        public byte this[int index]
        {
            get
            {
                if (index < 0 || (long)index > (long)((ulong)this.Length))
                {
                    throw new ArgumentException("idx");
                }
                return Marshal.ReadByte(new IntPtr(Bytes.ToInt64() + (long)index));
            }
            set
            {
                throw new NotImplementedException("NSData arrays can not be modified, use an NSMutableData instead");
            }
        }

        public bool Save(string path, bool atomically = true)
        {
            return ObjC.MessageSendBool(Handle, Selector.GetHandle("writeToFile:atomically:"), path, atomically);
        }

        public Stream AsStream()
        {
            //TODO: if we ever implement NSMutableData
            //if (this is NSMutableData)
            //{
            //    return new NSData.UnmanagedMemoryStreamWithMutableRef(this);
            //}
            return new NSData.UnmanagedMemoryStreamWithRef(this);
        }

        public byte[] ToArray()
        {
            byte[] array = new byte[this.Length];
            Marshal.Copy(Bytes, array, 0, array.Length);
            return array;
        }
    }

    [Flags]
    [CLSCompliant(false)]
    public enum NSDataReadingOptions : uint
    {
        Mapped = 1,
        Uncached = 2,
        Coordinated = 4,
        MappedAlways = 8
    }
}


text:
import os
import csv
import socket
import getpass

import utils.logger as logger

def export_csv(data_directory, filename, data):
  """Exports the content of data to a csv file in data_directory

  Args:
    data_directory: the directory to store the csv file.
    filename: the name of the .csv file.
    data: the collected data to be exported.

  Returns:
    The path to the newly created csv file.
  """
  if not os.path.exists(data_directory):
    os.makedirs(data_directory)
  csv_file_path = os.path.join(data_directory, filename)
  logger.log('Writing raw data into csv file: %s' % str(csv_file_path))

  with open(csv_file_path, 'w') as csv_file:
    hostname = socket.gethostname()
    username = getpass.getuser()
    csv_writer = csv.writer(csv_file)
    csv_writer.writerow([
        'project_source', 'project_commit', 'bazel_commit', 'run', 'cpu',
        'wall', 'system', 'memory', 'command', 'expressions', 'hostname',
        'username', 'options', 'exit_status', 'started_at', 'platform',
        'project_label'
    ])

    for (bazel_commit, project_commit), data_item in data.items():
      command, expressions, options = data_item['args']
      non_measurables = data_item['non_measurables']
      for idx, run in enumerate(data_item['results'], start=1):
        csv_writer.writerow([
            non_measurables['project_source'], project_commit, bazel_commit,
            idx, run['cpu'], run['wall'], run['system'], run['memory'], command,
            expressions, hostname, username, options, run['exit_status'],
            run['started_at'], non_measurables['platform'],
            non_measurables['project_label']
        ])
  return csv_file_path

def export_file(data_directory, filename, content):
  """Exports the content of data to a file in data_directory

  Args:
    data_directory: the directory to store the file.
    filename: the name of the file.
    content: the content to be exported.

  Returns:
    The path to the newly created file.
  """
  if not os.path.exists(data_directory):
    os.makedirs(data_directory)
  out_file_path = os.path.join(data_directory, filename)

  with open(out_file_path, 'w') as out_file:
    out_file.write(content)

  return out_file_path


text: audio support for swan-desktop