text:
title: Fun with AWS IoT Beta
date: 2015-10-16 12:00:00 Z
layout: post
subtitle: RasPi, NodeJS, and Python with the IoT Beta from AWS, a round the world
  doorbell.
author: Dan Ward
header-img: img/post-bg-01.jpg
---

tl;dr; code here https://github.com/dddanmar/aws-iot-raspberry-pi-button

AWS recently announced the Beta availability of their new platform for the Internet of Things.

The platform aims to be the communications broker between IoT devices and Amazon services such as Lambda, S3, DynamoDB and more.

Communication between devices is handled either via MQTT or their REST API.

SDKs are available for Embedded C and NodeJS.

Hardware packages are available from online retailers that are packaged specifically for AWS IoT, and recently it was announced Amazon were releasing a small set of Dash buttons with firmware intended to directly communicate with AWS IoT.

However, I'm not in a position to go out and buy any new gear at the moment, so I'm going to look at how to use the platform with both a Raspberry Pi and an ESP8266 stand alone Wi-Fi Module. Also, I'm not the biggest fan of NodeJS so I want to investigate how to subscribe to the MQTT feed with Python for some flexability.

The Raspberry Pi Button - Hardware

I've just had my wedding, and for a bit of maker flair I had built a small photobooth. It was nothing too fancy - a small wooden box purchased from the local arts store, a push button and an USB cabled Arduino were placed on the table for guests to push and take a photo.

The box is well over sized for the hardware that was used inside of it, and can easily fit a Rasperry Pi, USB battery pack, Wifi module, and of course, the button.

For the button, any momentary switch will do. For my uses I have used Pin7 as it's internal pullup is already defined in the onoff npm package we will use in the software. Less wires and resistors the better.

RpiButton, a box, a button, a RasPi, Wifi module and battery.

RpiButton, parts crammed into the box.

RpiButton, all sealed up.

The Raspberry Pi Button - Software

The Pi's button is driven from the NodeJS SDK supplied from AWS.

I'll admit I spent a fair bit of time trying to work out how to work with the SDK, and after some hair pulling I was found this lovely github repo from sreid. It contains some ready to go code samples, as well as a great README.md file to guide you through setting up a Thing in the IoT page on the Amazon console.

For the sender, using the npm module 'onoff' makes it very easy to read the GPIO status of a pin with NodeJS. All I needed to do here was put a new block at the bottom of the pi.js file from sreid's repository, and send that button state change off to AWS.

I've created a fork of the repo with my extra button code and pushed it up here.

You should be able to clone my repo, set up the device, download the certificates as sreid's README.md file describes, plug your switch into GPIO7 and GROUND, start the script and see the accept messages back from Amazon on each update.

{% gist 941c394d24631b54dbbc %}

That's it, you can set your NodeJS application to start on startup with something like node-startup, box it all up and turn the RpiButton on.

The Raspberry Pi Button - Python Receiver

Now the button itself is set up and posting data to Amazon, it's time to think of how this data can be consumed and used.

As I mentioned earlier, I'm not the biggest fan of NodeJS, so I was very keen to try out some Python to break free from the SDKs.

The main messaging system with AWS IoT is the nice and simple MQTT - this is a selection of topics you can subscribe to based on any event you want to listen to and react upon.

The event we want to listen in on is if the RpiButton's state has changed, and specifically if the button state is 0 (button is pushed down). The topics can be a bit confusing, the one we are interested in is the thing's shadow's accepted updates.

Topic: $aws/things/RpiButton/shadow/update/accepted

To find more topics available, check the listing in the IoT documentation.

Python has a fantastic MQTT library called Paho MQTT. Install it from pip and try the code below, updating the certificates and key to the path you have downloaded the files to previously.

{% gist 134a18c7e409fd5d47a1 %}

In my scenario, I have the github repo cloned on the Pi driving the button, and on my laptop to run the mqtt_client.py file.

If all goes well, you should push the button on the Pi, and a doorbell sound should play through the client machine.

We've made an IoT doorbell!

ESP8266 Button

Now I've got a bit of a better handle on the platform, it appears simple to interact with provided you can run an MQTT client on a device. The Rpi is too overpowered for the application is here, and it screams potential for the cheap WiFi module, the ESP8266.

Unfortunatley it looks like the two leading MQTT implementations for the ESP8266, esp_mqtt and ESPDuino both do not support client certificates, so we will look at Curl and in turn the ESP8266 with a RESTful request in the next blog post.


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mdrsolutions.util.sanitize;

/**
 *
 * @author michael.rodgers1
 */
public interface Sanitizable {
    /**
     * Sanitizable interface must be on Entity type objects that need to be
     * scanned with the Escape annotation. Implementing the Sanitizable interfaces
     * makes it easier to identify where to scan and not using reflection.
     *
     * Basically, DO NOT REMOVE implements Sanitizable from objects -- thanks!
     */
}

redpajama_set_name: RedPajamaGithub


text:
if [[ "$1" == "install" ]]; then
  useradd -g =uid -u 901 -s /bin/ksh -d /var/mailserv _mailserv
  echo "_mailserv   ALL=(ALL) NOPASSWD: SETENV: ALL" >> /etc/sudoers
fi

cd /var/mailserv/admin && chown -R _mailserv:_mailserv log db public tmp
cd /var/mailserv/admin/public && chown _mailserv:_mailserv javascripts stylesheets

cd /var/mailserv/account && chown -R _mailserv:_mailserv log public tmp
cd /var/mailserv/account/public && chown _mailserv:_mailserv javascripts stylesheets

#
# Making dovecot-lda deliver setuid root
# (needed for delivery to different userids)
#
touch /var/log/imap
chgrp _dovecot /usr/local/libexec/dovecot/dovecot-lda
chmod 4750 /usr/local/libexec/dovecot/dovecot-lda
mkdir /var/mailserv/mail >/dev/null 2>&1

#
# Create custom log files for log viewer admin interface
#
touch /var/log/imap_webmin
touch /var/log/maillog_webmin
touch /var/log/messages_webmin.log

chmod 644 /var/log/imap_webmin
chmod 644 /var/log/maillog_webmin
chmod 644 /var/log/messages_webmin.log


text:
<?xml version='1.0' encoding='UTF-8'?>
<Document>
  <Header>
    <SchemaName>Location</SchemaName>
    <Identifier>location_geonames_6509004</Identifier>
    <DocumentState>public</DocumentState>
    <TimeStamp>1390753462448</TimeStamp>
    <SummaryFields>
      <Title>NL > North Brabant > Novotel Breda</Title>
    </SummaryFields>
  </Header>
  <Body>
    <Location>
      <GeopoliticalHierarchy>NL,North Brabant,Novotel Breda</GeopoliticalHierarchy>
      <LocationName>
        <Appelation>Novotel Breda</Appelation>
        <LocationNameType>hotel</LocationNameType>
        <Comments></Comments>
      </LocationName>
      <Coordinates>
        <Longitude>4.7452</Longitude>
        <Latitude>51.5666</Latitude>
      </Coordinates>
      <GeonamesURI>http://www.geonames.org/6509004</GeonamesURI>
      <WikipediaLink/>
      <DbpediaLink/>
    </Location>
  </Body>
</Document>


text:
package com.cloud.network.dao;

import java.util.List;

import com.cloud.utils.db.GenericDao;

public interface AccountGuestVlanMapDao extends GenericDao<AccountGuestVlanMapVO, Long> {

    public List<AccountGuestVlanMapVO> listAccountGuestVlanMapsByAccount(long accountId);

    public List<AccountGuestVlanMapVO> listAccountGuestVlanMapsByVlan(long guestVlanId);

    public List<AccountGuestVlanMapVO> listAccountGuestVlanMapsByPhysicalNetwork(long physicalNetworkId);

    public int removeByAccountId(long accountId);

}


text:
import os
import sys

# Add parent folder to sys.path, so we can import boot.
# App Engine causes main.py to be reloaded if an exception gets raised
# on the first request of a main.py instance, so don't add project_dir multiple
# times.
project_dir = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
if project_dir not in sys.path or sys.path.index(project_dir) > 0:
    while project_dir in sys.path:
        sys.path.remove(project_dir)
    sys.path.insert(0, project_dir)

for path in sys.path[:]:
    if path != project_dir and os.path.isdir(os.path.join(path, 'django')):
        sys.path.remove(path)
        break

# Remove the standard version of Django.
if 'django' in sys.modules and sys.modules['django'].VERSION < (1, 2):
    for k in [k for k in sys.modules
              if k.startswith('django\.') or k == 'django']:
        del sys.modules[k]

from djangoappengine.boot import setup_env, setup_logging, env_ext
setup_env()

from django.core.handlers.wsgi import WSGIHandler
from google.appengine.ext.webapp.util import run_wsgi_app
from django.conf import settings

def log_traceback(*args, **kwargs):
    import logging
    logging.exception('Exception in request:')

from django.core import signals
signals.got_request_exception.connect(log_traceback)

def real_main():
    # Reset path and environment variables
    global path_backup
    try:
        sys.path = path_backup[:]
    except:
        path_backup = sys.path[:]
    os.environ.update(env_ext)
    setup_logging()

    # Create a Django application for WSGI.
    application = WSGIHandler()

    # Run the WSGI CGI handler with that application.
    run_wsgi_app(application)

def profile_main():
    import logging, cProfile, pstats, random, StringIO
    only_forced_profile = getattr(settings, 'ONLY_FORCED_PROFILE', False)
    profile_percentage = getattr(settings, 'PROFILE_PERCENTAGE', None)
    if (only_forced_profile and
                'profile=forced' not in os.environ.get('QUERY_STRING')) or \
            (not only_forced_profile and profile_percentage and
                float(profile_percentage) / 100.0 <= random.random()):
        return real_main()

    prof = cProfile.Profile()
    prof = prof.runctx('real_main()', globals(), locals())
    stream = StringIO.StringIO()
    stats = pstats.Stats(prof, stream=stream)
    sort_by = getattr(settings, 'SORT_PROFILE_RESULTS_BY', 'time')
    if not isinstance(sort_by, (list, tuple)):
        sort_by = (sort_by,)
    stats.sort_stats(*sort_by)

    restrictions = []
    profile_pattern = getattr(settings, 'PROFILE_PATTERN', None)
    if profile_pattern:
        restrictions.append(profile_pattern)
    max_results = getattr(settings, 'MAX_PROFILE_RESULTS', 80)
    if max_results and max_results != 'all':
        restrictions.append(max_results)
    stats.print_stats(*restrictions)
    extra_output = getattr(settings, 'EXTRA_PROFILE_OUTPUT', None) or ()
    if not isinstance(sort_by, (list, tuple)):
        extra_output = (extra_output,)
    if 'callees' in extra_output:
        stats.print_callees()
    if 'callers' in extra_output:
        stats.print_callers()
    logging.info('Profile data:\n%s', stream.getvalue())

main = getattr(settings, 'ENABLE_PROFILER', False) and profile_main or real_main

if __name__ == '__main__':
    main()


text:
/**
 * This class is generated by jOOQ
 */
package us.fok.lenzenslijper.models.jooq.routines;

/**
 * This class is generated by jOOQ.
 */
