text:
platform: windows 10
device: se-8124
language: csharp
---

Run a simple Csharp sample on SE-8124 device running Windows 10
===
---

# Table of Contents

-   [Introduction](#Introduction)
-   [Step 1: Prerequisites](#Prerequisites)
-   [Step 2: Prepare your Device](#PrepareDevice)
-   [Step 3: Build and Run the Sample](#Build)

# Introduction

**About this document**

This document describes how to connect SE-8124 device running Windows 10 with Azure IoT SDK. This multi-step process includes:
-   Configuring Azure IoT Hub
-   Registering your IoT device
-   Build and deploy Azure IoT SDK on device

# Step 1: Prerequisites

You should have the following items ready before beginning the process:

-   [Prepare your development environment][setup-devbox-windows]
-   [Setup your IoT hub][lnk-setup-iot-hub]
-   [Provision your device and get its credentials][lnk-manage-iot-hub]
-   SE-8124 device.

# Step 2: Prepare your Device

-   Power on SE-8124 (Windows 10 Enterprise).
-   Connect the device to network to use Internet access.
-   Turn on [Developer mode](https://msdn.microsoft.com/library/windows/apps/xaml/dn706236.aspx)
-   Make sure **SE-8124** is ready as per instructions given on [Prepare your development environment](https://github.com/Azure/azure-iot-sdks/blob/master/csharp/device/doc/devbox_setup.md#prerequisites)
-   Follow the instructions from [device website](http://www.protech-usa.net/new_web/Products/product_en.asp?P_id=546&P_typeNo=4&P_subtypeNo=2#tab-1)

# Step 3: Build and Run the sample

-   Download the [Azure IoT SDK](https://github.com/Azure/azure-iot-sdks) and the sample programs and save them to your local repository.
-   Start a new instance of Visual Studio 2015.
-   Open the **iothub_csharp_client.sln** solution in the `csharp\device` folder in your local copy of the repository.
-   In Visual Studio, from Solution Explorer, navigate to the **samples** folder.
-   In the **DeviceClientAmqpSample** project, open the ***Program.cs*** file.
-   Locate the following code in the file:

        private const string DeviceConnectionString = "<replace>";

-   Replace `<replace>` with the connection string for your device.
-   In **Solution Explorer**, right-click the **DeviceClientAmqpSample** project, click **Debug**, and then click **Start new instance** to build and run the sample. The console displays messages as the application sends device-to-cloud messages to IoT Hub.
-   Use the **DeviceExplorer** utility to observe the messages IoT Hub receives from the **Device Client AMQP Sample** application.
-   Refer "Monitor device-to-cloud events" in [DeviceExplorer Usage document](https://github.com/Azure/azure-iot-sdks/blob/master/tools/DeviceExplorer/doc/how_to_use_device_explorer.md) to see the data your device is sending.
-   Refer "Send cloud-to-device messages" in [DeviceExplorer Usage document](https://github.com/Azure/azure-iot-sdks/blob/master/tools/DeviceExplorer/doc/how_to_use_device_explorer.md) for instructions on sending messages to device.

[setup-devbox-windows]: https://github.com/Azure/azure-iot-sdks/blob/master/c/doc/devbox_setup.md
[lnk-setup-iot-hub]: ../setup_iothub.md
[lnk-manage-iot-hub]: ../manage_iot_hub.md


text:
package com.gentics.mesh.test.assertj;

import com.gentics.mesh.search.verticle.ElasticsearchProcessVerticle;
import com.gentics.mesh.test.context.MeshTestContext;

public final class MeshCoreAssertion {

	public static MeshTestContextAssert assertThat(MeshTestContext actual) {
		return new MeshTestContextAssert(actual);
	}

	public static SearchVerticleAssert assertThat(ElasticsearchProcessVerticle actual) {
		return new SearchVerticleAssert(actual);
	}
}

redpajama_set_name: RedPajamaGithub


text:
var http = require('http');
var url = require('url');

function start(route) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log('Request for' + pathname + 'received.');

    route(pathname);

    response.writeHeader(200, {'Content-Type': 'text/plain'});
    response.write('hello world');
    response.end();
  }
  http.createServer(onRequest).listen(8088);
  console.log('Server is running at 8088');

  // __filename: 输出脚本所在位置的绝对路径
  console.log('server filename:', __filename);

  // __dirname: 输出脚本所在目录
  console.log('server dirname', __dirname);
}

exports.start = start;


text:
/*
 * @test
 * @bug 6971877
 * @author Joseph D. Darcy
 * @summary Verify a primary exception suppresses all throwables
 */

public class TwrSuppression implements AutoCloseable {
    public static void main(String... args) throws Throwable {
        try {
            try (TwrSuppression r1 = new TwrSuppression(false);
                 TwrSuppression r2 = new TwrSuppression(true)) {
                throw new RuntimeException();
            }
        } catch(RuntimeException e) {
            Throwable[] suppressedExceptions = e.getSuppressed();
            int length = suppressedExceptions.length;
            if (length != 2)
                throw new RuntimeException("Unexpected length " + length);

            if (suppressedExceptions[0].getClass() != Error.class ||
                suppressedExceptions[1].getClass() != Exception.class) {
                System.err.println("Unexpected suppressed types!");
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }

    private boolean throwError;

    private TwrSuppression(boolean throwError) {
        this.throwError = throwError;
    }

    @Override
    public void close() throws Exception {
        if (throwError) {
            throw new Error();
        } else {
            throw new Exception();
        }
    }
}


text:
#import <Foundation/Foundation.h>
#import <SDWebImage/SDWebImageDownloaderOperation.h>

/**
 *  A class that fits the NSOperation+SDWebImageDownloaderOperation requirement so we can test
 */
@interface SDWebImageTestDownloadOperation : NSOperation <SDWebImageDownloaderOperation>

@property (nonatomic, strong, nullable) NSURLRequest *request;
@property (nonatomic, strong, nullable) NSURLResponse *response;

@end


text:
angular.module('alv-ch-ng.ui-forms').run(['$templateCache', function($templateCache) {
  'use strict';

  $templateCache.put('template/typeahead/typeahead-match.html',
    ""
  );

  $templateCache.put('template/typeahead/typeahead-popup.html',
    "
\n" +
    "
\n" +
    "

\n" +
    "
\n" +
    "
"
  );

  $templateCache.put('template/tooltip/tooltip-html-unsafe-popup.html',
    "
\n" +
    "

\n" +
    "

\n" +
    "
\n"
  );

  $templateCache.put('template/tooltip/tooltip-popup.html',
    "
\n" +
    "

\n" +
    "

\n" +
    "
\n"
  );

}]);


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace TeachersAssistant {

    public partial class WebUserControlStudentCard {

        /// <summary>
        /// TableCardLayout control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Table TableCardLayout;

        /// <summary>
        /// ImageStudent control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Image ImageStudent;

        /// <summary>
        /// LabelStudentName control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelStudentName;

        /// <summary>
        /// LabelStudentId control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelStudentId;

        /// <summary>
        /// LabelStudentGender control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelStudentGender;

        /// <summary>
        /// LabelStudentEmail control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelStudentEmail;

        /// <summary>
        /// LabelStudentCgpa control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelStudentCgpa;

        /// <summary>
        /// LabelStudentSemester control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelStudentSemester;

        /// <summary>
        /// LabelCreditsCompleted control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label LabelCreditsCompleted;
    }
}


text:
package org.apache.accumulo.server.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.KeyExtent;
import org.apache.accumulo.core.data.PartialKey;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.file.FileOperations;
import org.apache.accumulo.core.file.FileSKVIterator;
import org.apache.accumulo.core.file.FileSKVWriter;
import org.apache.accumulo.core.file.rfile.RFile;
import org.apache.accumulo.core.file.rfile.RFileOperations;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.accumulo.core.iterators.system.MultiIterator;
import org.apache.accumulo.core.util.CachedConfiguration;
import org.apache.accumulo.core.util.LocalityGroupUtil;
import org.apache.accumulo.core.volume.Volume;
import org.apache.accumulo.server.ServerConstants;
import org.apache.accumulo.server.fs.FileRef;
import org.apache.accumulo.server.fs.VolumeManager;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
import org.apache.log4j.Logger;

public class FileUtil {

  public static class FileInfo {
    Key firstKey = new Key();
    Key lastKey = new Key();

    public FileInfo(Key firstKey, Key lastKey) {
      this.firstKey = firstKey;
      this.lastKey = lastKey;
    }

    public Text getFirstRow() {
      return firstKey.getRow();
    }

    public Text getLastRow() {
      return lastKey.getRow();
    }
  }

  private static final Logger log = Logger.getLogger(FileUtil.class);

  private static Path createTmpDir(AccumuloConfiguration acuConf, VolumeManager fs) throws IOException {
    String accumuloDir = fs.choose(ServerConstants.getTemporaryDirs());

    Path result = null;
    while (result == null) {
      result = new Path(accumuloDir + "/tmp/idxReduce_" + String.format("%09d", new Random().nextInt(Integer.MAX_VALUE)));

      try {
        fs.getFileStatus(result);
        result = null;
        continue;
      } catch (FileNotFoundException fne) {
        // found an unused temp directory
      }

      fs.mkdirs(result);

      // try to reserve the tmp dir
      // In some versions of hadoop, two clients concurrently trying to create the same directory might both return true
      // Creating a file is not subject to this, so create a special file to make sure we solely will use this directory
      if (!fs.createNewFile(new Path(result, "__reserve")))
        result = null;
    }
    return result;
  }

  public static Collection<String> reduceFiles(AccumuloConfiguration acuConf, Configuration conf, VolumeManager fs, Text prevEndRow, Text endRow,
      Collection<String> mapFiles, int maxFiles, Path tmpDir, int pass) throws IOException {
    ArrayList<String> paths = new ArrayList<String>(mapFiles);

    if (paths.size() <= maxFiles)
      return paths;

    String newDir = String.format("%s/pass_%04d", tmpDir, pass);

    int start = 0;

    ArrayList<String> outFiles = new ArrayList<String>();

    int count = 0;

    while (start < paths.size()) {
      int end = Math.min(maxFiles + start, paths.size());
      List<String> inFiles = paths.subList(start, end);

      start = end;

      String newMapFile = String.format("%s/%04d.%s", newDir, count++, RFile.EXTENSION);

      outFiles.add(newMapFile);
      FileSystem ns = fs.getVolumeByPath(new Path(newMapFile)).getFileSystem();
      FileSKVWriter writer = new RFileOperations().openWriter(newMapFile.toString(), ns, ns.getConf(), acuConf);
      writer.startDefaultLocalityGroup();
      List<SortedKeyValueIterator<Key,Value>> iters = new ArrayList<SortedKeyValueIterator<Key,Value>>(inFiles.size());

      FileSKVIterator reader = null;
      try {
        for (String s : inFiles) {
          ns = fs.getVolumeByPath(new Path(s)).getFileSystem();
          reader = FileOperations.getInstance().openIndex(s, ns, ns.getConf(), acuConf);
          iters.add(reader);
        }

        MultiIterator mmfi = new MultiIterator(iters, true);

        while (mmfi.hasTop()) {
          Key key = mmfi.getTopKey();

          boolean gtPrevEndRow = prevEndRow == null || key.compareRow(prevEndRow) > 0;
          boolean lteEndRow = endRow == null || key.compareRow(endRow) <= 0;

          if (gtPrevEndRow && lteEndRow)
            writer.append(key, new Value(new byte[0]));

          if (!lteEndRow)
            break;

          mmfi.next();
        }
      } finally {
        try {
          if (reader != null)
            reader.close();
        } catch (IOException e) {
          log.error(e, e);
        }

        for (SortedKeyValueIterator<Key,Value> r : iters)
          try {
            if (r != null)
              ((FileSKVIterator) r).close();
          } catch (IOException e) {
            // continue closing
            log.error(e, e);
          }

        try {
            writer.close();
        } catch (IOException e) {
          log.error(e, e);
          throw e;
        }
      }
    }

    return reduceFiles(acuConf, conf, fs, prevEndRow, endRow, outFiles, maxFiles, tmpDir, pass + 1);
  }

  public static SortedMap<Double,Key> findMidPoint(VolumeManager fs, AccumuloConfiguration acuConf, Text prevEndRow, Text endRow, Collection<String> mapFiles,
      double minSplit) throws IOException {
    return findMidPoint(fs, acuConf, prevEndRow, endRow, mapFiles, minSplit, true);
  }

  public static double estimatePercentageLTE(VolumeManager fs, AccumuloConfiguration acuconf, Text prevEndRow, Text endRow, Collection<String> mapFiles,
      Text splitRow) throws IOException {

    Configuration conf = CachedConfiguration.getInstance();

    Path tmpDir = null;

    int maxToOpen = acuconf.getCount(Property.TSERV_TABLET_SPLIT_FINDMIDPOINT_MAXOPEN);
    ArrayList<FileSKVIterator> readers = new ArrayList<FileSKVIterator>(mapFiles.size());

    try {
      if (mapFiles.size() > maxToOpen) {
        tmpDir = createTmpDir(acuconf, fs);

        log.debug("Too many indexes (" + mapFiles.size() + ") to open at once for " + endRow + " " + prevEndRow + ", reducing in tmpDir = " + tmpDir);

        long t1 = System.currentTimeMillis();
        mapFiles = reduceFiles(acuconf, conf, fs, prevEndRow, endRow, mapFiles, maxToOpen, tmpDir, 0);
        long t2 = System.currentTimeMillis();

        log.debug("Finished reducing indexes for " + endRow + " " + prevEndRow + " in " + String.format("%6.2f secs", (t2 - t1) / 1000.0));
      }

      if (prevEndRow == null)
        prevEndRow = new Text();

      long numKeys = 0;

      numKeys = countIndexEntries(acuconf, prevEndRow, endRow, mapFiles, true, conf, fs, readers);

      if (numKeys == 0) {
        // not enough info in the index to answer the question, so instead of going to
        // the data just punt and return .5
        return .5;
      }

      List<SortedKeyValueIterator<Key,Value>> iters = new ArrayList<SortedKeyValueIterator<Key,Value>>(readers);
      MultiIterator mmfi = new MultiIterator(iters, true);

      // skip the prevendrow
      while (mmfi.hasTop() && mmfi.getTopKey().compareRow(prevEndRow) <= 0) {
        mmfi.next();
      }

      int numLte = 0;

      while (mmfi.hasTop() && mmfi.getTopKey().compareRow(splitRow) <= 0) {
        numLte++;
        mmfi.next();
      }

      if (numLte > numKeys) {
        // something went wrong
        throw new RuntimeException("numLte > numKeys " + numLte + " " + numKeys + " " + prevEndRow + " " + endRow + " " + splitRow + " " + mapFiles);
      }

      // do not want to return 0% or 100%, so add 1 and 2 below
      return (numLte + 1) / (double) (numKeys + 2);

    } finally {
      cleanupIndexOp(acuconf, tmpDir, fs, readers);
    }
  }

  /**
   *
   * @param mapFiles
   *          - list MapFiles to find the mid point key
   *
   *          ISSUES : This method used the index files to find the mid point. If the map files have different index intervals this method will not return an
   *          accurate mid point. Also, it would be tricky to use this method in conjunction with an in memory map because the indexing interval is unknown.
   */
  public static SortedMap<Double,Key> findMidPoint(VolumeManager fs, AccumuloConfiguration acuConf, Text prevEndRow, Text endRow, Collection<String> mapFiles,
      double minSplit, boolean useIndex) throws IOException {
    Configuration conf = CachedConfiguration.getInstance();

    Collection<String> origMapFiles = mapFiles;

    Path tmpDir = null;

    int maxToOpen = acuConf.getCount(Property.TSERV_TABLET_SPLIT_FINDMIDPOINT_MAXOPEN);
    ArrayList<FileSKVIterator> readers = new ArrayList<FileSKVIterator>(mapFiles.size());

    try {
      if (mapFiles.size() > maxToOpen) {
        if (!useIndex)
          throw new IOException("Cannot find mid point using data files, too many " + mapFiles.size());
        tmpDir = createTmpDir(acuConf, fs);

        log.debug("Too many indexes (" + mapFiles.size() + ") to open at once for " + endRow + " " + prevEndRow + ", reducing in tmpDir = " + tmpDir);

        long t1 = System.currentTimeMillis();
        mapFiles = reduceFiles(acuConf, conf, fs, prevEndRow, endRow, mapFiles, maxToOpen, tmpDir, 0);
        long t2 = System.currentTimeMillis();

        log.debug("Finished reducing indexes for " + endRow + " " + prevEndRow + " in " + String.format("%6.2f secs", (t2 - t1) / 1000.0));
      }

      if (prevEndRow == null)
        prevEndRow = new Text();

      long t1 = System.currentTimeMillis();

      long numKeys = 0;

      numKeys = countIndexEntries(acuConf, prevEndRow, endRow, mapFiles, tmpDir == null ? useIndex : false, conf, fs, readers);

      if (numKeys == 0) {
        if (useIndex) {
          log.warn("Failed to find mid point using indexes, falling back to data files which is slower. No entries between " + prevEndRow + " and " + endRow
              + " for " + mapFiles);
          // need to pass original map files, not possibly reduced indexes
          return findMidPoint(fs, acuConf, prevEndRow, endRow, origMapFiles, minSplit, false);
        }
        throw new IOException("Failed to find mid point, no entries between " + prevEndRow + " and " + endRow + " for " + mapFiles);
      }

      List<SortedKeyValueIterator<Key,Value>> iters = new ArrayList<SortedKeyValueIterator<Key,Value>>(readers);
      MultiIterator mmfi = new MultiIterator(iters, true);

      // skip the prevendrow
      while (mmfi.hasTop() && mmfi.getTopKey().compareRow(prevEndRow) <= 0)
        mmfi.next();

      // read half of the keys in the index
      TreeMap<Double,Key> ret = new TreeMap<Double,Key>();
      Key lastKey = null;
      long keysRead = 0;

      Key keyBeforeMidPoint = null;
      long keyBeforeMidPointPosition = 0;

      while (keysRead < numKeys / 2) {
        if (lastKey != null && !lastKey.equals(mmfi.getTopKey(), PartialKey.ROW) && (keysRead - 1) / (double) numKeys >= minSplit) {
          keyBeforeMidPoint = new Key(lastKey);
          keyBeforeMidPointPosition = keysRead - 1;
        }

        if (lastKey == null)
          lastKey = new Key();

        lastKey.set(mmfi.getTopKey());

        keysRead++;

        // consume minimum
        mmfi.next();
      }

      if (keyBeforeMidPoint != null)
        ret.put(keyBeforeMidPointPosition / (double) numKeys, keyBeforeMidPoint);

      long t2 = System.currentTimeMillis();

      log.debug(String.format("Found midPoint from indexes in %6.2f secs.%n", ((t2 - t1) / 1000.0)));

      ret.put(.5, mmfi.getTopKey());

      // sanity check
      for (Key key : ret.values()) {
        boolean inRange = (key.compareRow(prevEndRow) > 0 && (endRow == null || key.compareRow(endRow) < 1));
        if (!inRange) {
          throw new IOException("Found mid point is not in range " + key + " " + prevEndRow + " " + endRow + " " + mapFiles);
        }
      }

      return ret;
    } finally {
      cleanupIndexOp(acuConf, tmpDir, fs, readers);
    }
  }

  protected static void cleanupIndexOp(AccumuloConfiguration acuConf, Path tmpDir, VolumeManager fs, ArrayList<FileSKVIterator> readers) throws IOException {
    // close all of the index sequence files
    for (FileSKVIterator r : readers) {
      try {
        if (r != null)
          r.close();
      } catch (IOException e) {
        // okay, try to close the rest anyway
        log.error(e, e);
      }
    }

    if (tmpDir != null) {
      Volume v = fs.getVolumeByPath(tmpDir);
      if (v.getFileSystem().exists(tmpDir)) {
        fs.deleteRecursively(tmpDir);
        return;
      }

      log.error("Did not delete tmp dir because it wasn't a tmp dir " + tmpDir);
    }
  }

  private static long countIndexEntries(AccumuloConfiguration acuConf, Text prevEndRow, Text endRow, Collection<String> mapFiles, boolean useIndex,
      Configuration conf, VolumeManager fs, ArrayList<FileSKVIterator> readers) throws IOException {

    long numKeys = 0;

    // count the total number of index entries
    for (String ref : mapFiles) {
      FileSKVIterator reader = null;
      Path path = new Path(ref);
      FileSystem ns = fs.getVolumeByPath(path).getFileSystem();
      try {
        if (useIndex)
          reader = FileOperations.getInstance().openIndex(path.toString(), ns, ns.getConf(), acuConf);
        else
          reader = FileOperations.getInstance().openReader(path.toString(), new Range(prevEndRow, false, null, true), LocalityGroupUtil.EMPTY_CF_SET, false, ns, ns.getConf(),
              acuConf);

        while (reader.hasTop()) {
          Key key = reader.getTopKey();
          if (endRow != null && key.compareRow(endRow) > 0)
            break;
          else if (prevEndRow == null || key.compareRow(prevEndRow) > 0)
            numKeys++;

          reader.next();
        }
      } finally {
        try {
          if (reader != null)
            reader.close();
        } catch (IOException e) {
          log.error(e, e);
        }
      }

      if (useIndex)
        readers.add(FileOperations.getInstance().openIndex(path.toString(), ns, ns.getConf(), acuConf));
      else
        readers.add(FileOperations.getInstance().openReader(path.toString(), new Range(prevEndRow, false, null, true), LocalityGroupUtil.EMPTY_CF_SET, false, ns, ns.getConf(),
            acuConf));

    }
    return numKeys;
  }

  public static Map<FileRef,FileInfo> tryToGetFirstAndLastRows(VolumeManager fs, AccumuloConfiguration acuConf, Set<FileRef> mapfiles) {

    HashMap<FileRef,FileInfo> mapFilesInfo = new HashMap<FileRef,FileInfo>();

    long t1 = System.currentTimeMillis();

    for (FileRef mapfile : mapfiles) {

      FileSKVIterator reader = null;
      FileSystem ns = fs.getVolumeByPath(mapfile.path()).getFileSystem();
      try {
        reader = FileOperations.getInstance().openReader(mapfile.toString(), false, ns, ns.getConf(), acuConf);

        Key firstKey = reader.getFirstKey();
        if (firstKey != null) {
          mapFilesInfo.put(mapfile, new FileInfo(firstKey, reader.getLastKey()));
        }

      } catch (IOException ioe) {
        log.warn("Failed to read map file to determine first and last key : " + mapfile, ioe);
      } finally {
        if (reader != null) {
          try {
            reader.close();
          } catch (IOException ioe) {
            log.warn("failed to close " + mapfile, ioe);
          }
        }
      }

    }

    long t2 = System.currentTimeMillis();

    log.debug(String.format("Found first and last keys for %d map files in %6.2f secs", mapfiles.size(), (t2 - t1) / 1000.0));

    return mapFilesInfo;
  }

  public static WritableComparable<Key> findLastKey(VolumeManager fs, AccumuloConfiguration acuConf, Collection<FileRef> mapFiles) throws IOException {
    Key lastKey = null;

    for (FileRef ref : mapFiles) {
      Path path = ref.path();
      FileSystem ns = fs.getVolumeByPath(path).getFileSystem();
      FileSKVIterator reader = FileOperations.getInstance().openReader(path.toString(), true, ns, ns.getConf(), acuConf);

      try {
        if (!reader.hasTop())
          // file is empty, so there is no last key
          continue;

        Key key = reader.getLastKey();

        if (lastKey == null || key.compareTo(lastKey) > 0)
          lastKey = key;
      } finally {
        try {
          if (reader != null)
            reader.close();
        } catch (IOException e) {
          log.error(e, e);
        }
      }
    }

    return lastKey;

  }

  private static class MLong {
    public MLong(long i) {
      l = i;
    }

    long l;
  }

  public static Map<KeyExtent,Long> estimateSizes(AccumuloConfiguration acuConf, Path mapFile, long fileSize, List<KeyExtent> extents, Configuration conf,
      VolumeManager fs) throws IOException {

    long totalIndexEntries = 0;
    Map<KeyExtent,MLong> counts = new TreeMap<KeyExtent,MLong>();
    for (KeyExtent keyExtent : extents)
      counts.put(keyExtent, new MLong(0));

    Text row = new Text();
    FileSystem ns = fs.getVolumeByPath(mapFile).getFileSystem();
    FileSKVIterator index = FileOperations.getInstance().openIndex(mapFile.toString(), ns, ns.getConf(), acuConf);

    try {
      while (index.hasTop()) {
        Key key = index.getTopKey();
        totalIndexEntries++;
        key.getRow(row);

        for (Entry<KeyExtent,MLong> entry : counts.entrySet())
          if (entry.getKey().contains(row))
            entry.getValue().l++;

        index.next();
      }
    } finally {
      try {
        if (index != null)
          index.close();
      } catch (IOException e) {
        // continue with next file
        log.error(e, e);
      }
    }

    Map<KeyExtent,Long> results = new TreeMap<KeyExtent,Long>();
    for (KeyExtent keyExtent : extents) {
      double numEntries = counts.get(keyExtent).l;
      if (numEntries == 0)
        numEntries = 1;
      long estSize = (long) ((numEntries / totalIndexEntries) * fileSize);
      results.put(keyExtent, estSize);
    }
    return results;
  }

  public static Collection<String> toPathStrings(Collection<FileRef> refs) {
    ArrayList<String> ret = new ArrayList<String>();
    for (FileRef fileRef : refs) {
      ret.add(fileRef.path().toString());
    }

    return ret;
  }

}


text:
package org.broadinstitute.dsde.workbench.sam.azure

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.{Directive0, Directive1, Route}
import cats.syntax.all._
import org.broadinstitute.dsde.workbench.model.{ErrorReport, WorkbenchEmail, WorkbenchExceptionWithErrorReport}
import org.broadinstitute.dsde.workbench.sam.ImplicitConversions.ioOnSuccessMagnet
import org.broadinstitute.dsde.workbench.sam._
import org.broadinstitute.dsde.workbench.sam.api.{SecurityDirectives, _}
import org.broadinstitute.dsde.workbench.sam.azure.AzureJsonSupport._
import org.broadinstitute.dsde.workbench.sam.model._
import org.broadinstitute.dsde.workbench.sam.service.CloudExtensions
import org.broadinstitute.dsde.workbench.sam.util.SamRequestContext
import spray.json.JsString

trait AzureRoutes extends SecurityDirectives {
  val azureService: Option[AzureService]

  def azureRoutes(samUser: SamUser, samRequestContext: SamRequestContext): Route =
    azureService
      .map { service =>
        pathPrefix("azure" / "v1") {
          path("user" / "petManagedIdentity") {
            post {
              entity(as[GetOrCreatePetManagedIdentityRequest]) { request =>
                requireUserCreatePetAction(request, samUser, samRequestContext) {
                  complete {
                    service.getOrCreateUserPetManagedIdentity(samUser, request, samRequestContext).map { case (pet, created) =>
                      val status = if (created) StatusCodes.Created else StatusCodes.OK
                      status -> JsString(pet.objectId.value)
                    }
                  }
                }
              }
            }
          } ~
            path("petManagedIdentity" / Segment) { userEmail =>
              post {
                requireCloudExtensionCreatePetAction(samUser, samRequestContext) {
                  loadSamUser(WorkbenchEmail(userEmail), samRequestContext) { targetSamUser =>
                    entity(as[GetOrCreatePetManagedIdentityRequest]) { request =>
                      requireUserCreatePetAction(request, targetSamUser, samRequestContext) {
                        complete {
                          service.getOrCreateUserPetManagedIdentity(targetSamUser, request, samRequestContext).map { case (pet, created) =>
                            val status = if (created) StatusCodes.Created else StatusCodes.OK
                            status -> JsString(pet.objectId.value)
                          }
                        }
                      }
                    }
                  }
                }
              }
            }
        }
      }
      .getOrElse(reject)

  // Validates the provided SamUser has 'link' permission on the spend-profile resource represented by the
  // GetOrCreatePetManagedIdentityRequest
  private def requireUserCreatePetAction(request: GetOrCreatePetManagedIdentityRequest, samUser: SamUser, samRequestContext: SamRequestContext): Directive0 =
    onSuccess(azureService.flatTraverse(_.getBillingProfileId(request))).flatMap {
      case Some(resourceId) =>
        requireAction(FullyQualifiedResourceId(SamResourceTypes.spendProfile, resourceId), SamResourceActions.link, samUser.id, samRequestContext)
      case None =>
        failWith(
          new WorkbenchExceptionWithErrorReport(
            ErrorReport(StatusCodes.NotFound, s"Managed resource group ${request.managedResourceGroupName.value} not found")
          )
        )

    }

  // Validates the provided SamUser has 'getPetManagedIdentityAction' on the 'azure' cloud-extension resource.
  private def requireCloudExtensionCreatePetAction(samUser: SamUser, samRequestContext: SamRequestContext): Directive0 =
    requireAction(
      FullyQualifiedResourceId(CloudExtensions.resourceTypeName, AzureExtensions.resourceId),
      AzureExtensions.getPetManagedIdentityAction,
      samUser.id,
      samRequestContext
    )

  // Loads a SamUser from the database by email. Fails with 404 if not found.
  private def loadSamUser(email: WorkbenchEmail, samRequestContext: SamRequestContext): Directive1[SamUser] =
    onSuccess(azureService.flatTraverse(_.getSamUser(email, samRequestContext))).flatMap {
      case Some(samUser) => provide(samUser)
      case None =>
        failWith(new WorkbenchExceptionWithErrorReport(ErrorReport(StatusCodes.NotFound, s"User ${email.value} not found")))
    }
}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

# Check if the allele registry API site is up or down; if down display down message in component, if up show widget

package EnsEMBL::Web::Tools::FailOver::AlleleRegistry;

use strict;
use warnings;

use EnsEMBL::Web::File::Utils::URL qw(file_exists);

use base qw(EnsEMBL::Web::Tools::FailOver);

sub new {
  my ($proto,$hub) = @_;

  my $self        = $proto->SUPER::new("alleleregistry");
  $self->{'hub'}  = $hub;
  $self->{'check_url'}  = $hub->get_ExtURL('ALLELE_REGISTRY'); # http://reg.test.genome.network
  return $self;
}

sub endpoints         { return ['direct']; }
sub fail_for          { return 120; } # seconds after a failure to try checking again
sub failure_dir       { return $_[0]->{'hub'}->species_defs->ENSEMBL_FAILUREDIR; }
sub min_initial_dead  { return 5; }
sub successful        { return $_[1]; }

sub attempt {
  my ($self,$endpoint,$payload,$tryhard) = @_;
  my $check_url = $self->{'check_url'};
  return 0 unless defined $check_url;

  return file_exists($check_url);
}

1;


text:
import {UserSettings, CommentHandling, UrlHandling, DynamicContentHandling} from './interfaces';

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {

  // The selector array - this can be expanded to target comments/comment sections on as many sites as possible.
  const selectorArray: ReadonlyArray<string> = ['body [id*="comment"]', 'body [class*="comment"]', '#disqus_thread', '[class*="replies-to"]'];

  // The current URL (for allowlist/blocklist usage)
  const currentURL: string = document.location.href;

  let userSettings: UserSettings = {
    'blockAllComments': request.settings.blockComments,
    'display': request.settings.visualDisplay,
    'allowlist': request.allowlist,
    'blocklist': request.blocklist
  };

  let comments: CommentHandling = {
    'getAll': document.querySelectorAll(selectorArray.join()),
    'hideAll': (): void => {
      for (let i of Array.from(comments.getAll).keys()) {
        if (userSettings.display === 'collapse') {
          (<HTMLElement>comments.getAll[i]).style.display = 'none';
        }
        else if (userSettings.display === 'hidden') {
          (<HTMLElement>comments.getAll[i]).style.visibility = 'hidden';
        }
      }
    }
  };

  let urlHandling: UrlHandling = {
    'blockableContent': false,
    'checkProtocol': (urlString: string): string => {
      if (urlString.search(/^http[s]?\:\/\//) === -1) {
        urlString = '*://' + urlString;
      }

      return urlString;
    }
  };

  let dynamicContentHandling: DynamicContentHandling = {
    'observeChanges': {
      'config': {
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true,
        attributeFilter: ['id', 'class']
      },
      'mutations': new (<any>window).MutationObserver((): void => {
        let matches = document.querySelectorAll(selectorArray.join());

        for (let i of Array.from(matches).keys()) {
          if ((<HTMLElement>matches[i]).style.display !== 'none') {
            if (userSettings.display === 'collapse') {
              (<HTMLElement>matches[i]).style.display = 'none';
            }
            else if (userSettings.display === 'hidden') {
              (<HTMLElement>matches[i]).style.visibility = 'hidden';
            }
          }
        }
      })
    }
  }

  const isNotInAllowList = (): boolean => {
    const allowlist: any = userSettings.allowlist;

    for (let i of allowlist.keys()) {
      let structuredURL: string = urlHandling.checkProtocol(allowlist[i].toString());
      let regexURL: RegExp = new RegExp(structuredURL.replace(/\./g, '\\.').replace(/\*/g, '.+') + '/?$');

      if (regexURL.test(currentURL)) {
        return false;
      }
    }

    return true;
  };

  const isInBlockList = (): boolean => {
    const blocklist: any = userSettings.blocklist;

    for (let i of blocklist.keys()) {
      let structuredURL: string = urlHandling.checkProtocol(blocklist[i].toString());
      let regexURL: RegExp = new RegExp(structuredURL.replace(/\./g, '\\.').replace(/\*/g, '.+') + '/?$');

      if (regexURL.test(currentURL)) {
        return true;
      }
    }

    return false;
  };

  if (userSettings.blockAllComments) {
    // If all comments are set to be blocked by default,
    // Check whether the current URL is in Allow List and take appropriate action.
    if (isNotInAllowList()) {
      // It is necessary to show page action.
      urlHandling.blockableContent = true;
      // Observe any additional elements that match selectorArray
      dynamicContentHandling.observeChanges.mutations.observe(document.body, dynamicContentHandling.observeChanges.config);
      // This URL/URL pattern is not Allow List - loop through all comments on page and hide (depending on user visual setting).
      comments.hideAll();
    }
  }
  else {
    if (isInBlockList()) {
      // It is necessary to show page action.
      urlHandling.blockableContent = true;
      // Observe any additional elements that match selectorArray
      dynamicContentHandling.observeChanges.mutations.observe(document.body, dynamicContentHandling.observeChanges.config);
      // Current URL is in Block List - hide all comments.
      comments.hideAll();
    }
  }
  // Need to include whether or not the current page contains blockable content, so that the page action can be displayed.
  sendResponse({ 'blockableContent': urlHandling.blockableContent, 'commentsLength': comments.getAll.length });
});


text:
'use strict';

const assert = require('assert');

const valueTRUE = new Date();
const valueFALSE = 'ImNotAnDate';

assert.equal(true, require('./isDate')(valueTRUE));
assert.equal(false, require('./isDate')(valueFALSE));

console.log(valueTRUE + ' é uma data?', require('./isDate')(valueTRUE));
console.log(valueFALSE + ' é uma data?', require('./isDate')(valueFALSE));


text:
package pro.taskana.rest;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.config.EnableHypermediaSupport;
import org.springframework.hateoas.config.EnableHypermediaSupport.HypermediaType;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import pro.taskana.BaseQuery.SortDirection;
import pro.taskana.Workbasket;
import pro.taskana.WorkbasketAccessItem;
import pro.taskana.WorkbasketPermission;
import pro.taskana.WorkbasketQuery;
import pro.taskana.WorkbasketService;
import pro.taskana.WorkbasketSummary;
import pro.taskana.WorkbasketType;
import pro.taskana.exceptions.DomainNotFoundException;
import pro.taskana.exceptions.InvalidArgumentException;
import pro.taskana.exceptions.InvalidWorkbasketException;
import pro.taskana.exceptions.NotAuthorizedException;
import pro.taskana.exceptions.WorkbasketAlreadyExistException;
import pro.taskana.exceptions.WorkbasketInUseException;
import pro.taskana.exceptions.WorkbasketNotFoundException;
import pro.taskana.impl.util.LoggerUtils;
import pro.taskana.rest.resource.DistributionTargetListResource;
import pro.taskana.rest.resource.DistributionTargetResource;
import pro.taskana.rest.resource.DistributionTargetResourceAssembler;
import pro.taskana.rest.resource.PagedResources.PageMetadata;
import pro.taskana.rest.resource.WorkbasketAccessItemListResource;
import pro.taskana.rest.resource.WorkbasketAccessItemResource;
import pro.taskana.rest.resource.WorkbasketAccessItemResourceAssembler;
import pro.taskana.rest.resource.WorkbasketResource;
import pro.taskana.rest.resource.WorkbasketResourceAssembler;
import pro.taskana.rest.resource.WorkbasketSummaryListResource;
import pro.taskana.rest.resource.WorkbasketSummaryResourceAssembler;

/** Controller for all {@link Workbasket} related endpoints. */
@RestController
@EnableHypermediaSupport(type = HypermediaType.HAL)
public class WorkbasketController extends AbstractPagingController {

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

  private static final String LIKE = "%";
  private static final String NAME = "name";
  private static final String NAME_LIKE = "name-like";
  private static final String KEY = "key";
  private static final String KEY_LIKE = "key-like";
  private static final String OWNER = "owner";
  private static final String OWNER_LIKE = "owner-like";
  private static final String DESCRIPTION_LIKE = "description-like";
  private static final String DOMAIN = "domain";
  private static final String REQUIRED_PERMISSION = "required-permission";
  private static final String TYPE = "type";
  private static final String DESCRIPTION = "description";

  private static final String SORT_BY = "sort-by";
  private static final String SORT_DIRECTION = "order";

  private WorkbasketService workbasketService;

  private WorkbasketResourceAssembler workbasketResourceAssembler;

  private WorkbasketSummaryResourceAssembler workbasketSummaryResourceAssembler;

  private DistributionTargetResourceAssembler distributionTargetResourceAssembler;

  private WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler;

  WorkbasketController(
      WorkbasketService workbasketService,
      WorkbasketResourceAssembler workbasketResourceAssembler,
      WorkbasketSummaryResourceAssembler workbasketSummaryResourceAssembler,
      DistributionTargetResourceAssembler distributionTargetResourceAssembler,
      WorkbasketAccessItemResourceAssembler workbasketAccessItemResourceAssembler) {
    this.workbasketService = workbasketService;
    this.workbasketResourceAssembler = workbasketResourceAssembler;
    this.workbasketSummaryResourceAssembler = workbasketSummaryResourceAssembler;
    this.distributionTargetResourceAssembler = distributionTargetResourceAssembler;
    this.workbasketAccessItemResourceAssembler = workbasketAccessItemResourceAssembler;
  }

  @GetMapping(path = Mapping.URL_WORKBASKET)
  @Transactional(readOnly = true, rollbackFor = Exception.class)
  public ResponseEntity<WorkbasketSummaryListResource> getWorkbaskets(
      @RequestParam MultiValueMap<String, String> params) throws InvalidArgumentException {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Entry to getWorkbaskets(params= {})", params);
    }

    WorkbasketQuery query = workbasketService.createWorkbasketQuery();
    query = applySortingParams(query, params);
    query = applyFilterParams(query, params);

    PageMetadata pageMetadata = getPageMetadata(params, query);
    List<WorkbasketSummary> workbasketSummaries = getQueryList(query, pageMetadata);
    WorkbasketSummaryListResource pagedResources =
        workbasketSummaryResourceAssembler.toResources(workbasketSummaries, pageMetadata);

    ResponseEntity<WorkbasketSummaryListResource> response = ResponseEntity.ok(pagedResources);
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from getWorkbaskets(), returning {}", response);
    }

    return response;
  }

  @GetMapping(path = Mapping.URL_WORKBASKET_ID)
  @Transactional(readOnly = true, rollbackFor = Exception.class)
  public ResponseEntity<WorkbasketResource> getWorkbasket(
      @PathVariable(value = "workbasketId") String workbasketId)
      throws WorkbasketNotFoundException, NotAuthorizedException {
    LOGGER.debug("Entry to getWorkbasket(workbasketId= {})", workbasketId);
    ResponseEntity<WorkbasketResource> result;
    Workbasket workbasket = workbasketService.getWorkbasket(workbasketId);
    result = ResponseEntity.ok(workbasketResourceAssembler.toResource(workbasket));
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from getWorkbasket(), returning {}", result);
    }

    return result;
  }

  @DeleteMapping(path = Mapping.URL_WORKBASKET_ID)
  @Transactional(rollbackFor = Exception.class, noRollbackFor = WorkbasketNotFoundException.class)
  public ResponseEntity<?> markWorkbasketForDeletion(
      @PathVariable(value = "workbasketId") String workbasketId)
      throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException,
          WorkbasketInUseException {
    LOGGER.debug("Entry to markWorkbasketForDeletion(workbasketId= {})", workbasketId);
    //http status code accepted because workbaskets will not be deleted immediately
    ResponseEntity<?> response =
        ResponseEntity.accepted().body(workbasketService.deleteWorkbasket(workbasketId));
    LOGGER.debug("Exit from markWorkbasketForDeletion(), returning {}", response);
    return response;
  }

  @PostMapping(path = Mapping.URL_WORKBASKET)
  @Transactional(rollbackFor = Exception.class)
  public ResponseEntity<WorkbasketResource> createWorkbasket(
      @RequestBody WorkbasketResource workbasketResource)
      throws InvalidWorkbasketException, NotAuthorizedException, WorkbasketAlreadyExistException,
          WorkbasketNotFoundException, DomainNotFoundException {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Entry to createWorkbasket(workbasketResource= {})", workbasketResource);
    }

    Workbasket workbasket = workbasketResourceAssembler.toModel(workbasketResource);
    workbasket = workbasketService.createWorkbasket(workbasket);
    ResponseEntity<WorkbasketResource> response =
        ResponseEntity.status(HttpStatus.CREATED)
            .body(workbasketResourceAssembler.toResource(workbasket));
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from createWorkbasket(), returning {}", response);
    }

    return response;
  }

  @PutMapping(path = Mapping.URL_WORKBASKET_ID)
  @Transactional(rollbackFor = Exception.class)
  public ResponseEntity<WorkbasketResource> updateWorkbasket(
      @PathVariable(value = "workbasketId") String workbasketId,
      @RequestBody WorkbasketResource workbasketResource)
      throws InvalidWorkbasketException, WorkbasketNotFoundException, NotAuthorizedException {
    LOGGER.debug("Entry to updateWorkbasket(workbasketId= {})", workbasketId);
    ResponseEntity<WorkbasketResource> result;
    if (workbasketId.equals(workbasketResource.workbasketId)) {
      Workbasket workbasket = workbasketResourceAssembler.toModel(workbasketResource);
      workbasket = workbasketService.updateWorkbasket(workbasket);
      result = ResponseEntity.ok(workbasketResourceAssembler.toResource(workbasket));
    } else {
      throw new InvalidWorkbasketException(
          "Target-WB-ID('"
              + workbasketId
              + "') is not identical with the WB-ID of to object which should be updated. ID=('"
              + workbasketResource.getId()
              + "')");
    }

    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from updateWorkbasket(), returning {}", result);
    }

    return result;
  }

  @GetMapping(path = Mapping.URL_WORKBASKET_ID_ACCESSITEMS)
  @Transactional(readOnly = true, rollbackFor = Exception.class)
  public ResponseEntity<WorkbasketAccessItemListResource> getWorkbasketAccessItems(
      @PathVariable(value = "workbasketId") String workbasketId)
      throws NotAuthorizedException, WorkbasketNotFoundException {
    LOGGER.debug("Entry to getWorkbasketAccessItems(workbasketId= {})", workbasketId);
    ResponseEntity<WorkbasketAccessItemListResource> result;

    List<WorkbasketAccessItem> accessItems =
        workbasketService.getWorkbasketAccessItems(workbasketId);
    result =
        ResponseEntity.ok(
            workbasketAccessItemResourceAssembler.toResources(workbasketId, accessItems));
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from getWorkbasketAccessItems(), returning {}", result);
    }

    return result;
  }

  @PutMapping(path = Mapping.URL_WORKBASKET_ID_ACCESSITEMS)
  @Transactional(rollbackFor = Exception.class)
  public ResponseEntity<WorkbasketAccessItemListResource> setWorkbasketAccessItems(
      @PathVariable(value = "workbasketId") String workbasketId,
      @RequestBody List<WorkbasketAccessItemResource> workbasketAccessResourceItems)
      throws NotAuthorizedException, InvalidArgumentException, WorkbasketNotFoundException {
    LOGGER.debug("Entry to setWorkbasketAccessItems(workbasketId= {})", workbasketId);
    if (workbasketAccessResourceItems == null) {
      throw new InvalidArgumentException("Can´t create something with NULL body-value.");
    }

    List<WorkbasketAccessItem> wbAccessItems = new ArrayList<>();
    workbasketAccessResourceItems.forEach(
        item -> wbAccessItems.add(workbasketAccessItemResourceAssembler.toModel(item)));
    workbasketService.setWorkbasketAccessItems(workbasketId, wbAccessItems);
    List<WorkbasketAccessItem> updatedWbAccessItems =
        workbasketService.getWorkbasketAccessItems(workbasketId);

    ResponseEntity<WorkbasketAccessItemListResource> response =
        ResponseEntity.ok(
            workbasketAccessItemResourceAssembler.toResources(workbasketId, updatedWbAccessItems));
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from setWorkbasketAccessItems(), returning {}", response);
    }

    return response;
  }

  @GetMapping(path = Mapping.URL_WORKBASKET_ID_DISTRIBUTION)
  @Transactional(readOnly = true, rollbackFor = Exception.class)
  public ResponseEntity<DistributionTargetListResource> getDistributionTargets(
      @PathVariable(value = "workbasketId") String workbasketId)
      throws WorkbasketNotFoundException, NotAuthorizedException {

    LOGGER.debug("Entry to getDistributionTargets(workbasketId= {})", workbasketId);
    List<WorkbasketSummary> distributionTargets =
        workbasketService.getDistributionTargets(workbasketId);
    DistributionTargetListResource distributionTargetListResource =
        distributionTargetResourceAssembler.toResources(workbasketId, distributionTargets);
    ResponseEntity<DistributionTargetListResource> result =
        ResponseEntity.ok(distributionTargetListResource);
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from getDistributionTargets(), returning {}", result);
    }

    return result;
  }

  @PutMapping(path = Mapping.URL_WORKBASKET_ID_DISTRIBUTION)
  @Transactional(rollbackFor = Exception.class)
  public ResponseEntity<DistributionTargetListResource> setDistributionTargetsForWorkbasketId(
      @PathVariable(value = "workbasketId") String sourceWorkbasketId,
      @RequestBody List<String> targetWorkbasketIds)
      throws WorkbasketNotFoundException, NotAuthorizedException {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug(
          "Entry to getTasksStatusReport(workbasketId= {}, targetWorkbasketIds´= {})",
          sourceWorkbasketId,
          LoggerUtils.listToString(targetWorkbasketIds));
    }

    workbasketService.setDistributionTargets(sourceWorkbasketId, targetWorkbasketIds);

    List<WorkbasketSummary> distributionTargets =
        workbasketService.getDistributionTargets(sourceWorkbasketId);
    ResponseEntity<DistributionTargetListResource> response =
        ResponseEntity.ok(
            distributionTargetResourceAssembler.toResources(
                sourceWorkbasketId, distributionTargets));
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from getTasksStatusReport(), returning {}", response);
    }

    return response;
  }

  // TODO - schema inconsistent with PUT and GET
  @DeleteMapping(path = Mapping.URL_WORKBASKET_DISTRIBUTION_ID)
  @Transactional(rollbackFor = Exception.class)
  public ResponseEntity<Resources<DistributionTargetResource>>
      removeDistributionTargetForWorkbasketId(
          @PathVariable(value = "workbasketId") String targetWorkbasketId)
          throws WorkbasketNotFoundException, NotAuthorizedException {
    LOGGER.debug(
        "Entry to removeDistributionTargetForWorkbasketId(workbasketId= {})", targetWorkbasketId);
    List<WorkbasketSummary> sourceWorkbaskets =
        workbasketService.getDistributionSources(targetWorkbasketId);
    for (WorkbasketSummary source : sourceWorkbaskets) {
      workbasketService.removeDistributionTarget(source.getId(), targetWorkbasketId);
    }

    ResponseEntity<Resources<DistributionTargetResource>> response =
        ResponseEntity.noContent().build();
    LOGGER.debug("Exit from removeDistributionTargetForWorkbasketId(), returning {}", response);
    return response;
  }

  private WorkbasketQuery applySortingParams(
      WorkbasketQuery query, MultiValueMap<String, String> params) throws IllegalArgumentException {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Entry to applySortingParams(query= {}, params={})", query, params);
    }

    // sorting
    String sortBy = params.getFirst(SORT_BY);
    if (sortBy != null) {
      SortDirection sortDirection;
      if (params.getFirst(SORT_DIRECTION) != null
          && "desc".equals(params.getFirst(SORT_DIRECTION))) {
        sortDirection = SortDirection.DESCENDING;
      } else {
        sortDirection = SortDirection.ASCENDING;
      }
      switch (sortBy) {
        case (NAME):
          query = query.orderByName(sortDirection);
          break;
        case (KEY):
          query = query.orderByKey(sortDirection);
          break;
        case (OWNER):
          query = query.orderByOwner(sortDirection);
          break;
        case (TYPE):
          query = query.orderByType(sortDirection);
          break;
        case (DESCRIPTION):
          query = query.orderByDescription(sortDirection);
          break;
        default:
          throw new IllegalArgumentException("Unknown order '" + sortBy + "'");
      }
    }
    params.remove(SORT_BY);
    params.remove(SORT_DIRECTION);
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from applySortingParams(), returning {}", query);
    }

    return query;
  }

  private WorkbasketQuery applyFilterParams(
      WorkbasketQuery query, MultiValueMap<String, String> params) throws InvalidArgumentException {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Entry to applyFilterParams(query= {}, params= {})", query, params);
    }

    if (params.containsKey(NAME)) {
      String[] names = extractCommaSeparatedFields(params.get(NAME));
      query.nameIn(names);
      params.remove(NAME);
    }
    if (params.containsKey(NAME_LIKE)) {
      query.nameLike(LIKE + params.get(NAME_LIKE).get(0) + LIKE);
      params.remove(NAME_LIKE);
    }
    if (params.containsKey(KEY)) {
      String[] names = extractCommaSeparatedFields(params.get(KEY));
      query.keyIn(names);
      params.remove(KEY);
    }
    if (params.containsKey(KEY_LIKE)) {
      query.keyLike(LIKE + params.get(KEY_LIKE).get(0) + LIKE);
      params.remove(KEY_LIKE);
    }
    if (params.containsKey(OWNER)) {
      String[] names = extractCommaSeparatedFields(params.get(OWNER));
      query.ownerIn(names);
      params.remove(OWNER);
    }
    if (params.containsKey(OWNER_LIKE)) {
      query.ownerLike(LIKE + params.get(OWNER_LIKE).get(0) + LIKE);
      params.remove(OWNER_LIKE);
    }
    if (params.containsKey(DESCRIPTION_LIKE)) {
      query.descriptionLike(LIKE + params.get(DESCRIPTION_LIKE).get(0) + LIKE);
      params.remove(DESCRIPTION_LIKE);
    }
    if (params.containsKey(DOMAIN)) {
      query.domainIn(extractCommaSeparatedFields(params.get(DOMAIN)));
      params.remove(DOMAIN);
    }
    if (params.containsKey(TYPE)) {
      switch (params.getFirst(TYPE)) {
        case "PERSONAL":
          query.typeIn(WorkbasketType.PERSONAL);
          break;
        case "GROUP":
          query.typeIn(WorkbasketType.GROUP);
          break;
        case "CLEARANCE":
          query.typeIn(WorkbasketType.CLEARANCE);
          break;
        case "TOPIC":
          query.typeIn(WorkbasketType.TOPIC);
          break;
        default:
          throw new InvalidArgumentException(
              "Unknown Workbasket type '" + params.getFirst(TYPE) + "'");
      }
      params.remove(TYPE);
    }
    if (params.containsKey(REQUIRED_PERMISSION)) {
      for (String authorization : params.getFirst(REQUIRED_PERMISSION).split(",")) {
        switch (authorization.trim()) {
          case "READ":
            query.callerHasPermission(WorkbasketPermission.READ);
            break;
          case "OPEN":
            query.callerHasPermission(WorkbasketPermission.OPEN);
            break;
          case "APPEND":
            query.callerHasPermission(WorkbasketPermission.APPEND);
            break;
          case "TRANSFER":
            query.callerHasPermission(WorkbasketPermission.TRANSFER);
            break;
          case "DISTRIBUTE":
            query.callerHasPermission(WorkbasketPermission.DISTRIBUTE);
            break;
          case "CUSTOM_1":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_1);
            break;
          case "CUSTOM_2":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_2);
            break;
          case "CUSTOM_3":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_3);
            break;
          case "CUSTOM_4":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_4);
            break;
          case "CUSTOM_5":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_5);
            break;
          case "CUSTOM_6":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_6);
            break;
          case "CUSTOM_7":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_7);
            break;
          case "CUSTOM_8":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_8);
            break;
          case "CUSTOM_9":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_9);
            break;
          case "CUSTOM_10":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_10);
            break;
          case "CUSTOM_11":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_11);
            break;
          case "CUSTOM_12":
            query.callerHasPermission(WorkbasketPermission.CUSTOM_12);
            break;
          default:
            throw new InvalidArgumentException("Unknown authorization '" + authorization + "'");
        }
      }
      params.remove(REQUIRED_PERMISSION);
    }
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Exit from applyFilterParams(), returning {}", query);
    }

    return query;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/Sample/Sample.iml" filepath="$PROJECT_DIR$/Sample/Sample.iml" />
      <module fileurl="file://$PROJECT_DIR$/ScreenSlidePager.iml" filepath="$PROJECT_DIR$/ScreenSlidePager.iml" />
      <module fileurl="file://$PROJECT_DIR$/SlidePageIndicator/SlidePageIndicator.iml" filepath="$PROJECT_DIR$/SlidePageIndicator/SlidePageIndicator.iml" />
      <module fileurl="file://$PROJECT_DIR$/SlidePager/SlidePager.iml" filepath="$PROJECT_DIR$/SlidePager/SlidePager.iml" />
    </modules>
  </component>
