text:
<sky-demo-page title="List">
  <sky-demo-page-summary>
    This list component displays a SKY UX-themed list of data.  It includes options for adding
    searching, filtering, paging, and multiple view types.

Related Components

Here is a list of related components that can be used within the list component.

List Filters (sky-contrib-list-filters)

List Paging (sky-contrib-list-paging)

List Toolbar (sky-contrib-list-toolbar)

        List View Checklist (sky-contrib-list-view-checklist)

List View Grid (sky-contrib-list-view-grid)

        List View Repeater (sky-contrib-list-view-repeater)

List
      Action Bar (sky-contrib-list-action-bar)

  </sky-demo-page-summary>

  <sky-demo-page-properties>
    <sky-demo-page-property
        propertyName="data"
        defaultValue="[]"
        isOptional="true"
    >
      Specifies the data to display.
      Must provide data or dataProvider.
      Acceptable values: Observable Array or Array.
    </sky-demo-page-property>
    <sky-demo-page-property
        propertyName="dataProvider"
        defaultValue="SkyListInMemoryDataProvider"
        isOptional="true"
    >
      Specific a data provider used to obtain data to display.
      Must provide data or dataProvider.
      Acceptable values: extends ListDataProvider.
    </sky-demo-page-property>
    <sky-demo-page-property
        propertyName="defaultView"
        defaultValue=""
        isOptional="true"
    >
      Specifies a reference to the ListViewComponent to display when initialized.
    </sky-demo-page-property>
    <sky-demo-page-property
        propertyName="initialTotal"
        defaultValue=""
        isOptional="true"
    >
      Specifies the total number of items for the initial data set when initialized.
      When used in conjunction with data and dataProvider it allows an
      initial data to be set with the need to call the dataProvider.
    </sky-demo-page-property>
    <sky-demo-page-property
        propertyName="search"
        defaultValue=""
        isOptional="true"
    >
      Specific a function to apply as a global sort on the list.
      Acceptable value: (searchText: string) => Observable Array or Promise Array.
    </sky-demo-page-property>
    <sky-demo-page-property
        propertyName="selectedIds"
        defaultValue=""
        isOptional="true"
    >
      Specific a set of selected ids to used with a checklist view.
      Acceptable values: Observable Array of strings or Array of strings.
    </sky-demo-page-property>
    <sky-demo-page-property
        propertyName="sortFields"
        defaultValue=""
        isOptional="true"
    >
      Specific a set of views to sort by. If array of fields then sorted by order of array.
      Acceptable values: string, Observable string, Array of strings,
      or Observable Array of strings.
    </sky-demo-page-property>
  </sky-demo-page-properties>

  <sky-demo-page-example>

List with multiple views

    <sky-contrib-list-demo></sky-contrib-list-demo>

List with custom view

    <sky-contrib-list-demo-custom></sky-contrib-list-demo-custom>

    <sky-demo-page-code demoName="List"></sky-demo-page-code>
  </sky-demo-page-example>
</sky-demo-page>


text:
import threading
import time
import datetime
import csv
from operator import itemgetter

class EventReader(threading.Thread):
    def __init__(self, file=None, show=None):
        threading.Thread.__init__(self, name="event file player")
        if not file:
            raise ValueError("no file path provided")
        self.file = file
        self.show = show
        self._stopevent = threading.Event()
        self.pending_event = None
        self.started = 0
        self.start_offset = 0
        self.song_start = "start"
        self.looping = False
        self.looping_duration = 0
        self.run_started = 0
        self.reader = None
        self.init_reader()

    def init_reader(self):
        del(self.reader)
        self.reader = csv.reader(open(self.file, 'rb'))

    def seek_start(self):
        while not self.started:
            event = self.reader.next()
            m = event[1]
            if m == self.song_start:
                self.start_offset = float(event[3])  # ms timestamp of event
                self.started = time.time()
                if hasattr(self.show, 'audio_player'):
                    self.show.audio_player.start()
                print self.start_offset

    def run(self):
        print "%s starts" % (self.getName(),)
        # TODO self.run_started and self.started seem redundant and may not be
        # needed?
        self.run_started = time.time()
        self.seek_start()
        while not self._stopevent.is_set():
            # TODO do I need an attribute here to only run full loops - or
            # always respect duration?
            if self.looping and self.looping_duration:
                if time.time() > self.run_started + self.looping_duration:
                    self._stopevent.set()
                    continue
            if not self.pending_event:
                try:
                    self.pending_event = self.reader.next()
                    print self.pending_event
                except StopIteration:
                    if self.looping:
                        if self.looping_duration:
                            if (time.time() >
                                    self.run_started + self.looping_duration):
                                self._stopevent.set()
                                continue
                        self.init_reader()
                        self.started = 0
                        self.seek_start()
                        print "looping"
                        continue
                    else:
                        self._stopevent.set()
                        continue
                    self._stopevent.set()
                    continue
            # tracktime = (((time.time() - self.started)) + self.start_offset)
            time_delta = time.time() - self.started
            event_delta = float(self.pending_event[3]) - self.start_offset
            if time_delta >= event_delta:
                if self.pending_event[0][0].lower() == 't':
                    print "triggering " + self.pending_event[1]
                    lightobj = self.show.get_named_element(
                            self.pending_event[1])
                    lightobj.trigger(int(self.pending_event[2]))
                elif self.pending_event[0][0].lower() == 'm':
                    lightname, attr = self.pending_event[1].split('.')
                    lightobj = self.show.get_named_element(lightname)
                    setattr(lightobj, attr, int(self.pending_event[2]))
                self.pending_event = None
            else:
                self._stopevent.wait(.1)
        print "%s ends" % (self.getName(),)
        self.cleanup()

    def cleanup(self):
        if self.file:
            try:
                self.file_obj.close()
            except:
                pass

    def join(self, timeout=None):
        if self.looping:
            self._stopevent.set()
            self.cleanup()
        threading.Thread.join(self, timeout)

    def stop(self):
        self._stopevent.set()
        self.cleanup()
        self.join()

def logger(s):
    print s

class TriggerFilePlayer(threading.Thread):
    observers = {}
    daemon = True

    def __init__(self, file, dispatch_func=logger):
        threading.Thread.__init__(self, name="trigger file player")
        self._stopevent = threading.Event()
        self.file = file
        self.file_obj = open(file, 'r')
        self.dispatch = dispatch_func
        self.pending_message = None
        self.started = 0
        self.start_offset = 0
        self.song_start = [144, 39, 127, 0]
        self.looping = False
        self.looping_duration = 0
        self.run_started = 0

    def init_reader(self):
        self.file_obj = open(self.file, 'r')

    def seek_start(self):
        while not self.started:
            l = self.file_obj.readline().strip()
            event = eval(l)
            m = event[0]
            if m == self.song_start:
                self.start_offset = event[1]  # ms timestamp of event
                self.started = time.time()

    def run(self):
        print "%s starts" % (self.getName(),)
        self.run_started = time.time()
        self.seek_start()
        while not self._stopevent.is_set():
            # TODO do I need an attribute here to only run full loops - or
            # always respect duration?
            if self.looping and self.looping_duration:
                if time.time() > self.run_started + self.looping_duration:
                    self._stopevent.set()
                    continue
            if not self.pending_message:
                l = self.file_obj.readline().strip()
                if l:
                    self.pending_message = eval(l)
                else:
                    self.cleanup()
                    if self.looping:
                        if self.looping_duration:
                            if (time.time() >
                                    self.run_started + self.looping_duration):
                                self._stopevent.set()
                                continue
                        self.init_reader()
                        self.started = 0
                        self.seek_start()
                        print "looping"
                        continue
                    else:
                        self._stopevent.set()
                        continue
            tracktime = (((time.time() - self.started) * 1000)
                    + self.start_offset)
            if tracktime >= self.pending_message[1]:
                self.dispatch(self.pending_message)
                self.pending_message = None
            self._stopevent.wait(.003)
        print "%s ends" % (self.getName(),)
        self.cleanup()

    def cleanup(self):
        if self.file:
            try:
                self.file_obj.close()
            except:
                pass

    def join(self, timeout=None):
        if self.looping:
            self._stopevent.set()
            self.cleanup()
        threading.Thread.join(self, timeout)

    def stop(self):
        self._stopevent.set()
        self.cleanup()
        self.join()

class BasicScheduleComponent(object):
    def __init__(self, *arg, **kwargs):
        super(BasicScheduleComponent, self).__init__()
        self.file = kwargs.get('file', '')
        self.looping_duration = 0
        self.looping = False
        self.timed = False
        self.name = "generic component"

    def time_test(self):
        return datetime.datetime.now().minute % 10

class BasicScheduledPlayer(threading.Thread):
    """
    A simple manager of trigger file playing will need something more put
    together later @@
    """
    def __init__(self, *arg, **kwargs):
        super(BasicScheduledPlayer, self).__init__()
        self._stopevent = threading.Event()
        self.dispatch = kwargs.get('dispatch_func')
        # (tm_year=2010, tm_mon=12, tm_mday=3, tm_hour=4, tm_min=51, tm_sec=4,
        # tm_wday=4, tm_yday=337, tm_isdst=0)
        self.start_time = datetime.time()
        self.end_time = datetime.time()
        self.components = []
        self.show = None

    def run(self):
        print "Scheduled Player Starts"
        while not self._stopevent.is_set():
            now = datetime.datetime.now().time()
            if not (self.start_time < now < self.end_time):
                print "delaying"
                if self.show:
                    self.show.blackout()
                time.sleep(1)
                continue
            for c in self.components:
                t = TriggerFilePlayer(c.file, dispatch_func=self.dispatch)
                t.looping_duration = c.looping_duration
                t.looping = c.looping
                print "starting %s" % c.name
                t.start()
                if c.timed:
                    while c.time_test():
                        time.sleep(1)
                    print "%s time test returned false" % c.name
                    t.stop()
                else:
                    t.join()
                    print "%s ended" % c.name

    def stop(self):
        self._stopevent.set()
        self.join()

class FileMerger(object):
    def __init__(self):
        super(FileMerger, self).__init__()
        self.all_events = []

    def merge_files(self, filelist, outfile=None):
        for f in filelist:
            self.add_file(f)
        self.merge()
        if self.outfile:
            self.write_file(outfile)

    def write_file(self, outfile):
        fobj = open(outfile, 'wb')
        writer = csv.writer(fobj)
        for e in self.sorted_events:
            writer.writerow(e)
        fobj.close()

    def merge(self):
        """Sort the concatenated data"""
        self.sorted_events = sorted(self.all_events, key=itemgetter(3))
        self.sorted_events.insert(0, ['trigger', 'start', '255', '0'])

    def add_file(self, f):
        # ('type','target','data','time'))
        reader = csv.reader(open(f, 'rb'))
        in_start = False
        start_time = 0
        for l in reader:
            if not in_start and l[1].lower() != 'music':
                start_time = l[3]
                continue
            # align all time to start start
            l[3] = l[3] - start_time
            self.all_events.append(l)

