text:
package com.seleniumtests.reporter.pluginmodel;

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

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

/**
 *
Java class for anonymous complex type.
 *
 *

 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 *

   <complexType>
     <complexContent>
       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
         <sequence>
           <element ref="{}test" maxOccurs="unbounded"/>
         </sequence>
         <attribute name="purpose" use="required" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
         <attribute name="class-name" use="required" type="{http://www.w3.org/2001/XMLSchema}NMTOKEN" />
       </restriction>
     </complexContent>
   </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"test"})
@XmlRootElement(name = "plugin")
public class Plugin {

    @XmlElement(required = true)
    protected List<Test> test;
    @XmlAttribute(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NMTOKEN")
    protected String purpose;
    @XmlAttribute(name = "class-name", required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    @XmlSchemaType(name = "NMTOKEN")
    protected String className;

    /**
     * Gets the value of the className property.
     *
     * @return  possible object is {@link String }
     */
    public String getClassName() {
        return className;
    }

    /**
     * Gets the value of the purpose property.
     *
     * @return  possible object is {@link String }
     */
    public String getPurpose() {
        return purpose;
    }

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

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

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

     *

       getTest().add(newItem);
     *

     *
     *

     *

     *
Objects of the following type(s) are allowed in the list {@link Test }
     */
    public List<Test> getTest() {
        if (test == null) {
            test = new ArrayList<Test>();
        }

        return this.test;
    }

    /**
     * Sets the value of the className property.
     *
     * @param  value  allowed object is {@link String }
     */
    public void setClassName(final String value) {
        this.className = value;
    }

    /**
     * Sets the value of the purpose property.
     *
     * @param  value  allowed object is {@link String }
     */
    public void setPurpose(final String value) {
        this.purpose = value;
    }

}


text:
<tool id='export.gate_1.0.0' name='Export GATE/XML' version='1.0.0'>
  <description>export GATE/XML from a Data object</description>
  <command>lsd $__tool_directory__/export.lsd $input $output</command>
  <inputs>
    <param name='input' type='data' format='gate' />
  </inputs>
  <outputs>
    <data name='output' format='xml'/>
  </outputs>
  <help><![CDATA[

**What it does**

Gate Developer is released under the `GNU Lesser General Public License 3.0 <https://www.gnu.org/licenses/lgpl-3.0.html>`_

]]>
</help>
</tool>

redpajama_set_name: RedPajamaGithub


text:
<!--

@module {can.Component} property-table <property-table />
@parent can-admin.components
-->

## Description

A widget for getting and displaying an objects properties in a tabular two column format.
The first column is mapped to the object property name, which is formatted by removing spaces
and capitalizing the first letter. Additional display options may be provided through the
`fields` property.

## Usage

```html
<property-table object-id="3" {connection}="connection"
 {fields}="detailFields" />
```

## Demo

@demo property-table/demo/demo.html 500


text:
class HeadersController < ApplicationController

  before_action :authenticate
  before_action -> { require_permission_to 'write_graphics' }

  def index
    @headers = Header.by_recent.paginate(:page => params[:page], :per_page => 25)
    switch_to_admin_layout
  end

  def show
    @header = Header.find(params[:id])
    switch_to_admin_layout
  end

  def new
    @header = Header.new
    switch_to_admin_layout
  end

  def edit
    @header = Header.find(params[:id])
    switch_to_admin_layout
  end

  def create
    @header = Header.new(params[:header])
    if @header.save
      redirect_to @header, notice: t('headers.create.notice')
    else
      render action: "new", layout: 'admin'
    end
  end

  def update
    @header = Header.find(params[:id])
    if @header.update_attributes(params[:header])
      redirect_to @header, notice: t('headers.update.notice')
    else
      render action: "edit", layout: 'admin'
    end
  end

  def destroy
    @header = Header.find(params[:id])
    @header.destroy
    redirect_to headers_url
  end
end


text:
namespace Snow.Tests.SettingParsers
{
    using System.IO;
    using Models;
    using Xunit;

    public class PostParserTests
    {
        [Fact]
        public void Given_Location_To_Markdown_Files_Should_Be_Able_To_Open()
        {
            //Test exists to satistify my own ego to know if these files can be opened for testing.
            var files = new[]
            {
                "SettingParsers/TestFiles/series-sample-test-1.md",
                "SettingParsers/TestFiles/series-sample-test-2.md",
                "SettingParsers/TestFiles/series-sample-test-3.md",
            };

            foreach (var s in files)
            {
                var file = File.ReadAllText(s);

                Assert.NotEqual("", file);
            }
        }

        [Fact]
        public void Given_File_Should_Return_Tuple_With_Item1_Containing_Header()
        {
            var fileData = File.ReadAllText("SettingParsers/TestFiles/series-sample-test-1.md");
            const string expected = @"---
layout: post
series:
    name: 123
    current: 1
    part: test part 1
    part: test part 2
    part: test part 3
title: some title
---";

            var result = PostParser.ParseDataFromFile(fileData);

            Assert.Equal(expected, result.Item1);
        }

        [Fact]
        public void Given_File_Should_Return_Tuple_With_Item2_Containing_Post()
        {
            var fileData = File.ReadAllText("SettingParsers/TestFiles/series-sample-test-1.md");
            const string expected = @"

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Donec porttitor non velit nec feugiat.";

            var result = PostParser.ParseDataFromFile(fileData);

            Assert.Equal(expected, result.Item2);
        }

        [Fact]
        public void Given_A_File_With_No_Header_Should_Return_Raw_Post_And_Empty_Header()
        {
            var fileData = File.ReadAllText("SettingParsers/TestFiles/series-sample-test-2.md");
            const string expected = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Donec porttitor non velit nec feugiat.";

            var result = PostParser.ParseDataFromFile(fileData);

            Assert.Equal(string.Empty, result.Item1);
            Assert.Equal(expected, result.Item2);
        }

        [Fact]
        public void Given_Empty_RawSettings_Should_Return_Empty_Dictionary()
        {
            var result = PostParser.ParseSettings("");

            Assert.Empty(result);
        }