</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycotaxon 17: 400 (1983)

#### Original name
Tylopilus snellii Wolfe

### Remarks
null


text:
Impressionen

		{% if page.amp == true %}
		{% if page.image.picnum %}<amp-img src="/images/flying-friends/m_kite-mallorca_0{{ page.image.picnum }}.jpg" width="320" height="240" layout="responsive" alt="{{ page.subtitle }}" title="{{ page.subtitle }}" ></amp-img>{% else %}<amp-img src="/images/flying-friends/m_kite-mallorca_008.jpg" width="320" height="240" layout="responsive" alt="Fotos von Kitesurfer bei Kite-Mallorca" title="Fotos von Kitesurfer bei Kite-Mallorca" ></amp-img>{% endif %}» mehr Bilder
		<meta itemprop="url" content="{{ site.url }}/images/flying-friends/m_kite-mallorca_0{{ page.image.picnum }}.jpg">
		{% else %}
		{% if page.image.picnum %}{% else %}{% endif %}» mehr Bilder
		<meta itemprop="url" content="{{ site.url }}/images/flying-friends/m_kite-mallorca_0{{ page.image.picnum }}.jpg">
		{% endif %}

		<meta itemprop="width" content="100%">
    	<meta itemprop="height" content="100%">


text:
<?php

