text:
function create_retro_flow_image_collagen(rf_path,im,bin_im,index,x_flow,y_flow,x_shift,y_shift,mue2pix_ratio,fps,max_r_flow,flow_field_arrow_distance, files, varargin)

nVarargs = length(varargin)
if nVarargs > 0
    lunit_str = varargin{1};
    tunit_str = varargin{2};
else
    lunit_str = 'µm';
    tunit_str = 'minute';
end

switch lunit_str
    case 'm'
        length_scale_unit = 1e6;
    case 'mm'
        length_scale_unit = 1e3;
    case 'µm'
        length_scale_unit = 1;
    case 'nm'
        length_scale_unit = 1e-3;
    otherwise
        assert(false,'unknown lenghtscale')
end

switch tunit_str
    case 'day'
        time_scale_unit = 1440;
    case 'hour'
        time_scale_unit = 60;
    case 'minute'
        time_scale_unit = 1;
    case 'second'
        time_scale_unit = 1/60;
    otherwise
        assert(false,['unknown timescale:' tunit_str])
end

hold off;
tic
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Define parameters (are saved in analysis_parameters.mat):
%flow_field_arrow_distance=25;       %Flow field arrow distance
%max_r_flow=5;                       %max retrograde flow amplitude for colorcoding
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%first run: save the parameters defined above
if index==1
    save([rf_path,'/analysis_parameters.mat'],'flow_field_arrow_distance','max_r_flow','-append');
end

%create a new figure to display the flow fiels in.
%h=fig_handle;
h=figure;
%axes(h);

%get the images
im1=im;
[y_max,x_max]=size(im1);
%now take care of the x_shift, y_shift;
im_int(1:y_shift+y_max,x_shift+x_max)=0;
im_int(y_shift+1:y_shift+y_max,x_shift+1:x_shift+x_max)=im1;
im1=im_int;