redpajama_set_name: RedPajamaGithub


text:
package com.youama.nexus.parser;

import org.junit.*;
import static org.junit.Assert.*;

import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

/**
 * @author David Belicza
 * @since 0.1.0
 */
public class HTMLBuilderTest {

    @Test
    public void testGetDOM() {
        Document doc = HTMLBuilder
                .getDOM("test link

test2 link");
        Elements elements = doc.getAllElements();
        // Seven because of parent and the HTML, HEAD, etc built tags.
        assertEquals(7, elements.size());

        doc = HTMLBuilder.getDOM(
                "test link

test2 link",
                HTMLBuilder.UTF8);
        elements = doc.getAllElements();
        // Seven because of parent and the HTML, HEAD, etc built tags.
        assertEquals(7, elements.size());
    }
}


text:
package net.wendal.nutzbook.quartz.job;

import org.nutz.integration.quartz.annotation.Scheduled;
import org.nutz.ioc.loader.annotation.IocBean;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

@IocBean
@Scheduled(cron="0 0 6 * * ?")
public class QiniuUserAvatarUpdateJob implements Job {

	public void execute(JobExecutionContext context) throws JobExecutionException {
		// TODO 待完成
	}

}


text:
function main() {
    while getopts 'h' OPT; do
        case ${OPT} in
            h)
                printf ""
                exit 0
                ;;
        esac
    done

    printf "[+] Creating ${HOME}/bin directory\n"
    if [ -d ${HOME}/bin ]; then
        printf "[-] Folder already exists\n"
    else
        mkdir ${HOME}/bin
    fi
    printf "[*] Remember to add the following line to your shell config\n"
    printf "    PATH=\$PATH:\$HOME/bin"

    printf "[+] Installing tools for firmware RE\n"
    apt-get install -y squashfs-tools radare2 binwalk qemu clang lldb

}

main ${@}


text:
package mysql

import (
	"context"
	"io/ioutil"
	"net"
	"os"
	"path"
	"reflect"
	"testing"

	"vitess.io/vitess/go/vt/tlstest"
	"vitess.io/vitess/go/vt/vttls"
)

const clientCertUsername = "Client Cert"

func TestValidCert(t *testing.T) {
	th := &testHandler{}

	authServer := &AuthServerClientCert{
		Method: MysqlClearPassword,
	}

	// Create the listener, so we can get its host.
	l, err := NewListener("tcp", ":0", authServer, th, 0, 0, false)
	if err != nil {
		t.Fatalf("NewListener failed: %v", err)
	}
	defer l.Close()
	host := l.Addr().(*net.TCPAddr).IP.String()
	port := l.Addr().(*net.TCPAddr).Port

	// Create the certs.
	root, err := ioutil.TempDir("", "TestSSLConnection")
	if err != nil {
		t.Fatalf("TempDir failed: %v", err)
	}
	defer os.RemoveAll(root)
	tlstest.CreateCA(root)
	tlstest.CreateSignedCert(root, tlstest.CA, "01", "server", "server.example.com")
	tlstest.CreateSignedCert(root, tlstest.CA, "02", "client", clientCertUsername)

	// Create the server with TLS config.
	serverConfig, err := vttls.ServerConfig(
		path.Join(root, "server-cert.pem"),
		path.Join(root, "server-key.pem"),
		path.Join(root, "ca-cert.pem"),
		"")
	if err != nil {
		t.Fatalf("TLSServerConfig failed: %v", err)
	}
	l.TLSConfig.Store(serverConfig)
	go func() {
		l.Accept()
	}()

	// Setup the right parameters.
	params := &ConnParams{
		Host:  host,
		Port:  port,
		Uname: clientCertUsername,
		Pass:  "",
		// SSL flags.
		Flags:      CapabilityClientSSL,
		SslCa:      path.Join(root, "ca-cert.pem"),
		SslCert:    path.Join(root, "client-cert.pem"),
		SslKey:     path.Join(root, "client-key.pem"),
		ServerName: "server.example.com",
	}

	ctx := context.Background()
	conn, err := Connect(ctx, params)
	if err != nil {
		t.Fatalf("Connect failed: %v", err)
	}
	defer conn.Close()

	// Make sure this went through SSL.
	result, err := conn.ExecuteFetch("ssl echo", 10000, true)
	if err != nil {
		t.Fatalf("ExecuteFetch failed: %v", err)
	}
	if result.Rows[0][0].ToString() != "ON" {
		t.Errorf("Got wrong result from ExecuteFetch(ssl echo): %v", result)
	}

	userData := th.LastConn().UserData.Get()
	if userData.Username != clientCertUsername {
		t.Errorf("userdata username is %v, expected %v", userData.Username, clientCertUsername)
	}

	expectedGroups := []string{"localhost", "127.0.0.1", clientCertUsername}
	if !reflect.DeepEqual(userData.Groups, expectedGroups) {
		t.Errorf("userdata groups is %v, expected %v", userData.Groups, expectedGroups)
	}

	// Send a ComQuit to avoid the error message on the server side.
	conn.writeComQuit()
}

func TestNoCert(t *testing.T) {
	th := &testHandler{}

	authServer := &AuthServerClientCert{
		Method: MysqlClearPassword,
	}

	// Create the listener, so we can get its host.
	l, err := NewListener("tcp", ":0", authServer, th, 0, 0, false)
	if err != nil {
		t.Fatalf("NewListener failed: %v", err)
	}
	defer l.Close()
	host := l.Addr().(*net.TCPAddr).IP.String()
	port := l.Addr().(*net.TCPAddr).Port

	// Create the certs.
	root, err := ioutil.TempDir("", "TestSSLConnection")
	if err != nil {
		t.Fatalf("TempDir failed: %v", err)
	}
	defer os.RemoveAll(root)
	tlstest.CreateCA(root)
	tlstest.CreateSignedCert(root, tlstest.CA, "01", "server", "server.example.com")

	// Create the server with TLS config.
	serverConfig, err := vttls.ServerConfig(
		path.Join(root, "server-cert.pem"),
		path.Join(root, "server-key.pem"),
		path.Join(root, "ca-cert.pem"),
		"")
	if err != nil {
		t.Fatalf("TLSServerConfig failed: %v", err)
	}
	l.TLSConfig.Store(serverConfig)
	go func() {
		l.Accept()
	}()

	// Setup the right parameters.
	params := &ConnParams{
		Host:       host,
		Port:       port,
		Uname:      "user1",
		Pass:       "",
		Flags:      CapabilityClientSSL,
		SslCa:      path.Join(root, "ca-cert.pem"),
		ServerName: "server.example.com",
	}

	ctx := context.Background()
	conn, err := Connect(ctx, params)
	if err == nil {
		t.Errorf("Connect() should have errored due to no client cert")
	}
	if conn != nil {
		conn.Close()
	}
}


text:
package org.axonframework.eventsourcing.eventstore.jpa;

import org.axonframework.common.AxonConfigurationException;
import org.axonframework.common.io.IOUtils;
import org.axonframework.common.jdbc.PersistenceExceptionResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.EntityExistsException;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

/**
 * SQLErrorCodesResolver is an implementation of PersistenceExceptionResolver used to resolve sql error codes to see if
 * it is an duplicate key constraint violation.
 *

 * SQL Code configuration is available for the following database engines, which may be identifier automatically via
 * the data source:

 *
HSQL DB

 *
MySQL

 *
Apache Derby

 *
DB2

 *
H2

 *
Informix Dynamic Server

 *
MS SQL Server

 *
Oracle

 *
PostgreSQL

 *
Sybase

 *

 *
 * @author Martin Tilma
 * @author Allard Buijze
 * @since 0.7
 */