namespace Topxia\Api\Resource;

use Biz\Article\Service\ArticleService;
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Topxia\Service\Common\ServiceKernel;
use Topxia\Api\Util\TagUtil;

class Article extends BaseResource
{
    public function get(Application $app, Request $request, $id)
    {
        $article = $this->getArticleService()->getArticle($id);

        return $this->filter($article);
    }

    public function filter($res)
    {
        $res['thumb']         = $this->getFileUrl($res['thumb']);
        $res['originalThumb'] = $this->getFileUrl($res['originalThumb']);
        $res['picture']       = $this->getFileUrl($res['picture']);
        $res['body']          = $this->filterHtml($res['body']);
        $res['createdTime']   = date('c', $res['createdTime']);
        $res['updatedTime']   = date('c', $res['updatedTime']);

        $site          = $this->getSettingService()->get('site', array());
        $res['source'] = isset($site['name']) ? $site['name'] : '';
        $res['tags']   = TagUtil::buildTags('article', $res['id']);

        return $res;
    }

    /**
     * @return ArticleService
     */
    protected function getArticleService()
    {
        return $this->getServiceKernel()->createService('Article:ArticleService');
    }

    protected function getSettingService()
    {
        return ServiceKernel::instance()->createService('System:SettingService');
    }
}


text:
package org.zstack.header.identity;

