text:
<!doctype html>

		<meta charset="utf-8">

		<title>Learning Typescript</title>

		<meta name="description" content="A guided introduction to Typescript">
		<meta name="author" content="Bryan Rayner">

		<meta name="apple-mobile-web-app-capable" content="yes" />
		<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />

		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<link rel="stylesheet" href="css/reveal.min.css">
		<link rel="stylesheet" href="css/theme/default.css" id="theme">

		<link rel="stylesheet" href="lib/css/zenburn.css">

Learning Typescript

Or, an appeal to Web Developers to embrace typed languages

						Created by Bryan E Rayner

Why not just Javascript?

Javascript, for all it's benefits, provides a considerable challenge for many developers.

Especially in team environments, many web developers opt for different solutions to work around the pitfalls.

What's so bad?

While reasons vary between developers, many leave for common, related reasons:

Limited syntax

Foreign concepts (prototypes)

Perceived language limitations

Lack of IDE support

Preference for different syntax (Ruby)

Alternatives

There are many options available to web developers looking for Javascript alternatives.

Coffee Script

Traceur (ES6 compiler)

Clojurescript

Dart

Typescript

Today, we'll be focusing on Typescript.

Why Typescript?

Typescript avoids changing the syntax of Javascript as much as possible.

All Javascript is Jperfectly valid Typescript. Typescript outputs human-readable Javascript.

Typescript adds one feature that is missing from Javascript - Type Definitions.

What is a type?

Type systems have existed in computing for longer than I've been alive.

They are one of the only things keeping your code working.

They translate this:
						var boxCounter = 5;

To this value in RAM:
						00000000 00000000 00000000 00000101

Strong / Weak types

To demonstrate the differences between strong & weak types in languages, look at this code snippet:

// Javascript:
	// This is a variable. It could be anything.
	var boxCounter;         // Allocate an arbitrary amount of RAM.
	boxCounter = 5;         // Store a value of 5.
	boxCounter = 'cinco';   // Store an array of 16-bit Unicode Characters.

	// C++:
	// This is a 64-bit integer.
	// It can be anything from –2,147,483,648 to 2,147,483,647
	long boxCounter;            // Allocate 8 bytes in RAM.
	boxCounter = 5;             // Set the value to 5.
	boxCounter = 'no bueno';    // This code won't even work.

Why do Static Typing?

There are many benefits to statically typed languages:
						- IDE support for auto-completion / closer teamwork.
						- Ability to quickly find errors
						- Faster code execution
						- Less run-time errors

Objections to Static Types:

Programmers who come from a Javascript/Python/Ruby background can have objections to type systems:

Type systems add complicated syntax to my code

It takes longer for me to write code in C++, Java, etc...

I want to accept multiple types of inputs for my function.

I like to quack when I work. 'Duck Typing' please.

Best of Both Worlds

Typescript provides an answer to the Javascript developer who is looking to have all the benefits
						of statically typed systems, without the headaches associated with a complicated type syntax.

Types are optional - All Javascript is perfectly valid Typescript.

Types and Interfaces

We use types all the time - A Javascript developer commonly recognizes five types:

Number
	String
	Boolean
	Object
	Function

Default types in Typescript

Like Javascript, Typescript supports some basic types:

number
	boolean
	string

Plus, some new types:
						void
						any

What happened to Object and Function?

Compilers

In reality, Object and Function are much more complicated than they appear.
						An object could be anything, and it can change over time.

// Perfectly valid (and insane) Javascript:
	var object = {};
	object.value = 'The fruit bowl has the following: ';
	object.value = function () { return 'Apple';}
	object['value'] = object.value() + "'s and oranges.";
	object.value = (function() {
	return object.value + ' And banannas.';
	})();

How is a compiler to know which is which?

How can an IDE provide you with reliable code hinting in this situation?

'Duck Typing' works great for developers, but how do you tell a compiler what a duck is?

Interfaces

Interfaces tell Typescript what to expect when it sees your custom object.

// Duck interface
	interface Duck {
	age: number;
	name: string;
	secretIdentity: string;

	walk(distance:number): void;
	fly(destination:string) : void;
	quack(volume: number): void;
	}

Generic Types

For a typical SPA, we might see something like this:

interface Resource<T> {
	route: string;
	get(): T;
	post(value:T): boolean;
	put(values: any): boolean;
	delete(value: T): boolean;
	}

