text:
package com.salesmanager.core.modules.order;

import java.awt.Graphics2D;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.jopendocument.dom.OOUtils;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;
import org.jopendocument.model.OpenDocument;
import org.jopendocument.renderer.ODTRenderer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfDocument;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
import com.salesmanager.core.business.merchant.model.MerchantStore;
import com.salesmanager.core.business.order.model.Order;
import com.salesmanager.core.business.order.model.OrderTotal;
import com.salesmanager.core.business.order.model.orderproduct.OrderProduct;
import com.salesmanager.core.business.reference.country.model.Country;
import com.salesmanager.core.business.reference.country.service.CountryService;
import com.salesmanager.core.business.reference.language.model.Language;
import com.salesmanager.core.business.reference.zone.model.Zone;
import com.salesmanager.core.business.reference.zone.service.ZoneService;
import com.salesmanager.core.constants.Constants;
import com.salesmanager.core.utils.ProductPriceUtils;
import com.salesmanager.core.utils.ProductUtils;

public class ODSInvoiceModule implements InvoiceModule {

	private final static String INVOICE_TEMPLATE = "templates/invoice/Invoice";
	private final static String INVOICE_TEMPLATE_EXTENSION = ".ods";
	private final static String TEMP_INVOICE_SUFFIX_NAME = "_invoice.ods";
	private final static int ADDRESS_ROW_START = 2;
	private final static int ADDRESS_ROW_END = 5;

	private final static int BILLTO_ROW_START = 8;
	private final static int BILLTO_ROW_END = 13;

	private final static int PRODUCT_ROW_START = 16;

	private static final Logger LOGGER = LoggerFactory.getLogger( ODSInvoiceModule.class );

	@Autowired
	private ZoneService zoneService;

	@Autowired
	private CountryService countryService;

	@Autowired
	private ProductPriceUtils priceUtil;

	@Override
	public ByteArrayOutputStream createInvoice(MerchantStore store, Order order, Language language) throws Exception {

			List<Zone> zones = zoneService.getZones(store.getCountry(), language);
			Map<String,Country> countries = countryService.getCountriesMap(language);

			//get default template
			String template = new StringBuilder().append(INVOICE_TEMPLATE).append("_").append(language.getCode().toLowerCase()).append(INVOICE_TEMPLATE_EXTENSION).toString();

			//try by language
			InputStream is = null;
			try {
				is = getClass().getClassLoader().getResourceAsStream(template);
			} catch (Exception e) {
				LOGGER.warn("Cannot open template " + template);
				throw new Exception("Cannot open " + template);
			}

			if(is==null) {
				try {
					is = getClass().getClassLoader().getResourceAsStream(new StringBuilder().append(INVOICE_TEMPLATE).append(INVOICE_TEMPLATE_EXTENSION).toString());
				} catch (Exception e) {
					LOGGER.warn("Cannot open template " + template);
					throw new Exception("Cannot open " + new StringBuilder().append(INVOICE_TEMPLATE).append(INVOICE_TEMPLATE_EXTENSION).toString());
				}
			}

			if(is==null) {
				LOGGER.warn("Cannot open template " + template);
				throw new Exception("Cannot open " + new StringBuilder().append(INVOICE_TEMPLATE).append(INVOICE_TEMPLATE_EXTENSION).toString());
			}

			File file = new File(order.getId() + "_working");
			OutputStream os = new FileOutputStream(file);
			IOUtils.copy(is, os);
			os.close();
			//File file = new File(resource.toURI().toURL());

			Sheet sheet = SpreadSheet.createFromFile(file).getSheet(0);

			//Store name
			sheet.setValueAt(store.getStorename(), 0, 0);

			//Address
			//count store address cell
			int storeAddressCell = ADDRESS_ROW_START;

			Map<String,Zone> zns = zoneService.getZones(language);

			//3
			StringBuilder storeAddress = null;
			if(!StringUtils.isBlank(store.getStoreaddress())) {
				storeAddress = new StringBuilder();
				storeAddress.append(store.getStoreaddress());
			}
			if(!StringUtils.isBlank(store.getStorecity())) {
				if(storeAddress==null) {
					storeAddress = new StringBuilder();
				} else {
					storeAddress.append(", ");
				}
				storeAddress.append(store.getStorecity());
			}
			if(storeAddress!=null) {
				sheet.setValueAt(storeAddress.toString(), 0, storeAddressCell);
				storeAddressCell ++;
			}

			//4
			StringBuilder storeProvince = null;
			if(store.getZone()!=null) {
				storeProvince = new StringBuilder();

				for(Zone z : zones) {
					if(z.getCode().equals(store.getZone().getCode())) {
						storeProvince.append(z.getName());
						break;
					}
				}

			} else {
				if(!StringUtils.isBlank(store.getStorestateprovince())) {
					storeProvince = new StringBuilder();
					storeProvince.append(store.getStorestateprovince());
				}
			}
			if(store.getCountry()!=null) {
				if(storeProvince==null) {
					storeProvince = new StringBuilder();
				} else {
					storeProvince.append(", ");
				}

				Country c = countries.get(store.getCountry().getIsoCode());
				if(c!=null) {
					storeProvince.append(c.getName());
				} else {
					storeProvince.append(store.getCountry().getIsoCode());
				}

			}
			if(storeProvince!=null) {
				sheet.setValueAt(storeProvince.toString(), 0, storeAddressCell);
				storeAddressCell ++;
			}

			//5
			if(!StringUtils.isBlank(store.getStorepostalcode())) {
				sheet.setValueAt(store.getStorepostalcode(), 0, storeAddressCell);
				storeAddressCell ++;
			}

			//6
			if(!StringUtils.isBlank(store.getStorephone())) {
				sheet.setValueAt(store.getStorephone(), 0, storeAddressCell);
			}

			//delete address blank lines
			for(int i = storeAddressCell; i<ADDRESS_ROW_END; i++) {
				sheet.setValueAt("", 0, i);
			}

			//invoice date
			SimpleDateFormat format = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
			sheet.setValueAt(format.format(order.getDatePurchased()), 3, 2);

			//invoice number
			sheet.setValueAt(order.getId(), 3, 3);

			//bill to
			//count bill to address cell
			int billToCell = BILLTO_ROW_START;
			if(!StringUtils.isBlank(order.getBilling().getFirstName())) {
				StringBuilder nm = new StringBuilder();
				nm.append(order.getBilling().getFirstName()).append(" ").append(order.getBilling().getLastName());
				sheet.setValueAt(nm.toString(), 0, billToCell);
				billToCell ++;
			}

			//9
			if(!StringUtils.isBlank(order.getBilling().getCompany())) {
				sheet.setValueAt(order.getBilling().getCompany(), 0, billToCell);
				billToCell ++;
			}

			//10
			StringBuilder billToAddress = null;
			if(!StringUtils.isBlank(order.getBilling().getAddress())) {
				billToAddress = new StringBuilder();
				billToAddress.append(order.getBilling().getAddress());
			}
			if(!StringUtils.isBlank(order.getBilling().getCity())) {
				if(billToAddress==null) {
					billToAddress = new StringBuilder();
				} else {
					billToAddress.append(", ");
				}
				billToAddress.append(order.getBilling().getCity());
			}
			if(billToAddress!=null) {
				sheet.setValueAt(billToAddress.toString(), 0, billToCell);
				billToCell ++;
			}

			//11
			StringBuilder billToProvince = null;
			if(order.getBilling().getZone()!=null) {
				billToProvince = new StringBuilder();

				Zone billingZone = zns.get(order.getBilling().getZone().getCode());
				if(billingZone!=null) {
						billToProvince.append(billingZone.getName());
				}

			} else {
				if(!StringUtils.isBlank(order.getBilling().getState())) {
					billToProvince = new StringBuilder();
					billToProvince.append(order.getBilling().getState());
				}
			}
			if(order.getBilling().getCountry()!=null) {
				if(billToProvince==null) {
					billToProvince = new StringBuilder();
				} else {
					billToProvince.append(", ");
				}
				Country c = countries.get(order.getBilling().getCountry().getIsoCode());
				if(c!=null) {
					billToProvince.append(c.getName());
				} else {
					billToProvince.append(order.getBilling().getCountry().getIsoCode());
				}

			}
			if(billToProvince!=null) {
				sheet.setValueAt(billToProvince.toString(), 0, billToCell);
				billToCell ++;
			}

			//12
			if(!StringUtils.isBlank(order.getBilling().getPostalCode())) {
				billToCell ++;
				sheet.setValueAt(order.getBilling().getPostalCode(), 0, billToCell);
				billToCell ++;
			}

			//13
			if(!StringUtils.isBlank(order.getBilling().getTelephone())) {
				sheet.setValueAt(order.getBilling().getTelephone(), 0, billToCell);
			}

			//delete address blank lines
			for(int i = billToCell; i<BILLTO_ROW_END; i++) {
				sheet.setValueAt("", 0, i);
			}

			//products
			Set<OrderProduct> orderProducts = order.getOrderProducts();
			int productCell = PRODUCT_ROW_START;
			for(OrderProduct orderProduct : orderProducts) {

				String orderProductName = ProductUtils.buildOrderProductDisplayName(orderProduct);

				sheet.setValueAt(orderProductName.toString(), 0, productCell);

				int quantity = orderProduct.getProductQuantity();
				sheet.setValueAt(quantity, 1, productCell);
				String amount = priceUtil.getStoreFormatedAmountWithCurrency(store, orderProduct.getOneTimeCharge());
				sheet.setValueAt(amount, 2, productCell);
				String t = priceUtil.getStoreFormatedAmountWithCurrency(store, priceUtil.getOrderProductTotalPrice(store, orderProduct));
				sheet.setValueAt(t, 3, productCell);

				productCell++;

			}

			//print totals
			productCell++;
			Set<OrderTotal> totals = order.getOrderTotal();
			for(OrderTotal orderTotal : totals) {

				String totalName = orderTotal.getText();
				if(totalName.contains(".")) {
					totalName = orderTotal.getTitle();
				}
				String totalValue = priceUtil.getStoreFormatedAmountWithCurrency(store,orderTotal.getValue());
				sheet.setValueAt(totalName, 2, productCell);
				sheet.setValueAt(totalValue, 3, productCell);
				productCell++;
			}

			//sheet.getCellAt(0, 0).setImage(arg0)
			//sheet.getCellAt(0, 0).setStyleName(arg0)
			//sheet.getCellAt(0, 0).getStyle().

			//generate invoice file
			StringBuilder tempInvoiceName = new StringBuilder();
			tempInvoiceName.append(order.getId()).append(TEMP_INVOICE_SUFFIX_NAME);
			File outputFile = new File(tempInvoiceName.toString());
			OOUtils.open(sheet.getSpreadSheet().saveAs(outputFile));

			final OpenDocument doc = new OpenDocument();
			doc.loadFrom(tempInvoiceName.toString());

			 // Open the PDF document
			 Document document = new Document(PageSize.A4);

			 //File outFile = new File("invoice.pdf");

			 PdfDocument pdf = new PdfDocument();

			 document.addDocListener(pdf);

			 //FileOutputStream fileOutputStream = new FileOutputStream(outFile);
			 ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

			 PdfWriter writer = PdfWriter.getInstance(pdf, outputStream);
			 pdf.addWriter(writer);

			 document.open();

			 // Create a template and a Graphics2D object
			 Rectangle pageSize = document.getPageSize();
			 int w = (int) (pageSize.getWidth() * 0.9);
			 int h = (int) (pageSize.getHeight() * 0.95);
			 PdfContentByte cb = writer.getDirectContent();
			 PdfTemplate tp = cb.createTemplate(w, h);

			 Graphics2D g2 = tp.createPrinterGraphics(w, h, null);
			 // If you want to prevent copy/paste, you can use
			 // g2 = tp.createGraphicsShapes(w, h, true, 0.9f);

			 tp.setWidth(w);
			 tp.setHeight(h);

			 // Configure the renderer
			 ODTRenderer renderer = new ODTRenderer(doc);
			 renderer.setIgnoreMargins(true);
			 renderer.setPaintMaxResolution(true);

			 // Scale the renderer to fit width
			 renderer.setResizeFactor(renderer.getPrintWidth() / w);
			 // Render
			 renderer.paintComponent(g2);
			 g2.dispose();

			 // Add our spreadsheet in the middle of the page
			 float offsetX = (pageSize.getWidth() - w) / 2;
			 float offsetY = (pageSize.getHeight() - h) / 2;
			 cb.addTemplate(tp, offsetX, offsetY);
			 // Close the PDF document
			 document.close();
			 outputFile.delete();//remove temp file
			 file.delete();//remove spreadsheet file
			 is.close();
			 return outputStream;

	}

}