public class SQLErrorCodesResolver implements PersistenceExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(SQLErrorCodesResolver.class);
    private static final String SQL_ERROR_CODES_PROPERTIES = "SQLErrorCode.properties";
    private static final String PROPERTY_NAME_SUFFIX = ".duplicateKeyCodes";
    private static final String LIST_SEPARATOR = ",";

    private List<Integer> duplicateKeyCodes = Collections.emptyList();

    /**
     * Initializes the SQLErrorCodesResolver using the given list of SQL Codes representing Key Constraint Violations.
     *
     * @param duplicateKeyCodes A list of Integer containing SQL Codes representing Key Constraint Violations
     */
    public SQLErrorCodesResolver(List<Integer> duplicateKeyCodes) {
        this.duplicateKeyCodes = duplicateKeyCodes;
    }

    /**
     * Initialize a SQLErrorCodesResolver, automatically detecting the database name through the given dataSource. The
     * database product name is used to resolve the database error codes.
     *
     * @param dataSource The data source providing the information about the backing database.
     * @throws java.sql.SQLException      when retrieving the database product name fails
     * @throws AxonConfigurationException is the dataSource returns an unknown database product name. Use {@link
     *                                    #SQLErrorCodesResolver(java.util.Properties, javax.sql.DataSource)} instead.
     */
    public SQLErrorCodesResolver(DataSource dataSource) throws SQLException {
        Properties properties = loadDefaultPropertyFile();
        initialize(properties, getDatabaseProductNameFromDataSource(dataSource));
    }

    /**
     * Initialize a SQLErrorCodesResolver, automatically detecting the database name through the given dataSource. The
     * database product name is used to resolve the database error codes. As an alternative you could set the property
     * databaseDuplicateKeyCodes
     *
     * @param databaseProductName The product name of the database
     * @throws AxonConfigurationException is the dataSource returns an unknown database product name. Use {@link
     *                                    #SQLErrorCodesResolver(java.util.Properties, String)} instead.
     */
    public SQLErrorCodesResolver(String databaseProductName) {
        initialize(loadDefaultPropertyFile(), databaseProductName);
    }

    /**
     * Initialize a SQLErrorCodesResolver, automatically detecting the database name through the given dataSource. The
     * database product name is used to resolve the database error codes. As an alternative you could set the property
     * databaseDuplicateKeyCodes
     *

     * The form of the properties is expected to be:

     * {@code databaseName}.duplicateKeyCodes=keyCode[,keyCode]*

     * Where {@code databaseName} is the database product name as returned by the driver, with spaces ('
     * ') replaced by underscore ('_'). The key codes must be a comma separated list of SQL Error code numbers (int).
     *
     * @param properties          the properties defining SQL Error Codes for Duplicate Key violations for different
     *                            databases
     * @param databaseProductName The product name of the database
     */
    public SQLErrorCodesResolver(Properties properties, String databaseProductName) {
        initialize(properties, databaseProductName);
    }

    /**
     * Initialize the SQLErrorCodesResolver with the given {@code properties} and use the {@code dataSource}
     * to automatically retrieve the database product name.
     *

     * The form of the properties is expected to be:

     * {@code databaseName}.duplicateKeyCodes=keyCode[,keyCode]*

     * Where {@code databaseName} is the database product name as returned by the driver, with spaces ('
     * ') replaced by underscore ('_'). The key codes must be a comma separated list of SQL Error code numbers (int).
     *
     * @param properties the properties defining SQL Error Codes for Duplicate Key violations for different databases
     * @param dataSource The data source providing the database product name
     * @throws java.sql.SQLException when retrieving the database product name fails
     */
    public SQLErrorCodesResolver(Properties properties, DataSource dataSource) throws SQLException {
        initialize(properties, getDatabaseProductNameFromDataSource(dataSource));
    }

    private void initialize(Properties properties, String databaseProductName) {
        duplicateKeyCodes = loadKeyViolationCodes(databaseProductName, properties);
    }

    @SuppressWarnings({"ThrowableResultOfMethodCallIgnored"})
    @Override
    public boolean isDuplicateKeyViolation(Exception exception) {
        if (causeIsEntityExistsException(exception)) {
            return true;
        }
        SQLException sqlException = findSQLException(exception);
        boolean isDuplicateKey = false;
        if (sqlException != null) {
            isDuplicateKey = duplicateKeyCodes.contains(sqlException.getErrorCode());
        }
        return isDuplicateKey;
    }

    private boolean causeIsEntityExistsException(Throwable exception) {
        return exception instanceof EntityExistsException
                || (exception.getCause() != null && causeIsEntityExistsException(exception.getCause()));
    }

    private SQLException findSQLException(Throwable exception) {
        SQLException sqlException = null;
        while (sqlException == null && exception != null) {
            if (exception instanceof SQLException) {
                sqlException = (SQLException) exception;
            } else {
                exception = exception.getCause();
            }
        }

        return sqlException;
    }

    private String getDatabaseProductNameFromDataSource(DataSource dataSource) throws SQLException {
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            return connection.getMetaData().getDatabaseProductName();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                // we did our best.
                logger.warn("An error occurred while trying to close the database connection. Ignoring...", e);
            }
        }
    }

    private List<Integer> loadKeyViolationCodes(String databaseProductName, Properties properties) {
        String key = databaseProductName.replaceAll(" ", "_") + PROPERTY_NAME_SUFFIX;
        String property = properties.getProperty(key);

        List<Integer> keyCodes = new ArrayList<>();

        if (property == null) {
            throw new AxonConfigurationException(String.format(
                    "The database product name '%s' is unknown. No SQLCode configuration is known for that database.",
                    databaseProductName));
        }
        String[] codes = property.split(LIST_SEPARATOR);
        for (String code : codes) {
            keyCodes.add(Integer.valueOf(code));
        }

        return keyCodes;
    }

    private Properties loadDefaultPropertyFile() {
        Properties properties = new Properties();
        InputStream resources = null;
        try {
            resources = SQLErrorCodesResolver.class.getResourceAsStream(SQL_ERROR_CODES_PROPERTIES);
            properties.load(resources);
        } catch (IOException e) {
            throw new AxonConfigurationException("Unable to read from a file that should be ", e);
        } finally {
            IOUtils.closeQuietly(resources);
        }
        return properties;
    }
}


text:
using System;
using MongoDB.Bson;
using MongoDB.Driver;
using NUnit.Framework;

namespace MongoDB.Driver.Tests
{
    [TestFixture]
    public class MongoDatabaseSettingsTests
    {
        private MongoClient _client;
        private MongoServer _server;

        [TestFixtureSetUp()]
        public void TestFixtureSetUp()
        {
            _client = new MongoClient();
            _server = _client.GetServer();
        }

        [Test]
        public void TestAll()
        {
            var settings = new MongoDatabaseSettings
            {
                GuidRepresentation = GuidRepresentation.PythonLegacy,
                ReadPreference = ReadPreference.Primary,
                WriteConcern = WriteConcern.Acknowledged
            };

            Assert.AreEqual(GuidRepresentation.PythonLegacy, settings.GuidRepresentation);
            Assert.AreSame(ReadPreference.Primary, settings.ReadPreference);
#pragma warning disable 618
            Assert.AreEqual(new SafeMode(true), settings.SafeMode);
#pragma warning restore
            Assert.AreSame(WriteConcern.Acknowledged, settings.WriteConcern);
        }

        [Test]
        public void TestAllObsolete()
        {
#pragma warning disable 618
            var settings = new MongoDatabaseSettings(_server, "database")
            {
                GuidRepresentation = GuidRepresentation.PythonLegacy,
                ReadPreference = ReadPreference.Primary,
                WriteConcern = WriteConcern.Acknowledged
            };

            Assert.AreEqual("database", settings.DatabaseName);
            Assert.AreEqual(GuidRepresentation.PythonLegacy, settings.GuidRepresentation);
            Assert.AreSame(ReadPreference.Primary, settings.ReadPreference);
            Assert.AreEqual(new SafeMode(true), settings.SafeMode);
            Assert.AreEqual(false, settings.SlaveOk);
            Assert.AreSame(WriteConcern.Acknowledged, settings.WriteConcern);
#pragma warning restore
        }

        [Test]
        public void TestClone()
        {
            // set everything to non default values to test that all settings are cloned
            var settings = new MongoDatabaseSettings
            {
                GuidRepresentation = GuidRepresentation.PythonLegacy,
                ReadPreference = ReadPreference.Secondary,
                WriteConcern = WriteConcern.W2
            };
            var clone = settings.Clone();
            Assert.IsTrue(clone.Equals(settings));
        }

        [Test]
        public void TestConstructor()
        {
            var settings = new MongoDatabaseSettings();
            Assert.AreEqual(GuidRepresentation.Unspecified, settings.GuidRepresentation);
            Assert.AreEqual(null, settings.ReadPreference);
#pragma warning disable 618
            Assert.AreEqual(null, settings.SafeMode);
#pragma warning restore
            Assert.AreEqual(null, settings.WriteConcern);
        }

        [Test]
        public void TestConstructorObsolete()
        {
#pragma warning disable 618
            var settings = new MongoDatabaseSettings(_server, "database");
            Assert.AreEqual("database", settings.DatabaseName);
            Assert.AreEqual(MongoDefaults.GuidRepresentation, settings.GuidRepresentation);
            Assert.AreEqual(ReadPreference.Primary, settings.ReadPreference);
            Assert.AreEqual(new SafeMode(true), settings.SafeMode);
            Assert.AreEqual(false, settings.SlaveOk);
            Assert.AreEqual(WriteConcern.Acknowledged, settings.WriteConcern);
#pragma warning restore
        }

        [Test]
        public void TestDatabaseNameObsolete()
        {
#pragma warning disable 618
            var settings = new MongoDatabaseSettings(_server, "database");
            Assert.AreEqual("database", settings.DatabaseName);

            settings.Freeze();
            Assert.AreEqual("database", settings.DatabaseName);
#pragma warning restore
        }

        [Test]
        public void TestEquals()
        {
            var settings = new MongoDatabaseSettings();
            var clone = settings.Clone();
            Assert.IsTrue(clone.Equals(settings));

            settings.Freeze();
            clone.Freeze();
            Assert.IsTrue(clone.Equals(settings));

            clone = settings.Clone();
            clone.GuidRepresentation = GuidRepresentation.PythonLegacy;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.ReadPreference = ReadPreference.Secondary;
            Assert.IsFalse(clone.Equals(settings));

#pragma warning disable 618
            clone = settings.Clone();
            clone.SafeMode = SafeMode.W2;
            Assert.IsFalse(clone.Equals(settings));

            clone = settings.Clone();
            clone.SlaveOk = !settings.SlaveOk;
            Assert.IsFalse(clone.Equals(settings));
#pragma warning restore

            clone = settings.Clone();
            clone.WriteConcern = WriteConcern.W2;
            Assert.IsFalse(clone.Equals(settings));
        }

        [Test]
        public void TestFeeze()
        {
            var settings = new MongoDatabaseSettings
            {
                ReadPreference = new ReadPreference(),
                WriteConcern = new WriteConcern()
            };
            Assert.IsFalse(settings.IsFrozen);
            Assert.IsFalse(settings.ReadPreference.IsFrozen);
            Assert.IsFalse(settings.WriteConcern.IsFrozen);
            var hashCode = settings.GetHashCode();
            var stringRepresentation = settings.ToString();

            settings.Freeze();
            Assert.IsTrue(settings.IsFrozen);
            Assert.IsTrue(settings.ReadPreference.IsFrozen);
            Assert.IsTrue(settings.WriteConcern.IsFrozen);
            Assert.AreEqual(hashCode, settings.GetHashCode());
            Assert.AreEqual(stringRepresentation, settings.ToString());
        }

        [Test]
        public void TestFrozenCopy()
        {
            var settings = new MongoDatabaseSettings();
            Assert.IsFalse(settings.IsFrozen);

            var frozenCopy = settings.FrozenCopy();
            Assert.IsFalse(settings.IsFrozen);
            Assert.IsTrue(frozenCopy.IsFrozen);
            Assert.AreNotSame(settings, frozenCopy);

            var secondFrozenCopy = frozenCopy.FrozenCopy();
            Assert.IsTrue(secondFrozenCopy.IsFrozen);
            Assert.AreSame(frozenCopy, secondFrozenCopy);
        }

        [Test]
        public void TestGuidRepresentation()
        {
            var settings = new MongoDatabaseSettings();
            Assert.AreEqual(GuidRepresentation.Unspecified, settings.GuidRepresentation);

            var guidRepresentation = GuidRepresentation.PythonLegacy;
            settings.GuidRepresentation = guidRepresentation;
            Assert.AreEqual(guidRepresentation, settings.GuidRepresentation);

            settings.Freeze();
            Assert.AreEqual(guidRepresentation, settings.GuidRepresentation);
            Assert.Throws<InvalidOperationException>(() => { settings.GuidRepresentation = guidRepresentation; });
        }