<T> represents a generic type. It gets defined as you use it.

Example:

interface Chicken{
	id: number;
	name: string;
	breed: string;
	weight: number;
	}

	class ChickenResource implements Resource<Chicken>
	{

	}

Setting Up Typescript

Setting up Typescript requires a working knowledge of NPM. We'll also be covering Grunt-TS,
						and how this can be used to compile Typescript files on a project basis.

NPM Package

npm install -g typescript

This installs the Typescript compiler globally. The latest version is 1.1.0-1, which we'll be using.

Typescript Compiler

tsc [options] [file]

Unfortunately, this doesn't watch entire folders, like SASS. However, this can be fixed quickly with Grunt-TS.

THE END


text:
const DrawCard = require('../../../drawcard.js');

class TheHandsSolar extends DrawCard {
    setupCardAbilities(ability) {
        this.action({
            title: 'Kneel to give INT icon',
            cost: ability.costs.kneelSelf(),
            target: {
                activePromptTitle: 'Select a character',
                cardCondition: card => card.location === 'play area' && card.getType() === 'character'
            },
            handler: context => {
                this.untilEndOfPhase(ability => ({
                    match: context.target,
                    effect: ability.effects.addIcon('intrigue')
                }));

                this.game.addMessage('{0} kneels {1} to give {2} an {3} icon until the end of the phase',
                                      this.controller, this, context.target, 'intrigue');
            }
        });
    }
}

TheHandsSolar.code = '06030';

module.exports = TheHandsSolar;

redpajama_set_name: RedPajamaGithub


text:
"""This directory contains local site-specific implementations."""

import logging
from grr.lib import config_lib
from grr.lib import log as lib_log

def ConfigInit():
  config_lib.ConfigLibInit()

def ServerLogInit():
  lib_log.LogInit()
  lib_log.AppLogInit()

def ClientLogInit():
  lib_log.LogInit()


text:
package lib.driver.clinic.driver_class;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;

import lib.SessionFactoryUtil;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import core.classes.api.user.AdminUser;
import core.classes.clinic.clinic_patient_attachment;
import core.classes.clinic.clinic_patient_queue;
import core.classes.clinic.clinic_visit;
import core.classes.opd.Allergy;
import core.classes.opd.OutPatient;

public class clinic_patient_queueDBDriver {

	Session session = SessionFactoryUtil.getSessionFactory().getCurrentSession();

	public boolean saveclinic_patient_queue(clinic_patient_queue objclinic_patient_queue,int userid, int pID){
		Transaction tx=null;

		try {
			Calendar currentDate = Calendar.getInstance();
			tx = session.beginTransaction();
			clinic_visit objclinic_visit = (clinic_visit) session.get(clinic_visit.class, pID);
			AdminUser user = (AdminUser) session.get(AdminUser.class, userid);
			objclinic_patient_queue.setClinic_queue_assign_by(user);
			objclinic_patient_queue.setClinic_visit_id(objclinic_visit);
			session.save(objclinic_patient_queue);
			tx.commit();
			return true;
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return false;
		}

	}

	public boolean updateclinic_patient_queue(clinic_patient_queue objclinic_patient_queue,int userid){
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			clinic_patient_queue obj2clinic_patient_queue=(clinic_patient_queue) session.get(clinic_patient_queue.class, objclinic_patient_queue.getClinic_queue_token_no());
			obj2clinic_patient_queue.setClinic_visit_type(objclinic_patient_queue.getClinic_visit_type());
			obj2clinic_patient_queue.setClinic_queue_status(objclinic_patient_queue.getClinic_queue_status());
			obj2clinic_patient_queue.setClinic_queue_assign_date(objclinic_patient_queue.getClinic_queue_assign_date());
			clinic_visit objclinic_visit = (clinic_visit) session.get(clinic_visit.class, userid);
			obj2clinic_patient_queue.setClinic_visit_id(objclinic_visit);
			AdminUser user = (AdminUser) session.get(AdminUser.class, userid);
			obj2clinic_patient_queue.setClinic_queue_assign_by(user);
			session.update(obj2clinic_patient_queue);
			tx.commit();
			return true;
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return false;
		}

	}

	public List<clinic_patient_queue> retrieveclinic_patient_queueclinic_queue_token_no(int pID){
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("Select a from clinic_patient_queue as a where a.clinic_queue_token_no=:clinic_queue_token_no ");
			query.setParameter("clinic_queue_token_no", pID);
			List<clinic_patient_queue> aList = castList(clinic_patient_queue.class,query.list());
			tx.commit();
			return aList;
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return null;
		}
	}

	public List<clinic_patient_queue> retrieveclinic_patient_queue(){
		Transaction tx = null;
		try {
			tx = session.beginTransaction();
			Query query = session.createQuery("Select a from clinic_patient_queue as a ");
			List<clinic_patient_queue> aList = castList(clinic_patient_queue.class,query.list());
			tx.commit();
			return aList;
		} catch (RuntimeException ex) {
			if (tx != null && tx.isActive()) {
				try {
					tx.rollback();
				} catch (HibernateException he) {
					System.err.println("Error rolling back transaction");
				}
				throw ex;
			}
			return null;
		}
	}

	public static <T> List<T> castList(Class<? extends T> clazz, Collection<?> c) {
	    List<T> r = new ArrayList<T>(c.size());
	    for(Object o: c)
	      r.add(clazz.cast(o));
	    return r;
	}

}