@javax.annotation.Generated(value    = { "http://www.jooq.org", "3.3.0" },
                            comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ProcessLinkForSubmission extends org.jooq.impl.AbstractRoutine<java.lang.Void> {

	private static final long serialVersionUID = -1820598684;

	/**
	 * The parameter public.process_link_for_submission._revision_link.
	 */
	public static final org.jooq.Parameter<java.lang.Object> _REVISION_LINK = createParameter("_revision_link", org.jooq.impl.DefaultDataType.getDefaultDataType("USER-DEFINED"));

	/**
	 * The parameter public.process_link_for_submission._revision_summary.
	 */
	public static final org.jooq.Parameter<us.fok.lenzenslijper.models.jooq.udt.records.RevisionSummaryRecord> _REVISION_SUMMARY = createParameter("_revision_summary", us.fok.lenzenslijper.models.jooq.udt.RevisionSummary.REVISION_SUMMARY.getDataType());

	/**
	 * Create a new routine call instance
	 */
	public ProcessLinkForSubmission() {
		super("process_link_for_submission", us.fok.lenzenslijper.models.jooq.Public.PUBLIC);

		addInParameter(_REVISION_LINK);
		addInParameter(_REVISION_SUMMARY);
	}

	/**
	 * Set the _revision_link parameter IN value to the routine
	 */
	public void set_RevisionLink(java.lang.Object value) {
		setValue(us.fok.lenzenslijper.models.jooq.routines.ProcessLinkForSubmission._REVISION_LINK, value);
	}

	/**
	 * Set the _revision_summary parameter IN value to the routine
	 */
	public void set_RevisionSummary(us.fok.lenzenslijper.models.jooq.udt.records.RevisionSummaryRecord value) {
		setValue(us.fok.lenzenslijper.models.jooq.routines.ProcessLinkForSubmission._REVISION_SUMMARY, value);
	}
}


text:
About Modern Business

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed voluptate nihil eum consectetur similique? Consectetur, quod, incidunt, harum nisi dolores delectus reprehenderit voluptatem perferendis dicta dolorem non blanditiis ex fugiat.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe, magni, aperiam vitae illum voluptatum aut sequi impedit non velit ab ea pariatur sint quidem corporis eveniet. Odit, temporibus reprehenderit dolorum!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, consequuntur, modi mollitia corporis ipsa voluptate corrupti eum ratione ex ea praesentium quibusdam? Aut, in eum facere corrupti necessitatibus perspiciatis quis?


text:
namespace sandbox {

class BrokerServices;
class PolicyDiagnosticsReceiver;
class ProcessState;
class TargetPolicy;
class TargetServices;

// BrokerServices exposes all the broker API.
// The basic use is to start the target(s) and wait for them to end.
//
// This API is intended to be called in the following order
// (error checking omitted):
//  BrokerServices* broker = SandboxFactory::GetBrokerServices();
//  broker->Init();
//  PROCESS_INFORMATION target;
//  broker->SpawnTarget(target_exe_path, target_args, &target);
//  ::ResumeThread(target->hThread);
//  // -- later you can call:
//  broker->WaitForAllTargets(option);
//
class BrokerServices {
 public:
  // Initializes the broker. Must be called before any other on this class.
  // returns ALL_OK if successful. All other return values imply failure.
  // If the return is ERROR_GENERIC, you can call ::GetLastError() to get
  // more information.
  virtual ResultCode Init() = 0;

  // Returns the interface pointer to a new, empty policy object. Use this
  // interface to specify the sandbox policy for new processes created by
  // SpawnTarget()
  virtual scoped_refptr<TargetPolicy> CreatePolicy() = 0;

  // Creates a new target (child process) in a suspended state.
  // Parameters:
  //   exe_path: This is the full path to the target binary. This parameter
  //   can be null and in this case the exe path must be the first argument
  //   of the command_line.
  //   command_line: The arguments to be passed as command line to the new
  //   process. This can be null if the exe_path parameter is not null.
  //   policy: This is the pointer to the policy object for the sandbox to
  //   be created.
  //   last_warning: The argument will contain an indication on whether
  //   the process security was initialized completely, Only set if the
  //   process can be used without a serious compromise in security.
  //   last_error: If an error or warning is returned from this method this
  //   parameter will hold the last Win32 error value.
  //   target: returns the resulting target process information such as process
  //   handle and PID just as if CreateProcess() had been called. The caller is
  //   responsible for closing the handles returned in this structure.
  // Returns:
  //   ALL_OK if successful. All other return values imply failure.
  virtual ResultCode SpawnTarget(const wchar_t* exe_path,
                                 const wchar_t* command_line,
                                 scoped_refptr<TargetPolicy> policy,
                                 ResultCode* last_warning,
                                 DWORD* last_error,
                                 PROCESS_INFORMATION* target) = 0;

  // This call blocks (waits) for all the targets to terminate.
  // Returns:
  //   ALL_OK if successful. All other return values imply failure.
  //   If the return is ERROR_GENERIC, you can call ::GetLastError() to get
  //   more information.
  virtual ResultCode WaitForAllTargets() = 0;

  // This call creates a snapshot of policies managed by the sandbox and
  // returns them via a helper class.
  // Parameters:
  //   receiver: The |PolicyDiagnosticsReceiver| implementation will be
  //   called to accept the results of the call.
  // Returns:
  //   ALL_OK if the request was dispatched. All other return values
  //   imply failure, and the responder will not receive its completion
  //   callback.
  virtual ResultCode GetPolicyDiagnostics(
      std::unique_ptr<PolicyDiagnosticsReceiver> receiver) = 0;

 protected:
  ~BrokerServices() {}
};

// TargetServices models the current process from the perspective
// of a target process. To obtain a pointer to it use
// Sandbox::GetTargetServices(). Note that this call returns a non-null
// pointer only if this process is in fact a target. A process is a target
// only if the process was spawned by a call to BrokerServices::SpawnTarget().
//
// This API allows the target to gain access to resources with a high
// privilege token and then when it is ready to perform dangerous activities
// (such as download content from the web) it can lower its token and
// enter into locked-down (sandbox) mode.
// The typical usage is as follows:
//
//   TargetServices* target_services = Sandbox::GetTargetServices();
//   if (target_services) {
//     // We are the target.
//     target_services->Init();
//     // Do work that requires high privileges here.
//     // ....
//     // When ready to enter lock-down mode call LowerToken:
//     target_services->LowerToken();
//   }
//
// For more information see the BrokerServices API documentation.
class TargetServices {
 public:
  // Initializes the target. Must call this function before any other.
  // returns ALL_OK if successful. All other return values imply failure.
  // If the return is ERROR_GENERIC, you can call ::GetLastError() to get
  // more information.
  virtual ResultCode Init() = 0;

  // Discards the impersonation token and uses the lower token, call before
  // processing any untrusted data or running third-party code. If this call
  // fails the current process could be terminated immediately.
  virtual void LowerToken() = 0;

  // Returns the ProcessState object. Through that object it's possible to have
  // information about the current state of the process, such as whether
  // LowerToken has been called or not.
  virtual ProcessState* GetState() = 0;

 protected:
  ~TargetServices() {}
};

class PolicyInfo {
 public:
  // Returns a JSON representation of the policy snapshot.
  // This pointer has the same lifetime as this PolicyInfo object.
  virtual const char* JsonString() = 0;
  virtual ~PolicyInfo() {}
};

// This is returned by BrokerServices::GetPolicyDiagnostics().
// PolicyInfo entries need not be ordered.
class PolicyList {
 public:
  virtual std::vector<std::unique_ptr<PolicyInfo>>::iterator begin() = 0;
  virtual std::vector<std::unique_ptr<PolicyInfo>>::iterator end() = 0;
  virtual size_t size() const = 0;
  virtual ~PolicyList() {}
};

// This class mediates calls to BrokerServices::GetPolicyDiagnostics().
class PolicyDiagnosticsReceiver {
 public:
  // ReceiveDiagnostics() should return quickly and should not block the
  // thread on which it is called.
  virtual void ReceiveDiagnostics(std::unique_ptr<PolicyList> policies) = 0;
  // OnError() is passed any errors encountered and |ReceiveDiagnostics|
  // will not be called.
  virtual void OnError(ResultCode code) = 0;
  virtual ~PolicyDiagnosticsReceiver() {}
};

}  // namespace sandbox

#endif  // SANDBOX_WIN_SRC_SANDBOX_H_


text:
'use babel'
'use strict'

const {Emitter} = require('atom')

var ServiceProvider = function ServiceProvider () {}

var providers = new Map()
var currentProvider
var emitter = new Emitter()

ServiceProvider.prototype.addProvider = function (provider) {
  providers.set(provider.name, provider)
}

ServiceProvider.prototype.removeAll = function () {
  providers.clear()
}

ServiceProvider.prototype.currentProvider = function () {
  return currentProvider
}

ServiceProvider.prototype.setCurrentProvider = function (provider) {
  currentProvider = provider
  emitter.emit('did-change-provider', provider)
}

ServiceProvider.prototype.observeProvider = function (callback) {
  emitter.on('did-change-provider', (provider) => {
    callback(provider)
  })

  if (currentProvider) {
    callback(currentProvider)
  }
}

ServiceProvider.prototype.get = function (name) {
  return providers.get(name)
}

ServiceProvider.prototype.destroy = function () {
  emitter.dispose()
}

module.exports = new ServiceProvider()


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE90_LDAP_Injection__w32_char_listen_socket_72b.cpp
Label Definition File: CWE90_LDAP_Injection__w32.label.xml
Template File: sources-sink-72b.tmpl.cpp
*/
/*
 * @description
 * CWE: 90 LDAP Injection
 * BadSource: listen_socket Read data using a listen socket (server side)
 * GoodSource: Use a fixed string
 * Sinks:
 *    BadSink : data concatenated into LDAP search, which could result in LDAP Injection
 * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
 *
 * */

#include "std_testcase.h"
#include <vector>

#include <windows.h>
#include <Winldap.h>

#pragma comment(lib, "wldap32")

using namespace std;

namespace CWE90_LDAP_Injection__w32_char_listen_socket_72
{

#ifndef OMITBAD

void badSink(vector<char *> dataVector)
{
    /* copy data out of dataVector */
    char * data = dataVector[2];
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        char filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snprintf(filter, 256-1, "(cn=%s)", data);
        pLdapConnection = ldap_initA("localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sA(
                            pLdapConnection,
                            "base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<char *> dataVector)
{
    char * data = dataVector[2];
    {
        LDAP* pLdapConnection = NULL;
        ULONG connectSuccess = 0L;
        ULONG searchSuccess = 0L;
        LDAPMessage *pMessage = NULL;
        char filter[256];
        /* POTENTIAL FLAW: data concatenated into LDAP search, which could result in LDAP Injection*/
        _snprintf(filter, 256-1, "(cn=%s)", data);
        pLdapConnection = ldap_initA("localhost", LDAP_PORT);
        if (pLdapConnection == NULL)
        {
            printLine("Initialization failed");
            exit(1);
        }
        connectSuccess = ldap_connect(pLdapConnection, NULL);
        if (connectSuccess != LDAP_SUCCESS)
        {
            printLine("Connection failed");
            exit(1);
        }
        searchSuccess = ldap_search_ext_sA(
                            pLdapConnection,
                            "base",
                            LDAP_SCOPE_SUBTREE,
                            filter,
                            NULL,
                            0,
                            NULL,
                            NULL,
                            LDAP_NO_LIMIT,
                            LDAP_NO_LIMIT,
                            &pMessage);
        if (searchSuccess != LDAP_SUCCESS)
        {
            printLine("Search failed");
            if (pMessage != NULL)
            {
                ldap_msgfree(pMessage);
            }
            exit(1);
        }
        /* Typically you would do something with the search results, but this is a test case and we can ignore them */
        /* Free the results to avoid incidentals */
        if (pMessage != NULL)
        {
            ldap_msgfree(pMessage);
        }
        /* Close the connection */
        ldap_unbind(pLdapConnection);
    }
}

#endif /* OMITGOOD */

} /* close namespace */


text:
import builder from 'focus-core/component/builder';
import types from 'focus-core/component/types';
const React = require('react');
const Checkbox = require('../../../components/input/checkbox');
const i18nBehaviour = require('../../i18n/mixin');
const {pull} = require('lodash/array');

const selectCheckboxMixin = {
    mixins: [i18nBehaviour],
    /**
    * Tag name.
    */
    displayName: 'SelectCheckbox',

    /** @inheritdoc */
    getDefaultProps() {
        return {
            values: [], // all values
            value: [], // selected values list
            valueKey: 'value', // key for the displayed value
            labelKey: 'label' // key for the displayed label
        };
    },
    /** @inheritdoc */
    propTypes() {
        return {
            values: types('array'),
            value: types('array'),
            valueKey: types('string'),
            labelKey: types('string'),
            onChange: types('func')
        };
    },

    /** @inheritdoc */
    getInitialState() {
        return {
            selectedValues: this.props.value
        };
    },

    componentWillMount() {
        console.warn('FocusComponents v0.15: the \'select-checkbox\' component from FocusComponents.common is deprecated, please use FocusComponents.components.select.SelectCheckbox');
    },

    /** @inheritdoc */
    componentWillReceiveProps(newProps) {
        if(newProps) {
            this.setState({selectedValues: newProps.value});
        }
    },

    /**
    * Get the value from the select in the DOM.
    * @return {string} value
    */
    getValue() {
        return this.state.selectedValues;
    },

    /**
     * Handle a change of value.
     * @param  {[type]} key       the key
     * @param  {[type]} newStatus the new status
     */
    _handleCheckboxChange(key, newStatus) {
        if(this.props.onChange) {
            this.props.onChange(key, newStatus);
            return;
        }
        const selectedValues = this.state.selectedValues;
        if(newStatus) {
            selectedValues.push(key);
        } else {
            pull(selectedValues, key);
        }
        this.setState({value: selectedValues});
    },
    /**
     * Closure to capture key and checbox status.
     * @param  {[type]} key the key of checkbox
     * @return {[type]} status closure
     */
    _getCheckboxChangeHandler(key) {
        return (status) => {
            this._handleCheckboxChange(key, status);
        };
    },
    /**
     * Render all selection checkbox.
     * @return {ReactDOMNode} list of ReactDomNode
     */
    renderCheckboxes() {
        return this.props.values.map((val, idx) => {
            const value = val[this.props.valueKey];
            const label = val[this.props.labelKey];
            const isChecked = 0 <= this.state.selectedValues.indexOf(value);
            return (
                <Checkbox key={idx} label={this.i18n(label)} onChange={this._getCheckboxChangeHandler(value)} value={isChecked} />
            );
        });
    },

    /** @inheritdoc */
    render() {
        return (
            <div data-focus='select-checkbox'>
                {this.renderCheckboxes()}
            </div>
        );
    }
};

module.exports = builder(selectCheckboxMixin);


text:
/*
 Theme Name:   Open Media
 Description:  Open Media Foundation Theme based on Twenty Thirteen
 Author:       Dimitar Dimitrov
 Author URI:   http://openmedia.bg
 Template:     twentythirteen
 Version:      1.0.0
 Text Domain:  open-media
*/

@import url("../twentythirteen/style.css");

body.home .entry-title {
	color: #555;
}

body.home .entry-content h2 {
	text-align: center;
	font-weight: normal;
}

body.home .entry-content h4 {
	text-align: center;
}

body.home .entry-content h3, h4, h5 {
	font-weight: normal;
}

.site-logo img {
	Border: 5px solid;
}

.site {
	max-width: none;
	border-style: none;
}

.page h1.entry-title {
	margin-top: 10px;
	font-size: 3em;
}

.site-header .home-link {
	display: none;
}

h1, h2, h3, h4, h5, h6 {
	font-family: Myriad Pro, Helvetica, Verdana, Sans-serif;
}

.su-button-style-flat span {
	font-family: Myriad Pro, Helvetika, Verdana, sans-serif;
}

body {
	font-family: Myriad Sans, Helvetica, Verdana sans-serif;
}

.navbar {
	background-color: #f3f3f3;
	max-width: none;
}

.nav-menu .current_page_item > a,
.nav-menu .current_page_ancestor > a,
.nav-menu .current-menu-item > a,
.nav-menu .current-menu-ancestor > a {
	color: #000;
	font-weight: normal;
	font-style: normal;
	background-color: #fff;
}

.nav-menu li:hover > a,
.nav-menu li a:hover {
	background-color: #fff;
	color: #000;
}

.main-navigation,
.entry-header,
.entry-content,
.entry-summary,
.entry-meta,
.site-footer .sidebar-container {
	max-width: 750px;
}

ul.nav-menu,
div.nav-menu > ul {
	margin: 0 0 0 -20px;
}

#post-2 > header > h1 {
	text-align: center;
}

a,
.entry-meta a,
.site-footer .widget a,
.entry-content a,
.comment-content a {
	color: #039FB0;
}

.entry-content a:hover,
.comment-content a:hover,
.entry-meta a:hover {
	color: #039FB0;
}

input[type="submit"], input[type="button"], input[type="reset"] {
	background: linear-gradient(to bottom,#039FB0 0%,#039FB0 100%);
	border: none;
	border-bottom: 3px solid #037480;
}

button:hover, button:focus, input[type="submit"]:hover, input[type="button"]:hover, input[type="reset"]:hover, input[type="submit"]:focus, input[type="button"]:focus, input[type="reset"]:focus {
	background: linear-gradient(to bottom,#039FB0 0%,#037480 100%);
}

.entry-title a:hover {
	color: #037480;
}

.site-footer {
	background-color: #303033;
	padding: 50px 0 30px 0;
}

.site-footer .sidebar-container {
	background: none;
	margin: 0 auto;
	padding: 0;
}

.site-footer .widget-area {
	padding: 0;
	margin-right: -30px;
	width: auto;
	max-width: none;
}

.site-footer .widget {
	padding: 0;
	width: 220px;
	margin: 0 30px 30px 0;
}

.widget .widget-title {
	font-style: normal;
}

.site-footer .widget .widget-title {
	color: #666;
}

/* MailChimp join form */
.mc4wp-form {
	margin: 20px 0;
}

.join-form {
	max-width: 600px;
	margin: 0 auto;
}

.mc4wp-form .join-form input.email {
	display: inline-block;
	width: 60%;
	padding: 10px 15px;
}

.mc4wp-form .join-form input.submit {
	display: inline-block;
	width: 36%;
}


text:
// [START earthengine__apidocs__ee_geometry_multilinestring_withindistance]
// Define a MultiLineString object.
var multiLineString = ee.Geometry.MultiLineString(
   [[[-122.088, 37.418], [-122.086, 37.422], [-122.082, 37.418]],
    [[-122.087, 37.416], [-122.083, 37.416], [-122.082, 37.419]]]);

// Define other inputs.
var inputGeom = ee.Geometry.Point(-122.090, 37.423);

// Apply the withinDistance method to the MultiLineString object.
var multiLineStringWithinDistance = multiLineString.withinDistance({'right': inputGeom, 'distance': 500, 'maxError': 1});

// Print the result to the console.
print('multiLineString.withinDistance(...) =', multiLineStringWithinDistance);

// Display relevant geometries on the map.
Map.setCenter(-122.085, 37.422, 15);
Map.addLayer(multiLineString,
             {'color': 'black'},
             'Geometry [black]: multiLineString');
Map.addLayer(inputGeom,
             {'color': 'blue'},
             'Parameter [blue]: inputGeom');
// [END earthengine__apidocs__ee_geometry_multilinestring_withindistance]


text:
function fe = feSet(fe,param,val,varargin)
% Set fascicle evaluation parameters.
%
%   fe = feSet(fe,param,val,varargin)
%
%----------
% feSet(fe,'bvecsindices');
%----------
% Set the a second diffusion signla measuremnt (repeat).
% Image_vals is the image array with the dwi signal taken from all the
% voxels in the new dataset the fe.roi
% fe = feSet(fe,'diffusion signal repeat',image_vals);
%----------
% Set the the s0 (no diffusion direction measurement) for a second
% diffusion signla measuremnt (repeat).
% Image_vals is the image array with the dwi signal taken from all the
% voxels in the new dataset the fe.roi
% fe = feSet(fe,'b0signalrepeat',image_vals);
%----------
%
%
% Copyright (2013-2015), Franco Pestilli, Stanford University, pestillifranco@gmail.com.

% Check for input parameters
if notDefined('fe'),    error('fe structure required'); end
if notDefined('param'), error('param required'); end
% if ~exist('val','var'), error('Value required'); end
% This is better.  Let's see if much breaks (BW).
if ~exist('val','var'), val = []; end

% Squeeze out spaces and force lower case
param = mrvParamFormat(param);

%%
switch param
  % Book-keeping
  case 'name'
    fe.name  = val;        % This one's name
  case 'type'
    fe.type  = 'faseval'; % Always fascicle evaluation
  case 'savedir'
    fe.path.savedir  = val; % Always fascicle evaluation

    % Set top level structure, not just single slot
  case 'life'
    fe  = val;  % Structure of parameters and results from LIFE analysis

  case 'fgfromacpc'
    % Fiber group representing the candidate connectome.
    % Everything is in IMAGE coordinates (not in ACPC) in the FE structure.
    % Here we make this assumption.

    % If it is a string we assume thisis a file name for a fiber group.
    % We load the fiber group from file.
    if ischar(val) && exist(val,'file')
       [p,n]  = fileparts(val);
       val    = fgRead(val);

    elseif isstruct(val) && isfield(val,'fibers')
    % We do nothing beside assuming that the fiber group
    % is passed in ACPC coordinates as default in mrDiffusion

    else error('[%s] incorrect val parameter %s.',mfilename, val);
    end

    % If a fiber group structure was passed in instead
    % we assume that it was passed in in AC-PC coordinates
    % (the default in mrDiffusion) we trasform  in IMAGE coordinates
    val = dtiXformFiberCoords(val, fe.xform.acpc2img,'img');

    % Finally we set the fiber group in the FE structure in IMAGE coordinates
    fe  = feSet(fe,'fg',val);

    % Must clear the fields associated with the fiber group every time a new FG is set.
    fe = feSet(fe,'voxel 2 fiber node pairs',[]);

  case {'fgimg', 'fg'}
    % Fiber group candidate fascicles, Connectome.
    % Everything is in img coordinates in LiFE
    %
    fe.fg  = val;
    % Must clear when we change the fg
    fe = feSet(fe,'voxel 2 fiber node pairs',[]);

  case {'fgtensors','tensors','fgq','q'}
    % fe = feSet(fe, 'tensors', tensors);    - set the passed tensors
    fe.fibers.tensors = val;

  case 'roi'
    % Cell array of regions of interest where we evaluate
    % Must clear v2fnp
    fe.roi   = val;
    fe       = feSet(fe,'v2fnp',[]);

  case {'roifromfg','fgroi','roifg'}
      % This is not really a set.  It doesn't rely on val.  So nothing is
      % set to val.
      %
      % It probably shouldn't be in this function, or what should be in
      % this function is a real set that forces val to contains the roi
      % coords.  Or the the whole roi.  The fragment below would make
      % sense. (BW)
      %
      %   c = feGet(fe,'img all fg coords')
      %   fe = feSet(fe,'roi fg',c)
      %
      % As it stands this always creates an ROI that has all of
      % the unique image coords from the fibers in the fe structure.

      name   = sprintf('roi_%s', fe.fg.name);
      randColor = rand(1,3);
      fe.roi = dtiNewRoi(name,randColor,fefgGet(feGet(fe,'fg img'),'unique image coords'));

  case 'xform'
    fe.xform = val;  % Transforms between coords for fg, roi, and dwi data

  %% Diffusion data related parameters
  case {'bvecs','diffusionbvecs'}
    % feSet(fe,'bvecs');
    fe.bvecs = val;
  case {'bvecsindices','diffusionimagesindicesindwivolume'}
    % feSet(fe,'bvecsindices');
    fe.bvecsindices = val;
  case {'bvals','diffusionbvals'}
    fe.bvals = val;
  case {'diffusionsignalimage','dsi', 'diffusion_signal_img'}
    fe.diffusion_signal_img = val;
  case {'b0signalimage','b0img', 'diffusion_s0_im','s0image'}
    fe.diffusion_S0_img = val;
  case {'usedvoxels'}
    fe.usedVoxels = val;
  case {'modeltensor'}
    fe.modelTensor = val;
  case {'roivoxels','roicoords'}
    % What space?  What form for the coords?
    % Always in IMG coords in LiFE.
    fe.roi.coords = val;

    %% The LiFE model
  case 'mfiber'
    fe.Mfiber = val;             % Fiber portion of M matrix
  case {'measuredsignalfull', 'dsigmeasured'}      % Measured signal in ROI
    fe.dSig  = val;
  case 'fit'
    fe.fit = val;
  case 'voxfit'
    fe.voxfit = val;
  case 'xvalfit'
    fe.xvalfit = val;

    %% Connectome fibers information.
  case {'numberofuniquefibersineachvoxel','uniquefibersnum','numberofuniquefibers','numuniquef'}
    fe.fibers.unique.num = val;
  case {'indextouniquefibersineachvoxel','uniquefibersindex','uniqueindex','indexesofuniquefibers','indexuniquef','uniquefibers'}
    fe.fibers.unique.index = val;
  case {'numberoftotalfibersineachvoxel','totalfibernmber','fibersnum','numberoffibers','numf','numfibers'}
    fe.fibers.total.num = val;
  case {'indexoftotalfibersineachvoxel','totalfiberindex','fibersbyvox','fibersinvox'}
    fe.fibers.total.index = val;
  case {'voxel2fibernodepairs','v2fnp'}
    % This has to be cleared whenever we change fg or roi
    fe.voxel2FNpair = val;
    % Spatial coordinate transforms for voxels and fg to coordinate frames
  case {'xformimg2acpc','img2acpc','img2acpcxform'}
    fe.xform.img2acpc = val;
  case {'xformacpc2img','acpc2img','acpc2imgxform'}
    fe.xform.acpc2img = val;
  case {'size','imgsize','volumesize','dims','dim'}
    fe.imagedim = val;

    %% Diffusion data reapeted measure parameters
  case 'dwirepeatfile'
    fe.path.dwifilerep = val;  % Diffusion weighted file used for testing results
  case {'diffusionsignalimagerepeat'}
    % Set the a second diffusion signla measuremnt (repeat).
    %
    % Image_vals is the image array with the dwi signal taken from all the
    % voxels in the new dataset the fe.roi
    %
    % fe = feSet(fe,'diffusion signal repeat',image_vals);
    fe.rep.diffusion_signal_img = val;
  case {'s0imagerepeat'}
    % Set the the s0 (no diffusion direction measurement) for a second
    % diffusion signla measuremnt (repeat).
    %
    % Image_vals is the image array with the dwi signal taken from all the
    % voxels in the new dataset the fe.roi
    %
    % fe = feSet(fe,'b0signalrepeat',image_vals);
    fe.rep.diffusion_S0_img = val;
  case {'bvecsrepeat','diffusionbvecsrepeat'}
    % feSet(fe,'bvecsrepeat');
    fe.rep.bvecs = val;
  case {'bvecsindicesrepeat','diffusionimagesindicesindwivolumerepeat'}
    % feSet(fe,'bvecsindicesrepeat');
    fe.rep.bvecsindices = val;
  case {'bvalsrepeat','diffusionbvalsrepeat'}
    % fe = feSet(fe,'bvalsrepeat')
    fe.rep.bvals = val;
  case {'imgsizerepeat'}
    fe.rep.imagedim = val;

  case {'anatomyfile'}
    fe.path.anatomy = val;
  case 'dwifile'
    fe.path.dwifile = val;  % Diffusion weighted file used for testing results
  case 'dtfile'
    fe.path.dtfile = val;  % Diffusion weighted file used for testing results

  otherwise
    error('Unknown parameter %s\n',param);
end

end


text:
from django.db import models
from apps.registro.models.Anexo import Anexo
from apps.registro.models.TipoDominio import TipoDominio
from apps.registro.models.TipoCompartido import TipoCompartido
from apps.registro.models.Nivel import Nivel
from apps.seguridad.audit import audit

@audit
class AnexoInformacionEdilicia(models.Model):
    anexo = models.ForeignKey(Anexo)
    tipo_dominio = models.ForeignKey(TipoDominio, null = True)
    tipo_compartido = models.ForeignKey(TipoCompartido, null = True, blank = True)
    niveles = models.ManyToManyField(Nivel, null = True, blank = True, db_table = 'registro_anexo_edificio_compartido_niveles')

    class Meta:
        app_label = 'registro'
        db_table = 'registro_anexo_informacion_edilicia'


text:
{$web=M("web")->information}
<!DOCTYPE HTML>

<meta charset="UTF-8">
<title>{include "inc/title.html"}</title>
<link href="/css/style.css" rel="stylesheet" type="text/css">
<meta name="description" content="{$web['description']}">
<meta name="keywords" content="{$web['key']}">
<meta name="generator" content="FengCms" />
<meta name="author" content="FengCms">

{include "scrap/header.html"}

	<hgroup id="hgroup">

网站地图

		{include "inc/where.html"}
	</hgroup>

			{$map}

{include "scrap/footer.html"}


text:
<?xml version="1.0" encoding="utf-8" ?>
<Tasks>
  <!--
    UglifyHtml is a sequential task that compresses and minifies HTML files.

    The minified files generated are loaded by this task so that other tasks can select them through the selectFiles option.
  -->
  <Task id="$int" name="UglifyHtml" description="$string" enabled="true|false">
    <!--
      The HTML (.html) files loaded by the task having as id $taskId will be compressed and minified.
    -->
    <Setting name="selectFiles" value="$taskId" />
    <Setting name="selectFiles" value="$taskId" />
    <!-- You can add as many selecteFiles as you want.-->
  </Task>
</Tasks>


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.rankingexpression.transform;

import com.yahoo.searchlib.rankingexpression.Reference;
import com.yahoo.searchlib.rankingexpression.rule.CompositeNode;
import com.yahoo.searchlib.rankingexpression.rule.ExpressionNode;
import com.yahoo.searchlib.rankingexpression.rule.FunctionNode;
import com.yahoo.searchlib.rankingexpression.rule.NameNode;
import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode;
import com.yahoo.searchlib.rankingexpression.rule.TensorFunctionNode;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.evaluation.TypeContext;
import com.yahoo.tensor.functions.Reduce;

import java.util.Optional;

/**
 * Transforms min(tensor,dim) and max(tensor,dim) to
 * reduce(tensor,min/max,dim). This is necessary as the backend does
 * not recognize these forms of min and max.
 *
 * @author lesters
 */
public class TensorMaxMinTransformer<CONTEXT extends TransformContext> extends ExpressionTransformer<CONTEXT> {

    @Override
    public ExpressionNode transform(ExpressionNode node, CONTEXT context) {
        if (node instanceof CompositeNode) {
            node = transformChildren((CompositeNode) node, context);
        }
        if (node instanceof FunctionNode) {
            node = transformFunctionNode((FunctionNode) node, context.types());
        }
        return node;
    }

    public static ExpressionNode transformFunctionNode(FunctionNode node, TypeContext<Reference> context) {
        switch (node.getFunction()) {
            case min:
            case max:
                return transformMaxAndMinFunctionNode(node, context);
        }
        return node;
    }

    /**
     * Transforms max and min functions if the first
     * argument returns a tensor type and the second argument is a valid
     * dimension in the tensor.
     */
    private static ExpressionNode transformMaxAndMinFunctionNode(FunctionNode node, TypeContext<Reference> context) {
        if (node.children().size() != 2) {
            return node;
        }
        ExpressionNode arg1 = node.children().get(0);
        Optional<String> dimension = dimensionName(node.children().get(1));
        if (dimension.isPresent()) {
            TensorType type = arg1.type(context);
            if (type.dimension(dimension.get()).isPresent()) {
                return replaceMaxAndMinFunction(node);
            }
        }
        return node;
    }

    private static Optional<String> dimensionName(ExpressionNode node) {
        if (node instanceof ReferenceNode) {
            Reference reference = ((ReferenceNode)node).reference();
            if (reference.isIdentifier())
                return Optional.of(reference.name());
            else
                return Optional.empty();
        }
        else if (node instanceof NameNode) {
            return Optional.of(((NameNode)node).getValue());
        }
        else {
            return Optional.empty();
        }
    }

    private static ExpressionNode replaceMaxAndMinFunction(FunctionNode node) {
        ExpressionNode arg1 = node.children().get(0);
        ExpressionNode arg2 = node.children().get(1);

        TensorFunctionNode.ExpressionTensorFunction expression = TensorFunctionNode.wrap(arg1);
        Reduce.Aggregator aggregator = Reduce.Aggregator.valueOf(node.getFunction().name());
        String dimension = ((ReferenceNode) arg2).getName();

        return new TensorFunctionNode(new Reduce<>(expression, aggregator, dimension));
    }

}


text:
using Poco::Dynamic::Var;

namespace Poco {
namespace JSON {

Object::Object(bool preserveInsertionOrder): _preserveInsOrder(preserveInsertionOrder)
{
}

Object::Object(const Object& copy) : _values(copy._values),
	_preserveInsOrder(copy._preserveInsOrder),
	_pStruct(0)
{
	if (_preserveInsOrder)
	{
		// need to update pointers in _keys to point to copied _values
		for (KeyPtrList::const_iterator it = copy._keys.begin(); it != copy._keys.end(); ++it)
		{
			ValueMap::const_iterator itv = _values.find(**it);
			poco_assert (itv != _values.end());
			_keys.push_back(&itv->first);
		}
	}
}

Object::~Object()
{
}

Var Object::get(const std::string& key) const
{
	ValueMap::const_iterator it = _values.find(key);
	if (it != _values.end())
	{
		return it->second;
	}

	return Var();
}

Array::Ptr Object::getArray(const std::string& key) const
{
	ValueMap::const_iterator it = _values.find(key);
	if ((it != _values.end()) && (it->second.type() == typeid(Array::Ptr)))
	{
		return it->second.extract<Array::Ptr>();
	}

	return 0;
}

Object::Ptr Object::getObject(const std::string& key) const
{
	ValueMap::const_iterator it = _values.find(key);
	if ((it != _values.end()) && (it->second.type() == typeid(Object::Ptr)))
	{
		return it->second.extract<Object::Ptr>();
	}

	return 0;
}

void Object::getNames(std::vector<std::string>& names) const
{
	names.clear();
	for(ValueMap::const_iterator it = _values.begin(); it != _values.end(); ++it)
	{
		names.push_back(it->first);
	}
}

void Object::stringify(std::ostream& out, unsigned int indent, int step) const
{
	if (step < 0) step = indent;

	if(!_preserveInsOrder)
		doStringify(_values, out, indent, step);
	else
		doStringify(_keys, out, indent, step);
}

const std::string& Object::getKey(KeyPtrList::const_iterator& iter) const
{
	ValueMap::const_iterator it = _values.begin();
	ValueMap::const_iterator end = _values.end();
	for (; it != end; ++it)
	{
		if (it->first == **iter) return it->first;
	}

	throw NotFoundException(**iter);
}

void Object::set(const std::string& key, const Dynamic::Var& value)
{
	std::pair<ValueMap::iterator, bool> ret = _values.insert(ValueMap::value_type(key, value));
	if (!ret.second) ret.first->second = value;
	if (_preserveInsOrder)
	{
		KeyPtrList::iterator it = _keys.begin();
		KeyPtrList::iterator end = _keys.end();
		for (; it != end; ++it)
		{
			if (key == **it) return;
		}
		_keys.push_back(&ret.first->first);
	}
}

Poco::DynamicStruct Object::makeStruct(const Object::Ptr& obj)
{
	Poco::DynamicStruct ds;

	ConstIterator it  = obj->begin();
	ConstIterator end = obj->end();
	for (; it != end; ++it)
	{
		if (obj->isObject(it))
		{
			Object::Ptr pObj = obj->getObject(it->first);
			DynamicStruct str = makeStruct(pObj);
			ds.insert(it->first, str);
		}
		else if (obj->isArray(it))
		{
			Array::Ptr pArr = obj->getArray(it->first);
			std::vector<Poco::Dynamic::Var> v = Poco::JSON::Array::makeArray(pArr);
			ds.insert(it->first, v);
		}
		else
			ds.insert(it->first, it->second);
	}

	return ds;
}

Object::operator const Poco::DynamicStruct& () const
{
	if (!_pStruct)
	{
		ValueMap::const_iterator it = _values.begin();
		ValueMap::const_iterator end = _values.end();
		_pStruct = new Poco::DynamicStruct;
		for (; it != end; ++it)
		{
			if (isObject(it))
			{
				_pStruct->insert(it->first, makeStruct(getObject(it->first)));
			}
			else if (isArray(it))
			{
				_pStruct->insert(it->first, Poco::JSON::Array::makeArray(getArray(it->first)));
			}
			else
			{
				_pStruct->insert(it->first, it->second);
			}
		}
	}

	return *_pStruct;
}

void Object::clear()
{
	_values.clear();
	_keys.clear();
	_pStruct = 0;
}

} } // namespace Poco::JSON


text:
package io.apiman.manager.api.beans.audit;

/**
 * Indicates what type of entity an audit entry is related to.
 *
 * @author eric.wittmann@redhat.com
 */
public enum AuditEntityType {

    Organization, Client, Plan, Api

}


text:
{-# LANGUAGE Rank2Types, ScopedTypeVariables #-}
---------------------------------------------------------
-- |
-- Module        : Network.Wai.Middleware.Gzip
-- Copyright     : Michael Snoyman
-- License       : BSD3
--
-- Maintainer    : Michael Snoyman <michael@snoyman.com>
-- Stability     : Unstable
-- Portability   : portable
--
-- Automatic gzip compression of responses.
--
---------------------------------------------------------
module Network.Wai.Middleware.Gzip
    ( gzip
    , GzipSettings
    , gzipFiles
    , GzipFiles (..)
    , gzipCheckMime
    , def
    , defaultCheckMime
    ) where

import Network.Wai
import Data.Maybe (fromMaybe, isJust)
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString as S
import Data.Default.Class
import Network.HTTP.Types ( Status, Header, hContentEncoding, hUserAgent
                          , hContentType, hContentLength)
import System.Directory (doesFileExist, createDirectoryIfMissing)
import Data.ByteString.Builder (byteString)
import qualified Data.ByteString.Builder.Extra as Blaze (flush)
import Control.Exception (try, SomeException)
import qualified Data.Set as Set
import Network.Wai.Header
import Network.Wai.Internal
import qualified Data.Streaming.ByteString.Builder as B
import qualified Data.Streaming.Zlib as Z
import Control.Monad (unless)
import Data.Function (fix)
import Control.Exception (throwIO)
import qualified System.IO as IO
import Data.ByteString.Lazy.Internal (defaultChunkSize)
import Data.Word8 (_semicolon)

data GzipSettings = GzipSettings
    { gzipFiles :: GzipFiles
    , gzipCheckMime :: S.ByteString -> Bool
    }

-- | Gzip behavior for files.
data GzipFiles
    = GzipIgnore -- ^ Do not compress file responses.
    | GzipCompress -- ^ Compress files. Note that this may counteract
                   -- zero-copy response optimizations on some
                   -- platforms.
    | GzipCacheFolder FilePath -- ^ Compress files, caching them in
                               -- some directory.
    | GzipPreCompressed GzipFiles -- ^ If we use compression then try to use the filename with ".gz"
                                  -- appended to it, if the file is missing then try next action
                                  --
                                  -- @since 3.0.17
    deriving (Show, Eq, Read)

-- | Use default MIME settings; /do not/ compress files.
instance Default GzipSettings where
    def = GzipSettings GzipIgnore defaultCheckMime

-- | MIME types that will be compressed by default:
-- @text/@ @*@, @application/json@, @application/javascript@,
-- @application/ecmascript@, @image/x-icon@.
defaultCheckMime :: S.ByteString -> Bool
defaultCheckMime bs =
    S8.isPrefixOf "text/" bs || bs' `Set.member` toCompress
  where
    bs' = fst $ S.break (== _semicolon) bs
    toCompress = Set.fromList
        [ "application/json"
        , "application/javascript"
        , "application/ecmascript"
        , "image/x-icon"
        ]

-- | Use gzip to compress the body of the response.
--
-- Analyzes the \"Accept-Encoding\" header from the client to determine
-- if gzip is supported.
--
-- File responses will be compressed according to the 'GzipFiles' setting.
gzip :: GzipSettings -> Middleware
gzip set app env sendResponse = app env $ \res ->
    case res of
        ResponseRaw{} -> sendResponse res
        ResponseFile{} | gzipFiles set == GzipIgnore -> sendResponse res
        _ -> if "gzip" `elem` enc && not isMSIE6 && not (isEncoded res) && (bigEnough res)
                then
                    let runAction x = case x of
                            (ResponseFile s hs file Nothing, GzipPreCompressed nextAction) ->
                                 let
                                    compressedVersion = file ++ ".gz"
                                 in
                                    doesFileExist compressedVersion >>= \y ->
                                       if y
                                         then (sendResponse $ ResponseFile s (fixHeaders hs) compressedVersion Nothing)
                                         else (runAction (ResponseFile s hs file Nothing, nextAction))
                            (ResponseFile s hs file Nothing, GzipCacheFolder cache) ->
                                case lookup hContentType hs of
                                    Just m
                                        | gzipCheckMime set m -> compressFile s hs file cache sendResponse
                                    _ -> sendResponse res
                            (ResponseFile {}, GzipIgnore) -> sendResponse res
                            _ -> compressE set res sendResponse
                    in runAction (res, gzipFiles set)
                else sendResponse res
  where
    enc = fromMaybe [] $ (splitCommas . S8.unpack)
                    `fmap` lookup "Accept-Encoding" (requestHeaders env)
    ua = fromMaybe "" $ lookup hUserAgent $ requestHeaders env
    isMSIE6 = "MSIE 6" `S.isInfixOf` ua
    isEncoded res = isJust $ lookup hContentEncoding $ responseHeaders res

    bigEnough rsp = case contentLength (responseHeaders rsp) of
      Nothing -> True -- This could be a streaming case
      Just len -> len >= minimumLength

    -- For a small enough response, gzipping will actually increase the size
    -- Potentially for anything less than 860 bytes gzipping could be a net loss
    -- The actual number is application specific though and may need to be adjusted
    -- http://webmasters.stackexchange.com/questions/31750/what-is-recommended-minimum-object-size-for-gzip-performance-benefits
    minimumLength = 860

compressFile :: Status -> [Header] -> FilePath -> FilePath -> (Response -> IO a) -> IO a
compressFile s hs file cache sendResponse = do
    e <- doesFileExist tmpfile
    if e
        then onSucc
        else do
            createDirectoryIfMissing True cache
            x <- try $
                 IO.withBinaryFile file IO.ReadMode $ \inH ->
                 IO.withBinaryFile tmpfile IO.WriteMode $ \outH -> do
                    deflate <- Z.initDeflate 7 $ Z.WindowBits 31
                    -- FIXME this code should write to a temporary file, then
                    -- rename to the final file
                    let goPopper popper = fix $ \loop -> do
                            res <- popper
                            case res of
                                Z.PRDone -> return ()
                                Z.PRNext bs -> do
                                    S.hPut outH bs
                                    loop
                                Z.PRError ex -> throwIO ex
                    fix $ \loop -> do
                        bs <- S.hGetSome inH defaultChunkSize
                        unless (S.null bs) $ do
                            Z.feedDeflate deflate bs >>= goPopper
                            loop
                    goPopper $ Z.finishDeflate deflate
            either onErr (const onSucc) (x :: Either SomeException ()) -- FIXME bad! don't catch all exceptions like that!
  where
    onSucc = sendResponse $ responseFile s (fixHeaders hs) tmpfile Nothing

    onErr _ = sendResponse $ responseFile s hs file Nothing -- FIXME log the error message

    tmpfile = cache ++ '/' : map safe file
    safe c
        | 'A' <= c && c <= 'Z' = c
        | 'a' <= c && c <= 'z' = c
        | '0' <= c && c <= '9' = c
    safe '-' = '-'
    safe '_' = '_'
    safe _ = '_'

compressE :: GzipSettings
          -> Response
          -> (Response -> IO a)
          -> IO a
compressE set res sendResponse =
    case lookup hContentType hs of
        Just m | gzipCheckMime set m ->
            let hs' = fixHeaders hs
             in wb $ \body -> sendResponse $ responseStream s hs' $ \sendChunk flush -> do
                    (blazeRecv, _) <- B.newBuilderRecv B.defaultStrategy
                    deflate <- Z.initDeflate 1 (Z.WindowBits 31)
                    let sendBuilder builder = do
                            popper <- blazeRecv builder
                            fix $ \loop -> do
                                bs <- popper
                                unless (S.null bs) $ do
                                    sendBS bs
                                    loop
                        sendBS bs = Z.feedDeflate deflate bs >>= deflatePopper
                        flushBuilder = do
                            sendBuilder Blaze.flush
                            deflatePopper $ Z.flushDeflate deflate
                            flush
                        deflatePopper popper = fix $ \loop -> do
                            result <- popper
                            case result of
                                Z.PRDone -> return ()
                                Z.PRNext bs' -> do
                                    sendChunk $ byteString bs'
                                    loop
                                Z.PRError e -> throwIO e

                    body sendBuilder flushBuilder
                    sendBuilder Blaze.flush
                    deflatePopper $ Z.finishDeflate deflate
        _ -> sendResponse res
  where
    (s, hs, wb) = responseToStream res

-- Remove Content-Length header, since we will certainly have a
-- different length after gzip compression.
fixHeaders :: [Header] -> [Header]
fixHeaders =
    ((hContentEncoding, "gzip") :) . filter notLength
  where
    notLength (x, _) = x /= hContentLength

splitCommas :: String -> [String]
splitCommas [] = []
splitCommas x =
    let (y, z) = break (== ',') x
     in y : splitCommas (dropWhile (== ' ') $ drop 1 z)


text:
package org.jf.baksmali;

import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.Parameters;
import com.google.common.collect.Lists;
import org.jf.dexlib2.DexFileFactory;
import org.jf.dexlib2.Opcodes;
import org.jf.dexlib2.dexbacked.DexBackedDexFile;
import org.jf.dexlib2.iface.MultiDexContainer;
import org.jf.util.jcommander.Command;
import org.jf.util.jcommander.ExtendedParameter;
import org.jf.util.jcommander.ExtendedParameters;

import javax.annotation.Nonnull;
import java.io.File;
import java.io.IOException;
import java.util.List;

@Parameters(commandDescription = "Lists the dex files in an apk/oat file.")
@ExtendedParameters(
        commandName = "dex",
        commandAliases = "d")
public class ListDexCommand extends Command {

    @Parameter(names = {"-h", "-?", "--help"}, help = true,
            description = "Show usage information")
    private boolean help;

    @Parameter(description = "An apk or oat file.")
    @ExtendedParameter(argumentNames = "file")
    private List<String> inputList = Lists.newArrayList();

    public ListDexCommand(@Nonnull List<JCommander> commandAncestors) {
        super(commandAncestors);
    }

    @Override public void run() {
        if (help || inputList == null || inputList.isEmpty()) {
            usage();
            return;
        }

        if (inputList.size() > 1) {
            System.err.println("Too many files specified");
            usage();
            return;
        }

        String input = inputList.get(0);
        File file = new File(input);

        if (!file.exists()) {
            System.err.println(String.format("Could not find the file: %s", input));
            System.exit(-1);
        }

        List<String> entries;
        try {
            MultiDexContainer<? extends DexBackedDexFile> container =
                    DexFileFactory.loadDexContainer(file, Opcodes.getDefault());
            entries = container.getDexEntryNames();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        for (String entry: entries) {
            System.out.println(entry);
        }
    }
}


text:
// Write a program for extracting all email addresses from given text. All substrings that match the format <identifier>@<host>…<domain> should be recognized as emails.

using System;
using System.Text.RegularExpressions;

class EmailExtractor
{
    static void Main()
    {
        string text = @"Please contact us by phone (+359 222 222 222) or by email at exa_mple@abv.bg or at baj.ivan@yahoo.co.uk . This is not email: test@test. This also: @telerik.com. Neither this: a@a.b.";

        string[] splittedText = text.Split(' ');

        for (int i = 0; i < splittedText.Length; i++)
        {
            if (Regex.IsMatch(splittedText[i], @"[\w., \-]{2,15}@[\w]{2,15}[.]{1}[\w.]{2,6}"))
            {
                Console.WriteLine(splittedText[i]);
            }
        }
    }
}


text:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
/// Extensions for configuring ApiExplorer using <see cref="Endpoint.Metadata"/>.
/// </summary>
public static class EndpointMetadataApiExplorerServiceCollectionExtensions
{
    /// <summary>
    /// Configures ApiExplorer using <see cref="Endpoint.Metadata"/>.
    /// </summary>
    /// <param name="services">The <see cref="IServiceCollection"/>.</param>
    public static IServiceCollection AddEndpointsApiExplorer(this IServiceCollection services)
    {
        // Try to add default services in case MVC services aren't added.
        services.TryAddSingleton<IActionDescriptorCollectionProvider, DefaultActionDescriptorCollectionProvider>();
        services.TryAddSingleton<IApiDescriptionGroupCollectionProvider, ApiDescriptionGroupCollectionProvider>();

        services.TryAddEnumerable(
            ServiceDescriptor.Transient<IApiDescriptionProvider, EndpointMetadataApiDescriptionProvider>());

        return services;
    }
}


text:
package com.cnge06.cne.json.m;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonProtocol {
	private static final ObjectMapper mapper = new ObjectMapper();
	private String path;
	private String content;

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public static ObjectMapper getObjectMapper() {
		return mapper;
	}

	/**
	 * 将java对象转换成json字符串
	 *
	 * @param obj
	 *            准备转换的对象
	 * @return json字符串
	 * @throws Exception
	 */
	public static String beanToJson(Object obj) throws Exception {
		try {
			ObjectMapper objectMapper = getObjectMapper();
			String json = objectMapper.writeValueAsString(obj);
			return json;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 将json字符串转换成java对象
	 * @param json 准备转换的json字符串
	 * @param clazz  准备转换的类
	 * @return
	 * @throws Exception
	 */
	public static Object jsonToBean(String json, Class<?> clazz) throws Exception {
		try {
		ObjectMapper objectMapper = getObjectMapper();
		Object o = objectMapper.readValue(json, clazz);
		return o;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
}


text:
Japanese traditional colors. Inspired by [NIPPON COLORS](http://nipponcolors.com/).

### Install

```
npm install nippon-colors
```


text:
Às vezes você pode querer:

1. Aplicar um carregador personalizado de string a uma linguagem em vez de deixar `vue-loader` responsável.

2. Sobrescrever a configuração embutida do carregador para a linguagem padrão.

3. Pré-processar ou pós-processar um bloco de linguagem especifico com carregadores personalizado.

Para fazer isto, especifique a opção `loaders` para `vue-loader`:

> Observe que `preLoaders` e`postLoaders` são suportados apenas em verões >=10.3.0

### Webpack 2.x

```js
// webpack.config.js
module.exports = {
  // outras opções...
  module: {
    // module.rules é o mesmo que module.loaders em 1.x
    rules : [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          // `loaders` substituirá os carregadores padrões.
          // A configuração a seguir fará com que todas as tags <script> sem
          // o atributo "lang" sejam carrega com coffee-loader
          loaders: {
            js: 'coffee-loader'
          },

          // `preLoaders` são anexados antes dos carregadores padrões
          // Você pode usar isso para pré-processar blocos de linguagem
          // - um caso de uso comum seria intercionalização (i18n)  em tempo de construção.
          preLoaders: {
            js: '/caminho/personalizado/para/carregador'
          },

          // `postLoaders` são anexados após os carregadores padrões.
          //
          // - Para `html`, o resultado retornado pelo carregador padrão
          //   será compilado em código de função de renderização JavaScript.
          //
          // - Para `css`, o resultado será retornado por vue-style-loader
          //   que não é particulamente útil em muitos casos. Usando um plugin
          //   postcss será uma opção melhor.
          postLoaders: {
            html: 'babel-loader'
          },

          // `excludedPreLoaders` should be regex
          excludedPreLoaders: /(eslint-loader)/
        }
      }
    ]
  }
}
```

### Webpack 1.x

```js
// webpack.config.js
module.exports = {
  // outras opções...
  module: {
    loaders: [
      {
        test: /\.vue$/,
        loader: 'vue'
      }
    ]
  },
  // configurações vue-loader
  vue: {
    loaders: {
      // mesmo que as regras de configurações acima
    }
  }
}
```

Um uso mais prático das configurações avançadas do carregador é [extrair o CSS do componente em um único arquivo](./extract-css.md).


text:
<?php //-->

namespace Eden\Eventbrite\Event;

use Eden\Eventbrite\Base as EventbriteBase;
use Eden\Eventbrite\Argument as Argument;

/**
 * Eventbrite search
 *
 * @vendor Eden
 * @package Eventbrite
 * @author Airon Paul Dumael airon.dumael@gmail.com
 */
class Search extends EventbriteBase
{
    const URL = 'https://www.eventbrite.com/json/event_search';

    protected $query = array();

    /**
     * Sets token or user and api
     *
     * @param string $user
     * @param string|bool|null $api
     * @return void
     */
    public function __construct($user, $api = false)
    {
        //argument test
        Argument::i()
            //Argument 1 must be a string
            ->test(1, 'string')
            //Argument 2 must be a string, bool or null
            ->test(2, 'string', 'bool', 'null');

        $this->api = $api;
        $this->user = $user;
    }

    /**
     * Only return the number of results found
     *
     * @return Eden\Eventbrite\Event\Search
     */
    public function countOnly()
    {
        $this->query['count_only'] = 'true';

        return $this;
    }

    /**
     * Retrieves response
     *
     * @return array
     */
    public function send()
    {
        return $this->getJsonResponse(self::URL, $this->query);
    }

    /**
     * Filters by address
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setAddress($address)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['address'] = $address;

        return $this;
    }

    /**
     * Filters by categories
     *
     * @param string|array
     * @return Eden\Eventbrite\Event\Search
     */
    public function setCategory($category)
    {
        //Argument 1 must be a string or array
        Argument::i()->test(1, 'string', 'array');

        if (is_array($category)) {
            $category = implode(',', $category);
        }

        $this->query['category'] = $category;

        return $this;
    }

    /**
     * Filters by country
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setCountry($country)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['country'] = $country;

        return $this;
    }

    /**
     * Filters by city
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setCity($city)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['city'] = $city;

        return $this;
    }

    /**
     * Filters by event date. Limit the list of results to a
     * date range, specified by a label or by exact dates.
     * Currently supported labels include: All, Future,
     * Past, Today, Yesterday, Last Week, This Week,
     * Next week, This Month, Next Month and months by
     * name like October. Exact date ranges take the
     * form 2008-04-25 2008-04-27.
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setDate($date)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['date'] = $date;

        return $this;
    }

    /**
     * Filters by when the event was created. Limit the
     * list of results to a date range, specified by a
     * label or by exact dates. Currently supported
     * labels include: All, Future, Past, Today,
     * Yesterday, Last Week, This Week, Next week,
     * This Month, Next Month and months by name like
     * October. Exact date ranges take the form
     * 2008-04-25 2008-04-27.
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setDateCreated($date)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['date_created'] = $date;

        return $this;
    }

    /**
     * Filters by when the event was modified. Limit the
     * list of results to a date range, specified by a
     * label or by exact dates. Currently supported
     * labels include: All, Future, Past, Today,
     * Yesterday, Last Week, This Week, Next week,
     * This Month, Next Month and months by name like
     * October. Exact date ranges take the form
     * 2008-04-25 2008-04-27.
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setDateModified($date)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['date_modified'] = $date;

        return $this;
    }

    /**
     * Filters by keywords
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setKeywords($keywords)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['keywords'] = $keywords;

        return $this;
    }

    /**
     * Filters by latitude
     *
     * @param float
     * @return Eden\Eventbrite\Event\Search
     */
    public function setLatitude($latitude)
    {
        //Argument 1 must be a float
        Argument::i()->test(1, 'float');

        $this->query['latitude'] = $latitude;

        return $this;
    }

    /**
     * Filters by longitude
     *
     * @param float
     * @return Eden\Eventbrite\Event\Search
     */
    public function setLongitude($longitude)
    {
        //Argument 1 must be a float
        Argument::i()->test(1, 'float');

        $this->query['longitude'] = $longitude;

        return $this;
    }

    /**
     * Set number of results
     *
     * @param int
     * @return Eden\Eventbrite\Event\Search
     */
    public function setMax($max)
    {
        //Argument 1 must be a int
        Argument::i()->test(1, 'int');

        if ($max > 100) {
            $max = 100;
        }

        $this->query['max'] = $max;

        return $this;
    }

    /**
     * Filters by organizer
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setOrganizer($organizer)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['organizer'] = $organizer;

        return $this;
    }

    /**
     * Filters by postal/zip code
     *
     * @param string|int
     * @return Eden\Eventbrite\Event\Search
     */
    public function setPostal($postal)
    {
        //Argument 1 must be a string or integer
        Argument::i()->test(1, 'string', 'int');

        $this->query['postal_code'] = $postal;

        return $this;
    }

    /**
     * Filters by region
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setRegion($region)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['region'] = $region;

        return $this;
    }

    /**
     * Filters within a specified area
     *
     * @param int
     * @return Eden\Eventbrite\Event\Search
     */
    public function setWithin($within)
    {
        //Argument 1 must be a int
        Argument::i()->test(1, 'int');

        $this->query['within'] = $within;

        return $this;
    }

    /**
     * Filters within an area unit
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setWithinUnit($unit)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['within_unit'] = $unit;

        return $this;
    }

    /**
     * Sort by city
     *
     * @return Eden\Eventbrite\Event\Search
     */
    public function sortByCity()
    {
        $this->query['sort_by'] = 'city';

        return $this;
    }

    /**
     * Sort by event date
     *
     * @return Eden\Eventbrite\Event\Search
     */
    public function sortByDate()
    {
        $this->query['sort_by'] = 'date';

        return $this;
    }

    /**
     * Sort by event id
     *
     * @return Eden\Eventbrite\Event\Search
     */
    public function sortById()
    {
        $this->query['sort_by'] = 'id';

        return $this;
    }

    /**
     * Sort by event name
     *
     * @return Eden\Eventbrite\Event\Search
     */
    public function sortByName()
    {
        $this->query['sort_by'] = 'name';

        return $this;
    }

    /**
     * Set page
     *
     * @param int
     * @return Eden\Eventbrite\Event\Search
     */
    public function setPage($page)
    {
        //Argument 1 must be a int
        Argument::i()->test(1, 'int');

        $this->query['page'] = $page;

        return $this;
    }

    /**
     * Filter by event ids greater than specified
     *
     * @param int
     * @return Eden\Eventbrite\Event\Search
     */
    public function setSince($since)
    {
        //Argument 1 must be a int
        Argument::i()->test(1, 'int');

        $this->query['since_id'] = $since;

        return $this;
    }

    /**
     * Sets a tracking link
     *
     * @param string
     * @return Eden\Eventbrite\Event\Search
     */
    public function setTracking($tracking)
    {
        //Argument 1 must be a string
        Argument::i()->test(1, 'string');

        $this->query['tracking_link'] = $tracking;

        return $this;
    }
}


text:
require 'hive/diagnostic'
module Hive
  class Diagnostic
    class Android
      class Uptime < Diagnostic

        def diagnose(data={})
          if config.has_key?(:reboot_timeout)
            uptime = self.device_api.uptime
            if  uptime < config[:reboot_timeout]
              data[:next_reboot_in] = {:value => "#{config[:reboot_timeout] - uptime}", :unit => "s"}
              self.pass("Time for next reboot: #{config[:reboot_timeout] - uptime}s", data)
            else
              self.fail("Reboot required", data)
            end
          else
            data[:reboot] = {:value => "Not configured for reboot. Set in config {:reboot_timeout => '2400'}"}
            self.pass("Not configured for reboot", data)
          end
        end

        def repair(result)
          data = {}
          Hive.logger.info("Rebooting the device")
          begin
            data[:last_rebooted] = {:value => Time.now}
            self.pass("Reboot", data)
            self.device_api.reboot
          rescue
            Hive.logger.error("Device not found")
          end
          diagnose(data)
        end

      end
    end
  end
end


text:
<?php

namespace TelegramBot\Types;

/**
 * Represents a venue. By default, the venue will be sent by the user.
 * Alternatively, you can use input_message_content to send a message with the specified content instead of the venue.
 *
 * Note: This will only work in Telegram versions released after 9 April, 2016. Older clients will ignore them.
 * @see https://core.telegram.org/bots/api#inlinequeryresultvenue
 */
class InlineQueryResultVenue
{
    /**
     * Type of the result, must be venue
     * @var string $type
     */
    public $type;

    /**
     * Unique identifier for this result, 1-64 Bytes
     * @var string $id
     */
    public $id;

    /**
     * Latitude of the venue location in degrees
     * @var double $latitude
     */
    public $latitude;

    /**
     * Longitude of the venue location in degrees
     * @var double $longitude
     */
    public $longitude;

    /**
     * Title of the venue
     * @var string $title
     */
    public $title;

    /**
     * Address of the venue
     * @var string $address
     */
    public $address;

    /**
     * Optional. Foursquare identifier of the venue if known
     * @var string $foursquare_id
     */
    public $foursquare_id;

    /**
     * $foursquare_type Optional. Foursquare type of the venue. (For example, "arts_entertainment/default", "arts_entertainment/aquarium" or "food/icecream".)
     * @var string $foursquare_type
     */
    public $foursquare_type;

    /**
     * Optional. Google Places identifier of the venue
     * @var string $google_place_id
     */
    public $google_place_id;

    /**
     * Optional. Google Places type of the venue.
     * (See {@see https://developers.google.com/places/web-service/supported_types supported types}.)
     * @var string $google_place_type
     */
    public $google_place_type;

    /**
     * Optional.
     * {@see https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating Inline keyboard}
     * attached to the message
     * @var InlineKeyboardMarkup $reply_markup
     */
    public $reply_markup;

    /**
     * Optional. Content of the message to be sent instead of the venue
     * @var InputTextMessageContent|InputLocationMessageContent|InputVenueMessageContent|InputContactMessageContent $input_message_content
     */
    public $input_message_content;

    /**
     * Optional. Url of the thumbnail for the result
     * @var string $thumb_url
     */
    public $thumb_url;

    /**
     * Optional. Thumbnail width
     * @var int $thumb_width
     */
    public $thumb_width;

    /**
     * Optional. Thumbnail height
     * @var int $thumb_height
     */
    public $thumb_height;
}


text:
using System.Threading;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using PurdueIo.Database;

namespace PurdueIo.Api.Controllers
{
    public class MeetingsController : ODataController
    {
        private ApplicationDbContext dbContext;

        public MeetingsController(ApplicationDbContext dbContext)
        {
            this.dbContext = dbContext;
        }

        [HttpGet]
        [EnableQuery(MaxExpansionDepth = EdmModelBuilder.MAX_EXPAND_DEPTH,
            MaxAnyAllExpressionDepth = EdmModelBuilder.MAX_EXPAND_DEPTH)]
        public IActionResult Get(CancellationToken token)
        {
            return Ok(dbContext.Meetings);
        }
    }
}


text:
#ifndef SC_PARDISO_MATRIX_HPP
#   define SC_PARDISO_MATRIX_HPP

#include <string.h>
#include <map>
#include <assert.h>
#include "DiagonalMatrix.hpp"
#include "Matrix.hpp"
#include "Vector3.hpp"

/*!
 * Sparse Matrix
 * The data structure of this sparse matrix is particularly optimized
 * for intel MKL PARDISO or DSS solver call.
 *
 * NOTE: it assumes the diagonal elements is always non-zero
 */

struct PardisoMatrixIO;

template <typename T>
class PardisoMatrix
{
    friend struct PardisoMatrixIO;

    public:
        PardisoMatrix(int m, int n):
                numCols_(n), numRows_(m), isSymm_(false),
                isPosDef_(false)
        {  rows_.resize(m); }

        PardisoMatrix(int s, bool isSym = false):
                numCols_(s), numRows_(s), isSymm_(isSym),
                isPosDef_(false)
        {  rows_.resize(s); }

        PardisoMatrix(int s, bool isSym, bool isPosDef):
                numCols_(s), numRows_(s), isSymm_(isSym),
                isPosDef_(isPosDef)
        {  rows_.resize(s); }

        PardisoMatrix():numCols_(0), numRows_(0), isSymm_(false),
                isPosDef_(false)
        {}

        void clear()
        {
            for(size_t i = 0;i < rows_.size();++ i) rows_[i].clear();
        }

        void resize(int s, bool isSym = false)
        {
            numCols_ = numRows_ = s;
            isSymm_ = isSym;
            rows_.resize(s);
            clear();
        }

        void resize(int s, bool isSym, bool isPosDef)
        {
            numCols_ = numRows_ = s;
            isSymm_ = isSym;
            isPosDef_ = isPosDef;
            rows_.resize(s);
            clear();
        }

        void add(const PardisoMatrix<T>& mat)
        {
            if ( data_.size() != mat.data_.size() ||
                 rowIdx_.size() != mat.rowIdx_.size() )
            {
                fprintf(stderr, "ERROR: Two Pardiso Matrices for scaleAdd call have different sparsity pattern\n");
                exit(1);
            }

            for(size_t i = 0;i < data_.size();++ i)
                data_[i] += mat.data_[i];
        }

        /*!
         * Axpy operator: compute this = this + beta * mat
         * It assumes the this matrix and the mat have the same sparsity pattern.
         */
        void axpy(T beta, const PardisoMatrix<T>& mat)
        {
            if ( data_.size() != mat.data_.size() ||
                 rowIdx_.size() != mat.rowIdx_.size() )
            {
                fprintf(stderr, "ERROR: Two Pardiso Matrices for scaleAdd call have different sparsity pattern\n");
                exit(1);
            }

            for(size_t i = 0;i < data_.size();++ i)
                data_[i] += beta * mat.data_[i];
        }

        void axpy(T beta, const DiagonalMatrix<T>& mat)
        {
            if ( mat.size() != numCols_ || numCols_ != numRows_ )
            {
                fprintf(stderr, "ERROR: the size of diagonal matrix is inconsistent with this PardisoMatrix\n");
                exit(1);
            }

#ifdef USE_OPENMP
            #pragma omp parallel for default(none) schedule(dynamic, 8000) shared(beta, mat)
#endif
            for(int i = 0;i < numCols_;++ i)
                *(rows_[i][i]) += beta * mat[i];
        }

        void axpy(T beta, const DiagonalMatrix< Vector3<T> >& mat)
        {
            if ( mat.size()*3 != numCols_ || numCols_ != numRows_ )
            {
                fprintf(stderr, "ERROR: the size of diagonal matrix is inconsistent with this PardisoMatrix\n");
                exit(1);
            }

            const T* ptr = (const T*)mat.data();
#ifdef USE_OPENMP
            #pragma omp parallel for default(none) schedule(dynamic, 8000) shared(beta, ptr)
#endif
            for(int i = 0;i < numCols_;++ i)
                *(rows_[i][i]) += beta * ptr[i];
        }

        /*!
         * indicate the mat[nr][nc] is nonzero
         * the benifit is, for example,
         * as long as we don't remesh, and the mesh isn't split during
         * the simulation, the sparity pattern of stiffness matrix
         * doesn't change.
         */
        void set_nonzero(int nr, int nc);
        void generate_pattern();        // $$TESTED

        void add(int nr, int nc, T v)
        {
            if ( isSymm_ && nr > nc )
            {
                /*
                 * Here we assume mat[nr][nc] += v only applies to the
                 * upper trangle part of the matrix when this is a
                 * symmetric matrix
                 */
                return;
            }
            assert(rows_[nr].count(nc));
            *(rows_[nr][nc]) += v;
        }

        /*! make all the elements be zero */
        void zeros()
        {
            memset(&data_[0], 0, sizeof(T)*data_.size());
        }

        void multiply(const std::vector< Vector3<T> >& in,
                      std::vector< Vector3<T> >& out) const;

        void multiply(const T* in, T* out) const;

        bool check_symmetry();

        void dump() const;
        void to_matrix(Matrix<T>& mat) const;

        /* ================ Retrival Methods =============== */
        int num_rows() const
        { return numRows_; }
        int num_cols() const
        { return numCols_; }
        int num_nonzeros() const
        { return data_.size(); }

        const T* data() const
        { return &data_[0]; }

        const int* col_indices() const
        { return &cols_[0]; }

        const int* row_indices() const
        { return &rowIdx_[0]; }

        T* data()
        { return &data_[0]; }

        int* col_indices()
        { return &cols_[0]; }

        int* row_indices()
        { return &rowIdx_[0]; }

        bool is_symmetric() const
        { return isSymm_; }

        bool is_positive_definite() const
        { return isPosDef_; }

        bool& is_positive_definite()
        { return isPosDef_; }

        bool operator == (const PardisoMatrix<T>& m2) const;

    private:
        typedef std::map<int, T*> RowMap;

        int                 numCols_;
        int                 numRows_;
        int                 numNonZero_;
        std::vector<RowMap> rows_;
        /*! indicate if it is symmetric matrix */
        bool                isSymm_;
        bool                isPosDef_;

        /* the data structure for Pardiso storage format */
        std::vector<T>      data_;
        std::vector<int>    cols_;
        std::vector<int>    rowIdx_;
};

///////////////////////////////////////////////////////////////////////////////
template <typename T>
bool PardisoMatrix<T>::check_symmetry()
{
    if ( numCols_ != numRows_ ) return false;
    if ( isSymm_ ) return true;

    for(int i = 0;i < numRows_;++ i)
    {
        typename RowMap::iterator end = rows_[i].end();
        for(typename RowMap::iterator it = rows_[i].begin();
                it != end;++ it)
        {
            if ( it->first < i ) continue;
            if ( !rows_[it->first].count(i) ||
                 M_ABS(*rows_[it->first][i] - *it->second) >
                 1E-10*M_MAX(M_ABS(*rows_[it->first][i]), M_ABS(*it->second)) )
                return false;
        }
    }
    return true;
}

/*
 * If the matrix is symmetric, it stores only the upper part of it
 */
template <typename T>
void PardisoMatrix<T>::set_nonzero(int nr, int nc)
{
    if ( isSymm_ && nr > nc )
        rows_[nc][nr] = NULL;
    else
        rows_[nr][nc] = NULL;
}

/*
 * NOTE that in order to ease to work with Fortran routines, the indices
 *      in both cols_ and rowIdx_ are all 1-based.
 */
template <typename T>
void PardisoMatrix<T>::generate_pattern()
{
    data_.clear();
    cols_.clear();
    rowIdx_.clear();

    // # of nonzero elements
    numNonZero_ = 0;
    for(int i = 0;i < numRows_;++ i)
        numNonZero_ += rows_[i].size();
    data_.resize(numNonZero_);

    for(int i = 0, ptr = 0;i < numRows_;++ i)
    {
        if ( rows_.empty() )
        {
            fprintf(stderr, "Warning: With zeros in the %d-th row\n, cannot generate sparsity pattern for PARDISO call", i);
            return;
        }

        typename RowMap::iterator it  = rows_[i].begin();
        typename RowMap::iterator end = rows_[i].end();
        rowIdx_.push_back(ptr + 1);
        for(;it != end;++ it)
        {
            cols_.push_back(it->first + 1);    // 1-based column index
            it->second = &(data_[ptr]);
            ++ ptr;
        }
    }

    rowIdx_.push_back(data_.size() + 1);      // 1-based row index
}

template <typename T>
void PardisoMatrix<T>::multiply(const std::vector< Vector3<T> >& in,
                                std::vector< Vector3<T> >& out) const
{
    assert(in.size()*3 == numCols_);
    if ( out.size() != numRows_ ) out.resize(numRows_);

    const T* inPtr = (const T*)&in[0];
    T* outPtr = (T*)out[0];
#ifdef USE_OPENMP
    #pragma omp parallel for default(none) schedule(dynamic) shared(inPtr, outPtr)
#endif
    for(int i = 0;i < numRows_;++ i)
    {
        outPtr[i] = 0;
        typename RowMap::const_iterator end = rows_[i].end();
        for(typename RowMap::const_iterator it = rows_[i].begin();
                it != end;++ it)
            outPtr[i] += inPtr[it->first]*(*(it->second));
    }
}

template <typename T>
void PardisoMatrix<T>::multiply(const T* in, T* out) const
{
#ifdef USE_OPENMP
    #pragma omp parallel for default(none) schedule(dynamic) shared(inPtr, outPtr)
#endif
    for(int i = 0;i < numRows_;++ i)
    {
        out[i] = 0;
        typename RowMap::const_iterator end = rows_[i].end();
        for(typename RowMap::const_iterator it = rows_[i].begin();
                it != end;++ it)
            out[i] += in[it->first]*(*(it->second));
    }
}

template <typename T>
void PardisoMatrix<T>::to_matrix(Matrix<T>& mat) const
{
    mat.zeros();

    int rowId = 0;
    for(size_t i = 0;i < data_.size();++ i)
    {
        int colId = cols_[i] - 1;
        if ( rowIdx_[rowId+1] == i+1 ) ++ rowId;
        mat.set(colId, rowId, data_[i]);
    }
}

template <typename T>
void PardisoMatrix<T>::dump() const
{
    using namespace std;

    cout << "data: { ";
    for(int i = 0;i < data_.size();++ i)
        cout << data_[i] << ' ';
    cout << '}' << endl;
    cout << "col: { ";
    for(int i = 0;i < cols_.size();++ i)
        cout << cols_[i] << ' ';
    cout << '}' << endl;
    cout << "row: { ";
    for(int i = 0;i < rowIdx_.size();++ i)
        cout << rowIdx_[i] << ' ';
    cout << '}' << endl;
}

template <>
void PardisoMatrix<double>::add(const PardisoMatrix<double>& mat);

template<>
void PardisoMatrix<double>::axpy(double beta, const PardisoMatrix<double>& mat);

template<>
bool PardisoMatrix<double>::operator == (const PardisoMatrix<double>& m2) const;

template<>
bool PardisoMatrix<float>::operator == (const PardisoMatrix<float>& m2) const;

#endif


text:
package org.conqat.engine.core.bundle.library;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

import org.conqat.engine.core.bundle.BundleInfo;
import org.conqat.engine.core.bundle.library.license.CustomLicense;
import org.conqat.engine.core.bundle.library.license.ELicense;
import org.conqat.engine.core.bundle.library.license.ILicense;
import org.conqat.lib.commons.collections.CollectionUtils;
import org.conqat.lib.commons.collections.UnmodifiableSet;
import org.conqat.lib.commons.filesystem.FileSystemUtils;

/**
 * Descriptor for a Java library holding information about its name, version and
 * license. A library can consist of multiple jar files. The link between
 * library descriptor files and jar files is based on file names. I.e.
 * my-library.lib will cover all jar files with a name matching
 * my-library(.*).jar.
 *
 * @author $Author: poehlmann $
 * @version $Rev: 46536 $
 * @ConQAT.Rating YELLOW Hash: A9251E088A7DF092B057597466D38322
 */
public class LibraryDescriptor {

	/** The name of the library. */
	private final String name;

	/** A short description of the library. */
	private final String description;

	/** The version string of the library. */
	private final String version;

	/** The website url with information about the library. */
	private final String website;

	/** Optional remarks about the usage of the library. */
	private final String remarks;

	/** The license of the library. */
	private ILicense license;

	/** The library descriptor file. */
	private final File descriptorFile;

	/** The bundle this descriptor lies in. */
	private final BundleInfo bundle;

	/** Constructor. */
	public LibraryDescriptor(File descriptorFile, BundleInfo bundle)
			throws IOException {
		this.descriptorFile = descriptorFile;
		this.bundle = bundle;

		Properties props = new Properties();
		props.load(new FileReader(descriptorFile));

		name = props.getProperty("name");
		version = props.getProperty("version");
		website = props.getProperty("website");
		description = props.getProperty("description");
		remarks = props.getProperty("remarks");

		String licenseName = props.getProperty("license");
		license = ELicense.fromName(licenseName);
		if (license == null) {
			String descriptorName = FileSystemUtils
					.getFilenameWithoutExtension(descriptorFile);
			File noticeFile = new File(descriptorFile.getParentFile(),
					descriptorName.concat(".notice"));
			license = CustomLicense.fromProperties(props, noticeFile);
		}
	}

	/**
	 * @return The unique identifier of the descriptor within its bundle, i.e.
	 *         the filename without the .lib extension.
	 */
	public String getId() {
		return FileSystemUtils.getFilenameWithoutExtension(descriptorFile);
	}

	/** @return The name of the library. */
	public String getName() {
		return name;
	}

	/** @return The short description of the library. */
	public String getDescription() {
		return description;
	}

	/** @return The version string of the library. */
	public String getVersion() {
		return version;
	}

	/** @return The website url with information about the library. */
	public String getWebsite() {
		return website;
	}

	/** @return optional remarks about the usage of the library or null. */
	public String getRemarks() {
		return remarks;
	}

	/** @return The license of the library. */
	public ILicense getLicense() {
		return license;
	}

	/** @return The list of all libraries covered by this descriptor. */
	public UnmodifiableSet<File> getLibraries() {
		Set<File> libraries = new HashSet<File>();
		final String descriptorId = getId();
		for (File library : bundle.getLibraries()) {
			if (library.getName().startsWith(descriptorId)) {
				libraries.add(library);
			}
		}
		return CollectionUtils.asUnmodifiable(libraries);
	}

	/** @return The library descriptor property file. */
	public File getDescriptorFile() {
		return descriptorFile;
	}

	/** @returns The bundle containing the descriptor. */
	public BundleInfo getBundle() {
		return bundle;
	}
}