        [Fact]
        public void Given_Header_With_Empty_Settings_Should_Return_Empty_Dictionary()
        {
            var result = PostParser.ParseSettings(@"---

---");

            Assert.Empty(result);
        }

        [Fact]
        public void Given_Header_That_Contains_Two_Properties_With_Values_Should_Map_To_Dictionary_Correctly()
        {
            var fileData = File.ReadAllText("SettingParsers/TestFiles/series-sample-test-3.md");
            var result = PostParser.ParseSettings(fileData);

            Assert.Equal("post", result["layout"]);
            Assert.Equal("some title", result["title"]);
        }

        [Fact]
        public void Given_Header_Which_Contains_Blank_Lines_Should_Only_Parse_Out_Valid_Lines_Correctly()
        {
            var fileData = File.ReadAllText("SettingParsers/TestFiles/series-sample-test-4.md");
            var result = PostParser.ParseSettings(fileData);

            Assert.Equal("post", result["layout"]);
            Assert.Equal("some title", result["title"]);
            Assert.Equal(2, result.Count);
        }

        [Fact]
        public void Given_Header_Which_Contains_Series_Should_Return_Series_Key_With_Series_Object()
        {
            var fileData = File.ReadAllText("SettingParsers/TestFiles/series-sample-test-5.md");
            var result = PostParser.ParseSettings(fileData);

            Assert.True(result.ContainsKey("series"));

            var series = (Series) result["series"];

            Assert.NotEmpty(series.Parts);
            Assert.Equal("123", series.Name);
            Assert.Equal(2, series.Current);
        }
    }
}


text:
{% extends "../ar/head-signedin.html" %}

{% block page_title %}
  Review licence data - GOV.UK
{% endblock %}

{% block content %}

  {% from "custom_inc/waterdata.html" import permits %}

  {% include "../partials/feedback-banner.html" %}

  {% include "../partials/nav-ar-inbox.html" %}

        View licences

      Search for a licence
      Search by registered email address or licence number

        <input type="text" class="form-control form-control--block column-two-thirds" />

          Search

              Licence number

              Last editor

              Last edit

              Status
               ▾

                {{ permits[1].LicenceSerialNo }}

              Last editor

            J Mipps

              Last edited

            2 July 2018

              In progress

                {{ permits[2].LicenceSerialNo }}

              Last editor

            Celeste Fishood

              Last edited

            1 July 2018

              For NALD approval

                {{ permits[3].LicenceSerialNo }}

              Last editor

            Ben Jucks

              Last edited

            12 July 2018

              For NALD approval

                {{ permits[4].LicenceSerialNo }}

              Last editor

            J Mipps

              Last edited

            16 June 2018

              For NALD approval

                {{ permits[5].LicenceSerialNo }}

              Last editor

              Last edited

                {{ permits[6].LicenceSerialNo }}

              Last editor

            J Mipps

              Last edited

            31 May 2018

{% endblock %}


text:
package tbax.baxshops.commands;

import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import tbax.baxshops.*;
import tbax.baxshops.errors.PrematureAbortException;
import tbax.baxshops.CommandHelp;
import tbax.baxshops.serialization.ItemNames;

public final class CmdTake extends BaxShopCommand
{
    @Override
    public @NotNull String getName()
    {
        return "take";
    }

    @Override
    public @NotNull String[] getAliases()
    {
        return new String[]{"take","t"};
    }

    @Override
    public String getPermission()
    {
        return "shops.owner";
    }

    @Override
    public CommandHelp getHelp(@NotNull ShopCmdActor actor) throws PrematureAbortException
    {
        CommandHelp help = super.getHelp(actor);
        help.setDescription("take an item from a shop without purchasing it");
        help.setArgs(
            new CommandHelpArgument("item", "the item to take from the shop", true),
            new CommandHelpArgument("quantity", "the quantity to take from the shop", false, 1)
        );
        return help;
    }

    @Override
    public boolean hasValidArgCount(@NotNull ShopCmdActor actor)
    {
        BaxShop shop;
        if (actor.getNumArgs() == 3 || actor.getNumArgs() == 2)
            return true;
        shop = actor.getShop();
        return actor.getNumArgs() == 1 && shop != null && shop.size() == 1;
    }

    @Override
    public boolean requiresSelection(@NotNull ShopCmdActor actor)
    {
        return true;
    }

    @Override
    public boolean requiresOwner(@NotNull ShopCmdActor actor)
    {
        return true;
    }

    @Override
    public boolean requiresPlayer(@NotNull ShopCmdActor actor)
    {
        return true;
    }

    @Override
    public boolean requiresItemInHand(@NotNull ShopCmdActor actor)
    {
        return false;
    }