import org.zstack.header.message.APIEvent;

/**
 * Created by frank on 7/10/2015.
 */
public class APIResetUserPasswordEvent extends APIEvent {
    public APIResetUserPasswordEvent() {
    }

    public APIResetUserPasswordEvent(String apiId) {
        super(apiId);
    }
}


text:
package main

import (
	"flag"
	"log"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"strconv"
	"syscall"
	"time"

	"github.com/weaveworks/procspy"
	"github.com/weaveworks/scope/probe/docker"
	"github.com/weaveworks/scope/probe/endpoint"
	"github.com/weaveworks/scope/probe/host"
	"github.com/weaveworks/scope/probe/overlay"
	"github.com/weaveworks/scope/probe/process"
	"github.com/weaveworks/scope/report"
	"github.com/weaveworks/scope/xfer"
)

var version = "dev" // set at build time

func main() {
	var (
		httpListen         = flag.String("http.listen", "", "listen address for HTTP profiling and instrumentation server")
		publishInterval    = flag.Duration("publish.interval", 3*time.Second, "publish (output) interval")
		spyInterval        = flag.Duration("spy.interval", time.Second, "spy (scan) interval")
		listen             = flag.String("listen", ":"+strconv.Itoa(xfer.ProbePort), "listen address")
		prometheusEndpoint = flag.String("prometheus.endpoint", "/metrics", "Prometheus metrics exposition endpoint (requires -http.listen)")
		spyProcs           = flag.Bool("processes", true, "report processes (needs root)")
		dockerEnabled      = flag.Bool("docker", false, "collect Docker-related attributes for processes")
		dockerInterval     = flag.Duration("docker.interval", 10*time.Second, "how often to update Docker attributes")
		dockerBridge       = flag.String("docker.bridge", "docker0", "the docker bridge name")
		weaveRouterAddr    = flag.String("weave.router.addr", "", "IP address or FQDN of the Weave router")
		procRoot           = flag.String("proc.root", "/proc", "location of the proc filesystem")
	)
	flag.Parse()

	if len(flag.Args()) != 0 {
		flag.Usage()
		os.Exit(1)
	}

	log.Printf("probe version %s", version)

	procspy.SetProcRoot(*procRoot)

	if *httpListen != "" {
		log.Printf("profiling data being exported to %s", *httpListen)
		log.Printf("go tool pprof http://%s/debug/pprof/{profile,heap,block}", *httpListen)
		if *prometheusEndpoint != "" {
			log.Printf("exposing Prometheus endpoint at %s%s", *httpListen, *prometheusEndpoint)
			http.Handle(*prometheusEndpoint, makePrometheusHandler())
		}
		go func() {
			err := http.ListenAndServe(*httpListen, nil)
			log.Print(err)
		}()
	}

	if *spyProcs && os.Getegid() != 0 {
		log.Printf("warning: process reporting enabled, but that requires root to find everything")
	}

	publisher, err := xfer.NewTCPPublisher(*listen)
	if err != nil {
		log.Fatal(err)
	}
	defer publisher.Close()

	var (
		hostName     = hostname()
		hostID       = hostName // TODO: we should sanitize the hostname
		taggers      = []Tagger{newTopologyTagger(), host.NewTagger(hostID)}
		reporters    = []Reporter{host.NewReporter(hostID, hostName), endpoint.NewReporter(hostID, hostName, *spyProcs)}
		processCache *process.CachingWalker
	)

	processCache = process.NewCachingWalker(process.NewWalker(*procRoot))
	reporters = append(reporters, process.NewReporter(processCache, hostID))

	if *dockerEnabled {
		if err := report.AddLocalBridge(*dockerBridge); err != nil {
			log.Fatalf("failed to get docker bridge address: %v", err)
		}

		dockerRegistry, err := docker.NewRegistry(*dockerInterval)
		if err != nil {
			log.Fatalf("failed to start docker registry: %v", err)
		}
		defer dockerRegistry.Stop()

		taggers = append(taggers, docker.NewTagger(dockerRegistry, processCache))
		reporters = append(reporters, docker.NewReporter(dockerRegistry, hostID))
	}

	if *weaveRouterAddr != "" {
		weave, err := overlay.NewWeave(*weaveRouterAddr)
		if err != nil {
			log.Fatalf("failed to start Weave tagger: %v", err)
		}
		taggers = append(taggers, weave)
		reporters = append(reporters, weave)
	}

	log.Printf("listening on %s", *listen)

	quit := make(chan struct{})
	defer close(quit)
	go func() {
		var (
			pubTick = time.Tick(*publishInterval)
			spyTick = time.Tick(*spyInterval)
			r       = report.MakeReport()
		)

		for {
			select {
			case <-pubTick:
				publishTicks.WithLabelValues().Add(1)
				publisher.Publish(r)
				r = report.MakeReport()

			case <-spyTick:
				if err := processCache.Update(); err != nil {
					log.Printf("error reading processes: %v", err)
				}

				for _, reporter := range reporters {
					newReport, err := reporter.Report()
					if err != nil {
						log.Printf("error generating report: %v", err)
					}
					r.Merge(newReport)
				}

				r = Apply(r, taggers)

			case <-quit:
				return
			}
		}
	}()

	log.Printf("%s", <-interrupt())
}

