text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.intuso.housemate</groupId>
        <artifactId>housemate-package-server</artifactId>
        <version>2.0.0-SNAPSHOT</version>
    </parent>

	<artifactId>housemate-package-server-jsw</artifactId>
    <packaging>jar</packaging>
    <name>Housemate Package Server JSW</name>
	<description>Housemate Server Java Service Wrapper</description>

    <dependencies>

        <!-- Jar module -->
		<dependency>
            <groupId>${project.groupId}</groupId>
			<artifactId>housemate-package-server-jar</artifactId>
			<version>${project.version}</version>
		</dependency>

        <!-- ActiveMQ WebConsole -->
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-web-console</artifactId>
            <type>war</type>
            <version>${activemq.version}</version>
        </dependency>

        <!-- Plugins -->
    </dependencies>

	<build>
        <resources>
            <resource>
                <directory>src/main/conf</directory>
                <targetPath>${project.build.directory}/jsw/housemate/conf</targetPath>
            </resource>
        </resources>

        <plugins><!-- Copy dependency configs/resources in -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>3.0.0</version>

                <!-- ActiveMQ web console files -->
                <executions>
                    <execution>
                        <id>activemq-webconsole</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>

                                <!-- Copy the activemq webconsole war -->
                                <artifactItem>
                                    <groupId>org.apache.activemq</groupId>
                                    <artifactId>activemq-web-console</artifactId>
                                    <version>${activemq.version}</version>
                                    <type>war</type>
                                    <overWrite>true</overWrite>
                                    <excludes>
                                        WEB-INF/lib/activemq-broker-*.jar,
                                        WEB-INF/lib/activemq-client-*.jar,
                                        WEB-INF/lib/activemq-openwire-legacy-*.jar
                                    </excludes>
                                    <outputDirectory>${project.build.directory}/jsw/housemate/conf/activemq/webconsole</outputDirectory>
                                </artifactItem>

                                <!-- Copy our config for the activemq webconsole -->
                                <artifactItem>
                                    <groupId>${project.groupId}</groupId>
                                    <artifactId>housemate-package-server-jar</artifactId>
                                    <version>${project.version}</version>
                                    <type>jar</type>
                                    <overWrite>true</overWrite>
                                    <includes>activemq/**</includes>
                                    <outputDirectory>${project.build.directory}/jsw/housemate/conf/</outputDirectory>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                    <execution>
                        <id>jstl-jar</id>
                        <phase>install</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/jsw/housemate/conf/activemq/webconsole/WEB-INF/lib</outputDirectory>
                            <includeArtifactIds>jstl</includeArtifactIds>
                        </configuration>
                    </execution>

                    <!-- Copy plugins in -->
                    <execution>
                        <id>copy</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/jsw/housemate/plugins</outputDirectory>
                            <artifactItems>

                                <!-- RFXtrx434 -->
                                <artifactItem>
                                    <groupId>${project.groupId}</groupId>
                                    <artifactId>housemate-extension-plugin-rfxcom-hardware</artifactId>
                                    <version>${project.version}</version>
                                    <classifier>jar-with-dependencies</classifier>
                                    <overWrite>true</overWrite>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <!-- Wrap everything in a java service wrapper -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>create-empty-directory</id>
                        <phase>process-classes</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <tasks>
                                <mkdir dir="${basedir}/target/jsw/housemate/logs" />
                                <mkdir dir="${basedir}/target/jsw/housemate/tmp" />
                            </tasks>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>appassembler-maven-plugin</artifactId>
                <version>1.9.0</version>
                <configuration>
                    <configurationDirectory>conf</configurationDirectory>
                    <assembleDirectory>${project.build.directory}/jsw/housemate</assembleDirectory>
                    <target>${project.build.directory}</target>
                    <repositoryLayout>flat</repositoryLayout>
                    <includeConfigurationDirectoryInClasspath>false</includeConfigurationDirectoryInClasspath>
                    <defaultJvmSettings>
                        <initialMemorySize>256M</initialMemorySize>
                        <maxMemorySize>1024M</maxMemorySize>
                        <extraArguments>
                            <extraArgument>-Djava.library.path=lib</extraArgument>
                            <extraArgument>-Dfile.encoding=UTF-8</extraArgument>
                        </extraArguments>
                    </defaultJvmSettings>
                    <daemons>
                        <daemon>
                            <id>housemate</id>
                            <mainClass>com.intuso.housemate.pkg.server.jar.Main</mainClass>
                            <commandLineArguments>
                                <commandLineArgument>-conf.dir</commandLineArgument>
                                <commandLineArgument>conf</commandLineArgument>
                            </commandLineArguments>
                            <platforms>
                                <platform>jsw</platform>
                            </platforms>
                            <generatorConfigurations>
                                <generatorConfiguration>
                                    <generator>jsw</generator>
                                    <includes>
                                        <include>linux-x86-32</include>
                                        <include>linux-x86-64</include>
                                        <include>windows-x86-32</include>
                                        <include>windows-x86-64</include>
                                    </includes>
                                    <configuration>
                                        <property>
                                            <name>wrapper.logfile</name>
                                            <value>logs/wrapper.log</value>
                                        </property>
                                        <property>
                                            <name>wrapper.logfile.rollmode</name>
                                            <value>SIZE</value>
                                        </property>
                                        <property>
                                            <name>wrapper.logfile.maxsize</name>
                                            <value>10m</value>
                                        </property>
                                        <property>
                                            <name>wrapper.logfile.maxfiles</name>
                                            <value>10</value>
                                        </property>
                                        <property>
                                            <name>wrapper.ntservice.displayname</name>
                                            <value>Intuso Housemate Server</value>
                                        </property>
                                    </configuration>
                                </generatorConfiguration>
                            </generatorConfigurations>
                        </daemon>
                    </daemons>
                </configuration>
                <executions>
                    <execution>
                        <id>generate-jsw-scripts</id>
                        <phase>package</phase>
                        <goals>
                            <goal>generate-daemons</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!-- Zip up the jsw directory -->
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.2-beta-5</version>
                <configuration>
                    <descriptors>
                        <descriptor>${basedir}/jsw.xml</descriptor>
                    </descriptors>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <!-- this is used for inheritance merges -->
                        <phase>package</phase>
                        <!-- append to the packaging phase. -->
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
	</build>
</project>


text:
//snippet-sourcedescription:[DetachRolePolicy.java demonstrates how to detach a policy from an AWS Identity and Access Management (IAM) role.]
//snippet-keyword:[AWS SDK for Java v2]
//snippet-service:[IAM]

package com.example.iam;

// snippet-start:[iam.java2.detach_role_policy.import]
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.iam.IamClient;
import software.amazon.awssdk.services.iam.model.IamException;
// snippet-end:[iam.java2.detach_role_policy.import]

/**
 * Before running this Java V2 code example, set up your development environment, including your credentials.
 *
 * For more information, see the following documentation topic:
 *
 * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html
 */
public class DetachRolePolicy {
    public static void main(String[] args) {

        final String usage = "\n" +
            "Usage:\n" +
            "    <roleName> <policyArn> \n\n" +
            "Where:\n" +
            "    roleName - A role name that you can obtain from the AWS Management Console. \n\n" +
            "    policyArn - A policy ARN that you can obtain from the AWS Management Console. \n\n" ;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String roleName = args[0];
        String policyArn = args[1];
        Region region = Region.AWS_GLOBAL;
        IamClient iam = IamClient.builder()
            .region(region)
            .credentialsProvider(ProfileCredentialsProvider.create())
            .build();
        detachPolicy(iam, roleName, policyArn);
        System.out.println("Done");
        iam.close();
    }