%This is already prepared for Dannys Labview version, with the binary shapes stored in rf_path/binary_shape.
%If the folder exists, read from there, otherwise do it on your own
% if isdir([rf_path,filesep,'binary_shape']
%     files_bin=dir([rf_path,filesep,'binary_shape',filesep,'corr*']);
%     r_im_erode=double(imread([rf_path,filesep,'binary_shape',filesep,files_bin(index).name]));
%     r_im_erode(find(r_im_erode==255))=1;
%     r_im_erode_int(1:y_shift+y_max,x_shift+x_max)=0;
%     r_im_erode_int(y_shift+1:y_shift+y_max,x_shift+1:x_shift+x_max)=r_im_erode;
%     r_im_erode=r_im_erode_int;
% else
%     r_im_erode=better_edge(im1);    %edge detection function written by Danny.
% end

%again, take care of the image shift
im_int(1:y_shift+y_max,x_shift+x_max)=0;
im_int(y_shift+1:y_shift+y_max,x_shift+1:x_shift+x_max)=bin_im;
r_im_erode=im_int;

[y_max,x_max]=size(im1);
max_size=max(size(im1));

x_flow=double(x_flow);
y_flow=double(y_flow);
[y_max_field,x_max_field]=size(x_flow);

%Make sure im1, and the flow data have the same size, if not reshape the flow data accordingly
if (~(size(x_flow)==size(im1)))
    intermediate(1:y_max,1:x_max)=NaN;
    intermediate(1:min([y_max,y_max_field]),1:min([x_max,x_max_field]))=x_flow(1:min([y_max,y_max_field]),1:min([x_max,x_max_field]));
    x_flow=intermediate;
    intermediate(1:y_max,1:x_max)=NaN;
    intermediate(1:min([y_max,y_max_field]),1:min([x_max,x_max_field]))=y_flow(1:min([y_max,y_max_field]),1:min([x_max,x_max_field]));
    y_flow=intermediate;
end
clear('intermediate');

%invert_im1
im1_inv=double(im1);
im1_inv=255-im1_inv;
im1_inv=uint8(im1_inv);

%use the shape, to cut of whatever of the retro flow maps is outside the real shape
x_flow=r_im_erode.*x_flow;
y_flow=r_im_erode.*y_flow;
x_flow(isnan(x_flow))=0;
y_flow(isnan(y_flow))=0;
x_flow_i=x_flow(x_shift+1:end,y_shift+1:end);
y_flow_i=y_flow(x_shift+1:end,y_shift+1:end);
x_flow=x_flow_i;y_flow=y_flow_i;
[th_flow,r_flow]=cart2pol(x_flow,y_flow);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%Now we should have everything together to start the drawing the image
%First make the color coded growth retrograde flow
r_flow(isnan(r_flow))=0;
%r_flow=r_flow(x_shift+1:end,y_shift+1:end);
imshow(r_flow/length_scale_unit*time_scale_unit)
colormap('gray')
set(gca,'CLim',[0,max_r_flow/length_scale_unit*time_scale_unit])
display(max_r_flow/length_scale_unit*time_scale_unit)

mkdir([rf_path,filesep,'gray-scale']);
mkdir([rf_path,filesep,'color_code']);
mkdir([rf_path,filesep,'color_code_and_arrows']);

out0=[rf_path,filesep,'gray-scale',filesep, files(index).name(1:end-4),'_','grayscale.png']
print(h,'-dpng','-r150',out0);

%here I will write the colorbar
if index==1
    fig1=figure;
    left=100; bottom=100 ; width=20 ; height=500;
    pos=[left bottom width height];
    axis off
    set(gca,'CLim',[0,max_r_flow/length_scale_unit*time_scale_unit])
    cb=colorbar
    ylabel(cb,['speed ' lunit_str '/' tunit_str])
    colormap gray
    set(fig1,'OuterPosition',pos)
    color_bar=[rf_path,filesep,'gray-scale',filesep, 'colorbar_grayscale.pdf']
    print(fig1,'-dpdf','-r150',color_bar);
    close(fig1)
end

colormap('jet')

set(gca,'CLim',[0,max_r_flow/length_scale_unit*time_scale_unit])
display(max_r_flow/length_scale_unit*time_scale_unit)
hold on

%now get and draw the flow field arrows
plot_data=generate_plot_normalized_collagen(x_flow,y_flow,flow_field_arrow_distance);
hold on

out=[rf_path,filesep,'color_code',filesep, files(index).name(1:end-4),'_','colorcode.png'];
print(h,'-dpng','-r150',out);

%here I will write the colorbar
if index==1
    fig1=figure;
    left=100; bottom=100 ; width=20 ; height=500;
    pos=[left bottom width height];
    axis off
    set(gca,'CLim',[0,max_r_flow/length_scale_unit*time_scale_unit])
    cb=colorbar
    ylabel(cb,['speed ' lunit_str '/' tunit_str])
    colormap jet
    set(fig1,'OuterPosition',pos)
    color_bar=[rf_path,filesep,'color_code',filesep, 'colorbar.pdf']
    print(fig1,'-dpdf','-r150',color_bar);
    close(fig1)
end
quiver(plot_data(:,1),plot_data(:,2),plot_data(:,3),plot_data(:,4),0.3,'k');
%cb = colorbar();

out2=[rf_path,'/color_code_and_arrows',filesep, files(index).name(1:end-4),'_','colorcode_arrows.png']
print(h,'-dpng','-r150',out2);
if index==1
    fig1=figure;
    left=100; bottom=100 ; width=20 ; height=500;
    pos=[left bottom width height];
    axis off
    set(gca,'CLim',[0,max_r_flow/length_scale_unit*time_scale_unit])
    colorbar
    colormap jet
    set(fig1,'OuterPosition',pos)
    color_bar=[rf_path,filesep,'color_code_and_arrows',filesep, 'colorbar.pdf']
    print(fig1,'-dpdf','-r150',color_bar);
    close(fig1)
end

%Draw a 10µm scale bar
fill([x_max-x_shift-5-10/mue2pix_ratio,x_max-x_shift-5-10/mue2pix_ratio,x_max-5-x_shift,x_max-5],[5,15,15,5],'w')
%text(x_max-5-10/mue2pix_ratio,20,'10 µm','Color','w')

%Save the images, the display_edge_array, and of course the final_results_out

%now correct for the stupid matlab exporting and resizeing
for cout = {out2 out out0}
    im_corr = imread(cout{1});
    im_bw   = mean(im_corr,3);
    x_mean=mean(im_bw,2);
    y_mean=mean(im_bw,1);
    x_im_f=find(~(x_mean==255));
    y_im_f=find(~(y_mean==255));
    im_corr_cut = im_corr(x_im_f(1):x_im_f(length(x_im_f)),y_im_f(1):y_im_f(length(y_im_f)),:);
    [y_im_corr_cut,x_im_corr_cut,depth]=size(im_corr_cut);
    im1_resized=imresize(im1_inv,[y_im_corr_cut,x_im_corr_cut]);
    im_corr_resized=imresize(im_corr_cut,size(im));
    imwrite(im_corr_resized,cout{1});
end
%finally get an overlay with the original image, to give the structural information!!
%im1_inv_d(:,:,1)=double(im1_inv);im1_inv_d(:,:,2)=double(im1_inv);im1_inv_d(:,:,3)=double(im1_inv);
%im1_inv_resize=im1_inv_d(x_shift+1:end,y_shift+1:end,:);
%im_corr_cut_im1=uint8(ceil(double(im_corr_resized).*im1_inv_resize./255));
%imwrite(im_corr_cut_im1,[rf_path,filesep,'interpolation_image',filesep,'plus_actin',filesep,'all_overlay',num2str(index+1000),'all_filt.png']);
data_out=[rf_path,'/interpolation_data',filesep, files(index).name(1:end-4),'_','colorcode_arrows.png']
save([rf_path,filesep,'interpolation_data',filesep, files(index).name(1:end-4),'_','interpolated_flow.mat'],'x_flow','y_flow','mue2pix_ratio','fps');

close(h)
toc
pause(0.1)


text:
start:
	@ $$(npm bin)/webpack-dev-server --config ./webpack.config.js --mode=development

.PHONY: start

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">SweetHistory</string>
    <string name="action_addSintom">Agregar síntoma</string>
    <string name="action_addEvent">Agregar evento</string>
    <string name="titleSectionAdvices">CONSEJOS</string>
    <string name="titleSectionEvents">EVENTOS</string>
    <string name="titleSectionSintoms">SÍNTOMAS</string>
	<string name="drawer_open">Drawer Open</string>
	<string name="drawer_close">Drawer Closed</string>
    <string name="name">nombre(s)</string>
    <string name="lastname">apellidos</string>
    <string name="birthday">fecha de nacimiento</string>
    <string name="weigth">peso</string>
    <string name="heigth">medida</string>
    <string name="genre">sexo</string>
    <string name="apgar">apgar</string>
    <string name="lastVisit">última visita</string>
    <string name="city">ciudad</string>
    <string name="save">Guardar</string>
    <string name="cellNumber">núm. celular</string>
    <string name="officeNumber">núm. consultorio</string>
    <string name="email">correo electrónico</string>
    <string name="address">dirección</string>
    <string name="question">¿Qué esta pasando?</string>
    <string name="addAlarm">Alarmas</string>
	<string name="cancelAlarm">Cancelar</string>
	<string name="notificationTitle">Recuerda… </string>
	<string name="datePickerTitle">Selecciona una fecha</string>
	<string name="txtAlarm">Recordar qué…</string>

	<string name="sectionTimeLine">Historia</string>
	<string name="sectionBabyRegister">Registrar Bebé</string>
	<string name="sectionDoctorRegister">Registrar Doctor</string>
	<string name="sectionAlarms">Recordatorios</string>
	<string-array name="sectionNames">
		<item>@string/sectionTimeLine</item>
		<item>@string/sectionBabyRegister</item>
		<item>@string/sectionAlarms</item>
		<item>@string/sectionDoctorRegister</item>
    </string-array>
    <string name="hintEach">Cada…</string>
    <string name="txtDateInitial">A partir de…</string>
    <string name="txtTimeInitial">A las…</string>
    <string name="timePickerTile">Selecciona una hora</string>
    <string name="errorEmptyFiels">Se deben llenar todos los campos</string>
    <string name="alarmDeleted">Alarma eliminada correctamente</string>

    <string-array name="units">
        <item>segundo (s)</item>
        <item>minuto (s)</item>
        <item>hora (s)</item>
        <item>día (s)</item>
        <item>semana (s)</item>
    </string-array>
</resources>


text:
package org.apache.hadoop.hbase.zookeeper;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Semaphore;

import junit.framework.Assert;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.master.TestActiveMasterManager.NodeDeletionListener;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.MiscTests;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.Threads;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

@Category({MiscTests.class, MediumTests.class})
public class TestZooKeeperNodeTracker {
  private static final Log LOG = LogFactory.getLog(TestZooKeeperNodeTracker.class);
  private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();

  private final static Random rand = new Random();

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.startMiniZKCluster();
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    TEST_UTIL.shutdownMiniZKCluster();
  }

  /**
   * Test that we can interrupt a node that is blocked on a wait.
   * @throws IOException
   * @throws InterruptedException
   */
  @Test public void testInterruptible() throws IOException, InterruptedException {
    Abortable abortable = new StubAbortable();
    ZooKeeperWatcher zk = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(),
      "testInterruptible", abortable);
    final TestTracker tracker = new TestTracker(zk, "/xyz", abortable);
    tracker.start();
    Thread t = new Thread() {
      @Override
      public void run() {
        try {
          tracker.blockUntilAvailable();
        } catch (InterruptedException e) {
          throw new RuntimeException("Interrupted", e);
        }
      }
    };
    t.start();
    while (!t.isAlive()) Threads.sleep(1);
    tracker.stop();
    t.join();
    // If it wasn't interruptible, we'd never get to here.
  }

  @Test
  public void testNodeTracker() throws Exception {
    Abortable abortable = new StubAbortable();
    ZooKeeperWatcher zk = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(),
        "testNodeTracker", abortable);
    ZKUtil.createAndFailSilent(zk, zk.znodePaths.baseZNode);

    final String node =
      ZKUtil.joinZNode(zk.znodePaths.baseZNode, new Long(rand.nextLong()).toString());

    final byte [] dataOne = Bytes.toBytes("dataOne");
    final byte [] dataTwo = Bytes.toBytes("dataTwo");

    // Start a ZKNT with no node currently available
    TestTracker localTracker = new TestTracker(zk, node, abortable);
    localTracker.start();
    zk.registerListener(localTracker);

    // Make sure we don't have a node
    assertNull(localTracker.getData(false));

    // Spin up a thread with another ZKNT and have it block
    WaitToGetDataThread thread = new WaitToGetDataThread(zk, node);
    thread.start();

    // Verify the thread doesn't have a node
    assertFalse(thread.hasData);

    // Now, start a new ZKNT with the node already available
    TestTracker secondTracker = new TestTracker(zk, node, null);
    secondTracker.start();
    zk.registerListener(secondTracker);

    // Put up an additional zk listener so we know when zk event is done
    TestingZKListener zkListener = new TestingZKListener(zk, node);
    zk.registerListener(zkListener);
    assertEquals(0, zkListener.createdLock.availablePermits());

    // Create a completely separate zk connection for test triggers and avoid
    // any weird watcher interactions from the test
    final ZooKeeper zkconn = new ZooKeeper(
        ZKConfig.getZKQuorumServersString(TEST_UTIL.getConfiguration()), 60000,
        new StubWatcher());

    // Add the node with data one
    zkconn.create(node, dataOne, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    // Wait for the zk event to be processed
    zkListener.waitForCreation();
    thread.join();

    // Both trackers should have the node available with data one
    assertNotNull(localTracker.getData(false));
    assertNotNull(localTracker.blockUntilAvailable());
    assertTrue(Bytes.equals(localTracker.getData(false), dataOne));
    assertTrue(thread.hasData);
    assertTrue(Bytes.equals(thread.tracker.getData(false), dataOne));
    LOG.info("Successfully got data one");

    // Make sure it's available and with the expected data
    assertNotNull(secondTracker.getData(false));
    assertNotNull(secondTracker.blockUntilAvailable());
    assertTrue(Bytes.equals(secondTracker.getData(false), dataOne));
    LOG.info("Successfully got data one with the second tracker");

    // Drop the node
    zkconn.delete(node, -1);
    zkListener.waitForDeletion();

    // Create a new thread but with the existing thread's tracker to wait
    TestTracker threadTracker = thread.tracker;
    thread = new WaitToGetDataThread(zk, node, threadTracker);
    thread.start();

    // Verify other guys don't have data
    assertFalse(thread.hasData);
    assertNull(secondTracker.getData(false));
    assertNull(localTracker.getData(false));
    LOG.info("Successfully made unavailable");

    // Create with second data
    zkconn.create(node, dataTwo, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

    // Wait for the zk event to be processed
    zkListener.waitForCreation();
    thread.join();

    // All trackers should have the node available with data two
    assertNotNull(localTracker.getData(false));
    assertNotNull(localTracker.blockUntilAvailable());
    assertTrue(Bytes.equals(localTracker.getData(false), dataTwo));
    assertNotNull(secondTracker.getData(false));
    assertNotNull(secondTracker.blockUntilAvailable());
    assertTrue(Bytes.equals(secondTracker.getData(false), dataTwo));
    assertTrue(thread.hasData);
    assertTrue(Bytes.equals(thread.tracker.getData(false), dataTwo));
    LOG.info("Successfully got data two on all trackers and threads");

    // Change the data back to data one
    zkconn.setData(node, dataOne, -1);

    // Wait for zk event to be processed
    zkListener.waitForDataChange();

    // All trackers should have the node available with data one
    assertNotNull(localTracker.getData(false));
    assertNotNull(localTracker.blockUntilAvailable());
    assertTrue(Bytes.equals(localTracker.getData(false), dataOne));
    assertNotNull(secondTracker.getData(false));
    assertNotNull(secondTracker.blockUntilAvailable());
    assertTrue(Bytes.equals(secondTracker.getData(false), dataOne));
    assertTrue(thread.hasData);
    assertTrue(Bytes.equals(thread.tracker.getData(false), dataOne));
    LOG.info("Successfully got data one following a data change on all trackers and threads");
  }

  public static class WaitToGetDataThread extends Thread {

    TestTracker tracker;
    boolean hasData;

    public WaitToGetDataThread(ZooKeeperWatcher zk, String node) {
      tracker = new TestTracker(zk, node, null);
      tracker.start();
      zk.registerListener(tracker);
      hasData = false;
    }

    public WaitToGetDataThread(ZooKeeperWatcher zk, String node,
        TestTracker tracker) {
      this.tracker = tracker;
      hasData = false;
    }

    @Override
    public void run() {
      LOG.info("Waiting for data to be available in WaitToGetDataThread");
      try {
        tracker.blockUntilAvailable();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      LOG.info("Data now available in tracker from WaitToGetDataThread");
      hasData = true;
    }
  }

  public static class TestTracker extends ZooKeeperNodeTracker {
    public TestTracker(ZooKeeperWatcher watcher, String node,
        Abortable abortable) {
      super(watcher, node, abortable);
    }
  }

  public static class TestingZKListener extends ZooKeeperListener {
    private static final Log LOG = LogFactory.getLog(NodeDeletionListener.class);

    private Semaphore deletedLock;
    private Semaphore createdLock;
    private Semaphore changedLock;
    private String node;

    public TestingZKListener(ZooKeeperWatcher watcher, String node) {
      super(watcher);
      deletedLock = new Semaphore(0);
      createdLock = new Semaphore(0);
      changedLock = new Semaphore(0);
      this.node = node;
    }

    @Override
    public void nodeDeleted(String path) {
      if(path.equals(node)) {
        LOG.debug("nodeDeleted(" + path + ")");
        deletedLock.release();
      }
    }

    @Override
    public void nodeCreated(String path) {
      if(path.equals(node)) {
        LOG.debug("nodeCreated(" + path + ")");
        createdLock.release();
      }
    }

    @Override
    public void nodeDataChanged(String path) {
      if(path.equals(node)) {
        LOG.debug("nodeDataChanged(" + path + ")");
        changedLock.release();
      }
    }

    public void waitForDeletion() throws InterruptedException {
      deletedLock.acquire();
    }

    public void waitForCreation() throws InterruptedException {
      createdLock.acquire();
    }

    public void waitForDataChange() throws InterruptedException {
      changedLock.acquire();
    }
  }

  public static class StubAbortable implements Abortable {
    @Override
    public void abort(final String msg, final Throwable t) {}

    @Override
    public boolean isAborted() {
      return false;
    }

  }

  public static class StubWatcher implements Watcher {
    @Override
    public void process(WatchedEvent event) {}
  }

  @Test
  public void testCleanZNode() throws Exception {
    ZooKeeperWatcher zkw = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(),
        "testNodeTracker", new TestZooKeeperNodeTracker.StubAbortable());

    final ServerName sn = ServerName.valueOf("127.0.0.1:52", 45L);

    ZKUtil.createAndFailSilent(zkw,
        TEST_UTIL.getConfiguration().get(HConstants.ZOOKEEPER_ZNODE_PARENT,
            HConstants.DEFAULT_ZOOKEEPER_ZNODE_PARENT));

    final String nodeName =  zkw.znodePaths.masterAddressZNode;

    // Check that we manage the case when there is no data
    ZKUtil.createAndFailSilent(zkw, nodeName);
    MasterAddressTracker.deleteIfEquals(zkw, sn.toString());
    Assert.assertFalse(ZKUtil.getData(zkw, nodeName) == null);

    // Check that we don't delete if we're not supposed to
    ZKUtil.setData(zkw, nodeName, MasterAddressTracker.toByteArray(sn, 0));
    MasterAddressTracker.deleteIfEquals(zkw, ServerName.valueOf("127.0.0.2:52", 45L).toString());
    Assert.assertFalse(ZKUtil.getData(zkw, nodeName) == null);

    // Check that we delete when we're supposed to
    ZKUtil.setData(zkw, nodeName,MasterAddressTracker.toByteArray(sn, 0));
    MasterAddressTracker.deleteIfEquals(zkw, sn.toString());
    Assert.assertTrue( ZKUtil.getData(zkw, nodeName)== null );

    // Check that we support the case when the znode does not exist
    MasterAddressTracker.deleteIfEquals(zkw, sn.toString()); // must not throw an exception
  }

}


text:
package net.devkat.ocm

import com.typesafe.scalalogging.slf4j.Logging

trait Ocm extends SessionHolder with Mapper with Crud with Query


text:
/*
Package strftime implements Python's strftime in Go

Example:
	str, err := strftime.Format("%Y/%m/%d", time.Now()) // 2019/07/07

Directives:
	%a - Locale's abbreviated weekday name
	%A - Locale's full weekday name
	%b - Locale's abbreviated month name
	%B - Locale's full month name
	%c - Locale's appropriate date and time representation
	%d - Day of the month as a decimal number [01,31]
	%H - Hour (24-hour clock) as a decimal number [00,23]
	%I - Hour (12-hour clock) as a decimal number [01,12]
	%j - Day of year
	%m - Month as a decimal number [01,12]
	%M - Minute as a decimal number [00,59]
	%p - Locale's equivalent of either AM or PM
	%S - Second as a decimal number [00,61]
	%U - Week number of the year
	%w - Weekday as a decimal number
	%W - Week number of the year
	%x - Locale's appropriate date representation
	%X - Locale's appropriate time representation
	%y - Year without century as a decimal number [00,99]
	%Y - Year with century as a decimal number
	%Z - Time zone name (no characters if no time zone exists)

Note that %c returns RFC1123 which is a bit different from what Python does
*/
package strftime