func interrupt() chan os.Signal {
	c := make(chan os.Signal)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
	return c
}


text:
if [ ! -f scripts/runPreprocessing_scraps.sh ]; then
    echo "Please run this command from the csuEvalFaceRec directory"
    exit 1
fi

run() {
    $@ || { echo "Command failed: $@"; echo; exit 1; }
}

###### End of PREAMBLE ######

PATH=$PATH:bin/`arch`
export PATH

FERET_PGM_SOURCE="data/csuScrapShots/source/pgm"
FERET_SFI_DIR="data/csuScrapShots/normSep2002sfi"
EYE_COORDS="imagelists/coords.scraps"

mkdir -p $FERET_SFI_DIR

echo "Running Preprocessing on scrapshots images. Using CSU Defaults for Optional Settings"
run csuPreprocessNormalize $EYE_COORDS $FERET_PGM_SOURCE -sfi  $FERET_SFI_DIR

# Using normalized raster images from directory <data/csuScrapShots/normSep2002sfi>

# Creating directory for training data.

run mkdir -p train/scraps

# Running standard feret PCA training.

run csuSubspaceTrain -imDir data/csuScrapShots/normSep2002sfi imagelists/scrap_all.srt train/scraps/feretPCA.train


text:
<link rel="import" href="packages://ui-kit/widget/loader/loader.html">