    @Override
    public void onCommand(@NotNull ShopCmdActor actor) throws PrematureAbortException
    {
        BaxShop shop = actor.getShop();
        BaxEntry entry;
        assert shop != null;
        if (actor.getNumArgs() == 1) {
            actor.appendArgs(1, 1);
        }
        else if (actor.getNumArgs() == 2) {
            actor.appendArg(1);
        }

        entry = actor.getArgEntry(1);
        BaxQuantity amt = actor.getArgShopQty(2, entry);

        if (!shop.hasFlagInfinite()) {
            if (amt.getQuantity() > entry.getAmount()) {
                actor.exitError(Resources.NO_SUPPLIES);
            }
            else if (entry.getAmount() == 0) {
                actor.exitError("There's no more %s in the shop", entry.getName());
            }
        }
        if (amt.getQuantity() < 0) {
            actor.exitError(Resources.INVALID_DECIMAL, "amount to take");
        }
        else if (amt.getQuantity() == 0) {
            actor.exitError("You took nothing");
        }

        ItemStack stack = entry.toItemStack();
        stack.setAmount(amt.getQuantity());
        entry.subtract(amt.getQuantity());

        int overflow = actor.giveItem(stack);
        if (overflow > 0) {
            entry.add(overflow);
            actor.sendMessage(Resources.SOME_ROOM, amt.getQuantity() - overflow, ItemNames.getName(stack));
        }
        else {
            actor.sendMessage("%s %s added to your inventory.",
                Format.itemName(
                    stack.getAmount(),
                    ItemNames.getName(stack)),
                amt.getQuantity() == 1 ? "was" : "were"
            );
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<title>The cloudi_service_db_pgsql application</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="EDoc">

Modules

cloudi_service_db_pgsql


text:
__revision__ = "test/GetOption/help.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"

"""
Test use of GetOption('help') to short-circuit work.
"""

import TestSCons

test = TestSCons.TestSCons()

test.write('SConstruct', """\
if GetOption('help'):
   print "GetOption('help') set"
else:
    print "no help for you"
""")

test.run(arguments = '-q -Q', stdout = "no help for you\n")

expect = "GetOption('help') set"

test.run(arguments = '-q -Q -h')
test.fail_test(test.stdout().split('\n')[0] != expect)

test.run(arguments = '-q -Q --help')
test.fail_test(test.stdout().split('\n')[0] != expect)

test.pass_test()

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


text:
/**
 * Problem description:      Implement an algorithm to delete a node in the middle of a singly linked list,
 *                           given only access to that node.
 * Solution time complexity: O(n)
 * Comments:
 */

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param node: a node in the list should be deleted
     * @return: nothing
     */
    void deleteNode(ListNode *node)
    {
        auto temp = node->next;
        *node     = std::move(*node->next);

        delete temp; temp = nullptr;
    }
};


text:
module VirtualBox
  module COM
    module Interface
      module Version_4_1_X
        class Console < AbstractInterface
          IID = "6375231a-c17c-464b-92cb-ae9e128d71c3"

          property :machine, :Machine, :readonly => true
          property :state, :MachineState, :readonly => true
          property :guest, :Guest, :readonly => true
          property :keyboard, :Keyboard, :readonly => true
          property :mouse, :Mouse, :readonly => true
          property :display, :Display, :readonly => true
          property :debugger, :MachineDebugger, :readonly => true
          property :usb_devices, [:USBDevice], :readonly => true
          property :remote_usb_devices, [:HostUSBDevice], :readonly => true
          property :shared_folders, [:SharedFolder], :readonly => true
          property :vrde_server_info, :VRDEServerInfo, :readonly => true
          property :event_source, :EventSource, :readonly => true
          property :attached_pci_devices, [:PciDeviceAttachment], :readonly => true
          property :use_host_clipboard, T_BOOL

          function :power_up, :Progress, []
          function :power_up_paused, :Progress, []
          function :power_down, :Progress, []
          function :reset, nil, []
          function :pause, nil, []
          function :resume, nil, []
          function :power_button, nil, []
          function :sleep_button, nil, []
          function :get_power_button_handled, T_BOOL, []
          function :get_guest_entered_acpi_mode, T_BOOL, []
          function :save_state, :Progress, []
          function :adopt_saved_state, nil, [WSTRING]
          function :discard_saved_state, nil, [T_BOOL]
          function :get_device_activity, :DeviceActivity, [:DeviceType]
          function :attach_usb_device, nil, [WSTRING]
          function :detach_usb_device, :USBDevice, [WSTRING]
          function :find_usb_device_by_address, :USBDevice, [WSTRING]
          function :find_usb_device_by_id, :USBDevice, [WSTRING]
          function :create_shared_folder, nil, [WSTRING, WSTRING, T_BOOL, T_BOOL]
          function :remove_shared_folder, nil, [WSTRING]
          function :take_snapshot, :Progress, [WSTRING, WSTRING]
          function :delete_snapshot, :Progress, [WSTRING]
          function :delete_snapshot_and_all_children, :Progress, [WSTRING]
          function :delete_snapshot_range, :Progress, [WSTRING, WSTRING]
          function :restore_snapshot, :Progress, [:Snapshot]
          function :teleport, :Progress, [WSTRING, T_UINT32, WSTRING, T_UINT32]
        end
      end
    end
  end
end


text:
"""
This is an example file which tell you how to use QPython to develop android app.
If get a video link address from a remote webpage and play it with the A8 Player to play. ( It needs the network )

@Author: River
@Date: 2012-10-22
"""

from jnius import cast
from jnius import autoclass
from jnius import JavaException
from android import AndroidBrowser
from urllib2 import urlopen

print "[A8 Player with qpython example]"

# get and parse video link
response = urlopen('http://qpython.com/samples/script_data.txt')
if response:
    content = response.read()
    import json
    data = json.loads(content)
    link = data['link']

    # get android object
    PythonActivity = autoclass('org.renpy.android.PythonActivity')
    Intent = autoclass('android.content.Intent')
    Uri = autoclass('android.net.Uri')
    Toast = autoclass('android.widget.Toast')

    # play the url
    intent = Intent()
    intent.setAction(Intent.ACTION_VIEW)
    intent.setClassName('com.hipipal.mna8', 'com.hipipal.mna8.PLAPlayerAct')
    intent.setDataAndType(Uri.parse(link), 'video/*')
    currentActivity = cast('android.app.Activity', PythonActivity.mActivity)

    try:
        s = "Play Video: %s..." % link
        print s

        currentActivity.startActivity(intent)
    except JavaException:
        s = "Need install A8 Player App first"
        print s

        browser = AndroidBrowser()
        browser.open("http://play.tubebook.net/a8-video-player.html")

    print "[A8 Player with qpython END]"

else:

    print "Maybe network error, could not get the parameters for play"


text:
package org.adg.learning.algorithm.alg4;
/******************************************************************************
 *  Compilation:  javac PrintEnergy.java
 *  Execution:    java PrintEnergy input.png
 *  Dependencies: SeamCarver.java
 *
 *
 *  Read image from file specified as command line argument. Print energy
 *  of each pixel as calculated by SeamCarver object.
 *
 ******************************************************************************/

import edu.princeton.cs.algs4.Picture;
import edu.princeton.cs.algs4.StdOut;

public class PrintEnergy {

    public static void main(String[] args) {
        Picture picture = new Picture(args[0]);
        StdOut.printf("image is %d pixels wide by %d pixels high.\n", picture.width(), picture.height());

        SeamCarver sc = new SeamCarver(picture);

        StdOut.printf("Printing energy calculated for each pixel.\n");

        for (int row = 0; row < sc.height(); row++) {
            for (int col = 0; col < sc.width(); col++)
                StdOut.printf("%9.0f ", sc.energy(col, row));
            StdOut.println();
        }
    }

}


text:
<!DOCTYPE html>

        <title>toast</title>
		<meta charset="utf-8">
		<link rel="stylesheet" href="node_modules/qunitjs/qunit/qunit.css">


text:
package com.tenxerconsulting.swagger.doclet.sample.resources;

import com.yammer.dropwizard.auth.Auth;

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/Auth")
public class AuthResource {
    /**
     * @status 404 not found
     */
    @GET
    public String authorize(@Auth String user) {
        return "USER = " + user;
    }
}


text:
Given(/^the following proposed organisations exist:$/) do |table|
  require 'boolean'
  table.hashes.each do |hash|
    create_hash = {}
    proposer = nil
    hash.each_pair do |field_name, field_value|
      if field_name != "proposer_email"
        key_value_to_add = {field_name.to_sym => field_value}
      else
        proposer = User.find_by(email: field_value)
      end
      create_hash.merge! key_value_to_add unless key_value_to_add.nil?
    end
    proposed_org = ProposedOrganisation.new create_hash
    proposed_org.users << proposer if proposer
    proposed_org.save!
  end
end

Given(/^a proposed organisation has been proposed by "(.*)"$/) do |user_email|
  usr = User.find_by(email: user_email)
  unsaved_proposed_organisation(usr).save!
end

Then(/^I should see the details of the proposed organisation$/) do
  [:name, :description, :email, :address, :postcode].each do |key|
    expect(page).to have_content unsaved_proposed_organisation[key]
  end
  ["Donate to Friendly Charity now!", 'We are a not for profit organisation registered or working in Harrow'].each do |value|
      expect(page).to have_content value
  end
end

Given /^the following organisations exist:$/ do |organisations_table|
  organisations_table.hashes.each do |org|
    VCR.use_cassette("#{org["name"]}-#{org["postcode"]}") do
      Organisation.create! org
    end
  end
end

Given /^the following users are registered:$/ do |users_table|
  users_table.hashes.each do |user|
    user["superadmin"] = user["superadmin"] == "true"
    user["organisation"] = Organisation.find_by_name(user["organisation"])
    user["pending_organisation"] = Organisation.find_by_name(user["pending_organisation"])
    User.create! user
  end
end

Given /the following volunteer opportunities exist/ do |volunteer_ops_table|
  volunteer_ops_table.hashes.each do |volunteer_op|
    volunteer_op["organisation"] = Organisation.find_by_name(volunteer_op["organisation"])
    VolunteerOp.create! volunteer_op
  end
end

Given /the following categories exist/ do |categories_table|
  categories_table.hashes.each do |cat|
    Category.create! cat
  end
end

Given /^the following categories_organisations exist:$/ do |join_table|
  join_table.hashes.each do |row|
     cat = Category.find_by_name row[:category]
     org = Organisation.find_by_name row[:organisation]
     org.categories << cat
  end
end

Given /^the proposed organisations have the categories:$/ do |join_table|
  join_table.hashes.each do |row|
     cat = Category.find_by_name row[:category]
     org = ProposedOrganisation.find_by_name row[:proposed_organisation]
     org.categories << cat
  end
end

Given /^the following pages exist:$/ do |pages_table|
  pages_table.hashes.each do |page|
    Page.create! page
  end
end

When(/^a static page named "(.*?)" with permalink "(.*?)" and markdown content:$/) \
do |name, permalink, content|
  Page.create!(:name => name,
               :permalink => permalink,
               :content => content,
               :link_visible => true)
end

And(/^a file exists:$/) do |table|
  CSV.open("db/email_test.csv", "wb") do |csv|
    csv << table.hashes[0].keys
    table.hashes.each do |org|
      csv << org.values
    end
  end
end

Then(/^the organisation "([^"]*)" should be deleted$/) do |name|
  org = Organisation.only_deleted.find_by_name name
  expect(org).not_to be_nil
end

Then(/^the "(.*?) proposed edits for the organisation named "(.*?)" should only be soft deleted$/) do |number, name|
  number = number.to_i
  org = Organisation.with_deleted.find_by(name: name)
  expect(ProposedOrganisationEdit.where(organisation: org)).to be_empty
  expect(ProposedOrganisationEdit.with_deleted.where(organisation: org).size).to eq number
end


text:
package com.djs.learn.sorting;

public class SelectionSort extends AbstractSorting
{
	public String getMethodName(){
		return "Selection Sort";
	}

	@Override
	public Integer[] sort(Integer[] data, boolean output){
		int i, j, smallestPosition;

		if (output) {
			System.out.printf("%2c, %2c: ", 'i', 'j');
			printData(data);
		}

		// 1. In first sub-list, find the smallest element, and put in the first position.
		// 2. Decrease the sub-list.
		// 3. In second sub-list, find the smallest element, and put in the second position.
		// 4. Repeat 2 and 3.

		for (i = 0; i < data.length; i++) {
			// Keep current position, suppose the element is the smallest in the following sub-list.
			smallestPosition = i;

			// Find real smallest element in the sub-list,
			// and keep that position.
			for (j = i + 1; j < data.length; j++) {
				if (data[j] < data[smallestPosition]) {
					smallestPosition = j;
				}
			}

			// If there is another real smallest element,
			// swap them.
			if (smallestPosition != i) {
				data[i] = (Integer)swap(data[smallestPosition], data[smallestPosition] = data[i]);

				if (output) {
					System.out.printf("      : %2d->%2d\n", smallestPosition, i);
				}
			}

			if (output) {
				System.out.printf("%2d, %2d: ", i, j);
				printData(data);
			}
		}

		return data;
	}
}


text:
'use strict';

module.exports = (it, expect, collect) => {
  it('should return a random item from the collection', () => {
    const collection = collect([1, 2, 3, 4, 5]);
    const random = collection.random();

    expect(random).to.be.within(1, 5);
    expect(collection.all().length).to.eql(5);
  });

  it('should return n random items from the collection', () => {
    const arrayOfRandomValues = collect([1, 2, 3, 4, 5]).random(3);

    expect(arrayOfRandomValues.all().length).to.eql(3);
    expect(arrayOfRandomValues.all()[0]).to.be.within(1, 5);
    expect(arrayOfRandomValues.all()[1]).to.be.within(1, 5);
    expect(arrayOfRandomValues.all()[2]).to.be.within(1, 5);
    expect(arrayOfRandomValues.all()[3]).to.eql(undefined);
  });

  it('should return n random items from the collection, also when 1 is passed', () => {
    const arrayOfRandomValues = collect([1, 2, 3, 4, 5]).random(1);

    expect(arrayOfRandomValues.all().length).to.eql(1);
    expect(arrayOfRandomValues.all()[0]).to.be.within(1, 5);
  });

  it('should not modify the collection', () => {
    const collection = collect([1, 2, 3, 4, 5, 8, 6]);
    collection.random();
    expect(collection.all()).to.eql([1, 2, 3, 4, 5, 8, 6]);
  });

  it('should work when collection is based on an object', () => {
    const collection = collect({
      first: 1,
      second: 2,
      third: 3,
      fourth: 4,
    });

    expect(collection.random()).to.be.within(1, 4);

    expect(collection.all()).to.eql({
      first: 1,
      second: 2,
      third: 3,
      fourth: 4,
    });
  });
};


text:
package org.archive.format.gzip.zipnum;
/**
 * ZipNumCluster
 *
 * A ZipNumIndex representing multiple shards which can be loaded dynamically. The shard locations are loaded dynamically
 * from a specified file and can be reloaded at a specified internval.
 *   Files used
 *   - ALL.loc - a required file specifying <shard>\t<location uri>[\t<more location uris>]
 *   - ALL.lastblocks - a file specifying size of last blocks in each shard. This is optional and only used for size calculation.
 *
 */

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.archive.util.ArchiveUtils;
import org.archive.util.GeneralURIStreamFactory;
import org.archive.util.binsearch.SeekableLineReader;
import org.archive.util.binsearch.SeekableLineReaderFactory;
import org.archive.util.binsearch.SeekableLineReaderIterator;
import org.archive.util.binsearch.impl.HTTPSeekableLineReader;
import org.archive.util.iterator.CloseableIterator;

public class ZipNumCluster extends ZipNumIndex {

	final static Logger LOGGER = Logger.getLogger(ZipNumCluster.class.getName());

	protected final static CloseableIterator<String> EMPTY_ITERATOR = new CloseableIterator<String>()
	{
		@Override
		public boolean hasNext() {
			return false;
		}

		@Override
		public String next() {
			return null;
		}

		@Override
		public void remove() {

		}

		@Override
		public void close() throws IOException {

		}
	};

	private class LocationUpdater implements Runnable
	{
		@Override
		public void run() {
			try {
				while (true) {
					long currModTime = locReaderFactory.getModTime();

					if (currModTime != lastModTime) {
						syncLoad(currModTime);

						Thread.sleep(checkInterval);

						if (summary != null) {
							summary.reloadFactory();
						}
					}

					Thread.sleep(checkInterval);
				}
			} catch (InterruptedException ie) {

			}
		}
	}

	protected HashMap<String, String[]> locMap = null;
	protected SeekableLineReaderFactory locReaderFactory = null;
	protected String locFile;

	protected long lastModTime = 0;

	protected int checkInterval = 30000;

	protected Thread updaterThread;

	public final static String EARLIEST_TIMESTAMP = "_EARLIEST";
	public final static String LATEST_TIMESTAMP = "_LATEST";
	public final static String OFF = "OFF";

	protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	protected Date startDate, endDate;

	class BlockSize
	{
		String urltimestamp;
		long count;
	}

	protected BlockSize[] lastBlockSizes = new BlockSize[0];
	protected String blockSizesFile;

	protected String locRoot = null, newLocRoot = null;

	protected long totalAdjustment = 0;

	protected Date newStartDate, newEndDate;
	protected boolean newIsDisabled = false;
	protected boolean disabled = false;

	//final static int DEFAULT_LOC_CACHE_EXPIRE_MILLIS = 120000;

	protected ConcurrentHashMap<String, LocCacheEntry> locCacheMap;

	protected boolean cacheRemoteLoc = false;

	protected int locCacheExpireMillis = 120000;

	protected int locCacheMaxDuration = 1000;

	class LocCacheEntry
	{
		String loc;
		long expire;

		LocCacheEntry(String loc, long expire)
		{
			this.loc = loc;
			this.expire = expire;
		}

		public boolean equals(Object obj)
		{
			if (obj == null) {
				return false;
			}

			if (obj instanceof String) {
				return loc.equals(obj);
			}

			if (obj instanceof LocCacheEntry) {
				return loc.equals(((LocCacheEntry)obj).loc);
			}

			return false;
		}
	}

	@Override
	public void init() throws IOException
	{
		super.init();

		this.blockSizesFile = locFile.replaceAll(".loc", ".lastblocks");

		locMap = new HashMap<String, String[]>();

		if (cacheRemoteLoc) {
			locCacheMap = new ConcurrentHashMap<String, LocCacheEntry>();
		}

		try {
			locReaderFactory = GeneralURIStreamFactory.createSeekableStreamFactory(locFile, false);
			lastModTime = locReaderFactory.getModTime();

			loadPartLocations(locMap);

		} catch (IOException io) {
			LOGGER.warning("Exception on Load -- Disabling Cluster! " + io.toString());
			disabled = true;
			return;
		}

		disabled = newIsDisabled;
		startDate = newStartDate;
		endDate = newEndDate;
		locRoot = newLocRoot;
		this.cdxLinesTotalCount = computeTotalLines();

		if (!disabled) {
			this.loadLastBlockSizes(blockSizesFile);
		}

		if (checkInterval > 0) {
			updaterThread = new Thread(new LocationUpdater(), "LocationUpdaterThread");
			updaterThread.start();
		}
	}

	protected void syncLoad(long newModTime)
	{
		HashMap<String, String[]> destMap = new HashMap<String, String[]>();

		try {
			loadPartLocations(destMap);
		} catch (IOException e) {
			LOGGER.warning(e.toString());
			return;
		}

		if (!disabled) {
			this.loadLastBlockSizes(blockSizesFile);
		}

		if (LOGGER.isLoggable(Level.INFO)) {
			LOGGER.info("*** Location Update: " + locFile);
		}

		ArrayList<String[]> filesToClose = new ArrayList<String[]>();

		synchronized (this) {
			for (Entry<String, String[]> files : destMap.entrySet()) {
				String[] existingFiles = locMap.get(files.getKey());

				String[] newFiles = files.getValue();

				if ((existingFiles != null) && !Arrays.equals(existingFiles, newFiles)) {
					filesToClose.add(existingFiles);
				}

				locMap.put(files.getKey(), newFiles);
			}

			//locMap.putAll(destMap);

			startDate = newStartDate;
			endDate = newEndDate;
			disabled = newIsDisabled;
			locRoot = newLocRoot;

			this.cdxLinesTotalCount = computeTotalLines();
		}

		if (this.locCacheMap != null) {
			locCacheMap.clear();
		}

		closeExistingFiles(filesToClose);

		lastModTime = newModTime;
	}

	private void closeExistingFiles(ArrayList<String[]> filesToClose) {
		for (String[] files : filesToClose) {
			for (String file : files) {
				try {
					blockLoader.closeFileFactory(file);
				} catch (IOException e) {
					LOGGER.warning(e.toString());
				}
			}
		}
	}

	public synchronized String[] getLocations(String key)
	{
		return locMap.get(key);
	}

	public String getLocRoot()
	{
		return locRoot;
	}

	public String getLocFile()
	{
		return locFile;
	}

	public void setLocFile(String locFile)
	{
		this.locFile = locFile;
	}

	public int getLocCacheExpireMillis() {
		return locCacheExpireMillis;
	}

	public void setLocCacheExpireMillis(int locCacheExpireMillis) {
		this.locCacheExpireMillis = locCacheExpireMillis;
	}

	public int getLocCacheMaxDuration() {
		return locCacheMaxDuration;
	}

	public void setLocCacheMaxDuration(int locCacheMaxDuration) {
		this.locCacheMaxDuration = locCacheMaxDuration;
	}

	public boolean isCacheRemoteLoc() {
		return cacheRemoteLoc;
	}

	public void setCacheRemoteLoc(boolean cacheRemoteLoc) {
		this.cacheRemoteLoc = cacheRemoteLoc;
	}

	protected Date parseDate(String date)
	{
		try {
			return dateFormat.parse(date);
		} catch (ParseException e) {
			return null;
		}
	}

	public boolean dateRangeCheck(String key)
	{
		// Allow a cluster to be "disabled" by specifying an empty ALL.loc
		if (disabled) {
			return false;
		}

		if ((startDate == null) && (endDate == null)) {
			return true;
		}

		int spaceIndex = key.indexOf(' ');
		if (spaceIndex < 0) {
			return true;
		}

		String dateStr = key.substring(spaceIndex + 1);
		Date reqDate = null;

		try {
			reqDate = ArchiveUtils.getDate(dateStr);
		} catch (ParseException e) {
			return true;
		}

		if ((startDate != null) && reqDate.before(startDate)) {
			return false;
		}

		if ((endDate != null) && reqDate.after(endDate)) {
			return false;
		}

		return true;
	}

	protected void loadLastBlockSizes(String filename)
	{
		BufferedReader reader = null;

		String line = null;

		List<BlockSize> list = new ArrayList<BlockSize>();
		totalAdjustment = 0;

		try {
			reader = new BufferedReader(new FileReader(filename));

			while ((line = reader.readLine()) != null) {
				String[] splits = line.split("\t");

				BlockSize block = new BlockSize();
				block.count = Long.parseLong(splits[1]);
				block.urltimestamp = splits[2];
				list.add(block);
				totalAdjustment += block.count;
			}
		} catch (Exception e) {
			LOGGER.warning(e.toString());

		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					LOGGER.warning(e.toString());
				}
			}
		}

		lastBlockSizes = list.toArray(new BlockSize[list.size()]);
	}