text:
package com.kc.shiptransport.mvp.contacts;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import com.kc.shiptransport.R;
import com.kc.shiptransport.data.source.DataRepository;
import com.kc.shiptransport.mvp.BaseActivity;

/**
 * @author 邱永恒
 * @time 2017/8/11  9:49
 * @desc ${TODD}
 */

public class ContactActivity extends BaseActivity{

    private ContactFragment fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_plan);

        if (savedInstanceState != null) {
            fragment = (ContactFragment) getSupportFragmentManager().getFragment(savedInstanceState, "ContactFragment");
        } else {
            fragment = new ContactFragment();
        }

        if (!fragment.isAdded()) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragment_repository, fragment)
                    .commit();
        }

        new ContactPresenter(this, fragment, new DataRepository());
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (fragment.isAdded()) {
            getSupportFragmentManager().putFragment(outState, "ContactFragment", fragment);
        }
    }

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, ContactActivity.class);
        Bundle bundle = new Bundle();
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
}


text:
package com.haringeymobile.ukweather.test;

import android.content.Intent;
import android.test.ActivityUnitTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.widget.TextView;

import com.haringeymobile.ukweather.AboutActivity;

public class AboutActivityUnitTest extends ActivityUnitTestCase<AboutActivity> {

    private AboutActivity aboutActivity;
    private TextView aboutTextView_1;
    private TextView aboutTextView_2;