<template id="simple">
  <editor-loader></editor-loader>
</template>

<template id="mask">
  <editor-loader mask></editor-loader>
</template>


text:
package be.ordina.msdashboard.applicationinstance.events;

import be.ordina.msdashboard.applicationinstance.ApplicationInstance;

import org.springframework.context.ApplicationEvent;

/**
 * An {@link ApplicationEvent application event} which signals a change in the {@link ApplicationInstance application instance}'s health status.
 *
 * @author Tim Ysewyn
 */
public class ApplicationInstanceHealthUpdated extends ApplicationEvent {

	public ApplicationInstanceHealthUpdated(ApplicationInstance instance) {
		super(instance);
	}

}


text:
layout: page
title: Summit Peak Inc. Trade Fair
date: 2016-05-24
author: Ryan Rosario
tags: weekly links, java
status: published
summary: Etiam volutpat arcu sed fermentum euismod.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 02/15/2017
  endDate: 02/17/2017
  ctyhocn: WNCHHHX
  groupCode: SPITF
published: true
---
Donec rhoncus lorem massa, facilisis maximus tellus pharetra eget. Praesent eleifend tellus ut metus sollicitudin, vel accumsan massa aliquet. Maecenas vehicula vitae ipsum quis porttitor. Vestibulum et vehicula est. Vestibulum lobortis fermentum rhoncus. Ut scelerisque accumsan lobortis. Mauris maximus luctus tortor a elementum. Ut porta nunc sed vulputate finibus. Donec consequat metus sed sem faucibus sagittis. Suspendisse fermentum diam in venenatis tincidunt. In finibus euismod nisi ac porttitor. Curabitur placerat in turpis ac fermentum.

* Phasellus ut justo eu nisi varius commodo
* Aliquam eleifend lectus eu eros ultrices pulvinar.

Aenean consectetur malesuada mi vel aliquam. Phasellus vitae aliquet turpis. Fusce sed mauris ut ligula efficitur dictum ac in urna. Maecenas pretium urna justo, vel imperdiet arcu imperdiet id. Integer lacinia lectus eget mauris fringilla, at laoreet orci vestibulum. Nulla id dui sed justo elementum tempus. Integer egestas ante vitae tincidunt scelerisque. Maecenas vulputate sagittis enim a facilisis. Donec mi leo, tempor nec dapibus quis, suscipit ac nibh. Maecenas ligula arcu, ultricies ac eleifend in, tristique vitae ante. Duis eleifend nunc dui, fringilla tincidunt orci pulvinar at. In semper justo porta, semper ipsum in, consectetur felis. Duis ipsum orci, ullamcorper quis condimentum a, viverra non eros. Proin pulvinar, libero eu iaculis pharetra, ipsum nunc eleifend eros, eu tincidunt quam est eget neque. Aliquam aliquam viverra vulputate. Donec tristique ultricies massa in tempor.


text:
FILE(REMOVE_RECURSE
  "CMakeFiles/nullary_4.dir/nullary.cpp.o"
  "nullary_4.pdb"
  "nullary_4"
)

# Per-language clean rules from dependency scanning.
FOREACH(lang CXX)
  INCLUDE(CMakeFiles/nullary_4.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)


text:
package com.medzone.mpermissionlib.factory;

/**
 * @author hyc
 * @since 2017/7/28 12:18
 */

public abstract class AbstractFactory<T> {
    public abstract T create();
}


text:
package org.cloudfoundry.uaa.users;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.cloudfoundry.QueryParameter;
import org.cloudfoundry.uaa.IdentityZoned;
import org.immutables.value.Value;

/**
 * The request payload for the get user verification link operation
 */
@Value.Immutable
abstract class _GetUserVerificationLinkRequest implements IdentityZoned {

    /**
     * The redirect URI
     */
    @QueryParameter("redirect_uri")
    abstract String getRedirectUri();

    /**
     * The user id
     */
    @JsonIgnore
    abstract String getUserId();

}


text:
import fs from "fs";
import { PackageFormat } from "./model";

export function readPackageJson(): PackageFormat {
	return JSON.parse(fs.readFileSync("./package.json", "utf-8"));
}


text:
package org.apache.storm.starter.trident;

import java.io.Serializable;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.storm.Config;
import org.apache.storm.StormSubmitter;
import org.apache.storm.generated.StormTopology;
import org.apache.storm.starter.spout.RandomNumberGeneratorSpout;
import org.apache.storm.trident.Stream;
import org.apache.storm.trident.TridentTopology;
import org.apache.storm.trident.operation.builtin.Debug;
import org.apache.storm.trident.testing.FixedBatchSpout;
import org.apache.storm.trident.tuple.TridentTuple;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Values;

/**
 * This class demonstrates different usages of
 * * {@link Stream#minBy(String)}
 * * {@link Stream#maxBy(String)}
 * operations on trident {@link Stream}.
 */
public class TridentMinMaxOfDevicesTopology {

    /**
     * Creates a topology with device-id and count (which are whole numbers) as tuple fields in a stream and it finally
     * generates result stream based on min amd max with device-id and count values.
     */
    public static StormTopology buildDevicesTopology() {
        String deviceID = "device-id";
        String count = "count";
        Fields allFields = new Fields(deviceID, count);

        RandomNumberGeneratorSpout spout = new RandomNumberGeneratorSpout(allFields, 10, 1000);

        TridentTopology topology = new TridentTopology();
        Stream devicesStream = topology.newStream("devicegen-spout", spout).
            each(allFields, new Debug("##### devices"));

        devicesStream.minBy(deviceID).
            each(allFields, new Debug("#### device with min id"));

        devicesStream.maxBy(count).
            each(allFields, new Debug("#### device with max count"));

        return topology.build();
    }