import (
	"fmt"
	"regexp"
	"time"
)

const (
	// Version is the package version
	Version = "0.1.5"

	// Week in time.Duration
	Week = time.Hour * 24 * 7
)

// See http://docs.python.org/3/library/time.html#time.strftime
var conv = map[string]string{
	"%a": "Mon",        // Locale's abbreviated weekday name
	"%A": "Monday",     // Locale's full weekday name
	"%b": "Jan",        // Locale's abbreviated month name
	"%B": "January",    // Locale's full month name
	"%c": time.RFC1123, // Locale's appropriate date and time representation
	"%d": "02",         // Day of the month as a decimal number [01,31]
	"%H": "15",         // Hour (24-hour clock) as a decimal number [00,23]
	"%I": "03",         // Hour (12-hour clock) as a decimal number [01,12]
	"%m": "01",         // Month as a decimal number [01,12]
	"%M": "04",         // Minute as a decimal number [00,59]
	"%p": "PM",         // Locale's equivalent of either AM or PM
	"%S": "05",         // Second as a decimal number [00,61]
	"%x": "01/02/06",   // Locale's appropriate date representation
	"%X": "15:04:05",   // Locale's appropriate time representation
	"%y": "06",         // Year without century as a decimal number [00,99]
	"%Y": "2006",       // Year with century as a decimal number
	"%Z": "MST",        // Time zone name (no characters if no time zone exists)
}

var (
	fmtRe = regexp.MustCompile("%[%a-zA-Z]")
)

// repl replaces % directives with right time, will panic on unknown directive
func repl(match string, t time.Time) (string, error) {
	if match == "%%" {
		return "%", nil
	}

	format, ok := conv[match]
	if ok {
		return t.Format(format), nil
	}

	switch match {
	case "%j":
		start := time.Date(t.Year(), time.January, 1, 0, 0, 0, 0, time.UTC)
		day := int(t.Sub(start).Hours()/24) + 1
		return fmt.Sprintf("%03d", day), nil
	case "%w":
		return fmt.Sprintf("%d", t.Weekday()), nil
	case "%W", "%U":
		start := time.Date(t.Year(), time.January, 1, 23, 0, 0, 0, time.UTC)
		week := 0
		for start.Before(t) {
			week++
			start = start.Add(Week)
		}

		return fmt.Sprintf("%02d", week), nil
	}

	return "", fmt.Errorf("unknown directive - %s", match)
}

// Format return string with % directives expanded.
// Will return error on unknown directive.
func Format(format string, t time.Time) (string, error) {
	var err error

	fn := func(match string) string {
		s, rerr := repl(match, t)
		if rerr != nil {
			err = rerr
		}
		return s
	}

	return fmtRe.ReplaceAllStringFunc(format, fn), err
}


text:
// I2Cdev library collection - TCA6424A I2C device class
// Based on Texas Instruments TCA6424A datasheet, 9/2010 (document SCPS193B)
// 7/31/2011 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//     2011-07-31 - initial release

#include "TCA6424A.h"

/** Default constructor, uses default I2C address.
 * @see TCA6424A_DEFAULT_ADDRESS
 */
TCA6424A::TCA6424A() {
    devAddr = TCA6424A_DEFAULT_ADDRESS;
}

/** Specific address constructor.
 * @param address I2C address
 * @see TCA6424A_DEFAULT_ADDRESS
 * @see TCA6424A_ADDRESS_ADDR_LOW
 * @see TCA6424A_ADDRESS_ADDR_HIGH
 */
TCA6424A::TCA6424A(uint8_t address) {
    devAddr = address;
}

/** Power on and prepare for general usage.
 * The TCA6424A I/O expander requires no preparation after power-on. All pins
 * will be default to INPUT mode, and the device is ready for usage immediately.
 * This is an empty function for consistency and/or future expansion.
 */
void TCA6424A::initialize() {
}

/** Verify the I2C connection.
 * Make sure the device is connected and responds as expected.
 * @return True if connection is valid, false otherwise
 */
bool TCA6424A::testConnection() {
    return I2Cdev::readBytes(devAddr, TCA6424A_RA_INPUT0, 3, buffer) == 3;
}

// INPUT* registers (x0h - x2h)

/** Get a single INPUT pin's logic level.
 * @return Pin logic level (0 or 1)
 */
bool TCA6424A::readPin(uint16_t pin) {
    I2Cdev::readBit(devAddr, TCA6424A_RA_INPUT0 + (pin / 8), pin % 8, buffer);
    return buffer[0];
}
/** Get all pin logic levels from one bank.
 * @param bank Which bank to read (0/1/2 for P0*, P1*, P2* respectively)
 * @return 8 pins' logic levels (0 or 1 for each pin)
 */
uint8_t TCA6424A::readBank(uint8_t bank) {
    I2Cdev::readByte(devAddr, TCA6424A_RA_INPUT0 + bank, buffer);
    return buffer[0];
}
/** Get all pin logic levels from all banks.
 * Reads into single 3-byte data container.
 * @param banks Container for all bank's pin values (P00-P27)
 */
void TCA6424A::readAll(uint8_t *banks) {
    I2Cdev::readBytes(devAddr, TCA6424A_RA_INPUT0, 3, banks);
}
/** Get all pin logic levels from all banks.
 * Reads into individual 1-byte containers.
 * @param bank0 Container for Bank 0's pin values (P00-P07)
 * @param bank1 Container for Bank 1's pin values (P10-P17)
 * @param bank2 Container for Bank 2's pin values (P20-P27)
 */
void TCA6424A::readAll(uint8_t *bank0, uint8_t *bank1, uint8_t *bank2) {
    I2Cdev::readBytes(devAddr, TCA6424A_RA_INPUT0, 3, buffer);
    *bank0 = buffer[0];
    *bank1 = buffer[1];
    *bank2 = buffer[2];
}

// OUTPUT* registers (x4h - x6h)

/** Get a single OUTPUT pin's setting.
 * Note that this returns the level set in the flip-flop, and does not
 * necessarily represent the actual logic level present at the pin.
 * @return Pin output setting (0 or 1)
 */
bool TCA6424A::getPinOutputLevel(uint16_t pin) {
    I2Cdev::readBit(devAddr, TCA6424A_RA_OUTPUT0 + (pin / 8), pin % 8, buffer);
    return buffer[0];
}
/** Get all pin output settings from one bank.
 * Note that this returns the level set in the flip-flop, and does not
 * necessarily represent the actual logic level present at the pin.
 * @param bank Which bank to read (0/1/2 for P0*, P1*, P2* respectively)
 * @return 8 pins' output settings (0 or 1 for each pin)
 */
uint8_t TCA6424A::getBankOutputLevel(uint8_t bank) {
    I2Cdev::readByte(devAddr, TCA6424A_RA_OUTPUT0 + bank, buffer);
    return buffer[0];
}
/** Get all pin output settings from all banks.
 * Reads into single 3-byte data container.
 * @param banks Container for all bank's pin values (P00-P27)
 */
void TCA6424A::getAllOutputLevel(uint8_t *banks) {
    I2Cdev::readBytes(devAddr, TCA6424A_RA_OUTPUT0, 3, banks);
}
/** Get all pin output settings from all banks.
 * Reads into individual 1-byte containers. Note that this returns the level
 * set in the flip-flop, and does not necessarily represent the actual logic
 * level present at the pin.
 * @param bank0 Container for Bank 0's pin values (P00-P07)
 * @param bank1 Container for Bank 1's pin values (P10-P17)
 * @param bank2 Container for Bank 2's pin values (P20-P27)
 */
void TCA6424A::getAllOutputLevel(uint8_t *bank0, uint8_t *bank1, uint8_t *bank2) {
    I2Cdev::readBytes(devAddr, TCA6424A_RA_OUTPUT0, 3, buffer);
    *bank0 = buffer[0];
    *bank1 = buffer[1];
    *bank2 = buffer[2];
}
/** Set a single OUTPUT pin's logic level.
 * @param pin Which pin to write (0-23)
 * @param value New pin output logic level (0 or 1)
 */
void TCA6424A::writePin(uint16_t pin, bool value) {
    I2Cdev::writeBit(devAddr, TCA6424A_RA_OUTPUT0 + (pin / 8), pin % 8, value);
}
/** Set all OUTPUT pins' logic levels in one bank.
 * @param bank Which bank to write (0/1/2 for P0*, P1*, P2* respectively)
 * @param value New pins' output logic level (0 or 1 for each pin)
 */
void TCA6424A::writeBank(uint8_t bank, uint8_t value) {
    I2Cdev::writeByte(devAddr, TCA6424A_RA_OUTPUT0 + bank, value);
}
/** Set all OUTPUT pins' logic levels in all banks.
 * @param banks All pins' new logic values (P00-P27) in 3-byte array
 */
void TCA6424A::writeAll(uint8_t *banks) {
    I2Cdev::writeBytes(devAddr, TCA6424A_RA_OUTPUT0 | TCA6424A_AUTO_INCREMENT, 3, banks);
}
/** Set all OUTPUT pins' logic levels in all banks.
 * @param bank0 Bank 0's new logic values (P00-P07)
 * @param bank1 Bank 1's new logic values (P10-P17)
 * @param bank2 Bank 2's new logic values (P20-P27)
 */
void TCA6424A::writeAll(uint8_t bank0, uint8_t bank1, uint8_t bank2) {
    buffer[0] = bank0;
    buffer[1] = bank1;
    buffer[2] = bank2;
    I2Cdev::writeBytes(devAddr, TCA6424A_RA_OUTPUT0 | TCA6424A_AUTO_INCREMENT, 3, buffer);
}

// POLARITY* registers (x8h - xAh)

/** Get a single pin's polarity (normal/inverted) setting.
 * @return Pin polarity setting (0 or 1)
 */
bool TCA6424A::getPinPolarity(uint16_t pin) {
    I2Cdev::readBit(devAddr, TCA6424A_RA_POLARITY0 + (pin / 8), pin % 8, buffer);
    return buffer[0];
}
/** Get all pin polarity (normal/inverted) settings from one bank.
 * @param bank Which bank to read (0/1/2 for P0*, P1*, P2* respectively)
 * @return 8 pins' polarity settings (0 or 1 for each pin)
 */
uint8_t TCA6424A::getBankPolarity(uint8_t bank) {
    I2Cdev::readByte(devAddr, TCA6424A_RA_POLARITY0 + bank, buffer);
    return buffer[0];
}
/** Get all pin polarity (normal/inverted) settings from all banks.
 * Reads into single 3-byte data container.
 * @param banks Container for all bank's pin values (P00-P27)
 */
void TCA6424A::getAllPolarity(uint8_t *banks) {
    I2Cdev::readBytes(devAddr, TCA6424A_RA_POLARITY0, 3, banks);
}
/** Get all pin polarity (normal/inverted) settings from all banks.
 * Reads into individual 1-byte containers.
 * @param bank0 Container for Bank 0's pin values (P00-P07)
 * @param bank1 Container for Bank 1's pin values (P10-P17)
 * @param bank2 Container for Bank 2's pin values (P20-P27)
 */