	protected void loadPartLocations(HashMap<String, String[]> destMap) throws IOException
	{
		SeekableLineReaderIterator lines = null;

		newStartDate = newEndDate = null;
		newIsDisabled = false;

		try {

			lines = new SeekableLineReaderIterator(locReaderFactory.get());

			while (lines.hasNext()) {
				String line = lines.next();

				if (line.isEmpty()) {
					continue;
				}

				String[] parts = line.split("\\t");

				if (parts[0].equals(OFF)) {
					newIsDisabled = true;
					break;
				}

				if (parts.length < 2) {
					String msg = "Bad line(" + line + ") in (" + locFile + ")";
					LOGGER.warning(msg);
					continue;
				}

				if (parts[0].equals(EARLIEST_TIMESTAMP)) {
					newStartDate = parseDate(parts[1]);
					continue;
				} else if (parts[0].equals(LATEST_TIMESTAMP)) {
					newEndDate = parseDate(parts[1]);
					continue;
				}

				String locations[] = new String[parts.length - 1];

				if (newLocRoot == null) {
					int lastSlash = parts[1].lastIndexOf('/');
					newLocRoot = parts[1].substring(0, lastSlash + 1);
				}

				for (int i = 1; i < parts.length; i++) {
					locations[i-1] = parts[i];
				}

				destMap.put(parts[0], locations);
			}
		} finally {
			if (lines != null) {
				lines.close();
			}
		}
	}

