text:
package tw.gov.epa.taqmpredict.util;

import android.Manifest;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.nobrain.android.permissions.AndroidPermissions;
import com.nobrain.android.permissions.Checker;

import tw.gov.epa.taqmpredict.MainActivity;

/**
 * Created by user on 2017/2/6.
 */

public class PermissionsManager {
    private static final String TAG = PermissionsManager.class.getSimpleName();

    public static final int REQUEST_CODE = 102;

    public static void checkPermission(MainActivity activity){
        AndroidPermissions.check(activity)
                .permissions(Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_NETWORK_STATE)
                .hasPermissions(new Checker.Action0() {
                    @Override
                    public void call(String[] permissions) {
                        String msg = "Permission has " + permissions[0];
                        Log.d(TAG, msg);
//                        Toast.makeText(activity,
//                                msg,
//                                Toast.LENGTH_SHORT).show();
                    }
                })
                .noPermissions(new Checker.Action1() {
                    @Override
                    public void call(String[] permissions) {
                        String msg = "Permission has no " + permissions[0];
                        Log.d(TAG, msg);
//                        Toast.makeText(activity,
//                                msg,
//                                Toast.LENGTH_SHORT).show();

                        ActivityCompat.requestPermissions(activity
                                , new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                                        Manifest.permission.ACCESS_COARSE_LOCATION,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                        Manifest.permission.ACCESS_NETWORK_STATE}
                                , REQUEST_CODE);
                    }
                })
                .check();

    }
}


text:
package nl.yacht.lakesideresort.controller;

import nl.yacht.lakesideresort.domain.Room;
import nl.yacht.lakesideresort.manager.RoomManager;
import nl.yacht.lakesideresort.repository.RoomRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import java.time.LocalDate;

import static org.junit.Assert.*;
import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@RunWith(SpringRunner.class)
@WebMvcTest(RoomController.class)
public class RoomControllerTest {

	@Autowired
	private MockMvc mockMvc;

	@MockBean
	private RoomManager roomManager;

	@MockBean
	private SimpMessagingTemplate simpMessagingTemplate;

	@Test
	public void getRooms() throws Exception {
		mockMvc.perform(get("/api/room"))
			.andExpect(status().isOk());
	}

	@Test
	public void findRoomByRoomNumber() throws Exception {
		mockMvc.perform(get("/api/room/search/42"))
			.andExpect(status().isOk());
	}

	@Test
	public void getSingleRoom() throws Exception {
		mockMvc.perform(get("/api/room/42"))
				.andExpect(status().isOk());
	}

	@Test
	public void insertRoom() throws Exception {
		mockMvc.perform(post("/api/room/")
				.contentType(MediaType.APPLICATION_JSON)
				.content("{\"roomNumber\":99,\"roomSize\":\"ONE_PERSON\",\"roomType\":\"BUDGET\",\"availableFrom\":\"2017-02-03\"}"))
				.andExpect(status().isOk());
	}

	@Test
	public void changeRoom() throws Exception {
		mockMvc.perform(put("/api/room/42")
				.contentType(MediaType.APPLICATION_JSON)
				.content("{\"roomNumber\":99,\"roomSize\":\"ONE_PERSON\",\"roomType\":\"BUDGET\",\"availableFrom\":\"2017-02-03\"}"))
				.andExpect(status().isOk());
	}