        [Test]
        public void TestReadPreference()
        {
            var settings = new MongoDatabaseSettings();
            Assert.AreEqual(null, settings.ReadPreference);

            var readPreference = ReadPreference.Secondary;
            settings.ReadPreference = readPreference;
            Assert.AreEqual(readPreference, settings.ReadPreference);

            settings.Freeze();
            Assert.AreEqual(readPreference, settings.ReadPreference);
            Assert.Throws<InvalidOperationException>(() => { settings.ReadPreference = readPreference; });
        }

        [Test]
        public void TestSafeMode()
        {
#pragma warning disable 618
            var settings = new MongoDatabaseSettings();
            Assert.AreEqual(null, settings.SafeMode);

            var safeMode = SafeMode.W2;
            settings.SafeMode = safeMode;
            Assert.AreEqual(safeMode, settings.SafeMode);

            settings.Freeze();
            Assert.AreEqual(safeMode, settings.SafeMode);
            Assert.Throws<InvalidOperationException>(() => { settings.SafeMode = safeMode; });
#pragma warning restore
        }

        [Test]
        public void TestSlaveOk()
        {
#pragma warning disable 618
            var settings = new MongoDatabaseSettings(_server, "database");
            Assert.AreEqual(false, settings.SlaveOk);

            var slaveOk = true;
            settings.SlaveOk = slaveOk;
            Assert.AreEqual(slaveOk, settings.SlaveOk);

            settings.Freeze();
            Assert.AreEqual(slaveOk, settings.SlaveOk);
            Assert.Throws<InvalidOperationException>(() => { settings.SlaveOk = slaveOk; });
#pragma warning restore
        }

        [Test]
        public void TestWriteConcern()
        {
            var settings = new MongoDatabaseSettings();
            Assert.AreEqual(null, settings.WriteConcern);

            var writeConcern = WriteConcern.W2;
            settings.WriteConcern = writeConcern;
            Assert.AreEqual(writeConcern, settings.WriteConcern);

            settings.Freeze();
            Assert.AreEqual(writeConcern, settings.WriteConcern);
            Assert.Throws<InvalidOperationException>(() => { settings.WriteConcern = writeConcern; });
        }
    }
}


text:
from django.shortcuts import render
from upload_image_box.example.forms import *
from django.conf import settings
from upload_image_box.settings import *

# Example view
def upload_example(request):
    # if you want to upload inside a custom directory
    # request.session['CUSTOM_CROPPED_IMG_DIRECTORY'] = CUSTOM_CROPPED_IMG_DIRECTORY

    # if a GET (or any other method) we'll create a blank form
    form_no_crop = uploadedImagesNoCropForm()
    form_crop = uploadedImagesCropForm()

    context = {
        "post" : request.POST,
        "form_no_crop": form_no_crop,
        "form_crop": form_crop,
    }

    return render(request, 'upload_image_box/upload_example.html', context)


text:
package com.amazonaws.services.ec2.model.transform;

import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;

import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;

import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;

/**
 * UserData StAX Unmarshaller
 */

@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UserDataStaxUnmarshaller implements Unmarshaller<UserData, StaxUnmarshallerContext> {

    public UserData unmarshall(StaxUnmarshallerContext context) throws Exception {
        UserData userData = new UserData();
        int originalDepth = context.getCurrentDepth();
        int targetDepth = originalDepth + 1;

        if (context.isStartOfDocument())
            targetDepth += 1;

        while (true) {
            XMLEvent xmlEvent = context.nextEvent();
            if (xmlEvent.isEndDocument())
                return userData;

            if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

                if (context.testExpression("data", targetDepth)) {
                    userData.setData(StringStaxUnmarshaller.getInstance().unmarshall(context));
                    continue;
                }
            } else if (xmlEvent.isEndElement()) {
                if (context.getCurrentDepth() < originalDepth) {
                    return userData;
                }
            }
        }
    }

    private static UserDataStaxUnmarshaller instance;

    public static UserDataStaxUnmarshaller getInstance() {
        if (instance == null)
            instance = new UserDataStaxUnmarshaller();
        return instance;
    }
}


text: Integrity (using Angular 1) self hosted with Katana/Owin


text:
package com.github.mob41.osumer.exceptions;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;

import com.github.mob41.osumer.exceptions.DebugDump;
import com.github.mob41.osumer.exceptions.DebuggableException;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.Desktop;

import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.SystemColor;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class ErrorDumpDialog extends JDialog {

	private final JPanel contentPanel = new JPanel();

	/**
	 * Create the dialog.
	 */
	public ErrorDumpDialog(DebugDump debugDump) {
		setTitle("Unexpected Error");
		setModal(true);
		setResizable(false);
		setBounds(100, 100, 505, 300);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);

		JLabel lblOsumerHasJust = new JLabel("osumer has just encountered an unexpected error.");
		lblOsumerHasJust.setHorizontalAlignment(SwingConstants.CENTER);

		JLabel lblPleasePostA = new JLabel("Please post a new issue in osumer's GitHub project page. ");
		JLabel lblPleaseAlsoInclude = new JLabel("Please also include the following dump output or the saved dump file (.osmerdump)");
		lblPleaseAlsoInclude.setHorizontalAlignment(SwingConstants.CENTER);
		lblPleaseAlsoInclude.setFont(new Font("PMingLiU", Font.BOLD, 12));
		JLabel lblclickHereTo = new JLabel("[Click here to link to page]");
		lblclickHereTo.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent arg0) {
				try {
					Desktop.getDesktop().browse(new URI("https://github.com/mob41/osumer/issues/new"));
				} catch (IOException | URISyntaxException e) {
					e.printStackTrace();
				}
			}
		});
		lblclickHereTo.setFont(new Font("PMingLiU", Font.BOLD | Font.ITALIC, 12));
		lblclickHereTo.setForeground(Color.BLUE);
		lblclickHereTo.setHorizontalAlignment(SwingConstants.CENTER);
		JLabel lblDebugDumpInfo = new JLabel("Debug dump info:");

		JScrollPane scrollPane = new JScrollPane();
		GroupLayout gl_contentPanel = new GroupLayout(contentPanel);
		gl_contentPanel.setHorizontalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.LEADING)
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 467, Short.MAX_VALUE)
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addComponent(lblOsumerHasJust, GroupLayout.DEFAULT_SIZE, 414, Short.MAX_VALUE)
							.addContainerGap())
						.addComponent(lblPleaseAlsoInclude, GroupLayout.DEFAULT_SIZE, 467, Short.MAX_VALUE)
						.addGroup(gl_contentPanel.createSequentialGroup()
							.addComponent(lblPleasePostA)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(lblclickHereTo, GroupLayout.DEFAULT_SIZE, 198, Short.MAX_VALUE))
						.addComponent(lblDebugDumpInfo, GroupLayout.DEFAULT_SIZE, 467, Short.MAX_VALUE)))
		);
		gl_contentPanel.setVerticalGroup(
			gl_contentPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPanel.createSequentialGroup()
					.addContainerGap()
					.addComponent(lblOsumerHasJust)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_contentPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(lblPleasePostA)
						.addComponent(lblclickHereTo))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(lblPleaseAlsoInclude)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(lblDebugDumpInfo)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE))
		);

		JTextArea textArea = new JTextArea();
		textArea.setText(debugDump != null ? debugDump.toString() : "Debug dump is null");
		textArea.setBackground(SystemColor.control);
		textArea.setEditable(false);
		scrollPane.setViewportView(textArea);
		contentPanel.setLayout(gl_contentPanel);
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("Ignore");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						dispose();
					}
				});
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Save dump");
				cancelButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						if (debugDump == null){
							JOptionPane.showMessageDialog(ErrorDumpDialog.this, "\"debugDump\" is null, cannot save dump with null", "Error", JOptionPane.ERROR_MESSAGE);
							return;
						}
						JFileChooser chooser = new JFileChooser();
						chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
						chooser.setFileFilter(new FileFilter(){

							@Override
							public boolean accept(File arg0) {
								if (arg0 == null){
									return false;
								}

								if (arg0.isDirectory()){
									return true;
								}

								String str = arg0.getName();
								final String ext = ".txt";

								if (str.length() < ext.length()){
									return false;
								}

								return str.endsWith(ext);
							}

							@Override
							public String getDescription() {
								return ".txt (osumer dump files)";
							}

						});
						chooser.setSelectedFile(new File("osumer-debugDump-" + debugDump.getGenerated() + ".txt"));

						int option = chooser.showSaveDialog(ErrorDumpDialog.this);

						if (option == JFileChooser.CANCEL_OPTION){
							return;
						}

						File file = chooser.getSelectedFile();
						if (file.exists()){
							file.delete();
						}
						try {
							file.createNewFile();
							FileOutputStream out = new FileOutputStream(file);
							PrintWriter writer = new PrintWriter(out, true);
							writer.println(debugDump.toString());
							writer.flush();
							writer.close();
							out.close();
						} catch (IOException e){
							JOptionPane.showMessageDialog(ErrorDumpDialog.this, "Error saving dump:\n" + e, "Error", JOptionPane.ERROR_MESSAGE);
							return;
						}

						JOptionPane.showMessageDialog(ErrorDumpDialog.this, "Saved dump to location:\n" + file.getAbsolutePath(), "Info", JOptionPane.INFORMATION_MESSAGE);
					}
				});
				buttonPane.add(cancelButton);
			}
		}
	}
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>AngularJs Query Builder by MyForce</title>

	<link href="css/styles.css" rel="stylesheet">
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<link href='https://fonts.googleapis.com/css?family=Architects+Daughter' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.9.1/styles/github.min.css">

					View project on

GitHub

AngularJS Query Builder

What is AngularJS Query Builder?

				This directive lets the end user create queries in a visual manner.

In this page you can see basic and advanced usage examples.

Download

				There are several options to do that:

Using bower: `bower install myforce-angularjs-query-builder`

						Download the .zip file from here

						Using it from GitHub raw using this link

		<accordion close-others="true">
			<accordion-group heading="Basic Usage Example" is-open="true">

Demo

								Example Output Readable

								Example Output as string

							<query-builder title="Query builder" settings="settings1" fields="fields1" operators="operators1" comparators="comparators1" group="filter1.group"></query-builder>

Code

			</accordion-group>
			<accordion-group heading="Start From String" is-open="false">

Demo

								Example Output Readable

								Example Output as string

							<query-builder title="query-builder" fields="fields2" operators="operators2" comparators="comparators2" group="filter2.group" settings="settings2" as-string="queryAsString2"></query-builder>