    /**
     * Creates a topology which demonstrates min/max operations on tuples of stream which contain vehicle and driver fields
     * with values {@link TridentMinMaxOfDevicesTopology.Vehicle} and {@link TridentMinMaxOfDevicesTopology.Driver} respectively.
     */
    public static StormTopology buildVehiclesTopology() {
        Fields driverField = new Fields(Driver.FIELD_NAME);
        Fields vehicleField = new Fields(Vehicle.FIELD_NAME);
        Fields allFields = new Fields(Vehicle.FIELD_NAME, Driver.FIELD_NAME);

        FixedBatchSpout spout = new FixedBatchSpout(allFields, 10, Vehicle.generateVehicles(20));
        spout.setCycle(true);

        TridentTopology topology = new TridentTopology();
        Stream vehiclesStream = topology.newStream("spout1", spout).
            each(allFields, new Debug("##### vehicles"));

        Stream slowVehiclesStream =
            vehiclesStream
                .min(new SpeedComparator())
                .each(vehicleField, new Debug("#### slowest vehicle"));

        Stream slowDriversStream =
            slowVehiclesStream
                .project(driverField)
                .each(driverField, new Debug("##### slowest driver"));

        vehiclesStream
            .max(new SpeedComparator())
            .each(vehicleField, new Debug("#### fastest vehicle"))
            .project(driverField)
            .each(driverField, new Debug("##### fastest driver"));

        vehiclesStream
            .max(new EfficiencyComparator()).
            each(vehicleField, new Debug("#### efficient vehicle"));

        return topology.build();
    }

    public static void main(String[] args) throws Exception {

        StormTopology topology = buildDevicesTopology();
        Config conf = new Config();
        conf.setMaxSpoutPending(20);
        conf.setNumWorkers(3);
        StormSubmitter.submitTopologyWithProgressBar("devices-topology", conf, topology);
    }

    static class SpeedComparator implements Comparator<TridentTuple>, Serializable {

        @Override
        public int compare(TridentTuple tuple1, TridentTuple tuple2) {
            Vehicle vehicle1 = (Vehicle) tuple1.getValueByField(Vehicle.FIELD_NAME);
            Vehicle vehicle2 = (Vehicle) tuple2.getValueByField(Vehicle.FIELD_NAME);
            return Integer.compare(vehicle1.maxSpeed, vehicle2.maxSpeed);
        }
    }

    static class EfficiencyComparator implements Comparator<TridentTuple>, Serializable {

        @Override
        public int compare(TridentTuple tuple1, TridentTuple tuple2) {
            Vehicle vehicle1 = (Vehicle) tuple1.getValueByField(Vehicle.FIELD_NAME);
            Vehicle vehicle2 = (Vehicle) tuple2.getValueByField(Vehicle.FIELD_NAME);
            return Double.compare(vehicle1.efficiency, vehicle2.efficiency);
        }

    }

    static class Driver implements Serializable {
        static final String FIELD_NAME = "driver";
        final String name;
        final int id;

        Driver(String name, int id) {
            this.name = name;
            this.id = id;
        }

        @Override
        public String toString() {
            return "Driver{" +
                   "name='" + name + '\'' +
                   ", id=" + id +
                   '}';
        }
    }

    static class Vehicle implements Serializable {
        static final String FIELD_NAME = "vehicle";
        final String name;
        final int maxSpeed;
        final double efficiency;

        public Vehicle(String name, int maxSpeed, double efficiency) {
            this.name = name;
            this.maxSpeed = maxSpeed;
            this.efficiency = efficiency;
        }

        public static List<Object>[] generateVehicles(int count) {
            List<Object>[] vehicles = new List[count];
            for (int i = 0; i < count; i++) {
                int id = i - 1;
                vehicles[i] =
                    (new Values(
                        new Vehicle("Vehicle-" + id, ThreadLocalRandom.current().nextInt(0, 100),
                                    ThreadLocalRandom.current().nextDouble(1, 5)),
                        new Driver("Driver-" + id, id)
                    ));
            }
            return vehicles;
        }

        @Override
        public String toString() {
            return "Vehicle{" +
                   "name='" + name + '\'' +
                   ", maxSpeed=" + maxSpeed +
                   ", efficiency=" + efficiency +
                   '}';
        }
    }
}


text:
/*
 * FRC 4931 (http://www.evilletech.com)
 *
 * Open source software. Licensed under the FIRST BSD license file in the
 * root directory of this project's Git repository.
 */

/*
 * FRC 4931 (http://www.evilletech.com)
 *
 * Open source software. Licensed under the FIRST BSD license file in the
 * root directory of this project's Git repository.
 */

package org.frc4931.robot.subsystem;

import edu.wpi.first.wpilibj.command.Subsystem;

/**
 * An aggregate of all of the {@link Subsystem}s that make up the physical ramp system.
 */
public final class Ramp extends SubsystemBase {
    public final Guardrail guardrail;
    public final RampLifter rampLift;
    public final Kicker kicker;

    /**
     * Creates a new {@link RampLifter} using a {@link Guardrail} and a {@link RampLifter}.
     *
     * @param guardrail The {@link Guardrail} for this {@link Ramp}
     * @param rampLift The {@link RampLifter} for this {@link Ramp}
     * @param kicker The {@link Kicker} for this {@link Ramp}
     */
    public Ramp(Guardrail guardrail, RampLifter rampLift, Kicker kicker) {
        this.guardrail = guardrail;
        this.rampLift = rampLift;
        this.kicker = kicker;
    }
}


text:
import java.io.*;
import java.text.*;
import java.util.*;
public class AggregatePerDay {
  public static void main(String[] args) throws Exception {
    SortedMap<String, long[]> byteHistory = new TreeMap<String, long[]>();
    BufferedReader br = new BufferedReader(new FileReader(
        "bridge-bandwidth-histories-sorted.txt"));
    String line;
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
        "yyyy-MM-dd HH:mm:ss");
    dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    SimpleDateFormat dateFormat = new SimpleDateFormat(
        "yyyy-MM-dd");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    SimpleDateFormat timeFormat = new SimpleDateFormat(
        "HH:mm:ss");
    timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    while ((line = br.readLine()) != null) {
      String[] parts = line.split(" ");
      if (parts.length < 3) {
        continue;
      }
      String fingerprint = parts[2];
      while (line.contains("-history")) {
        line = line.substring(line.indexOf("-history") - 4);
        boolean isReadHistory = line.startsWith("read");
        line = line.substring(5);
        parts = line.split(" ");
        if (parts.length >= 6 && parts[5].length() > 0 && !parts[5].contains("history")) {
          String[] bytes = parts[5].split(",");
          long intervalEnd = dateTimeFormat.parse(parts[1] + " " + parts[2]).getTime();
          for (int i = bytes.length - 1; i >= 0; i--) {
            String key = fingerprint + ","
                + dateFormat.format(intervalEnd)
                + (isReadHistory ? ",read" : ",write");
            long timeIndex = timeFormat.parse(
                dateTimeFormat.format(intervalEnd).split(" ")[1]).getTime()
                / (15L * 60L * 1000L);
            long value = Long.parseLong(bytes[i]);
            if (!byteHistory.containsKey(key)) {
              byteHistory.put(key, new long[96]);
            }
            byteHistory.get(key)[(int) timeIndex] = value + 1L;
            intervalEnd -= 15L * 60L * 1000L;
          }
        }
      }
    }
    br.close();
    BufferedWriter bw = new BufferedWriter(new FileWriter(
        "bridge-bandwidth-per-day.csv"));
    for (Map.Entry<String, long[]> e : byteHistory.entrySet()) {
      long total = 0L, count = 0L;
      for (long val : e.getValue()) {
        if (val > 0L) {
          total += val - 1L;
          count += 1L;
        }
      }
      bw.write(e.getKey() + "," + total + "," + count + "\n");
    }
    bw.close();
  }
}


text:
using System;
using System.Runtime.InteropServices;
using System.Threading;

/*
 * This is a fix for issue #1383.
 *
 *    https://github.com/mono/SkiaSharp/issues/1383
 *
 * On Windows, .NET locks are alertable when using the STA threading model and can
 * cause the Windows message loop to be dispatched (typically on WM_PAINT messages).
 * This can lead to re-entrancy and a deadlock on the HandleDictionary lock.
 *
 * This fix replaces the ReaderWriteLockSlim instance on Windows with a native Win32
 * CRITICAL_SECTION.
 */

namespace SkiaSharp.Internals
{
	/// <summary>
	/// Abstracts a platform dependant lock implementation
	/// </summary>
	public interface IPlatformLock
	{
		void EnterReadLock ();
		void ExitReadLock ();
		void EnterWriteLock ();
		void ExitWriteLock ();
		void EnterUpgradeableReadLock ();
		void ExitUpgradeableReadLock ();
	}

	/// <summary>
	/// Helper class to create a IPlatformLock instance, by default according to the current platform
	/// but also client toolkits can plugin their own implementation.
	/// </summary>
	public static class PlatformLock
	{
		/// <summary>
		/// Creates a platform lock
		/// </summary>
		/// <returns></returns>
		public static IPlatformLock Create ()
		{
			// Just call the factory
			return Factory ();
		}

		/// <summary>
		/// The factory for creating platform locks
		/// </summary>
		/// <remarks>
		/// Use this to plugin your own lock implementation.  Must be set
		/// before using other SkiaSharp functionality that causes the lock
		/// to be created (currently only used by SkiaSharps internal
		/// HandleDictionary).
		/// </remarks>
		public static Func<IPlatformLock> Factory { get; set; } = DefaultFactory;

		/// <summary>
		/// Default platform lock factory
		/// </summary>
		/// <returns>A reference to a new platform lock implementation</returns>
		public static IPlatformLock DefaultFactory ()
		{
			if (PlatformConfiguration.IsWindows)
				return new NonAlertableWin32Lock ();
			else
				return new ReadWriteLock ();
		}

		/// <summary>
		/// Non-Windows platform lock uses ReaderWriteLockSlim
		/// </summary>
		class ReadWriteLock : IPlatformLock
		{
			public void EnterReadLock () => _lock.EnterReadLock ();
			public void ExitReadLock () => _lock.ExitReadLock ();
			public void EnterWriteLock () => _lock.EnterWriteLock ();
			public void ExitWriteLock () => _lock.ExitWriteLock ();
			public void EnterUpgradeableReadLock () => _lock.EnterUpgradeableReadLock ();
			public void ExitUpgradeableReadLock () => _lock.ExitUpgradeableReadLock ();

			ReaderWriterLockSlim _lock = new ReaderWriterLockSlim ();
		}

		/// <summary>
		/// Windows platform lock uses Win32 CRITICAL_SECTION
		/// </summary>
		class NonAlertableWin32Lock : IPlatformLock
		{
			public NonAlertableWin32Lock ()
			{
				_cs = Marshal.AllocHGlobal (Marshal.SizeOf<CRITICAL_SECTION> ());
				if (_cs == IntPtr.Zero)
					throw new OutOfMemoryException ("Failed to allocate memory for critical section");

				InitializeCriticalSectionEx (_cs, 4000, 0);
			}

			~NonAlertableWin32Lock ()
			{
				if (_cs != IntPtr.Zero) {
					DeleteCriticalSection (_cs);
					Marshal.FreeHGlobal (_cs);
					_cs = IntPtr.Zero;
				}
			}