text:
<!--
    Any modification, copies of sections of this file must be attached with this
    license and shown clearly in the developer's project. The code can be used
    as long as you state clearly you do not own it. Any violation might result in
     a take-down.

    MIT License

    Copyright (c) 2016, 2017 Anthony Law

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.
 -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.github.mob41</groupId>
    <artifactId>osumer</artifactId>
    <version>${global.version}</version>
  </parent>
  <artifactId>osumer-ui</artifactId>
  <name>osumer-ui</name>
  <description>An UI to connect to osumer daemon.</description>
  <repositories>
  	<repository>
  		<snapshots>
  			<enabled>false</enabled>
  		</snapshots>
  		<id>bintray-dukke-maven</id>
  		<name>bintray</name>
  		<url>https://dl.bintray.com/dukke/maven</url>
  	</repository>
  </repositories>
  <pluginRepositories>
  	<pluginRepository>
  		<snapshots>
  			<enabled>false</enabled>
  		</snapshots>
  		<id>bintray-dukke-maven</id>
  		<name>bintray-plugins</name>
  		<url>https://dl.bintray.com/dukke/maven</url>
  	</pluginRepository>
  </pluginRepositories>
  <dependencies>
  	<dependency>
  		<groupId>com.github.mob41</groupId>
  		<artifactId>osumer-debugdump</artifactId>
  		<version>${global.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>com.github.mob41</groupId>
  		<artifactId>osums-api</artifactId>
  		<version>${global.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>com.github.mob41</groupId>
  		<artifactId>osumer-lib</artifactId>
  		<version>${global.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>com.github.mob41</groupId>
  		<artifactId>osumer-installer</artifactId>
  		<version>${global.version}</version>
  	</dependency>
  	<dependency>
  		<groupId>org.jfxtras</groupId>
  		<artifactId>jmetro</artifactId>
  		<version>5.2</version>
  	</dependency>
  </dependencies>
  <build>
    <plugins>
    	<plugin>
    		<groupId>org.apache.maven.plugins</groupId>
    		<artifactId>maven-dependency-plugin</artifactId>
			<executions>
        		<execution>
            		<id>copy-dependencies</id>
            		<phase>prepare-package</phase>
            		<goals>
                		<goal>copy-dependencies</goal>
            		</goals>
            		<configuration>
                		<outputDirectory>${project.parent.build.directory}/lib</outputDirectory>
                		<overWriteReleases>false</overWriteReleases>
                		<overWriteSnapshots>false</overWriteSnapshots>
                		<overWriteIfNewer>true</overWriteIfNewer>
            		</configuration>
        		</execution>
    		</executions>
		</plugin>
		<plugin>
			<groupId>org.apache.maven.plugins</groupId>
        	<artifactId>maven-jar-plugin</artifactId>
        	<configuration>
        		<outputDirectory>${project.parent.build.directory}</outputDirectory>
          		<archive>
            		<manifest>
              			<addClasspath>true</addClasspath>
              			<classpathPrefix>lib/</classpathPrefix>
              			<mainClass>com.github.mob41.osumer.ui.AppMain</mainClass>
            		</manifest>
          		</archive>
        	</configuration>
      	</plugin>
      	<plugin>
          <groupId>com.akathist.maven.plugins.launch4j</groupId>
          <artifactId>launch4j-maven-plugin</artifactId>
          <executions>
            <execution>
              <id>l4j-gui</id>
              <phase>package</phase>
              <goals><goal>launch4j</goal></goals>
              <configuration>
                <headerType>gui</headerType>
                <outfile>${project.parent.build.directory}/${project.artifactId}.exe</outfile>
                <jar>${project.parent.build.directory}/${project.artifactId}-${global.version}.jar</jar>
                <errTitle>osumer2</errTitle>
                <supportUrl>https://github.com/mob41/osumer/issues/new</supportUrl>
                <classPath>
                  <mainClass>com.github.mob41.osumer.ui.AppMain</mainClass>
                  <addDependencies>false</addDependencies>
                  <preCp>anything</preCp>
                </classPath>
                <jre>
                  <path>jre</path>
                  <minVersion>1.8.0</minVersion>
                  <runtimeBits>32</runtimeBits>
                  <initialHeapSize>64</initialHeapSize>
                  <maxHeapSize>128</maxHeapSize>
                </jre>
                <versionInfo>
                  <fileVersion>${global.generation}.${global.build}</fileVersion>
                  <txtFileVersion>${global.version}</txtFileVersion>
                  <fileDescription>osumer2 UI</fileDescription>
                  <copyright>Copyright (c) 2019 mob41</copyright>
                  <productVersion>${global.generation}.${global.build}</productVersion>
                  <txtProductVersion>${global.version}</txtProductVersion>
                  <productName>osumer2 UI</productName>
                  <internalName>osumer-ui</internalName>
                  <originalFilename>osumer-ui.exe</originalFilename>
                </versionInfo>
              </configuration>
            </execution>
          </executions>
        </plugin>
    </plugins>
  </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
$(function () {
    //TODO get from url
    var deployment = 'network-config';
    var pathname = window.location.pathname; // Returns path only
    // init socket.io
    var socket = io.connect({path:'/posm-admin/socket.io'});
    var subTasks = ['wpa', 'wpa-passphrase', 'network-mode', 'ssid'];

    // get deployment status on page load
    POSM.deployment.updateDeploymentStatus(function(status){
        if(typeof status[deployment].msg === "string"){
            updateSupportMessage(status[deployment].msg);
        }

        showProgressSpinner(status[deployment]);
        updateDeploySubNav(status[deployment]);
        addTextFieldOnClickEvents(status[deployment]);
    });

    $('#action-btn').click(function (evt) {
        var cfg = getSelectedNetworkConfig();
        var value = getConfigValue(cfg);

        if(typeof value === 'string' && typeof cfg === 'string') {
            $.post('/posm-admin/network-config/' + cfg + '?value=' + value)
                .done(function (data) {

                    $('#snackbar').get(0).MaterialSnackbar.showSnackbar({
                        message: data.msg,
                        timeout: 3000,
                        actionText: 'Cancel'
                    });
                })
                .error(function (err) {
                    $('#snackbar').get(0).MaterialSnackbar.showSnackbar({
                        message: JSON.parse(err.responseText).msg,
                        timeout: 3000
                    });

                    updateSupportMessage(JSON.parse(err.responseText).msg);
                    POSM.updateNavBarStatusIcon(null, 'error_outline');

                });
        } else {
            var errorMsg = typeof value === "undefined" ? 'Please Toggle Captive/Bridge Switch' : 'Please select the radio button corresponding to your Network Config change';
            $('#snackbar').get(0).MaterialSnackbar.showSnackbar({
                message: errorMsg,
                timeout: 4000,
                actionText: 'Cancel'
            });
        }
        evt.preventDefault();
    });

    // process network/captive toggle
    $('#network-mode-switch').click(function (evt){
        setNetworkMode();
    });

    // listen for stdout on posm
    socket.on('network-config', function (iomsg) {
        // handles progress spinner
        showProgressSpinner(iomsg.status);
        updateDeploySubNav(iomsg.status);
        POSM.deployment.updateDeploymentStatus();

        // in progress
        if(iomsg.status.initialized){
            updateSupportMessage(iomsg.status.msg);
            // updateDeploySubNav(iomsg.status);
            POSM.updateNavBarStatusIcon('initialized');
            updateDeploySubNav(iomsg.status);
        }

        if (iomsg.output) {
            if(iomsg.status.error){
                // red console text on error
                var span = $('<span />').addClass("msg-error").html(iomsg.output);
                $('#console').append(span);
            } else {
                $('#console').append(iomsg.output);
            }
            // keep scroll at bottom of console output
            var d = $('#console');
            d.scrollTop(d.prop("scrollHeight") + 45);
            //updateDeploySubNav(iomsg.status);
        }
        // done
        if (iomsg.status.complete) {
            // update status
            POSM.deployment.updateDeploymentStatus();
            // false means the scripts exited without trouble
            if (!iomsg.status.error) {
                updateSupportMessage('The full deployment script has been executed.');
                POSM.updateNavBarStatusIcon('complete');
                updateDeploySubNav(iomsg.status);

            } else {
                updateSupportMessage('There was a problem with fetching and unpacking the HOT Export tar.gz.');
                POSM.updateNavBarStatusIcon(null,'error');
            }
        }

    });

    // hide spinner and disable action button
    function showProgressSpinner (status) {
        var initializedTask = getSelectedNetworkConfig();

        // loop through sub tasks
        subTasks.forEach(function(task){
            if(status[task]) {
                if (status[task].initialized === true) {
                    initializedTask = task;
                    $("#network-config-progress-spinner").show();
                    // disable start button
                    $("#action-btn").prop("disabled", true);
                }
                if ((typeof initializedTask === "string" && status[initializedTask].complete) || typeof initializedTask === "undefined") {
                    $("#network-config-progress-spinner").hide();
                    $("#action-btn").prop("disabled", false);
                }
            } else {
                $("#network-config-progress-spinner").hide();
                $("#action-btn").prop("disabled", false);
            }
        })
    }

    // update status message above url input
    function updateSupportMessage (text) {
        $('#supporting-msg-txt').html(text);
    }

    // update deploy sub scripts icons
    function updateDeploySubNav (status, selector){

        $(":radio").each(function(index,value){
            var id = value.id;
            $(".sub-task").each(function(index,value){
                // skip wifi bridge switch
                if(index !== 0) {
                    var icon = value.children[0];
                    var inputId = value.children[1].id.replace("-textfield", "");

                    if (status[id] && inputId == id) {
                        var iconType;

                        if (status[id].error) iconType = 'error_outline';
                        if (status[id].initialized) iconType = 'compare_arrows';
                        if (status[id].complete) iconType = 'check_circle';

                        $(icon).text(iconType);
                    }
                }
            })
        });
    }

    // get selected radio button, return config name
    function getSelectedNetworkConfig() {
        var checkedRadio;

        $(":radio").each(function (index, value) {
            if ($(value).parent().hasClass("is-checked")) {
                checkedRadio = value.id;
            }
        });

        return checkedRadio;
    }

    // get selected radio button, return config name
    function getNetworkMode() {
        var networkMode;

        $(":checkbox").each(function (index, value) {
            if ($(value).parent().hasClass("is-checked")) {
                networkMode = 'Bridge';
            } else {
                networkMode = 'Captive';
            }
        });

        return networkMode;
    }

    function setNetworkMode() {
        var networkMode;

        $(":checkbox").each(function (index, value) {
            // is-checked class is not appended so assign opposite valu
            if ($(value).parent().hasClass("is-checked")) {
                networkMode = 'Captive';
            } else {
                networkMode = 'Bridge';
            }
        });

        $('.mdl-switch__label').html(networkMode);
    }

    function getConfigValue(cfg){
        var value;

        if(cfg === 'wpa' || cfg === 'wpa-passphrase' || cfg === 'ssid'){
            value = $('#' + cfg + '-textfield').val();
        } else if (cfg === 'network-mode') {
            value = ($('.mdl-switch__label').html() == 'Bridge/Captive') ? undefined : getNetworkMode().toLowerCase();
        }

        return value;
    }

    // select radio button on text input click
    function addTextFieldOnClickEvents(status) {

        subTasks.forEach(function(task){
            var value = status[task].value;
            if(task !== 'network-mode'){
                $('#' + task + '-textfield').click(function(){
                    // find the corresponding radio button and check
                    $(":radio").each(function (index, value) {
                        if (value.id === task) {
                            $(value).parent().addClass("is-checked");
                        } else {
                            $(value).parent().removeClass("is-checked");
                        }

                    })
                })
            }

            if (typeof value === 'string'){
                $('#' + task + '-textfield').val(value);
                $('#' + task + '-textfield-label').html('');
            }
        })

    }
});


text:
<resources>
    <string name="app_name">NavigationDrawer</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="nav_header_title">Navigation Drawer Example</string>
</resources>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2008-2020, Hazelcast, Inc. All Rights Reserved.
  ~
  ~ 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>
    <name>hazelcast-jet-spring</name>
    <description>Spring integration for Hazelcast Jet</description>
    <url>http://www.hazelcast.com/</url>

    <artifactId>hazelcast-jet-spring</artifactId>

    <parent>
        <groupId>com.hazelcast.jet</groupId>
        <artifactId>hazelcast-jet-root</artifactId>
        <version>4.4-SNAPSHOT</version>
    </parent>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifestEntries>
                            <Automatic-Module-Name>com.hazelcast.jet.spring</Automatic-Module-Name>
                        </manifestEntries>
                    </archive>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <createSourcesJar>true</createSourcesJar>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                    <transformers>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.handlers</resource>
                        </transformer>
                        <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                            <resource>META-INF/spring.schemas</resource>
                        </transformer>
                    </transformers>
                    <artifactSet>
                        <includes>
                            <include>com.hazelcast:hazelcast-spring</include>
                        </includes>
                    </artifactSet>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>com.hazelcast.jet</groupId>
            <artifactId>hazelcast-jet</artifactId>
            <version>${project.parent.version}</version>
        </dependency>
        <dependency>
            <groupId>com.hazelcast</groupId>
            <artifactId>hazelcast-spring</artifactId>
            <version>${hazelcast.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.hazelcast.jet</groupId>
            <artifactId>hazelcast-jet-core</artifactId>
            <version>${project.parent.version}</version>
            <classifier>tests</classifier>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
turb
====

Turb is a new web app and mobile platform  which notify users about new trends


text:
def acct_groups(list_of_names)
  new_list = list_of_names.sort.shuffle.each_slice(4).to_a
  if new_list[-1].length < 3
    (new_list[-1] << new_list[-2]).flatten!
  end
  new_list
end

def remove_person(list_of_names, string_person)
  list_of_names.delete(string_person)
end

def add_person(list_of_names, string_person)
  list_of_names.push(string_person)
end

#Driver Code
names = ["Nathan Luo", "Kim Allen","Jenna Andersen", "Pamela Antonow", "Jupiter Baudot", "Ovi Calvo", "Awilda Cantres", "Celeste Carter", "Mike Cerrone", "Eunice Choi","Un Choi", "Kristie Chow", "Regina Compton", "Marcus Davis", "Paul Etscheit", "Solomon Fernandez", "Marcel Galang", "Aurelio Garcia", "Hector Jair Moreno Gomez", "Ricky Binhai Hu", "Kai Huang", "Alex Jamar", "Harmin Jeong", "Lauren Jin", "CJ Joulain", "Michael Landon", "Richard Leo", "Julian Lesse", "Ryan Lesson", "Ian Lockwood", "Christopher Mark", "Lauren Markzon", "Miguel Angel Melendez", "David OKeefe", "Nathan Park", "Landey Patton", "Farman Pirzada", "Samuel Frederick Purcell", "Salim Rahimi", "Colin Razevich", "Irina Renteria", "Jamie Runyan", "Eric Shou", "Michael Silberstein", "Rosslyn Sinclair-Chin", "Aji Slater", "Marvy Tagala", "George Warnbold", "Shawn Watson", "Hana Worku", "Nicholas Yee"]
remove_person(names, "Ryan Lesson")
remove_person(names, "Solomon Fernandez")
add_person(names, "Ryan Leston")
p acct_groups(names)

# 4. Reflection
#
# What was the most interesting and most difficult part of this challenge?
# => The most difficult part of this challenge was accounting for people leaving the cohort.  What would happen to the groups
# Do you feel you are improving in your ability to write pseudocode and break the problem down?
# => Yes! Although I didn't demonstrate that this time around.
# Was your approach for automating this task a good solution? What could have made it even better?
# => I think so, I provided that if the last group is less than 3 students, add them to the gorup just before that.
# => I think there is more I could have done, I wanted to make sure each group was sorted with at least one member
# => from each location (san-fran, chi-town, big-apple) but that would have taken way longer!
# What data structure did you decide to store the accountability groups in and why?
# => Just an array of arrays...
# What did you learn in the process of refactoring your initial solution? Did you learn any new Ruby methods?
# => As you can see, I made many improvements to the sorting and provided so that no one was alone.


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

class BrandonsGift extends DrawCard {
    setupCardAbilities(ability) {
        this.reaction({
            when: {
                onCardEntersPlay: event => (
                    event.card.controller === this.controller &&
                    event.playingType === 'marshal' &&
                    event.card.hasTrait('Builder') &&
                    event.card.getType() === 'character')

            },
            limit: ability.limit.perPhase(3),
            handler: () => {
                this.untilEndOfPhase(ability => ({
                    targetController: 'current',
                    effect: ability.effects.reduceNextMarshalledCardCost(1, card => card.isFaction('thenightswatch'))
                }));

                this.game.addMessage('{0} uses {1} to reduce the cost of the next {2} card they marshal this phase by 1',
                    this.controller, this, 'thenightswatch');
            }
        });
    }
}

BrandonsGift.code = '02026';

module.exports = BrandonsGift;


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Classes</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen">
<link rel="stylesheet" href="print.css" type="text/css" media="print">

Tweensy Original	All Packages | Index | FramesNo Frames

All Classes

Documentation for classes includes syntax, usage information, and code samples for methods, properties, and event handlers and listeners for those APIs that belong to a specific class in ActionScript. The classes are listed alphabetically. If you are not sure to which class a certain method or property belongs, you can look it up in the Index.

 	Class	Package	Description

 	AbstractTween

	com.flashdynamix.motion.plugins
  This abstract tween class provides necessary functionality to the typed plugin
  tweens.

 	Back

	fl.motion.easing
  The Back class defines three easing functions to implement
  motion with ActionScript animations.

 	BackEaseParams

	com.flashdynamix.motion.easing
  Ease params designed specifically for use with the Back ease equation.

 	Bezier2D

	com.flashdynamix.motion.guides
  Allows for Objects to follow a 2D bezier path.

 	Bounce

	fl.motion.easing
  The Bounce class defines three easing functions to implement
  bouncing motion with ActionScript animation, similar to a ball
  falling and bouncing on a floor with several decaying rebounds.

 	Circular

	fl.motion.easing
  The Circular class defines three easing functions to implement
  motion with ActionScript animation.

 	ColorMatrix

	com.flashdynamix.motion.extras
  Has methods that provide enhancements to assist with applying ColorMatrixFilter effects to DisplayObjects.

  These methods include :

brightness

saturation

hue

threshold

colorize

contrast

 	ColorTween

	com.flashdynamix.motion.plugins
  This plugin will be used when tweening ColorTransforms.

 	Cubic

	fl.motion.easing
  The Cubic class defines three easing functions to implement
  motion with ActionScript animation.

 	CustomEasing

	com.flashdynamix.motion.easing
  The CustomEasing Class allows for you to create your own custom ease equations

  'precalculated' allows for an Array of precalculated points describing an ease equation.

  'curve' allows for a bezier curve describing an ease eequation.

 	Direction2D

	com.flashdynamix.motion.guides
  Allows for Objects to follow a 2D directional path.

 	DisplayTween

	com.flashdynamix.motion.plugins
  This plugin will be used when tweening DisplayObjects.

 	Elastic

	fl.motion.easing
  The Elastic class defines three easing functions to implement
  motion with ActionScript animation, where the motion is defined by
  an exponentially decaying sine wave.

 	ElasticEaseParams

	com.flashdynamix.motion.easing
  Ease params designed specifically for use with the Elastic ease equation.

 	Exponential

	fl.motion.easing
  The Exponential class defines three easing functions to implement
  motion with ActionScript animation.

 	FilterTween

	com.flashdynamix.motion.plugins
  This plugin will be used when tweening BitmapFilters.

 	Linear

	fl.motion.easing
 The Linear class defines easing functions to implement
 non-accelerated motion with ActionScript animations.

 	MatrixTransform

	com.flashdynamix.motion.extras

 	MatrixTween

	com.flashdynamix.motion.plugins
  This plugin will be used when tweening Matrices.

 	MovieClipTween

	com.flashdynamix.motion.plugins
  This plugin will be used when tweening MovieClips.

  This plugin also provides additional functionality to allow for tweening the currentFrame in a MovieClip.

 	MultiTypeObjectPool

	com.flashdynamix.utils

 	ObjectPool

	com.flashdynamix.utils

 	ObjectTween

	com.flashdynamix.motion.plugins
  This plugin is the default plugin and will be used when tweening Objects which don't have a custom plugin.

 	Orbit2D

	com.flashdynamix.motion.guides
  Allows for Objects to follow a 2D orbit path.

  This path is defined by a radiusX/radiusX and centerX/centerY.

 	Quadratic

	fl.motion.easing
  The Quadratic class defines three easing functions to implement
  accelerated motion with ActionScript animations.

 	Quartic

	fl.motion.easing
  The Quartic class defines three easing functions to implement
  motion with ActionScript animation.

 	Quintic

	fl.motion.easing
  The Quintic class defines three easing functions to implement
  motion with ActionScript animation.

 	Sine

	fl.motion.easing
  The Sine class defines three easing functions to implement
  motion with ActionScript animation.

 	SoundTween

	com.flashdynamix.motion.plugins
  This plugin will be used when tweening SoundTransforms.

 	SWFProfiler

	com.flashdynamix.utils
  The SWFProfiler is a degugging tool which allows for monitoring the amount of memory and the frame rate of a SWF.

 	Tweensy

	com.flashdynamix.motion
  The Tweensy Class contains a collection of tweens specified by property tweens for an Object instance.

 	TweensyGroup

	com.flashdynamix.motion
  The TweensyGroup Class contains a collection of tweens specified by property tweens for an Object instance.

 	TweensyPluginList

	com.flashdynamix.motion.plugins

 	TweensySequence

	com.flashdynamix.motion
  TweensySequence Class allows for complex animations which occur one after another.

 	TweensyTimeline

	com.flashdynamix.motion
  TweensyTimeline groups instances of tweens which are animating for the same duration.


text:
package edu.ucsb.cs56.w15.drawings.emorozova.advanced;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class AnimatedPictureViewer {

    private DrawPanel panel = new DrawPanel();

    Thread anim;

    private int x = 200;
    private int y = 200;

    private int x2 = 200;
    private int y2 = 200;

    private int dx = 5;

    public static void main (String[] args) {
      new AnimatedPictureViewer().go();
    }

    public void go() {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      frame.getContentPane().add(panel);
      frame.setSize(640,480);
      frame.setVisible(true);

      frame.getContentPane().addMouseListener(new MouseAdapter() {
        public void mouseEntered(MouseEvent e){
        System.out.println("mouse entered");
          anim = new Animation();
          anim.start();
        }

        public void mouseExited(MouseEvent e){
          System.out.println("Mouse exited");
          // Kill the animation thread
          anim.interrupt();
          while (anim.isAlive()){}
          anim = null;
          panel.repaint();
        }
      });

    } // go()

    class DrawPanel extends JPanel {
       public void paintComponent(Graphics g) {

        Graphics2D g2 = (Graphics2D) g;

         // Clear the panel first
          g2.setColor(Color.white);
          g2.fillRect(0,0,this.getWidth(), this.getHeight());

          // Draw the Ipod
          g2.setColor(Color.black);
          StripedLighthouse test = new StripedLighthouse(100, 200, 70, 160);
          g2.draw(test);

	  // Draw wave
	  g2.setColor(Color.blue);
	  Wave w = new Wave(x + 20, y-20, 350, 20);
	  g2.draw(w);

	  Wave w2 = new Wave(x2, y2-10, 350, 20);
	  g2.draw(w2);

	  Wave w3 = new Wave(x+20, y, 350, 20);
	  g2.draw(w3);
       }
    }

    class Animation extends Thread {
      public void run() {
        try {
          while (true) {
            // Bounce off the walls

	       if (x >= 200) { dx = -1; }
	       if (x <= 150) { dx = 1; }

	       x += dx;
	       x2 += (-1*dx);

            panel.repaint();
            Thread.sleep(50);
          }
        } catch(Exception ex) {
          if (ex instanceof InterruptedException) {
            // Do nothing - expected on mouseExited
          } else {
            ex.printStackTrace();
            System.exit(1);
          }
        }
      }
    }

}


text:
var fs            = require('fs');
var path          = require('path');
var filterImports = require('babel-plugin-filter-imports');
var featureFlags  = require('babel-plugin-feature-flags');
var babelBuild    = require('./babel-build');
var strippedBuildPlugins = require('./stripped-build-plugins');

module.exports = function(packageName, tree, environmentBuildingFor) {
  var options = strippedBuildPlugins(environmentBuildingFor);

  return babelBuild(packageName, tree, options);
};


text:
package org.apache.hadoop.security;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import org.apache.hadoop.util.NativeCodeLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JniBasedUnixGroupsNetgroupMappingWithFallback implements
    GroupMappingServiceProvider {

  private static final Logger LOG = LoggerFactory
      .getLogger(JniBasedUnixGroupsNetgroupMappingWithFallback.class);

  private GroupMappingServiceProvider impl;

  public JniBasedUnixGroupsNetgroupMappingWithFallback() {
    if (NativeCodeLoader.isNativeCodeLoaded()) {
      this.impl = new JniBasedUnixGroupsNetgroupMapping();
    } else {
      LOG.info("Falling back to shell based");
      this.impl = new ShellBasedUnixGroupsNetgroupMapping();
    }
    if (LOG.isDebugEnabled()) {
      LOG.debug("Group mapping impl=" + impl.getClass().getName());
    }
  }

  @Override
  public List<String> getGroups(String user) throws IOException {
    return impl.getGroups(user);
  }

  @Override
  public void cacheGroupsRefresh() throws IOException {
    impl.cacheGroupsRefresh();
  }

  @Override
  public void cacheGroupsAdd(List<String> groups) throws IOException {
    impl.cacheGroupsAdd(groups);
  }

  @Override
  public Set<String> getGroupsSet(String user) throws IOException {
    return impl.getGroupsSet(user);
  }

}


text:
package org.apache.hive.service.cli;

import org.apache.hadoop.hive.common.log.ProgressMonitor;

import java.util.List;

public class JobProgressUpdate {
  public final double progressedPercentage;
  public final String footerSummary;
  public final long startTimeMillis;
  private final List<String> headers;
  private final List<List<String>> rows;
  public final String status;

  JobProgressUpdate(ProgressMonitor monitor) {
    this(monitor.headers(), monitor.rows(), monitor.footerSummary(), monitor.progressedPercentage(),
        monitor.startTime(), monitor.executionStatus());
  }

  private JobProgressUpdate(List<String> headers, List<List<String>> rows, String footerSummary,
      double progressedPercentage, long startTimeMillis, String status) {
    this.progressedPercentage = progressedPercentage;
    this.footerSummary = footerSummary;
    this.startTimeMillis = startTimeMillis;
    this.headers = headers;
    this.rows = rows;
    this.status = status;
  }

  public List<String> headers() {
    return headers;
  }

  public List<List<String>> rows() {
    return rows;
  }
}


text:
package com.freshdigitable.udonroad;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.content.res.AppCompatResources;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;

/**
 * IconAttachedTextView shows text with icon at first.
 *
 * Created by akihit on 2016/12/15.
 */

public class IconAttachedTextView extends AppCompatTextView {

  public IconAttachedTextView(Context context) {
    this(context, null);
  }

  public IconAttachedTextView(Context context, AttributeSet attrs) {
    this(context, attrs, R.attr.iconAttachedTextViewStyle);
  }

  public IconAttachedTextView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    final TypedArray a = context.obtainStyledAttributes(attrs,
        R.styleable.IconAttachedTextView, defStyleAttr, R.style.Widget_IconAttachedTextView);
    try {
      int iconRes = a.getResourceId(R.styleable.IconAttachedTextView_icon, -1);
      final Drawable icon = iconRes > 0 ? AppCompatResources.getDrawable(context, iconRes)
          : a.getDrawable(R.styleable.IconAttachedTextView_icon);
      final int iconColor = a.getColor(R.styleable.IconAttachedTextView_tintIcon, NO_ID);
      setIcon(icon, iconColor);
    } finally {
      a.recycle();
    }
  }

  public void setIcon(@DrawableRes int icon) {
    setIcon(AppCompatResources.getDrawable(getContext(), icon), NO_ID);
  }

  public void setIcon(Drawable icon, int iconColor) {
    if (icon != null) {
      icon = icon.mutate();
      final int width
          = icon.getIntrinsicWidth() * getLineHeight() / icon.getIntrinsicHeight();
      icon.setBounds(0, 0, width, getLineHeight());
      if (iconColor != NO_ID) {
        DrawableCompat.setTint(icon, iconColor);
      }
      setCompoundDrawables(icon, null, null, null);
    }
  }

  public void tintIcon(@ColorRes int colorRes) {
    for (Drawable d : getCompoundDrawables()) {
      if (d == null) {
        continue;
      }
      DrawableCompat.setTint(d, ContextCompat.getColor(getContext(), colorRes));
    }
  }
}


text:
<?php
/*
Plugin Name: WP Migrate DB Pro Media Files
Plugin URI: http://deliciousbrains.com/wp-migrate-db-pro/
Description: An extension to WP Migrate DB Pro, allows the migration of media files.
Author: Delicious Brains
Version: 1.1.1
Author URI: http://deliciousbrains.com
*/

// Copyright (c) 2013 Delicious Brains. All rights reserved.
//
// Released under the GPL license
// http://www.opensource.org/licenses/gpl-license.php
//
// **********************************************************************
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// **********************************************************************

function wp_migrate_db_pro_media_files_init() {
	if ( ! is_admin() || ! class_exists( 'WPMDBPro_Addon' ) ) return;

	require_once 'class/wpmdbpro-media-files.php';

	global $wpmdbpro_media_files;
	$wpmdbpro_media_files = new WPMDBPro_Media_Files( __FILE__ );
}

add_action( 'admin_init', 'wp_migrate_db_pro_media_files_init' );


text:
Package.describe({
  name: 'mixmax:underscore-updates',
  version: '0.2.3',
  summary: 'Extend Meteor\'s Underscore with selected methods from the latest standard version.',
  git: 'https://github.com/mixmaxhq/meteor-underscore-updates',
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.versionsFrom('1.1.0.2');
  api.use('underscore');
  api.imply('underscore');
  api.addFiles('underscore-updates.js');
});


text:
module DeeplyValid

  #
  # The Validation lets us define validations using
  # several different kinds of rules.
  #
  class Validation

    attr_accessor :options

    #
    # The initializer defines the conditions that will
    # satasfy this validation.
    #
    # @param [Regexp] rule    When `rule` is a `Regexp` we use `=~` to validate
    # @param [Hash]   rule    When `rule` is a `Hash`, then `valid_structure?` does the validation
    # @param [Object] rule    When `rule` is any other non-nil object, use `==` to validate
    # @param [Proc]   &block  An optional block, which will take one param and return true or false
    #
    def initialize(rule = nil, options = {}, &block)

      if rule.nil? && !block_given?
        raise "No validation rule specified"
      end

      @options = options
      @rule = rule
      @block = block
    end

    #
    # Validate data by regexp
    #
    # @param [String] String to be validated
    #
    def valid_pattern?(data)
      !!(data =~ @rule)
    end

    #
    # Recursively validate a complex data structure
    # For now, only hashes are supported.
    #
    # == Example Rules:
    #
    #   { :key => /regexp/ }
    #   { :key => Validation.new { |d| d > 20 } }
    #   { :key => "literal" }
    #   { :key => { :key2 => /regexp/ }, :key2 => "literal" }
    #
    # As you see, rules can be nested arbitrarily deep.
    # The validaions work like you would expect.
    #
    #   { :key => /[a-z]+/ } will validate { :key => "a" }
    #   { :key => /[a-z]+/ } will NOT validate { :key => 123 }
    #
    # @param [Hash] Hash fragment to be validated
    # @param [Hash] Optional rules for validating hash fragment
    # @return true if valid, false if invalid
    #
    def valid_structure?(data, fragment_rule = nil)
      (fragment_rule || @rule).all? do |k, v|

        v = v.call(@data) if v.is_a?(Proc)

        if v.is_a?(Validation)
          (v.options[:optional] && !data.has_key?(k)) || v.valid?(data[k])

        elsif v.is_a?(Regexp)
          !!(data[k] =~ v)

        elsif v.is_a?(Hash)
          valid_structure?(data[k], v)

        elsif v.nil?
          !data.has_key?(k)

        else
          data[k] == v
        end
      end
    end

    #
    # Validate data of any rule type.
    #
    # @param [Object] data the data to be validated
    # @return true if valid, false if invalid
    #
    def valid?(data)

      @data = data

      rule = @rule.is_a?(Proc) ? @rule.call(@data) : @rule

      result = if rule.kind_of?(Regexp)
        valid_pattern?(data)

      elsif rule.kind_of?(Validation)
        rule.valid?(data)

      elsif rule.kind_of?(Hash)
        valid_structure?(data)

      elsif @block
        @block.call(data)

      else
        data == @rule
      end

      @data = nil

      result

    end

  end

end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Herzogia 5(1-2): 56 (1979)

#### Original name
Buellia catawbensis Willey

### Remarks
null


text:
<title>DOM tests -- CSS2 interface</title>

This is caption a

Text inside table a

This is caption b

Text inside table b

This is caption c

Text inside table c


text:
<?php

use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
use Prajna\Prajna;

$app = new Application();

// mount controller dynamically
$controllers = array(
	'acmpolicy'      => function(){return new Bacharu\Controllers\ACMPolicy();},
	'console'        => function(){return new Bacharu\Controllers\Console();},
	'crashdump'      => function(){return new Bacharu\Controllers\CrashDump();},
	'debug'          => function(){return new Bacharu\Controllers\Debug();},
	'dpci'           => function(){return new Bacharu\Controllers\DPCI();},
	'event'          => function(){return new Bacharu\Controllers\Event();},
	'host'           => function(){return new Bacharu\Controllers\Host();},
	'hostcpu'        => function(){return new Bacharu\Controllers\HostCpu();},
	'hostmetrics'    => function(){return new Bacharu\Controllers\HostMetrics();},
	'network'        => function(){return new Bacharu\Controllers\Network();},
	'pbd'            => function(){return new Bacharu\Controllers\PBD();},
	'pif'            => function(){return new Bacharu\Controllers\PIF();},
	'pifmetrics'     => function(){return new Bacharu\Controllers\PIFMetrics();},
	'ppci'           => function(){return new Bacharu\Controllers\PPCI();},
	'sr'             => function(){return new Bacharu\Controllers\SR();},
	'task'           => function(){return new Bacharu\Controllers\Task();},
	'user'           => function(){return new Bacharu\Controllers\User();},
	'vbd'            => function(){return new Bacharu\Controllers\VBD();},
	'vbdmetrics'     => function(){return new Bacharu\Controllers\VBDMetrics();},
	'vdi'            => function(){return new Bacharu\Controllers\VDI();},
	'vif'            => function(){return new Bacharu\Controllers\VIF();},
	'vifmetrics'     => function(){return new Bacharu\Controllers\VIFMetrics();},
	'vm'             => function(){return new Bacharu\Controllers\VM();},
	'vmguestmetrics' => function(){return new Bacharu\Controllers\VMGuestMetrics();},
	'vmmetrics'      => function(){return new Bacharu\Controllers\VMMetrics();},
	'vtpm'           => function(){return new Bacharu\Controllers\VTPM();},
	'xspolicy'       => function(){return new Bacharu\Controllers\XSPolicy();},
	''               => function(){return new Bacharu\Controllers\Misc();}
);

list(,$basepath) = explode('/',parse_url($_SERVER['REQUEST_URI'],PHP_URL_PATH));
if(isset($controllers[$basepath])){
	$app->mount('/'.$basepath, $controllers[$basepath]());
}
else{
	error_log(__FILE__.' Invalid Path.  No controller matches.');
	$app->abort(404, 'Not Found');
}

$app->register(new Silex\Provider\SessionServiceProvider());

// configure hooks
$app->before(function () use($app) {
	$app['twig'] = function(){
		return getTwig();
	};
	$app['config'] = parse_ini_file(__DIR__.'/config/config.ini',true);
	$app['response'] = new Response();
	if($Prajna = $app['session']->get('PrajnaSession')){
		$app['prajna'] = unserialize($Prajna);
	}
	else{
		$app['prajna'] = function() use($app) {
			return new Prajna($app['config']['xapi']);
		};
	}
});

$app->after(function () use($app) {
	$app['session']->set('PrajnaSession',serialize($app['prajna']));
	error_log('MEMORY USAGE: '.(memory_get_usage(true)/1024/1024).'M');
});

$app->error(function (\Exception $e, $code) use($app) {
	$app['response']->setContent('blah');
	return $app['response'];
});


text:
This work is licensed under the Creative Commons CC0 License

---

# Refining of persistence as activity files
### xtUML Project Implementation Note

1. Abstract
-----------
While being pressed for time, the work for the new persistence mechanism was
promoted while not being completely finished. The remaining issues needed to
either be fixed or follow-on issues need to be raised. The code needs to be
cleaned up.

2. Document References
----------------------
2.1 [#8887 Clean up new persistence mechanism for activities](https://support.onefact.net/issues/8887) -- Parent issue
2.2 [#8917 Fully support persistence as activity files for OAL](https://support.onefact.net/issues/8917)
2.3 [#8918 Fix import parser in the io plugin](https://support.onefact.net/issues/8918)
2.4 [#8919 NumberFormatException when loading pre-dialect attribute models with proxies](https://support.onefact.net/issues/8919)
2.5 [#8920 Update Dialect attribute usage in the MC projects](https://support.onefact.net/issues/8920)

3. Background
-------------
Here are the issues that were present at the last promotion:

1. Different dialects were not supported. All activities were persisted into
  `.masl` files. This needed to be updated so that the persistence mechanism
  properly multiplexed/demultiplexed the activities into the right files based
  on the dialect at the activity granularity.
2. Not every type of activity is supported. Only the activities used by MASL
  are fully supported. Because of this, persistence as files will be limited to
  the MASL dialect
3. The import parser has problems that cause it to mishandle comments. The parser
  needs to be revisited to avoid action language corruption.
4. Default dialect behavior was half-baked. New activities were dialect-less,
  editor selecting code was broken. This needed to be changed so that at
  creation, activities were given the default dialect, and then the editor is
  chosen based on the dialect of the selected activity.
5. Dialect strings were floating around the source code. The available dialects
  needed to be gathered into one location (enumeration). This also allows
  dialect setting through the "Properties" view to be a drop-down menu and not a
  free form text field.
6. `ActionFile`, `ImportFactory`, and `ExportFactory` classes had outdated APIs
  that assume dialect is at the PMC (package, component, class) granularity.
  These APIs needed to be cleaned up.

4. Requirements
---------------
4.1 Activity dialect
4.1.1 Activity dialect shall be settable via drop-down menu in the "Properties"
view
4.1.2 Activity dialect shall be set to the default when a new activity is
created
4.1.3 Activity dialects shall be maintained in one place
4.1.3.1 An xtUML enumeration type shall be created for this purpose
4.1.3.2 All references to hard coded string values for dialect shall be
removed/replaced

4.2 Persistence of files
4.2.1 Activities with different dialects shall be persisted in different files
marked by `.<dialect>` extension
4.2.2 Activities shall be parsed from many files
4.2.3 Parsed activities shall be assigned their dialect based on the file they
are parsed from
4.2.4 Activities containing co-existing action language in multiple dialects
shall not be supported in persistence
4.2.5 A restriction shall be added to limit this persistence to the MASL dialect
only

4.3 Sufficient code cleanup shall be done in the persistence change
4.4 Issues shall be raised for problems not addressed in this changeset

5. Work Required
----------------
5.1 An enumerated type `ActionDialect` was added to the OOA of OOA. Enumerators
`oal` and `masl` were introduced.
5.2 Each class with the `Dialect` attribute was updated for the type to be
`ActionDialect`. The schema was updated in MC-Java accordingly.
5.2 Changed the type in all the preferences code to match the new type of the
action dialect.
5.3 Added code to the initializers of classes with `Dialect` attributes so that
the dialect is set to the default preference on creation.
5.4 Updated import and export classes to persist and import from different
dialect files.
5.5 Cleaned up the `ActionFile` class with the new changes.
5.6 Updated references to the changed APIs across the code base.
5.7 Added a restriction to only let MASL files be imported and persisted as
files.

6. Implementation Comments
--------------------------

6.1 It may seem as though requirement 4.2.5 contradicts the rest of 4.2. Why
would the implementation be able to read and write to many different dialect
files if we are simply going to restrict it to one anyway. The reason is because
the restriction is meant to be a temporary safeguard. OAL activities are not
fully supported, so in the interest of making this a promotable change, the
restriction maintains OAL in the well tested persistence environment. When more
time/occasion arises to extend this work to fully support `.oal` files, the
infrastructure will be in place.

6.2 Remaining issues

6.2.1 As mentioned above, problem 2 in the "Background" section is not being handled
in this work. Issue #8917 [[2.2]](#2.2) is raised.

6.2.2 Problem 3 in the "Background" section is also not handled as part of this
work. Issue #8918 [[2.3]](#2.3) is raised.

6.2.3 During this work I uncovered another bug having to do with the import of
old models (pre dialect attribute) and the proxy objects of dialect-having
classes. I observed this first when loading the "GPS Watch" model. A
`NumberFormatException` is raised when loading a provided signal proxy because the proxy path is supposed to be the
dialect attribute and is parsed as an integer. I believe this bug was missed
before because dialect was a string also. Issue #8919 [[2.4]](#2.4) is raised.

6.2.4 Dialect attributes are still strings in the MC projects. m2x, masl, and
x2m need to update any references to dialect to match the enumeration in the
OOA of OOA. Issue #8920 [[2.5]](#2.5) has been raised.

7. Unit Test
------------

7.1 Create a test model.
7.2 Set the "Default Action Language Dialect" to OAL.
7.3 Create two functions in a new package. Verify that the dialect is OAL for
both in the Properties view.
7.4 Double click on one of the functions. Verify that the OAL editor is opened.
7.5 Edit both functions and save. Verify that the action language appears in
the `.xtuml` file in the workspace.
7.6 Use the drop-down menu in the Properties view to change the dialect of one
function to MASL. Verify that `<package_name>.masl` has been created in the
workspace and that the action language is correct.
7.7 Double click the function. Verify that the MASL editor is opened.
7.8 Switch to the Java perspective, close and reopen the project. Open both
functions and verify that the action language is correct.
7.9 Use the drop-down menu to change the other function to the MASL dialect.
Verify that both functions exist int the `<package_name>.masl` file and that all
action language is gone from the `.xtuml` file.
7.10 Set the "Default Action Language Dialect" to MASL.
7.11 Create a third function and verify that the dialect is MASL.

8. User Documentation
---------------------
None

9. Code Changes
---------------
Fork/Repository: leviathan747/bridgepoint
Branch: 8887_persistence_cleanup

 src/MC-Java/ooa_schema.sql                                                                                |  18 +++++++++---------
 src/org.xtuml.bp.cli/src/org/xtuml/bp/cli/MergeWorkbenchAdvisor.java                                                                             |   4 +---
 src/org.xtuml.bp.core/arc/create_core_plugin_class.arc                                                                                |   4 +---
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Component/Signal Provisions and Requirements/Provided Operation/Provided Operation.xtuml |  12 ++++++++++--
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Component/Signal Provisions and Requirements/Provided Signal/Provided Signal.xtuml       |  12 ++++++++++--
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Component/Signal Provisions and Requirements/Required Operation/Required Operation.xtuml |  12 ++++++++++--
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Component/Signal Provisions and Requirements/Required Signal/Required Signal.xtuml       |  12 ++++++++++--
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Datatypes/Datatypes.xtuml                                                                |  52 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Domain/Bridge/Bridge.xtuml                                                               |  10 +++++++++-
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Domain/Function/Function.xtuml                                                           |  10 +++++++++-
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/External Entities/External Entities.xtuml                                                |  30 ++++++++++++++++++++++++++++++
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Functions/import_functions/import_functions.xtuml                                        |  19 +++++++++++++------
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/State Machine/Action/Action.xtuml                                                        |   9 ++++++++-
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/State Machine/State Machine State/State Machine State.xtuml                              |   1 +
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/State Machine/Transition/Transition.xtuml                                                |   1 +
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Subsystem/Attribute/Attribute.xtuml                                                      |   1 +
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Subsystem/Derived Base Attribute/Derived Base Attribute.xtuml                            |   9 ++++++++-
 src/org.xtuml.bp.core/models/org.xtuml.bp.core/ooaofooa/Subsystem/Operation/Operation.xtuml                                                      |  10 +++++++++-
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/common/ActionFile.java                                                                               | 127 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/common/BridgePointPreferencesModel.java                                                              |   2 +-
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/common/BridgePointPreferencesStore.java                                                              |  12 +++++-------
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/common/ComponentResourceListener.java                                                                |   2 +-
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/common/PersistableModelComponent.java                                                                |  15 +++++++--------
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/common/PersistenceManager.java                                                                       |   2 +-
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/ui/AbstractModelExportFactory.java                                                                   |   7 +++----
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/ui/AbstractModelImportFactory.java                                                                   |   2 --
 src/org.xtuml.bp.core/src/org/xtuml/bp/core/ui/preferences/ActionLanguagePreferences.java                                                        |  11 ++++++-----
 src/org.xtuml.bp.io.core/arc/export_functions.inc                                                                                |  54 +++++++++++++++++++++++++++++++++++++++++++++++++-----
 src/org.xtuml.bp.io.core/arc/gen_export_java.inc                                                                                | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------------------------------------------------------
 src/org.xtuml.bp.io.core/arc/gen_import_java.inc                                                                                |  18 +++++++++---------
 src/org.xtuml.bp.io.core/src/org/xtuml/bp/io/core/CoreImport.java                                                                                |  18 ++++--------------
 src/org.xtuml.bp.io.core/src/org/xtuml/bp/io/core/actions.g                                                                                |   4 ++--
 src/org.xtuml.bp.io.mdl.test/src/IOMdlTestGenerics.java                                                                                |   6 +++---
 src/org.xtuml.bp.io.mdl/src/org/xtuml/bp/io/mdl/ExportModelFactory.java                                                                          |  12 +++++-------
 src/org.xtuml.bp.io.mdl/src/org/xtuml/bp/io/mdl/ImportModelFactory.java                                                                          |   4 ----
 src/org.xtuml.bp.model.compare.test/arc/generate_metamodel_compare_test.arc                                                                      |   2 ++
 src/org.xtuml.bp.model.compare/src/org/xtuml/bp/model/compare/contentmergeviewer/ModelContentMergeViewer.java                                    |   2 +-
 src/org.xtuml.bp.ui.canvas.test/src/org/xtuml/bp/ui/canvas/test/CanvasTest.java                                                                  |   2 +-
 src/org.xtuml.bp.ui.explorer/arc/create_explorer_view.inc                                                                                |  26 ++++++++------------------
 src/org.xtuml.bp.ui.properties.test/src/org/xtuml/bp/ui/properties/test/EnumRangeTest.java                                                       |   6 +++++-
 src/org.xtuml.bp.ui.text/src/org/xtuml/bp/ui/text/masl/MASLEditorInput.java                                                                      |  24 ------------------------
 src/org.xtuml.bp.ui.text/src/org/xtuml/bp/ui/text/masl/MASLEditorInputFactory.java                                                               |  34 +++++++++++++++++++++++++---------
 42 files changed, 469 insertions(+), 281 deletions(-)

End
---


text:
package edu.utah.further.fqe.ds.api.domain;

import static edu.utah.further.core.api.text.ToStringCustomStyles.SHORT_WITH_SPACES_STYLE;

import javax.xml.bind.annotation.XmlTransient;

import org.apache.commons.lang.builder.ToStringBuilder;

import edu.utah.further.core.api.context.DefaultImplementation;

/**
 * A base class of {@link ResultContext} implementations.
 *

 * -----------------------------------------------------------------------------------

 * (c) 2008-2013 FURTHeR Project, Health Sciences IT, University of Utah

 * Contact: {@code <further@utah.edu>}

 * Biomedical Informatics, 26 South 2000 East

 * Room 5775 HSEB, Salt Lake City, UT 84112

 * Day Phone: 1-801-581-4080

 * -----------------------------------------------------------------------------------
 *
 * @author Oren E. Livne {@code <oren.livne@utah.edu>}
 * @version Jun 4, 2010
 */
@DefaultImplementation(ResultContext.class)
@XmlTransient
public abstract class AbstractResultContext implements ResultContext
{
	// ========================= CONSTANTS =================================

	/**
	 * @serial Serializable version identifier.
	 */
	private static final long serialVersionUID = 1L;

	// ========================= FIELDS ====================================

	/**
	 * A convenient direct reference to this query's result set. Must be manually set on
	 * this object.
	 */
	@XmlTransient
	private Object result;

	// ========================= CONSTRUCTORS ==============================

	// ========================= IMPLEMENTATION: Object ====================

	/**
	 * @return
	 * @see edu.utah.further.fqe.ds.api.domain.ResultContext#toString()
	 */
	@Override
	public final String toString()
	{
		return new ToStringBuilder(this, SHORT_WITH_SPACES_STYLE)
				.append("id", getId())
				.append("rootEntityClass", getRootEntityClass())
				.append("transferObjectClass", getTransferObjectClass())
				.append("numRecords", getNumRecords())
				.toString();
	}

	// ========================= IMPLEMENTATION: ResultContext =============

	/**
	 * Return the raw query result type.
	 *
	 * @return the result
	 */
	@Override
	public Object getResult()
	{
		return result;
	}

	/**
	 * Set a new value for the entityList property.
	 *
	 * @param entityList
	 *            the entityList to set
	 */
	@Override
	public void setResult(final Object result)
	{
		this.result = result;
	}
}


text:
package com.baidu.bjf.remoting.protobuf.computeSize;

import com.baidu.bjf.remoting.protobuf.FieldType;
import com.baidu.bjf.remoting.protobuf.annotation.Protobuf;

import java.util.List;

/***
 *
 * 2021/11/8 10:16
 */
public class PackedListObject {

	@Protobuf(description = "object id list", fieldType = FieldType.SFIXED64)
	private List<Long> objectIds;

	public static PackedListObject valueOf(List<Long> objectIds){
		PackedListObject data = new PackedListObject();
		data.objectIds = objectIds;
		return data;
	}

	public List<Long> getObjectIds() {
		return objectIds;
	}

	public void setObjectIds(List<Long> objectIds) {
		this.objectIds = objectIds;
	}
}


text:
require 'spec_helper'

describe Redch::Config do
  let(:config) { { 'sos' => { 'a' => 'test' } } }
  let(:hashr_config) { Hashr.new(config) }
  let(:yaml_config) { hashr_config.to_hash.to_yaml }

  let(:file) { double 'file' }
  let(:filename) { Redch::Config.filename }

  before do
    allow(YAML).to receive(:load_file).and_return(config)
  end

  describe '#load' do
    before do
      allow(File).to receive(:write).with(config.to_yaml)
    end

    it 'returns a Hashr instance' do
      allow(File).to receive(:open).with(filename, 'r')
      expect(Redch::Config.load).to be_kind_of(Hashr)
    end

    it 'raises if file does not exist' do
      allow(File).to receive(:open).with(filename, 'r').and_raise(Errno::ENOENT)
      expect { Redch::Config.load }.to raise_error(Errno::ENOENT)
    end
  end

  describe '#save', :save => true do
    before do
      allow(File).to receive(:open).with(filename, 'w').and_yield(file)
    end

    it 'stores the passed configuration' do
      expect(file).to receive(:write).with(yaml_config)
      Redch::Config.save(hashr_config)
    end

    it 'overwrites the values of existing keys' do
      expect(file).to receive(:write).with(config.to_yaml)

      Redch::Config.save(config)
      config['sos']['a'] = 'new_test'

      expect(file).to receive(:write).with(config.to_yaml)

      Redch::Config.save(config)
    end
  end
end


text:
package org.lex.perf.engine;

import java.math.BigDecimal;

/**
* Created by Алексей on 29.03.2015.
*/
public class IndexEvent {

    public EngineIndex engineIndex;

    public long requestTime;

    public BigDecimal value;

    public final Duration own = new Duration();

    public final Duration[] childsDurations;

    public IndexEvent(int childsCount) {
        this.childsDurations = new Duration[childsCount];
        for (int i = 0; i < childsCount; i++) {
            childsDurations[i] = new Duration();
        }
    }
}


text:
package web.notifier;

import org.elasticsearch.metrics.JsonMetrics;
import org.elasticsearch.metrics.percolation.Notifier;

/**
 *
 */
public class SystemOutNotifier implements Notifier {

    @Override
    public void notify(JsonMetrics.JsonMetric jsonMetric, String id) {
        System.out.println(String.format("Metric %s of type %s at date %s matched with percolation id %s", jsonMetric.name(), jsonMetric.type(), jsonMetric.timestampAsDate(), id));
    }
}


text:
module('Canvas Profile Normal Test', {
  setup: function() {
    TEST_TIMEOUT = 60000;
    init();
  }, teardown: function() {
    var img = document.getElementById('images');
    img.style.visibility = 'hidden';
  }
});

/**
 * Canvasプロファイルの異常系テストを行うクラス。
 * @class
 */
var CanvasProfileNormalTest = {};

CanvasProfileNormalTest.draw = function(text) {
  var width = 120;
  var height = 120;
  var canvas =  document.getElementById('canvas');
  var context = canvas.getContext('2d');
  context.beginPath();
  context.clearRect(0, 0, width, height);
  context.fillStyle = '#ffffff';
  context.fillRect(0, 0, width, height);
  context.stroke();
  context.restore();
  context.save();

  context.beginPath();
  context.font = "18pt Arial";
  context.fillStyle = 'rgb(0, 0, 0)';
  for (var i = 0; i < 10; i++) {
    context.fillText(text, 10, (i + 1) * 20);
  }
  context.restore();
  context.save();

  canvas = canvas.toDataURL();
  var base64Data = canvas.split(',')[1];
  var data = window.atob(base64Data);
  var buff = new ArrayBuffer(data.length);
  var arr = new Uint8Array(buff);
  var blob, i, dataLen;
  for (i = 0, dataLen = data.length; i < dataLen; i++) {
      arr[i] = data.charCodeAt(i);
  }
  blob = new Blob([arr], {type: 'image/png'});
  return blob;
};

/**
 * デフォルトのモードでデバイスに画像表示するテストを行う。
 *
【HTTP通信】

 *

 * Method: POST

 * Path: /canvas/drawimage?serviceId=xxxx&accessToken=xxx

 *

 *
【期待する動作】

 *

 * ・resultに0が返ってくること。

 *

 */
CanvasProfileNormalTest.drawImageNormalTest001 = function(assert) {
  var img = document.getElementById('images');
  img.style.visibility = 'visible';

  var blob = CanvasProfileNormalTest.draw('drawImageNormalTest001');

  searchTestService(function(accessToken, serviceId) {
    var builder = new dConnect.URIBuilder();
    builder.setProfile(dConnect.constants.canvas.PROFILE_NAME);
    builder.setAttribute(dConnect.constants.canvas.ATTR_DRAWIMAGE);

    var formData = new FormData();
    formData.append('serviceId', serviceId);
    formData.append('accessToken', accessToken);
    formData.append('filename', 'test.png');
    formData.append('mimeType', 'image/png');
    formData.append('x', 0);
    formData.append('y', 0);
    formData.append('data', blob);

    var uri = builder.build();
    dConnect.post(uri, null, formData, function(json) {
      assert.ok(true, 'result=' + json.result);
      QUnit.start();
    }, function(errorCode, errorMessage) {
      assert.ok(checkErrorCode(errorCode), "errorCode=" + errorCode + ", errorMessage=" + errorMessage);
      QUnit.start();
    });
  }, function(errorCode, errorMessage) {
    assert.ok(false, 'errorCode=' + errorCode + ', errorMessage=' + errorMessage);
    QUnit.start();
  });
};
QUnit.asyncTest('drawImageNormalTest001(put)', CanvasProfileNormalTest.drawImageNormalTest001);

/**
 * scalesのモードでデバイスに画像表示するテストを行う。
 *
【HTTP通信】

 *

 * Method: POST

 * Path: /canvas/drawimage?serviceId=xxxx&accessToken=xxx

 *

 *
【期待する動作】

 *

 * ・resultに0が返ってくること。

 *

 */
CanvasProfileNormalTest.drawImageNormalTest002 = function(assert) {
  var img = document.getElementById('images');
  img.style.visibility = 'visible';

  var blob = CanvasProfileNormalTest.draw('drawImageNormalTest002');

  searchTestService(function(accessToken, serviceId) {
    var builder = new dConnect.URIBuilder();
    builder.setProfile(dConnect.constants.canvas.PROFILE_NAME);
    builder.setAttribute(dConnect.constants.canvas.ATTR_DRAWIMAGE);

    var formData = new FormData();
    formData.append('serviceId', serviceId);
    formData.append('accessToken', accessToken);
    formData.append('mode', 'scales');
    formData.append('filename', 'test.png');
    formData.append('mimeType', 'image/png');
    formData.append('x', 50);
    formData.append('y', 50);
    formData.append('data', blob);

    var uri = builder.build();
    dConnect.post(uri, null, formData, function(json) {
      assert.ok(true, 'result=' + json.result);
      QUnit.start();
    }, function(errorCode, errorMessage) {
      assert.ok(checkErrorCode(errorCode), "errorCode=" + errorCode + ", errorMessage=" + errorMessage);
      QUnit.start();
    });
  }, function(errorCode, errorMessage) {
    assert.ok(false, 'errorCode=' + errorCode + ', errorMessage=' + errorMessage);
    QUnit.start();
  });
};
QUnit.asyncTest('drawImageNormalTest002(mode is scales)', CanvasProfileNormalTest.drawImageNormalTest002);

/**
 * fillsのモードでデバイスに画像表示するテストを行う。
 *
【HTTP通信】

 *

 * Method: POST

 * Path: /canvas/drawimage?serviceId=xxxx&accessToken=xxx

 *

 *
【期待する動作】

 *

 * ・resultに0が返ってくること。

 *

 */
CanvasProfileNormalTest.drawImageNormalTest003 = function(assert) {
  var img = document.getElementById('images');
  img.style.visibility = 'visible';

  var blob = CanvasProfileNormalTest.draw('drawImageNormalTest003');

  searchTestService(function(accessToken, serviceId) {
    var builder = new dConnect.URIBuilder();
    builder.setProfile(dConnect.constants.canvas.PROFILE_NAME);
    builder.setAttribute(dConnect.constants.canvas.ATTR_DRAWIMAGE);

    var formData = new FormData();
    formData.append('serviceId', serviceId);
    formData.append('accessToken', accessToken);
    formData.append('mode', 'fills');
    formData.append('filename', 'test.png');
    formData.append('mimeType', 'image/png');
    formData.append('x', -50);
    formData.append('y', -50);
    formData.append('data', blob);

    var uri = builder.build();
    dConnect.post(uri, null, formData, function(json) {
      assert.ok(true, 'result=' + json.result);
      QUnit.start();
    }, function(errorCode, errorMessage) {
      assert.ok(checkErrorCode(errorCode), "errorCode=" + errorCode + ", errorMessage=" + errorMessage);
      QUnit.start();
    });
  }, function(errorCode, errorMessage) {
    assert.ok(false, 'errorCode=' + errorCode + ', errorMessage=' + errorMessage);
    QUnit.start();
  });
};
QUnit.asyncTest('drawImageNormalTest003(mode is fills)', CanvasProfileNormalTest.drawImageNormalTest003);

/**
 * デバイスから画像を削除するテストを行う。
 *
【HTTP通信】

 *

 * Method: DELETE

 * Path: /canvas/drawimage?serviceId=xxxx&accessToken=xxx

 *

 *
【期待する動作】

 *

 * ・resultに1が返ってくること。

 * ・errCodeに3が返ってくること。

 *

 */
CanvasProfileNormalTest.deleteDrawImageNormalTest001 = function(assert) {
  var img = document.getElementById('images');
  img.style.visibility = 'visible';

  var blob = CanvasProfileNormalTest.draw('drawImageNormalTest001');

  searchTestService(function(accessToken, serviceId) {
    var builder = new dConnect.URIBuilder();
    builder.setProfile(dConnect.constants.canvas.PROFILE_NAME);
    builder.setAttribute(dConnect.constants.canvas.ATTR_DRAWIMAGE);

    var formData = new FormData();
    formData.append('serviceId', serviceId);
    formData.append('accessToken', accessToken);
    formData.append('filename', 'test.png');
    formData.append('mimeType', 'image/png');
    formData.append('data', blob);

    var uri = builder.build();
    dConnect.post(uri, null, formData, function(json) {
      assert.ok(true, 'result=' + json.result);

      var builder = new dConnect.URIBuilder();
      builder.setProfile(dConnect.constants.canvas.PROFILE_NAME);
      builder.setAttribute(dConnect.constants.canvas.ATTR_DRAWIMAGE);
      builder.setServiceId(serviceId);
      builder.setAccessToken(accessToken);

      var uri = builder.build();
      dConnect.delete(uri, null,  function(json) {
        assert.ok(true, 'result=' + json.result);
        QUnit.start();
      }, function(errorCode, errorMessage) {
        assert.ok(checkErrorCode(errorCode),
            "errorCode=" + errorCode + ", errorMessage=" + errorMessage);
        QUnit.start();
      });
    }, function(errorCode, errorMessage) {
      assert.ok(checkErrorCode(errorCode),
          "errorCode=" + errorCode + ", errorMessage=" + errorMessage);
      QUnit.start();
    });
  }, function(errorCode, errorMessage) {
    assert.ok(false, 'errorCode=' + errorCode + ', errorMessage=' + errorMessage);
    QUnit.start();
  });
};
QUnit.asyncTest('deleteDrawImageNormalTest001(put)', CanvasProfileNormalTest.deleteDrawImageNormalTest001);