void TCA6424A::getAllPolarity(uint8_t *bank0, uint8_t *bank1, uint8_t *bank2) {
    I2Cdev::readBytes(devAddr, TCA6424A_RA_POLARITY0, 3, buffer);
    *bank0 = buffer[0];
    *bank1 = buffer[1];
    *bank2 = buffer[2];
}
/** Set a single pin's polarity (normal/inverted) setting.
 * @param pin Which pin to write (0-23)
 * @param polarity New pin polarity setting (0 or 1)
 */
void TCA6424A::setPinPolarity(uint16_t pin, bool polarity) {
    I2Cdev::writeBit(devAddr, TCA6424A_RA_POLARITY0 + (pin / 8), pin % 8, polarity);
}
/** Set all pin polarity (normal/inverted) settings in one bank.
 * @param bank Which bank to write (0/1/2 for P0*, P1*, P2* respectively)
 * @return New pins' polarity settings (0 or 1 for each pin)
 */
void TCA6424A::setBankPolarity(uint8_t bank, uint8_t polarity) {
    I2Cdev::writeByte(devAddr, TCA6424A_RA_POLARITY0 + bank, polarity);
}
/** Set all pin polarity (normal/inverted) settings in all banks.
 * @param banks All pins' new logic values (P00-P27) in 3-byte array
 */
void TCA6424A::setAllPolarity(uint8_t *banks) {
    I2Cdev::writeBytes(devAddr, TCA6424A_RA_POLARITY0 | TCA6424A_AUTO_INCREMENT, 3, banks);
}
/** Set all pin polarity (normal/inverted) settings in all banks.
 * @param bank0 Bank 0's new polarity values (P00-P07)
 * @param bank1 Bank 1's new polarity values (P10-P17)
 * @param bank2 Bank 2's new polarity values (P20-P27)
 */
void TCA6424A::setAllPolarity(uint8_t bank0, uint8_t bank1, uint8_t bank2) {
    buffer[0] = bank0;
    buffer[1] = bank1;
    buffer[2] = bank2;
    I2Cdev::writeBytes(devAddr, TCA6424A_RA_POLARITY0 | TCA6424A_AUTO_INCREMENT, 3, buffer);
}

// CONFIG* registers (xCh - xEh)

/** Get a single pin's direction (I/O) setting.
 * @return Pin direction setting (0 or 1)
 */
bool TCA6424A::getPinDirection(uint16_t pin) {
    I2Cdev::readBit(devAddr, TCA6424A_RA_CONFIG0 + (pin / 8), pin % 8, buffer);
    return buffer[0];
}
/** Get all pin direction (I/O) settings from one bank.
 * @param bank Which bank to read (0/1/2 for P0*, P1*, P2* respectively)
 * @return 8 pins' direction settings (0 or 1 for each pin)
 */
uint8_t TCA6424A::getBankDirection(uint8_t bank) {
    I2Cdev::readByte(devAddr, TCA6424A_RA_CONFIG0 + bank, buffer);
    return buffer[0];
}
/** Get all pin direction (I/O) settings from all banks.
 * Reads into single 3-byte data container.
 * @param banks Container for all bank's pin values (P00-P27)
 */
void TCA6424A::getAllDirection(uint8_t *banks) {
    I2Cdev::readBytes(devAddr, TCA6424A_RA_CONFIG0, 3, banks);
}
/** Get all pin direction (I/O) settings from all banks.
 * Reads into individual 1-byte containers.
 * @param bank0 Container for Bank 0's pin values (P00-P07)
 * @param bank1 Container for Bank 1's pin values (P10-P17)
 * @param bank2 Container for Bank 2's pin values (P20-P27)
 */
void TCA6424A::getAllDirection(uint8_t *bank0, uint8_t *bank1, uint8_t *bank2) {
    I2Cdev::readBytes(devAddr, TCA6424A_RA_CONFIG0, 3, buffer);
    *bank0 = buffer[0];
    *bank1 = buffer[1];
    *bank2 = buffer[2];
}
/** Set a single pin's direction (I/O) setting.
 * @param pin Which pin to write (0-23)
 * @param direction Pin direction setting (0 or 1)
 */
void TCA6424A::setPinDirection(uint16_t pin, bool direction) {
    I2Cdev::writeBit(devAddr, TCA6424A_RA_CONFIG0 + (pin / 8), pin % 8, direction);
}
/** Set all pin direction (I/O) settings in one bank.
 * @param bank Which bank to read (0/1/2 for P0*, P1*, P2* respectively)
 * @param direction New pins' direction settings (0 or 1 for each pin)
 */
void TCA6424A::setBankDirection(uint8_t bank, uint8_t direction) {
    I2Cdev::writeByte(devAddr, TCA6424A_RA_CONFIG0 + bank, direction);
}
/** Set all pin direction (I/O) settings in all banks.
 * @param banks All pins' new direction values (P00-P27) in 3-byte array
 */
void TCA6424A::setAllDirection(uint8_t *banks) {
    I2Cdev::writeBytes(devAddr, TCA6424A_RA_CONFIG0 | TCA6424A_AUTO_INCREMENT, 3, banks);
}
/** Set all pin direction (I/O) settings in all banks.
 * @param bank0 Bank 0's new direction values (P00-P07)
 * @param bank1 Bank 1's new direction values (P10-P17)
 * @param bank2 Bank 2's new direction values (P20-P27)
 */
void TCA6424A::setAllDirection(uint8_t bank0, uint8_t bank1, uint8_t bank2) {
    buffer[0] = bank0;
    buffer[1] = bank1;
    buffer[2] = bank2;
    I2Cdev::writeBytes(devAddr, TCA6424A_RA_CONFIG0 | TCA6424A_AUTO_INCREMENT, 3, buffer);
}


text:
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using System;
using System.Collections.Generic;

namespace Microsoft.DataTransfer.AzureTable.FunctionalTests
{
    sealed class DictionaryTableEntity : TableEntity
    {
        private readonly IReadOnlyDictionary<string, object> data;

        public DictionaryTableEntity() { }

        public DictionaryTableEntity(string key, IReadOnlyDictionary<string, object> data)
        {
            PartitionKey = String.Empty;
            RowKey = key;
            this.data = data;
        }

        public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
        {
            var results = base.WriteEntity(operationContext);

            foreach (var item in data)
                results.Add(item.Key, AsEntityProperty(item.Value));

            return results;
        }

        private static EntityProperty AsEntityProperty(object value)
        {
            if (value is bool)
                return new EntityProperty((bool)value);

            if (value is byte[])
                return new EntityProperty((byte[])value);

            if (value is DateTime)
                return new EntityProperty((DateTime)value);

            if (value is DateTimeOffset)
                return new EntityProperty((DateTimeOffset)value);

            if (value is double || value is float)
                return new EntityProperty((double)value);

            if (value is Guid)
                return new EntityProperty((Guid)value);

            if (value is int)
                return new EntityProperty((int)value);

            if (value is long)
                return new EntityProperty((long)value);

            if (value is string)
                return new EntityProperty((string)value);

            return new EntityProperty((string)null);
        }
    }
}


text:
/**
 *

 * marcosnr
 * 28/02/2012
 */
package au.org.aurin.wif.io;

import javax.annotation.Resource;

import org.geotools.data.Query;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureStore;
import org.opengis.feature.simple.SimpleFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import au.org.aurin.wif.exception.config.WifInvalidConfigException;
import au.org.aurin.wif.model.WifProject;
import au.org.aurin.wif.model.allocation.AllocationLU;
import au.org.aurin.wif.model.allocation.AllocationScenario;
import au.org.aurin.wif.model.allocation.control.ALURule;
import au.org.aurin.wif.svc.ProjectService;
import au.org.aurin.wif.svc.WifKeys;
import au.org.aurin.wif.svc.allocation.AllocationScenarioService;

/**
 * The Class GeodataFiltererIT.
 */
@ContextConfiguration(locations = { "/test-integration-context.xml" })
public class GeodataFiltererIT extends AbstractTestNGSpringContextTests {

  /** The geodata finder. */
  @Autowired
  private GeodataFinder geodataFinder;

  /** The project service. */
  @Resource
  private ProjectService projectService;

  /** The geodata filterer. */
  @Autowired
  private GeodataFilterer geodataFilterer;

  /** The project. */
  private WifProject project;

  /** The allocation scenario service. */
  @Resource
  private AllocationScenarioService allocationScenarioService;

  /** The feature store. */
  private SimpleFeatureStore featureStore;

  /** The Constant LOGGER. */
  private static final Logger LOGGER = LoggerFactory
      .getLogger(GeodataFiltererIT.class);

  /**
   * Load wif project.
   *
   * @throws WifInvalidConfigException
   *           the wif invalid config exception
   * @throws Exception
   *           the exception
   */
  @BeforeClass(enabled = true, groups = { "setup", "geo", "database" })
  public void loadWifProject() throws WifInvalidConfigException, Exception {
    project = projectService.getProject(WifKeys.TEST_PROJECT_ID);
    Assert.assertNotNull(project);
    Assert.assertNotNull(project.getSuitabilityConfig());
    final String uazDBTable = project.getSuitabilityConfig()
        .getUnifiedAreaZone();
    featureStore = geodataFinder.getFeatureStorefromDB(uazDBTable);
  }

  /**
   * Gets the allocation rule.
   *
   * @return the allocation rule
   * @throws Exception
   *           the exception
   */
  @Test(enabled = true, groups = { "setup", "geo", "database" })
  public void getAllocationRule() throws Exception {

    LOGGER.debug("getAllocationRule: {}");
    final AllocationScenario allocationScenario = allocationScenarioService
        .getAllocationScenario(WifKeys.TEST_ALLOCATION_SCENARIO_ID);
    final AllocationLU residentiallu = project
        .getExistingLandUseByLabel("Conservation");
    final String existingLULabel = project.getExistingLUAttributeName();
    final String scoreLabel = residentiallu.getAssociatedLU()
        .getFeatureFieldName();

    final ALURule rule = geodataFilterer.getAllocationRule(residentiallu,
        allocationScenario, scoreLabel, existingLULabel, "", "", null, 0.0);
    final Query ruleQuery = rule.getRuleQuery();
    // ruleQuery.
    final SimpleFeatureCollection sortedUazCollection = featureStore
        .getFeatures(rule.getRuleQuery());
    LOGGER.debug("sortedUazCollection size: {}", sortedUazCollection.size());
    // Assert.assertEquals(sortedUazCollection.size(), 7834);
    final SimpleFeatureIterator its = sortedUazCollection.features();
    // 2. for each ORDERED UAZ
    int remaining = 0;
    final String areaLabel = allocationScenario.getWifProject().getAreaLabel();
    while (its.hasNext() && remaining < 10) {
      // 3. while there is a still area to allocate
      final SimpleFeature uazFeature = its.next();

      final String id = uazFeature.getID();
      LOGGER.debug("Allocating feature id: {}", id);
      final Double featureArea = (Double) uazFeature.getAttribute(areaLabel);
      LOGGER.debug("feature suitability score= {}, feature area = {},",
          uazFeature.getAttribute(scoreLabel), featureArea);
      remaining++;
    }
  }
}


text:
package org.elasticsearch.search.highlight;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.apache.lucene.search.highlight.DefaultEncoder;
import org.apache.lucene.search.highlight.Encoder;
import org.apache.lucene.search.highlight.SimpleHTMLEncoder;
import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.search.fetch.FetchSubPhase;
import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.search.lookup.SearchLookup;

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

public final class HighlightUtils {

    //U+2029 PARAGRAPH SEPARATOR (PS): each value holds a discrete passage for highlighting (postings highlighter)
    public static final char PARAGRAPH_SEPARATOR = 8233;

    private HighlightUtils() {

    }