Code

			</accordion-group>
			<accordion-group heading="Custom Selection Template" is-open="false">

Demo

								Example Output Readable

								Example Output as string

							<query-builder fields="fields3" operators="operators3" comparators="comparators3" group="filter3.group" settings="settings3" as-string="queryAsString3"></query-builder>

Code

			</accordion-group>
			<accordion-group heading="Disable comparators">

Demo

								Example Output Readable

								Example Output as string

							<query-builder title="Query builder" settings="settings4" fields="fields4" operators="operators4" comparators="comparators4" group="filter4.group"></query-builder>

Code

			</accordion-group>
			<accordion-group heading="Only Allow Field Once">

Demo

								Example Output Readable

								Example Output as string

							<query-builder title="Query builder" settings="settings5" fields="fields5" operators="operators5" comparators="comparators5" group="filter5.group"></query-builder>

Code

			</accordion-group>
		</accordion>

Full Directive Documentation

Attributes

List of allowed attributes, you can find more information about them in the usage examples above.

					Attribute Name
					Type
					Optional
					Description

						fields

					Array
					no
					An array of the possible values of the left side of an expression.

						operators

					Array
					no
					An array of the possible values of the operators in the query. (For example and, or, ...)

						comparators

					Array
					no
					An array of the possible values of the comparators of an expression.

						group

					Object
					no
					The query as an object

						as-string

					string
					yes
					Used for input as string.

						watch-for-string

					bool
					yes
					When set to true directive will watch for as-string to change and then parse that value. Once parsed watch-for-string is set back to false.

						settings

					Object
					yes
					A settings object that can be passed to the directive

						title

					string
					yes
					Title of the query builder. Displayed when settings.bootstrapPanelsEnabled is true

						change

					function
					yes
					Function that will be called when something changes in the query, only for the comparators with a data template an own function needs to be provided for when the data changes there.

Field Object

List of the properties of the objects in the fields array

					Property Name
					Type
					Optional
					Description

						id

					Object
					no
					A unique indentifier of the field

						name

					string
					no
					A name for the field. This is what is displayed in the select box

						options

					Array
					yes
					An array of the possible values for the field. Needs to have an id and when not using custom comparator data templates also a name.

						disabledComparators

					Array
					yes
					An array of ids of the comparators that can not be used with this field.

Operator Object

List of the properties of the objects in the operators array

					Property Name
					Type
					Optional
					Description

						value

					string
					no
					A unique indentifier of the operator

						name

					string
					no
					A name for the operator. This is what is displayed in the select box

Comparator Object

List of the properties of the objects in the operators array

					Property Name
					Type
					Optional
					Description

						id

					Object
					no
					A unique indentifier of the comparator

						name

					string
					no
					A name for the comparator. This is what is displayed in the select box

						dataTemplate

					string
					yes
					String refering to a template that has been put into the $templateCache. Template can use the options of the field with 'rule.field.options' and needs to set 'rule.data' to an object or an array of objects with an id

						defaultData

					only when dataTemplate is used
					When using a dataTemplate the data will be initialized to this.

Settings Object

					Property Name
					Type
					Optional
					Description

						nesting

					boolean
					yes
					Enable or disable nesting

						addIconClass

					string
					yes
					The class of the span in the Add condition or group button

						removeIconClass

					string
					yes
					The class of the span in the Remove condition or group button

						addButtonClass

					string
					yes
					The class Add condition or group button

						removeButtonClass

					string
					yes
					The class Remove condition or group button

						onlyAllowFieldsOnce

					boolean
					yes
					When true a field can only be used in a query once

Full Service Documentation

The queryService is available for injection with 'queryService'

Methods

				asString(group)

				Converts the object that is returned by the directive to a string representation and uses id's where possible

				asReadable(group)

				Converts the object that is returned by the directive to a string representation and uses names where possible and spaces to keep it readable

				parseFromString(string, fields, operators, comparators)

				Converts a string outputted by asString back to an object using the fields, operators and comparators passed to the function.

Contributed by MyForce NV

This page was generated by GitHub Pages using the Architect theme by Jason Long.


text:
ACDSense Evaluation Data Service
===============================

The ACDSense Evaluation Data Service is a RESTful service for managing evaluation data in the ACDSense scenario, an IoT scenario based on the Extensible Messaging and Presence Protocol (XMPP). This document provides instructions on how to build and deploy the service from source.

Enabling Strong Encryption
-----------------------

The ACDSense Evaluation Data Service was developed on the LAS2peer Platform, a federated P2P service platform. LAS2peer requires end-to-end encryption for all communication between nodes in a P2P network. If you use an Oracle Java version, you have to enable strong encryption for LAS2peer (and the service) to operate correctly. With an Open JDK, this step is not needed.

- Download policy from Oracle: [JCE for Java 7](http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html "JCE-7")
- Extract files to `./lib/security/`, relative to your Java Runtime Environment (replacing the existing files).

Building the Service
-------------------------------------

