text:
require File.dirname(__FILE__) + '/helper'
require File.dirname(__FILE__) + '/../init'

class PaginationTest < ActiveRecordTestCase
  fixtures :users

  class PaginationController < ActionController::Base
    def list_developers
      @developers = Developer.paginate :page => params[:page], :per_page => (params[:per_page] || 4).to_i

      options = [:class, :prev_label, :next_label, :inner_window, :outer_window]
      @options = params.slice(*options)
      options.each { |key| params.delete key }

      render :inline => '<%= will_paginate @developers, @options %>'
    end

    def no_pagination
      @developers = Developer.paginate :page => params[:page], :per_page => 15
      render :inline => '<%= will_paginate @developers %>'
    end

  protected
    def rescue_errors(e) raise e end
    def rescue_action(e) raise e end
  end

  def setup
    @controller = PaginationController.new
    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    super
  end

  def test_will_paginate
    get :list_developers

    entries = assigns :developers
    assert entries
    assert_equal 4, entries.size

    assert_select 'div.pagination', 1, 'no main DIV' do |el|
      assert_select 'a[href]', 3 do |elements|
        validate_page_numbers [2,3,2], elements
        assert_select elements.last, ':last-child', "Next »"
      end
      assert_select 'span', 2
      assert_select 'span.disabled:first-child', "« Previous"
      assert_select 'span.current', entries.current_page.to_s
    end
  end

  def test_will_paginate_with_options
    get :list_developers, :page => 2, :class => 'will_paginate', :prev_label => 'Prev', :next_label => 'Next'
    assert_response :success

    entries = assigns :developers
    assert entries
    assert_equal 4, entries.size

    assert_select 'div.will_paginate', 1, 'no main DIV' do
      assert_select 'a[href]', 4 do |elements|
        validate_page_numbers [nil,nil,3,3], elements
        assert_select elements.first, 'a', "Prev"
        assert_select elements.last, 'a', "Next"
      end
      assert_select 'span.current', entries.current_page.to_s
    end
  end

  def test_will_paginate_windows
    get :list_developers, :page => 6, :per_page => 1, :inner_window => 2
    assert_response :success

    entries = assigns :developers
    assert entries
    assert_equal 1, entries.size

    assert_select 'div.pagination', 1, 'no main DIV' do
      assert_select 'a[href]', 10 do |elements|
        validate_page_numbers [5,nil,2,4,5,7,8,10,11,7], elements
        assert_select elements.first, 'a', "« Previous"
        assert_select elements.last, 'a', "Next »"
      end
      assert_select 'span.current', entries.current_page.to_s
    end
  end

  def test_no_pagination
    get :no_pagination
    entries = assigns :developers
    assert_equal 1, entries.page_count
    assert_equal Developer.count, entries.size

    assert_select 'div', false
    assert_equal '', @response.body
  end

protected

  def validate_page_numbers expected, links
    assert_equal(expected, links.map { |e|
      e['href'] =~ /\Wpage=([^&]*)/
      $1 ? $1.to_i : $1
    })
  end
end


text:
var five = require("../lib/johnny-five.js"),
    board = new five.Board();

board.on("ready", function() {
  var led = new five.Led(process.argv[2] || 13);

  this.repl.inject({
    led: led
  });
});

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _SOC_GPIO_STRUCT_H_
#define _SOC_GPIO_STRUCT_H_