    static List<Object> loadFieldValues(FieldMapper<?> mapper, SearchContext searchContext, FetchSubPhase.HitContext hitContext, boolean forceSource) throws IOException {
        List<Object> textsToHighlight;
        if (!forceSource && mapper.fieldType().stored()) {
            CustomFieldsVisitor fieldVisitor = new CustomFieldsVisitor(ImmutableSet.of(mapper.names().indexName()), false);
            hitContext.reader().document(hitContext.docId(), fieldVisitor);
            textsToHighlight = fieldVisitor.fields().get(mapper.names().indexName());
            if (textsToHighlight == null) {
                // Can happen if the document doesn't have the field to highlight
                textsToHighlight = ImmutableList.of();
            }
        } else {
            SearchLookup lookup = searchContext.lookup();
            lookup.setNextReader(hitContext.readerContext());
            lookup.setNextDocId(hitContext.docId());
            textsToHighlight = lookup.source().extractRawValues(mapper.names().sourcePath());
        }
        assert textsToHighlight != null;
        return textsToHighlight;
    }

    static class Encoders {
        static Encoder DEFAULT = new DefaultEncoder();
        static Encoder HTML = new SimpleHTMLEncoder();
    }
}


text:
export class Index {
  configureRouter(config, router) {
    config.map([
        {route:['', '/list'],       moduleId:'./list',          name:'list',        nav:false,      title:'Transfer-Out'},
        {route:'view/:id',          moduleId:'./view',          name:'view',        nav:false,      title:'View:Transfer-Out'},
        {route:'edit/:id',          moduleId:'./edit',          name:'edit',        nav:false,      title:'Edit:Transfer-Out'},
        {route:'create',            moduleId:'./create',        name:'create',      nav:false,      title:'Create:Transfer-Out'}
    ]);

    this.router = router;
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Microglaena wallrothiana var. septentriona

### Remarks
null


text:
var crocuta = require( '../../lib/client' )( );

var job = crocuta.createJob( 'hello world' ).joule( function( ){
	console.log( 'Hello Crocuta!' );
	done( 'Hello User!' );
});

crocuta.onReady( function( ){
	job.send( function( err, compiled_job ){
		compiled_job.start( undefined, function( err, result ){
			console.log( 'Complete' )
			console.log( result );
			crocuta.stop( );
		} );
	} );
} )


text:
/* global debuggerModule */
debuggerModule.controller("metricsController", ['$scope', '$interval', '$filter', 'iwcClient', "$log", function (scope, $interval, $filter, client, log) {
    var filter = $filter('filter');
    scope.updateFrequency = 1000;
    scope.metricWindow = 60000;
    scope.updateActive = false;
    scope.metrics = [];
    scope.metricsActive = 0;
    var metricsByName = {};

    scope.selectAllFilteredItems = function (state) {
        var filtered = filter(scope.metrics, {'name': scope.viewFilter});

        angular.forEach(filtered, function (item) {
            item.visible = state;
        });
    };

    var ensureGroup = function (name) {
//        if(scope.groupVisibility[name]===undefined) {
//            scope.groupVisibility[name]=(name.match("participants.*receivedPackets.rate1m")!==null);
//        }
        if (metricsByName[name] === undefined) {
            var metricDef = {
                name: name,
                visible: false
            };
            scope.metrics.push(metricDef);
            metricsByName[name] = metricDef;
        }

    };

    var updateWanted = function (name) {
        return metricsByName[name].visible;
    };

    var pushDataPoint = function (dataPoints, name, time, value) {
        ensureGroup(name);
        if (updateWanted(name)) {
            dataPoints.push({
                group: name,
                x: time,
                y: value
            });
        }
    };
    scope.refresh = function () {
        var dataPoints = [];
        var nowDate = new Date();
        client.getMetrics().then(function (metrics) {
            metrics.forEach(function (m) {
                if (typeof m.value === "object") {
                    for (var k in m.value) {
                        pushDataPoint(dataPoints, m.name + "." + k, nowDate, m.value[k]);
                    }
                } else {
                    pushDataPoint(dataPoints, m.name, nowDate, m.value);
                }
            });
            scope.$apply();
            scope.$broadcast('timeSeriesData', dataPoints);
            scope.metricsActive = dataPoints.length;
        });
    };

    client.connect().then(function () {
        scope.refresh();
    }).catch(function(err) {
        log.error(err);
    });

    var timer = null;
    var updateTimer = function () {
        if (timer) {
            $interval.cancel(timer);
        }
        if (scope.updateActive) {
            timer = $interval(scope.refresh, scope.updateFrequency);
        }
    };

    scope.$watch('updateActive', updateTimer);
    scope.$watch('updateFrequency', updateTimer);
}]);

debuggerModule.directive("metrics", [function () {
    return {
        restrict: 'E',
        templateUrl: 'templates/metrics.tpl.html'
    };
}]);

debuggerModule.directive("metricsToolbar", [function () {
    return {
        restrict: 'E',
        templateUrl: 'templates/metricsToolbar.tpl.html'
    };
}]);

debuggerModule.directive("metricsContent", [function () {
    return {
        restrict: 'E',
        templateUrl: 'templates/metricsContent.tpl.html'
    };
}]);

debuggerModule.directive("metricsDetail", [function () {
    return {
        restrict: 'E',
        templateUrl: 'templates/metricsDetail.tpl.html'
    };
}]);


text:
import React from 'react';
import {Provider} from 'react-redux';
import {mount} from 'enzyme';
import chai, {expect} from 'chai';
import chaiEnzyme from 'chai-enzyme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Login from '../../src/js/components/Login';
import configureStore from 'redux-mock-store';
import {reducer} from 'redux-form';

const muiTheme = getMuiTheme({}, { userAgent: false });

chai.use(chaiEnzyme());

const mockStore = configureStore();

/*global describe it*/
describe('<LoginDialog />', () => {
  'use strict';

  it('should not be visible if passed prop open=false', () => {
    const store = mockStore({ form: reducer });
    const wrapper = mount(
      <MuiThemeProvider muiTheme={muiTheme}>
        <Provider store={store}>
          <Login open={false} />
        </Provider>
      </MuiThemeProvider>
    );

    expect(wrapper).to.contain(<Login open={false} />);
    expect(wrapper.find('.Login')).to.have.style('visibility', 'hidden');
  });
});


text:
require "pivotal-tracker-console/displayable/main"
require "pivotal-tracker-console/displayable/project"
require "pivotal-tracker-console/displayable/story"


text:
import 'vs/css!./quickInput';
import * as dom from 'vs/base/browser/dom';
import { InputBox, IRange, MessageType } from 'vs/base/browser/ui/inputbox/inputBox';
import { inputBackground, inputForeground, inputBorder, inputValidationInfoBackground, inputValidationInfoForeground, inputValidationInfoBorder, inputValidationWarningBackground, inputValidationWarningForeground, inputValidationWarningBorder, inputValidationErrorBackground, inputValidationErrorForeground, inputValidationErrorBorder } from 'vs/platform/theme/common/colorRegistry';
import { ITheme } from 'vs/platform/theme/common/themeService';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { StandardKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import Severity from 'vs/base/common/severity';

const $ = dom.$;

export class QuickInputBox {

	private container: HTMLElement;
	private inputBox: InputBox;
	private disposables: IDisposable[] = [];

	constructor(
		private parent: HTMLElement
	) {
		this.container = dom.append(this.parent, $('.quick-input-box'));
		this.inputBox = new InputBox(this.container, null);
		this.disposables.push(this.inputBox);
	}

	onKeyDown = (handler: (event: StandardKeyboardEvent) => void): IDisposable => {
		return dom.addDisposableListener(this.inputBox.inputElement, dom.EventType.KEY_DOWN, (e: KeyboardEvent) => {
			handler(new StandardKeyboardEvent(e));
		});
	}

	onDidChange = (handler: (event: string) => void): IDisposable => {
		return this.inputBox.onDidChange(handler);
	}

	get value() {
		return this.inputBox.value;
	}

	set value(value: string) {
		this.inputBox.value = value;
	}

	select(range: IRange | null = null): void {
		this.inputBox.select(range);
	}

	setPlaceholder(placeholder: string) {
		this.inputBox.setPlaceHolder(placeholder);
	}

	get placeholder() {
		return this.inputBox.inputElement.getAttribute('placeholder');
	}

	set placeholder(placeholder: string) {
		this.inputBox.setPlaceHolder(placeholder);
	}

	get password() {
		return this.inputBox.inputElement.type === 'password';
	}

	set password(password: boolean) {
		this.inputBox.inputElement.type = password ? 'password' : 'text';
	}

	set enabled(enabled: boolean) {
		this.inputBox.setEnabled(enabled);
	}

	setAttribute(name: string, value: string) {
		this.inputBox.inputElement.setAttribute(name, value);
	}

	removeAttribute(name: string) {
		this.inputBox.inputElement.removeAttribute(name);
	}

	showDecoration(decoration: Severity): void {
		if (decoration === Severity.Ignore) {
			this.inputBox.hideMessage();
		} else {
			this.inputBox.showMessage({ type: decoration === Severity.Info ? MessageType.INFO : decoration === Severity.Warning ? MessageType.WARNING : MessageType.ERROR, content: '' });
		}
	}

	setFocus(): void {
		this.inputBox.focus();
	}

	layout(): void {
		this.inputBox.layout();
	}

	style(theme: ITheme) {
		this.inputBox.style({
			inputForeground: theme.getColor(inputForeground),
			inputBackground: theme.getColor(inputBackground),
			inputBorder: theme.getColor(inputBorder),
			inputValidationInfoBackground: theme.getColor(inputValidationInfoBackground),
			inputValidationInfoForeground: theme.getColor(inputValidationInfoForeground),
			inputValidationInfoBorder: theme.getColor(inputValidationInfoBorder),
			inputValidationWarningBackground: theme.getColor(inputValidationWarningBackground),
			inputValidationWarningForeground: theme.getColor(inputValidationWarningForeground),
			inputValidationWarningBorder: theme.getColor(inputValidationWarningBorder),
			inputValidationErrorBackground: theme.getColor(inputValidationErrorBackground),
			inputValidationErrorForeground: theme.getColor(inputValidationErrorForeground),
			inputValidationErrorBorder: theme.getColor(inputValidationErrorBorder),
		});
	}

	dispose() {
		this.disposables = dispose(this.disposables);
	}
}


text:
package flex.messaging.util;

import flex.messaging.FlexComponent;
import flex.messaging.config.ConfigMap;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * This class watches for changes on files and forces a re-deploy by touching the specified files.
 *
 * @exclude
 */
public class RedeployManager implements FlexComponent
{
    private boolean enabled;
    private long watchInterval;
    private List watches;
    private List touches;

    private ScheduledExecutorService redeployService;
    private boolean started;

    //--------------------------------------------------------------------------
    //
    // Constructor
    //
    //--------------------------------------------------------------------------

    /**
     * Constructs a new RedeployManager with default settings.
     */
    public RedeployManager()
    {
        this(null);
    }

    /**
     * Constructs a new RedeployManager with the supplied thread
     * factory.
     *
     * @param tf Thread factory to use for the scheduled service used.
     */
    public RedeployManager(ThreadFactory tf)
    {
        if (tf == null)
            tf = new MonitorThreadFactory();

        enabled = false;
        touches = new ArrayList();
        watchInterval = 20;
        watches = new ArrayList();

        redeployService = Executors.newSingleThreadScheduledExecutor(tf);
    }

    //--------------------------------------------------------------------------
    //
    // Initialize, validate, start, and stop methods.
    //
    //--------------------------------------------------------------------------

    /**
     * Implements FlexComponents.initialize.
     * This is no-op for RedeployManager as it does not have an id and all
     * its properties are directly settable.
     */
    public void initialize(String id, ConfigMap properties)
    {
        // No-op
    }

    /**
     * Implements FlexComponent.start.
     * Starts the RedeployManager.
     */
    public void start()
    {
        if (!started && enabled)
        {
            redeployService.schedule(new RedeployTask(), 20 * 1000, TimeUnit.MILLISECONDS);
            started = true;
        }
    }

    /**
     * Stops the RedeployManager.
     */
    public void stop()
    {
        if (started && enabled)
        {
            redeployService.shutdown();
            started = false;
        }
    }

    //--------------------------------------------------------------------------
    //
    // Public Methods
    //
    //--------------------------------------------------------------------------

    /**
     * Returns whether redeploy is enabled or not.
     *
     * @return true if redeploy is enabled; otherwise false.
     */
    public boolean isEnabled()
    {
        return enabled;
    }

    /**
     * Sets whether redeploy is enabled or not.
     *
     * @param enabled Whether redeploy is enabled or not.
     */
    public void setEnabled(boolean enabled)
    {
        this.enabled = enabled;
    }

    /**
     * Implements FlexComponent.isStarted.
     * Returns whether the RedeployManager is started or not.
     *
     * @return true if the component is started; otherwise false.
     */
    public boolean isStarted()
    {
        return started;
    }

    /**
     * Returns the watch interval.
     *
     * @return The watch interval.
     */
    public long getWatchInterval()
    {
        return watchInterval;
    }

    /**
     * Sets the watch interval.
     *
     * @param watchInterval The watch interval to set.
     */
    public void setWatchInterval(long watchInterval)
    {
        this.watchInterval = watchInterval;
    }

    /**
     * Returns the list of watch files.
     *
     * @return The list of watch files.
     */
    public List getWatchFiles()
    {
        return watches;
    }

    /**
     * Adds a watch file. Note that the watch file set with this method should
     * not contain the context.root token.
     *
     * @param watch The watch file to add.
     */
    public void addWatchFile(String watch)
    {
        watches.add(watch);
    }

    /**
     * Sets the list of watch files. Note that watch files set with this method
     * should not contain contain the context.root token.
     *
     * @param watches The list of watch files to set.
     */
    public void setWatchFiles(List watches)
    {
        this.watches = watches;
    }

    /**
     * Returns the list of touch files.
     *
     * @return The list of touch files.
     */
    public List getTouchFiles()
    {
        return touches;
    }

    /**
     * Adds a touch file. Note that the touch file set with this method should
     * not contain the context.root token.
     *
     * @param touch The touch file to add.
     */
    public void addTouchFile(String touch)
    {
        touches.add(touch);
    }

    /**
     * Sets the list of touch files. Note that touch files set with this method
     * should not contain the context.root token.
     *
     * @param touches The list of touch files to set.
     */
    public void setTouchFiles(List touches)
    {
        this.touches = touches;
    }

    /**
     * Forces the redeployment.
     */
    public void forceRedeploy()
    {
        Iterator iter = touches.iterator();
        while (iter.hasNext())
        {
            String filename = (String)iter.next();
            File file = new File(filename);
            if (file.exists() && (file.isFile() || file.isDirectory()))
            {
                file.setLastModified(System.currentTimeMillis());
            }
        }
    }

    //--------------------------------------------------------------------------
    //
    // Nested Classes
    //
    //--------------------------------------------------------------------------

    class MonitorThreadFactory implements ThreadFactory
    {
        public Thread newThread(Runnable r)
        {
            Thread t = new Thread(r);
            t.setDaemon(true);
            t.setName("RedeployManager");
            return t;
        }
    }

    class RedeployTask implements Runnable
    {
        public void run()
        {
            boolean redeploy = false;

            // check if any of the redeploy watches have changed
            Iterator iter = watches.iterator();
            while (iter.hasNext() && !redeploy)
            {
                WatchedObject watched = (WatchedObject)iter.next();
                if (!watched.isUptodate())
                    redeploy = true;
            }

            if (redeploy)
                forceRedeploy();
            else
                redeployService.schedule(new RedeployTask(), watchInterval * 1000, TimeUnit.MILLISECONDS);
        }
    }
}


text:
package net.bingyan.campass.rest;

import android.app.Application;

import com.google.gson.Gson;

import net.bingyan.campass.greendao.Cache;
import net.bingyan.campass.greendao.CacheDao;
import net.bingyan.campass.greendao.DaoSession;
import net.bingyan.campass.MyApplication;

import java.util.Date;

/**
 * Created by ant on 14-8-9.
 */
public  class CacheHelper<T> {
    Class<T> t;
    CacheDao cacheDao;

    public CacheHelper(Application app, Class<T> t) {
        DaoSession session = ((MyApplication) app).getDaoSession();
        cacheDao = session.getCacheDao();
        this.t=t;
    }

    public T getCache() {
        Cache cache = cacheDao.queryBuilder()
                .where(CacheDao.Properties.Name.eq(t.getName()))
                .unique();
        if (cache!=null) {
            return new Gson().fromJson(cache.getJson(), t);
        }
        return null;
    }

    public T getCache(String tag) {
        Cache cache = cacheDao.queryBuilder()
                .where(CacheDao.Properties.Name.eq(t.getName() + tag))
                .unique();
        if (cache!=null) {
            return new Gson().fromJson(cache.getJson(), t);
        }
        return null;
    }

    public  void putCache(T t) {
        Cache newsListCache = new Cache();
        newsListCache.setName(t.getClass().getName());
        newsListCache.setJson(new Gson().toJson(t));
        newsListCache.setDate(new Date());
//        cacheDao.insert(newsListCache);
        cacheDao.insertOrReplace(newsListCache);
    }

    public void putCache(T t, String tag) {
        Cache newsListCache = new Cache();
        newsListCache.setName(t.getClass().getName() + tag);
        newsListCache.setJson(new Gson().toJson(t));
        newsListCache.setDate(new Date());
        cacheDao.insertOrReplace(newsListCache);
    }

    public  T getCache(long time) {
        Cache cache = cacheDao.queryBuilder()
                .where(CacheDao.Properties.Name.eq(t.getName()))
                .unique();
        //getTime() milliseconds 毫秒
        if (cache!=null&&(new Date().getTime()-cache.getDate().getTime()<time)) {
            return new Gson().fromJson(cache.getJson(), t);
        }
        return null;
    }

}


text:
<head>
  <link href="http://gmpg.org/xfn/11" rel="profile" />
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <meta name="author" content="{{ site.author.name }}" />
  <meta name="description" content="{{ site.tagline }}" />
  <link rel="canonical" href="{{ site.url }}{{ page.url }}" />

  <title>
    {% if page.title %} {{ page.title }} · {{ site.title }} {% else %} {{
    site.title }} · {{ site.tagline }} {% endif %}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="/public/css/poole.css" />
  <link rel="stylesheet" href="/public/css/app.css" />
  <!-- Preload code syntax CSS -->
  <link rel="preload" as="style" href="/public/css/syntax.css" />

  <!-- Typekit -->
  <link rel="preload" as="style" href="https://use.typekit.net/cxf2crd.css" crossorigin>
  <link rel="stylesheet" href="https://use.typekit.net/cxf2crd.css" crossorigin>

  <!-- Icons -->
  <link rel="shortcut icon" href="/public/favicon.ico" />

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" href="/atom.xml" />
</head>


text:
package eu.modernmt.decoder;

import eu.modernmt.lang.LanguagePair;

import java.util.Set;

/**
 * Created by davide on 02/08/17.
 */
public interface DecoderListener {

    void onTranslationDirectionsChanged(Set<LanguagePair> directions);

}


text:
package asset_test

import (
	"cloud.google.com/go/asset/v1beta1"
	"golang.org/x/net/context"
	assetpb "google.golang.org/genproto/googleapis/cloud/asset/v1beta1"
)

func ExampleNewClient() {
	ctx := context.Background()
	c, err := asset.NewClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use client.
	_ = c
}

func ExampleClient_ExportAssets() {
	ctx := context.Background()
	c, err := asset.NewClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &assetpb.ExportAssetsRequest{
		// TODO: Fill request struct fields.
	}
	op, err := c.ExportAssets(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

func ExampleClient_BatchGetAssetsHistory() {
	ctx := context.Background()
	c, err := asset.NewClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}

	req := &assetpb.BatchGetAssetsHistoryRequest{
		// TODO: Fill request struct fields.
	}
	resp, err := c.BatchGetAssetsHistory(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}


text:
package org.oscm.dataservice.local;

import org.oscm.domobjects.CatalogEntry;
import org.oscm.domobjects.Marketplace;
import org.oscm.domobjects.Product;

/**
 * Factory for creating objects that have certain properties set with respect to
 * query results.
 *
 * @author Dirk Bernsau
 *
 */
public class QueryBasedObjectFactory {

    /**
     * Creates a CatalogEntry for given supplier and product on the
     * given marketplace and sets the position of the entry to the end of
     * existing products of this organization. The created catalog entry is not
     * yet persisted. If no marketplace is given, the local marketplace of the
     * supplier is assumed.
     *
     * @param product
     *            the product
     * @param marketplace
     *            the marketplace
     * @return the transient catalog entry
     */
    public static CatalogEntry createCatalogEntry(Product product,
            Marketplace marketplace) {
        // now generate a catalog entry and determine the next usable
        // position for the entry
        CatalogEntry catalogEntry = new CatalogEntry();
        catalogEntry.setProduct(product);
        catalogEntry.setMarketplace(marketplace);

        return catalogEntry;
    }

}


text:
{% extends 'base.html' %}

{% block title %}
  Answering machine
{% endblock %}

{% block subtitle %}
  Projects
{% endblock %}

{% block content %}

Projects available for registration

{% for project in projects %}

{{project.title}}

{% empty %}
  None.
{% endfor %}

{% endblock %}

{% block footer %}
Please use the link received by e-mail to answer your project questions.
{% endblock %}


text:
using System;
using System.Collections.Generic;
using System.Html;
using System.Runtime.CompilerServices;
using afung.MangaWeb3.Client.Modal;
using afung.MangaWeb3.Common;
using jQueryApi;

namespace afung.MangaWeb3.Client.Widget
{
    public class MangaPage
    {
        private int mangaId;
        private int page;
        private int width;
        private int height;
        private bool ltr;
        private int totalPages;
        private Action onload;
        private Action onfailure;
        private jQueryObject imageObject;
        private jQueryObject imagePart1Object;
        private jQueryObject imagePart2Object;
        private MangaPageRequest pageRequest;
        private int pageRequestDelay;
        private bool loaded;
        private bool loading;
        private bool unloaded;
        private int _offset;
        private int _offsetY;

        public int Offset
        {
            get
            {
                return _offset;
            }
            private set
            {
                _offset = Math.Round(value);
                UpdateCssTransform();
            }
        }

        public int OffsetY
        {
            get
            {
                return _offsetY;
            }
            set
            {
                _offsetY = Math.Round(value);
                UpdateCssTransform();
            }
        }

        public bool Loaded
        {
            get
            {
                return loaded;
            }
        }

        public int Page
        {
            get
            {
                return page;
            }
        }

        private ImageElement imageElement
        {
            get
            {
                return imageObject == null || !imageObject.Is("img") ? null : (ImageElement)imageObject.GetElement(0);
            }
        }

        private ImageElement imageElementPart1
        {
            get
            {
                return imagePart1Object == null ? null : (ImageElement)imagePart1Object.GetElement(0);
            }
        }

        private ImageElement imageElementPart2
        {
            get
            {
                return imagePart2Object == null ? null : (ImageElement)imagePart2Object.GetElement(0);
            }
        }

        public jQueryObject AttachedObject
        {
            get
            {
                return imageObject;
            }
        }

        public MangaPage(int mangaId, int page, int width, int height, bool ltr, int totalPages)
        {
            this.mangaId = mangaId;
            this.page = page;
            this.width = width - 2;
            this.height = height;
            this.ltr = ltr;
            this.totalPages = totalPages;
            unloaded = loading = loaded = false;
        }

        public void Load(Action onload, Action onfailure)
        {
            if (loaded)
            {
                onload();
                return;
            }

            this.onload = onload;
            this.onfailure = onfailure;

            loading = true;

            pageRequest = new MangaPageRequest();
            pageRequest.id = mangaId;
            pageRequest.page = ltr ? totalPages - page - 1 : page;
            pageRequest.width = Settings.DisplayType == 0 ? 0 : (int)Math.Round(width * Environment.PixelRatio); // Fit Height?
            pageRequest.height = Settings.DisplayType == 2 ? 0 : (int)Math.Round(height * Environment.PixelRatio); // Fit Width?
            pageRequest.dimensions = Environment.IsiOS && Settings.FixAutoDownscale;
            pageRequest.part = 0;

            Request.Send(pageRequest, MangaPageRequestSucess);
        }

        [AlternateSignature]
        private extern void MangaPageRequestSucess(JsonResponse response);
        private void MangaPageRequestSucess(MangaImageResponse response)
        {
            if (unloaded)
            {
                return;
            }

            if (response.status == 0)
            {
                imageObject = jQuery.FromHtml("").Bind(
                    "load",
                    delegate(jQueryEvent e)
                    {
                        // check iOS downscale issue
                        if (pageRequest.dimensions
                            && (pageRequest.width == 0 || (imageElement.Width < pageRequest.width && imageElement.Width < response.dimensions[0]))
                            && (pageRequest.height == 0 || (imageElement.Height < pageRequest.height && imageElement.Height < response.dimensions[1])))
                        {
                            imageObject.Unbind("load").Attribute("src", "");
                            imageObject = null;
                            LoadPart1();
                            return;
                        }

                        LoadFinish();
                    }).Attribute("src", response.url);
            }
            else if (response.status == 1)
            {
                Window.SetTimeout(
                    delegate
                    {
                        Request.Send(pageRequest, MangaPageRequestSucess);
                    },
                    pageRequestDelay = pageRequestDelay + 1000);
            }
            else
            {
                ErrorModal.ShowError(Strings.Get("MangaNotAvailable"));
                onfailure();
            }
        }

        private void LoadPart1()
        {
            pageRequestDelay = 0;
            pageRequest.dimensions = false;
            pageRequest.part = 1;
            Request.Send(pageRequest, MangaPagePart1RequestSucess);
        }

        [AlternateSignature]
        private extern void MangaPagePart1RequestSucess(JsonResponse response);
        private void MangaPagePart1RequestSucess(MangaImageResponse response)
        {
            if (unloaded)
            {
                return;
            }

            if (response.status == 0)
            {
                imagePart1Object = jQuery.FromHtml("").Bind(
                    "load",
                    delegate(jQueryEvent e)
                    {
                        LoadPart2();
                    }).Attribute("src", response.url);
            }
            else if (response.status == 1)
            {
                Window.SetTimeout(
                    delegate
                    {
                        Request.Send(pageRequest, MangaPagePart1RequestSucess);
                    },
                    pageRequestDelay = pageRequestDelay * 2 + 1000);
            }
            else
            {
                ErrorModal.ShowError(Strings.Get("MangaNotAvailable"));
                onfailure();
            }
        }

        private void LoadPart2()
        {
            pageRequestDelay = 0;
            pageRequest.part = 2;
            Request.Send(pageRequest, MangaPagePart2RequestSucess);
        }

        [AlternateSignature]
        private extern void MangaPagePart2RequestSucess(JsonResponse response);
        private void MangaPagePart2RequestSucess(MangaImageResponse response)
        {
            if (unloaded)
            {
                return;
            }

            if (response.status == 0)
            {
                imagePart2Object = jQuery.FromHtml("").Bind(
                    "load",
                    delegate(jQueryEvent e)
                    {
                        LoadFinish();
                    }).Attribute("src", response.url);
            }
            else if (response.status == 1)
            {
                Window.SetTimeout(
                    delegate
                    {
                        Request.Send(pageRequest, MangaPagePart2RequestSucess);
                    },
                    pageRequestDelay = pageRequestDelay * 2 + 1000);
            }
            else
            {
                ErrorModal.ShowError(Strings.Get("MangaNotAvailable"));
                onfailure();
            }
        }

        private void LoadFinish()
        {
            if (imageObject != null && imageObject.Is("img"))
            {
                if (Settings.DisplayType == 0)
                {
                    imageObject.Height(height);
                }
                else if (Settings.DisplayType == 2)
                {
                    imageObject.Width(width);
                }
                else
                {
                    double widthFactor = width / imageElement.Width;
                    double heightFactor = height / imageElement.Height;
                    double factor = widthFactor < heightFactor ? widthFactor : heightFactor;
                    imageObject
                        .Width(Math.Round(imageElement.Width * factor))
                        .Height(Math.Round(imageElement.Height * factor));
                }
            }
            else
            {
                imageObject = jQuery.FromHtml("

").Append(imagePart1Object).Append(imagePart2Object);

                if (Settings.DisplayType == 0)
                {
                    imagePart1Object.Height(height);
                    imagePart2Object.Height(height);
                    imageObject.Height(height).Width(imageElementPart1.Width / imageElementPart1.Height * height * 2);
                }
                else if (Settings.DisplayType == 2)
                {
                    int halfWidth = Math.Round(width / 2);
                    imagePart1Object.Width(halfWidth);
                    imagePart2Object.Width(halfWidth);
                    imageObject.Width(halfWidth * 2);
                }
                else
                {
                    double widthFactor = width / imageElementPart1.Width / 2;
                    double heightFactor = height / imageElementPart1.Height;
                    double factor = widthFactor < heightFactor ? widthFactor : heightFactor;
                    int halfWidth = Math.Round(imageElementPart1.Width * factor);
                    int sHeight = Math.Round(imageElementPart1.Height * factor);
                    imagePart1Object.Width(halfWidth).Height(sHeight);
                    imagePart2Object.Width(halfWidth).Height(sHeight);
                    imageObject.Width(halfWidth * 2).Height(sHeight);
                }
            }

            loading = false;
            loaded = true;
            onload();
        }

        public void AppendTo(jQueryObject mangaArea, int offset, int sign, MangaPage otherPage)
        {
            if (Settings.UseAnimation)
            {
                imageObject.AddClass("fade");
                Window.SetTimeout(
                    delegate
                    {
                        imageObject.AddClass("in");
                    },
                    1);
            }

            imageObject.AddClass("read-manga-page").AppendTo(mangaArea);
            Offset = offset + sign * otherPage.Width;
            OffsetY = Height > mangaArea.GetHeight() ? 0 : ((mangaArea.GetHeight() - Height) / 2);

        }

        public void Remove()
        {
            imageObject.Remove();
        }

        public int Width
        {
            get
            {
                return imageObject == null ? 0 : imageObject.GetOuterWidth();
            }
        }

        public int Height
        {
            get
            {
                return imageObject == null ? 0 : imageObject.GetOuterHeight();
            }
        }

        [AlternateSignature]
        public extern void Unload();
        public void Unload(bool loadNext)
        {
            if (Script.IsNullOrUndefined(loadNext)) loadNext = true;
            loaded = false;
            unloaded = true;

            if (imageObject != null && imageObject.Is("img"))
            {
                imageObject.Unbind("load").Attribute("src", "");
                imageObject = null;
            }

            if (imagePart1Object != null && imagePart1Object.Is("img"))
            {
                imagePart1Object.Unbind("load").Attribute("src", "");
                imagePart1Object = null;
            }

            if (imagePart2Object != null && imagePart2Object.Is("img"))
            {
                imagePart2Object.Unbind("load").Attribute("src", "");
                imagePart1Object = null;
            }

            if (loading && loadNext)
            {
                loading = false;
                onload();
            }
        }

        private void UpdateCssTransform()
        {
            if (Environment.IsIE9OrLower)
            {
                string cssValue = "translate(" + _offset + "px," + _offsetY + "px)";
                imageObject.CSS("transform", cssValue).CSS("-ms-transform", cssValue);
            }
            else
            {
                string cssValue = "translate3d(" + _offset + "px," + _offsetY + "px,0)";
                imageObject.CSS("transform", cssValue).CSS("-ms-transform", cssValue).CSS("-moz-transform", cssValue).CSS("-webkit-transform", cssValue).CSS("-o-transform", cssValue);
            }
        }
    }
}


text:
/**
 * @fileoverview An object representing a custom EE Function.
 */

goog.provide('ee.CustomFunction');

goog.require('ee.ComputedObject');
goog.require('ee.Function');
goog.require('ee.Number');
goog.require('ee.Serializer');
goog.require('ee.String');
goog.require('ee.Types');
goog.require('ee.rpc_node');
goog.require('goog.array');
goog.requireType('ee.Encodable');
goog.requireType('ee.api');

/**
 * Creates a function defined by a given expression with unbound variables.
 * The expression is created by evaluating the given JavaScript function
 * using variables as placeholders.
 *
 * @param {ee.Function.Signature} signature The function's signature. If any of
 *     the argument names are null, their names will be generated
 *     deterministically, based on the body.
 * @param {Function} body The JavaScript function to evaluate.
 *
 * @constructor
 * @extends {ee.Function}
 */
ee.CustomFunction = function(signature, body) {
  if (!(this instanceof ee.CustomFunction)) {
    return ee.ComputedObject.construct(ee.CustomFunction, arguments);
  }

  const vars = [];
  const args = signature['args'];
  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    const type = ee.Types.nameToClass(arg['type']);
    vars.push(ee.CustomFunction.variable(type, arg['name']));
  }

  // Check that the method returns something, before we try
  // encoding it in resolveNamelessArgs_().
  if (body.apply(null, vars) === undefined) {
    throw Error('User-defined methods must return a value.');
  }

  /**
   * The signature of the function.
   * @type {ee.Function.Signature}
   * @private
   */
  this.signature_ = ee.CustomFunction.resolveNamelessArgs_(
      signature, vars, body);

  /**
   * The function evaluated using placeholders.
   * @type {*}
   * @private
   */
  this.body_ = body.apply(null, vars);
};
goog.inherits(ee.CustomFunction, ee.Function);
// Exporting manually to avoid marking the class public in the docs.
goog.exportSymbol('ee.CustomFunction', ee.CustomFunction);

/** @override */
ee.CustomFunction.prototype.encode = function(encoder) {
  return {
    'type': 'Function',
    'argumentNames': goog.array.map(
        this.signature_['args'], function(arg) { return arg['name']; }),
    'body': encoder(this.body_)
  };
};

/** @override @return {!ee.api.ValueNode} */
ee.CustomFunction.prototype.encodeCloudValue = function(
    /** !ee.Encodable.Serializer */ serializer) {
  return ee.rpc_node.functionDefinition(
      this.signature_['args'].map(arg => arg['name']),
      serializer.makeReference(this.body_));
};

/** @override @return {!ee.api.ValueNode} */
ee.CustomFunction.prototype.encodeCloudInvocation = function(
    /** !ee.Encodable.Serializer */ serializer, /** ? */ args) {
  return ee.rpc_node.functionByReference(serializer.makeReference(this), args);
};

/** @override */
ee.CustomFunction.prototype.getSignature = function() {
  return this.signature_;
};

/**
 * Returns a placeholder variable with a given name that implements a given
 * EE type.
 *
 * @param {Function} type A type to mimic.
 * @param {string?} name The name of the variable as it will appear in the
 *     arguments of the custom functions that use this variable. If null, a
 *     name will be auto-generated in resolveNamelessArgs_().
 * @return {*} A variable with the given name implementing the given type.
 */
ee.CustomFunction.variable = function(type, name) {
  type = type || Object;
  if (!(type.prototype instanceof ee.ComputedObject)) {
    // Try to convert to an EE type.
    if (!type || type == Object) {
      type = ee.ComputedObject;
    } else if (type == String) {
      type = ee.String;
    } else if (type == Number) {
      type = ee.Number;
    } else if (type == Array) {
      type = goog.global['ee']['List'];
    } else {
      throw Error('Variables must be of an EE type, ' +
                  'e.g. ee.Image or ee.Number.');
    }
  }

  /**
   * Avoid Object.create() for backwards compatibility.
   * @constructor
   */
  const klass = function(name) {
    this.func = null;
    this.args = null;
    this.varName = name;
  };
  klass.prototype = type.prototype;
  return new klass(name);
};

/**
 * Creates a CustomFunction calling a given native function with the specified
 * return type and argument types and auto-generated argument names.
 *
 * @param {Function} func The native function to wrap.
 * @param {string|Function} returnType The type of the return value, either
 *     as a string or a constructor/class reference.
 * @param {Array.<string|Function>} arg_types The types of the arguments,
 *     either as strings or constructor/class references.
 * @return {!ee.CustomFunction} The constructed CustomFunction.
 */
ee.CustomFunction.create = function(func, returnType, arg_types) {
  const stringifyType = function(type) {
    if (typeof type === 'string') {
      return type;
    } else {
      return ee.Types.classToName(type);
    }
  };
  const args = goog.array.map(arg_types, function(argType) {
    return {
      'name': null,
      'type': stringifyType(argType)
    };
  });
  const signature = {
    'name': '',
    'returns': stringifyType(returnType),
    'args': args
  };
  return new ee.CustomFunction(signature, func);
};

/**
 * Deterministically generates names for the unnamed variables, based on the
 * body.
 *
 * @param {!ee.Function.Signature} signature The signature which may contain
 *     null argument names.
 * @param {!Array<!ee.ComputedObject>} vars A list of variables, some of which
 *     may be nameless. These will be updated to include names when this
 *     method returns.
 * @param {!Function} body The JavaScript function to evaluate.
 * @return {!ee.Function.Signature} The signature with null arg names resolved.
 * @private
 * @suppress {accessControls} We are accessing the protected varName.
 */
ee.CustomFunction.resolveNamelessArgs_ = function(signature, vars, body) {
  const namelessArgIndices = [];
  for (let i = 0; i < vars.length; i++) {
    if (vars[i].varName === null) {
      namelessArgIndices.push(i);
    }
  }

  // Do we have any nameless arguments at all?
  if (namelessArgIndices.length === 0) {
    return signature;
  }

  // Generate the name base by counting the number of custom functions
  // within the body.
  const countFunctions = (expression) => {
    const countNodes = (nodes) =>
        nodes.map(countNode).reduce((a, b) => a + b, 0);
    const countNode = (node) => {
      if (node.functionDefinitionValue) {
        return 1;
      } else if (node.arrayValue) {
        return countNodes(node.arrayValue.values);
      } else if (node.dictionaryValue) {
        return countNodes(Object.values(node.dictionaryValue.values));
      } else if (node.functionInvocationValue) {
        const fn = node.functionInvocationValue;
        return countNodes(Object.values(fn.arguments));
      }
      return 0;
    };
    return countNodes(Object.values(expression.values));
  };

  // There are three function building phases, which each call body.apply:
  // 1 - Check Return.  The constructor verifies that body.apply returns a
  // result, but does not try to serialize the result. If the function tries to
  // use unbound variables (eg, using .getInfo() or print()), ComputedObject
  // will throw an exception when these calls try to serialize themselves, so
  // that unbound variables are not passed in server calls.
  // 2 - Count Functions.  We serialize the result here. At this point all
  // variables must have names for serialization to succeed, but we don't yet
  // know the correct function depth. So we serialize with unboundName set to
  // '<unbound>', which should silently succeed. If this does end up in server
  // calls, the function is very unusual: the first call doesn't use unbound
  // variables but the second call does. In this rare case we will return server
  // errors complaining about <unbound>.
  // 3 - Final Serialize.  Finally, the constructor calls body.apply with the
  // correct, depth-dependent names, which are used when the CustomFunction
  // is serialized and sent to the server.
  const serializedBody = ee.Serializer.encodeCloudApiExpression(
      body.apply(null, vars), '<unbound>');
  const baseName = `_MAPPING_VAR_${countFunctions(serializedBody)}_`;

  // Update the vars and signature by the name.
  for (let i = 0; i < namelessArgIndices.length; i++) {
    const index = namelessArgIndices[i];
    const name = baseName + i;
    vars[index].varName = name;
    signature['args'][index]['name'] = name;
  }

  return signature;
};


text:
namespace BearCore
{
	class BEARTOOL_API BearWindow
	{
	public:
		enum style
		{
			None = 0,
			Titlebar = 1 << 0,
			Resize = 1 << 1,
			Close = 1 << 2,
			Fullscreen = 1 << 3,
			Default = Titlebar | Resize | Close
		};
		enum show
		{
			Maximized=6,
			Minimized=3,
			Normal=1
		};
		BearWindow();
		BearWindow(const BearWindow& right);
		BearWindow& operator =(const BearWindow& right);
		void swap(BearWindow& right);
		BearWindow(const char* Title, uint32 x, uint32 y, uint32 width, uint32 height, style Style=Default,show Show=Normal);
		BearWindow(const char*Title, uint32 width, uint32 height, style Style=Fullscreen, show Show=Normal);
		void create(const char*Title, uint32 x, uint32 y, uint32 width, uint32 height, style Style = Default, show Show = Normal);
		void create(const char* Title, uint32 width, uint32 height, style Style = Fullscreen, show Show = Normal);
		void CreateLogo(const char* bmppath);
		void destory();
		bool isDraw(bool onclosed);
		void setTitle(const char*Title);
		void setPosition(uint32 x, uint32 y);
		void setSizeCentr(uint32 x, uint32 y);
		void setSize(uint32 width, uint32 height);
		void setFullScreen(bool fs);
		void setIcon(uint32 size_x, uint32 size_y, uint8*pixel);
		void setStyle(style Style);
		show getShow() const;
		style getStyle() const;
		const BearString& getTitle() const;
		void setShow(show Show);
		static BearVector2<uint32> getSizeScreen() ;
		BearVector2<uint32> getPosition() const;
		BearVector2<uint32> getSize() const;
		bool isFullScreen() const;
		bool isActive() const;
		void*createPanel(uint32 x, uint32 y, uint32 width, uint32 height);
		void* getHWND() const;
		~BearWindow();
	private:
		BearVector2<uint32> m_pos;
		BearVector2<uint32> m_size;
		void create(show Show);
	    void* m_win;
		bool m_fullscreen;
		BearString m_title;
		show m_show;
		style m_style;
	};
}


text:
echo "### Fetch all the latest Pi updates."
apt-get -y update
apt-get -y dist-upgrade
echo ""

echo "### Update the kernel and firmware to latest versions."
rpi-update
echo ""


text:
FULLPROOF STORES
================

#What's a store ?
A store is an interface to some form data storage provided by the javascript runtime, and used by fullproof to store an
inverted index. A store is expected to manage the creation and deletion of a set of inverted indexes.

#What's an inverted index ?
Inverted indexes (or simply "indexes" in the context of fullproof) manage tuplets <term, value> or <term, value, score>, where term is a linguistic token (for instance an english word),
and value is an application-specific primary value (typically a number or a string specific to your application, that allows it to retrieve a specific document.
The score is an optional data, used by the ScoringEngine (so don't bother with it if you're using
the BooleanEngine) to sort the final result sets (typically, an higher score means the word is more relevant, while a lower score means
it's less relevant to the document).

#Store functions
A store must implement the following functions:

##open(caps, reqIndexArray, callback, errorCallback)
Opens a store and configure it. Arguments:
- caps: a fullproof.Capabilities object that provides information to the store (dbName and dbSize)
- reqIndexArray: an array of fullproof.IndexRequest objects that describe all the indexes to be created by the store.
- callback: a function called when the engine completes the indexes opening/creation/initialization process.
- errorCallback: if some problem occurs preventing the store to open the indexes, this function is called.

##close(callback)
Closes a store and all its indexes. The callback function is called when everything is closed.

#Index functions
An index must implement the following functions

##clear(callback)
Delete all the data stored by this index (ie. after this call, it's empty). The next time the index is opened,
the initializer will be called, in order to populate the index.
The callback is called with a reference to this index when the action is complete.

##inject(word, value, callback)
if value is a fullproof.ScoredEntry, it is used to store a value and its score
otherwise, the store injects in its database the value as is, associated to the specified term).
The callback is called when the operation is complete, with parameter true for success, or false if the
injection failed.

##injectBulk(wordArray, valueArray, callback)
like inject, but massively inject an array of entries.

##lookup(word, callback)
calls the callback with an instance of a fullproof.ResultSet that holds the data associated to the word.
The objects contained in the resultset can be fullproof.ScoredElement if the index was created with the
useScore:true parameter, or just the values (as injected) otherwise.
Callers can modify the result set, but must not modify the objects contained (as they may be referenced by
the index for storage or caching).


text:
package sagan.site.guides;

import java.util.Arrays;
import java.util.Optional;

import sagan.site.support.ResourceNotFoundException;
import sagan.site.support.nav.Navigation;
import sagan.site.support.nav.Section;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Controller that handles requests for tutorial docs at /guides/tutorials.
 *
 * @see GettingStartedGuideController
 */
@Controller
@Navigation(Section.GUIDES)
@RequestMapping("/guides/topicals")
class TopicalController {

	private Topicals topicals;

	@Autowired
	public TopicalController(Topicals topicals) {
		this.topicals = topicals;
	}

	@GetMapping("/{topical}")
	public String viewTutorial(@PathVariable String topical, Model model) {
		boolean knownTopical = Arrays.stream(this.topicals.findAll()).anyMatch(header -> header.getName().equals(topical));
		if (knownTopical) {
			Topical topicalGuide = this.topicals.findByName(topical);
			model.addAttribute("guide", topicalGuide);
			model.addAttribute("description",
					"this topical is designed to be read and comprehended in under an hour, it provides broad "
							+ "coverage of a topic that is possibly nuanced or requires deeper understanding than you would get from a getting started guide");
			return "guides/gs/guide";
		}
		throw new ResourceNotFoundException("Missing topical guide: '" + topical + "'");
	}

}


text:
//
//  CJLocationChangeModel.h
//  CJTotalDemo
//
//  Created by ciyouzen on 2018/1/18.
//  Copyright © 2018年 dvlproad. All rights reserved.
//

#import <Foundation/Foundation.h>

///距离新增的模型
@interface CJLocationChangeModel : NSObject

@property (nonatomic, assign) double addedMilesFromBMK;     /**< 这段时间内新增的距离(百度计算) */
@property (nonatomic, assign) double addedMilesFromSystem;  /**< 这段时间内新增的距离(系统计算) */
@property (nonatomic, assign) NSInteger secondInterval;     /**< 这段时间内间隔的时长 */
@property (nonatomic, assign) double KMHSpeed;              /**< 这段时间内的时速(时速计算采用百度计算出来的距离) */

@end