	public int getCheckInterval() {
		return checkInterval;
	}

	public void setCheckInterval(int checkInterval) {
		this.checkInterval = checkInterval;
	}

	public long getTotalAdjustment() {
		return totalAdjustment;
	}

	public int getNumBlocks() {
		return lastBlockSizes.length;
	}

	public long getLastBlockDiff(String startKey, int startPart, int endPart) {
		if (startPart >= lastBlockSizes.length || endPart >= lastBlockSizes.length) {
			return 0;
		}

		if (startKey.equals(lastBlockSizes[startPart].urltimestamp)) {
			startPart++;
		}

		long diff = 0;

		for (int i = startPart; i < endPart; i++) {
			diff += lastBlockSizes[i].count;
			diff -= this.getCdxLinesPerBlock();
		}

		return diff;
	}

	// Adjust from shorter blocks, if loaded
	public long computeTotalLines()
	{
		long numLines = 0;

		try {
			numLines = this.getNumLines(summary.getRange("", ""));
		} catch (IOException e) {
			LOGGER.warning(e.toString());
			return 0;
		}

		long adjustment = getTotalAdjustment();
		numLines -= (getNumBlocks() - 1);
		numLines *= this.getCdxLinesPerBlock();
		numLines += adjustment;
		return numLines;
	}