For building the service you need a running Java SDK (both Oracle and Open JDK should work) and [Apache Ant](http://ant.apache.org/) >1.8.
With the above prerequisites met, change directory to the service's root directory and build the service with Ant.

    cd ${SERVICE_ROOT}
    ant all

The build process will resolve all dependencies to LAS2peer libraries and other third-party libraries using [Apache Ivy](https://ant.apache.org/ivy/). Besides compilation, running JUnit tests and generating JavaDocs the build process produces a set of initial cryptographic agent keys to be used for service operation in a directory ```./startup``` (see also section _LAS2peer Authentication_ later).

Deploying the Service
----------------------------------------

__Database Preparation & Configuration__

The ACDSense Evaluation Data Service makes use of a [mySQL](http://www.mysql.com/) database for data management. Thus, before deploying the service, a respective database must be created and added to the service's configuration.

1) Use the SQL script ```./doc/sql/database.schema.sql``` to create a database.

2) Configure database parameters in ```./config/i5.las2peer.services.acdsense.DataService.properties```.

__LAS2peer Start Script Configuration__

The service comes with a set of start scripts for starting a LAS2peer node (```./bin/start_network.bat``` for MS Win; ``` ./bin/start_network.sh``` for Unix), including the service and a Web Connector to make its RESTful API available to external callers outside the P2P network.

Per default, the following ports are used for communication:
- Port 9001 - LAS2peer P2P communication
- Port 8080 - RESTful service access via Web Connector

To change default configuration, change the start scripts accordingly.

Starting the Service
---
To start the service, simply run one of the LAS2peer start scripts mentioned above.

    ./bin/start_network.bat
    ./bin/start_network.sh

After successful launch of LAS2peer, you are directed to an interactive LAS2peer shell. Typing ```help``` provides information on interactive shell options. If you do not want to start LAS2peer in interactive mode, remove the start parameter ```interactive``` from the respective start script.

LAS2peer Authentication
---

Any connection to LAS2peer requires authentication with a numeric LAS2peer user identifier and a password.
During the build process, cryptographic keys for one example user agent "UserA" are generated with password "userAPass". You find the correct user id in the file ```./startup/agent-user-UserA.xml```.

For information on how to generate additional user agents, please refer to the LAS2peer Tutorial ["Add User Agents"](https://github.com/rwth-acis/LAS2peer-Tutorial-Project/wiki/Adding-User-Agents).


text:
package org.basex.query.util.collation;

import java.util.*;

import org.basex.query.*;
import org.basex.query.util.hash.*;
import org.basex.query.util.list.*;
import org.basex.query.value.item.*;
import org.basex.util.*;

/**
 * This set indexes items under the terms of a collation.
 *
 * @author BaseX Team 2005-15, BSD License
 * @author Christian Gruen
 */
public final class CollationItemSet implements ItemSet {
  /** Items. */
  private final ItemList items = new ItemList();
  /** Collation. */
  private final Collation coll;

  /**
   * Constructor.
   * @param coll collation
   */
  public CollationItemSet(final Collation coll) {
    this.coll = coll;
  }

  @Override
  public boolean add(final Item item, final InputInfo ii) throws QueryException {
    final int is = items.size();
    for(int id = 0; id < is; id++) {
      if(items.get(id).equiv(item, coll, ii)) return false;
    }
    items.add(item);
    return true;
  }

  @Override
  public Iterator<Item> iterator() {
    return items.iterator();
  }
}


text:
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace PrtgAPI.Utilities
{
    [ExcludeFromCodeCoverage]
    internal static class StringExtensions
    {
        public static string ForcePlural(this string str)
        {
            if (str.EndsWith("s")) //either "s" or "ies"
                return str;

            if (str.EndsWith("y"))
                return str.Substring(0, str.Length - 1) + "ies";

            return str + "s";
        }

        public static string Plural(this string str, int count)
        {
            if (count > 1 || count == 0)
                return str + "s";

            return str;
        }

        public static string Plural(this string str, IList list)
        {
            return Plural(str, list.Count);
        }

        public static string FromPlural(this string str)
        {
            if (str.EndsWith("s"))
                return str.Substring(0, str.Length - 1);

            return str;
        }

        public static string ToSentenceCase(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;

            return str[0].ToString().ToUpper() + str.Substring(1);
        }

        public static string EnsurePeriod(this string str)
        {
            if (str == null)
                return ".";

            if (str.EndsWith(".") || str.EndsWith("?") || str.EndsWith("!"))
                return str;

            return $"{str}.";
        }

        public static string ToQuotedList<T>(this IEnumerable<T> list)
        {
            if (list == null)
                return "''";

            return string.Join(", ", list.Select(l => $"'{l}'"));
        }

        public static string ToQuotedList(this object obj)
        {
            if (obj.IsIEnumerable())
                return obj.ToIEnumerable().ToQuotedList();

            return $"'{obj}'";
        }
    }
}


text:
<!--
  ~ Copyright (c) 2015, Nordic Semiconductor
  ~ All rights reserved.
  ~
  ~ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  ~
  ~ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  ~
  ~ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
  ~ documentation and/or other materials provided with the distribution.
  ~
  ~ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
  ~ software without specific prior written permission.
  ~
  ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  ~ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  ~ HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  ~ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  ~ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
  ~ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:orientation="vertical"
	tools:context=".HTSActivity">

	<com.github.mikephil.charting.charts.LineChart
		android:id="@+id/chart"
		android:layout_width="fill_parent"
		android:layout_centerInParent="true"
		android:layout_height="400dp" />

	<no.nordicsemi.android.nrftoolbox.widget.ForegroundRelativeLayout
		style="@style/HeaderShadow"
		android:layout_width="match_parent"
		android:layout_height="match_parent">
		<!-- The size of text below must be fixed, therefore dp are used instead of sp -->

		<no.nordicsemi.android.nrftoolbox.widget.TrebuchetTextView
			android:id="@+id/text_hts_value"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_centerHorizontal="true"
			android:layout_alignParentBottom="true"
			android:ellipsize="end"
			android:freezesText="true"
			android:maxLines="1"
			android:text="@string/not_available_value"
			android:textSize="80sp"/>

		<no.nordicsemi.android.nrftoolbox.widget.TrebuchetTextView
			android:id="@+id/text_hts_unit"
			android:layout_width="wrap_content"
			android:layout_height="wrap_content"
			android:layout_centerVertical="true"
			android:layout_alignParentBottom="true"
			android:layout_toRightOf="@id/text_hts_value"
			android:layout_marginBottom="25dp"
			android:text="@string/hts_unit_celsius"
			android:textSize="30sp"/>

	</no.nordicsemi.android.nrftoolbox.widget.ForegroundRelativeLayout>
</LinearLayout>


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using JoyOI.OnlineJudge.WebApi.Lib;

namespace JoyOI.OnlineJudge.WebApi.Controllers.ManagementServiceCallback
{
    [Route("management/[controller]")]
    public class HackController : BaseController
    {
        [HttpPost("stagechange/{id:Guid}")]
        public async Task<IActionResult> StageChange(
            [FromServices] HackStateMachineHandler handler,
            Guid id)
        {
            await handler.HandleHackResultAsync(id, default(CancellationToken));
            return Result(200, "ok");
        }
    }
}


text:
package org.keycloak.models.map.deploymentState;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.common.Profile;
import org.keycloak.common.Version;
import org.keycloak.common.util.Base64Url;
import org.keycloak.common.util.SecretGenerator;
import org.keycloak.migration.MigrationModel;
import org.keycloak.migration.ModelVersion;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.DeploymentStateProvider;
import org.keycloak.models.DeploymentStateProviderFactory;
import org.keycloak.models.DeploymentStateSpi;
import org.keycloak.provider.EnvironmentDependentProviderFactory;

public class MapDeploymentStateProviderFactory implements DeploymentStateProviderFactory, EnvironmentDependentProviderFactory {

    public static final String PROVIDER_ID = "map";

    private static final String RESOURCES_VERSION_SEED = "resourcesVersionSeed";

    @Override
    public DeploymentStateProvider create(KeycloakSession session) {
        return INSTANCE;
    }

    @Override
    public void init(Config.Scope config) {
        String seed = config.get(RESOURCES_VERSION_SEED);
        if (seed == null) {
            Logger.getLogger(DeploymentStateProviderFactory.class)
                    .warnf("It is recommended to set '%s' property in the %s provider config of %s SPI", RESOURCES_VERSION_SEED, PROVIDER_ID, DeploymentStateSpi.NAME);
            //generate random string for this installation
            seed = SecretGenerator.getInstance().randomString(10);
        }
        try {
            Version.RESOURCES_VERSION = Base64Url.encode(MessageDigest.getInstance("MD5")
                    .digest((seed + new ModelVersion(Version.VERSION_KEYCLOAK).toString()).getBytes()))
                    .substring(0, 5);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void postInit(KeycloakSessionFactory factory) {
    }

    @Override
    public String getId() {
        return PROVIDER_ID;
    }

    @Override
    public void close() {
    }

    @Override
    public boolean isSupported() {
        return Profile.isFeatureEnabled(Profile.Feature.MAP_STORAGE);
    }

    private static final DeploymentStateProvider INSTANCE =  new DeploymentStateProvider() {

        private final MigrationModel INSTANCE = new MigrationModel() {
            @Override
                public String getStoredVersion() {
                    return null;
                }
                @Override
                public String getResourcesTag() {
                    throw new UnsupportedOperationException("Not supported.");
                }
                @Override
                public void setStoredVersion(String version) {
                    throw new UnsupportedOperationException("Not supported.");
                }
        };

        @Override
        public MigrationModel getMigrationModel() {
            return INSTANCE;
        }

        @Override
        public void close() {
        }

    };
}


text:
package main

import (
	"flag"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"os"
	"regexp"
	"strconv"
	"time"
	"strings"
)

const (
	DefaultNumOfResultToShow = 3
)

type Time struct {
	hour, minute int
}

func (time *Time) toString() string {
	if time.minute < 10 {
		return fmt.Sprintf("%d:0%d ", time.hour, time.minute)
	} else {
		return fmt.Sprintf("%d:%d ", time.hour, time.minute)
	}
}

func (t1 *Time) isLaterThan(t2 Time) bool {
	return t1.hour > t2.hour || (t1.hour == t2.hour && t1.minute > t2.minute)
}

func departureTime(departure string) Time {
	ret, _ := regexp.MatchString("^[0-9]{1,2}:[0-9]{1,2}$", departure)
	var hour int
	var minute int
	if ret {
		re := regexp.MustCompile("^([0-9]{1,2}):([0-9]{1,2})$")
		bs := []byte(departure)
		group := re.FindSubmatch(bs)
		h, _ := strconv.Atoi(string(group[1]))
		m, _ := strconv.Atoi(string(group[2]))
		if h >= 0 && h < 24 && m >= 0 && m < 60 {
			hour = h
			minute = m
		} else {
			now := time.Now()
			hour = now.Hour()
			minute = now.Minute()
		}
	} else {
		now := time.Now()
		hour = now.Hour()
		minute = now.Minute()
	}
	return Time{hour, minute}
}

func getTimeTableUrl() string {
	weekday := time.Now().Weekday().String()
	if weekday == "Saturday" || weekday == "Sunday" {
		return "http://www.jreast-timetable.jp/2007/timetable/tt0413/0413021.html"
	} else {
		return "https://www.jreast-timetable.jp/2007/timetable/tt0413/0413020.html"
	}
}

func convertTimeToNumString(hour string) string {
	return strings.Replace(hour, "時", "", 1)
}

func createTimetable() []Time {
	var timetable = make([]Time, 0)
	url := getTimeTableUrl()
	doc, _ := goquery.NewDocument(url)
	doc.Find(".timetable .result_03").Each(func(_ int, s *goquery.Selection) {
		s.Find("tbody tr").Each(func(_ int, s *goquery.Selection) {
			key, err := strconv.Atoi(convertTimeToNumString(s.Find("td:nth-child(1)").Text()))
			if err == nil {
				s.Find("td:nth-child(2) div.timetable_time[data-dest='府']").Each(func(_ int, s *goquery.Selection) {
					value, _ := strconv.Atoi(s.Find(".minute").Text())
					timetable = append(timetable, Time{key, value})
				})
			}
		})
	})
	return timetable
}

func printTimes(times []string) {
	for _, v := range times {
		fmt.Println(v)
	}
}

func main() {
	var (
		departure   string
		numOfResult int
		isLast      bool
	)
	flag.StringVar(&departure, "t", "", "specify departure time.")
	flag.BoolVar(&isLast, "l", false, "show last bus of the day.")
	flag.IntVar(&numOfResult, "n", DefaultNumOfResultToShow, "specify amount of result.")
	flag.Parse()

	if numOfResult < 0 {
		fmt.Fprintf(os.Stderr, "parameter for -n must be greater than 0.\n")
		os.Exit(2)
	}

	departureTime := departureTime(departure)
	timetable := createTimetable()

	if isLast {
		result := []string{timetable[len(timetable)-1].toString()}
		printTimes(result)
		return
	}

	result := make([]string, 0, numOfResult)
	for i := 0; i < len(timetable); i++ {
		v := timetable[i]
		if v.isLaterThan(departureTime) {
			timeStr := v.toString()
			result = append(result, timeStr)
			if len(result) >= numOfResult {
				break
			}
		}
	}
	printTimes(result)
}


text:
var assert = require('assert'),
    pbkdf2Sha512 = require('./pbkdf2_sha512');

var KeyDerivation = {
    defaultIterations: 35000,
    subkeyIterations: 1,
    keySizeBits: 256
};

KeyDerivation.compute = function(pw, salt, iterations) {
    iterations = iterations || this.defaultIterations;
    assert(pw instanceof Buffer, 'Password must be provided as a Buffer');
    assert(salt instanceof Buffer, 'Salt must be provided as a Buffer');
    assert(salt.length > 0, 'Salt must not be empty');
    assert(typeof iterations === 'number', 'Iterations must be a number');
    assert(iterations > 0, 'Iteration count should be at least 1');

    if (salt.length > 0x80) {
        throw new Error('Sanity check: Invalid salt, length can never be greater than 128');
    }

    return pbkdf2Sha512.digest(pw, salt, iterations, this.keySizeBits / 8);
};

module.exports = KeyDerivation;


text:
# limivorous

 An implementation of the Observable pattern for simple Javascript
 data models. Yes, another implementation of Observable for
 Javascript.

**Why another Observable?**

There are lots of implementations of Observable for Javascript - why
right another one?

In part, as part of learning Javascript in a real project. And because
my needs for that project were quite simple, I wanted to work in bare
Javascript without pulling in a large framework. Many reactive
frameworks for Javascript bundle templating along with their data
modelling, and I wanted something simple that focused solely on the
data model and change events.

limivorous is intended to work with simple data model objects built
with the Javascript module pattern. The main requirements are:

* Support standard property get syntax, for compatibility with
  templating engines such as [handlebars](http://handlebarsjs.com/).
* Support a method chaining style or setting properties in addition to
  regular assignment.
* Don't require a browser

### Example

```javascript
var limivorous = require('limivorous')

Tag = function(data) {
  "use strict";

  var self = limivorous.observable()
                       .property('id')
                       .property('name')
                       .property('color', { init: 'red' } )
                       .build()

  /** Add any functions or other private storage */

  return self
}

t = Tag()
t.on('change:name', function(e) {
  console.log('Name changed from ' + e.previous + ' to ' + e.value)
})
```

## Licence & copyright

Limivorous is copyright © 2014 Adam Alpern and licenced under the
MIT licence. All rights not explicitly granted in the MIT license are
reserved. See the included LICENSE file for more details.


text:
<?php
/**
 * DefaultController.php
 *
 * @author    Timo M
 * @namespace Anticom\ShowcaseBundle\Controller
 * @package   Controller
 * @license   http://www.opensource.org/licenses/mit-license.php MIT
 */

namespace Anticom\ShowcaseBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

/**
 * Class DefaultController
 */
class DefaultController extends Controller {
    /**
     * Show static launch page
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function indexAction() {
        return $this->render('AnticomShowcaseBundle:Default:index.html.twig');
    }

    /**
     * Show static impress page
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function impressAction() {
        return $this->render('AnticomShowcaseBundle:Default:impress.html.twig');
    }

    /**
     * Show static contact page
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function contactAction() {
        return $this->render('AnticomShowcaseBundle:Default:contact.html.twig');
    }
}


text:
namespace co {
	class IModulePart; typedef co::RefPtr<IModulePart> IModulePartRef;
} // namespace co
// End Of Forward Declarations

// co.IModulePartLoader Mapping:
namespace co {

class IModulePartLoader : public co::IService
{
public:
	virtual ~IModulePartLoader() {;}

	virtual bool canLoadModulePart( const std::string& moduleName ) = 0;

	virtual co::IModulePart* loadModulePart( const std::string& moduleName ) = 0;
};

typedef co::RefPtr<IModulePartLoader> IModulePartLoaderRef;

} // namespace co

namespace co {
template<> struct kindOf<co::IModulePartLoader> : public kindOfBase<TK_INTERFACE> {};
template<> struct nameOf<co::IModulePartLoader> { static const char* get() { return "co.IModulePartLoader"; } };
} // namespace co

#endif // _CO_IMODULEPARTLOADER_H_


text:
function Get-DbaAgentJobOutputFile {
    <#
    .Synopsis
        Returns the Output File for each step of one or many agent job with the Job Names provided dynamically if
        required for one or more SQL Instances

    .DESCRIPTION
        This function returns for one or more SQL Instances the output file value for each step of one or many agent job with the Job Names
        provided dynamically. It will not return anything if there is no Output File

    .PARAMETER SqlInstance
        The target SQL Server instance or instances. This can be a collection and receive pipeline input to allow the function to be executed against multiple SQL Server instances.

    .PARAMETER SQLCredential
        Login to the target instance using alternative credentials. Accepts PowerShell credentials (Get-Credential).

        Windows Authentication, SQL Server Authentication, Active Directory - Password, and Active Directory - Integrated are all supported.

        For MFA support, please use Connect-DbaInstance. be it Windows or SQL Server. Windows users are determined by the existence of a backslash, so if you are intending to use an alternative Windows connection instead of a SQL login, ensure it contains a backslash.

    .PARAMETER Job
        The job(s) to process - this list is auto-populated from the server. If unspecified, all jobs will be processed.

    .PARAMETER ExcludeJob
        The job(s) to exclude - this list is auto-populated from the server

    .PARAMETER EnableException
        By default, when something goes wrong we try to catch it, interpret it and give you a friendly warning message.
        This avoids overwhelming you with "sea of red" exceptions, but is inconvenient because it basically disables advanced scripting.
        Using this switch turns this "nice by default" feature off and enables you to catch exceptions with your own try/catch.

    .NOTES
        Tags: Agent, Job
        Author: Rob Sewell (https://sqldbawithabeard.com) | Simone Bizzotto (@niphold)

        Website: https://dbatools.io
        Copyright: (c) 2018 by dbatools, licensed under MIT
        License: MIT https://opensource.org/licenses/MIT

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Job 'The Agent Job'

        This will return the configured paths to the output files for each of the job step of the The Agent Job Job
        on the SERVERNAME instance

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME

        This will return the configured paths to the output files for each of the job step of all the Agent Jobs
        on the SERVERNAME instance

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME,SERVERNAME2 -Job 'The Agent Job'

        This will return the configured paths to the output files for each of the job step of the The Agent Job Job
        on the SERVERNAME instance and SERVERNAME2

    .EXAMPLE
        $Servers = 'SERVER','SERVER\INSTANCE1'
        Get-DbaAgentJobOutputFile -SqlInstance $Servers -Job 'The Agent Job' -OpenFile

        This will return the configured paths to the output files for each of the job step of the The Agent Job Job
        on the SERVER instance and the SERVER\INSTANCE1 and open the files if they are available

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME  | Out-GridView

        This will return the configured paths to the output files for each of the job step of all the Agent Jobs
        on the SERVERNAME instance and Pipe them to Out-GridView

    .EXAMPLE
        PS C:\> (Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME | Out-GridView -PassThru).FileName | Invoke-Item

        This will return the configured paths to the output files for each of the job step of all the Agent Jobs
        on the SERVERNAME instance and Pipe them to Out-GridView and enable you to choose the output
        file and open it

    .EXAMPLE
        PS C:\> Get-DbaAgentJobOutputFile -SqlInstance SERVERNAME -Verbose

        This will return the configured paths to the output files for each of the job step of all the Agent Jobs
        on the SERVERNAME instance and also show the job steps without an output file

    #>
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory, HelpMessage = 'The SQL Server Instance',
            ValueFromPipeline,
            ValueFromPipelineByPropertyName,
            ValueFromRemainingArguments = $false,
            Position = 0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [DbaInstanceParameter[]]$SqlInstance,
        [Parameter(HelpMessage = 'SQL Credential',
            ValueFromPipelineByPropertyName,
            ValueFromRemainingArguments = $false,
            Position = 1)]
        [PSCredential]$SqlCredential,
        [object[]]$Job,
        [object[]]$ExcludeJob,
        [switch]$EnableException
    )

    process {
        foreach ($instance in $sqlinstance) {
            try {
                $server = Connect-SqlInstance -SqlInstance $instance -SqlCredential $SqlCredential
            } catch {
                Stop-Function -Message "Error occurred while establishing connection to $instance" -Category ConnectionError -ErrorRecord $_ -Target $instance -Continue
            }

            $jobs = $Server.JobServer.Jobs
            if ($Job) {
                $jobs = $jobs | Where-Object Name -In $Job
            }
            if ($ExcludeJob) {
                $jobs = $jobs | Where-Object Name -NotIn $ExcludeJob
            }
            foreach ($j in $Jobs) {
                foreach ($Step in $j.JobSteps) {
                    if ($Step.OutputFileName) {
                        [pscustomobject]@{
                            ComputerName         = $server.ComputerName
                            InstanceName         = $server.ServiceName
                            SqlInstance          = $server.DomainInstanceName
                            Job                  = $j.Name
                            JobStep              = $Step.Name
                            OutputFileName       = $Step.OutputFileName
                            RemoteOutputFileName = Join-AdminUNC $Server.ComputerName $Step.OutputFileName
                            StepId               = $Step.Id
                        } | Select-DefaultView -ExcludeProperty StepId
                    } else {
                        Write-Message -Level Verbose -Message "$step for $j has no output file"
                    }
                }
            }
        }
    }
}


text:
#ifndef ASYLO_TEST_GRPC_CLIENT_SIDE_AUTH_TEST_CONSTANTS_H_
#define ASYLO_TEST_GRPC_CLIENT_SIDE_AUTH_TEST_CONSTANTS_H_

#include <cstdint>

#include "asylo/identity/platform/sgx/sgx_identity.pb.h"
#include "asylo/util/statusor.h"

namespace asylo {

// Matches the client-side auth configuration in the BUILD file.
extern const uint32_t kClientSideAuthServerIsvprodid;
extern const uint32_t kClientSideAuthServerIsvsvn;

// Returns an SGX identity expectation that will match the identity for an
// enclave that uses the client-side auth test configuration and is signed with
// the Asylo debug key.
StatusOr<SgxIdentityExpectation> ClientSideAuthEnclaveSgxIdentityExpectation();

}  // namespace asylo
#endif  // ASYLO_TEST_GRPC_CLIENT_SIDE_AUTH_TEST_CONSTANTS_H_


text:
from heapq import heappush, heappop
from math import sqrt
import random
import json
import codecs
import time
from zort.environ import util

# even-r : 'pointy top'

__all__ = ['HexMapModel',
           'Cell',
           'evenr_to_axial',
           'axial_to_evenr',
           'pixel_to_axial',
           'sprites_to_axial',
           'axial_to_sprites',
           'sprites_to_hex',
           'collide_hex',
           'hex_round',
           'dist_axial',
           'dist_axial2']

ratio_13 = 1. / 3.
ratio_23 = 2. / 3.
ratio_32 = 3. / 2
sqrt_3 = sqrt(3)

# round axial coordinates
def hex_round(coords):
    x, y, z = axial_to_cube(coords)
    rx, ry, rz = [round(i, 0) for i in (x, y, z)]
    dx = abs(rx - x)
    dy = abs(ry - y)
    dz = abs(rz - z)
    if dx > dy and dx > dz:
        rx = -ry - rz
    elif dy > dz:
        ry = -rx - rz
    else:
        rz = -rx - ry
    assert (rx + ry + rz == 0)
    return cube_to_axial((rx, ry, rz))

def axial_to_pixel(coords, size):
    return size * sqrt_3 * (coords[0] - 0.5 * (coords[1] & 1)), \
           size * 3 / 2 * coords[1]

def pixel_to_axial(coords, size):
    x, y = [float(i) for i in coords[:2]]
    size = float(size)
    return (ratio_13 * sqrt_3 * x - ratio_13 * y) / size, ratio_32 * y / size

def axial_to_cube(coords):
    return coords[0], coords[1], -coords[0] - coords[1]

def cube_to_axial(coords):
    return coords[0], coords[1]

def axial_to_oddr(coords):
    # axial => cube
    x = coords[0]
    z = coords[1]
    # y = -x-z

    # cube => odd-r
    q = x + (z - (z & 1)) / 2
    r = z

    return q, r

def axial_to_evenr(coords):
    # axial => cube
    x = coords[0]
    z = coords[1]
    # y = -x-z

    # cube => evenr
    q = x + (z + (z & 1)) / 2
    # r = z

    return q, z

def oddr_to_axial(coords):
    # odd-r => cube
    q, r = coords
    qq = q - (r - (r & 1)) / 2
    rr = r
    return qq, rr

def evenr_to_axial(coords):
    # even-r => cube
    q, r = coords
    qq = q - (r + (r & 1)) / 2
    return qq, r

# special purpose function for sprites only
def sprites_to_axial(coords):
    x, y = coords[:2]
    # return int(ratio_13 * sqrt_3 * x - ratio_13 * y), int(ratio_23 * y)
    return ratio_13 * sqrt_3 * x - ratio_13 * y, ratio_23 * y

# special purpose function for sprites only
def axial_to_sprites(coords):
    q, r = coords[:2]
    return sqrt_3 * (q + r / 2.), ratio_32 * r

# special purpose function for sprites only
def sprites_to_hex(coords):
    return hex_round(sprites_to_axial(coords))

def cube_to_pixel(coords, radius):
    cx, cy, cz = coords
    y = ratio_32 * radius * cz
    # b = 2/3 * y / s
    #x = sqrt_3 * radius * (cz / 2. + cx)
    x = - sqrt_3 * radius * (cz / 2. + cy)
    #r = (sqrt(3)/3 * x - y/3 ) / s
    #g = -(sqrt(3)/3 * x + y/3 ) / s
    return x, y

# collision test for testing level geometry
def collide_hex(cell0, cell1, left_radius=1.0, right_radius=1.0):
    x0, y0 = cube_to_pixel(axial_to_cube(cell0), 1)
    x1, y1 = cube_to_pixel(axial_to_cube(cell1), 1)
    dx = x1 - x0
    dy = y1 - y0
    rr = left_radius + right_radius
    return (dx * dx) + (dy * dy) < rr * rr

# returns x and y
def dist_axial2(cell0, cell1):
    q0, r0 = cell0[:2]
    q1, r1 = cell1[:2]
    return abs(q0 - q1) + abs(r0 - r1), abs(q0 + r0 - q1 - r1) / 2

# returns x + y
def dist_axial(cell0, cell1):
    q0, r0 = cell0[:2]
    q1, r1 = cell1[:2]
    return (abs(q0 - q1) + abs(r0 - r1) +
            abs(q0 + r0 - q1 - r1)) / 2.0

class Cell(object):
    def __init__(self, **kwargs):
        self.cost = int(kwargs.get("cost", 0))
        self.filename = kwargs.get("filename", None)
        self.raised = kwargs.get("raised", False)
        self.height = float(kwargs.get("height", 0.0))

    def to_json(self):
        return {
            "cost": self.cost,
            "filename": self.filename,
            "raised": self.raised,
            "height": self.height
        }

class HexMapModel(object):
    def __init__(self):
        self._data = dict()
        self._width = None
        self._height = None
        self._dirty = False

    def surrounding(self, coords, avoid_raised=True):
        s = (coords for coords in util.surrounding_noclip(coords)
             if coords in self._data)
        return s if not avoid_raised else \
            (coords for coords in s if not self._data[coords].raised)

    def collidecircle(self, coords, radius):
        """test if circle overlaps level geometry above layer 0 only

        :param coords: axial coords
        :param radius: axial coords
        :return: list of coords
        """
        wall_offset = [0, .1]
        retval = list()
        round_coords = [int(i) for i in hex_round(coords)]
        neighbors = list(util.surrounding_noclip(round_coords))

        if not len(set(neighbors)) == 6:
            pass

        for n in neighbors:
            neigh = tuple([int(i) for i in n])
            cell = self._data.get(neigh, None)

            if cell is None:
                continue

            if not cell.raised:
                continue

            new = coords[0] - wall_offset[0], coords[1] - wall_offset[1]
            if collide_hex(new, neigh, radius, .9):
                retval.append(neigh)
        return retval

    def _make_file_data(self):
        return {
            "width": self._width,
            "height": self._height,
            "data": {str(key): value.to_json() for key, value in
                     self._data.items()}
        }

    def save_to_disk(self, path):
        with codecs.open(path, "wb", encoding="utf-8") as fob:
            data = self._make_file_data()
            json.dump(data, fob, indent=2)

    def load_from_disk(self, path):
        with codecs.open(path, "rb", encoding="utf-8") as fob:
            data = json.load(fob)
            self._width = data["width"]
            self._height = data["height"]
            self._data = dict()
            for key, cell_data in data["data"].items():
                self._data[eval(key)] = Cell(**cell_data)

    def get_cell(self, coords):
        return self._data.get(tuple(coords), None)

    def get_nearest_cell(self, coords):
        # expects coords in fractional axial coordinates
        return hex_round(coords)

    def add_cell(self, coords, cell):
        coords = tuple(coords)
        assert (len(coords) == 2)
        coords = tuple(int(i) for i in coords)
        self._data[coords] = cell
        self._trigger_bounds_update()

    def remove_cell(self, coords):
        del self._data[coords]
        self._trigger_bounds_update()

    def _trigger_bounds_update(self):
        self._width = None
        self._height = None
        self.quadtree = None

    def _calc_bounds(self):
        x_list = list()
        y_list = list()
        for cell in self._data.keys():
            x, y = axial_to_evenr(cell)
            x_list.append(x)
            y_list.append(y)

        if len(x_list):
            self._width = int(max(x_list) - min(x_list) + 1)
        else:
            self._width = 0

        if len(y_list):
            self._height = int(max(y_list) - min(y_list) + 1)
        else:
            self._height = 0

    @property
    def width(self):
        if self._width is None:
            self._calc_bounds()
        return self._width

    @property
    def height(self):
        if self._height is None:
            self._calc_bounds()
        return self._height

    @property
    def size(self):
        if self._height is None or self._width is None:
            self._calc_bounds()
        return self._width, self._height

    @property
    def cells(self):
        return self._data.items()

    @staticmethod
    def get_facing(cell, facing):
        return (cell[0] + util.neighbor_mat[facing],
                cell[1] + util.neighbor_mat[facing])

    @staticmethod
    def dist(cell0, cell1):
        q0, r0 = cell0
        q1, r1 = cell1
        return (abs(q0 - q1) + abs(r0 - r1) +
                abs(q0 + r0 - q1 - r1)) / 2.0

    def neighboring_radius(self, center, radius,
                           blacklist=set(), avoid_raised=True):
        neighbors = set()
        neighbors.add(center)
        for i in range(radius):
            tmp = set()
            for n in neighbors:
                tmp.update(set(self.surrounding(n, avoid_raised)))
            neighbors.update(tmp)

        neighbors.difference_update(blacklist)

        return neighbors

    def pathfind_evenr(self, current, end, blacklist=set(), avoid_raised=True):
        current = evenr_to_axial(current)
        end = evenr_to_axial(end)
        blacklist = {evenr_to_axial(coord) for coord in blacklist}
        return self.pathfind(current, end, blacklist, avoid_raised)

    def pathfind_ramble(self, current, home, radius, blacklist=set(),
                        avoid_raised=True):
        neighbors = self.neighboring_radius(home, radius, blacklist,
                                            avoid_raised)

        blacklist.update(
            {coord for coord in self._data})
        blacklist.difference_update(neighbors)
        return self.pathfind(current, random.choice(list(neighbors)), blacklist,
                             avoid_raised)

    def pathfind(self, current, end, blacklist=set(), avoid_raised=True):
        def cell_available(cell):
            return coord_available(cell[1])

        def coord_available(coord):
            return coord not in closed_set and coord not in blacklist

        def retrace_path(c):
            path = []
            while parent.get(c, None) is not None:
                c = parent[c]
                path.append(c)
            return list(reversed(path)) or None

        start_time = time.time()
        parent = {}
        open_heap = []
        open_set = set()
        closed_set = set()
        current = current[0], current[1]
        open_set.add(current)
        open_heap.append(current)
        while open_set:
            if time.time() - start_time > .0125:
                try:
                    return retrace_path(current), False
                except:
                    return None, True

            current = heappop(open_heap)

            if current == end:
                return retrace_path(current), True

            open_set.remove(current)
            closed_set.add(current)
            cells = filter(
                cell_available,
                ((self.dist(coord, end) + self.get_cell(coord).cost, coord)
                 for coord in self.surrounding(current, avoid_raised)))
            # Push the highest costing tiles first, so we'll check them last
            # Should keep working when there's a dead end
            for cell in cells:
                parent[cell[1]] = current
                if cell[1] not in open_set:
                    open_set.add(cell[1])
                    heappush(open_heap, cell[1])

        return None, True


text:
package org.apache.camel.parser.java;

import java.io.File;
import java.util.List;

import org.apache.camel.parser.ParserResult;
import org.apache.camel.parser.helper.CamelJavaParserHelper;
import org.jboss.forge.roaster.Roaster;
import org.jboss.forge.roaster.model.source.JavaClassSource;
import org.jboss.forge.roaster.model.source.MethodSource;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class RoasterConcatFieldRouteBuilderConfigureTest {

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

    @Test
    void parse() throws Exception {
        JavaClassSource clazz = (JavaClassSource) Roaster
                .parse(new File("src/test/java/org/apache/camel/parser/java/MyConcatFieldRouteBuilder.java"));
        MethodSource<JavaClassSource> method = clazz.getMethod("configure");

        List<ParserResult> list = CamelJavaParserHelper.parseCamelConsumerUris(method, true, true);
        for (ParserResult result : list) {
            LOG.info("Consumer: " + result.getElement());
        }
        assertEquals("ftp:localhost:{{ftpPort}}/myapp?password=admin&username=admin", list.get(0).getElement());

        list = CamelJavaParserHelper.parseCamelProducerUris(method, true, true);
        for (ParserResult result : list) {
            LOG.info("Producer: " + result.getElement());
        }
        assertEquals("log:b", list.get(0).getElement());
    }

}


text:
<img src="http://www.nerodesk.com/logo_large.png" width="384px" height="85px"/>

[![Made By Teamed.io](http://img.teamed.io/btn.svg)](http://www.teamed.io)
[![DevOps By Rultor.com](http://www.rultor.com/b/Nerodesk/nerodesk)](http://www.rultor.com/p/Nerodesk/nerodesk)

[![Build Status](https://travis-ci.org/Nerodesk/nerodesk.svg?branch=master)](https://travis-ci.org/Nerodesk/nerodesk)

Fast, Simple, Open-Source Cloud Storage.

[www.nerodesk.com](http://www.nerodesk.com)

To start application using default port use command line specified below:

```
$ mvn clean package
$ java -cp target/nerodesk.jar:target/deps/* com.nerodesk.Launch --port=8080
```
If you're on Windows:

```
java -cp target\nerodesk.jar;target\deps\* com.nerodesk.Launch --port=8080
```

## How to contribute

Fork repository, make changes, send us a pull request. We will review
your changes and apply them to the `master` branch shortly, provided
they don't violate our quality standards. To avoid frustration, before
sending us your pull request please run full Maven build:

```
$ mvn clean install -Pqulice,cobertura
```

Don't forget to set your default encoding to UTF-8. On Windows:

```
SET JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF-8
```

To avoid build errors use maven 3.2+. Minimum Java version is 1.7.

To start a web server locally run:

```
$ mvn clean integration-test -Phit-refresh -Dport=8080
```

If you have questions or general suggestions, don't hesitate to submit
a new [GitHub issue](https://github.com/nerodesk/nerodesk/issues/new).

## License & Copyright

Copyright (c) 2015, nerodesk.com. All rights reserved.

License information can be found [here](https://github.com/Nerodesk/nerodesk/blob/master/LICENSE.txt).