	@Test
	public void deleteRoom() throws Exception {
		mockMvc.perform(delete("/api/room/42"))
				.andExpect(status().isOk());
	}

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE ui:UiBinder SYSTEM "http://dl.google.com/gwt/DTD/xhtml.ent">
<ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	xmlns:g="urn:import:com.google.gwt.user.client.ui"
	xmlns:b="urn:import:org.gwtbootstrap3.client.ui"
	xmlns:bh="urn:import:org.gwtbootstrap3.client.ui.html"
	xmlns:t="urn:import:org.sagebionetworks.web.client.view.bootstrap.table"
	xmlns:bd="urn:import:org.gwtbootstrap3.extras.datetimepicker.client.ui">
	<bh:Div>
		<bh:Div addStyleNames="pageHeader">
			<b:Heading addStyleNames="pageHeaderTitle" size="H3" text="Review Current Access" />
		</bh:Div>
		<b:NavPills
			addStyleNames="margin-left-35 margin-right-10 margin-top-5">
			<b:AnchorListItem text="ACT data access dashboard"
				href="#!ACTDataAccessSubmissionDashboard:default" />
		</b:NavPills>
		<bh:Div ui:field="showHideAccessRequirementButtonContainer"
			pull="RIGHT" addStyleNames="moveup-35 margin-right-10" />
		<bh:Div ui:field="synAlertContainer" />
		<b:Panel ui:field="accessRequirementUI"
			addStyleNames="margin-left-35 margin-right-10 light-border padding-10">
			<bh:Div ui:field="accessRequirementContainer" />
		</b:Panel>
		<b:Button ui:field="clearAccessRequirementFilter"
			type="PRIMARY" addStyleNames="margin-left-35" size="EXTRA_SMALL"
			icon="SEARCH">Expand search to all Access Requirements</b:Button>
		<bh:Div
			addStyleNames="margin-top-30 margin-left-35 min-height-400 margin-right-10">
			<b:Row>
				<b:Column size="SM_4">
					<b:Panel
						addStyleNames="margin-left-10 margin-right-10 margin-bottom-20">
						<b:PanelHeader>
							<b:Heading size="H3" text="Submitter Filter" />
							<bh:Div ui:field="currentSubmitterContainer" />
							<b:Button ui:field="clearSubmitterFilter" icon="TIMES" marginRight="25"
								addStyleNames="top-right" size="EXTRA_SMALL" />
						</b:PanelHeader>
						<b:PanelBody>
							<bh:Div ui:field="submitterSelectContainer" />
						</b:PanelBody>
					</b:Panel>
				</b:Column>
				<b:Column size="SM_4" ui:field="accessorUI">
					<b:Panel
						addStyleNames="margin-left-10 margin-right-10 margin-bottom-20">
						<b:PanelHeader>
							<b:Heading size="H3" text="Accessor Filter" />
							<bh:Div ui:field="currentAccessorContainer" />
							<b:Button ui:field="clearAccessorFilter" icon="TIMES" marginRight="25"
								addStyleNames="top-right" size="EXTRA_SMALL" />
						</b:PanelHeader>
						<b:PanelBody>
							<bh:Div ui:field="accessorSelectContainer" />
						</b:PanelBody>
					</b:Panel>
				</b:Column>
				<b:Column size="SM_4">
					<b:Panel
						addStyleNames="margin-left-10 margin-right-10 margin-bottom-20">
						<b:PanelHeader>
							<b:Heading size="H3" text="Expires..." />
							<b:Button ui:field="clearDateFilter" icon="TIMES" marginRight="25"
								addStyleNames="top-right" size="EXTRA_SMALL" />
						</b:PanelHeader>
						<b:PanelBody>
							<b:FormLabel>before</b:FormLabel>
							<bd:DateTimePicker
								ui:field="expiresBeforeDatePicker" autoClose="true"
								highlightToday="true" showTodayButton="true" showMeridian="false"
								format="mm/dd/yyyy hh:ii:ss" minView="MONTH"
								hasKeyboardNavigation="false" />
						</b:PanelBody>
					</b:Panel>
				</b:Column>
			</b:Row>
			<b:Button ui:field="exportButton"
				text="Export CSV" size="EXTRA_SMALL" pull="RIGHT" marginRight="30"/>
			<b:Anchor ui:field="downloadLink" text="Download CSV" marginRight="30"
				visible="false" icon="DOWNLOAD" pull="RIGHT" />
			<bh:Hr />
			<bh:Div marginLeft="5" marginRight="5">
				<!-- table header -->
				<t:Table
					addStyleNames="table-layout-fixed margin-bottom-20"
					width="100%">
					<t:TableRow>
						<!-- action column (revoke) -->
						<t:TableHeader width="100px" />
						<t:TableHeader width="40%">
							<bh:Span text="Submitted By" />
						</t:TableHeader>
						<t:TableHeader width="40%">
							<!-- list of accessor badge -->
							<bh:Span text="Accessors" />
						</t:TableHeader>
						<t:TableHeader width="175px">
							<bh:Span text="Expires On" />
						</t:TableHeader>
						<t:TableHeader width="200px">
							<!-- easy way to copy all (synapse.org) email addresses -->
							<bh:Span text="Email" />
						</t:TableHeader>
						<t:TableHeader width="80px" addStyleNames="text-align-center">
							<bh:Span text="Menu" />
						</t:TableHeader>
					</t:TableRow>
				</t:Table>
				<bh:Div ui:field="tableData" addStyleNames="margin-bottom-20" />
			</bh:Div>
		</bh:Div>
		<bh:Div addStyleNames="clear" />
	</bh:Div>
</ui:UiBinder>


text:
A repository containing support code and resources from the [Institute for Medical Informatics, Statistics and Documentation at the Medical University of Graz (Austria)](https://www.medunigraz.at/imi/en/) participation at the [2017 TREC Precision Medicine / Clinical Decision Support Track](http://trec-cds.appspot.com/2017.html). For further information on this track and the final results please check the official [TREC-PM 2017 overview paper](https://trec.nist.gov/pubs/trec26/papers/Overview-PM.pdf). Team name: **imi_mug**

If you use data or code in your work, please cite our [TREC 2017 proceedings paper](https://trec.nist.gov/pubs/trec26/papers/imi_mug-PM.pdf):

*TREC 2017 Precision Medicine - Medical University of Graz. Pablo López-García, Michel Oleynik, Zdenko Kasáč and Stefan Schulz. Text REtrieval Conference, Gaithersburg, MD. 2017. Available at https://trec.nist.gov/pubs/trec26/papers/imi_mug-PM.pdf.*

The complete TREC 2017 proceedings are available [here](https://trec.nist.gov/pubs/trec26/trec2017.html).

Also of interest:

* [Our TREC 2017 presentation slides](https://github.com/bst-mug/trec2017/blob/master/docs/presentation.pdf)
* [Our TREC 2017 Poster](https://github.com/bst-mug/trec2017/blob/master/docs/poster.pdf)

## Code Dependencies

- JDK 8+
- maven
- make (for `trec_eval` tool)
- gcc (for `trec_eval` tool)
- Elasticsearch 5.4.0+

[![Build Status](https://travis-ci.org/bst-mug/trec2017.svg?branch=master)](https://travis-ci.org/bst-mug/trec2017)
[![Coverage Status](https://coveralls.io/repos/github/bst-mug/trec2017/badge.svg?branch=master)](https://coveralls.io/github/bst-mug/trec2017?branch=master)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Oobe user image screen implementation.
 */

cr.define('login', function() {
  var UserImagesGrid = options.UserImagesGrid;
  var ButtonImages = UserImagesGrid.ButtonImages;

  /**
   * Array of button URLs used on this page.
   * @type {Array.<string>}
   * @const
   */
  var ButtonImageUrls = [
    ButtonImages.TAKE_PHOTO
  ];

  /**
   * Whether the web camera item should be preselected, if available.
   * @type {boolean}
   * @const
   */
  var PRESELECT_CAMERA = false;

  /**
   * Creates a new OOBE screen div.
   * @constructor
   * @extends {HTMLDivElement}
   */
  var UserImageScreen = cr.ui.define(login.Screen);

  /**
   * Registers with Oobe.
   * @param {boolean} lazyInit If true, screen is decorated on first show.
   */
  UserImageScreen.register = function(lazyInit) {
    var screen = $('user-image');
    if (lazyInit) {
      screen.__proto__ = UserImageScreen.prototype;
      screen.deferredDecorate = function() {
        UserImageScreen.decorate(screen);
      };
    } else {
      UserImageScreen.decorate(screen);
    }
    Oobe.getInstance().registerScreen(screen);
  };

  UserImageScreen.prototype = {
    __proto__: login.Screen.prototype,

    /**
     * Currently selected user image index (take photo button is with zero
     * index).
     * @type {number}
     */
    selectedUserImage_: -1,

    /**
     * URL for profile picture.
     */
    profileImageUrl_: null,

    /** @override */
    decorate: function(element) {
      var imageGrid = $('user-image-grid');
      UserImagesGrid.decorate(imageGrid);

      // Preview image will track the selected item's URL.
      var previewElement = $('user-image-preview');
      previewElement.oncontextmenu = function(e) { e.preventDefault(); };

      imageGrid.previewElement = previewElement;
      imageGrid.selectionType = 'default';
      imageGrid.flipPhotoElement = $('flip-photo');

      imageGrid.addEventListener('select',
                                 this.handleSelect_.bind(this));
      imageGrid.addEventListener('activate',
                                 this.handleImageActivated_.bind(this));
      imageGrid.addEventListener('phototaken',
                                 this.handlePhotoTaken_.bind(this));
      imageGrid.addEventListener('photoupdated',
                                 this.handlePhotoUpdated_.bind(this));

      // Set the title for camera item in the grid.
      imageGrid.setCameraTitles(
          loadTimeData.getString('takePhoto'),
          loadTimeData.getString('photoFromCamera'));

      this.profileImageLoading = true;

      // Profile image data (if present).
      this.profileImage_ = imageGrid.addItem(
          ButtonImages.PROFILE_PICTURE,           // Image URL.
          loadTimeData.getString('profilePhoto'), // Title.
          undefined,                              // Click handler.
          0,                                      // Position.
          function(el) {
            // Custom decorator for Profile image element.
            var spinner = el.ownerDocument.createElement('div');
            spinner.className = 'spinner';
            var spinnerBg = el.ownerDocument.createElement('div');
            spinnerBg.className = 'spinner-bg';
            spinnerBg.appendChild(spinner);
            el.appendChild(spinnerBg);
            el.id = 'profile-image';
          });
      this.profileImage_.type = 'profile';

      $('take-photo').addEventListener(
          'click', this.handleTakePhoto_.bind(this));
      $('discard-photo').addEventListener(
          'click', this.handleDiscardPhoto_.bind(this));

      // Toggle 'animation' class for the duration of WebKit transition.
      $('flip-photo').addEventListener(
          'click', this.handleFlipPhoto_.bind(this));
      $('user-image-stream-crop').addEventListener(
          'webkitTransitionEnd', function(e) {
            previewElement.classList.remove('animation');
          });
      $('user-image-preview-img').addEventListener(
          'webkitTransitionEnd', function(e) {
            previewElement.classList.remove('animation');
          });

      this.updateLocalizedContent();

      chrome.send('getImages');
    },

    /**
     * Header text of the screen.
     * @type {string}
     */
    get header() {
      return loadTimeData.getString('userImageScreenTitle');
    },

    /**
     * Buttons in oobe wizard's button strip.
     * @type {array} Array of Buttons.
     */
    get buttons() {
      var okButton = this.ownerDocument.createElement('button');
      okButton.id = 'ok-button';
      okButton.textContent = loadTimeData.getString('okButtonText');
      okButton.addEventListener('click', this.acceptImage_.bind(this));
      return [okButton];
    },

    /**
     * The caption to use for the Profile image preview.
     * @type {string}
     */
    get profileImageCaption() {
      return this.profileImageCaption_;
    },
    set profileImageCaption(value) {
      this.profileImageCaption_ = value;
      this.updateCaption_();
    },

    /**
     * True if the Profile image is being loaded.
     * @type {boolean}
     */
    get profileImageLoading() {
      return this.profileImageLoading_;
    },
    set profileImageLoading(value) {
      this.profileImageLoading_ = value;
      $('user-image-screen-main').classList.toggle('profile-image-loading',
                                                   value);
      if (value)
        announceAccessibleMessage(loadTimeData.getString('syncingPreferences'));
      this.updateProfileImageCaption_();
    },

    /**
     * Handles image activation (by pressing Enter).
     * @private
     */
    handleImageActivated_: function() {
      switch ($('user-image-grid').selectedItemUrl) {
        case ButtonImages.TAKE_PHOTO:
          this.handleTakePhoto_();
          break;
        default:
          this.acceptImage_();
          break;
      }
    },

    /**
     * Handles selection change.
     * @param {Event} e Selection change event.
     * @private
     */
    handleSelect_: function(e) {
      var imageGrid = $('user-image-grid');
      $('ok-button').disabled = false;

      // Camera selection
      if (imageGrid.selectionType == 'camera') {
        $('flip-photo').tabIndex = 1;
        // No current image selected.
        if (imageGrid.cameraLive) {
          imageGrid.previewElement.classList.remove('phototaken');
          $('ok-button').disabled = true;
        } else {
          imageGrid.previewElement.classList.add('phototaken');
          this.notifyImageSelected_();
        }
      } else {
        imageGrid.previewElement.classList.remove('phototaken');
        $('flip-photo').tabIndex = -1;
        this.notifyImageSelected_();
      }
      // Start/stop camera on (de)selection.
      if (!imageGrid.inProgramSelection &&
          imageGrid.selectionType != e.oldSelectionType) {
        if (imageGrid.selectionType == 'camera') {
          // Programmatic selection of camera item is done in
          // startCamera callback where streaming is started by itself.
          imageGrid.startCamera(
              function() {
                // Start capture if camera is still the selected item.
                $('user-image-preview-img').classList.toggle(
                    'animated-transform', true);
                return imageGrid.selectedItem == imageGrid.cameraImage;
              });
        } else {
          $('user-image-preview-img').classList.toggle('animated-transform',
                                                       false);
          imageGrid.stopCamera();
        }
      }
      this.updateCaption_();
      // Update image attribution text.
      var image = imageGrid.selectedItem;
      $('user-image-author-name').textContent = image.author;
      $('user-image-author-website').textContent = image.website;
      $('user-image-author-website').href = image.website;
      $('user-image-attribution').style.visibility =
          (image.author || image.website) ? 'visible' : 'hidden';
    },

    /**
     * Handle camera-photo flip.
     */
    handleFlipPhoto_: function() {
      var imageGrid = $('user-image-grid');
      imageGrid.previewElement.classList.add('animation');
      imageGrid.flipPhoto = !imageGrid.flipPhoto;
      var flipMessageId = imageGrid.flipPhoto ?
         'photoFlippedAccessibleText' : 'photoFlippedBackAccessibleText';
      announceAccessibleMessage(loadTimeData.getString(flipMessageId));
    },

    /**
     * Handle photo capture from the live camera stream.
     */
    handleTakePhoto_: function(e) {
      $('user-image-grid').takePhoto();
      chrome.send('takePhoto');
    },

    /**
     * Handle photo captured event.
     * @param {Event} e Event with 'dataURL' property containing a data URL.
     */
    handlePhotoTaken_: function(e) {
      chrome.send('photoTaken', [e.dataURL]);
      announceAccessibleMessage(
          loadTimeData.getString('photoCaptureAccessibleText'));
    },

    /**
     * Handle photo updated event.
     * @param {Event} e Event with 'dataURL' property containing a data URL.
     */
    handlePhotoUpdated_: function(e) {
      chrome.send('photoTaken', [e.dataURL]);
    },

    /**
     * Handle discarding the captured photo.
     */
    handleDiscardPhoto_: function(e) {
      var imageGrid = $('user-image-grid');
      imageGrid.discardPhoto();
      chrome.send('discardPhoto');
      announceAccessibleMessage(
          loadTimeData.getString('photoDiscardAccessibleText'));
    },

    /**
     * Event handler that is invoked just before the screen is shown.
     * @param {object} data Screen init payload.
     */
    onBeforeShow: function(data) {
      Oobe.getInstance().headerHidden = true;
      var imageGrid = $('user-image-grid');
      imageGrid.updateAndFocus();
      chrome.send('onUserImageScreenShown');
    },

    /**
     * Event handler that is invoked just before the screen is hidden.
     */
    onBeforeHide: function() {
      $('user-image-grid').stopCamera();
    },

    /**
     * Accepts currently selected image, if possible.
     * @private
     */
    acceptImage_: function() {
      var okButton = $('ok-button');
      if (!okButton.disabled) {
        // This ensures that #ok-button won't be re-enabled again.
        $('user-image-grid').disabled = true;
        okButton.disabled = true;
        chrome.send('onUserImageAccepted');
      }
    },

    /**
     * Updates user profile image.
     * @param {?string} imageUrl Image encoded as data URL. If null, user has
     *     the default profile image, which we don't want to show.
     * @private
     */
    setProfileImage_: function(imageUrl) {
      this.profileImageLoading = false;
      this.profileImageUrl_ = imageUrl;
      if (imageUrl !== null) {
        this.profileImage_ =
            $('user-image-grid').updateItem(this.profileImage_, imageUrl);
      }
    },

    /**
     * @param {boolean} present Whether camera is detected.
     */
    setCameraPresent_: function(present) {
      $('user-image-grid').cameraPresent = present;
    },

    /**
     * Controls the profile image as one of image options.
     * @param {enabled} Whether profile image option should be displayed.
     * @private
     */
    setProfilePictureEnabled_: function(enabled) {
      var imageGrid = $('user-image-grid');
      if (enabled) {
      } else {
        imageGrid.removeItem(this.profileImage_);
      }
    },

    /**
     * Appends default images to the image grid. Should only be called once.
     * @param {Array.<{url: string, author: string, website: string}>} images
     *   An array of default images data, including URL, author and website.
     * @private
     */
    setDefaultImages_: function(imagesData) {
      var imageGrid = $('user-image-grid');
      for (var i = 0, data; data = imagesData[i]; i++) {
        var item = imageGrid.addItem(data.url, data.title);
        item.type = 'default';
        item.author = data.author || '';
        item.website = data.website || '';
      }
      chrome.send('screenReady');
    },

    /**
     * Selects user image with the given URL.
     * @param {string} url URL of the image to select.
     * @private
     */
    setSelectedImage_: function(url) {
      var imageGrid = $('user-image-grid');
      imageGrid.selectedItemUrl = url;
      imageGrid.focus();
    },

    /**
     * Hides curtain with spinner.
     * @private
     */
    hideCurtain_: function() {
      this.classList.remove('loading');
      Oobe.getInstance().updateScreenSize(this);
    },

    /**
     * Updates the image preview caption.
     * @private
     */
    updateCaption_: function() {
      $('user-image-preview-caption').textContent =
          $('user-image-grid').selectionType == 'profile' ?
          this.profileImageCaption : '';
    },

    /**
     * Updates localized content of the screen that is not updated via template.
     */
    updateLocalizedContent: function() {
      this.updateProfileImageCaption_();
    },

    /**
     * Updates profile image caption.
     * @private
     */
    updateProfileImageCaption_: function() {
      this.profileImageCaption = loadTimeData.getString(
        this.profileImageLoading_ ? 'profilePhotoLoading' : 'profilePhoto');
    },

    /**
     * Notifies chrome about image selection.
     * @private
     */
    notifyImageSelected_: function() {
      var imageGrid = $('user-image-grid');
      chrome.send('selectImage',
                  [imageGrid.selectedItemUrl,
                   imageGrid.selectionType,
                   !imageGrid.inProgramSelection]);
    },
  };

  // Forward public APIs to private implementations.
  [
    'setDefaultImages',
    'setCameraPresent',
    'setProfilePictureEnabled',
    'setProfileImage',
    'setSelectedImage',
    'hideCurtain'
  ].forEach(function(name) {
    UserImageScreen[name] = function(value) {
      $('user-image')[name + '_'](value);
    };
  });

  return {
    UserImageScreen: UserImageScreen
  };
});


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project

     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.
-->

<ripple xmlns:android="http://schemas.android.com/apk/res/android"
     android:color="#ff9cdfd9">
     <item>
          <shape android:shape="oval">
               <solid android:color="#9cc8c4" />
               <size android:width="@dimen/recents_lock_to_app_size"
                     android:height="@dimen/recents_lock_to_app_size" />
          </shape>
     </item>
</ripple>


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/C:/Users/LENOVO/Documents/GitHub/GoGame/GoGame/src/gtp/gogame/ConstBoard.java</file>
            <file>file:/C:/Users/LENOVO/Documents/GitHub/GoGame/GoGame/src/mundo/gogame/Tablero.java</file>
            <file>file:/C:/Users/LENOVO/Documents/GitHub/GoGame/GoGame/src/gtp/gogame/GtpSynchronizer.java</file>
            <file>file:/C:/Users/LENOVO/Documents/GitHub/GoGame/GoGame/src/gtp/gogame/Board.java</file>
        </group>
    </open-files>
</project-private>


text:
/* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef MOZILLA_LAYERS_BLOBYCBCRSURFACE_H
#define MOZILLA_LAYERS_BLOBYCBCRSURFACE_H

#include <stddef.h>                     // for size_t
#include <stdint.h>                     // for uint8_t, uint32_t
#include "ImageTypes.h"                 // for StereoMode
#include "mozilla/Attributes.h"         // for MOZ_STACK_CLASS
#include "mozilla/RefPtr.h"             // for TemporaryRef
#include "mozilla/gfx/Point.h"          // for IntSize

namespace mozilla {
namespace gfx {
class DataSourceSurface;
}

namespace layers {

class Image;

/**
 * Convenience class to share code between YCbCrImageDataSerializer
 * and YCbCrImageDataDeserializer.
 * Do not use it.
 */
class YCbCrImageDataDeserializerBase
{
public:
  bool IsValid() const { return mIsValid; }

  /**
   * Returns the Y channel data pointer.
   */
  uint8_t* GetYData();
  /**
   * Returns the Cb channel data pointer.
   */
  uint8_t* GetCbData();
  /**
   * Returns the Cr channel data pointer.
   */
  uint8_t* GetCrData();

  /**
   * Returns the Y channel stride.
   */
  uint32_t GetYStride();
  /**
   * Returns the stride of the Cb and Cr channels.
   */
  uint32_t GetCbCrStride();

  /**
   * Returns the dimensions of the Y Channel.
   */
  gfx::IntSize GetYSize();

  /**
   * Returns the dimensions of the Cb and Cr Channel.
   */
  gfx::IntSize GetCbCrSize();

  /**
   * Stereo mode for the image.
   */
  StereoMode GetStereoMode();

  /**
   * Return a pointer to the begining of the data buffer.
   */
  uint8_t* GetData();

  /**
   * This function is meant as a helper to know how much shared memory we need
   * to allocate in a shmem in order to place a shared YCbCr image blob of
   * given dimensions.
   */
  static size_t ComputeMinBufferSize(const gfx::IntSize& aYSize,
                                     uint32_t aYStride,
                                     const gfx::IntSize& aCbCrSize,
                                     uint32_t aCbCrStride);
  static size_t ComputeMinBufferSize(const gfx::IntSize& aYSize,
                                     const gfx::IntSize& aCbCrSize);
  static size_t ComputeMinBufferSize(uint32_t aSize);

protected:
  YCbCrImageDataDeserializerBase(uint8_t* aData, size_t aDataSize)
    : mData (aData)
    , mDataSize(aDataSize)
    , mIsValid(false)
  {}

  void Validate();

  uint8_t* mData;
  size_t mDataSize;
  bool mIsValid;
};

/**
 * A view on a YCbCr image stored with its metadata in a blob of memory.
 * It is only meant as a convenience to access the image data, and does not own
 * the data. The instance can live on the stack and used as follows:
 *
 * const YCbCrImage& yuv = sharedImage.get_YCbCrImage();
 * YCbCrImageDataDeserializer deserializer(yuv.data().get<uint8_t>());
 * if (!deserializer.IsValid()) {
 *   // handle error
 * }
 * size = deserializer.GetYSize(); // work with the data, etc...
 */
class MOZ_STACK_CLASS YCbCrImageDataSerializer : public YCbCrImageDataDeserializerBase
{
public:
  YCbCrImageDataSerializer(uint8_t* aData, size_t aDataSize)
    : YCbCrImageDataDeserializerBase(aData, aDataSize)
  {
    // a serializer needs to be usable before correct buffer info has been written to it
    mIsValid = !!mData;
  }

  /**
   * Write the image informations in the buffer for given dimensions.
   * The provided pointer should point to the beginning of the (chunk of)
   * buffer on which we want to store the image.
   */
  void InitializeBufferInfo(uint32_t aYOffset,
                            uint32_t aCbOffset,
                            uint32_t aCrOffset,
                            uint32_t aYStride,
                            uint32_t aCbCrStride,
                            const gfx::IntSize& aYSize,
                            const gfx::IntSize& aCbCrSize,
                            StereoMode aStereoMode);
  void InitializeBufferInfo(uint32_t aYStride,
                            uint32_t aCbCrStride,
                            const gfx::IntSize& aYSize,
                            const gfx::IntSize& aCbCrSize,
                            StereoMode aStereoMode);
  void InitializeBufferInfo(const gfx::IntSize& aYSize,
                            const gfx::IntSize& aCbCrSize,
                            StereoMode aStereoMode);
  bool CopyData(const uint8_t* aYData,
                const uint8_t* aCbData, const uint8_t* aCrData,
                gfx::IntSize aYSize, uint32_t aYStride,
                gfx::IntSize aCbCrSize, uint32_t aCbCrStride,
                uint32_t aYSkip, uint32_t aCbCrSkip);
};

/**
 * A view on a YCbCr image stored with its metadata in a blob of memory.
 * It is only meant as a convenience to access the image data, and does not own
 * the data. The instance can live on the stack and used as follows:
 *
 * const YCbCrImage& yuv = sharedImage.get_YCbCrImage();
 * YCbCrImageDataDeserializer deserializer(yuv.data().get<uint8_t>());
 * if (!deserializer.IsValid()) {
 *   // handle error
 * }
 * size = deserializer.GetYSize(); // work with the data, etc...
 */
class MOZ_STACK_CLASS YCbCrImageDataDeserializer : public YCbCrImageDataDeserializerBase
{
public:
  YCbCrImageDataDeserializer(uint8_t* aData, size_t aDataSize)
    : YCbCrImageDataDeserializerBase(aData, aDataSize)
  {
    Validate();
  }

  /**
   * Convert the YCbCr data into RGB and return a DataSourceSurface.
   * This is a costly operation, so use it only when YCbCr compositing is
   * not supported.
   */
  TemporaryRef<gfx::DataSourceSurface> ToDataSourceSurface();
};

} // namespace
} // namespace

#endif


text:
layout:     post
title:      "在mac上运行docker"
subtitle:   "run docker on mac osx"
date:       2016-03-08 22:00:00
author:     "Kaelzhang"
header-img: "img/post-bg-unix-linux.jpg"
catalog:    true
tags:
    - docker
    - mac
---

![img](/img/header/mac docker.png)

>Build, Ship and Run Any App, Anywhere!

## 安装Docker
1.到https://www.docker.com/products/docker-toolbox下载docker toolbox
2.安装toolbox

Click the installer link to download.

Install Docker Toolbox by double-clicking the package or by right-clicking and choosing "Open" from the pop-up menu.

The installer launches the "Install Docker Toolbox" dialog.

## 运行Docker
在Spotlight中启动Docker Quickstart Terminal,执行Docker

## 访问私有registry
1.启动
在bash上执行:
>docker-machine ssh

进入虚拟机,并编辑/var/lib/boot2docker/profile文件,增加EXTRA_ARGS:
>EXTRA_ARGS="--insecure-registry 10.86.56.126:5000"

xxxxxx为ip或registry名字docker-registry.com.intra,如果是registry名记得在hosts内加上名字映射。

##### 参考资料:

1.https://github.com/docker


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Analyser</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <link rel="icon" type="image/png" sizes="174x174" href="./style/favicon.png">


text:
using Newtonsoft.Json;
using System.Collections.Generic;

namespace Bitlet.Coinbase.Models
{
    public class ApplicationsPage : RecordsPage
    {
        [JsonProperty("applications")]
        public IList<ApplicationResponse> Applications { get; set; }
    }
}


text:
name             'boxstarter'
maintainer       'Matt Wrock'
maintainer_email 'matt@mattwrock.com'
license          'Apache 2.0'
description      'Executes Chocolatey packages, windows updates, provides several windows configuration commands and can run any adhoc powershell in a reboot resilient context'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          '1.1.7'

supports 'windows'


text:
var renderAndroid = function(){
    var public = {
        pageIni: function(){
            if(config.FB){
                var fb = document.createElement('div'),
                    fbIcon = document.createElement('div');
                fb.id = 'floatButton';
                fbIcon.id = 'floatButton-icon';
                fbIcon.innerHTML = '+';
                fb.appendChild(fbIcon);
                body.appendChild(fb);
                tool.touchWP(fb,'touchend',function(){
                    var view = document.createElement('div'),
                        shade = document.createElement('div'),
                        ok;
                    fb.classList.remove('ani-FB-show');
                    fb.classList.add('ani-FB-hide');
                    shade.classList.add('shade');
                    view.classList.add('view');
                    view.innerHTML = '
这个按钮只是一个DEMO,
你可以在设置里关掉它!
请使用带有LocalStorage的浏览器访问本页,
安卓平台推荐使用chrome
好的';
                    shade.appendChild(view);
                    body.appendChild(shade);
                    view.style.marginTop = -tool.renderStyle(view,'height',true)/2 + 'px';
                    view.classList.add('FB-box-show');
                    ok = document.getElementById('view-ok');
                    tool.touchWP(ok,'touchend',function(){
                        body.removeChild(shade);
                        fb.classList.remove('ani-FB-hide');
                        fb.classList.add('ani-FB-show');
                    });
                });
            }else{
                var _fb = document.getElementById('floatButton');
                if(_fb){
                    body.removeChild(_fb);
                    while(true){
                        _fb = document.getElementById('floatButton');
                        if(_fb){
                            body.removeChild(_fb);
                        }
                        else{
                            break;
                        }
                    }
                }
            }
        },
        eventReg: function(){
            tool.touchWP(menu,'touchend',function(){
                var shade = document.createElement('div');
                shade.classList.add('shade');
                body.appendChild(shade);
                aside.classList.remove('ani-aside-hide');
                aside.classList.add('ani-aside-show');
                tool.touchWP(shade,'touchend',function(){
                    aside.classList.remove('ani-aside-show');
                    aside.classList.add('ani-aside-hide');
                    body.removeChild(shade);
                })
            });
            tool.touchWP(article,'touchstart',function(e){
                if (window.navigator.msPointerEnabled){
                    return
                }
                if((document.body.scrollTop === 0)){
                    touchStartY = e.targetTouches[0].pageY;
                }
                else{
                    touchStartY = e.targetTouches[0].pageY - document.body.scrollTop
                }
            },true);
            tool.touchWP(article,'touchmove',function(e){
                if (window.navigator.msPointerEnabled){
                    return
                }
                touchMoveY = e.targetTouches[0].pageY - touchStartY;
                if(document.body.scrollTop === 0){
                    article.style.marginTop = touchMoveY + 'px'
                }
                if(touchMoveY > 56){
                    var reText = document.getElementById('refresh-text'),
                        reImg = document.getElementById('refresh-img');
                    reText.innerHTML = '松开刷新';
                    reImg.src = './.src/img/refresh.png'
                }
                console.log(e.targetTouches[0].pageY - touchStartY + 'px')
            },true);
            tool.touchWP(article,'touchend',function(e){
                if (window.navigator.msPointerEnabled){
                    return
                }
                if(article.style.marginTop){
                    e.stopPropagation();
                }
                if(article.style.marginTop.replace(/px/,'') > 56){
                    ajax.reload();
                    var reText = document.getElementById('refresh-text'),
                        reImg = document.getElementById('refresh-img');
                    reText.innerHTML = '下拉刷新';
                    reImg.src = './.src/img/down.png'
                }
                article.style.marginTop = null;
            },true);
        },
        configLoad: function(){
            var configHide = document.getElementById('config-hide'),
                configFB = document.getElementById('config-FB'),
                configClean = document.getElementById('config-clean'),
                configLoad = document.getElementById('config-load'),
                configList = document.getElementsByClassName('config');

            if(config.hide){
                configHide.checked = 'checked'
            }
            else{
                configHide.checked = ''
            }
            if(config.FB){
                configFB.checked = 'checked'
            }
            else{
                configFB.checked = ''
            }

            function configFBChange(){
                var fb = document.getElementById('floatButton');
                config.FB = configFB.checked;
                localStorage.setItem('config',JSON.stringify(config))
                if(config.FB){
                    renderAndroid.pageIni();
                    fb = document.getElementById('floatButton');
                    fb.classList.remove('ani-FB-hide');
                    fb.classList.add('ani-FB-show');
                }
                else{
                    fb.classList.remove('ani-FB-show');
                    fb.classList.add('ani-FB-hide');
                    setTimeout(function(){
                        renderAndroid.pageIni();
                    },500)
                }
            }

            configHide.addEventListener('change',function(){
                config.hide = configHide.checked;
                localStorage.setItem('config',JSON.stringify(config));
                removeList();
                renderAndroid.dataLoad(pointer);
            });
            configFB.addEventListener('change',tool.deBounce(configFBChange,500));
            tool.touchWP(configClean,'touchend',function(){

                var view = document.createElement('div'),
                    yes ,no;
                view.classList.add('view');
                view.innerHTML = '
您真的要清理本地存储吗?
此操作将不可恢复
确认取消';
                body.appendChild(view);
                view.classList.add('FB-box-show');
                view.style.marginTop = -tool.renderStyle(view,'height',true)/2 + 'px';
                yes = document.getElementById('view-yes');
                no = document.getElementById('view-no');
                tool.touchWP(yes,'touchend',function(e){
                    body.removeChild(view);
                    worker.delLocalStorage();
                },true);
                tool.touchWP(no,'touchend',function(e){
                    body.removeChild(view)
                },true)
            });
            tool.touchWP(configLoad,'touchend',function(){
                ajax.reload();
            });
            for(var i = 0,leng = configList.length;i < leng;i++){
                tool.touchWP(configList[i],'touchstart',function(){
                    this.style.backgroundColor = '#03a9f4'
                });
                tool.touchWP(configList[i],'touchend',function(){
                    this.style.backgroundColor = '#ffffff'
                })
            }
        },
        dataLoad: function(obj){
            var fileList = Object.keys(obj),
                toggle = true;
            function animateClick(e,focus){
                var wave = document.createElement('div'),
                    file = document.getElementsByClassName('file'),
                    waveX, waveY;
                wave.classList.add('wave');
                if(window.navigator.msPointerEnabled){
                    if(focus.id.slice(4) === ''){
                        waveX = e.pageX + 'px';
                        waveY = e.pageY - 56 + 'px';
                    }else{
                        waveX = e.pageX + 'px';
                        if (pointer === src){
                            waveY = e.pageY - (focus.id.slice(4) * 73) - 56 + 'px'
                        }
                        else{
                            waveY = e.pageY - (focus.id.slice(4) * 73) - 129 + 'px'
                        }
                    }
                }
                else{
                    if(focus.id.slice(4) === ''){
                        waveX = e.changedTouches[0].pageX + 'px';
                        waveY = e.changedTouches[0].pageY - 56 + 'px';
                    }else{
                        waveX = e.changedTouches[0].pageX + 'px';
                        if (pointer === src){
                            waveY = e.changedTouches[0].pageY - (focus.id.slice(4) * 73) - 56 + 'px'
                        }
                        else{
                            waveY = e.changedTouches[0].pageY - (focus.id.slice(4) * 73) - 129 + 'px'
                        }
                    }
                }
                wave.style.left = waveX;
                wave.style.top = waveY;
                wave.classList.add('ani-file-click-wave');
                focus.appendChild(wave);
                for(var i = 0;i < file.length;i++){
                    file[i].classList.add('ani-file-hide')
                }
            }
            function createBack(){
                var back = document.createElement('div'),
                    type = document.createElement('div'),
                    text = document.createElement('span');
                back.classList.add('file');
                back.id = 'back';
                type.classList.add('life-type-folder');
                text.classList.add('life-text');
                text.innerHTML = '../';
                back.appendChild(type);
                back.appendChild(text);
                article.appendChild(back);
                setTimeout(function(){
                    back.classList.add('ani-file-show')
                },0);
                tool.touchWP(back,'touchend',function(e){  //注册返回按钮事件
                    animateClick(e,this);
                    tool.cssAniEvent(back,'AnimationEnd',function(){
                        removeList();
                        arrPoint.length = arrPoint.length - 1;
                        if(arrPoint.length === 0){
                            pointer = src
                        }
                        else{
                            var father = 'src';
                            for(var n = 0;n < arrPoint.length;n++){
                                father = father + '["' + arrPoint[n] + '"]'
                            }
                            pointer = eval(father);
                        }
                        renderAndroid.dataLoad(pointer);
                    });
                });
            }
            function createList(list){
                function download(e){
                    e.stopImmediatePropagation();
                    window.open(pointer[this['src']].____src.slice(1));
                }
                for(var i = 0, No = 0;i < list.length;i++){  //生成文件列表以及注册点击事件
                    var div = document.createElement('div'),
                        type = document.createElement('div'),
                        text = document.createElement('span'),
                        maxWidth = tool.renderStyle(article,'width',true) - 98,
                        ext = {
                            folder:[''],
                            text:['txt','text','html','css','js','json','bat','command'],
                            image:['jpg','jpeg','bmp','png','gif','svg'],
                            audio:['mp3','wav','m4a'],
                            video:['mp4','avi'],
                            other:[]
                        },
                        timer;
                    if(list[i].substr(0,4) === '____'){
                        continue
                    }
                    if(!config.hide && list[i][0] === '.'){
                        continue
                    }
                    if(!config.hide && list[i] === 'index.html'){
                        continue
                    }
                    if(!config.hide && list[i] === 'tree.txt'){
                        continue
                    }
                    if(!config.hide && list[i] === 'create-tree.command'){
                        continue
                    }
                    if(!config.hide && list[i] === 'index.haml'){
                        continue
                    }
                    div.classList.add('file');
                    div.id = 'file' + No;
                    No = No + 1;
                    div['src'] = list[i];
                    text.classList.add('life-text');
                    text.innerHTML = list[i];
                    if(tool.mySome(ext.folder,pointer[list[i]].____extension)){
                        type.classList.add('life-type-folder');
                    }
                    else if(tool.mySome(ext.text,pointer[list[i]].____extension)){
                        type.classList.add('life-type-text');
                    }
                    else if(tool.mySome(ext.image,pointer[list[i]].____extension)){
                        type.classList.add('life-type-image');
                    }
                    else if(tool.mySome(ext.audio,pointer[list[i]].____extension)){
                        type.classList.add('life-type-audio');
                    }
                    else if(tool.mySome(ext.video,pointer[list[i]].____extension)){
                        type.classList.add('life-type-video');
                    }
                    else{
                        type.classList.add('life-type-other');
                    }
                    div.appendChild(type);
                    div.appendChild(text);
                    article.appendChild(div);
                    if(tool.renderStyle(text,'width',true) > maxWidth ){
                        text.innerHTML = text.innerHTML.substr(0,~~maxWidth/18) + '...';
                    }
                    setTimeout(function(div){
                        div.classList.add('ani-file-show');
                    },50 + 50 * i,div);
                    tool.touchWP(div,'touchstart',function(e){
                        timer = setTimeout(download.bind(this,e),2000)
                    });
                    tool.touchWP(div,'touchend',function(e){
                        clearTimeout(timer);
                        if(toggle){
                            var target = this['src'];
                            if(pointer[target].____extension === ''){
                                toggle = false;
                                animateClick(e,this);
                                tool.cssAniEvent(this,'AnimationEnd',function(){
                                    removeList();
                                    arrPoint.push(target);
                                    pointer = pointer[target];
                                    renderAndroid.dataLoad(pointer);
                                })
                            }
                            else if(tool.mySome(ext.text,pointer[target].____extension)){
                                worker.regLocalStorage(JSON.stringify(pointer[target]),'Text');
                                if (window.navigator.msPointerEnabled){
                                    setTimeout(function(){
                                        window.location = './.open/text.html';
                                    },0)
                                }
                                else{
                                    setTimeout(function(){
                                        window.open('./.open/text.html');
                                    },0);
                                }
                            }
                            else if(tool.mySome(ext.image,pointer[target].____extension)){
                                worker.regLocalStorage(JSON.stringify(pointer[target]),'Image');
                                worker.regLocalStorage(JSON.stringify(pointer),'ImageSrc');
                                if (window.navigator.msPointerEnabled){
                                    setTimeout(function(){
                                        window.location = './.open/image.html';
                                    },0)
                                }
                                else{
                                    setTimeout(function(){
                                        window.open('./.open/image.html');
                                    },0);
                                }
                            }
                            else if(tool.mySome(ext.audio,pointer[target].____extension)){
                                worker.regLocalStorage(JSON.stringify(pointer[target]),'Audio');
                                if (window.navigator.msPointerEnabled){
                                    setTimeout(function(){
                                        window.location = './.open/audio.html';
                                    },0)
                                }
                                else{
                                    setTimeout(function(){
                                        window.open('./.open/audio.html');
                                    },0);
                                }
                            }
                            else if(tool.mySome(ext.video,pointer[target].____extension)){
                                worker.regLocalStorage(JSON.stringify(pointer[target]),'Video');
                                if (window.navigator.msPointerEnabled){
                                    setTimeout(function(){
                                        window.location = './.open/video.html';
                                    },0)
                                }
                                else{
                                    setTimeout(function(){
                                        window.open('./.open/video.html');
                                    },0);
                                }
                            }
                        }
                    })
                }
                if(obj === src){
                    title.innerHTML = window.location.origin.replace(/^\w+:\/\//,'');
                    pageSet();
                }
                else{
                    var m = '.';
                    for(var n = 0;n < arrPoint.length;n++){
                        m = m + '/' + arrPoint[n];
                    }
                    if(m.length > 40){
                        m = '...'
                    }
                    title.innerHTML = m;
                    pageSet();
                }

            }
            removeList();
            if(obj !== src){
                createBack();
            }
            createList(fileList);
        }
    };

    var body = document.body,
        top = document.getElementById('top'),
        menu = document.getElementById('menu'),
        aside = document.getElementById('aside'),
        article = document.getElementById('article'),
        back = document.getElementById('back'),
        title = document.getElementById('title');

    function removeList(){
        var file = Array.prototype.slice.call(document.getElementsByClassName('file')),
            first = document.getElementById('first');
        for(var n = 0;n < file.length;n++){
            article.removeChild(file[n]);
        }
        if(first){
            article.removeChild(first);
        }
    }
    function pageSet(){
        title.style.marginTop = (- ( tool.renderStyle(title,'height',true) / 2 )) + 'px';
    }

    return public
}();

//


text:
package com.mcdaniel.serverless;

import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.apigateway.AmazonApiGatewayClient;
import com.amazonaws.services.apigateway.model.GetExportRequest;
import com.amazonaws.services.apigateway.model.GetExportResult;
import com.amazonaws.services.apigateway.model.GetMethodRequest;
import com.amazonaws.services.apigateway.model.GetRestApisRequest;
import com.amazonaws.services.apigateway.model.GetRestApisResult;
import com.amazonaws.services.apigateway.model.Op;
import com.amazonaws.services.apigateway.model.PatchOperation;
import com.amazonaws.services.apigateway.model.RestApi;

public class Tester
{
	public static void main(String []args)
	{
		Tester t = new Tester();
		t.run();
	}

	public void run()
	{
		String AWSAccessKey="AKIAJM7YMMLXKUH5EWRQ";
		String AWSSecretKey="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";

        BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AWSAccessKey, AWSSecretKey);

        AmazonApiGatewayClient apiClient = new AmazonApiGatewayClient(awsCredentials);
        apiClient.setRegion(Region.getRegion(Regions.US_WEST_2));

        GetRestApisRequest graReq = new GetRestApisRequest();
		GetRestApisResult graRes = apiClient.getRestApis(graReq);
		RestApi theApi = null;
		for ( RestApi api : graRes.getItems() )
		{
			System.out.println("Found existing REST API: " + api.getName());
			if ( "TestAPI".equals(api.getName()))
			{
				theApi = api;

				GetExportRequest geReq = new GetExportRequest()
						.withRestApiId(api.getId())
						.withExportType("swagger")
						.withStageName("TEST");
				GetExportResult geRes = apiClient.getExport(geReq);
				String f = new String(geRes.getBody().array());
				int x = 1;
				String from = "";
				PatchOperation po = new PatchOperation()
						.withFrom(from)
						.withOp(Op.Replace)
						.withPath("");
			}
		}

	}
}


text:
.. highlight:: console

How to develop
--------------

Install the package following README.rst and then install development dependencies::

    $ pip install -U -r tests/requirements-dev.txt

Unit tests can be run with `pytest <https://pytest.org>`_ with::

    $ pytest -v --flakes --cov=cdsapi --cov-report=html --cache-clear

Coverage can be checked opening in a browser the file ``htmlcov/index.html`` for example with::

    $ open htmlcov/index.html

Code quality control checks can be run with::

    $ pytest -v --pep8 --mccabe

The complete python versions tests are run via `tox <https://tox.readthedocs.io>`_ with::

    $ tox

Please ensure the coverage at least stays the same before you submit a pull request.

Dependency management
---------------------

Update the `requirements-tests.txt` file with versions with::

    pip-compile -U -o tests/requirements-tests.txt setup.py tests/requirements-tests.in  # -U is optional

Release procedure
-----------------

Quality check release::

    $ git status
    $ check-manifest
    $ tox

Release with zest.releaser::

    $ prerelease
    $ release
    $ postrelease


text:
//#define DISABLE_AUTO_ACCEPT
//#define ENABLE_MANUAL_ACCEPT

using System;
using System.Threading;

namespace UdpKit.Examples.Simple {
    class DummySerializer : UdpSerializer {
        public override bool Pack (UdpStream stream, ref object o) {
            throw new NotImplementedException();
        }

        public override bool Unpack (UdpStream stream, ref object o) {
            throw new NotImplementedException();
        }
    }

    class Program {
        static void Client () {
            UdpSocket client = UdpSocket.Create<UdpPlatformManaged, DummySerializer>();
            client.Start(UdpEndPoint.Any);
            client.Connect(new UdpEndPoint(UdpIPv4Address.Localhost, 14000));

            while (true) {
                UdpEvent ev;

                while (client.Poll(out ev)) {
                    UdpLog.User("Event raised {0}", ev.EventType);

                    switch (ev.EventType) {
                        case UdpEventType.Connected:
                            UdpLog.User("Connected to server at {0}", ev.Connection.RemoteEndPoint);
                            break;

#if DISABLE_AUTO_ACCEPT
                        case UdpEventType.ConnectFailed:
                            UdpLog.User("Connection to {0} failed", ev.EndPoint);
                            break;
#endif
                    }
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }

        static void Server () {
#if DISABLE_AUTO_ACCEPT
            UdpConfig config = new UdpConfig();
            config.AutoAcceptIncommingConnections = false;
#else
            UdpConfig config = new UdpConfig();
#endif
            UdpSocket server = UdpSocket.Create<UdpPlatformManaged, DummySerializer>(config);
            server.Start(new UdpEndPoint(UdpIPv4Address.Localhost, 14000));

            while (true) {
                UdpEvent ev;

                while (server.Poll(out ev)) {
                    UdpLog.User("Event raised {0}", ev.EventType);

                    switch (ev.EventType) {
                        case UdpEventType.Connected:
                            UdpLog.User("Client connected from {0}", ev.Connection.RemoteEndPoint);
                            break;

#if ENABLE_MANUAL_ACCEPT
                        case UdpEventType.ConnectRequest:
                            UdpLog.User("Connection requested from {0}", ev.EndPoint);
                            server.Accept(ev.EndPoint);
                            break;
#endif
                    }
                }

                // Simulate ~60fps game loop
                Thread.Sleep(16);
            }
        }

        static void Main (string[] args) {
            Console.WriteLine("Example: Simple");
            Console.WriteLine("Press [S] to start server");
            Console.WriteLine("Press [C] to start client");
            Console.Write("... ");

            UdpLog.SetWriter((l, m) => Console.WriteLine(m));

            switch (Console.ReadKey(true).Key) {
                case ConsoleKey.S:
                    Console.WriteLine("Server");
                    Server();
                    break;

                case ConsoleKey.C:
                    Console.WriteLine("Client");
                    Client();
                    break;

                default:
                    Main(args);
                    break;
            }
        }
    }
}


text:
package net.tascalate.async.extras;

import static net.tascalate.async.CallContext.yield;

import java.time.Duration;

import java.util.Iterator;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Stream;

import net.tascalate.async.AsyncGenerator;
import net.tascalate.async.Scheduler;
import net.tascalate.async.Sequence;
import net.tascalate.async.async;

import net.tascalate.async.spi.CurrentCallContext;

import net.tascalate.concurrent.CompletableTask;

public class Generators {

    private Generators() {}

    @SafeVarargs
    public static <T> AsyncGenerator<T> concat(Sequence<? extends CompletionStage<T>>... sequences) {
        return concat(Stream.of(sequences));
    }

    public static <T> AsyncGenerator<T> concat(Iterable<? extends Sequence<? extends CompletionStage<T>>> sequences) {
        return concat(sequences.iterator());
    }

    public static <T> AsyncGenerator<T> concat(Stream<? extends Sequence<? extends CompletionStage<T>>> sequences) {
        return concat(sequences.iterator());
    }

    private static @async <T> AsyncGenerator<T> concat(Iterator<? extends Sequence<? extends CompletionStage<T>>> sequences) {
        while (sequences.hasNext()) {
            yield( sequences.next() );
        }
        return yield();
    }

    public static @async AsyncGenerator<Duration> delays(Duration duration) {
        Executor executor = new CurrentSchedulerExecutor(CurrentCallContext.scheduler());
        while (true) {
            yield( CompletableTask.delay(duration, executor) );
        }
    }

    public static @async AsyncGenerator<Duration> delays(long timeout, TimeUnit timeUnit) {
        Executor executor = new CurrentSchedulerExecutor(CurrentCallContext.scheduler());
        while (true) {
            yield( CompletableTask.delay(timeout, timeUnit, executor) );
        }
    }

    public static <T> Function<Sequence<? extends CompletionStage<T>>, PromisesSequence<T>> promisesSequence() {
        return DefaultPromisesSequence::new;
    }

    public static <T> Function<AsyncGenerator<T>, PromisesGenerator<T>> promisesGenerator() {
        return DefaultPromisesGenerator::new;
    }

    static class CurrentSchedulerExecutor implements Executor {
        private final Scheduler scheduler;
        CurrentSchedulerExecutor(Scheduler scheduler) {
            this.scheduler = scheduler;
        }

        @Override
        public void execute(Runnable command) {
            scheduler.schedule(command);
        }
    }
}


text:
namespace cc {
class LayerTreeFrameSink;
struct BeginMainFrameMetrics;
struct WebVitalMetrics;
}  // namespace cc

namespace blink {

class FrameWidget;
class WebGestureEvent;
class WebMouseEvent;

// This class is part of the foundation of all widgets. It provides
// callbacks from the compositing infrastructure that the individual widgets
// will need to implement.
class WidgetBaseClient {
 public:
  // Called to record the time taken to dispatch rAF aligned input.
  virtual void RecordDispatchRafAlignedInputTime(
      base::TimeTicks raf_aligned_input_start_time) {}

  // Called to update the document lifecycle, advance the state of animations
  // and dispatch rAF.
  virtual void BeginMainFrame(base::TimeTicks frame_time) = 0;

  // Requests that the lifecycle of the widget be updated.
  virtual void UpdateLifecycle(WebLifecycleUpdate requested_update,
                               DocumentUpdateReason reason) = 0;

  // TODO(crbug.com/704763): Remove the need for this.
  virtual void SetSuppressFrameRequestsWorkaroundFor704763Only(bool) {}

  // Called when main frame metrics are desired. The local frame's UKM
  // aggregator must be informed that collection is starting for the
  // frame.
  virtual void RecordStartOfFrameMetrics() {}

  // Called when a main frame time metric should be emitted, along with
  // any metrics that depend upon the main frame total time.
  virtual void RecordEndOfFrameMetrics(
      base::TimeTicks frame_begin_time,
      cc::ActiveFrameSequenceTrackers trackers) {}

  // Return metrics information for the stages of BeginMainFrame. This is
  // ultimately implemented by Blink's LocalFrameUKMAggregator. It must be a
  // distinct call from the FrameMetrics above because the BeginMainFrameMetrics
  // for compositor latency must be gathered before the layer tree is
  // committed to the compositor, which is before the call to
  // RecordEndOfFrameMetrics.
  virtual std::unique_ptr<cc::BeginMainFrameMetrics>
  GetBeginMainFrameMetrics() {
    return nullptr;
  }

  virtual std::unique_ptr<cc::WebVitalMetrics> GetWebVitalMetrics() {
    return nullptr;
  }

  // Methods called to mark the beginning and end of the
  // LayerTreeHost::UpdateLayers method. Only called when gathering main frame
  // UMA and UKM. That is, when RecordStartOfFrameMetrics has been called, and
  // before RecordEndOfFrameMetrics has been called.
  virtual void BeginUpdateLayers() {}
  virtual void EndUpdateLayers() {}

  // Methods called to mark the beginning and end of a commit to the impl
  // thread for a frame. Only called when gathering main frame
  // UMA and UKM. That is, when RecordStartOfFrameMetrics has been called, and
  // before RecordEndOfFrameMetrics has been called.
  virtual void BeginCommitCompositorFrame() {}
  virtual void EndCommitCompositorFrame(base::TimeTicks commit_start_time,
                                        base::TimeTicks commit_finish_time) {}

  // Applies viewport related properties during a commit from the compositor
  // thread.
  virtual void ApplyViewportChanges(const cc::ApplyViewportChangesArgs& args) {}

  virtual void UpdateCompositorScrollState(
      const cc::CompositorCommitData& commit_data) {}

  // Notifies that the layer tree host has completed a call to
  // RequestMainFrameUpdate in response to a BeginMainFrame.
  virtual void DidBeginMainFrame() {}
  virtual void DidCommitAndDrawCompositorFrame() {}

  virtual void DidObserveFirstScrollDelay(
      base::TimeDelta first_scroll_delay,
      base::TimeTicks first_scroll_timestamp) {}

  virtual void WillBeginMainFrame() {}
  virtual void DidCompletePageScaleAnimation() {}

  // Allocates a LayerTreeFrameSink to submit CompositorFrames to. Only
  // override this method if you wish to provide your own implementation
  // of LayerTreeFrameSinks (usually for tests). If this method returns null
  // a frame sink will be requested from the browser process (ie. default flow)
  virtual std::unique_ptr<cc::LayerTreeFrameSink>
  AllocateNewLayerTreeFrameSink() = 0;

  virtual void FocusChangeComplete() {}

  virtual WebInputEventResult DispatchBufferedTouchEvents() = 0;
  virtual WebInputEventResult HandleInputEvent(
      const WebCoalescedInputEvent&) = 0;
  virtual bool SupportsBufferedTouchEvents() = 0;

  virtual void DidHandleKeyEvent() {}
  virtual void WillHandleGestureEvent(const WebGestureEvent& event,
                                      bool* suppress) = 0;
  virtual void WillHandleMouseEvent(const WebMouseEvent& event) = 0;
  virtual void ObserveGestureEventAndResult(
      const WebGestureEvent& gesture_event,
      const gfx::Vector2dF& unused_delta,
      const cc::OverscrollBehavior& overscroll_behavior,
      bool event_processed) = 0;

  virtual WebTextInputType GetTextInputType() {
    return WebTextInputType::kWebTextInputTypeNone;
  }

  // Called to inform the Widget of the mouse cursor's visibility.
  virtual void SetCursorVisibilityState(bool is_visible) {}

  // The FrameWidget interface if this is a FrameWidget.
  virtual blink::FrameWidget* FrameWidget() { return nullptr; }

  // Called to inform the Widget that it has gained or lost keyboard focus.
  virtual void FocusChanged(mojom::blink::FocusState focus_state) {}

  // Call to request an animation frame from the compositor.
  virtual void ScheduleAnimation() {}

  // TODO(bokan): Temporary to unblock synthetic gesture events running under
  // VR. https://crbug.com/940063
  virtual bool ShouldAckSyntheticInputImmediately() { return false; }

  // Apply the visual properties.
  virtual void UpdateVisualProperties(
      const VisualProperties& visual_properties) = 0;

  // A callback to apply the updated screen rects, return true if it
  // was handled. If not handled WidgetBase will apply the screen
  // rects as the new values.
  virtual bool UpdateScreenRects(const gfx::Rect& widget_screen_rect,
                                 const gfx::Rect& window_screen_rect) {
    return false;
  }

  // Convert screen coordinates to device emulated coordinates (scaled
  // coordinates when devtools is used). This occurs for popups where their
  // window bounds are emulated.
  virtual void ScreenRectToEmulated(gfx::Rect& screen_rect) {}
  virtual void EmulatedToScreenRect(gfx::Rect& screen_rect) {}

  // Signal the orientation has changed.
  virtual void OrientationChanged() {}

  // Return the original (non-emulated) screen infos.
  virtual const display::ScreenInfos& GetOriginalScreenInfos() = 0;

  // Indication that the surface and screen were updated.
  virtual void DidUpdateSurfaceAndScreen(
      const display::ScreenInfos& previous_original_screen_infos) {}

  // Return the viewport visible rect.
  virtual gfx::Rect ViewportVisibleRect() = 0;

  // The screen orientation override.
  virtual absl::optional<display::mojom::blink::ScreenOrientation>
  ScreenOrientationOverride() {
    return absl::nullopt;
  }

  // Return the overridden device scale factor for testing.
  virtual float GetTestingDeviceScaleFactorOverride() { return 0.f; }

  // Test-specific methods below this point.
  virtual void ScheduleAnimationForWebTests() {}

  // Inform the widget that it was hidden.
  virtual void WasHidden() {}

  // Inform the widget that it was shown.
  virtual void WasShown(bool was_evicted) {}

  virtual void RunPaintBenchmark(int repeat_count,
                                 cc::PaintBenchmarkResult& result) {}

  // Called to indicate a synthetic event was queued.
  virtual void WillQueueSyntheticEvent(const WebCoalescedInputEvent& event) {}

  // When the WebWidget is part of a frame tree, returns the active url for
  // main frame of that tree, if the main frame is local in that tree. When
  // the WebWidget is of a different kind (e.g. a popup) it returns the active
  // url for the main frame of the frame tree that spawned the WebWidget, if
  // the main frame is local in that tree. When the relevant main frame is
  // remote in that frame tree, then the url is not known, and an empty url is
  // returned.
  virtual KURL GetURLForDebugTrace() = 0;

  // In EventTiming, we count the events invoked by user interactions. Some
  // touchstarts will be dropped before they get sent to the main thread.
  // Meanwhile, the corresponding pointerdown will not be fired. The following
  // pointerup will be captured in pointer_event_manager. The following touchend
  // will not be dispatched because there's no target which is always set by
  // touchstart. But we still want to count those touchstart, pointerdown and
  // touchend.
  virtual void CountDroppedPointerDownForEventTiming(unsigned count) {}

  // Whether to use ScrollPredictor to resample scroll events. This is false for
  // web_tests to ensure that scroll deltas are not timing-dependent.
  virtual bool AllowsScrollResampling() { return true; }
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_PLATFORM_WIDGET_WIDGET_BASE_CLIENT_H_


text:
.. py:currentmodule:: pylxd.models

Networks
========

:class:`Network` objects show the current networks available to LXD. Creation
and / or modification of networks is possible only if 'network' LXD API
extension is present.

Manager methods
---------------

Networks can be queried through the following client manager
methods:

  - :func:`~Network.all` - Retrieve all networks.
  - :func:`~Network.exists` - See if a profile with a name exists.
    Returns `bool`.
  - :func:`~Network.get` - Get a specific network, by its name.
  - :func:`~Network.create` - Create a new network.
    The name of the network is required. `description`, `type` and `config`
    are optional and the scope of their contents is documented in the LXD
    documentation.

Network attributes
------------------

  - :attr:`~Network.name` - The name of the network.
  - :attr:`~Network.description` - The description of the network.
  - :attr:`~Network.type` - The type of the network.
  - :attr:`~Network.used_by` - A list of containers using this network.
  - :attr:`~Network.config` - The configuration associated with the network.
  - :attr:`~Network.managed` - `boolean`; whether LXD manages the network.

Network methods
---------------

  - :func:`~Network.rename` - Rename the network.
  - :func:`~Network.save` - Save the network. This uses the PUT HTTP method and
    not the PATCH.
  - :func:`~Network.delete` - Deletes the network.

.. py:currentmodule:: pylxd.models

Examples
--------

:class:`Network` operations follow the same manager-style as other
classes. Networks are keyed on a unique name.

.. code-block:: python

    >>> network = client.networks.get('lxdbr0')

    >>> network
    Network(config={"ipv4.address": "10.74.126.1/24", "ipv4.nat": "true", "ipv6.address": "none"}, description="", name="lxdbr0", type="bridge")

    >>> print(network)
    {
      "name": "lxdbr0",
      "description": "",
      "type": "bridge",
      "config": {
        "ipv4.address": "10.74.126.1/24",
        "ipv4.nat": "true",
        "ipv6.address": "none"
      },
      "managed": true,
      "used_by": []
    }

The network can then be modified and saved.

    >>> network.config['ipv4.address'] = '10.253.10.1/24'
    >>> network.save()

To create a new network, use :func:`~Network.create` with a name, and optional
arguments: `description` and `type` and `config`.

    >>> network = client.networks.create(
    ...     'lxdbr1', description='My new network', type='bridge', config={})


text:
package org.zenoss.app.config;

import org.hibernate.validator.constraints.NotEmpty;

import com.fasterxml.jackson.annotation.JsonProperty;

public class ProxyConfiguration {

    @NotEmpty
   	@JsonProperty
   	private String protocol = "http";

	@NotEmpty
	@JsonProperty
	private String hostname = "127.0.0.1";

	@NotEmpty
	@JsonProperty
	private int port = 8080;

	public String getHostname() {
		return hostname;
	}

	public int getPort() {
		return port;
	}

    public String getProtocol() {
        return protocol;
    }
}


text:
<!doctype html>
<html>
<head>
	<title>paper-collapse-group</title>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<script src="../../webcomponentsjs/webcomponents-lite.js"></script>
	<script src="../../web-component-tester/browser.js"></script>

	<link rel="import" href="../paper-collapse-item.html">
	<link rel="import" href="../paper-collapse-group.html">
</head>
<body>

	<test-fixture id="Group">
		<template>
			<paper-collapse-group>
				<paper-collapse-item></paper-collapse-item>
				<paper-collapse-item></paper-collapse-item>
			</paper-collapse-group>
		</template>
	</test-fixture>

	<script>
	suite('<paper-collapse-group>', function() {

		setup(function() {
			element = fixture('Group');
		});

		test('can observer items inside content tag',function(done){
			flush(function(){
				expect(element._items).to.have.length(2);
				done();
			});
		});

		test('can observe new add elements',function(done){
			flush(function() {
				var item = document.createElement('paper-collapse-item');
				Polymer.dom(element).appendChild(item);
				// give the element some time to update
				element.async(function() {
					expect(element._items).to.have.length(3);
					done();
				}, 200);
			});
		});

		test('toggle works',function(done){

			flush(function(){

				var items = element._items;
				items[0].fire('toggle',items[0]);
				expect(items[1].opened).to.equal(false);

				items[1].fire('toggle',items[1]);
				expect(items[0].opened).to.equal(false);
				done();
			});
		});

	});
	</script>

</body>
</html>


text:
const parse = require('obj-parse'),
    deepKeys = require('deep-keys'),
    SimpleSchema = require('simpl-schema').default;

export class Mixed {
    //for schemas
}

export const SchemaReference = SimpleSchema.oneOf(String, Mixed);
export const JSONDate = SimpleSchema.oneOf(String, Number, Date);

export class SubSchema extends SimpleSchema {
    private readonly _apiCoreOriginal: any;

    constructor(schema: any, options?: any, ...args: any[]) {
        if(!options) options = { requiredByDefault: false };
        super(schema, options, ...args);
        this._apiCoreOriginal = schema;
    }

    get original() {
        return this._apiCoreOriginal
    }
}

export class ApiEdgeSchemaTransformation {
    applyToInput: (schema: any, model: any) => void;
    applyToOutput: (mode: any, schema: any) => void;
    affectedSchemaField: string;
    affectedModelFields: string[];
    parsedField: any;
    schemaType: any;

    constructor(input: (schema: any, model: any) => void,
                output: (model: any, schema: any) => void,
                modelFields: string[],
                schemaType: any,
                schemaField: string = "") {
        this.applyToInput = input;
        this.applyToOutput = output;
        this.affectedSchemaField = schemaField;
        this.affectedModelFields = modelFields;
        this.parsedField = parse(schemaField);
        this.schemaType = schemaType
    }

    setSchemaField(field: string) {
        this.affectedSchemaField = field;
        this.parsedField = parse(field);
    }
}

export class ApiEdgeSchema {
    fields: string[] = [];
    schema: any|null = null;
    originalSchema: any|null = null;
    transformations: ApiEdgeSchemaTransformation[];

    private fieldMatrix: { [key: string]: string[] } = {};
    private renameMatrix: { [key: string]: string } = {};
    transformField = (field: string) => {
        return this.renameMatrix[field] || field
    };

    transformFields = (fields: string[]): string[] => {
        let output: string[] = [];
        for (const field of fields) {
            const transformedFields = this.fieldMatrix[field];
            if(transformedFields) {
                transformedFields.forEach((f: string) => output.push(f))
            }
            else {
                if (this.renameMatrix[field])
                    output.push(this.renameMatrix[field]);
                else
                    output.push(field);
            }
        }
        return output
    };

    cleanAndValidateModel = (model: any, modifier: boolean = false): { valid: boolean, errors?: any[] } => {
        if(this.schema) {
            const context = this.schema.newContext();

            context.clean(model, {
                mutate: true,       //Update the original object
                filter: true,       //Remove not allowed fields
                autoConvert: true,  //Converts values when possible
                removeEmptyStrings: false,
                trimStrings: false,
                getAutoValues: !modifier //Fill defaults
            });

            model = modifier
                ? { $set: model }
                : model;

            context.validate(model, { modifier });

            return {
                valid: context.isValid(),
                errors: context.validationErrors().map(
                    ({ name }: any) => context.keyErrorMessage(name)
                )
            }
        }

        return { valid: true }
    };

    private createInputTransformer(schemaField: any, transform: string): (schema: any, model: any) => void {
        if(transform === "=") {
            return (schema: any, model: any) => schemaField.assign(model, schemaField(schema));
        }
        else if(transform[0] === "=") {
            const fieldName = transform.substring(1),
                modelField = parse(fieldName);

            return (schema: any, model: any) => modelField.assign(model, schemaField(schema));
        }
        else throw "Not Supported Transform";
    }

    private static createOutputTransformer(schemaField: any, transform: string): (model: any, schema: any) => void {
        if(transform === "=") {
            return (model: any, schema: any) => schemaField.assign(schema, schemaField(model));
        }
        else if(transform[0] === "=") {
            const fieldName = transform.substring(1),
                modelField = parse(fieldName);

            return (model: any, schema: any) => schemaField.assign(schema, modelField(model));
        }
        else {
            throw "Not Supported Transform";
        }
    }

    private createTransformation(schemaField: string, schema: any, typedSchema: any): ApiEdgeSchemaTransformation|undefined {
        const parsedSchemaField = parse(schemaField),
            transform: string|ApiEdgeSchemaTransformation = parsedSchemaField(schema);

        if(transform instanceof ApiEdgeSchemaTransformation) {
            transform.setSchemaField(schemaField);

            let transformedFields = this.fieldMatrix[transform.affectedSchemaField];
            if(transformedFields) {
                transform.affectedModelFields.forEach((field: string) => transformedFields.push(field))
            }
            else {
                this.fieldMatrix[transform.affectedSchemaField]
                    = transform.affectedModelFields.map((field: string) => field)
            }

            this.fixFields(schemaField);

            return transform;
        }
        else if(typeof transform === "string") {
            this.renameMatrix[schemaField] = transform.substring(1);

            return new ApiEdgeSchemaTransformation(
                this.createInputTransformer(parsedSchemaField, transform),
                ApiEdgeSchema.createOutputTransformer(parsedSchemaField, transform),
                [ schemaField ],
                typedSchema ? typedSchema[schemaField] : Mixed,
                schemaField
            )
        }
    }

    private fixFields(fieldName: string) {
        this.fields = this.fields.filter((field: string) => field.indexOf(fieldName+".") == -1)
    }

    constructor(schema: any, typedSchema: any = null, fields?: string[]) {
        this.fields = fields || deepKeys(schema, true);
        this.originalSchema = typedSchema;
        this.schema = typedSchema
            ? new SimpleSchema(typedSchema, { requiredByDefault: false })
            : null;

        this.transformations = [];
        for(let i = 0; i < this.fields.length; ++i) {
            const transform = this.createTransformation(this.fields[i], schema, typedSchema);
            if(transform)
                this.transformations.push(transform)
        }
    }
}


text:
<!DOCTYPE html>

	<link href="js/bootstrap.min.css" rel="stylesheet"type="text/css">
	<link href="css/moncss.css" rel="stylesheet"type="text/css">

	<title>Comparison of business integration software - Database support</title>
	<meta charset="utf-8">

Comparison of business integration software - Database support

			<fieldset>

					<form action="" method="post">
						<legend style="color:red;font-weight: bold;font-style:italic;text-align: center;" >Formulaire</legend>

								Sun Java Composite Application Platform Suite - Yes :

 <input type="radio" name="FeatureSun Java Composite Application Platform Suite - Yes" value="oui">Yes <input type="radio" name="FeatureSun Java Composite Application Platform Suite - Yes" value = "non">No <input type="radio" name="FeatureSun Java Composite Application Platform Suite - Yes" value = "non">Partial

								Software - ODBC :
 <input id="0" type="text" name="Feature">

								Software - API :
 <input id="1" type="text" name="Feature">

								AdroitLogic UltraESB - Yes :

 <input type="radio" name="FeatureAdroitLogic UltraESB - Yes" value="oui">Yes <input type="radio" name="FeatureAdroitLogic UltraESB - Yes" value = "non">No <input type="radio" name="FeatureAdroitLogic UltraESB - Yes" value = "non">Partial

								WebSphere Message Broker - Yes :

 <input type="radio" name="FeatureWebSphere Message Broker - Yes" value="oui">Yes <input type="radio" name="FeatureWebSphere Message Broker - Yes" value = "non">No <input type="radio" name="FeatureWebSphere Message Broker - Yes" value = "non">Partial

								Informatica Power Center - Yes :

 <input type="radio" name="FeatureInformatica Power Center - Yes" value="oui">Yes <input type="radio" name="FeatureInformatica Power Center - Yes" value = "non">No <input type="radio" name="FeatureInformatica Power Center - Yes" value = "non">Partial

								WebSphere Enterprise Service Bus and WebSphere Process Server - Yes :

 <input type="radio" name="FeatureWebSphere Enterprise Service Bus and WebSphere Process Server - Yes" value="oui">Yes <input type="radio" name="FeatureWebSphere Enterprise Service Bus and WebSphere Process Server - Yes" value = "non">No <input type="radio" name="FeatureWebSphere Enterprise Service Bus and WebSphere Process Server - Yes" value = "non">Partial

								WSO2 Enterprise Service Bus (ESB) - Yes :
 <input id="2" type="text" name="Feature">

								Flow Software - Yes :

 <input type="radio" name="FeatureFlow Software - Yes" value="oui">Yes <input type="radio" name="FeatureFlow Software - Yes" value = "non">No <input type="radio" name="FeatureFlow Software - Yes" value = "non">Partial

								JBoss Enterprise SOA Platform - No :

 <input type="radio" name="FeatureJBoss Enterprise SOA Platform - No" value="oui">Yes <input type="radio" name="FeatureJBoss Enterprise SOA Platform - No" value = "non">No <input type="radio" name="FeatureJBoss Enterprise SOA Platform - No" value = "non">Partial

								Apache Synapse - Yes :
 <input id="3" type="text" name="Feature">

								Automation Anywhere Integration Pack - Yes :
 <input id="4" type="text" name="Feature">

								JBoss Enterprise Service Bus (ESB) - No :

 <input type="radio" name="FeatureJBoss Enterprise Service Bus (ESB) - No" value="oui">Yes <input type="radio" name="FeatureJBoss Enterprise Service Bus (ESB) - No" value = "non">No <input type="radio" name="FeatureJBoss Enterprise Service Bus (ESB) - No" value = "non">Partial

								BizTalk Server - Yes :

 <input type="radio" name="FeatureBizTalk Server - Yes" value="oui">Yes <input type="radio" name="FeatureBizTalk Server - Yes" value = "non">No <input type="radio" name="FeatureBizTalk Server - Yes" value = "non">Partial

								Talend ESB - Yes :
 <input id="5" type="text" name="Feature">

<input type="submit" class="btn btn-info" value="Ajouter un produit" />
					</form>

			</fieldset>


text:
package com.alibaba.wasp.session;

import com.alibaba.wasp.ReadModel;
import com.alibaba.wasp.client.FClient;
import com.alibaba.wasp.jdbc.command.CommandInterface;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class ExecuteSession implements SessionInterface {

  private String sessionId;

  private AtomicInteger nextId = new AtomicInteger();

  public String getSessionId() {
    return sessionId;
  }

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

  public int getNextId() {
    return nextId.incrementAndGet();
  }

  public int getCurrentId() {
    return nextId.get();
  }

  @Override
  public void close() throws IOException {
    // To change body of implemented methods use File | Settings | File
    // Templates.
  }

  @Override
  public boolean isClosed() {
    return false; // To change body of implemented methods use File | Settings |
                  // File Templates.
  }

  @Override
  public CommandInterface prepareCommand(FClient fClient, String sql,
      int fetchSize, ReadModel readModel, boolean autoCommit, ExecuteSession statementSession) {
    return null; // To change body of implemented methods use File | Settings |
                 // File Templates.
  }

  @Override
  public CommandInterface prepareCommand(FClient fClient, List<String> sqls, boolean autoCommit, ExecuteSession statementSession) {
    return null;  //To change body of implemented methods use File | Settings | File Templates.
  }

  @Override
  public void afterWriting() {
    // To change body of implemented methods use File | Settings | File
    // Templates.
  }

  public void checkClosed() {
  }
}


text:
<?php namespace controllers\admin;

use \helpers\password,
	\helpers\session,
	\helpers\url,
	\core\view;

class Auth extends \core\controller {

	public function login(){

		if(Session::get('loggedin')){
			Url::redirect('admin');
		}

		$model = new \models\admin\auth();

		$data['title'] = 'Login';

		if(isset($_POST['submit'])){

			$username = $_POST['username'];
			$password = $_POST['password'];

			if(Password::verify($password, $model->getHash($_POST['username'])) == 0){
				$error[] = 'Wrong username of password';
			} else {
				Session::set('loggedin',true);
				Url::redirect('admin');
			}

		}

		View::renderadmintemplate('loginheader',$data);
		View::render('admin/login',$data,$error);
		View::renderadmintemplate('footer',$data);
	}

	public function logout(){

		Session::destroy();
		Url::redirect('admin/login');

	}

}


text:
param($installPath, $toolsPath, $package, $project)

$assemblyFName      = 'DllExport'
$targetFileName     = 'net.r_eg.DllExport.targets'
$metaLib            = $([System.IO.Path]::Combine("$installPath", 'lib\net20', $assemblyFName + '.dll'));
$gpc                = Get-MBEGlobalProjectCollection
$projects           = $gpc.GetLoadedProjects($project.FullName)

# Configurator

# $dllConf = Get-TempPathToConfiguratorIfNotLoaded 'net.r_eg.DllExport.Configurator.dll' "$toolsPath"
# if($dllConf) {
#     Import-Module $dllConf;
# }

Import-Module (Load-Configurator "$toolsPath")
Reset-Configuration -MetaLib "$metaLib" -InstallPath "$installPath" -ToolsPath "$toolsPath" -ProjectDTE $project -ProjectsMBE $gpc;

#

return $projects |  % {
    $currentProject = $_

    $currentProject.Xml.Imports | ? {
        $targetFileName -ieq [System.IO.Path]::GetFileName($_.Project)
    }  | % {
        $currentProject.Xml.RemoveChild($_)
    }
}


text:
from django.core.context_processors import csrf
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.template.loader import render_to_string
from django.views.decorators.csrf import csrf_exempt

from web.data import *
from web.berg import getQRCodeUrl, getCardHtml, printHtml
from web.utils import renderViewUser
from web.http_auth import http_basic_auth
from web.models import User, SharedTask

import json
import requests

HASHTAG = '#k4hoedown'
# TODO: copy access token from Facebook Graph API explorer here
ACCESS_TOKEN = 'XXX'
FACEBOOK_SEARCH_URL = 'https://graph.facebook.com/search'

#@http_basic_auth
def home(request):
    return render(request, 'admin/home.html', {})

#@http_basic_auth
def listUsers(request):
    users = User.objects.order_by('-created')
    for user in users:
        user.role_name = ROLES[user.role]
    return render(request, 'admin/list.html', {
        'users': users
    })

#@http_basic_auth
def viewUser(request, code):
    try:
        user = User.objects.get(code=code)
    except User.DoesNotExist:
        raise Exception('no user for code %s' % code)
    return renderViewUser(request, user, is_admin=True)

#@http_basic_auth
def printCard(request, code):
    try:
        user = User.objects.get(code=code)
    except User.DoesNotExist:
        raise Exception('no user for code %s' % code)
    card_html = getCardHtml(request, user)
    berg_response = printHtml(card_html)
    print berg_response
    return redirect('adminListUsers')

#@http_basic_auth
def updateUserStats(request, code):
    if request.method != 'POST':
        raise Exception('Cannot GET {0}'.format(request.path))
    try:
        user = User.objects.get(code=code)
    except User.DoesNotExist:
        raise Exception('no user for code %s' % code)
    user.cha = request.POST['cha']
    user.con = request.POST['con']
    user.dex = request.POST['dex']
    user.int = request.POST['int']
    user.str = request.POST['str']
    user.wis = request.POST['wis']
    user.save()
    return redirect('adminListUsers')

def updateUserName(request, code):
    if request.method != 'POST':
        raise Exception('Cannot GET {0}'.format(request.path))
    try:
        user = User.objects.get(code=code)
    except User.DoesNotExist:
        raise Exception('no user for code %s' % code)
    user.name = request.POST['name']
    user.save()
    return redirect('adminListUsers')

@csrf_exempt
def updateUserPhoto(request, code):
    if request.method != 'POST':
        raise Exception('Cannot GET {0}'.format(request.path))
    try:
        user = User.objects.get(code=code)
    except User.DoesNotExist:
        raise Exception('no user for code %s' % code)
    print code
    uploaded_file = request.FILES.get('file')
    if not uploaded_file:
        raise Exception('missing file')
    local_filepath = 'web/static/images/{0}'.format(uploaded_file.name)
    with open(local_filepath, 'wb+') as local_file:
        for chunk in uploaded_file.chunks():
            local_file.write(chunk)
    user.has_photo = True
    user.save()
    return HttpResponse(json.dumps({'success': True}), content_type='application/json')

def searchFacebook(request):
    """
    Returns a JSON array containing the post ids of the last <limit> posts
    that match query <q>.
    """
    q = request.GET['q']
    limit = int(request.GET.get('limit', 5))
    params = {
        'q': q,
        'limit': limit,
        'access_token': ACCESS_TOKEN
    }
    result = requests.get(FACEBOOK_SEARCH_URL, params=params)
    return HttpResponse(result.text, content_type='application/json')


text:
The gist of this exercise is to check the dependencies by executing these commands. If all result in some version number, you are ready for this workshop. Otherwise, jump to the first section below:

```bash
C:\> python --version
C:\> pip --version
C:\> virtualenv --version
C:\> git --version
```

### A. Python 2.7 or 3.4

#### 1. Check if Python is installed or accessible. Open the Command Prompt:

```bash
C:\> python --version
```

#### 2. If this is what you see, then it means you have no Python installed.

```bash
'python' is not recognized as an internal or external command, operable program or batch file.
```

#### 3. Download and install the latest Python 2.x or 3.x releases from this location.

```bash
https://www.python.org/downloads/windows/
```

#### 4. Add the Python path to the system environment variables. To do this, go to `My Computer` > `Properties` > `Advanced System Settings` > `Environment Variables` > `System Variables` > `Path` or `PYTHONPATH` (whichever will work). Click edit. Add this at the _end of the line_:

```bash
;C:\Python27;C:\Python27\Scripts
```

![](windows.png)

#### 5. Check again if Python is already accessible. Reopen the Command Prompt and execute:

```bash
C:\> python --version
```

#### 6. If all goes well, you should see

```bash
Python 2.7.x
```

### B. Pip

#### 1. Check if Pip is installed. Open the Command prompt and execute:

```bash
C:\> pip --version
```

#### 2. If this is what you see, then you don't have Pip installed:

```bash
'pip' is not recognized as an internal or external command, operable program or batch file.
```

#### 3. Install Pip by downloading this script ([https://bootstrap.pypa.io/get-pip.py](https://bootstrap.pypa.io/get-pip.py)) and executing this line in the Terminal:

```bash
C:\> python get-pip.py
```

#### 4. Check again if Pip is installed. Open the Terminal and execute:

```bash
C:\> pip --version
```

#### 5. If all goes well, you should see:

```bash
pip 1.5.x
```

### C. VirtualEnv

#### 1. Install VirtualEnv. Open the Command Prompt and execute:

```bash
C:\> pip install virtualenv
```

#### 2. Check if VirtualEnv is already installed. Reopen the Command Prompt and execute:

```bash
C:\> virtualenv --version
```

#### 3. If all goes well, you should see

```bash
virtualenv 1.x.x
```

### D. Git (optional)

As a developer, there's no excuse not to use Git. But if you don't have it in your machine, you don't have to worry about it. It's not really part of Django.

Download installer here: [http://git-scm.com/download/win](http://git-scm.com/download/win)


text:
Defines a special kind of checksum called a fingerprint. Unlike cryptographic
hash functions like MD5 and
SHA-1, which were designed to
withstand cryptographic attacks, the fingerprint function was explicitly designed
to produce a checksum unique to the text from which it was generated.

In particular, there is a mathematical formula that places an upper bound on the
probability of two randomly chosen (distinct) strings hashing to the same fingerprint.
By choosing a large enough fingerprint, the probability of a collision can be made
vanishingly small. Hence, the fingerprint of a text T can be used as a
fixed-size unique identifier for T.

@author Allan Heydon