	public CloseableIterator<String> getCDXIterator(String key, String start, String end, ZipNumParams params) throws IOException {

		if (!dateRangeCheck(key)) {
			return EMPTY_ITERATOR;
		}

		return super.getCDXIterator(key, start, end, params);
	}

	public CloseableIterator<String> getCDXIterator(String key, String prefix, boolean exact, ZipNumParams params) throws IOException {

		if (!dateRangeCheck(key)) {
			return EMPTY_ITERATOR;
		}

		return super.getCDXIterator(key, prefix, exact, params);
	}

	public boolean isDisabled() {
		return this.disabled;
	}

	@Override
	SeekableLineReader doBlockLoad(String partId, long startOffset, int totalLength) {

		SeekableLineReader reader = null;

		String[] locations = getLocations(partId);

		if (locations == null) {
			LOGGER.severe("No locations for block(" + partId +")");
			return null;
		}

		// Attempt cached load for http
		if (cacheRemoteLoc && (locCacheMap != null) && (locations.length > 0) && GeneralURIStreamFactory.isHttp(locations[0])) {
			reader = loadCachedBalancedReader(partId, locations, startOffset, totalLength);
		} else {
		// Standard block load path
			for (String location : locations) {
				reader = blockLoader.attemptLoadBlock(location, startOffset, totalLength, true, isRequired());
				if (reader != null) {
					return reader;
				}
			}
		}

		return reader;
	}