    // snippet-start:[iam.java2.detach_role_policy.main]
    public static void detachPolicy(IamClient iam, String roleName, String policyArn ) {

        try {
            DetachRolePolicyRequest request = DetachRolePolicyRequest.builder()
                .roleName(roleName)
                .policyArn(policyArn)
                .build();

            iam.detachRolePolicy(request);
            System.out.println("Successfully detached policy " + policyArn +
                " from role " + roleName);

        } catch (IamException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
    // snippet-end:[iam.java2.detach_role_policy.main]
}

redpajama_set_name: RedPajamaGithub


text:
package com.lucasbraz.cartographer.processor.model;

import com.squareup.javapoet.TypeName;

import java.beans.Introspector;
import java.util.HashMap;
import java.util.Map;

import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;

import static com.lucasbraz.cartographer.processor.Utils.capitalize;

public class MappedClass {

    private final TypeElement typeElement;

    public final String name;
    public final String capitalizedName;
    public final Map<String, Field> fields;

    public MappedClass(TypeElement typeElement) {
        this.capitalizedName = typeElement.getSimpleName().toString();
        this.name = Introspector.decapitalize(capitalizedName);
        this.typeElement = typeElement;

        fields = new HashMap<>();
        collectFields();
    }

    private void collectFields() {
        for (Element element : typeElement.getEnclosedElements()) {
            if (element.getKind() == ElementKind.FIELD) {
                String fieldName = element.getSimpleName().toString();
                boolean isPublic = isPublicField(element);
                boolean hasGet = hasGetMethod(fieldName);
                boolean hasSet = hasSetMethod(fieldName);

                fields.put(fieldName, new Field(fieldName, hasGet, hasSet, isPublic));
            }
        }
    }

    private boolean isPublicField(Element element) {
        return element.getModifiers().contains(Modifier.PUBLIC);
    }

    private boolean hasGetMethod(String attributeName) {
        return hasMethod(String.format("get%s", capitalize(attributeName)));
    }

    private boolean hasMethod(String methodName) {
        for (Element element : typeElement.getEnclosedElements()) {
            if (element.getKind() == ElementKind.METHOD
                    && methodName.equalsIgnoreCase(element.getSimpleName().toString())) {
                return true;
            }
        }
        return false;
    }

    private boolean hasSetMethod(String attributeName) {
        return hasMethod(String.format("set%s", capitalize(attributeName)));
    }

    public TypeName asType() {
        return TypeName.get(typeElement.asType());
    }

    public int getFieldCount() {
        return fields.size();
    }
}


text:
using System;
using System.Collections.ObjectModel;
using Microsoft.Phone.Notification;

namespace Entile
{
    public class HttpNotificationChannelAdapter : IHttpNotificationChannel
    {
        private HttpNotificationChannel _wrappedNotificationChannel;

        public HttpNotificationChannelAdapter(HttpNotificationChannel wrappedNotificationChannel)
        {
            _wrappedNotificationChannel = wrappedNotificationChannel;
        }

        public Uri ChannelUri
        {
            get { return _wrappedNotificationChannel.ChannelUri; }
        }

        public string ChannelName
        {
            get { return _wrappedNotificationChannel.ChannelName; }
        }

        public bool IsShellTileBound
        {
            get { return _wrappedNotificationChannel.IsShellTileBound; }
        }

        public bool IsShellToastBound
        {
            get { return _wrappedNotificationChannel.IsShellToastBound; }
        }

        public void Open()
        {
            _wrappedNotificationChannel.Open();
        }

        public void Close()
        {
            _wrappedNotificationChannel.Close();
        }

        public void BindToShellTile()
        {
            _wrappedNotificationChannel.BindToShellTile();
        }

        public void BindToShellTile(Collection<Uri> baseUri)
        {
            _wrappedNotificationChannel.BindToShellTile(baseUri);
        }

        public void BindToShellToast()
        {
            _wrappedNotificationChannel.BindToShellToast();
        }

        public void UnbindToShellTile()
        {
            _wrappedNotificationChannel.UnbindToShellTile();
        }

        public void UnbindToShellToast()
        {
            _wrappedNotificationChannel.UnbindToShellToast();
        }

        public event EventHandler<NotificationChannelUriEventArgs> ChannelUriUpdated
        {
            add { _wrappedNotificationChannel.ChannelUriUpdated += value; }
            remove { _wrappedNotificationChannel.ChannelUriUpdated -= value; }
        }

        public event EventHandler<NotificationChannelErrorEventArgs> ErrorOccurred
        {
            add { _wrappedNotificationChannel.ErrorOccurred += value; }
            remove { _wrappedNotificationChannel.ErrorOccurred -= value; }
        }

        public event EventHandler<HttpNotificationEventArgs> HttpNotificationReceived
        {
            add { _wrappedNotificationChannel.HttpNotificationReceived += value; }
            remove { _wrappedNotificationChannel.HttpNotificationReceived -= value; }
        }

        public event EventHandler<NotificationEventArgs> ShellToastNotificationReceived
        {
            add { _wrappedNotificationChannel.ShellToastNotificationReceived += value; }
            remove { _wrappedNotificationChannel.ShellToastNotificationReceived -= value; }
        }
    }
}


text:
<template name="clock">

    {{hours}}
    :
    {{minutes}}
    :
    {{seconds}}

</template>


text: homebrew_cask 'spotify'


text:
require File.expand_path(File.dirname(__FILE__) + '../../spec_helper')

describe XDo do
  describe 'with no display specification' do
    let(:xdo) { XDo.new }

    it 'should use the value of $DISPLAY' do
      xdo.display_name.should == ENV['DISPLAY']
    end

    describe 'after close' do
      before { xdo.close }

      it 'should not accept method calls' do
        lambda {
          xdo.display_name
        }.should raise_error(NoMethodError)
      end

      it 'should accept #close without crashing' do
        lambda {
          xdo.close
        }.should_not raise_error
      end
    end
  end

  describe 'find_windows' do
    let(:xdo) { XDo.new }

    describe 'with .* name pattern' do
      let(:windows) { xdo.find_windows :name => '.*' }

      it 'should return at least 1 element' do
        windows.should_not be_empty
      end

      it 'should return same number of windows as xdotool' do
        windows.length.should == `xdotool search --all --name ".*"`.split.length
      end

      it 'should have a XDo::Window as the first element' do
        windows.first.should be_kind_of(XDo::Window)
      end

      it 'should include the active window' do
        windows.should include(xdo.active_window)
      end

      it 'should include the "real" focused window' do
        windows.should include(xdo.real_focused_window)
      end
    end

    describe 'with no conditions' do
      let(:windows) { xdo.find_windows }

      it 'should include the active window' do
        windows.should include(xdo.active_window)
      end

      it 'should include the "real" focused window' do
        windows.should include(xdo.real_focused_window)
      end

      it 'should include the focused window' do
        windows.should include(xdo.focused_window)
      end

      it 'should return more than 3 windows' do
        windows.should have_at_least(3).windows
      end
    end

    describe 'with limit' do
      let(:windows) { xdo.find_windows :limit => 3 }

      it 'should only return 3 windows' do
        windows.should have(3).windows
      end
    end

    describe 'with the current PID' do
      let(:windows) { xdo.find_windows :pid => $PID }

      it 'should not return any windows for console process' do
        windows.should be_empty
      end
    end
  end

  describe 'active_window' do
    let(:xdo) { XDo.new }
    let(:window) { xdo.active_window }

    it 'should be an XDo::Window' do
      window.should be_kind_of(XDo::Window)
    end

    it 'should match the output of xdotool' do
      window._window.should == `xdotool getactivewindow`.to_i
    end
  end

  describe 'focused_window' do
    let(:xdo) { XDo.new }
    let(:window) { xdo.focused_window }

    it 'should be an XDo::Window' do
      window.should be_kind_of(XDo::Window)
    end
  end

  describe 'mouse' do
    let(:xdo) { XDo.new }
    let(:mouse) { xdo.mouse }

    it 'should be an XDo::Mouse' do
      mouse.should be_kind_of(XDo::Mouse)
    end
  end

  describe 'with :0 display name' do
    let(:display) { ':0'}
    let(:xdo) { XDo.new display }

    it 'should use given display name' do
      xdo.display_name.should == display
    end
  end

  describe 'lib_version' do
    let(:version) { XDo.lib_version }

    it 'should be non-nil' do
      version.should_not be_nil
    end

    it 'should be non-empty' do
      version.should_not be_empty
    end
  end
end


text:
package net.dv8tion.jda.core.entities.impl;

import net.dv8tion.jda.core.entities.*;

public class GuildVoiceStateImpl implements GuildVoiceState
{
    private final GuildImpl guild;
    private final Member member;

    private VoiceChannel connectedChannel;
    private String sessionId;
    private boolean selfMuted = false;
    private boolean selfDeafened = false;
    private boolean guildMuted = false;
    private boolean guildDeafened = false;
    private boolean suppressed = false;

    public GuildVoiceStateImpl(GuildImpl guild, Member member)
    {
        this.guild = guild;
        this.member = member;
    }

    @Override
    public boolean isSelfMuted()
    {
        return selfMuted;
    }

    @Override
    public boolean isSelfDeafened()
    {
        return selfDeafened;
    }

    @Override
    public JDAImpl getJDA()
    {
        return guild.getJDA();
    }

    @Override
    public AudioChannel getAudioChannel()
    {
        return connectedChannel;
    }

    @Override
    public String getSessionId()
    {
        return sessionId;
    }

    @Override
    public boolean isMuted()
    {
        return isSelfMuted() || isGuildMuted();
    }

    @Override
    public boolean isDeafened()
    {
        return isSelfDeafened() || isGuildDeafened();
    }

    @Override
    public boolean isGuildMuted()
    {
        return guildMuted;
    }

    @Override
    public boolean isGuildDeafened()
    {
        return guildDeafened;
    }

    @Override
    public boolean isSuppressed()
    {
        return suppressed;
    }

    @Override
    public VoiceChannel getChannel()
    {
        return connectedChannel;
    }

    @Override
    public Guild getGuild()
    {
        return guild;
    }

    @Override
    public Member getMember()
    {
        return member;
    }

    @Override
    public boolean inVoiceChannel()
    {
        return getChannel() != null;
    }

    @Override
    public int hashCode()
    {
        return member.hashCode();
    }

    @Override
    public boolean equals(Object obj)
    {
        if (!(obj instanceof GuildVoiceState))
        {
            return false;
        }
        GuildVoiceState oStatus = (GuildVoiceState) obj;
        return this == oStatus || (this.member.equals(oStatus.getMember()) && this.guild.equals(oStatus.getGuild()));
    }

    @Override
    public String toString()
    {
        return "VS:" + guild.getName() + ':' + member.getEffectiveName();
    }

    // -- Setters --

    public GuildVoiceStateImpl setConnectedChannel(VoiceChannel connectedChannel)
    {
        this.connectedChannel = connectedChannel;
        return this;
    }

    public GuildVoiceStateImpl setSessionId(String sessionId)
    {
        this.sessionId = sessionId;
        return this;
    }

    public GuildVoiceStateImpl setSelfMuted(boolean selfMuted)
    {
        this.selfMuted = selfMuted;
        return this;
    }

    public GuildVoiceStateImpl setSelfDeafened(boolean selfDeafened)
    {
        this.selfDeafened = selfDeafened;
        return this;
    }

    public GuildVoiceStateImpl setGuildMuted(boolean guildMuted)
    {
        this.guildMuted = guildMuted;
        return this;
    }

    public GuildVoiceStateImpl setGuildDeafened(boolean guildDeafened)
    {
        this.guildDeafened = guildDeafened;
        return this;
    }

    public GuildVoiceStateImpl setSuppressed(boolean suppressed)
    {
        this.suppressed = suppressed;
        return this;
    }
}


text:
layout: post
unique_id: blade_runner_2049
title: Blade Runner 2049
categories: []
locations:
---

YESTERDAY
* work in the city
* singapore fried noodles for lunch
* hardware testing
  * got about 10k data points for super secret project
* UAT for stache
  * found a bunch of edge cases, fixed all but three of them ...
  * forgot to test when phone is horizontal instead of vertical :P
* saw blade runner 2049!
  * love the plot, but little lengthy ...
* nothing open at midnight (aside from in-n-out)
  * macaroni + ham + chicken soup for dinner

TODAY:
* 1 reverse interview as a ML candidate
* 2 interviews
* dumplings and veggies for lunch
* Safeway run for my daily outing (q.q)
* started creating a music theory question bot
* vegetable stew for dinner!

LEARNINGS:
* how to deep link within an app using react-native-navigation and react-native-scrollable-tab-view
* 'child_added' vs 'child_changed' vs 'value' event listeners in [Firebase's Javascript API](https://firebase.google.com/docs/database/admin/retrieve-data)
  * 'child_added' triggers when a new child is added
  * 'child_removed' triggers when a child is removed
  * 'child_changed' triggers if a child is itself modified
  * 'value' triggers on any of the above


text:
<?php

namespace Doctrine\ORM\Cache;

/**
 * Cache entry interface
 *
 * <b>IMPORTANT NOTE:</b>
 *
 * Fields of classes that implement CacheEntry are public for performance reason.
 */
interface CacheEntry
{
}


text:
package webutil;

import java.net.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;

public class GetWebContent {

	private String code;
	private String result;

	public GetWebContent(){
		setCode("600000");
	}

	public GetWebContent(String code){
		setCode(code);
	}
	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getResult() {
		return result;
	}

	private void setResult(String result) {
		this.result = result;
	}

	/**
	 * this is real method to find the content from net
	 */

	public String findIt(){
		String dividendInfo = null; //the result will send back
		dividendInfo =code + ": "; // start with stock code
		ArrayList<String> dividendLines = new ArrayList<String>();
		boolean start= false;
		boolean end = false;
		try {
			URL target = new URL("http://stock.quote.stockstar.com/dividend_"+code+".shtml");
			BufferedReader in = new BufferedReader(
					new InputStreamReader(target.openStream()));

			String inputLine;
			while((inputLine = in.readLine()) != null){

				//get the stock name
				if(inputLine.contains("<title>")){
					dividendInfo = dividendInfo + getStockName(inputLine);
					//System.out.println(dividendInfo);
				}

				//get the stock close price
				if(inputLine.contains("stockclose")){
					dividendInfo += getStockClose(inputLine);
				}
				//get the stock dividend

				if(inputLine.contains("")){
					start = true;

				}
				if(inputLine.contains("")){
					start = false;
					end = true;
				}
				if(start && !end){
					dividendLines.add(inputLine);
					//System.out.println(inputLine);

				}

			}

			in.close();
			dividendInfo += getDivident(dividendLines);

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		//System.out.println(dividendInfo);
		setResult(dividendInfo);
		return getResult();
	}

	/**
	 * »ñÈ¡ÊÕÅ̼Û
	 * SwingÓÐhtml parser
	 * JsoupÒ²¿ÉÒÔÓÃ
	 * Ä¿Ç°Ñ¡ÔñÕýÔò±í´ïʽֱ½Ó´ÓStringÀïÕª³öÀ´
	 * @param inputLine
	 * @return
	 */
	private String getStockClose(String inputLine) {
		// TODO
15.73

		String ret = "---";

		ret = getPrice(inputLine);

		return ret;
	}

	/**
	 * »ñÈ¡Ãû³Æ
	 * @param inputLine
	 * @return
	 */
	private String getStockName(String inputLine) {
		// TODO <title>ÆÖ·¢ÒøÐÐ(600000)_ÈÚ×Ê·Öºì_֤ȯ֮ÐÇ</title>
		int x = inputLine.indexOf("<title>");
		int y = inputLine.indexOf("(");
		String ret = inputLine.substring(x+7, y)+ ": "; //need 2 space, 1 space will be omitted
		return ret;

	}

	/**
	 * »ñÈ¡µ±ÄêµÄ·Öºì
	 * @param dividendLines
	 * @return
	 */
	private String getDivident(ArrayList<String> dividendLines) {
		// TODO find the dividend from the dividend Lines
		String ret = "0" ;
		String line;

		for(int i = 0;i<dividendLines.size();i++){
			line = dividendLines.get(i);
			if(line.contains("2016")){
				ret = getPrice(line);
			}
		}

		return ret;
	}

	/**
	 * ´ÓStringÖлñÈ¡price
	 * ʹÓÃÕýÔò±í´ïʽµÄ·½·¨
	 * @param aLine
	 * @return
	 */
	private String getPrice(String aLine){
		String price = " ";
		Pattern patternPrice = Pattern.compile("\\d+\\.\\d+"); //¼Û¸ñÆ¥Åäģʽ=>>15.73
		Matcher matcher = patternPrice.matcher(aLine);
		if(matcher.find()){
			price = matcher.group() + ": ";
		}

		return price;
	}
	/**
	 * »ñÈ¡·ÖºìÅÅÃû£¬ÔÝʱ²»ÓÃ
	 * @param inputLine
	 * @return
	 */
	private String getRank(String inputLine) {
		// TODO »ñÈ¡·ÖºìÅÅÃû
		int x = inputLine.indexOf("ÅÉ");
		int y = inputLine.indexOf("λ");
		String ret=inputLine.substring(x, y);
		ret = ret.substring(ret.length()-3,ret.length());
		return ret;
	}

}


text:
layout: page
title: Berg Ice Holdings Executive Retreat
date: 2016-05-24
author: Billy Hahn
tags: weekly links, java
status: published
summary: Nam viverra diam vel malesuada.
banner: images/banner/leisure-01.jpg
booking:
  startDate: 08/13/2019
  endDate: 08/17/2019
  ctyhocn: BTRCNHX
  groupCode: BIHER
published: true
---
Curabitur id tortor accumsan, interdum velit at, ultricies sem. Maecenas eu metus ut mauris lobortis tincidunt. Morbi lobortis rhoncus nunc sit amet aliquam. Aenean id nibh quam. Maecenas rhoncus malesuada tellus. Morbi id vulputate quam. Sed neque leo, volutpat ut turpis vel, ultricies malesuada nibh. Etiam aliquam diam ipsum, eu finibus augue placerat ac.

1 Maecenas a orci eu libero blandit sagittis
1 Cras fringilla ante sed mollis aliquam
1 Pellentesque fringilla lorem sit amet enim tincidunt lobortis.

Aliquam dictum libero eu nunc consectetur, vitae laoreet mauris mattis. Praesent aliquam odio augue. Praesent in velit sagittis mi fermentum efficitur. Aliquam tempus risus non neque viverra faucibus. Nam egestas, neque vitae cursus feugiat, nisl elit sodales velit, quis imperdiet risus neque id risus. Suspendisse eu lacus cursus, tincidunt libero et, accumsan urna. Curabitur auctor, massa ac scelerisque faucibus, sapien nunc ultricies nisl, nec cursus est purus vitae libero.
Pellentesque rhoncus at nisi sit amet tristique. Integer sodales felis a massa tincidunt mattis. Nam id est diam. Ut non dictum lacus. Sed luctus tincidunt felis ut semper. Nunc vitae turpis libero. Duis vestibulum porttitor lacinia. Nunc dictum felis vitae enim viverra scelerisque. Donec congue risus id varius accumsan. Nam et tellus consectetur odio maximus egestas et eu nisl. Integer gravida felis quis neque aliquam hendrerit. In in purus in neque lobortis semper ut ut lorem. Aliquam porta tristique neque, sit amet suscipit odio egestas a.


text:
<?xml version="1.0" ?>
<Project>
	<Details>
		<Name>selenium_project</Name>
		<Title>selenium functional tests</Title>
		<Engineer>Sayyeda Farheen</Engineer>
		<Date>07/25/2018</Date>
		<default_onError action="next"/>
	</Details>
	<Testsuites>
		<Testsuite>
			<path>../suites/selenium_func_tests/gen_test_suite.xml</path>
			<onError action="next" value=""/>
			<impact>impact</impact>
		</Testsuite>
		<Testsuite>
			<path>../suites/selenium_func_tests/df_usage_suite.xml</path>
			<onError action="next" value=""/>
			<impact>impact</impact>
		</Testsuite>
		<Testsuite>
			<path>../suites/selenium_func_tests/json_usage_suite.xml</path>
			<onError action="next" value=""/>
			<impact>impact</impact>
		</Testsuite>
	</Testsuites>
</Project>


text:
package cron

func Init() {
	go GetDetectedItem()
	go DeleteOld()
}


text:
package com.madphysicist.jform.translate;

import java.awt.Component;
import java.io.Serializable;

/**
 * The fundamental interface for translating user input in an UI field into an
 * object. Some translators must be bound to a specific field. Others can be
 * used on any field of a given type. See {@code ComboBoxTranslator} and
 * {@code TextComponentTranslator} for examples of each case, respectively.
 * <p>
 * The contract of this interface is that any {@code Object} or {@code String}
 * that can be read from a component with {@code readValue()} or {@code
 * readString()} must be allowed to be written back to it. However, not every
 * object which can be written to a component with {@code writeValue()} is
 * required to be valid when read back. As a consequence, the {@code
 * writeValue()} method takes arguments of type {@code Object} rather than of
 * generic type {@code T}. Translators must be able to handle at least {@code
 * String} objects in addition the their usual output types when writing to a
 * field. Other types may be premitted as well, depending on the individual
 * translator. Additionally, {@code readValue()} and {@code readString()} should
 * both either throw an exception or return a valid value. There should never be
 * a case where {@code readValue()} can parse the component's contents while
 * {@code readString()} can not, or vice versa.
 *
 * @param <T> The raw type of the field. This can be anything at all. Popular
 * choices include {@code Number}, {@code String}, or array types.
 * @param <U> The type of UI component that this translator applies to. The type
 * must extend {@code java.awt.Component}.
 * @author Joseph Fox-Rabinovitz
 * @version 1.0.0, 25 May 2013: Joseph Fox-Rabinovitz: Created
 */
public interface Translator<T, U extends Component> extends Serializable
{
    /**
     * Converts a value in the specified form field into an Object.
     *
     * @param uiComponent the component to read from.
     * @return the value stored in the component.
     * @throws TranslatorException if the value could not be extracted due to
     * a formatting error.
     * @since 1.0.0
     */
    public T readValue(U uiComponent) throws TranslatorException;

    /**
     * Converts a value in the specified form field into a string instread of
     * the default return type. This method is particularly useful for exporting
     * fields for which the default type does not convert well with {@code
     * toString()}.
     *
     * @param uiComponent the component to read from.
     * @return the value stored in the component.
     * @throws TranslatorException if the value could not be extracted due to
     * a formatting error.
     * @since 1.0.0
     */
    public String readString(U uiComponent) throws TranslatorException;

    /**
     * Writes a value to the component. This value does not necessarily have to
     * be legible with {@code readValue()}. On the other hand, any value read by
     * either {@code readValue()} or {@code readString()} should be able to be
     * written back without causing an exception.
     *
     * @param value the value to write to the component. This value does not
     * necessarily have to be of a type that can be read back from the
     * component.
     * @param uiComponent the component to write to.
     * @throws TranslatorException if the value being written is incompatible
     * with the component.
     * @since 1.0.0
     */
    public void writeValue(Object value, U uiComponent) throws TranslatorException;
}


text:
<?php

namespace Zephir\Optimizers\FunctionCall;

use Zephir\Call;
use Zephir\CompilationContext;
use Zephir\CompiledExpression;
use Zephir\Exception;
use Zephir\Exception\CompilerException;
use Zephir\Optimizers\OptimizerAbstract;
use Zephir\Variable;

/**
 * Zephir\Optimizers\FunctionCall\PregMatchOptimizer.
 *
 * Optimizes calls to 'preg_match' using internal function.
 */
class PregMatchOptimizer extends OptimizerAbstract
{
    const GLOBAL_MATCH = 0;

    /**
     * {@inheritdoc}
     *
     * @param array              $expression
     * @param Call               $call
     * @param CompilationContext $context
     *
     * @throws CompilerException
     *
     * @return CompiledExpression
     */
    public function optimize(array $expression, Call $call, CompilationContext $context)
    {
        if (!isset($expression['parameters']) || \count($expression['parameters']) < 2) {
            throw new CompilerException(
                sprintf(
                    'preg_match() expects at least 2 parameters, %d given',
                    isset($expression['parameters']) ? \count($expression['parameters']) : 0
                ),
                $expression
            );
        }

        if (\count($expression['parameters']) > 5) {
            throw new CompilerException(
                sprintf(
                    'preg_match() expects at most 5 parameters, %d given',
                    \count($expression['parameters'])
                ),
                $expression
            );
        }

        $matches = $this->createMatches($expression, $context);
        list($flags, $offset) = $this->processOptionals($expression, $call, $context);

        /*
         * Process the expected symbol to be returned
         */
        $call->processExpectedReturn($context);

        $symbolVariable = $call->getSymbolVariable(true, $context);
        if (!$symbolVariable->isVariable()) {
            throw new CompilerException(
                'Returned values by functions can only be assigned to variant variables',
                $expression
            );
        }

        // zephir_preg_match
        $context->headersManager->add('kernel/string');

        try {
            $resolvedParams = $call->getReadOnlyResolvedParams($expression['parameters'], $context, $expression);

            if ($call->mustInitSymbolVariable()) {
                $symbolVariable->initVariant($context);
            }

            $symbol = $context->backend->getVariableCode($symbolVariable);
            $matchesSymbol = $context->backend->getVariableCode($matches);

            $context->codePrinter->output(
                sprintf(
                    'zephir_preg_match(%s, %s, %s, %s, %d, %s, %s);',
                    $symbol,
                    $resolvedParams[0],
                    $resolvedParams[1],
                    $matchesSymbol,
                    static::GLOBAL_MATCH,
                    $flags,
                    $offset
                )
            );

            return new CompiledExpression('variable', $symbolVariable->getRealName(), $expression);
        } catch (Exception $e) {
            throw new CompilerException($e->getMessage(), $expression, $e->getCode(), $e);
        }
    }

    /**
     * Process optional parameters.
     *
     *     preg_match(pattern, subject, matches, flags, offset)
     *
     * @param array              $expression
     * @param Call               $call
     * @param CompilationContext $context
     *
     * @throws CompilerException
     *
     * @return array
     */
    private function processOptionals(array &$expression, Call $call, CompilationContext $context)
    {
        $flags = null;
        $offset = null;

        $offsetParamOffset = 4;
        if (isset($expression['parameters'][4]) && 'int' === $expression['parameters'][4]['parameter']['type']) {
            $offset = $expression['parameters'][4]['parameter']['value'].' ';
            unset($expression['parameters'][4]);
        }

        if (isset($expression['parameters'][3]) && 'int' === $expression['parameters'][3]['parameter']['type']) {
            $flags = $expression['parameters'][3]['parameter']['value'].' ';
            $offsetParamOffset = 3;
            unset($expression['parameters'][3]);
        }

        try {
            $resolvedParams = $call->getReadOnlyResolvedParams($expression['parameters'], $context, $expression);

            if (null === $offset && isset($resolvedParams[$offsetParamOffset])) {
                $context->headersManager->add('kernel/operators');
                $offset = 'zephir_get_intval('.$resolvedParams[$offsetParamOffset].') ';
            }

            if (null === $flags && isset($resolvedParams[3])) {
                $context->headersManager->add('kernel/operators');
                $flags = 'zephir_get_intval('.$resolvedParams[3].') ';
            }
        } catch (Exception $e) {
            throw new CompilerException($e->getMessage(), $expression, $e->getCode(), $e);
        }

        if (null === $flags) {
            $flags = '0 ';
        }

        if (null === $offset) {
            $offset = '0 ';
        }

        return [$flags, $offset];
    }

    /**
     * Process the matches result.
     *
     *     preg_match(pattern, subject, matches)
     *
     * @param array              $expression
     * @param CompilationContext $context
     *
     * @return Variable
     */
    private function createMatches(array $expression, CompilationContext $context)
    {
        if (isset($expression['parameters'][2])) {
            $type = $expression['parameters'][2]['parameter']['type'];

            if ('variable' !== $type) {
                throw new CompilerException('Only variables can be passed by reference', $expression);
            }

            $name = $expression['parameters'][2]['parameter']['value'];

            if (!$variable = $context->symbolTable->getVariable($name)) {
                throw new CompilerException(
                    sprintf("Cannot mutate variable '%s' because it wasn't defined", $name),
                    $expression
                );
            }

            if (!\in_array($variable->getType(), ['variable', 'array'], true)) {
                throw new CompilerException(
                    sprintf(
                        "The '%s' variable must be either a variable or an array, got %s",
                        $name,
                        $variable->getType()
                    ),
                    $expression
                );
            }

            if (false == $variable->isInitialized()) {
                $variable->initVariant($context);
                $variable->setIsInitialized(true, $context);
            }
        } else {
            $variable = $context->symbolTable->addTemp('variable', $context);
            $variable->initVariant($context);
        }

        $variable->setDynamicTypes('array');

        return $variable;
    }
}


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

namespace PPM.Domain
{
    public class ProjectType
    {
        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Guid Id { get; private set; }
        public string Name { get; set; }

        public virtual HeadOfBusinessArrea HeadOfBusinessArrea { get; set; }
    }
}


text:
/*
 * 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.
 */
package com.facebook.presto.orc.reader;

import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.type.Type;
import com.facebook.presto.orc.OrcAggregatedMemoryContext;
import com.facebook.presto.orc.OrcCorruptionException;
import com.facebook.presto.orc.StreamDescriptor;
import com.facebook.presto.orc.Stripe;
import com.facebook.presto.orc.metadata.ColumnEncoding.ColumnEncodingKind;
import com.facebook.presto.orc.stream.InputStreamSources;
import com.google.common.io.Closer;
import org.openjdk.jol.info.ClassLayout;

import java.io.IOException;
import java.io.UncheckedIOException;

import static com.facebook.presto.orc.metadata.ColumnEncoding.ColumnEncodingKind.DICTIONARY;
import static com.facebook.presto.orc.metadata.ColumnEncoding.ColumnEncodingKind.DIRECT;
import static com.facebook.presto.orc.metadata.ColumnEncoding.ColumnEncodingKind.DIRECT_V2;
import static com.facebook.presto.orc.metadata.ColumnEncoding.ColumnEncodingKind.DWRF_DIRECT;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;

public class LongBatchStreamReader
        implements BatchStreamReader
{
    private static final int INSTANCE_SIZE = ClassLayout.parseClass(LongBatchStreamReader.class).instanceSize();

    private final StreamDescriptor streamDescriptor;
    private final LongDirectBatchStreamReader directReader;
    private final LongDictionaryBatchStreamReader dictionaryReader;
    private BatchStreamReader currentReader;

    public LongBatchStreamReader(Type type, StreamDescriptor streamDescriptor, OrcAggregatedMemoryContext systemMemoryContext)
            throws OrcCorruptionException
    {
        this.streamDescriptor = requireNonNull(streamDescriptor, "stream is null");
        directReader = new LongDirectBatchStreamReader(type, streamDescriptor, systemMemoryContext.newOrcLocalMemoryContext(LongBatchStreamReader.class.getSimpleName()));
        dictionaryReader = new LongDictionaryBatchStreamReader(type, streamDescriptor, systemMemoryContext.newOrcLocalMemoryContext(LongBatchStreamReader.class.getSimpleName()));
    }

    @Override
    public void prepareNextRead(int batchSize)
    {
        currentReader.prepareNextRead(batchSize);
    }

    @Override
    public Block readBlock()
            throws IOException
    {
        return currentReader.readBlock();
    }

    @Override
    public void startStripe(Stripe stripe)
            throws IOException
    {
        ColumnEncodingKind kind = stripe.getColumnEncodings().get(streamDescriptor.getStreamId())
                .getColumnEncoding(streamDescriptor.getSequence())
                .getColumnEncodingKind();
        if (kind == DIRECT || kind == DIRECT_V2 || kind == DWRF_DIRECT) {
            currentReader = directReader;
        }
        else if (kind == DICTIONARY) {
            currentReader = dictionaryReader;
        }
        else {
            throw new IllegalArgumentException("Unsupported encoding " + kind);
        }

        currentReader.startStripe(stripe);
    }

    @Override
    public void startRowGroup(InputStreamSources dataStreamSources)
            throws IOException
    {
        currentReader.startRowGroup(dataStreamSources);
    }

    @Override
    public String toString()
    {
        return toStringHelper(this)
                .addValue(streamDescriptor)
                .toString();
    }

    @Override
    public void close()
    {
        try (Closer closer = Closer.create()) {
            closer.register(directReader::close);
            closer.register(dictionaryReader::close);
        }
        catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    @Override
    public long getRetainedSizeInBytes()
    {
        return INSTANCE_SIZE + directReader.getRetainedSizeInBytes() + dictionaryReader.getRetainedSizeInBytes();
    }
}


text:
import unittest

from appcommon.model.command import Command, CommandCategory

class Test(unittest.TestCase):

    def test_command(self):
        IDE = 1
        NAME = '&Name...'
        DESC = 'desc'
        SHORTCUT_NAME = 'dummy'
        CLEAN_NAME = 'Name'
        NAME_AND_SHORTCUT = '&Name...\tdummy'

        self.flag = 0
        def dummy():
            self.flag = 1
        class DummyShortcut():
            name = SHORTCUT_NAME

        DEF_SHORTCUTS = [DummyShortcut()]

        c = Command(IDE, NAME, DESC, dummy, DEF_SHORTCUTS)

        self.assertEquals(IDE, c.ide)
        self.assertEquals(NAME, c.name)
        self.assertEquals(DESC, c.description)
        self.assertEquals(dummy, c._function)
        self.assertEquals(DEF_SHORTCUTS, c.default_shortcuts)
        self.assertEquals([], c.shortcuts)
        self.assertEquals(c.name_and_shortcut, NAME)
        self.assertEquals(c.clean_name, CLEAN_NAME)

        c.load_default_shortcut()
        self.assertEquals(DEF_SHORTCUTS, c.shortcuts)
        self.assertEquals(c.name_and_shortcut, NAME_AND_SHORTCUT)

        c()
        self.assertEquals(self.flag, 1)

    def test_command_category(self):
        NAME = '&Name'
        CLEAN_NAME = 'Name'

        c = CommandCategory(NAME, [1, 2])

        self.assertEquals(NAME, c.name)
        self.assertEquals(CLEAN_NAME, c.clean_name)
        self.assertEquals(c, [1, 2])

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.test_command']
    unittest.main()


text:
package org.multibit.file;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.Date;

import junit.framework.TestCase;

import org.junit.Test;
import org.multibit.Constants;
import org.multibit.CreateControllers;
import org.multibit.controller.bitcoin.BitcoinController;
import org.multibit.exchange.CurrencyConverter;
import org.multibit.model.bitcoin.WalletData;
import org.multibit.model.exchange.ExchangeModel;
import org.multibit.viewsystem.swing.action.ExportTransactionsSubmitAction;
import org.multibit.file.WalletTableDataEntryConverter;

import com.googlecode.jcsv.CSVStrategy;
import com.googlecode.jcsv.writer.CSVColumnJoiner;
import com.googlecode.jcsv.writer.internal.CSVColumnJoinerImpl;
import com.google.bitcoin.core.Wallet;

public class ExportTransactionsSubmitActionTest extends TestCase {
    public static final String WALLETS_TESTDATA_DIRECTORY = "wallets";

    public static final String TEST_EXPORT_PREFIX = "testExport";

    public static final String PROTOBUF1_WALLET_FILE = "protobuf1.wallet";

    @Test
    public void testExportTransactions() throws Exception {
        // Create MultiBit controller.
        final CreateControllers.Controllers controllers = CreateControllers.createControllers();
        final BitcoinController bitcoinController = controllers.bitcoinController;

        // Initialise currency converter.
        bitcoinController.getModel().setUserPreference(ExchangeModel.TICKER_FIRST_ROW_CURRENCY, "EUR");
        CurrencyConverter.INSTANCE.initialise(bitcoinController);
        CurrencyConverter.INSTANCE.setRate(BigDecimal.valueOf(10.0));

        ExportTransactionsSubmitAction action = new ExportTransactionsSubmitAction(bitcoinController, null);
        assertNotNull(action);

        // Load up the test wallet /wallets/protobuf1.
        // This has (at least) two transactions in it.
        File directory = new File(".");
        String currentPath = directory.getAbsolutePath();

        String testDirectory = currentPath + File.separator + Constants.TESTDATA_DIRECTORY + File.separator
                + WALLETS_TESTDATA_DIRECTORY;
        String testWalletFile = testDirectory + File.separator + PROTOBUF1_WALLET_FILE;

        // Load up the test wallet
        FileHandler fileHandler = new FileHandler(bitcoinController);
        Wallet testWallet = fileHandler.loadFromFile(new File(testWalletFile)).getWallet();

        assertNotNull(testWallet);
        assertTrue("Wrong number of transactions in wallet", testWallet.getTransactions(true).size() >= 2);

        // Write the transactions out to a file.
        File exportFile = File.createTempFile(TEST_EXPORT_PREFIX, ".csv");
        exportFile.delete();
        exportFile.deleteOnExit();

        // Check the file does not exist initially.
        assertTrue("Export file exists when it should not", !exportFile.exists());

        String exportTransactionsFilename = exportFile.getAbsolutePath();

        WalletData walletData = new WalletData();
        walletData.setWallet(testWallet);
        walletData.setWalletFilename(testWalletFile);

        action.exportTransactionsDoIt(walletData, exportTransactionsFilename);

        // Check the file does exist now.
        assertTrue("Export file does not exists when it should", exportFile.exists());

        FileInputStream fileInputStream = new FileInputStream(exportTransactionsFilename);
        DataInputStream dataInputStream = new DataInputStream(fileInputStream);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream, "UTF-8"));

        // Read file line by line.
        String line0 = bufferedReader.readLine();
        String line1 = bufferedReader.readLine();
        String line2 = bufferedReader.readLine();

        // Close the input stream.
        dataInputStream.close();

        assertNotNull("No header row read in", line0);
        assertNotNull("No row 1 read in", line1);
        assertNotNull("No row 2 read in", line2);

        assertEquals("Header row incorrect", "Date,Description,Amount (BTC),Amount (\u20AC),Transaction Id", line0);

        String[] rowExpectedAry = new String[5];
        CSVColumnJoiner columnJoiner = new CSVColumnJoinerImpl();
        WalletTableDataEntryConverter wtdec = new WalletTableDataEntryConverter();
        wtdec.setBitcoinController(bitcoinController);

        // Date is 29 Jul 2013 10:23
        rowExpectedAry[0] = wtdec.dateFormatter.format(new Date(1375089780000l));
        // Note \u5317\u4EAC = Beijing in Chinese.
        rowExpectedAry[1] = bitcoinController.getLocaliser().getString("multiBitModel.debitDescriptionWithLabel",
				new Object[]{"1CQH7Hp9nNQVDcKtFVwbA8tqPMNWDBvqE3", "unencrypted-1-\u5317\u4EAC"});
        rowExpectedAry[2] = "-0.015";
        rowExpectedAry[3] = "-0.15";
        rowExpectedAry[4] = "28916ed8592a4cf216d8eac7e5ccb5a08771f439e508ec2861b7ff612e15b827";

        String row1Expected = columnJoiner.joinColumns(rowExpectedAry, CSVStrategy.UK_DEFAULT);

        // Date is 29 Jul 2013 10:00
        rowExpectedAry[0] = wtdec.dateFormatter.format(new Date(1375088400000l));
        // Note \u5317\u4EAC = Beijing in Chinese.
        rowExpectedAry[1] = bitcoinController.getLocaliser().getString("multiBitModel.creditDescriptionWithLabel",
				new Object[]{"1GtMdodCNN5ewFcEUxxVBziBrLtQzSuZvq", "protobuf 1.1.\u5317\u4EAC"});
        rowExpectedAry[2] = "0.015";
        rowExpectedAry[3] = "0.15";
        rowExpectedAry[4] = "5eeabb42d0522c40cc63dace7746d5f82cd51292bc50a38c4dd68a854ec6cd77";

        String row2Expected = columnJoiner.joinColumns(rowExpectedAry, CSVStrategy.UK_DEFAULT);
        assertEquals("Row 1 incorrect", row1Expected, line1);
        assertEquals("Row 2 incorrect", row2Expected, line2);
    }
}


text:
const WebsocketClient = require('./websocket');
const PublicClient = require('./public');
const AccountClient = require('./account');
const TradeClient = require('./trade');
const adapters = require('./adapters');

module.exports = exports = {
  WebsocketClient,
  PublicClient,
  AccountClient,
  TradeClient,
  adapters,
};


text:
package com.yeungeek.modulartraning.block;

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.LifecycleOwner;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.FrameLayout;
import android.widget.TextView;

/**
 * @author yangjian
 * @date 2018/10/05
 */

public class PageBlock extends FrameLayout implements LifecycleObserver {
    private int pageId;
    private TypeFactory factory;

    private TextView loadingStatus;

    public PageBlock(@NonNull Context context) {
        super(context);
    }

    public PageBlock(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public PageBlock(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public PageBlock(Context context, int pageId, TypeFactory factory) {
        super(context);
        init();

        this.pageId = pageId;
        this.factory = factory;
    }

    private void init() {
        ((LifecycleOwner) getContext()).getLifecycle().addObserver(this);
        loadingStatus = new TextView(getContext());
        addView(loadingStatus);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
        Log.d("DEBUG", "====== onStart");
        loadingStatus.setText("start...");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.d("DEBUG", "====== onResume");
        loadingStatus.setText("resume pageId: " + pageId);
        factory.getList("onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        Log.d("DEBUG", "====== onDestroy");
        ((LifecycleOwner) getContext()).getLifecycle().removeObserver(this);
    }

    public static class Builder {
        private int pageId;
        private TypeFactory factory;

        public Builder setPageId(int pageId) {
            this.pageId = pageId;
            return this;
        }

        public Builder setFactory(TypeFactory factory) {
            this.factory = factory;
            return this;
        }

        public PageBlock build(Context context) {
            return new PageBlock(context, pageId, factory);
        }
    }

    /**
     * for outer
     */
    public interface TypeFactory {
        void getList(String pageName);
    }
}


text:
import {Observable} from "rxjs";
import * as _ from 'lodash';

export type ObservableProducer = {(...args:any[]):Observable<any>};

export function memoize() {
    return function (target:Object, key:string, desc:PropertyDescriptor) {
        if(_.isFunction(desc.value)) {
            const v = desc.value;
            desc.value = _.memoize(v);
        }
        if(_.isFunction(desc.get)) {
            const g = desc.get;
            desc.get = _.memoize(g);
        }
        return desc;
    }
}

interface LogDecoratorConfig {
    trace?:boolean;
}
const defaultConf:LogDecoratorConfig = {
    trace: false
}
export function Log(config:LogDecoratorConfig = defaultConf) {
    console.log('Log')
    return function(...args:any[]) {
        if(args.length === 3) {
            return logMethodFactory(config)
        }
    }
}

export function Trace() {
    console.log('Trace')
    return Log(Object.assign({}, defaultConf, {trace: true}))
}

const logMethodFactory = (config:LogDecoratorConfig):MethodDecorator => {
    const logger = config.trace ? console.trace : console.log;
    console.log('Decorate', config, logger)
    return function(
        target:Function,
        propertyKey:string,
        descriptor:PropertyDescriptor
    ) {
        const value = descriptor.value;
        descriptor.value = function(...args:any[]) {
            logger(`${target.name}.${propertyKey}()`, args)
            const result = value.apply(this, args);
            logger(`Result =>`, result)
            return result;
        }
    }
}


text:
/* This example is for experimenting with the new Simbody contact implementation,
which was in beta test in the Simbody 2.1 release, with first official release
in Simbody 2.2. The previous contact implementation is still present and
functional but will be removed soon.

The example shows how the new system tracks contact events and how you can
extract contact forces. It also shows off a number of features of the new
Simbody Visualizer, new in release 2.2. also. Here we display the forces and
torques as colored lines which remain the same color as long as a particular
contact event continues. We also track the energy dissipated by the contacts
and use it to display an energy quantity that should be conserved throughout
the simulation (that is, the current energy plus the dissipated energy
should be a constant).

The simulation uses very expensive, detailed contact surfaces using dense
meshes and the elastic foundation model. Consequently it runs with highly
variable step sizes, and fails to keep up with real time for some short
periods. We use the Visualizer's RealTime mode to buffer up some frames and
smooth out these rough spots so the simulation appears to run at an almost
steady real time rate, displayed at 30fps (depending on how fast your
computer is). Then at the end you can watch the action replay.

You can use this example to see how the different integrators behave when
confronted with a very stiff problem; depending on material properties CPodes
can be *much* faster than the explicit integrators, and it also exhibits very
high stability after the motion damps out. However, by changing material
properties and accuracy setting you can get reasonably good performance out
of the explicit integrators here, which will scale better to large systems.
*/

#include "Simbody.h"

#include <cstdio>
#include <exception>
#include <algorithm>
#include <iostream>
#include <fstream>
using std::cout; using std::endl;

using namespace SimTK;

Array_<State> saveEm;

static const Real TimeScale = 1;
static const Real FrameRate = 30;
static const Real ReportInterval = TimeScale/FrameRate;
static const Real ForceScale = .25;
static const Real MomentScale = .5;

class ForceArrowGenerator : public DecorationGenerator {
public:
    ForceArrowGenerator(const MultibodySystem& system,
                        const CompliantContactSubsystem& complCont)
    :   m_system(system), m_compliant(complCont) {}

    virtual void generateDecorations(const State& state, Array_<DecorativeGeometry>& geometry) override {
        const Vec3 frcColors[] = {Red,Orange,Cyan};
        const Vec3 momColors[] = {Blue,Green,Purple};
        m_system.realize(state, Stage::Velocity);

        const int ncont = m_compliant.getNumContactForces(state);
        for (int i=0; i < ncont; ++i) {
            const ContactForce& force = m_compliant.getContactForce(state,i);
            const ContactId     id    = force.getContactId();
            const Vec3& frc = force.getForceOnSurface2()[1];
            const Vec3& mom = force.getForceOnSurface2()[0];
            Real  frcMag = frc.norm(), momMag=mom.norm();
            int frcThickness = 1, momThickness = 1;
            Real frcScale = ForceScale, momScale = ForceScale;
            while (frcMag > 10)
                frcThickness++, frcScale /= 10, frcMag /= 10;
            while (momMag > 10)
                momThickness++, momScale /= 10, momMag /= 10;
            DecorativeLine frcLine(force.getContactPoint(),
                force.getContactPoint() + frcScale*frc);
            DecorativeLine momLine(force.getContactPoint(),
                force.getContactPoint() + momScale*mom);
            frcLine.setColor(frcColors[id%3]);
            momLine.setColor(momColors[id%3]);
            frcLine.setLineThickness(2*frcThickness);
            momLine.setLineThickness(2*momThickness);
            geometry.push_back(frcLine);
            geometry.push_back(momLine);

            ContactPatch patch;
            const bool found = m_compliant.calcContactPatchDetailsById(state,id,patch);
            //cout << "patch for id" << id << " found=" << found << endl;
            //cout << "resultant=" << patch.getContactForce() << endl;
            //cout << "num details=" << patch.getNumDetails() << endl;
            for (int i=0; i < patch.getNumDetails(); ++i) {
                const ContactDetail& detail = patch.getContactDetail(i);
                const Real peakPressure = detail.getPeakPressure();
                // Make a black line from the element's contact point in the normal
                // direction, with length proportional to log(peak pressure)
                // on that element.
                DecorativeLine normal(detail.getContactPoint(),
                    detail.getContactPoint()+ std::log10(peakPressure)
                                                * detail.getContactNormal());
                normal.setColor(Black);
                geometry.push_back(normal);
                // Make a red line that extends from the contact
                // point in the direction of the slip velocity, of length 3*slipvel.
                DecorativeLine slip(detail.getContactPoint(),
                    detail.getContactPoint()+3*detail.getSlipVelocity());
                slip.setColor(Red);
                geometry.push_back(slip);
            }
        }
    }
private:
    const MultibodySystem&              m_system;
    const CompliantContactSubsystem&    m_compliant;
};

class MyReporter : public PeriodicEventReporter {
public:
    MyReporter(const MultibodySystem& system,
               const CompliantContactSubsystem& complCont,
               Real reportInterval)
    :   PeriodicEventReporter(reportInterval), m_system(system),
        m_compliant(complCont)
    {}

    ~MyReporter() {}

    void handleEvent(const State& state) const override {
        m_system.realize(state, Stage::Dynamics);
        cout << state.getTime() << ": E = " << m_system.calcEnergy(state)
             << " Ediss=" << m_compliant.getDissipatedEnergy(state)
             << " E+Ediss=" << m_system.calcEnergy(state)
                               +m_compliant.getDissipatedEnergy(state)
             << endl;
        const int ncont = m_compliant.getNumContactForces(state);
        cout << "Num contacts: " << m_compliant.getNumContactForces(state) << endl;
        for (int i=0; i < ncont; ++i) {
            const ContactForce& force = m_compliant.getContactForce(state,i);
            //cout << force;
        }
        saveEm.push_back(state);
    }
private:
    const MultibodySystem&           m_system;
    const CompliantContactSubsystem& m_compliant;
};

// These are the item numbers for the entries on the Run menu.
static const int RunMenuId = 3, HelpMenuId = 7;
static const int GoItem = 1, ReplayItem=2, QuitItem=3;

// This is a periodic event handler that interrupts the simulation on a regular
// basis to poll the InputSilo for user input. If there has been some, process it.
// This one does nothing but look for the Run->Quit selection.
class UserInputHandler : public PeriodicEventHandler {
public:
    UserInputHandler(Visualizer::InputSilo& silo, Real interval)
    :   PeriodicEventHandler(interval), m_silo(silo) {}

    virtual void handleEvent(State& state, Real accuracy,
                             bool& shouldTerminate) const override
    {
        int menuId, item;
        if (m_silo.takeMenuPick(menuId, item) && menuId==RunMenuId && item==QuitItem)
            shouldTerminate = true;
    }

private:
    Visualizer::InputSilo& m_silo;
};

static void makeCube(Real h, PolygonalMesh& cube);
static void makeTetrahedron(Real r, PolygonalMesh& tet);
static void makePyramid(Real baseSideLength, PolygonalMesh& pyramid);
static void makeOctahedron(Real radius, PolygonalMesh& pyramid);

int main() {
  try
  { // Create the system.

    MultibodySystem         system;
    SimbodyMatterSubsystem  matter(system);
    GeneralForceSubsystem   forces(system);
    Force::Gravity   gravity(forces, matter, UnitVec3(2,-10,0), 1);

    ContactTrackerSubsystem  tracker(system);
    CompliantContactSubsystem contactForces(system, tracker);
    contactForces.setTrackDissipatedEnergy(true);
    contactForces.setTransitionVelocity(1e-3);

    GeneralContactSubsystem OLDcontact(system);
    const ContactSetIndex OLDcontactSet = OLDcontact.createContactSet();

    //makeCube(1, pyramidMesh);
    //makeTetrahedron(1, pyramidMesh);
    //pyramidMesh.transformMesh(Rotation(Pi/4, UnitVec3(-1,0,1)));
    //makePyramid(1, pyramidMesh);
    //makeOctahedron(1, pyramidMesh);
    PolygonalMesh sphereMesh;
    sphereMesh = PolygonalMesh::createSphereMesh(1,4);

    ContactGeometry::TriangleMesh sphere(sphereMesh);
    DecorativeMesh showSphere(sphere.createPolygonalMesh());
    Array_<DecorativeLine> normals;
    const Real NormalLength = .02;
    for (int fx=0; fx < sphere.getNumFaces(); ++fx)
        normals.push_back(
        DecorativeLine(sphere.findCentroid(fx),
                       sphere.findCentroid(fx)
                           + NormalLength*sphere.getFaceNormal(fx)));
    // not displaying mesh normals at the moment

    ContactCliqueId clique1 = ContactSurface::createNewContactClique();
    ContactCliqueId clique2 = ContactSurface::createNewContactClique();
    ContactCliqueId clique3 = ContactSurface::createNewContactClique();

    const Real fFac =1; // to turn off friction
    const Real fDis = .5*0.2; // to turn off dissipation
    const Real fVis =  .1*.1; // to turn off viscous friction
    const Real fK = 100*1e6; // pascals

    // Right hand wall
    matter.Ground().updBody().addDecoration(Vec3(.25+.01,0,0),
        DecorativeBrick(Vec3(.01,4,8)).setColor(Gray).setOpacity(.2));
    matter.Ground().updBody().addContactSurface(Vec3(.25,0,0),
        ContactSurface(ContactGeometry::HalfSpace(),
                       ContactMaterial(fK*.01,fDis*.9,fFac*.8,fFac*.7,fVis*10))
                       .joinClique(clique3));

    // Halfspace floor
    const Rotation R_xdown(-Pi/2,ZAxis);
    //matter.Ground().updBody().addDecoration(
    //    Transform(R_xdown, Vec3(0,-3-.01,0)),
    //    DecorativeBrick(Vec3(.01,4,8)).setColor(Gray).setOpacity(.1));
    matter.Ground().updBody().addContactSurface(
        Transform(R_xdown, Vec3(0,-3,0)),
        ContactSurface(ContactGeometry::HalfSpace(),
                       ContactMaterial(fK*.1,fDis*.9,fFac*.8,fFac*.7,fVis*10))
                       //ContactMaterial(2e6,.01,.1,.05,.01))
                       .joinClique(clique1));

    //// Big Sphere floor
    //const Real FloorRadius = 10;
    //matter.Ground().updBody().addDecoration(
    //    Vec3(0,-FloorRadius-3,0),
    //    DecorativeSphere(FloorRadius).setColor(Green));
    //matter.Ground().updBody().addContactSurface(
    //    Vec3(0,-FloorRadius-3,0),
    //    ContactSurface(ContactGeometry::Sphere(FloorRadius),
    //                   ContactMaterial(1e6,fDis*.9,fFac*.8,fFac*.7,fVis*10))
    //                   //ContactMaterial(2e6,.01,.1,.05,.01))
    //                   .joinClique(clique1));

    const Real rad = .4;
    Body::Rigid pendulumBody1(MassProperties(1.0, Vec3(0), Inertia(1)));
    pendulumBody1.addDecoration(Transform(),
        DecorativeSphere(rad).setOpacity(.4));
    pendulumBody1.addContactSurface(Transform(),
        ContactSurface(ContactGeometry::Sphere(rad),
                       ContactMaterial(fK*.01,fDis*.9,fFac*.8,fFac*.7,fVis*10))
                       .joinClique(clique2));

    Body::Rigid pendulumBody2(MassProperties(1.0, Vec3(0), Inertia(1)));
    pendulumBody2.addDecoration(Transform(),
        DecorativeSphere(rad).setColor(Orange).setOpacity(.4));
    pendulumBody2.addContactSurface(Transform(),
        ContactSurface(ContactGeometry::Sphere(rad),
                       ContactMaterial(fK*.01,fDis*.9,fFac*.8,fFac*.7,fVis*10))
                       .joinClique(clique1));

    MobilizedBody::Pin pendulum(matter.Ground(), Transform(Vec3(0)),
                                pendulumBody1,    Transform(Vec3(0, 1, 0)));

    MobilizedBody::Pin pendulum2(pendulum, Transform(Vec3(0)),
                                 pendulumBody2, Transform(Vec3(0, 1, 0)));

    Body::Rigid pendulumBody3(MassProperties(100.0, Vec3(0), 100*Inertia(1)));
    PolygonalMesh body3contact = PolygonalMesh::createSphereMesh(rad,2);
    ContactGeometry::TriangleMesh geo3(body3contact);
    const DecorativeMesh mesh3(geo3.createPolygonalMesh());
    pendulumBody3.addDecoration(Transform(),
        DecorativeMesh(mesh3).setOpacity(.2));
    pendulumBody3.addDecoration(Transform(),
        DecorativeMesh(mesh3).setColor(Gray)
                   .setRepresentation(DecorativeGeometry::DrawWireframe)
                   .setOpacity(.1));

    //ContactGeometry::Sphere geo3(rad);
    pendulumBody3.addContactSurface(Transform(),
        ContactSurface(geo3,
                       ContactMaterial(fK*.1,fDis*.9,fFac*.8,fFac*.7,fVis*10),
                       rad/2 /*thickness*/)
                       .joinClique(clique2));
    MobilizedBody::Pin pendulum3(matter.Ground(), Transform(Vec3(-2,0,0)),
                                 pendulumBody3, Transform(Vec3(0, 2, 0)));

    Force::MobilityLinearSpring(forces, pendulum2, MobilizerUIndex(0),
        10, 0*(Pi/180));

    const Real ballMass = 200;
    Body::Rigid ballBody(MassProperties(ballMass, Vec3(0),
                            ballMass*UnitInertia::sphere(1)));
    //ballBody.addDecoration(Transform(), DecorativeSphere(.3).setColor(Cyan));
    //ballBody.addContactSurface(Transform(),
    //    ContactSurface(ContactGeometry::Sphere(.3),
    //                   ContactMaterial(1e7,.05,fFac*.8,fFac*.7,fVis*10))
    //                   .joinClique(clique2));
    ballBody.addDecoration(Transform(),
        showSphere.setColor(Cyan).setOpacity(.2));
    ballBody.addDecoration(Transform(),
        showSphere.setColor(Gray)
                   .setRepresentation(DecorativeGeometry::DrawWireframe));
    //Use this to display surface normals if you want to see them.
    //for (unsigned i=0; i < normals.size(); ++i)
    //    ballBody.addDecoration(Transform(),
    //        normals[i].setColor(Gray));
    ballBody.addDecoration(Transform(), DecorativeSphere(1).setColor(Gray)
                                             .setOpacity(.1).setResolution(10));
    ballBody.addContactSurface(Transform(),
        ContactSurface(sphere,
                       ContactMaterial(fK*.1,fDis*.9,
                                       .1*fFac*.8,.1*fFac*.7,fVis*1),
                       .5 /*thickness*/)
                       //ContactMaterial(2e6,.01,.1,.05,.01))
                       //.joinClique(clique2)
                       );
    MobilizedBody::Free ball(matter.Ground(), Transform(Vec3(-2,0,0)),
        ballBody, Transform(Vec3(0)));

    //// The old way ...
    //OLDcontact.addBody(OLDcontactSet, ball,
    //    pyramid, Transform());

    //OLDcontact.addBody(OLDcontactSet, matter.updGround(),
    //    ContactGeometry::HalfSpace(), Transform(R_xdown, Vec3(0,-3,0)));
    //ElasticFoundationForce ef(forces, OLDcontact, OLDcontactSet);
    //Real stiffness = 1e6, dissipation = 0.01, us = 0.1,
    //    ud = 0.05, uv = 0.01, vt = 0.01;
    ////Real stiffness = 1e6, dissipation = 0.1, us = 0.8,
    ////    ud = 0.7, uv = 0.01, vt = 0.01;

    //ef.setBodyParameters(ContactSurfaceIndex(0),
    //    stiffness, dissipation, us, ud, uv);
    //ef.setTransitionVelocity(vt);
    //// end of old way.

    Visualizer viz(system);
    viz.addDecorationGenerator(new ForceArrowGenerator(system,contactForces));
    viz.setMode(Visualizer::RealTime);
    viz.setDesiredBufferLengthInSec(1);
    viz.setDesiredFrameRate(FrameRate);
    viz.setGroundHeight(-3);
    viz.setShowShadows(true);

    Visualizer::InputSilo* silo = new Visualizer::InputSilo();
    viz.addInputListener(silo);
    Array_<std::pair<String,int> > runMenuItems;
    runMenuItems.push_back(std::make_pair("Go", GoItem));
    runMenuItems.push_back(std::make_pair("Replay", ReplayItem));
    runMenuItems.push_back(std::make_pair("Quit", QuitItem));
    viz.addMenu("Run", RunMenuId, runMenuItems);

    Array_<std::pair<String,int> > helpMenuItems;
    helpMenuItems.push_back(std::make_pair("TBD - Sorry!", 1));
    viz.addMenu("Help", HelpMenuId, helpMenuItems);

    system.addEventReporter(new MyReporter(system,contactForces,ReportInterval));
    system.addEventReporter(new Visualizer::Reporter(viz, ReportInterval));

    // Check for a Run->Quit menu pick every 1/4 second.
    system.addEventHandler(new UserInputHandler(*silo, .25));

    // Initialize the system and state.

    system.realizeTopology();

    // Show ContactSurfaceIndex for each contact surface
    for (MobilizedBodyIndex mbx(0); mbx < matter.getNumBodies(); ++mbx) {
        const MobilizedBody& mobod = matter.getMobilizedBody(mbx);
        const int nsurfs = mobod.getBody().getNumContactSurfaces();
        printf("mobod %d has %d contact surfaces\n", (int)mbx, nsurfs);
        for (int i=0; i<nsurfs; ++i) {
            printf("%2d: index %d\n", i,
                   (int)tracker.getContactSurfaceIndex(mbx,i));
        }
    }

    State state = system.getDefaultState();
    ball.setQToFitTransform(state, Transform(Rotation(Pi/2,XAxis),
                                             Vec3(0,-1.8,0)));

    pendulum.setOneQ(state, 0, -Pi/12);
    pendulum3.setOneQ(state, 0, -Pi/4);

    viz.report(state);
    printf("Default state\n");
    cout << "t=" << state.getTime()
         << " q=" << pendulum.getQAsVector(state) << pendulum2.getQAsVector(state)
         << " u=" << pendulum.getUAsVector(state) << pendulum2.getUAsVector(state)
         << endl;

    cout << "\nChoose 'Go' from Run menu to simulate:\n";
    int menuId, item;
    do { silo->waitForMenuPick(menuId, item);
         if (menuId != RunMenuId || item != GoItem)
             cout << "\aDude ... follow instructions!\n";
    } while (menuId != RunMenuId || item != GoItem);

    pendulum.setOneU(state, 0, 5.0);
    ball.setOneU(state, 2, -20);

    ball.setOneU(state, 0, .05); // to break symmetry

    // Simulate it.

    // The system as parameterized is very stiff (mostly due to friction)
    // and thus runs best with CPodes which is extremely stable for
    // stiff problems. To get reasonable performance out of the explicit
    // integrators (like the RKs) you'll have to run at a very loose
    // accuracy like 0.1, or reduce the friction coefficients and
    // maybe the stiffnesses.

    //ExplicitEulerIntegrator integ(system);
    CPodesIntegrator integ(system,CPodes::BDF,CPodes::Newton);
    //RungeKuttaFeldbergIntegrator integ(system);
    //RungeKuttaMersonIntegrator integ(system);
    //RungeKutta3Integrator integ(system);
    //VerletIntegrator integ(system);
    //integ.setMaximumStepSize(1e-0001);
    integ.setAccuracy(1e-3); // minimum for CPodes
    //integ.setAccuracy(.01);
    TimeStepper ts(system, integ);

    ts.initialize(state);
    double cpuStart = cpuTime();
    double realStart = realTime();

    ts.stepTo(20.0);

    const double timeInSec = realTime() - realStart;
    const int evals = integ.getNumRealizations();
    cout << "Done -- took " << integ.getNumStepsTaken() << " steps in " <<
        timeInSec << "s elapsed for " << ts.getTime() << "s sim (avg step="
        << (1000*ts.getTime())/integ.getNumStepsTaken() << "ms) "
        << (1000*ts.getTime())/evals << "ms/eval\n";
    cout << "  CPU time was " << cpuTime() - cpuStart << "s\n";

    printf("Using Integrator %s at accuracy %g:\n",
        integ.getMethodName(), integ.getAccuracyInUse());
    printf("# STEPS/ATTEMPTS = %d/%d\n", integ.getNumStepsTaken(), integ.getNumStepsAttempted());
    printf("# ERR TEST FAILS = %d\n", integ.getNumErrorTestFailures());
    printf("# REALIZE/PROJECT = %d/%d\n", integ.getNumRealizations(), integ.getNumProjections());

    viz.dumpStats(std::cout);

    // Add as slider to control playback speed.
    viz.addSlider("Speed", 1, 0, 4, 1);
    viz.setMode(Visualizer::PassThrough);

    silo->clear(); // forget earlier input
    double speed = 1; // will change if slider moves
    while(true) {
        cout << "Choose Run/Replay to see that again ...\n";

        int menuId, item;
        silo->waitForMenuPick(menuId, item);

        if (menuId != RunMenuId) {
            cout << "\aUse the Run menu!\n";
            continue;
        }

        if (item == QuitItem)
            break;
        if (item != ReplayItem) {
            cout << "\aHuh? Try again.\n";
            continue;
        }

        for (double i=0; i < (int)saveEm.size(); i += speed ) {
            int slider; Real newValue;
            if (silo->takeSliderMove(slider,newValue)) {
                speed = newValue;
            }
            viz.report(saveEm[(int)i]);
        }
    }

  } catch (const std::exception& e) {
    std::printf("EXCEPTION THROWN: %s\n", e.what());
    exit(1);

  } catch (...) {
    std::printf("UNKNOWN EXCEPTION THROWN\n");
    exit(1);
  }

    return 0;
}

// Create a triangle mesh in the shape of a pyramid, with the
// square base in the x-z plane centered at 0,0,0 of given side length s.
// The base is split into two triangles. The apex will be at (0,s,0).
static void makePyramid(Real s, PolygonalMesh& pyramidMesh) {
    const Real h = s/2;
    Array_<Vec3> vertices;
    vertices.push_back(Vec3(-h, 0, -h));     // base
    vertices.push_back(Vec3( h, 0, -h));
    vertices.push_back(Vec3( h, 0,  h));
    vertices.push_back(Vec3(-h, 0,  h));
    vertices.push_back(Vec3( 0, s,  0)); // apex
    Array_<int> faceIndices;
    int faces[6][3] = {{0, 1, 2}, {0, 2, 3}, {1, 0, 4},
                       {2, 1, 4}, {3, 2, 4}, {0, 3, 4}};
    for (int i = 0; i < 6; i++)
        for (int j = 0; j < 3; j++)
            faceIndices.push_back(faces[i][j]);

    for (unsigned i=0; i < vertices.size(); ++i)
        pyramidMesh.addVertex(vertices[i]);
    for (unsigned i=0; i < faceIndices.size(); i += 3) {
        const Array_<int> verts(&faceIndices[i], &faceIndices[i]+3);
        pyramidMesh.addFace(verts);
    }
}

// Create a triangle mesh in the shape of a tetrahedron with the
// points in the corners of a cube inscribed in a sphere of radius r.
static void makeTetrahedron(Real r, PolygonalMesh& tet) {
    const Real h = r/std::sqrt(Real(3)); // half-dim of cube
    Array_<Vec3> vertices;
    vertices.push_back(Vec3( h, h,  h));
    vertices.push_back(Vec3(-h,-h,  h));
    vertices.push_back(Vec3(-h, h, -h));
    vertices.push_back(Vec3( h,-h, -h));
    Array_<int> faceIndices;
    int faces[4][3] = {{0, 2, 1}, {1, 3, 0}, {0, 3, 2}, {2, 3, 1}};
    for (int i = 0; i < 4; i++)
        for (int j = 0; j < 3; j++)
            faceIndices.push_back(faces[i][j]);

    for (unsigned i=0; i < vertices.size(); ++i)
        tet.addVertex(vertices[i]);
    for (unsigned i=0; i < faceIndices.size(); i += 3) {
        const Array_<int> verts(&faceIndices[i], &faceIndices[i]+3);
        tet.addFace(verts);
    }
}

static void makeOctahedralMesh(const Vec3& r, Array_<Vec3>& vertices,
                               Array_<int>&  faceIndices) {
    vertices.push_back(Vec3( r[0],  0,  0));   //0
    vertices.push_back(Vec3(-r[0],  0,  0));   //1
    vertices.push_back(Vec3( 0,  r[1],  0));   //2
    vertices.push_back(Vec3( 0, -r[1],  0));   //3
    vertices.push_back(Vec3( 0,  0,  r[2]));   //4
    vertices.push_back(Vec3( 0,  0, -r[2]));   //5
    int faces[8][3] = {{0, 2, 4}, {4, 2, 1}, {1, 2, 5}, {5, 2, 0},
                       {4, 3, 0}, {1, 3, 4}, {5, 3, 1}, {0, 3, 5}};
    for (int i = 0; i < 8; i++)
        for (int j = 0; j < 3; j++)
            faceIndices.push_back(faces[i][j]);
}

// Create a triangle mesh in the shape of an octahedron (like two
// pyramids stacked base-to-base, with the square base in the x-z plane
// centered at 0,0,0 of given "radius" r.
// The apexes will be at (0,+/-r,0).
static void makeOctahedron(Real r, PolygonalMesh& mesh) {
    Array_<Vec3> vertices;
    Array_<int> faceIndices;
    makeOctahedralMesh(Vec3(r), vertices, faceIndices);

    for (unsigned i=0; i < vertices.size(); ++i)
        mesh.addVertex(vertices[i]);
    for (unsigned i=0; i < faceIndices.size(); i += 3) {
        const Array_<int> verts(&faceIndices[i], &faceIndices[i]+3);
        mesh.addFace(verts);
    }
}

static void makeCube(Real h, PolygonalMesh& cube) {
    Array_<Vec3> vertices;
    vertices.push_back(Vec3( h, h,  h));
    vertices.push_back(Vec3( h, h, -h));
    vertices.push_back(Vec3( h,-h,  h));
    vertices.push_back(Vec3( h,-h, -h));
    vertices.push_back(Vec3(-h, h,  h));
    vertices.push_back(Vec3(-h, h, -h));
    vertices.push_back(Vec3(-h,-h,  h));
    vertices.push_back(Vec3(-h,-h, -h));

    Array_<int> faceIndices;
    int faces[6][4] = {{0,2,3,1},{1,5,4,0},{0,4,6,2},
                       {2,6,7,3},{3,7,5,1},{4,5,7,6}};
    for (int i = 0; i < 6; i++)
        for (int j = 0; j < 4; j++)
            faceIndices.push_back(faces[i][j]);

    for (unsigned i=0; i < vertices.size(); ++i)
        cube.addVertex(vertices[i]);
    for (unsigned i=0; i < faceIndices.size(); i += 4) {
        const Array_<int> verts(&faceIndices[i], &faceIndices[i]+4);
        cube.addFace(verts);
    }
}


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

    <title></title>

    <link href="../web/style.css" rel="stylesheet" type="text/css"/>

SceneJS > Examples > Subgraph Config on Pick Demo *

        <canvas id="theCanvas" width="1030" height="700">

This example requires a browser that supports the
                HTML5
                <canvas> feature.

        </canvas>

SceneJS Picking - Re-configuring Subgraph Nodes when they are Picked

This is a basic example that shows how picking can be used with a SceneJS.WithConfigs node, where the
                node responds to "picked" events in its subgraph by pushing new configurations (or content) into
                them.

Scene source code

Log


text:
name             'chef-init-apache2-apps'
maintainer       'Vubeology, LLC'
maintainer_email 'ross@vubeology.com'
license          'MIT'
description      'Easily install and configure apache2 web apps'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '0.0.1'

depends "apache2"


text:
// <copyright file="ProgressForm.cs" company="Adam Nachman">
// Copyright (c) 2009 All Right Reserved Adam Nachman
// 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.
// </copyright>
// <author>Adam Nachman</author>
namespace SqlDeployment
{
    using System;
    using System.Data.SqlClient;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Windows.Forms;
    using Microsoft.SqlServer.Management.Smo;

    // TODO: Handle cancel event to break execution on a given script, not just between scripts

    /// <summary>
    /// The ProgressForm class
    /// </summary>
    internal partial class ProgressForm : Form
    {
        #region Private Variables

        private Microsoft.SqlServer.Management.Smo.Server server = null;
        private Microsoft.SqlServer.Management.Smo.Database database = null;
        private ScriptExecutor executor = null;
        private ScriptExecutorConfiguration config = null;
        private Regex counterExpression = new Regex("(?<ObjectCount>[0-9])");
        private Regex progressExpression = new Regex("(\\d{1,})");
        private Thread executionThread = null;

        #endregion Private Variables

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the ProgressForm class
        /// </summary>
        /// <param name="server">The server to which the class is connected</param>
        /// <param name="database">The database againts which the class is executing</param>
        /// <param name="config">The cofiguration</param>
        public ProgressForm(Server server, Database database, ScriptExecutorConfiguration config)
        {
            if (server == null)
            {
                throw new ArgumentNullException("server", "server cannot be null");
            }

            if (database == null)
            {
                throw new ArgumentNullException("database", "database cannot be null");
            }

            if (config == null)
            {
                throw new ArgumentNullException("config", "config cannot be null");
            }

            this.server = server;
            this.database = database;
            this.config = config;
            this.InitializeComponent();
        }

        #endregion Constructors

        #region Delegates

        /// <summary>
        /// A delegate to handle the OnProgress events from the script executor
        /// </summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">The ScriptExecutorEventArgs arguments</param>
        private delegate void HandleOnProgressDelegate(object sender, ScriptExecutorEventArgs[] e);

        #endregion Delegates

        #region Form Event Handlers

        /// <summary>
        /// Fire on form load
        /// </summary>
        /// <param name="sender">The object sender</param>
        /// <param name="e">The EventArgs</param>
        private void ProgressForm_Load(object sender, EventArgs e)
        {
            this.InitializeFormValues();
        }

        /// <summary>
        /// Fires on form shown
        /// </summary>
        /// <param name="sender">The object sender</param>
        /// <param name="e">The EventArgs</param>
        private void ProgressForm_Shown(object sender, EventArgs e)
        {
            // TODO: Check Thread state
            this.ToggleButtonState(false);
            this.executionThread = new Thread(new ThreadStart(this.ExecuteScripts));
            this.executionThread.Start();
        }

        /// <summary>
        /// Fires on OK click
        /// </summary>
        /// <param name="sender">The object sender</param>
        /// <param name="e">The EventArgs</param>
        private void Ok_Click(object sender, EventArgs e)
        {
            // TODO: Check Thread state
            // TODO: Manage button state
            // TODO: Check execution state
            this.Close();
        }

        /// <summary>
        /// Cancels execution
        /// </summary>
        /// <param name="sender">The object sender</param>
        /// <param name="e">The EventArgs</param>
        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.executor.Stop();
        }

        #endregion Form Event Handlers

        #region Private Methods

        /// <summary>
        /// Initializes the form values
        /// </summary>
        private void InitializeFormValues()
        {
            this.lblProgress.Text = string.Empty;
            this.lblCurrentOperation.Text = string.Empty;
            this.progressOverall.Value = 0;
            this.progressOverall.Maximum = this.config.ExecutionSequence.Count;
        }

        /// <summary>
        /// Handles the progress of the script executor
        /// </summary>
        /// <param name="sender">The object sender</param>
        /// <param name="e">The event arguments</param>
        private void OnProgress(object sender, ScriptExecutorEventArgs[] e)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new HandleOnProgressDelegate(this.HandleOnProgress), sender, e);
            }
            else
            {
                this.HandleOnProgress(sender, e);
            }
        }

        /// <summary>
        /// Handles the progress of the script executor
        /// </summary>
        /// <param name="sender">The object sender</param>
        /// <param name="e">The event arguments</param>
        private void HandleOnProgress(object sender, ScriptExecutorEventArgs[] e)
        {
            Match m = null;
            if (e != null && e.Length > 0)
            {
                int length = e.Length;
                for (int i = 0; i < length; i++)
                {
                    switch (e[i].EventCode)
                    {
                        case ScriptExecutorEventArgs.EventMessageCode.ObjectCount:
                            this.progressCurrent.Value = 0;
                            m = this.counterExpression.Match(e[i].EventMessage);
                            if (m.Success)
                            {
                                this.progressCurrent.Maximum = int.Parse(m.Groups["ObjectCount"].Value);
                            }

                            break;
                        case ScriptExecutorEventArgs.EventMessageCode.Progress:
                            int progress = 0;
                            int count = 0;
                            m = this.progressExpression.Match(e[i].EventMessage);
                            this.lblCurrentOperation.Text = e[i].EventMessage.Replace("|", string.Empty);
                            if (m.Success)
                            {
                                progress = int.Parse(m.Groups[0].Value);
                                m = m.NextMatch();
                                count = int.Parse(m.Groups[0].Value);
                                if (count > this.progressCurrent.Maximum)
                                {
                                    this.progressCurrent.Maximum = count;
                                }

                                this.progressCurrent.Value = progress;
                            }

                            break;
                        case ScriptExecutorEventArgs.EventMessageCode.ExecutionComplete:
                            this.lblProgress.Text = "Complete";
                            this.ToggleButtonState(true);
                            break;
                        case ScriptExecutorEventArgs.EventMessageCode.ExecutionStoppingByRequest:
                            this.lblProgress.Text = "Stopping script execution";
                            break;
                        case ScriptExecutorEventArgs.EventMessageCode.ExecutionStoppedByRequest:
                            this.lblProgress.Text = "Execution stopped by user request";
                            this.ToggleButtonState(true);
                            break;
                        case ScriptExecutorEventArgs.EventMessageCode.ScriptExecution:
                            this.lblProgress.Text = e[i].EventMessage.Replace(".sql", string.Empty);
                            this.progressOverall.Value += 1;
                            break;
                        case ScriptExecutorEventArgs.EventMessageCode.SqlInfoMessage:
                            this.txtMessageInfo.AppendText(string.Concat(DateTime.Now.ToString("hh:mm tt"), " - ", e[i].EventMessage, Environment.NewLine));
                            break;
                    }
                }
            }

            Application.DoEvents();
        }

        /// <summary>
        /// Executes the scripts
        /// </summary>
        private void ExecuteScripts()
        {
            try
            {
                this.executor = new ScriptExecutor(this.server, this.database, this.config);
                this.executor.Progress += new ScriptExecutor.ScriptExecutorEventHandler(this.OnProgress);
                this.executor.Execute();
            }
            catch (FailedOperationException ex)
            {
                SqlException sqlEx = ex.InnerException.InnerException as SqlException;
                MessageBox.Show(sqlEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                this.executor.Progress -= new ScriptExecutor.ScriptExecutorEventHandler(this.OnProgress);
            }
        }

        /// <summary>
        /// Toggles the button states
        /// </summary>
        /// <param name="enableOK">The state of the "OK" button</param>
        private void ToggleButtonState(bool enableOK)
        {
            this.btnOK.Enabled = enableOK;
            this.btnCancel.Enabled = !enableOK;
        }

        #endregion Private Methods
    }
}


text:
package com.microsoft.band.sdk.sampleapp;

import android.app.Activity;
import android.app.Application;

public class BandNotificationToPinyin extends Application {
    private Activity mCurrentActivity = null;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public Activity getCurrentActivity() {
        return mCurrentActivity;
    }

    public void setCurrentActivity(Activity mCurrentActivity) {
        this.mCurrentActivity = mCurrentActivity;
    }
}