    public AboutActivityUnitTest() {
        super(AboutActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        Intent intent = new Intent(getInstrumentation().getTargetContext(), AboutActivity.class);
        startActivity(intent, null, null);
        aboutActivity = getActivity();
        aboutTextView_1 = (TextView) aboutActivity.findViewById(com.haringeymobile.ukweather.R.id.
                about_textview_part_1);
        aboutTextView_2 = (TextView) aboutActivity.findViewById(com.haringeymobile.ukweather.R.id.
                about_textview_part_2);
    }

    @MediumTest
    public void testPreConditions() {
        assertNotNull("Instance of AboutActivity is null", aboutActivity);
        assertNotNull("Text view for the first part is null", aboutTextView_1);
        assertNotNull("Text view for the first part is null", aboutTextView_2);
    }

}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

#include "pch.h"
#include "Scenario6_LargeCatalogProduct.xaml.h"

using namespace SDKTemplate;

using namespace Concurrency;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::ApplicationModel::Store;
using namespace Windows::UI::Xaml::Navigation;

Scenario6_LargeCatalogProduct::Scenario6_LargeCatalogProduct()
{
    InitializeComponent();
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.  The Parameter
/// property is typically used to configure the page.</param>
void Scenario6_LargeCatalogProduct::OnNavigatedTo(NavigationEventArgs^ e)
{
    ConfigureSimulatorAsync("in-app-purchase-large-catalog.xml").then([]()
    {
        return create_task(CurrentAppSimulator::LoadListingInformationAsync());
    }).then([this](task<ListingInformation^> currentTask)
    {
        try
        {
            ListingInformation^ listing = currentTask.get();
            auto product1 = listing->ProductListings->Lookup("product1");
            ProductPrice->Text = product1->FormattedPrice;
            product1ListingName = product1->Name;
            rootPage->NotifyUser("", NotifyType::StatusMessage);
        }
        catch (Platform::Exception^ exception)
        {
            rootPage->NotifyUser("LoadListingInformationAsync API call failed", NotifyType::ErrorMessage);
        }
        ProductNameChanged();
    });
}

Platform::String^ Scenario6_LargeCatalogProduct::BuildProductNameForDisplay()
{
    Platform::String^ displayName = DisplayNameTextBox->Text;
    return displayName->IsEmpty() ? product1ListingName : displayName;
}

void Scenario6_LargeCatalogProduct::ProductNameChanged()
{
    ProductName->Text = BuildProductNameForDisplay();
}

Platform::String^ Scenario6_LargeCatalogProduct::BuildOfferStringForDisplay(Platform::String^ offerId)
{
    if (offerId->IsEmpty())
    {
        return " with no offer id";
    }
    else
    {
        return " with offer id " + offerId;
    }
}

void Scenario6_LargeCatalogProduct::BuyAndFulfillProduct()
{
    Platform::String^ offerId = OfferIdTextBox->Text;
    Platform::String^ displayPropertiesName = DisplayNameTextBox->Text;
    ProductPurchaseDisplayProperties^ displayProperties = ref new ProductPurchaseDisplayProperties(displayPropertiesName);

    rootPage->NotifyUser("Buying Product 1" + BuildOfferStringForDisplay(offerId) + "...", NotifyType::StatusMessage);
    create_task(CurrentAppSimulator::RequestProductPurchaseAsync("product1", offerId, displayProperties)).then([this, offerId](task<PurchaseResults^> currentTask)
    {
        try
        {
            PurchaseResults^ results = currentTask.get();
            switch (results->Status)
            {
            case ProductPurchaseStatus::Succeeded:
                GrantFeatureLocally(results->TransactionId);
                FulfillProduct("product1", results);
                break;
            case ProductPurchaseStatus::NotFulfilled:
                if (!IsLocallyFulfilled(results->TransactionId))
                {
                    GrantFeatureLocally(results->TransactionId);
                }
                FulfillProduct("product1", results);
                break;
            case ProductPurchaseStatus::NotPurchased:
                rootPage->NotifyUser("Product 1" + BuildOfferStringForDisplay(offerId) + " was not purchased.", NotifyType::StatusMessage);
                break;
            }
        }
        catch (Platform::Exception^ exception)
        {
            rootPage->NotifyUser("Unable to buy Product 1" + BuildOfferStringForDisplay(offerId) + ".", NotifyType::ErrorMessage);
        }
    });
}

void Scenario6_LargeCatalogProduct::FulfillProduct(Platform::String^ productId, PurchaseResults^ purchaseResults)
{
    create_task(CurrentAppSimulator::ReportConsumableFulfillmentAsync(productId, purchaseResults->TransactionId)).then([this, purchaseResults](task<FulfillmentResult> currentTask)
    {
        Platform::String^ itemDescription = product1ListingName + BuildOfferStringForDisplay(purchaseResults->OfferId);
        Platform::String^ purchaseStringSimple = "You bought " + itemDescription + ".";
        if (purchaseResults->Status == ProductPurchaseStatus::NotFulfilled)
        {
            purchaseStringSimple = "You already purchased " + itemDescription + ".";
        }

        try
        {
            FulfillmentResult result = currentTask.get();
            switch (result)
            {
            case FulfillmentResult::Succeeded:
                if (purchaseResults->Status == ProductPurchaseStatus::NotFulfilled)
                {
                    rootPage->NotifyUser("You had already purchased " + itemDescription + " and it was just fulfilled.", NotifyType::StatusMessage);
                }
                else
                {
                    rootPage->NotifyUser("You bought and fulfilled " + itemDescription, NotifyType::StatusMessage);
                }
                break;
            case FulfillmentResult::NothingToFulfill:
                rootPage->NotifyUser("There is no purchased product 1 to fulfill with that transaction id.", NotifyType::StatusMessage);
                break;
            case FulfillmentResult::PurchasePending:
                rootPage->NotifyUser(purchaseStringSimple + " The purchase is pending so we cannot fulfill the product.", NotifyType::StatusMessage);
                break;
            case FulfillmentResult::PurchaseReverted:
                rootPage->NotifyUser(purchaseStringSimple + " But your purchase has been reverted.", NotifyType::StatusMessage);
                // Since the user's purchase was revoked, they got their money back.
                // You may want to revoke the user's access to the consumable content that was granted.
                break;
            case FulfillmentResult::ServerError:
                rootPage->NotifyUser(purchaseStringSimple + " There was an error when fulfilling.", NotifyType::StatusMessage);
                break;
            }
        }
        catch (Platform::Exception^ exception)
        {
            rootPage->NotifyUser(purchaseStringSimple + " There was an error when fulfilling.", NotifyType::ErrorMessage);
        }
    });
}

void Scenario6_LargeCatalogProduct::GrantFeatureLocally(Platform::Guid transactionId)
{
    consumedTransactionIds->Append(transactionId);

    // Grant the user their content. You will likely increase some kind of gold/coins/some other asset count.
}

bool Scenario6_LargeCatalogProduct::IsLocallyFulfilled(Platform::Guid transactionId)
{
    unsigned int index;
    return consumedTransactionIds->IndexOf(transactionId, &index);
}


text:
aws-tools
=========

***Sign S3 URL***

```
SYNOPSIS :
    sign_s3_url.bash
         --help
         --region <REGION>
         --bucket <BUCKET_NAME>
         --file <FILE_PATH>
         --aws-access-key-id <AWS_ACCESS_KEY_ID>
         --aws-secret-access-key <AWS_SECRET_ACCESS_KEY>
         --method <HTTP_REQUEST_METHOD>
         --minute-expire <MINUTE_TO_EXPIRE>

USE CASES :
    If you have a private/public S3 bucket and would like to share the downloadable links to anyone,
    this tool will help to generate signed S3 URLs

DESCRIPTION :
    --help                     Help page
    --region                   Region (optional, defaults to $AWS_DEFAULT_REGION)
                               Valid regions: ap-northeast-1 ap-southeast-1 ap-southeast-2
                                              eu-west-1 sa-east-1
                                              us-east-1 us-west-1 us-west-2
    --bucket                   Bucket name (require)
    --file-path                File path (require)
    --aws-access-key-id        AWS Access Key ID (optional, defaults to $AWS_ACCESS_KEY_ID)
    --aws-secret-access-key    AWS Secret Access Key (optional, defaults to $AWS_SECRET_ACCESS_KEY)
    --method                   HTTP request method (optional, defaults to 'GET' method)
    --minute-expire            Minutes to expire signed URL (optional, defaults to '15' minutes)

EXAMPLES :
    ./sign_s3_url.bash --help
    ./sign_s3_url.bash
        --bucket 'my_bucket_name'
        --file-path 'my_path/my_file.txt'
    ./sign_s3_url.bash
        --region 'us-west-1'
        --bucket 'my_bucket_name'
        --file-path 'my_path/my_file.txt'
        --aws-access-key-id '5KI6IA4AXMA39FV7O4E0'
        --aws-secret-access-key '5N2j9gJlw9azyLEVpbIOn/tZ2u3sVjjHM03qJfIA'
        --method 'PUT'
        --minute-expire 30
```


text:
package com.he5ed.lib.cloudprovider;

import android.content.Context;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
import static org.powermock.api.support.SuppressCode.suppressConstructor;

public class CloudProviderTest {

    private Context mContext;

    @Before
    public void setupAddNotePresenter() {
        // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To
        // inject the mocks in the test the initMocks method needs to be called.
        MockitoAnnotations.initMocks(this);

        // Get a reference to the class under test
        mContext = null;
    }

    @Test
    public void createCloudApi_noError() {
        suppressConstructor(CloudProvider.class);
        mockStatic(CloudProvider.class);
        CloudProvider mockCloudProvider = mock(CloudProvider.class);

    }

}


text:
verify.codeFix({
    description: `Convert 'SomeType' to mapped object type`,
    newFileContent: `type K = "foo" | "bar";
interface Foo { }
interface Bar<T> { bar: T; }
type SomeType = Foo & Bar<number> & {
    [prop in K]: any;
} & {
    a: number;
};`
})


text:
import {Component, Inject, ChangeDetectionStrategy} from 'angular2/core';
import {FormsTester,NOT_FITTING} from 'forms_a2/forms_a2';
import {AbstractControlRenderer,ControlRendererTester} from 'forms_a2/forms_a2';
import {PathUtil} from 'forms_a2/forms_a2';
import {DatalistIdProvider} from './DatalistIdProvider';

@Component({
    selector: 'TextDatalistControlRenderer',
    template: `

            {{label}}
            <input type="text" [(ngModel)]="_modelValue[fragment]" class="forms_textDatalistControl forms_controlInput" [attr.list]="_datalistId"/>
                <datalist [attr.id]="_datalistId">
                    <option *ngFor="#option of options" [value]="option"></option>
                </datalist>

{{error|json}}

    `
    ,
    styles: [``],
    directives:[],
    changeDetection:ChangeDetectionStrategy.OnPush
})
export class TextDatalistControlRenderer extends AbstractControlRenderer{
    private _subSchema:any;
    private _datalistId:string;
    constructor( @Inject('uiSchema') _uiSchema:IControlObject, @Inject('data') _data:any, @Inject('dataSchema') _dataSchema:any,datalistIdProvider:DatalistIdProvider) {
        super(_uiSchema,_data);
        this._subSchema=PathUtil.resolveSchema(_dataSchema,_uiSchema['scope']['$ref']);
        this._datalistId=datalistIdProvider.provideDatalistId;
    }

    private get options(){
        return this._subSchema.anyOf.reduce((prev,element)=>{return prev.concat(this.getOptions(element));},[]);
    }

    private getOptions(schema:any):any[]{
        if(schema.hasOwnProperty('enum'))
            return schema.enum;
        if(schema.hasOwnProperty('oneOf'))
            return schema.oneOf.reduce((prev,element)=>{return prev.concat(this.getOptions(element))},[]);
        if(schema.hasOwnProperty('allOf'))
            return schema.allOf.reduce((prev,element)=>{return prev.concat(this.getOptions(element))},[]);
        return [];
    }
}
export var TextDatalistControlRendererTester: FormsTester = function (element:IUISchemaElement, dataSchema:any, dataObject:any ){

    if(element.type!='Control')
        return NOT_FITTING;
    let currentDataSchema=PathUtil.resolveSchema(dataSchema,element['scope']['$ref']);
    if(
        currentDataSchema.anyOf!=undefined &&
        currentDataSchema.anyOf.reduce((prev,element)=>{return prev&&IsEnumOrString(element)},true)
    )
        return 10;
    return NOT_FITTING;
}
var IsEnumOrString=function(element:any):boolean{
    if(element.hasOwnProperty('enum') || element.type=='string')
        return true;
    if(element.hasOwnProperty('oneOf'))
        return element.oneOf.reduce((prev,element)=>{return prev&&IsEnumOrString(element)},true);
    if(element.hasOwnProperty('allOf'))
        return element.allOf.reduce((prev,element)=>{return prev&&IsEnumOrString(element)},true)
    return false;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<LearningStandards>
  <LearningStandardItem xml:lang="en" RefID="46FCB8D3BE3A40cc979606292BAD76AF">
    <RefURI>http://corestandards.org/ELA-Literacy/RL/3/3/</RefURI>
    <StandardHierarchyLevel>
      <number>6</number>
      <description>Standard</description>
    </StandardHierarchyLevel>
    <StatementCodes>
      <StatementCode>CCSS.ELA-Literacy.RL.3.3</StatementCode>
    </StatementCodes>
    <Statements>
      <Statement>Describe characters in a story (e.g., their traits, motivations, or feelings) and explain how their actions contribute to the sequence of events</Statement>
    </Statements>
    <GradeLevels>
      <GradeLevel>03</GradeLevel>
    </GradeLevels>
    <LearningStandardDocumentRefId>0FAC40650F514a459951A657F942B845</LearningStandardDocumentRefId>
    <RelatedLearningStandardItems>
      <LearningStandardItemRefId RelationshipType="childOf">A6406AEF4E9F4222BE929B9ADA7B8342</LearningStandardItemRefId>
    </RelatedLearningStandardItems>
  </LearningStandardItem>
</LearningStandards>


text:
layout: post
title: "OnClickListener with ProgressDialog by RxAndroid"
date: "2017-11-24 17:52"
author: 'u-ryo'
categories: [android, RxAndroid, RxJava, ProgressDialog]
comments: true
published: true
---
「clickしたらbackgroundで処理して
その間ProgressDialog出して
終わったらProgressDialog消して
終了/失敗dialogを表示する」のを
RxAndroid(AxJava)でやる、
というのは、
`using()`を使うといいらしいです。
cf. [RxJavaを使った通信中にProgressダイアログを出す](https://qiita.com/boohbah/items/e8010730725c54f85a3a)

元々がretrofit2を使ってないので、
retrofit2を使うともうちょっと違うかも。

```
@Override
public void onClick(View v) {
    LogUtil.d("診断取得結果をuploadする button");
    uploadButtonEnable(false);
    if (!activity.networkCheck()) {
        activity.genAlertDialog(activity.getString(
                R.string.no_network_connectivity_available_message),
                (dialog, which) -> {});
        uploadButtonEnable(true);
        return;
    }
    Single.using(this::showProgressDialog,
            dialog -> Single.<Boolean>create(this::setUploadSubscriber)
                    .subscribeOn(Schedulers.newThread())
                    .observeOn(AndroidSchedulers.mainThread()),
            Dialog::dismiss)
            .subscribe(this::controlUploadButtonWithDialog,
                    this::showUploadFailureDialog);
}

private ProgressDialog showProgressDialog() {
    ProgressDialog dialog = new ProgressDialog(activity);
    dialog.setMessage(activity.getString(R.string.history_uploading));
    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    dialog.show();
    LogUtil.d(dialog.toString());
    return dialog;
}

private void setUploadSubscriber(SingleSubscriber<? super Boolean> subscriber) {
    View historyListView = activity.findViewById(R.id.historyListView);
    List<String> selectedList = new ArrayList<>();
    Adapter adapter = null;
    if (historyListView != null) {
        adapter = ((ListView) historyListView).getAdapter();
        for (int i = 0; i < adapter.getCount(); i++) {
            Map<String, String> historyItems = (Map<String, String>) adapter.getItem(i);
            if ("true".equals(historyItems.get("historySelected"))) {
                selectedList.add(historyItems.get("historyCatalogID"));
            }
        }

        if (selectedList.isEmpty()) {
            subscriber.onSuccess(false);
            return;
        }
    }

    try {
        ProcessUtil.callReportDataAll(commonBean.toMapFull(), activity, selectedList);
        if ((!selectedList.isEmpty()
                && !ProcessUtil.uploadSucceeded(selectedList, activity))
                || (selectedList.isEmpty()
                && !ProcessUtil.lastUploadSucceeded(activity))) {
            subscriber.onError(new RuntimeException(""));
            return;
        }
        ProcessUtil.sendTerminalUsageHistory(commonBean.toMap(), activity);
        subscriber.onSuccess(true);
        LogUtil.d(selectedList.toString());

        if (adapter != null) {
            for (int i = 0; i < adapter.getCount(); i++) {
                Map<String, String> historyItems = (Map<String, String>) adapter.getItem(i);
                if ("true".equals(historyItems.get("historySelected"))) {
                    historyItems.put("historySelected", "false");
                    historyItems.put("historySaved",
                            activity.getString(R.string.history_list_already_saved));
                }
            }
        }
    } catch (Exception e) {
        LogUtil.e(e);
        subscriber.onError(e);
    }
}

private void controlUploadButtonWithDialog(boolean hasItemSelected) {
    ListView listView = (ListView) activity.findViewById(R.id.historyListView);
    if (hasItemSelected) {
        activity.genAlertDialog(activity.getString(
                R.string.diagnosis_result_upload_success_message),
                (dialog, which) -> {});
        if (listView != null) {
            for (int i = 0; i < listView.getChildCount(); i++) {
                CheckBox checkBox = (CheckBox) listView.getChildAt(i)
                        .findViewById(R.id.historySelected);
                if (checkBox.isChecked()) {
                    checkBox.setChecked(false);
                    checkBox.setEnabled(false);
                    TextView saved = (TextView) listView.getChildAt(i)
                            .findViewById(R.id.historySaved);
                    saved.setText(activity.getString(R.string.history_list_already_saved));
                    saved.setTextColor(Color.GRAY);
                }
            }
        }
    } else {
        activity.genAlertDialog(activity.getString(R.string.history_nothing_checked),
                (dialog, which) -> {});
    }
    uploadButtonEnable(false);
}

private void showUploadFailureDialog(Throwable e) {
    uploadButtonEnable(true);
    LogUtil.e(checkStr(e.getMessage()), e);
    activity.genAlertDialog(activity.getString(
            R.string.diagnosis_result_upload_failure_message)
                    + "\n" + e.getMessage(),
            (dialog, which) -> {});
}

public void uploadButtonEnable(boolean enable) {
    uploadButton.setEnabled(enable);
    if (enable) {
        uploadButton.getBackground().setColorFilter(null);
    } else {
        uploadButton.getBackground()
                .setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
    }
}
```


text:
package com.microsoft.xrm.sdk.Messages;

import com.microsoft.xrm.sdk.OrganizationRequest;

import java.util.UUID;

public final class LockInvoicePricingRequest extends OrganizationRequest {

    public LockInvoicePricingRequest() {
        this.setResponseType(new LockInvoicePricingResponse());
        this.setRequestName("LockInvoicePricing");
    }

    public UUID getInvoiceId() {
        if (this.getParameters().containsKey("InvoiceId")) {
            return (UUID) this.getParameters().get("InvoiceId");
        }

        return new UUID(0L, 0L);
    }

    public void setInvoiceId(UUID value) {
        this.set("InvoiceId", value);
    }

    @Override
    public String getRequestBody() {
        this.set("InvoiceId", getInvoiceId());
        return getSoapBody();
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <title>Sign In | Bootstrap Based Admin Template - Material Design</title>

    <link rel="icon" href="../bower_components/favicon.ico" type="image/x-icon">

    <link href="https://fonts.googleapis.com/css?family=Roboto:400,700&subset=latin,cyrillic-ext" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" type="text/css">

    <link href="<?php echo e(asset('/bower_components/adminbsb-materialdesign/plugins/bootstrap/css/bootstrap.css')); ?>" rel="stylesheet">

    <link href="<?php echo e(asset('/bower_components/adminbsb-materialdesign/plugins/node-waves/waves.css')); ?>" rel="stylesheet">

    <link href="<?php echo e(asset('/bower_components/adminbsb-materialdesign/plugins/animate-css/animate.css')); ?>" rel="stylesheet">

    <link href="<?php echo e(asset('/bower_components/adminbsb-materialdesign/css/style.css')); ?>" rel="stylesheet">

        Gestor de TESTS

            <form id="sign_in" method="POST">

Iniciar Sesión

                            person

                        <input type="text" class="form-control" name="username" placeholder="Email" required autofocus>

                            lock

                        <input type="password" class="form-control" name="password" placeholder="Contraseña" required>

                        <input type="checkbox" name="rememberme" id="rememberme" class="filled-in chk-col-pink">
                        Recuérdame

                        <button class="btn btn-block bg-pink waves-effect" type="submit">ENTRAR</button>

                        ¡Regístrate!

                        Recordar Contraseña

            </form>


text:
module ActiveImport
  VERSION = "0.1.7"
end


text:
MongoDB\Driver\ReadPreference::getMode()
--SKIPIF--
<?php require __DIR__ . "/../utils/basic-skipif.inc"?>
--FILE--
<?php
require_once __DIR__ . "/../utils/basic.inc";

$tests = array(
    MongoDB\Driver\ReadPreference::RP_PRIMARY,
    MongoDB\Driver\ReadPreference::RP_PRIMARY_PREFERRED,
    MongoDB\Driver\ReadPreference::RP_SECONDARY,
    MongoDB\Driver\ReadPreference::RP_SECONDARY_PREFERRED,
    MongoDB\Driver\ReadPreference::RP_NEAREST,
);

foreach ($tests as $test) {
    $rp = new MongoDB\Driver\ReadPreference($test);
    var_dump($rp->getMode());
}

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
int(1)
int(5)
int(2)
int(6)
int(10)
===DONE===


text:
package com.company;

public class Grupo {

    private String codigo;

    private Alumno[] alumnos = new Alumno[5];

    public Grupo() {

        for (int i = 0; i < 5; i++) {
            alumnos[i] = new Alumno();

        }
    }

    public String getCodigo() {
        return codigo;
    }

    public void setCodigo(String codigo) {
        this.codigo = codigo;
    }

    public Alumno[] getAlumnos() {
        return alumnos;
    }

    public void setAlumnos(Alumno[] alumnos) {
        this.alumnos = alumnos;
    }
}