	protected String locCacheGet(String key)
	{
		LocCacheEntry entry = locCacheMap.get(key);

		if (entry == null) {
			return null;
		}

		if (System.currentTimeMillis() > entry.expire) {
			locCacheMap.remove(key);
			return null;
		}

		return entry.loc;
	}

	protected void locCachePut(String key, String loc)
	{
		locCacheMap.putIfAbsent(key, new LocCacheEntry(loc, System.currentTimeMillis() + locCacheExpireMillis));
	}

	SeekableLineReader loadCachedBalancedReader(String partId, String[] locations, long offset, int length)
	{
		SeekableLineReader reader = null;

		String cachedUrl = locCacheGet(partId);

		if (cachedUrl != null) {
			long start = System.currentTimeMillis();

			reader = blockLoader.attemptLoadBlock(cachedUrl, offset, length, true, false);

			long duration = System.currentTimeMillis() - start;

			if ((reader == null) || (duration > locCacheMaxDuration)) {
				locCacheMap.remove(partId, cachedUrl);
			}

			if (reader != null) {
				return reader;
			}
		}

		ArrayList<Integer> indexs = new ArrayList<Integer>();

		for (int i = 0; i < locations.length; i++) {
			indexs.add(i);
		}
		if (locations.length > 1) {
			Collections.shuffle(indexs);
		}

		final int lastIndex = locations.length - 1;

		for (int i = 0; i < indexs.size(); i++) {

			int index = indexs.get(i);

			// Skip failed cached url
			if ((cachedUrl != null) && locations[index].equals(cachedUrl)) {
				continue;
			}

			long start = System.currentTimeMillis();

			boolean required = (isRequired() && (i == lastIndex));

			reader = blockLoader.attemptLoadBlock(locations[index], offset, length, true, required);

			long duration = System.currentTimeMillis() - start;

			if (reader != null) {
				String connectedUrl = ((HTTPSeekableLineReader)reader).getConnectedUrl();

				if ((duration < locCacheMaxDuration) && (connectedUrl != null)) {
					locCachePut(partId, connectedUrl);
				}

				return reader;
			}
		}

		return reader;
	}
}


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.PortfolioManager.domain.entities;

import com.PortfolioManager.domain.dao.IPortfolioDAO;
import com.PortfolioManager.domain.impl.PortfolioDAO;
import java.io.Serializable;
import java.util.Collection;
import java.util.StringTokenizer;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

/**
 *
 * @author Ahmed
 */
@Entity
public class Account implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private double money;
    private double investedMoney;
    private double initialMoney;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "account")
    private Collection<Portfolio> portfolios;

    private long selectedPortfolio;

    @OneToOne(mappedBy="account")
    private Investor investor;

    public Account() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Investor getInvestor() {
        return investor;
    }

    public void setInvestor(Investor investor) {
        this.investor = investor;
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public Collection<Portfolio> getPortfolios() {
        return portfolios;
    }

    public Portfolio getPortfolio()
    {
        IPortfolioDAO iPortfolioDAO=new PortfolioDAO();
        Portfolio portfolio=iPortfolioDAO.getPortfolioById(selectedPortfolio);
        return portfolio;
    }

    public void setPortfolios(Collection<Portfolio> portfolios) {
        this.portfolios = portfolios;
    }

    public void addPortfolio(Portfolio portfolio) {
        portfolio.setAccount(this);
        IPortfolioDAO iPortfolioDAO = new PortfolioDAO();
        iPortfolioDAO.persist(portfolio);

        double aux=portfolio.getLiquidMoney();

        setSelectedPortfolio(portfolio.getId());
        investedMoney+=aux;
        money-=aux;
        selectedPortfolio=portfolio.getId();
        portfolios.add(portfolio);
    }

    public void removePortfolio(Long id) {
        IPortfolioDAO iPortfolioDAO=new PortfolioDAO();
        Portfolio p=iPortfolioDAO.getPortfolioById(id);
        portfolios.remove(p);
        iPortfolioDAO.delete(p);
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Account)) {
            return false;
        }
        Account other = (Account) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.domain.entities.Account[ id=" + id + " ]";
    }

    public String displayMoney() {
		String monney;
		StringTokenizer st = new StringTokenizer("" + money, ".");
		monney = st.nextToken();
		String comma = st.nextToken();

		int l = comma.length();
		if (l > 2)
			l = 2;

		monney = monney + "." + comma.substring(0, l);
		return monney;
	}

    /**
     * @return the selectedPortfolio
     */
    public long getSelectedPortfolio() {
        return selectedPortfolio;
    }

    /**
     * @param selectedPortfolio the selectedPortfolio to set
     */
    public void setSelectedPortfolio(long selectedPortfolio) {
        this.selectedPortfolio = selectedPortfolio;
    }

    /**
     * @return the investedMoney
     */
    public double getInvestedMoney() {
        return investedMoney;
    }

    /**
     * @param investedMoney the investedMoney to set
     */
    public void setInvestedMoney(double investedMoney) {
        this.investedMoney = investedMoney;
    }

    public void credit(double money){
        this.money+=money;
        investedMoney-=money;
    }
    public void debit(double money)
    {
        this.money-=money;
        investedMoney+=money;
    }

    /**
     * @return the initialMoney
     */
    public double getInitialMoney() {
        return initialMoney;
    }

    /**
     * @param initialMoney the initialMoney to set
     */
    public void setInitialMoney(double initialMoney) {
        this.initialMoney = initialMoney;
    }
}