#ifdef __cplusplus
extern "C" {
#endif

	typedef volatile struct {
		uint32_t bt_select;
		 /*NA*/ uint32_t out;	/*GPIO0~31 output value */
		uint32_t out_w1ts;		/*GPIO0~31 output value write 1 to set */
		uint32_t out_w1tc;		/*GPIO0~31 output value write 1 to clear */
		union {
			struct {
				uint32_t data:8;	/*GPIO32~39 output value */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} out1;
		union {
			struct {
				uint32_t data:8;	/*GPIO32~39 output value write 1 to set */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} out1_w1ts;
		union {
			struct {
				uint32_t data:8;	/*GPIO32~39 output value write 1 to clear */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} out1_w1tc;
		union {
			struct {
				uint32_t sel:8;	/*SDIO PADS on/off control from outside */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} sdio_select;
		uint32_t enable;		/*GPIO0~31 output enable */
		uint32_t enable_w1ts;	/*GPIO0~31 output enable write 1 to set */
		uint32_t enable_w1tc;	/*GPIO0~31 output enable write 1 to clear */
		union {
			struct {
				uint32_t data:8;	/*GPIO32~39 output enable */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} enable1;
		union {
			struct {
				uint32_t data:8;	/*GPIO32~39 output enable write 1 to set */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} enable1_w1ts;
		union {
			struct {
				uint32_t data:8;	/*GPIO32~39 output enable write 1 to clear */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} enable1_w1tc;
		union {
			struct {
				uint32_t strapping:16;	/*GPIO strapping results: {2'd0  boot_sel_dig[7:1]  vsdio_boot_sel  boot_sel_chip[5:0]} .   Boot_sel_dig[7:1]: {U0RXD  SD_CLK  SD_CMD  SD_DATA0  SD_DATA1  SD_DATA2  SD_DATA3} .  vsdio_boot_sel: MTDI. boot_sel_chip[5:0]: {GPIO0  U0TXD  GPIO2  GPIO4  MTDO  GPIO5} */
				uint32_t reserved16:16;
			};
			uint32_t val;
		} strap;
		uint32_t in;			/*GPIO0~31 input value */
		union {
			struct {
				uint32_t data:8;	/*GPIO32~39 input value */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} in1;
		uint32_t status;		/*GPIO0~31 interrupt status */
		uint32_t status_w1ts;	/*GPIO0~31 interrupt status write 1 to set */
		uint32_t status_w1tc;	/*GPIO0~31 interrupt status write 1 to clear */
		union {
			struct {
				uint32_t intr_st:8;	/*GPIO32~39 interrupt status */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} status1;
		union {
			struct {
				uint32_t intr_st:8;	/*GPIO32~39 interrupt status write 1 to set */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} status1_w1ts;
		union {
			struct {
				uint32_t intr_st:8;	/*GPIO32~39 interrupt status write 1 to clear */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} status1_w1tc;
		uint32_t reserved_5c;
		uint32_t acpu_int;		/*GPIO0~31 APP CPU interrupt status */
		uint32_t acpu_nmi_int;	/*GPIO0~31 APP CPU non-maskable interrupt status */
		uint32_t pcpu_int;		/*GPIO0~31 PRO CPU interrupt status */
		uint32_t pcpu_nmi_int;	/*GPIO0~31 PRO CPU non-maskable interrupt status */
		uint32_t cpusdio_int;	/*SDIO's extent GPIO0~31 interrupt */
		union {
			struct {
				uint32_t intr:8;	/*GPIO32~39 APP CPU interrupt status */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} acpu_int1;
		union {
			struct {
				uint32_t intr:8;	/*GPIO32~39 APP CPU non-maskable interrupt status */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} acpu_nmi_int1;
		union {
			struct {
				uint32_t intr:8;	/*GPIO32~39 PRO CPU interrupt status */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} pcpu_int1;
		union {
			struct {
				uint32_t intr:8;	/*GPIO32~39 PRO CPU non-maskable interrupt status */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} pcpu_nmi_int1;
		union {
			struct {
				uint32_t intr:8;	/*SDIO's extent GPIO32~39 interrupt */
				uint32_t reserved8:24;
			};
			uint32_t val;
		} cpusdio_int1;
		union {
			struct {
				uint32_t reserved0:2;
				uint32_t pad_driver:1;	/*if set to 0: normal output  if set to 1: open drain */
				uint32_t reserved3:4;
				uint32_t int_type:3;	/*if set to 0: GPIO interrupt disable  if set to 1: rising edge trigger  if set to 2: falling edge trigger  if set to 3: any edge trigger  if set to 4: low level trigger  if set to 5: high level trigger */
				uint32_t wakeup_enable:1;	/*GPIO wake up enable  only available in light sleep */
				uint32_t config:2;
				 /*NA*/ uint32_t int_ena:5;	/*bit0: APP CPU interrupt enable  bit1: APP CPU non-maskable interrupt enable  bit3: PRO CPU interrupt enable  bit4:  PRO CPU non-maskable interrupt enable  bit5: SDIO's extent interrupt enable */
				uint32_t reserved18:14;
			};
			uint32_t val;
		} pin[40];
		union {
			struct {
				uint32_t rtc_max:10;
				uint32_t reserved10:21;
				uint32_t start:1;
			};
			uint32_t val;
		} cali_conf;
		union {
			struct {
				uint32_t value_sync2:20;
				uint32_t reserved20:10;
				uint32_t rdy_real:1;
				uint32_t rdy_sync2:1;
			};
			uint32_t val;
		} cali_data;
		union {
			struct {
				uint32_t func_sel:6;	/*select one of the 256 inputs */
				uint32_t sig_in_inv:1;	/*revert the value of the input if you want to revert  please set the value to 1 */
				uint32_t sig_in_sel:1;	/*if the slow signal bypass the io matrix or not if you want  setting the value to 1 */
				uint32_t reserved8:24;	/*The 256 registers below are selection control for 256 input signals connected to GPIO matrix's 40 GPIO input  if GPIO_FUNCx_IN_SEL is set to n(0<=n<40): it means GPIOn input is used for input signal x  if GPIO_FUNCx_IN_SEL is set to 0x38: the input signal x is set to 1   if GPIO_FUNCx_IN_SEL is set to 0x30: the input signal x is set to 0 */
			};
			uint32_t val;
		} func_in_sel_cfg[256];
		union {
			struct {
				uint32_t func_sel:9;	/*select one of the 256 output to 40 GPIO */
				uint32_t inv_sel:1;	/*invert the output value  if you want to revert the output value  setting the value to 1 */
				uint32_t oen_sel:1;	/*weather using the logical oen signal or not using the value setting by the register */
				uint32_t oen_inv_sel:1;	/*invert the output enable value  if you want to revert the output enable value  setting the value to 1 */
				uint32_t reserved12:20;	/*The 40 registers below are selection control for 40 GPIO output  if GPIO_FUNCx_OUT_SEL is set to n(0<=n<256): it means GPIOn input is used for output signal x  if GPIO_FUNCx_OUT_INV_SEL is set to 1  the output signal x is set to ~value.  if GPIO_FUNC0_OUT_SEL is 256 or GPIO_FUNC0_OEN_SEL is 1 using GPIO_ENABLE_DATA[x] for the enable value else using the signal enable */
			};
			uint32_t val;
		} func_out_sel_cfg[40];
	} gpio_dev_t;
	extern gpio_dev_t GPIO;

#ifdef __cplusplus
}
#endif
#endif							/* _SOC_GPIO_STRUCT_H_ */


text:
'use strict';

const lib = require('./lib'),
      info = require('./package'),
      Server = lib.Server;

/* index.js
 * Server initialization, library, and package information.
 * * */

// Library initializer
let rela = function(opts){
  return new Server(opts);
};

// Library access
Object.assign(rela, lib);

// Meta
rela.version = info.version;
rela.author = info.author;
rela.license = info.license;

// Export
module.exports = rela;


text:
package org.ogcs.log.test;

import org.junit.Test;
import org.ogcs.log.util.TimeV8Util;

import java.time.LocalDateTime;

/**
 * @author TinyZ
 * @date 2016-09-09.
 */
public class TimeV8Test {

    @Test
    public void test(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        String s1 = TimeV8Util.dateTime(now);

//        now.with(TemporalAdjusters.firstInMonth(DayOfWeek.of()))

        LocalDateTime localDateTime = now.plusDays(1);
        String s2 = TimeV8Util.dateTime(localDateTime);
        System.out.println();
    }
}


text:
/**
 * List prompt example
 */

'use strict';
var inquirer = require('..');

inquirer.prompt([
  {
    type: 'list',
    name: 'theme',
    message: 'What do you want to do?',
    choices: [
      'Order a pizza',
      'Make a reservation',
      new inquirer.Separator(),
      'Ask for opening hours',
      {
        name: 'Contact support',
        disabled: 'Unavailable at this time'
      },
      'Talk to the receptionist'
    ]
  },
  {
    type: 'list',
    name: 'size',
    message: 'What size do you need?',
    choices: ['Jumbo', 'Large', 'Standard', 'Medium', 'Small', 'Micro'],
    filter: function (val) {
      return val.toLowerCase();
    }
  }
]).then(function (answers) {
  console.log(JSON.stringify(answers, null, '  '));
});


text:
using bookmarks_helper::AddFolder;
using bookmarks_helper::AddURL;
using bookmarks_helper::GetBookmarkBarNode;
using bookmarks_helper::GetOtherNode;
using bookmarks_helper::ModelMatchesVerifier;
using bookmarks_helper::Move;
using bookmarks_helper::Remove;
using bookmarks_helper::SetTitle;

class SingleClientBookmarksSyncTest : public SyncTest {
 public:
  SingleClientBookmarksSyncTest() : SyncTest(SINGLE_CLIENT) {}
  virtual ~SingleClientBookmarksSyncTest() {}

 private:
  DISALLOW_COPY_AND_ASSIGN(SingleClientBookmarksSyncTest);
};

IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest, OfflineToOnline) {
  ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";

  DisableNetwork(GetProfile(0));
  const BookmarkNode* node = AddFolder(0, L"title");
  SetTitle(0, node, L"new_title");
  ASSERT_FALSE(GetClient(0)->AwaitFullSyncCompletion("Offline state change."));
  ProfileSyncService::Status status = GetClient(0)->GetStatus();

  // Depending on when exactly the network change notification occurs the
  // client could go to OFFLINE_UNSYNCED or OFFLINE. OFFLINE_UNSYNCED indicates
  // client tried to sync a local change and could not connect to the server.
  // OFFLINE indicates client received a network change notification of
  // the disconnection even before it tried to sync.
  ASSERT_TRUE(ProfileSyncService::Status::OFFLINE_UNSYNCED == status.summary ||
              ProfileSyncService::Status::OFFLINE == status.summary);

  EnableNetwork(GetProfile(0));
  ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Commit changes."));
  ASSERT_EQ(ProfileSyncService::Status::READY,
            GetClient(0)->GetStatus().summary);
  ASSERT_TRUE(ModelMatchesVerifier(0));
}

IN_PROC_BROWSER_TEST_F(SingleClientBookmarksSyncTest, Sanity) {
  ASSERT_TRUE(SetupClients()) << "SetupClients() failed.";

  // Starting state:
  // other_node
  //    -> top
  //      -> tier1_a
  //        -> http://mail.google.com  "tier1_a_url0"
  //        -> http://www.pandora.com  "tier1_a_url1"
  //        -> http://www.facebook.com "tier1_a_url2"
  //      -> tier1_b
  //        -> http://www.nhl.com "tier1_b_url0"
  const BookmarkNode* top = AddFolder(0, GetOtherNode(0), 0, L"top");
  const BookmarkNode* tier1_a = AddFolder(0, top, 0, L"tier1_a");
  const BookmarkNode* tier1_b = AddFolder(0, top, 1, L"tier1_b");
  const BookmarkNode* tier1_a_url0 = AddURL(
      0, tier1_a, 0, L"tier1_a_url0", GURL("http://mail.google.com"));
  const BookmarkNode* tier1_a_url1 = AddURL(
      0, tier1_a, 1, L"tier1_a_url1", GURL("http://www.pandora.com"));
  const BookmarkNode* tier1_a_url2 = AddURL(
      0, tier1_a, 2, L"tier1_a_url2", GURL("http://www.facebook.com"));
  const BookmarkNode* tier1_b_url0 = AddURL(
      0, tier1_b, 0, L"tier1_b_url0", GURL("http://www.nhl.com"));

  ASSERT_TRUE(SetupSync()) << "SetupSync() failed.";
  ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion(
      "Waiting for initial sync completed."));
  ASSERT_TRUE(ModelMatchesVerifier(0));

  //  Ultimately we want to end up with the following model; but this test is
  //  more about the journey than the destination.
  //
  //  bookmark_bar
  //    -> CNN (www.cnn.com)
  //    -> tier1_a
  //      -> tier1_a_url2 (www.facebook.com)
  //      -> tier1_a_url1 (www.pandora.com)
  //    -> Porsche (www.porsche.com)
  //    -> Bank of America (www.bankofamerica.com)
  //    -> Seattle Bubble
  //  other_node
  //    -> top
  //      -> tier1_b
  //        -> Wired News (www.wired.com)
  //        -> tier2_b
  //          -> tier1_b_url0
  //          -> tier3_b
  //            -> Toronto Maple Leafs (mapleleafs.nhl.com)
  //            -> Wynn (www.wynnlasvegas.com)
  //      -> tier1_a_url0
  const BookmarkNode* bar = GetBookmarkBarNode(0);
  const BookmarkNode* cnn = AddURL(0, bar, 0, L"CNN",
      GURL("http://www.cnn.com"));
  ASSERT_TRUE(cnn != NULL);
  Move(0, tier1_a, bar, 1);
  ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Bookmark moved."));
  ASSERT_TRUE(ModelMatchesVerifier(0));

  const BookmarkNode* porsche = AddURL(0, bar, 2, L"Porsche",
      GURL("http://www.porsche.com"));
  // Rearrange stuff in tier1_a.
  ASSERT_EQ(tier1_a, tier1_a_url2->parent());
  ASSERT_EQ(tier1_a, tier1_a_url1->parent());
  Move(0, tier1_a_url2, tier1_a, 0);
  Move(0, tier1_a_url1, tier1_a, 2);
  ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion(
      "Rearrange stuff in tier1_a"));
  ASSERT_TRUE(ModelMatchesVerifier(0));

  ASSERT_EQ(1, tier1_a_url0->parent()->GetIndexOf(tier1_a_url0));
  Move(0, tier1_a_url0, bar, bar->child_count());
  const BookmarkNode* boa = AddURL(0, bar, bar->child_count(),
      L"Bank of America", GURL("https://www.bankofamerica.com"));
  ASSERT_TRUE(boa != NULL);
  Move(0, tier1_a_url0, top, top->child_count());
  const BookmarkNode* bubble = AddURL(
      0, bar, bar->child_count(), L"Seattle Bubble",
          GURL("http://seattlebubble.com"));
  ASSERT_TRUE(bubble != NULL);
  const BookmarkNode* wired = AddURL(0, bar, 2, L"Wired News",
      GURL("http://www.wired.com"));
  const BookmarkNode* tier2_b = AddFolder(
      0, tier1_b, 0, L"tier2_b");
  Move(0, tier1_b_url0, tier2_b, 0);
  Move(0, porsche, bar, 0);
  SetTitle(0, wired, L"News Wired");
  SetTitle(0, porsche, L"ICanHazPorsche?");
  ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion("Change title."));
  ASSERT_TRUE(ModelMatchesVerifier(0));

  ASSERT_EQ(tier1_a_url0->id(), top->GetChild(top->child_count() - 1)->id());
  Remove(0, top, top->child_count() - 1);
  Move(0, wired, tier1_b, 0);
  Move(0, porsche, bar, 3);
  const BookmarkNode* tier3_b = AddFolder(0, tier2_b, 1, L"tier3_b");
  const BookmarkNode* leafs = AddURL(
      0, tier1_a, 0, L"Toronto Maple Leafs", GURL("http://mapleleafs.nhl.com"));
  const BookmarkNode* wynn = AddURL(0, bar, 1, L"Wynn",
      GURL("http://www.wynnlasvegas.com"));

  Move(0, wynn, tier3_b, 0);
  Move(0, leafs, tier3_b, 0);
  ASSERT_TRUE(GetClient(0)->AwaitFullSyncCompletion(
      "Move after addition of bookmarks."));
  ASSERT_TRUE(ModelMatchesVerifier(0));
}


text:
import org.jetbrains.annotations.NotNull;

class Test {
  private static void test(@NotNull Object foo) {
    assert foo != null;
  }

  private static void testParens(@NotNull Object foo) {
    assert (foo != null);
  }

  private static void testNegation(boolean b) {
    if(!b) {
      assert !b;
    }
  }

  private static void testAnd(boolean a, boolean b, boolean c) {
    if(b) {
      assert a && b && c;
    }
  }

  private static void testOr(boolean a, boolean b, boolean c) {
    if(b) {
      // c is never checked: probably not intended; report
      assert a || <warning descr="Condition 'b' is always 'true'">b</warning> || c;

      assert a || c || b;
    }
  }

  private static void testOrNot(boolean a, boolean b, boolean c) {
    if(!b) {
      assert !(a || b || c);
    }
  }

  private static void testOrNotFail(boolean a, boolean b, boolean c) {
    if(b) {
      assert <warning descr="Condition '!(a || b || c)' is always 'false'">!(<warning descr="Condition 'a || b || c' is always 'true'">a || <warning descr="Condition 'b' is always 'true'">b</warning> || c</warning>)</warning>;
    }
  }

  private static void testAndNotFail(boolean a, boolean b, boolean c) {
    if(b) {
      assert !(a && <warning descr="Condition 'b' is always 'true'">b</warning> && c);
    }
  }

  private static void testInstanceOf(java.util.List<String> list) {
    Object s = list.get(0);
    System.out.println(s.hashCode());
    assert s instanceof String;
    assert <warning descr="Condition 'list.get(1) instanceof String' is redundant and can be replaced with a null check">list.get(1) instanceof String</warning>;
    assert <warning descr="Condition 's instanceof Number' is always 'false'">s instanceof Number</warning>;
  }

  private static void test2(@NotNull Object foo) {
    if (foo == null) {
      throw new IllegalArgumentException();
    }
  }
  private static void test3(@NotNull Object foo) {
    if (foo == null) throw new IllegalArgumentException();
  }

  private static void test4(@NotNull Object foo) {
    if (<warning descr="Condition 'foo != null' is always 'true'">foo != null</warning>) throw new IllegalArgumentException();
  }

  private static void assertMethod(@NotNull Object foo) {
    assertTrue(foo != null);
    assertFalse(foo == null);
  }

  private static void assertMethodFail(@NotNull Object foo) {
    <warning descr="The call to 'assertTrue' always fails, according to its method contracts">assertTrue</warning>(<warning descr="Condition 'foo == null' is always 'false'">foo == null</warning>);
  }

  private static void testNull(Object obj) {
    if(obj != null) return;
    assertNull(obj);
  }

  static final void assertTrue(boolean x) {
    if(!x) throw new AssertionError();
  }

  static final void assertFalse(boolean x) {
    if(x) throw new AssertionError();
  }

  static final void assertNull(Object x) { if(x != null) throw new AssertionError(); }
}


text:
package com.sun.jini.qa.harness;

import java.io.PrintStream;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.StringTokenizer;

/**
 * A class which drives the execution of a test on a VM other than the one in
 * which the test harness is running. It is assumed that the name of the test
 * class is provided as an argument, and that the test class in turn has a
 * main method which is to be invoked by this class.  Success is
 * indicated if the invoked main method returns normally. Failure
 * is indicated if an exception is thrown. The test status is sent back to the
 * harness encoded in a character stream over System.err.
 *

 * It is assumed that all of the tests dependant classes are
 * loadable via the system class loader. Also, it is assumed
 * that the test environment is completely defined by the harness which
 * invokes this VM. No properties or other environmental object (such
 * as security managers) are set by this class.
 */
public class MainWrapper {

    /** The initial System.err, kept for private use */
    private static PrintStream origErr;

    /** The logger for this class */
    private static Logger logger =
	Logger.getLogger("com.sun.jini.qa.harness");

    /**
     * The main method invoked in the test VM. The first argument is
     * assumed to be the name of the test, which is only used for
     * annotating messages. The second argument is assumed to be
     * the name of the test implementation class, which must provide a
     * main method. The remaining arguments are assumed to be
     * arguments which are to be provided to the test.
     *

     * This method loads the test class named in the second argument
     * and invokes the main method of that class, passing an argument
     * list derived from the remaining arguments passed to this
     * method.  A normal return results in a successful status return
     * to the harness. An exception return results in a failure status
     * return to the harness. The status string is written as the final
     * output to System.err. Exit status of the VM is 0 if the
     * test passes and 1 for any type of failure.
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
	//XXXXX SUPPORT NEW VM INVOCATION MECHANISM
	origErr = System.err;
	System.setErr(System.out);
	if (args.length < 2) {
	    exit(false, Test.ENV, "MainWrapper arguments missing");
	}
	String testName = args[0];
	String testClassName = args[1];
	String[] testArgs = new String[args.length - 2];
	for (int i=0; i < args.length - 2; i++) {
	    testArgs[i] = args[i + 2];
	}
	Method mainMethod = null;
	try {
	    logger.log(Level.FINEST,
		       "MainWrapper classpath = '"
		       + System.getProperty("java.class.path")
		       + "'");
	    Class testClass = Class.forName(testClassName);
            mainMethod = testClass.getMethod("main",
					     new Class[]{testArgs.getClass()});
        } catch (Exception e) {
            e.printStackTrace();
	    exit(false,
		 Test.ENV,
		 "Failed to generate/instantiate test class:" + e);
	}
	try {
            mainMethod.invoke(null, new Object[]{testArgs});
	    exit(true, Test.TEST, "OK");
	} catch (InvocationTargetException e) {
	    e.getCause().printStackTrace();
            exit(false,
		 Test.TEST,
		 "Test " + testName + " failed: " + e.getCause());
	} catch (Throwable e) {
	    e.printStackTrace();
	    exit(false,
		 Test.TEST,
		 "Test " + testName + " failed: " + e);
	}
	//XXX cleanup temp directory??? Perhaps support an optional parameter?
    }

    /**
     * Encode the given Status into a one-line string.  Write that
     * string as the last line to System.err, and exit.
     *

     * When a test is run in
     * another VM, it must pass back the status information to the harness. To
     * do this, the wrapper converts the Status object returned
     * by the run method to a specially formatted string which is
     * written as the last output to System.err.
     * AbstractRunner tracks the data written to this stream,
     * searching for the string Status.STATUS_TOKEN
     * and converts the specially formatted info following this string
     * back to a Status object when the test VM
     * exits.
     *
     * @param s the status to encode, must never be null
     */
    private static void exit(boolean state, int type, String message) {
	origErr.println(MasterHarness.genMessage(state, type, message));
	System.out.flush();
	System.out.close();
  	origErr.flush();
  	origErr.close();
	System.exit((state ? 0 : 1));
    }
}


text:
package org.elasticsearch.benchmark.search.aggregations;

import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.StopWatch;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.SizeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.node.Node;
import org.elasticsearch.search.aggregations.AggregationBuilders;

import java.util.concurrent.ThreadLocalRandom;

import static org.elasticsearch.client.Requests.createIndexRequest;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;

public class QueryFilterAggregationSearchBenchmark {

    static final long COUNT = SizeValue.parseSizeValue("5m").singles();
    static final int BATCH = 1000;
    static final int QUERY_COUNT = 200;
    static final int NUMBER_OF_TERMS = 200;

    static Client client;

    public static void main(String[] args) throws Exception {
        Settings settings = settingsBuilder()
                .put("index.refresh_interval", "-1")
                .put(SETTING_NUMBER_OF_SHARDS, 2)
                .put(SETTING_NUMBER_OF_REPLICAS, 0)
                .build();

        String clusterName = QueryFilterAggregationSearchBenchmark.class.getSimpleName();
        Node node1 = nodeBuilder()
                .clusterName(clusterName)
                .settings(settingsBuilder().put(settings).put("name", "node1")).node();
        client = node1.client();

        long[] lValues = new long[NUMBER_OF_TERMS];
        for (int i = 0; i < NUMBER_OF_TERMS; i++) {
            lValues[i] = ThreadLocalRandom.current().nextLong();
        }

        Thread.sleep(10000);
        try {
            client.admin().indices().create(createIndexRequest("test")).actionGet();

            StopWatch stopWatch = new StopWatch().start();

            System.out.println("--> Indexing [" + COUNT + "] ...");
            long ITERS = COUNT / BATCH;
            long i = 1;
            int counter = 0;
            for (; i <= ITERS; i++) {
                BulkRequestBuilder request = client.prepareBulk();
                for (int j = 0; j < BATCH; j++) {
                    counter++;

                    XContentBuilder builder = jsonBuilder().startObject();
                    builder.field("id", Integer.toString(counter));
                    builder.field("l_value", lValues[ThreadLocalRandom.current().nextInt(NUMBER_OF_TERMS)]);

                    builder.endObject();

                    request.add(Requests.indexRequest("test").type("type1").id(Integer.toString(counter))
                            .source(builder));
                }
                BulkResponse response = request.execute().actionGet();
                if (response.hasFailures()) {
                    System.err.println("--> failures...");
                }
                if (((i * BATCH) % 100000) == 0) {
                    System.out.println("--> Indexed " + (i * BATCH) + " took " + stopWatch.stop().lastTaskTime());
                    stopWatch.start();
                }
            }
            System.out.println("--> Indexing took " + stopWatch.totalTime() + ", TPS " + (((double) (COUNT)) / stopWatch.totalTime().secondsFrac()));
        } catch (Exception e) {
            System.out.println("--> Index already exists, ignoring indexing phase, waiting for green");
            ClusterHealthResponse clusterHealthResponse = client.admin().cluster().prepareHealth().setWaitForGreenStatus().setTimeout("10m").execute().actionGet();
            if (clusterHealthResponse.isTimedOut()) {
                System.err.println("--> Timed out waiting for cluster health");
            }
        }
        client.admin().indices().prepareRefresh().execute().actionGet();
        if (client.prepareSearch().setSize(0).setQuery(matchAllQuery()).execute().actionGet().getHits().totalHits() != COUNT) {
            throw new Error();
        }
        System.out.println("--> Number of docs in index: " + COUNT);

        final long anyValue = ((Number) client.prepareSearch().execute().actionGet().getHits().hits()[0].sourceAsMap().get("l_value")).longValue();

        long totalQueryTime = 0;

        totalQueryTime = 0;
        for (int j = 0; j < QUERY_COUNT; j++) {
            SearchResponse searchResponse = client.prepareSearch()
                    .setSize(0)
                    .setQuery(termQuery("l_value", anyValue))
                    .execute().actionGet();
            totalQueryTime += searchResponse.getTookInMillis();
        }
        System.out.println("-->  Simple Query on first l_value " + totalQueryTime + "ms");

        totalQueryTime = 0;
        for (int j = 0; j < QUERY_COUNT; j++) {
            SearchResponse searchResponse = client.prepareSearch()
                    .setSize(0)
                    .setQuery(termQuery("l_value", anyValue))
                    .addAggregation(AggregationBuilders.filter("filter").filter(QueryBuilders.termQuery("l_value", anyValue)))
                    .execute().actionGet();
            totalQueryTime += searchResponse.getTookInMillis();
        }
        System.out.println("-->  Filter agg first l_value " + totalQueryTime + "ms");
    }
}


text:
The Regency is a tall blue-tiled building with a large entrance way. The entrance seems to be saying "this is a very elegant place to live," and the letters are a huge part of that.

The most peculiar letter is probably the "y" – at first I thought it might just be backwards, but it still doesn't quite look right when flipped. I think it is strange because of the direction that it curls, no pen stroke would naturally flow that way.

Not to be overlooked is the script for the word "The". It adds a certain elegance, especially when combined with the serif. I really enjoy the strange oblong ball terminals.

1445 West 14th Ave

![The Regency Study](/media/the-regency-study.png)
![The Regency Context](/media/the-regency-context.jpg)


text:
mkdir bin  # creates the bin folder in case it doesn't exist

rm -r bin/*  # remove contents of the bin folder

# creates folders in case they don't exist
mkdir bin/sav
mkdir bin/sav/backup
mkdir bin/out

cp -r csv bin/csv  # copy csv data to dist data folder
cp -r tax bin/tax  # copy csv data to dist data folder

cp README.md bin/README.md  # copy readme file to dist

cp build.spec src/launcher.spec  # copy spec file to sources folder

cd src  # cd to sources folder

pyinstaller launcher.spec --onefile --icon icon.ico --distpath ../bin --workpath ../tmp --clean  # create the executable
rm launcher.spec  # remove the temporary spec file

cd ..

rm -R tmp  # remove the work folder

pushd `dirname $0` > /dev/null
SCRIPTPATH=`pwd`
popd > /dev/null

gvfs-set-attribute -t string "bin/DiAnnotator" metadata::custom-icon file://${SCRIPTPATH}/ico/icon.png  # set the icon


text:
package cc.protea.spreedly.model;

import org.simpleframework.xml.Default;
import org.simpleframework.xml.Element;

import java.util.Date;

@Default(required = false)
public class SpreedlyTransactionResponseResponse {

    public boolean             success;
    public SpreedlyMessage     message;
    @Element(name = "avs_code", required = false)
    public SpreedlyAvsResponse avsResponse;
    @Element(name = "avs_message", required = false)
    public String              avsMessage;
    @Element(name = "cvv_code", required = false)
    public SpreedlyCvvResponse cvvResponse;
    @Element(name = "cvv_message", required = false)
    public String              cvvMessage;
    public boolean             pending;
    @Element(name = "error_code", required = false)
    public String              errorCode;
    @Element(name = "error_detail", required = false)
    public String              errorDetail;
    public boolean             cancelled;
    /**
     * Date and time of origination.
     */
    @Element(name = "created_at", required = false)
    public Date                createdOn;
    /**
     * Date and time of modification.
     */
    @Element(name = "updated_at", required = false)
    public Date                updatedOn;

}


text:
class MiqWidgetSet < ApplicationRecord
  include_concern 'SetData'

  acts_as_miq_set

  before_destroy :ensure_can_be_destroyed
  before_destroy :destroy_user_versions
  before_destroy :delete_from_dashboard_order

  before_validation :keep_group_when_saving
  after_save        :add_to_dashboard_order
  after_save        :update_members

  validates :group_id, :presence => true, :unless => :read_only?

  validates :name, :format => {:with => /\A[^|]*\z/, :on => :create, :message => "cannot contain \"|\""}

  validates :description, :uniqueness_when_changed => {:scope   => [:owner_id, :userid],
                                                       :message => _("must be unique for this group and userid")}
  belongs_to :group, :class_name => 'MiqGroup'

  scope :with_array_order, lambda { |ids, column = :id, column_type = :bigint|
    order = sanitize_sql_array(["array_position(ARRAY[?]::#{column_type}[], #{table_name}.#{column}::#{column_type})", ids])
    order(Arel.sql(order))
  }

  WIDGET_DIR =  File.expand_path(File.join(Rails.root, "product/dashboard/dashboards"))

  def self.default_dashboard
    find_by(:name => 'default', :read_only => true)
  end

  def self.with_users
    where.not(:userid => nil)
  end

  def update_members
    replace_children(Array(set_data_widgets)) if members.map(&:id).sort != set_data_widgets.ids.sort
    current_user = User.current_user
    members.each { |w| w.create_initial_content_for_user(current_user.userid) } if current_user # Generate content if not there
  end

  def add_to_dashboard_order
    return unless group

    group.add_to_dashboard_order(id)
    group.save
  end

  def delete_from_dashboard_order
    return unless group

    group.delete_from_dashboard_order(id)
    group.save
  end

  def ensure_can_be_destroyed
    if read_only?
      errors.add(:base, _("Unable to delete read-only WidgetSet"))
      throw(:abort)
    end
  end

  def destroy_user_versions
    # userid, group_id and name are set for user version
    # group_id, owner_type and owner_id are set for group version
    return if userid

    # When we destroy a WidgetSet for a group, we also want to destroy all user-modified versions
    MiqWidgetSet.with_users.where(:name => name, :group_id => owner_id).destroy_all
  end

  def self.destroy_user_versions
    MiqWidgetSet.with_users.destroy_all
  end

  def self.where_unique_on(name, user = nil)
    # user is nil for dashboards set for group
    userid = user.try(:userid)
    # a unique record is defined by name, group_id and userid
    if userid.present?
      where(:name => name, :group_id => user.current_group_id, :userid => userid)
    else
      where(:name => name, :userid => nil)
    end
  end

  def self.subscribed_for_user(user)
    where(:userid => user.userid)
  end

  def self.sync_from_dir
    Dir.glob(File.join(WIDGET_DIR, "*.yaml")).sort.each { |f| sync_from_file(f) }
  end

  def self.sync_from_file(filename)
    attrs = YAML.load_file(filename)

    lookup_attributes = {}
    lookup_attributes[:name] = attrs["name"]
    lookup_attributes[:userid] = nil
    lookup_attributes[:read_only] = true

    ws = find_by(lookup_attributes)

    if ws.nil? || ws.updated_on.utc < File.mtime(filename).utc
      # Convert widget descriptions to ids in set_data
      members = []
      attrs["set_data"] = attrs.delete("set_data_by_description").inject({}) do |h, k|
        col, arr = k
        h[col] = arr.collect do |d|
          w = MiqWidget.find_by(:description => d)
          members << w if w
          w.try(:id)
        end.compact
        h
      end

      owner_description = attrs.delete("owner_description")
      owner = MiqGroup.find_by(:description => owner_description) if owner_description
      if owner
        attrs["owner_type"] = "MiqGroup"
        attrs["owner_id"] = owner.id
      end
    end

    if ws
      if ws.updated_on.utc < File.mtime(filename).utc
        $log.info("Widget Set: [#{ws.description}] file has been updated on disk, synchronizing with model")
        ws.update!(attrs)
        ws.replace_children(members)
      end
    else
      $log.info("Widget Set: [#{attrs["description"]}] file has been added to disk, adding to model")
      ws = create(attrs)
      ws.replace_children(members)
    end
  end

  def self.copy_dashboard(source_widget_set, destination_name, destination_description, assign_to_group_id = nil)
    assign_to_group = MiqGroup.find(assign_to_group_id || source_widget_set.group_id || source_widget_set.owner_id)
    MiqWidgetSet.create!(:name        => destination_name,
                         :description => destination_description,
                         :owner_type  => "MiqGroup",
                         :set_type    => source_widget_set.set_type,
                         :set_data    => source_widget_set.set_data,
                         :owner_id    => assign_to_group.id)
  end

  def self.seed
    sync_from_dir
  end

  def self.display_name(number = 1)
    n_('Dashboard', 'Dashboards', number)
  end

  private

  def keep_group_when_saving
    self.group_id = owner_id if owner_type == "MiqGroup" && owner_id.present?
  end
end


text:
.class public interface abstract Landroid/media/AudioSystem$AudioRecordingCallback;
.super Ljava/lang/Object;
.source "AudioSystem.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/AudioSystem;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x609
    name = "AudioRecordingCallback"
.end annotation

# virtual methods
.method public abstract onRecordingConfigurationChanged(III[I)V
.end method


text:
package com.thoughtworks.go.domain.activity;

import com.thoughtworks.go.domain.cctray.viewers.AllowedViewers;
import com.thoughtworks.go.domain.cctray.viewers.Viewers;
import com.thoughtworks.go.util.DateUtils;
import org.jdom2.Element;
import org.junit.Test;

import java.util.Date;

import static com.thoughtworks.go.util.DataStructureUtils.s;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;

public class ProjectStatusTest {
    @Test
    public void shouldGetCcTrayStatusxml() throws Exception {
        String projectName = "projectName";
        String activity = "Building";
        String lastBuildStatus = "Success";
        String lastBuildLabel = "LastBuildLabel";
        Date lastBuildTime = new Date();
        String webUrl = "weburl";
        String contextPath = "http://localhost/go";

        ProjectStatus projectStatus = new ProjectStatus(projectName, activity, lastBuildStatus, lastBuildLabel,
                lastBuildTime, webUrl);

        Element element = projectStatus.ccTrayXmlElement(contextPath);

        assertThat(element.getName(), is("Project"));
        assertThat(element.getAttributeValue("name"), is(projectName));
        assertThat(element.getAttributeValue("activity"), is(activity));
        assertThat(element.getAttributeValue("lastBuildStatus"), is(lastBuildStatus));
        assertThat(element.getAttributeValue("lastBuildLabel"), is(lastBuildLabel));
        assertThat(element.getAttributeValue("lastBuildTime"), is(DateUtils.formatIso8601ForCCTray(lastBuildTime)));
        assertThat(element.getAttributeValue("webUrl"), is(contextPath + "/" + webUrl));
    }

    @Test
    public void shouldListViewers() throws Exception {
        Viewers viewers = mock(Viewers.class);

        ProjectStatus status = new ProjectStatus("name", "activity", "web-url");
        status.updateViewers(viewers);

        assertThat(status.viewers(), is(viewers));
    }

    @Test
    public void shouldProvideItsXmlRepresentation_WhenThereAreNoBreakers() throws Exception {
        ProjectStatus status = new ProjectStatus("name", "activity1", "build-status-1", "build-label-1",
                DateUtils.parseYYYYMMDD("2010-05-23"), "web-url");

        assertThat(status.xmlRepresentation(),
                is("<Project name=\"name\" activity=\"activity1\" lastBuildStatus=\"build-status-1\" lastBuildLabel=\"build-label-1\" " +
                        "lastBuildTime=\"2010-05-23T00:00:00\" webUrl=\"__SITE_URL_PREFIX__/web-url\" />"));
    }

    @Test
    public void shouldProvideItsXmlRepresentation_WhenThereAreBreakers() throws Exception {
        ProjectStatus status = new ProjectStatus("name", "activity1", "build-status-1", "build-label-1",
                DateUtils.parseYYYYMMDD("2010-05-23"), "web-url", s("breaker1", "breaker2"));

        assertThat(status.xmlRepresentation(),
                is("<Project name=\"name\" activity=\"activity1\" lastBuildStatus=\"build-status-1\" lastBuildLabel=\"build-label-1\" " +
                        "lastBuildTime=\"2010-05-23T00:00:00\" webUrl=\"__SITE_URL_PREFIX__/web-url\">" +
                        "<messages><message text=\"breaker1, breaker2\" kind=\"Breakers\" /></messages></Project>"));
    }

    @Test
    public void shouldAlwaysHaveEmptyStringAsXMLRepresentationOfANullProjectStatus() throws Exception {
        assertThat(new ProjectStatus.NullProjectStatus("some-name").xmlRepresentation(), is(""));
        assertThat(new ProjectStatus.NullProjectStatus("some-other-name").xmlRepresentation(), is(""));
    }

    @Test
    public void shouldNotBeViewableByAnyoneTillViewersAreUpdated() throws Exception {
        ProjectStatus status = new ProjectStatus("name", "activity", "web-url");

        assertThat(status.canBeViewedBy("abc"), is(false));
        assertThat(status.canBeViewedBy("def"), is(false));

        status.updateViewers(new AllowedViewers(s("abc", "ghi")));

        assertThat(status.canBeViewedBy("abc"), is(true));
        assertThat(status.canBeViewedBy("def"), is(false));
        assertThat(status.canBeViewedBy("ghi"), is(true));
    }
}


text:
using System;
using CommonDomain;
using CommonDomain.Persistence;

namespace Sample.Server.Support
{
    public class AggregateFactory : IConstructAggregates
    {
        public IAggregate Build(Type type, Guid id, IMemento snapshot)
        {
			var a = Activator.CreateInstance(type) as IAggregate;
            return a;
        }
    }
}


text:
var geoLocation = {
    formNumber : "C14",

    initInlinePicker: function(isReadOnly) {
        var btGeoLocationPicker = $("#buttonGeoLocationPicker");
        if (isReadOnly.toString().toLowerCase() == 'true') {
            btGeoLocationPicker.attr('disabled', 'disabled');
        }
    },

    showPicker: function (idfGeoLocation) {
        var url = bvUrls.getGeoLocationPickerUrl() + '?idfGeoLocation=' + idfGeoLocation;
        var title = EIDSS.BvMessages['titleGeoLocation'];
        bvPopup.showDefault(url, title, 700, 290, false);
        windowFacade.addFormNumber(bvPopup.defaultName, geoLocation.formNumber);
    },

    showFullPicker: function (idfGeoLocation) {
        var url = bvUrls.getGeoLocationFullPickerUrl() + '?idfGeoLocation=' + idfGeoLocation;
        var title = EIDSS.BvMessages['titleGeoLocation'];
        bvPopup.showDefault(url, title, 700, 290, false);
        windowFacade.addFormNumber(bvPopup.defaultName, geoLocation.formNumber);
    },

    onPickerChanged: function (idfGeoLocation) {
        var contentData = bvPopup.getDefaultWindowData();
        $.ajax({
            url: bvUrls.getSetGeoLocationUrl(),
            dataType: "json",
            type: "GET",
            data: {
                idfGeoLocation: idfGeoLocation,
                formData: contentData
            },
            success: function (data) {
                var hasError = formRefresher.hasError(data);
                formRefresher.updateControls(data);
                if (!hasError) {
                    bvPopup.closeDefaultPopup();
                    }
            },
            error: function () {
                bvPopup.closeDefaultPopup();
            }
        });
    },

    onCoordinateChangedSuccess: function (id) {
        comboBoxFacade.reloadReferenceComboBoxWithoutClearValue(id, 'Region');
        comboBoxFacade.reloadReferenceComboBoxWithoutClearValue(id, 'Rayon');
        comboBoxFacade.reloadReferenceComboBoxWithoutClearValue(id, 'Settlement');
    },

    onCoordinateChanged: function (e) {
        var id = comboBoxFacade.getIdByE(e);
        formRefresher.setOnChangedSuccess(geoLocation.onCoordinateChangedSuccess, id);
        formRefresher.onNumericChanged(e);
    },

    onCoordinateByMapChanged: function (objectIdent, lat, lon) {
        var idfGeoLocation = objectIdent.substring(objectIdent.indexOf('_') + 1, objectIdent.lastIndexOf('_'));
        $.ajax({
            url: bvUrls.getSetGeoLocationFromMapUrl(),
            dataType: "json",
            type: "GET",
            data: {
                idfGeoLocation: idfGeoLocation,
                dblLatitude: lat,
                dblLongitude: lon
            },
            success: function (data) {
                formRefresher.updateControls(data);
                geoLocation.onCoordinateChangedSuccess(objectIdent);
            },
            error: function () {
            }
        });
    },

}


text:
package cn.sunner.sms2calendar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import cn.sunner.sms2calendar.parser.SMSParser;

public class SMSReceiver extends BroadcastReceiver {

    public SMSReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // Get the data (SMS data) bound to intent
        Bundle bundle = intent.getExtras();

        SmsMessage[] msgs;

        if (bundle != null) {
            // Retrieve the SMS Messages received
            Object[] pdus = (Object[]) bundle.get("pdus");
            if (pdus != null) {
                msgs = new SmsMessage[pdus.length];

                // Combine every SMS message received. big SMS may be separated.
                String messageBody = "";
                for (int i = 0; i < msgs.length; i++) {
                    // Convert Object array
                    msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                    messageBody += msgs[i].getMessageBody();
                }

                SMSParser parser = getParser(msgs[0].getOriginatingAddress(), messageBody);
                if (parser != null) {
                    List<Event> events = parser.getEvents();
                    for (Event event : events) {
                        Notification.add(context, event);
                    }
                }
            }
        }
    }

    protected static SMSParser getParser(String fromNumber, String text) {
        try {
            Class <?> cls = Class.forName("cn.sunner.sms2calendar.parser.N" + fromNumber + "Parser");
            return (SMSParser) cls.getDeclaredConstructor(String.class).newInstance(text);
        } catch (ClassNotFoundException e) {
            // Do nothing. Not all phone number has a parser class
        } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}


text:
<?php

namespace OpenOrchestra\WorkflowAdminBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class OpenOrchestraWorkflowAdminExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        foreach ($config['facades'] as $transformer => $facade) {
            $container->setParameter('open_orchestra_workflow_admin.facade.' . $transformer .'.class', $facade);
        }

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('transformer.yml');
        $loader->load('voter.yml');
        $loader->load('form.yml');
        $loader->load('subscriber.yml');
        $loader->load('validator.yml');
        $loader->load('service.yml');
        $loader->load('business_rules.yml');

        $container->setParameter('open_orchestra_workflow_admin.choice.available_color', $config['available_color']);
    }
}


text:
{-# LANGUAGE FlexibleContexts, CPP #-}

module AWS.RDS.DBParameterGroup
    ( describeDBParameterGroups
    , createDBParameterGroup
    , deleteDBParameterGroup
    ) where

import Control.Applicative ((<$>), (<*>))
#if MIN_VERSION_conduit(1,1,0)
import Control.Monad.Trans.Resource (MonadThrow, MonadResource, MonadBaseControl)
import Data.Conduit (Consumer)
#else
import Data.Conduit (Consumer, MonadBaseControl, MonadResource, MonadThrow)
#endif
import Data.Text (Text)
import Data.XML.Types (Event)

import AWS.Lib.Parser (getT, element)
import AWS.Lib.Query ((|=), (|=?))
import AWS.RDS.Internal (RDS, rdsQuery, rdsQueryOnlyMetadata, elements)
import AWS.RDS.Types hiding (Event)
import AWS.Util (toText)

describeDBParameterGroups
    :: (MonadBaseControl IO m, MonadResource m)
    => Maybe Text -- ^ DBParameterGroupName
    -> Maybe Text -- ^ Marker
    -> Maybe Int -- ^ MaxRecords
    -> RDS m [DBParameterGroup]
describeDBParameterGroups name marker maxRecords =
    rdsQuery "DescribeDBParameterGroups" params $
        elements "DBParameterGroup" dbParameterGroupSink
  where
    params =
        [ "DBParameterGroupName" |=? name
        , "Marker" |=? marker
        , "MaxRecords" |=? toText <$> maxRecords
        ]

dbParameterGroupSink
    :: MonadThrow m
    => Consumer Event m DBParameterGroup
dbParameterGroupSink = DBParameterGroup
    <$> getT "DBParameterGroupFamily"
    <*> getT "Description"
    <*> getT "DBParameterGroupName"

createDBParameterGroup
    :: (MonadBaseControl IO m, MonadResource m)
    => Text -- ^ DBParameterGroupFamily
    -> Text -- ^ DBParameterGroupName
    -> Text -- ^ Description
    -> RDS m DBParameterGroup
createDBParameterGroup family name desc =
    rdsQuery "CreateDBParameterGroup" params $
        element "DBParameterGroup" dbParameterGroupSink
  where
    params =
        [ "DBParameterGroupFamily" |= family
        , "DBParameterGroupName" |= name
        , "Description" |= desc
        ]

deleteDBParameterGroup
    :: (MonadBaseControl IO m, MonadResource m)
    => Text -- ^ DBParameterGroupName
    -> RDS m ()
deleteDBParameterGroup name =
    rdsQueryOnlyMetadata "DeleteDBParameterGroup"
        ["DBParameterGroupName" |= name]


text:
package main

import (
	"bytes"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestAsJira(t *testing.T) {
	list := makeEventListTestData()
	buf := new(bytes.Buffer)
	list.AsJira(buf)
	assert.Contains(t, buf.String(), "|Hello|")
	assert.Contains(t, buf.String(), "|tuser|Hello|http://somewhere.com|")
}

func TestAsCSV(t *testing.T) {
	list := makeEventListTestData()
	buf := new(bytes.Buffer)
	list.AsCSV(buf)
	assert.Contains(t, buf.String(), "Hello,")
	assert.Contains(t, buf.String(), ",tuser,Hello,http://somewhere.com")
}

func TestAsHTML(t *testing.T) {
	list := makeEventListTestData()
	buf := new(bytes.Buffer)
	list.AsHTML(buf)
	assert.Contains(t, buf.String(), "tuser	Hello	http://somewhere.com
")
}

func TestAsJSON(t *testing.T) {
	list := makeEventListTestData()
	buf := new(bytes.Buffer)
	list.AsJSON(buf)
	assert.Contains(t, buf.String(), "\"Login\":\"tuser\",\"Title\":\"Hello\",\"URL\":\"http://somewhere.com\"}]")
}

func TestAsText(t *testing.T) {
	list := makeEventListTestData()
	buf := new(bytes.Buffer)
	list.AsText(buf)
	assert.Contains(t, buf.String(), "| Hello | ")
	assert.Contains(t, buf.String(), " | tuser  | Hello | http://somewhere.com |")
}

func TestFilter(t *testing.T) {
	list := makeEventListTestData().summaries
	filtered := filterEvents(*list, 0, 100)
	assert.Equal(t, 1, len(filtered), "Event got filtered incorrectly")
}

func TestFilterTooNew(t *testing.T) {
	list := makeEventListTestData().summaries
	filtered := filterEvents(*list, 10, 100)
	assert.Equal(t, 0, len(filtered), "Event got filtered incorrectly")
}

func TestFilterTooOld(t *testing.T) {
	list := makeEventListTestData().summaries
	filtered := filterEvents(*list, 0, 5)
	assert.Equal(t, 0, len(filtered), "Event got filtered incorrectly")
}

func makeEventListTestData() EventList {
	repo := "Hello"
	created := time.Now().AddDate(0, 0, -7)
	login := "tuser"
	url := "http://somewhere.com"
	list := EventList{
		summaries: &[]EventSummary{
			EventSummary{
				Repository: &repo,
				LastUsed:   &created,
				Login:      &login,
				Title:      &repo,
				URL:        &url,
			},
		},
	}
	return list
}


text:
<?php

class SampleDashboard extends StandaloneDashboard {
  public function buildDashboard(){

    $kpi1 = new KPIComponent('kpi1');
    $kpi1->setDimensions(3, 2);
    $kpi1->setCaption('Click Update');
    $kpi1->setValue(40);

    $kpi2 = new KPIComponent('kpi2');
    $kpi2->setDimensions(3, 2);
    $kpi2->setCaption('Click Remove');
    $kpi2->setValue(44);

    $kpi = new KPITableComponent('kpi');
    $kpi->setDimensions(4, 5);
    $kpi->setCaption('Sales by region 2013');

    $kpi->addKPI('first', array(
      'caption' => 'Bangalore',
      'value' => 2766,
      'numberPrefix' => '$'
    ));

    $kpi->addKPI('second', array(
      'caption' => 'Chennai',
      'value' => 1988,
      'numberPrefix' => '$'
    ));

    $kpi->addKPI('third', array(
      'caption' => 'Delhi',
      'value' => 1988,
      'numberPrefix' => '$'
    ));

    $kpi->setKPIValueColor('first', 'green');
    $kpi->setKPICaptionColor('second', 'red');

    $kpi1->bindToEvent('valueClick', array($kpi), 'handleUpdate', $this);
    $kpi2->bindToEvent('valueClick', array($kpi), 'handledelete', $this);

    $this->addComponent($kpi);
    $this->addComponent($kpi1);
    $this->addComponent($kpi2);
  }

  public function handleUpdate($source, $targets, $params) {
    $kpi = $this->getComponentByID('kpi');
    $kpi->updateKPI('first', array(
      'caption' => 'Kochi',
      'value' => 4000
    ));
    $kpi->setKPIValueColor('first', 'red');
  }

  public function handleDelete($source, $targets, $params) {
    $kpi = $this->getComponentByID('kpi');
    $kpi->deleteKPI('second');
  }
}

$db = new SampleDashboard();
$db->renderStandalone();


text:
using System;
using System.Runtime.Serialization;

namespace Org.Mentalis.Security.Certificates {
	/// <summary>
	/// The exception that is thrown when a certificate error is detected.
	/// </summary>
	[Serializable]
	public class CertificateException : Exception {
		/// <summary>
		/// Initializes a new instance of the CertificateException class with default properties.
		/// </summary>
		public CertificateException() : base() {}
		/// <summary>
		/// Initializes a new instance of the CertificateException class with a specified error message.
		/// </summary>
		/// <param name="message">The error message that explains the reason for the exception.</param>
		public CertificateException(string message) : base(message) {}
		/// <summary>
		/// Initializes a new instance of the CertificateException class with a specified error message and a reference to the inner exception that is the cause of this exception.
		/// </summary>
		/// <param name="message">The error message that explains the reason for the exception.</param>
		/// <param name="inner">The exception that is the cause of the current exception. If the inner parameter is not a null reference (<b>Nothing</b> in Visual Basic), the current exception is raised in a catch block that handles the inner exception.</param>
		public CertificateException(string message, Exception inner) : base(message, inner) {}
		/// <summary>
		/// Initializes a new instance of the CertificateException class with serialized data.
		/// </summary>
		/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
		/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
		protected CertificateException(SerializationInfo info, StreamingContext context) : base (info, context) {}
	}
}


text:
using DBLib;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebServiceAR
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {

        [WebMethod]
        public bool MakeLogin(string login, string senha)
        {
            LoginDB l = new LoginDB(login, senha);
            return l.Autenticar();
        }
    }
}


text:
//
//  UIButton+TXImagePosition.h
//  Demo_ButtonImageTitleEdgeInsets
//
//  Created by luxiaoming on 16/1/15.
//  Copyright © 2017年 ApeStar. All rights reserved.
//
//https://github.com/Phelthas/Demo_ButtonImageTitleEdgeInsets
// 用button的titleEdgeInsets和 imageEdgeInsets属性来实现button文字图片上下或者左右排列的
#import <UIKit/UIKit.h>

typedef NS_ENUM(NSInteger, TXImagePosition) {
    LXMImagePositionLeft = 0,              //图片在左,文字在右,默认
    LXMImagePositionRight = 1,             //图片在右,文字在左
    LXMImagePositionTop = 2,               //图片在上,文字在下
    LXMImagePositionBottom = 3,            //图片在下,文字在上
};

@interface UIButton (TXImagePosition)

/**
 *  利用UIButton的titleEdgeInsets和imageEdgeInsets来实现文字和图片的自由排列
 *  注意:这个方法需要在设置图片和文字之后才可以调用,且button的大小要大于 图片大小+文字大小+spacing
 *
 *  @param spacing 图片和文字的间隔
 */
- (void)tx_setImagePosition:(TXImagePosition)postion spacing:(CGFloat)spacing;

@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Smidge;
using Smidge.Cache;
using Smidge.CompositeFiles;
using Smidge.FileProcessors;
using Smidge.Models;
using Smidge.Nuglify;
using Smidge.Options;
using Umbraco.Cms.Core.Configuration;
using Umbraco.Cms.Core.Configuration.Models;
using Umbraco.Cms.Core.Hosting;
using Umbraco.Cms.Core.WebAssets;
using CssFile = Smidge.Models.CssFile;
using JavaScriptFile = Smidge.Models.JavaScriptFile;

namespace Umbraco.Cms.Web.Common.RuntimeMinification
{
    public class SmidgeRuntimeMinifier : IRuntimeMinifier
    {
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly IConfigManipulator _configManipulator;
        private readonly CacheBusterResolver _cacheBusterResolver;
        private readonly IBundleManager _bundles;
        private readonly SmidgeHelperAccessor _smidge;

        // used only for minifying in MinifyAsync not for an actual pipeline
        private readonly Lazy<PreProcessPipeline> _jsMinPipeline;
        private readonly Lazy<PreProcessPipeline> _cssMinPipeline;

        // default pipelines for processing js/css files for the back office
        private readonly Lazy<PreProcessPipeline> _jsOptimizedPipeline;
        private readonly Lazy<PreProcessPipeline> _jsNonOptimizedPipeline;
        private readonly Lazy<PreProcessPipeline> _cssOptimizedPipeline;
        private readonly Lazy<PreProcessPipeline> _cssNonOptimizedPipeline;
        private ICacheBuster? _cacheBuster;
        private readonly Type _cacheBusterType;

        public SmidgeRuntimeMinifier(
            IBundleManager bundles,
            SmidgeHelperAccessor smidge,
            IHostingEnvironment hostingEnvironment,
            IConfigManipulator configManipulator,
            IOptions<RuntimeMinificationSettings> runtimeMinificationSettings,
            CacheBusterResolver cacheBusterResolver)
        {
            _bundles = bundles;
            _smidge = smidge;
            _hostingEnvironment = hostingEnvironment;
            _configManipulator = configManipulator;
            _cacheBusterResolver = cacheBusterResolver;
            _jsMinPipeline = new Lazy<PreProcessPipeline>(() => _bundles.PipelineFactory.Create(typeof(JsMinifier)));
            _cssMinPipeline = new Lazy<PreProcessPipeline>(() => _bundles.PipelineFactory.Create(typeof(NuglifyCss)));

            // replace the default JsMinifier with NuglifyJs and CssMinifier with NuglifyCss in the default pipelines
            // for use with our bundles only (not modifying global options)
            _jsOptimizedPipeline = new Lazy<PreProcessPipeline>(() => bundles.PipelineFactory.DefaultJs().Replace<JsMinifier, SmidgeNuglifyJs>(_bundles.PipelineFactory));
            _jsNonOptimizedPipeline = new Lazy<PreProcessPipeline>(() =>
            {
                PreProcessPipeline defaultJs = bundles.PipelineFactory.DefaultJs();
                // remove minification from this pipeline
                defaultJs.Processors.RemoveAll(x => x is JsMinifier);
                return defaultJs;
            });
            _cssOptimizedPipeline = new Lazy<PreProcessPipeline>(() => bundles.PipelineFactory.DefaultCss().Replace<CssMinifier, NuglifyCss>(_bundles.PipelineFactory));
            _cssNonOptimizedPipeline = new Lazy<PreProcessPipeline>(() =>
            {
                PreProcessPipeline defaultCss = bundles.PipelineFactory.DefaultCss();
                // remove minification from this pipeline
                defaultCss.Processors.RemoveAll(x => x is CssMinifier);
                return defaultCss;
            });

            Type cacheBusterType = runtimeMinificationSettings.Value.CacheBuster switch
            {
                RuntimeMinificationCacheBuster.AppDomain => typeof(AppDomainLifetimeCacheBuster),
                RuntimeMinificationCacheBuster.Version => typeof(UmbracoSmidgeConfigCacheBuster),
                RuntimeMinificationCacheBuster.Timestamp => typeof(TimestampCacheBuster),
                _ => throw new NotImplementedException()
            };

            _cacheBusterType = cacheBusterType;
        }

        public string CacheBuster => (_cacheBuster ??= _cacheBusterResolver.GetCacheBuster(_cacheBusterType)).GetValue();

        // only issue with creating bundles like this is that we don't have full control over the bundle options, though that could
        public void CreateCssBundle(string bundleName, BundlingOptions bundleOptions, params string[]? filePaths)
        {
            if (filePaths?.Any(f => !f.StartsWith("/") && !f.StartsWith("~/")) ?? false)
            {
                throw new InvalidOperationException("All file paths must be absolute");
            }

            if (_bundles.Exists(bundleName))
            {
                throw new InvalidOperationException($"The bundle name {bundleName} already exists");
            }

            PreProcessPipeline pipeline = bundleOptions.OptimizeOutput
                ? _cssOptimizedPipeline.Value
                : _cssNonOptimizedPipeline.Value;

            Bundle bundle = _bundles.Create(bundleName, pipeline, WebFileType.Css, filePaths);
            bundle.WithEnvironmentOptions(ConfigureBundleEnvironmentOptions(bundleOptions));
        }

        public async Task<string> RenderCssHereAsync(string bundleName) => (await _smidge.SmidgeHelper.CssHereAsync(bundleName, _hostingEnvironment.IsDebugMode)).ToString();

        public void CreateJsBundle(string bundleName, BundlingOptions bundleOptions, params string[]? filePaths)
        {
            if (filePaths?.Any(f => !f.StartsWith("/") && !f.StartsWith("~/")) ?? false)
            {
                throw new InvalidOperationException("All file paths must be absolute");
            }

            if (_bundles.Exists(bundleName))
            {
                throw new InvalidOperationException($"The bundle name {bundleName} already exists");
            }

            PreProcessPipeline pipeline = bundleOptions.OptimizeOutput
                ? _jsOptimizedPipeline.Value
                : _jsNonOptimizedPipeline.Value;

            Bundle bundle = _bundles.Create(bundleName, pipeline, WebFileType.Js, filePaths);
            bundle.WithEnvironmentOptions(ConfigureBundleEnvironmentOptions(bundleOptions));
        }

        private BundleEnvironmentOptions ConfigureBundleEnvironmentOptions(BundlingOptions bundleOptions)
        {
            var bundleEnvironmentOptions = new BundleEnvironmentOptions();
            // auto-invalidate bundle if files change in debug
            bundleEnvironmentOptions.DebugOptions.FileWatchOptions.Enabled = true;
            // set cache busters
            bundleEnvironmentOptions.DebugOptions.SetCacheBusterType(_cacheBusterType);
            bundleEnvironmentOptions.ProductionOptions.SetCacheBusterType(_cacheBusterType);
            // config if the files should be combined
            bundleEnvironmentOptions.ProductionOptions.ProcessAsCompositeFile = bundleOptions.EnabledCompositeFiles;

            return bundleEnvironmentOptions;
        }

        public async Task<string> RenderJsHereAsync(string bundleName) => (await _smidge.SmidgeHelper.JsHereAsync(bundleName, _hostingEnvironment.IsDebugMode)).ToString();

        public async Task<IEnumerable<string>> GetJsAssetPathsAsync(string bundleName) => await _smidge.SmidgeHelper.GenerateJsUrlsAsync(bundleName, _hostingEnvironment.IsDebugMode);

        public async Task<IEnumerable<string>> GetCssAssetPathsAsync(string bundleName) => await _smidge.SmidgeHelper.GenerateCssUrlsAsync(bundleName, _hostingEnvironment.IsDebugMode);

        /// <inheritdoc />
        public async Task<string> MinifyAsync(string? fileContent, AssetType assetType)
        {
            switch (assetType)
            {
                case AssetType.Javascript:
                    return await _jsMinPipeline.Value
                        .ProcessAsync(
                            new FileProcessContext(fileContent, new JavaScriptFile(), BundleContext.CreateEmpty(CacheBuster)));
                case AssetType.Css:
                    return await _cssMinPipeline.Value
                        .ProcessAsync(new FileProcessContext(fileContent, new CssFile(), BundleContext.CreateEmpty(CacheBuster)));
                default:
                    throw new NotSupportedException("Unexpected AssetType");
            }
        }

        /// <inheritdoc />
        [Obsolete("Invalidation is handled automatically. Scheduled for removal V11.")]
        public void Reset()
        {
            var version = DateTime.UtcNow.Ticks.ToString();
            _configManipulator.SaveConfigValue(Cms.Core.Constants.Configuration.ConfigRuntimeMinificationVersion, version.ToString());
        }
    }
}


text:
<Object ID="DoesntContainValidator" __autoConstruct="DataSource" inheritsFrom="Validator" Constructor="doesntContain" addGlobalId="false">
    <fields>
        <substring type="string"/>
    </fields>
</Object>


text:
package com.jeeplus.weixin.fastweixin.api;

import com.jeeplus.weixin.fastweixin.api.config.ApiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author:yuzp17311
 * @version:v1.0
 * @date: 2017-02-27 17:52.
 */
public class ScanAPI extends BaseAPI {

    private static final Logger logger= LoggerFactory.getLogger(ScanAPI.class);

    /**
     * 构造方法,设置apiConfig
     *
     * @param config 微信API配置对象
     */
    protected ScanAPI(ApiConfig config) {
        super(config);
    }

}


text:
package uk.ac.ncl.openlab.intake24.client.survey.scheme;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.TextBox;
import org.pcollections.PVector;
import org.workcraft.gwt.shared.client.Callback1;
import org.workcraft.gwt.shared.client.Callback2;
import org.workcraft.gwt.shared.client.Option;
import uk.ac.ncl.openlab.intake24.client.survey.SimpleSurveyStageInterface;
import uk.ac.ncl.openlab.intake24.client.survey.Survey;
import uk.ac.ncl.openlab.intake24.client.survey.SurveyStage;
import uk.ac.ncl.openlab.intake24.client.ui.WidgetFactory;

import java.util.ArrayList;

public class MultipleChoiceCheckboxQuestion implements SurveyStage<Survey> {
    final private SafeHtml questionText;
    final private PVector<String> options;
    final private String acceptText;
    final private String dataField;
    final private Survey state;
    final private Option<String> otherOptionName;

    private CheckBox otherOption;
    private TextBox otherBox;

    public MultipleChoiceCheckboxQuestion(final Survey state, final SafeHtml questionText, final String acceptText, PVector<String> options,
                                          String dataField, Option<String> otherOptionName) {
        this.state = state;
        this.questionText = questionText;
        this.acceptText = acceptText;
        this.options = options;
        this.dataField = dataField;
        this.otherOptionName = otherOptionName;
    }

    @Override
    public SimpleSurveyStageInterface getInterface(final Callback1<Survey> onComplete, Callback2<Survey, Boolean> onIntermediateStateChange) {
        final FlowPanel content = new FlowPanel();
        content.addStyleName("intake24-multiple-choice-question");
        content.addStyleName("intake24-survey-content-container");

        content.add(WidgetFactory.createPromptPanel(questionText));

        FlowPanel checkboxesDiv = new FlowPanel();
        checkboxesDiv.addStyleName("scran24-ready-meals-checkboxes-block");

        final ArrayList<CheckBox> checkBoxes = new ArrayList<CheckBox>();

        for (String option : options) {
            FlowPanel rowDiv = new FlowPanel();
            CheckBox checkBox = new CheckBox(SafeHtmlUtils.htmlEscape(option));
            checkBox.setFormValue(option);
            checkBox.addStyleName("scran24-ready-meals-checkbox");
            checkBoxes.add(checkBox);
            rowDiv.add(checkBox);
            checkboxesDiv.add(rowDiv);
        }

        if (!otherOptionName.isEmpty()) {
            FlowPanel otherPanel = new FlowPanel();
            otherOption = new CheckBox(otherOptionName.getOrDie() + ": ");
            otherPanel.add(otherOption);
            otherBox = new TextBox();
            otherPanel.add(otherBox);
            checkboxesDiv.add(otherPanel);

            otherBox.addFocusHandler(new FocusHandler() {
                @Override
                public void onFocus(FocusEvent event) {
                    otherOption.setValue(true);
                }
            });
        }

        content.add(checkboxesDiv);

        Button accept = WidgetFactory.createGreenButton(acceptText, "multipleChoiceCheckboxContinueButton", new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {

                StringBuilder value = new StringBuilder();
                boolean first = true;

                for (CheckBox checkBox : checkBoxes)
                    if (checkBox.getValue()) {
                        if (first)
                            first = false;
                        else
                            value.append(", ");

                        value.append(checkBox.getFormValue());
                    }

                if (!otherOptionName.isEmpty()) {
                    if (otherOption.getValue()) {
                        if (!first)
                            value.append(", ");
                        value.append(otherBox.getText());
                    }
                }

                onComplete.call(state.withData(dataField, value.toString()));
            }
        });

        content.add(checkboxesDiv);
        content.add(accept);

        return new SimpleSurveyStageInterface(content, MultipleChoiceCheckboxQuestion.class.getSimpleName());
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="GenesisUI - UI Admin Kit Powered by Bootstrap 4">
  <meta name="author" content="Lukasz Holeczek">
  <meta name="keyword" content="GenesisUI - UI Admin Kit Powered by Bootstrap 4">

  <title>GenesisUI - UI Admin Kit</title>

  <link href="../css/font-awesome.min.css" rel="stylesheet">
  <link href="../css/simple-line-icons.css" rel="stylesheet">

  <link href="../css/style.css" rel="stylesheet">
  <link href="../css/docs.min.css" rel="stylesheet">

    <button class="navbar-toggler mobile-sidebar-toggler hidden-lg-up" type="button">☰</button>

        ☰

        Home

        About me

                Getting started

                    Introduction

                    Components

                    AJAX Version

                    Static Version

                    AngularJS Version

                    Angular2 Version

                    React.js Version

                    Vue.js Version

                    RTL Support

                    Browsers & devices

                    Options

                    Accessibility

                Layout

                    Overview

                    Grid

                    Media object

                    Responsive utilities

                Content

                    Reboot

                    Typography

                    Code

                    Images

                    Tables

                    Figures

                Components

                    Alerts

                    Badge

                    Breadcrumb

                    Buttons

                    Button group

                    Card

                    Carousel

                    Collapse

                    Dropdowns

                    Forms

                    Input group

                    List group

                    Modal

                    Navs

                    Navbar

                    Pagination

                    Popovers

                    Progress

                    Scrollspy

                    Tooltips

                Utilities

                    Borders

                    Clearfix

                    Close icon

                    Colors

                    Flexbox

                    Display property

                    Image replacement

                    Invisible content

                    Position

                    Responsive helpers

                    Screenreaders

                    Sizing

                    Spacing

                    Typography

                    Vertical align

                New components

                    Breadcrumb menu

                    Callout

                    Switches

                    Widgets

                    Utilities

Home

New components

Utility classes

                Utility classes

Bootstrap includes dozens of utilities—classes with a single purpose. They're designed to reduce the frequency of highly repetitive declarations in your CSS while allowing for quick and easy development.

Contents

Contents

Spacing

Spacing

Assign margin or padding to an element or a subset of its sides with shorthand classes. Includes support for individual properties, all properties, and vertical and horizontal properties. All classes are multiples on the global default value, 1rem.

The classes are named using the format: {property}-{sides}-{size}

Where property is one of:

m - for classes that set margin

p - for classes that set padding

Where sides is one of:

t - for classes that set margin-top or padding-top

b - for classes that set margin-bottom or padding-bottom

l - for classes that set margin-left or padding-left

r - for classes that set margin-right or padding-right

x - for classes that set both *-left and *-right

y - for classes that set both *-top and *-bottom

a - for classes that set a margin or padding on all 4 sides of the element

Where size is one of:

q - (by default) for classes that set the margin or padding to $spacer-x * 0.25 or $spacer-y * 0.25

h - (by default) for classes that set the margin or padding to $spacer-x * 0.5 or $spacer-y * 0.5

0 - for classes that eliminate the margin or padding by setting it to 0

1 - (by default) for classes that set the margin or padding to $spacer-x or $spacer-y

2 - (by default) for classes that set the margin or padding to $spacer-x * 1.5 or $spacer-y * 1.5

3 - (by default) for classes that set the margin or padding to $spacer-x * 3 or $spacer-y * 3

Here are some representative examples of these classes:

.px-q {
  padding-left: ($spacer-x * 0.25) !important;
  padding-right: ($spacer-x * 0.25) !important;
}

.pa-h {
  padding: ($spacer-y * 0.5) ($spacer-x * 0.5) !important;
}

        GenesisUI © 2017 creativeLabs.

        Powered by GenesisUI


text:
import {Injectable} from '@angular/core';

@Injectable()
class MyAlternateService {
}

@Injectable({providedIn: 'root', useClass: MyAlternateService})
export class MyService {
}


text:
"""Top-level package for Emu."""

from .__version__ import __author__, __email__, __version__  # noqa: F401

from .wsgi import application  # noqa: F401


text:
from subprocess import check_output
import sys

mainfile = "main.py"

def runTrial(path):
  cmd = "python %s %s" % (mainfile, path)
  print(cmd)
  out = check_output([cmd], shell=True)
  lines = out.split("\n")
  for line in lines:
    if "time:" in line:
      result = line.split(":")[1]
      return result;

if __name__ == "__main__":
  if len(sys.argv) < 3:
    print("usage: %s config_file num_trials")

  num_trials = int(sys.argv[2])
  config_path = sys.argv[1]
  results = []
  for i in range(num_trials):
    result = runTrial(config_path)
    results.append(result)

  print results