			IntPtr _cs;

			void Enter ()
			{
				if (_cs != IntPtr.Zero) {
					EnterCriticalSection(_cs);
				}
			}

			void Leave ()
			{
				if (_cs != IntPtr.Zero) {
					LeaveCriticalSection(_cs);
				}
			}

			public void EnterReadLock () { Enter (); }
			public void ExitReadLock () { Leave (); }
			public void EnterWriteLock () { Enter (); }
			public void ExitWriteLock () { Leave (); }
			public void EnterUpgradeableReadLock () { Enter (); }
			public void ExitUpgradeableReadLock () { Leave (); }

			[StructLayout (LayoutKind.Sequential)]
			public struct CRITICAL_SECTION
			{
				public IntPtr DebugInfo;
				public int LockCount;
				public int RecursionCount;
				public IntPtr OwningThread;
				public IntPtr LockSemaphore;
				public UIntPtr SpinCount;
			}

			[DllImport ("Kernel32.dll", SetLastError = true)]
			[return: MarshalAs (UnmanagedType.Bool)]
			static extern bool InitializeCriticalSectionEx (IntPtr lpCriticalSection, uint dwSpinCount, uint Flags);
			[DllImport ("Kernel32.dll")]
			static extern void DeleteCriticalSection (IntPtr lpCriticalSection);
			[DllImport ("Kernel32.dll")]
			static extern void EnterCriticalSection (IntPtr lpCriticalSection);
			[DllImport ("Kernel32.dll")]
			static extern void LeaveCriticalSection (IntPtr lpCriticalSection);
		}
	}

}


text:
---
layout: post
title:  "Blog test!"
date:   2016-07-23 14:40:33 +0800
categories: jekyll update
---
This is a demo article for testing the first log.

below is code of java,see if it's work.
{% highlight java %}
public class Person implement Serializable{
    private int name;

    public int getName(){
        return name;
    }

    /**
    *   setting name
    */
    public int setName(int name){
        this.name = name;
    }
}
{% endhighlight %}

```java
public class Person implement Serializable{
    private int name;

    public int getName(){
        return name;
    }

    /**
    *   setting name
    */
    public int setName(int name){
        this.name = name;
    }
}
```


text:
Param (
    [Parameter(Mandatory=$true)]
    [String] $SubscriptionId,
    [Parameter(Mandatory=$true)]
    [String] $ResourceGroupName,
    [Parameter(Mandatory=$true)]
    [String] $AutomationAccountName,
    [Parameter(Mandatory=$false)]
    [ValidateSet('AzureCloud','AzureUSGovernment')]
    [Alias('EnvironmentName')]
    [string] $Environment = 'AzureCloud',
    [Parameter(Mandatory=$false)]
    [int] $DaysSinceLastSeen = 30,
    [Parameter(Mandatory=$false)]
    [switch] $WhatIf
)

    Function GetAzureAccessToken {
        Param ()

        $context = Get-AzureRmContext
        $token = ($context.TokenCache.ReadItems() | Sort-Object ExpiresOn | Where-Object { (($_.TenantId -eq $context.Tenant.Id) -and ($_.DisplayableId -eq $context.Account.Id)) })[-1]
        if (($token.ExpiresOn.UtcDateTime.AddMinutes(-5)) -le ((Get-Date).ToUniversalTime())) {
            Write-Host ("Executing benign PowerShell statement in an attempt to refresh access token.")
            $null = Get-AzureRmSubscription
            $token = ($context.TokenCache.ReadItems() | Sort-Object ExpiresOn | Where-Object { (($_.TenantId -eq $context.Tenant.Id) -and ($_.DisplayableId -eq $context.Account.Id)) })[-1]
        }
        $token.AccessToken
    }

    Function GetAuthorizationHeader {
        Param ()

        $AccessToken = GetAzureAccessToken
        ("Bearer {0}" -f $AccessToken)
    }

    Function BuildHeaders {
        Param ()

        @{
            Authorization = GetAuthorizationHeader
        }
    }

    Function GetOrphanedHybridWorkerGroups {
        $currentTime = Get-Date
        $currentTimeUTC = $currentTime.ToUniversalTime()
        Write-Host ("Current Time: {0} ({1} UTC)" -f $currentTime, $currentTimeUTC)
        Write-Host ("Retrieving list of hybrid worker groups registered in Automation account '{0}'." -f $AutomationAccountName)
        $Uri = ("{0}subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.Automation/automationAccounts/{3}/hybridRunbookWorkerGroups?api-version=2015-10-31" -f $AzureManagementBaseUri, $SubscriptionId, $ResourceGroupName, $AutomationAccountName)
        $HWGList = @()
        do {
            try {
                Write-Host ("Retrieving Hybrid Worker data from '{0}'." -f $Uri)
                $results = Invoke-RestMethod -Method GET -Uri $Uri -Headers (BuildHeaders) -ContentType "application/json" -UseBasicParsing
                Write-Host ("Data successfully retrieved from {0}" -f $Uri)
                Write-Host ("Next link: {0}" -f $results.nextLink)
                $HWGList += $results.value
                $Uri = $results.nextlink
            } catch {
                if ($_.Exception.Message -like '*ResourceCollectionRequestsThrottled*') {
                    Write-Host ("Encountered resource throttling.  Sleeping for 60 seconds.")
                    Start-Sleep -Second 60
                } else {
                    Write-Error -Exception $_
                }
            }
        } until (!$Uri)
        $OrphanedHWG = @()
        foreach ($HWG in $HWGList) {
            # If there are no workers in the group, then consider the group orphaned
            if (($HWG.hybridRunbookWorkers | Measure-Object).Count -eq 0) {
                Write-Host ("Adding hybrid worker group named '{0}' as orphaned." -f $HWG.name)
                $OrphanedHWG += $HWG
            } else {
                # Retrieve the most recently seen hybrid worker
                $MostRecentSeenWorker = $HWG.hybridRunbookWorkers | Sort-Object -Property lastSeenDateTime -Descending | Select-Object -First 1
                $MostRecentSeenTime = Get-Date($MostRecentSeenWorker.lastSeenDateTime)
                $MostRecentSeenTimeUTC = $MostRecentSeenTime.ToUniversalTime()
                if ($MostRecentSeenTimeUTC -lt $CurrentTimeUTC.AddDays(-$DaysSinceLastSeen)) {
                    Write-Host ("Adding hybrid worker group named '{0}' as orphaned." -f $HWG.name)
                    $OrphanedHWG += $HWG
                }
            }
        }
        $OrphanedHWG
    }

    Function RemoveOrphanedHybridWorkerGroup {
        Param (
            [Parameter(Mandatory=$true)]
            [string] $HybridWorkerGroupName,
            [Parameter(Mandatory=$false)]
            [switch] $WhatIf
        )

        if ($WhatIf) {
            Write-Host ("what if: Deleting hybrid worker group named '{0}'." -f $HybridWorkerGroupName)
        } else {
            Write-Host ("Deleting hybrid worker group named '{0}'." -f $HybridWorkerGroupName)
            $Uri = ("{0}subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.Automation/automationAccounts/{3}/hybridRunbookWorkerGroups/{4}?api-version=2015-10-31" -f $AzureManagementBaseUri, $SubscriptionId, $ResourceGroupName, $AutomationAccountName, $HybridWorkerGroupName)
            Write-Host ("Deleting hybrid worker group from '{0}'." -f $Uri)
            Invoke-RestMethod -Method DELETE -Uri $Uri -Headers (BuildHeaders) -ContentType "application/json" -UseBasicParsing
        }
    }

# Clearing any Azure cached contexts for the current user
Write-Host ("Clearing Azure cached contexts for the current process.")
$null = Clear-AzureRmContext -Scope Process -Force

# Enable the ability for auto save of context to process
Write-Host ("Enabling context auto save for process scope.")
$null = Enable-AzureRmContextAutosave -Scope Process

# Login to Azure.
Write-Host ("Prompting user to login to Azure environment '{0}'." -f $Environment)
$account = Add-AzureRmAccount -Environment $Environment
if (!($account)) {
    throw ("Unable to successfully authenticate to Azure for environment '{0}'." -f $Environment)
}

# Selecting the subscription
Write-Host ("Setting subscription to '{0}'." -f $SubscriptionId)
$AzureContext = Set-AzureRmContext -SubscriptionId $SubscriptionId -Scope Process

# Setting Azure Resource Manager endpoint
$AzureManagementBaseUri = $AzureContext.Environment.ResourceManagerUrl
Write-Host ("Setting resource manager endpoint to {0}." -f $AzureManagementBaseUri)

# Get the list or hybrid worker groups that are considered orphaned
$OrphanedHWGs = GetOrphanedHybridWorkerGroups
Write-Host ("{0} orphaned hybrid worker group(s) identified." -f ($OrphanedHWGS | Measure-Object).Count)

# Remove each of the hybrid worker groups
foreach ($HWG in $OrphanedHWGs) {
    RemoveOrphanedHybridWorkerGroup -HybridWorkerGroupName $HWG.name -WhatIf:$WhatIf
}


text:
[![Status](https://travis-ci.org/liyang/assert.png)](https://travis-ci.org/liyang/assert)
<http://hackage.haskell.org/package/assert>


text:
{% extends 'common/templates/base_sidebar.html' %}
{% load nonce avatar vcard actor %}
{% block title %}
  {% ifequal request.user.nick view.nick %}
  Your {{POST_NAME}}s
  {% else %}
  {{POST_NAME}}s from {{ view.display_nick }}
  {% endifequal %}
{% endblock %}

{% block content %}

{% ifequal request.user.nick view.nick %}
  {% include 'common/templates/message_form.html' %}
{% else %}
  {% include 'form_error.html' %}

      {% with view as actor %}
        {% include 'common/templates/vcard_full.html' %}
      {% endwith %}

      {% if request.user %}
        {% if user_is_contact %}

          {{view.display_nick}} is your contact.
          {% actor_remove_contact request.user request.user view %}

        {% else %}

          {% actor_add_contact_long request.user request.user view %}

        {% endif %}
      {% endif %}

{% endifequal %}

{% if not request.mobile %}
  {% ifequal view.nick request.user.nick %}

      Overview

    Your {{POST_NAME}}s

  {% endifequal %}
{% endif %}

{% ifequal request.user.nick view.nick %}

Your {{POST_NAME}}s

{% else %}

{{POST_NAME}}s from {{ view.display_nick }}

{% endifequal %}

  {% include 'common/templates/stream.html' %}
  {% include 'common/templates/paging.html' %}
  {% include 'common/templates/feeds.html' %}

{% endblock %}

{% block sidebar %}
{% if not user_is_private %}
  {% include 'common/templates/sidebar_location.html' %}
  {% include 'common/templates/sidebar_contacts.html' %}
  {% with view_streams as streams %}
    {% include 'common/templates/sidebar_streams.html' %}
  {% endwith %}
{% else %}
  {% include 'actor/templates/sidebar_privateuser.html' %}
{% endif %}
{% endblock %}


text:
CREATE TABLE IF NOT EXISTS `error_report` (
  `error_report_id` int(10) NOT NULL AUTO_INCREMENT,
  `error_report_message` text,
  `error_report_email` varchar(255) DEFAULT NULL,
  `error_report_filename` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`error_report_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;


text:
<?php
# Error level
ini_set('display_errors', 1);
error_reporting(E_ALL);

# DB settings
define("DB_C", "mysql:host=localhost;dbname=loc_orm");
define("DB_U", "loc_orm");
define("DB_P", "12341234");

# debug mode
define("DEBUGGING", false);
?>