text:
package com.example.coolweather;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.coolweather.gson.Forecast;
import com.example.coolweather.gson.Weather;
import com.example.coolweather.service.AutoUpdateService;
import com.example.coolweather.util.HttpUtil;
import com.example.coolweather.util.Utility;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {

    public DrawerLayout drawerLayout;

    private Button navButton;

    public SwipeRefreshLayout swipeRefresh;
    private String mWeatherId;

    private ScrollView weatherLayout;

    private TextView titleCity;

    private TextView titleUpdateTime;

    private TextView degreeText;

    private TextView weatherInfoText;

    private LinearLayout forecastLayout;

    private TextView aqiText;

    private TextView pm25Text;

    private TextView comfortText;

    private TextView carWashText;

    private TextView sportText;

    private ImageView bingPicImg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21){
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
             | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        setContentView(R.layout.activity_weather);
        //初始化控件
        weatherLayout = (ScrollView) findViewById(R.id.weather_layout);
        titleCity = (TextView) findViewById(R.id.title_city);
        titleUpdateTime = (TextView) findViewById(R.id.title_update_time);
        degreeText = (TextView) findViewById(R.id.degree_text);
        weatherInfoText = (TextView) findViewById(R.id.weather_info_text);
        forecastLayout = (LinearLayout) findViewById(R.id.forecast_layout);
        aqiText = (TextView) findViewById(R.id.aqi_text);
        pm25Text = (TextView) findViewById(R.id.pm25_text);
        comfortText = (TextView) findViewById(R.id.comfort_text);
        carWashText = (TextView) findViewById(R.id.car_wash_text);
        sportText = (TextView) findViewById(R.id.sport_text);
        bingPicImg = (ImageView) findViewById(R.id.bing_pic_img);
        swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh);
        swipeRefresh.setColorSchemeResources(R.color.colorPrimary);

        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        navButton = (Button) findViewById(R.id.nav_button);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherString = preferences.getString("weather",null);
        if (weatherString!=null){
            //有缓存数据时直接解析天气数据
            Weather weather = Utility.handleWeatherResponse(weatherString);
            mWeatherId = weather.basic.weatherId;
            showWeatherInfo(weather);
        }else {
            //无天气数据时去服务器查询
            mWeatherId = getIntent().getStringExtra("weather_id");
            weatherLayout.setVisibility(View.INVISIBLE);
            requestWeather(mWeatherId);
        }

        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeather(mWeatherId);
            }
        });

        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });

        String bingPic = preferences.getString("bing_pic",null);
        if (bingPic!=null){
            Glide.with(this).load(bingPic).into(bingPicImg);
        }else {
            loadBingPic();
        }
    }

    private void loadBingPic() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager
                        .getDefaultSharedPreferences(WeatherActivity.this)
                        .edit();
                editor.putString("bing_pic",bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg);
                    }
                });
            }
        });
    }

    /**
     *根据天气id请求城市天气信息
     */
    void requestWeather(String weatherId) {
        Log.d("aaaaaaaa", "向服务器请求的Id:"+weatherId);
        String weatherUrl = "http://guolin.tech/api/weather?cityid="+weatherId+
                "&key=596a292706ba4c0a864962d5063c48e9";
        HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(WeatherActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT).show();
                        swipeRefresh.setRefreshing(false);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String responseText = response.body().string();
                final Weather weather = Utility.handleWeatherResponse(responseText);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (weather!=null && "ok".equals(weather.status)){
                            SharedPreferences.Editor editor = PreferenceManager
                                    .getDefaultSharedPreferences(WeatherActivity.this)
                                    .edit();
                            editor.putString("weather",responseText);
                            editor.apply();
                            mWeatherId = weather.basic.weatherId;
                            showWeatherInfo(weather);
                        }else {
                            Toast.makeText(WeatherActivity.this,"获取天气信息失败",Toast.LENGTH_SHORT).show();
                        }
                        swipeRefresh.setRefreshing(false);
                    }
                });
            }
        });
        loadBingPic();
    }

    /**
     * 处理并展示Weather实体类的数据
     */
    private void showWeatherInfo(Weather weather) {
        String cityName = weather.basic.cityName;
        String updateTime = weather.basic.update.updateTime.split(" ")[1];
        String degreed = weather.now.temperature+"℃";
        String weatherInfo =weather.now.more.info;
        titleCity.setText(cityName);
        titleUpdateTime.setText(updateTime);
        degreeText.setText(degreed);
        weatherInfoText.setText(weatherInfo);

        forecastLayout.removeAllViews();
        for (Forecast forecast:weather.forecastList) {
            View view = LayoutInflater.from(this).inflate(R.layout.forecast_item,forecastLayout,false);
            TextView dateText = view.findViewById(R.id.date_text);
            TextView infoText = view.findViewById(R.id.info_text);
            TextView maxText = view.findViewById(R.id.max_text);
            TextView minText = view.findViewById(R.id.min_text);
            dateText.setText(forecast.date);
            infoText.setText(forecast.more.info);
            maxText.setText(forecast.temperature.max);
            minText.setText(forecast.temperature.min);
            forecastLayout.addView(view);
        }

        if (weather.aqi != null){
            aqiText.setText(weather.aqi.city.api);
            pm25Text.setText(weather.aqi.city.pm25);
        }

        String comfort = "舒适度:"+weather.suggestion.comfort.info;
        String carWash = "洗车指数:"+weather.suggestion.carWash.info;
        String sport = "运动建议:"+weather.suggestion.sport.info;
        comfortText.setText(comfort);
        carWashText.setText(carWash);
        sportText.setText(sport);
        weatherLayout.setVisibility(View.VISIBLE);
        Intent intent = new Intent(this, AutoUpdateService.class);
        startService(intent);
    }
}


text:
set -e

# Change to the location of the script
cd $(dirname $0)

# Create the output file ahead of time to ensure it is available.
output_filename=kurmaos-disk.img.gz
touch ../../output/$output_filename

docker run --privileged --rm \
       -v `pwd`/../../output/kurma-init.tar.gz:/tmp/build/kurma-init-build/kurma-init.tar.gz \
       -v `pwd`/../..:/tmp/build/kurmaos-source \
       -v `pwd`/../../output/$output_filename:/tmp/build/$output_filename \
       -w /tmp/build \
       apcera/kurmaos-stage4 \
       bash -c "./kurmaos-source/packaging/kurmaos-disk/build.sh && cp raw.img.gz $output_filename"

echo "Compiled output available in ../../output/$output_filename"