text:
<?php defined('C5_EXECUTE') or die('Access Denied.');

/* @var $this PageView */

$valt = Loader::helper('validation/token');

if ($this->controller->getTask() == 'translate_po') {

    /* @var $section \Concrete\Core\Multilingual\Page\Section\Section */
    ?>

        <a href="<?php echo $controller->action('view'); ?>" class="btn btn-default"><?php echo t('Back to List'); ?>
        <?php echo t('Save to file'); ?>

    <?php

} else {

    if (!is_dir(DIR_LANGUAGES_SITE_INTERFACE) || !is_writable(DIR_LANGUAGES_SITE_INTERFACE)) {
        ?>
<?php echo t('You must create the directory %s and make it writable before you may run this tool. Additionally, all files within this directory must be writable.', DIR_LANGUAGES_SITE_INTERFACE); ?>
<?php
    }
    $nav = Loader::helper('navigation');
    Loader::model('section', 'multilingual');
    $pages = \Concrete\Core\Multilingual\Page\Section\Section::getList();
    $defaultSourceLocale = Config::get('concrete.multilingual.default_source_locale');

    $ch = Core::make('multilingual/interface/flag');
    $dh = Core::make('helper/date');
    if (count($pages) > 0) {
        ?>

                        <?php echo t('Name'); ?>
                        <?php echo t('Locale'); ?>
                        <?php echo t('Completion'); ?>
                        <?php echo t('Last Updated'); ?>

<?php
                        foreach ($pages as $pc) {
                            $pcl = \Concrete\Core\Multilingual\Page\Section\Section::getByID($pc->getCollectionID());
                            ?>

                                <?php echo $ch->getSectionFlagIcon($pc); ?>
                                <a href="<?php echo $nav->getLinkToCollection($pc); ?>"><?php echo $pc->getCollectionName(); ?>
                                <?php
                                    echo $pc->getLocale();
                                    if ($pc->getLocale() != $defaultSourceLocale) {
                                        ?><a href="#" class="icon-link launch-tooltip" title="<?php echo REL_DIR_LANGUAGES_SITE_INTERFACE; ?>/<?php echo $pc->getLocale(); ?>.mo"><?php
                                    }
                                ?>
                                <?php
                                    if ($pc->getLocale() != $defaultSourceLocale) {
                                        $data = $extractor->getSectionSiteInterfaceCompletionData($pc);
                                        ?>

                                            <div class="progress-bar" style="width: <?php echo $data['completionPercentage']; ?>%">

<?php
                                    }
                                ?>
                                <?php
                                    if ($pc->getLocale() != $defaultSourceLocale) {
                                        ?>
                                        <?php echo $data['completionPercentage']; ?>%
                                        -
                                        <?php echo t(/*i18n: %1$s is the partial number, %2$s is the total number. Example: 2 of 3 */'%1$s of %2$s', ''.$data['translatedCount'].'', ''.$data['messageCount'].''); ?>
                                        <?php
                                    }
                                ?>
                                <?php
                                    if ($pc->getLocale() != $defaultSourceLocale) {
                                        if (file_exists(DIR_LANGUAGES_SITE_INTERFACE.'/'.$pc->getLocale().'.mo')) {
                                            echo $dh->formatDateTime(filemtime(DIR_LANGUAGES_SITE_INTERFACE.'/'.$pc->getLocale().'.mo'), true);
                                        } else {
                                            echo t('File not found.');
                                        }
                                    } else {
                                        echo t('N/A');
                                    }
                                ?>
                                <?php
                                if ($pc->getLocale() == $defaultSourceLocale) {
                                    ?>	<?php
                                } else {
                                    ?><a href="<?php echo $this->action('translate_po', $pc->getCollectionID()); ?>" class="icon-link">	<?php
                                }
                                ?>

<?php
                        }
                    ?>

        <?php
        if (is_dir(DIR_LANGUAGES_SITE_INTERFACE) && is_writable(DIR_LANGUAGES_SITE_INTERFACE)) {
            ?>
            <form method="post" action="<?php echo $controller->action('submit'); ?>">

                    <button class="btn btn-default" type="submit" name="action" value="reload"><?php echo t('Reload Strings'); ?></button>
                    <button class="btn btn-default" type="submit" name="action" value="export"><?php echo t('Save to file'); ?></button>
                    <?php echo $valt->output(); ?>
                    <button class="btn btn-danger" type="button" data-dialog="reset" value="reset"><?php echo t('Reset All'); ?></button>

            </form>

<?php
                    $u = new User();
                    if ($u->isSuperUser()) {
                        ?>
                        <form method="post" class="form-stacked" style="padding-left: 0px" action="<?php echo $view->action('reset_languages'); ?>">
                            <?php echo Loader::helper("validation/token")->output('reset_languages'); ?>

<?php echo t('Are you sure? This will remove all translations from all languages, in the database and in your site PO files. This cannot be undone.'); ?>

                        </form>

                            <button class="btn btn-default pull-left" onclick="jQuery.fn.dialog.closeTop()"><?php echo t('Cancel'); ?></button>
                            <button class="btn btn-danger pull-right" onclick="$('#ccm-dialog-reset-languages form').submit()"><?php echo t('Confirm Reset'); ?></button>

                        <?php
                    } else {
                        ?>
<?php echo t('Only the admin user may reset all languages.'); ?>
<?php
                    }
                ?>

            <?php
        }
        ?>

        <?php
    } else {
        ?>
<?php echo t('You have not created any multilingual content sections yet.'); ?>
<?php
    }

}


text:
MLS.homeCompatibility = (function() {
	var hashLoaded = false,
        options = {
            callback: function () {},
            container: null,
            results: null
        },

        pub = {
			init: function(o) {
				options = $jQ.extend(options, {
					endpoint: MLS.ajax.endpoints.COMPATIBILITY_FILTER_NEW
				}, o);

				$jQ(options.container).find('#brand').unbind('click', pub.compatibilitySearch).on('click', pub.compatibilitySearch);
			},

			currentNavState: function ($e) {
				if ($e.is('select#device') || $e.is('select#brand')) {
					return MLS.util.getParamsFromUrl($e.val().split("?")[0]) + "&Ntt=*";
				}

				var keyVal = $jQ('#searchText').val() || "",
					servletPath = $jQ('#servletPath').val() || "",
					queryString = $jQ('#queryString').val() || "",
					slicePath = "",
					queryStringFinal = "";

				if (queryString == "") {
					slicePath = "/" + servletPath.split("/")[servletPath.split("/").length-1];
					queryString = slicePath;
				}
				console.log("home-compat currentNavState");
				passParam = queryString.split("&")[0];
				queryStringFinal = $e.val() + "&Ntt=" + $jQ.trim(keyVal) + "*";
				return queryStringFinal;
			},

			lastRequest: null,

			compatibilitySearch: function (e) {
				if (!$jQ(this).data("stoptrigger")) {

					var timeout = null;

					if (MLS.homeCompatibility.lastRequest != null)
					{
						MLS.homeCompatibility.lastRequest.error(function() {
							// do nothing, aborting.
						});
						MLS.homeCompatibility.lastRequest.abort();
						MLS.homeCompatibility.lastRequest = null;
					}

					console.log("endpoint := ",options.endpoint);

	                MLS.homeCompatibility.lastRequest = MLS.ajax.sendRequest(
			            options.endpoint,

			            pub.currentNavState($jQ(this)),

			            function (data) {
			            	MLS.homeCompatibility.lastRequest = null;

			            	if (data.hasOwnProperty('error') && data.error.responseHTML != "") {
					    	    return MLS.modal.open(data.error ? data.error.responseHTML : null, false, true, true);
					        }

					        if (timeout != null)
					        {
					        	clearTimeout(timeout);
					        	timeout = null;
					        }

					        if (data.success.responseHTML == "") {

					        }

					        /*var error = $jQ("#device-not-found");
							if (data.success.responseHTML == "")
					        {
                                error.fadeIn().find(".tooltip-close").unbind('click').click(function() {
                                    error.fadeOut();
                                    if (timeout != null)
							        {
							        	clearTimeout(timeout);
							        	timeout = null;
							        }
                                    return false;
                                });

                                timeout = setTimeout(function() {
                                    error.fadeOut();
                                	timeout = null;
					            }, 4000);
					        } else {
					        	if (timeout != null)
						        {
						        	clearTimeout(timeout);
						        	timeout = null;
						        }
					        	error.hide();
					        }*/
					        var $r = $jQ(options.results),
			            		v = null;
			            	$r.find('#device').html(data.success.responseHTML);
			            	$r.show();
							$jQ("#device").select2("open");
			            }
		        	);
				}
            },

            updateResults: function(r)
            {
            	options.callback(r);
            }
		};

	return pub;
} ());

redpajama_set_name: RedPajamaGithub


text:
Rest service with async EBJ method for sending mails.

## Build

`./gradlew clean wildfly-swarm-package`

## Run

`java -jar ./build/libs/gradle-mail-swarm.jar`

## Configuration

By default, this will try to connect to an SMTP server at
`localhost:25`. You can override this any of three ways:

* Edit `build.gradle` and change the `smtp.*` properties, then rebuild
  the swarm jar. This will embed the properties in the jar itself.
* Pass `smtp.*` properties to gradle when building the jar:
  `./gradlew clean wildfly-swarm-package -Dsmtp.host=foo` This will
  also embed the properties in the jar itself.
* Pass properties to the application at runtime:
  `java -Dsmtp.host=foo -jar ./build/libs/gradle-mail-swarm.jar`
  This will override the property that was embedded in the jar.


text:
package de.simu.decomap.config.interfaces.pollresultprocessor;

import org.aeonbits.owner.Config.Sources;

import de.simu.decomap.config.converter.PollResultFilterConverter;
import de.simu.decomap.messaging.resultprocessor.PollResultFilter;

@Sources("file:${filename}")
public interface IptablesPollResultProcessorConfig extends PollResultProcessorConfig {

	@Key("allowprocessor")
	@ConverterClass(PollResultFilterConverter.class)
	PollResultFilter[] allowProcessorFilters();

	@Key("startscript")
	String iptablesStartscript();
}


text:
package org.neo4j.kernel.impl.api.index;

import java.util.concurrent.Future;

import org.neo4j.kernel.api.index.IndexConfiguration;
import org.neo4j.kernel.api.index.IndexDescriptor;
import org.neo4j.kernel.api.index.IndexReader;
import org.neo4j.kernel.api.index.IndexUpdater;
import org.neo4j.kernel.api.index.SchemaIndexProvider;

import static org.neo4j.helpers.FutureAdapter.VOID;

public abstract class AbstractSwallowingIndexProxy implements IndexProxy
{
    private final IndexDescriptor descriptor;
    private final SchemaIndexProvider.Descriptor providerDescriptor;
    private final IndexPopulationFailure populationFailure;
    private final IndexConfiguration configuration;

    public AbstractSwallowingIndexProxy( IndexDescriptor descriptor, SchemaIndexProvider.Descriptor providerDescriptor,
            IndexPopulationFailure populationFailure, IndexConfiguration configuration )
    {
        this.descriptor = descriptor;
        this.providerDescriptor = providerDescriptor;
        this.populationFailure = populationFailure;
        this.configuration = configuration;
    }

    @Override
    public IndexPopulationFailure getPopulationFailure()
    {
        return populationFailure;
    }

    @Override
    public void start()
    {
        String message = "Unable to start index, it is in a " + getState().name() + " state.";
        throw new UnsupportedOperationException( message + ", caused by: " + getPopulationFailure() );
    }

    @Override
    public IndexUpdater newUpdater( IndexUpdateMode mode )
    {
        return SwallowingIndexUpdater.INSTANCE;
    }

    @Override
    public void force()
    {
    }

    @Override
    public void flush()
    {
    }

    @Override
    public IndexDescriptor getDescriptor()
    {
        return descriptor;
    }

    @Override
    public SchemaIndexProvider.Descriptor getProviderDescriptor()
    {
        return providerDescriptor;
    }

    @Override
    public Future<Void> close()
    {
        return VOID;
    }

    @Override
    public IndexReader newReader()
    {
        throw new UnsupportedOperationException();
    }

    @Override
    public IndexConfiguration config()
    {
        return configuration;
    }
}


text:
    ((void)(addr), (void)(size))
#define ASAN_UNPOISON_MEMORY_REGION(addr, size) \
    ((void)(addr), (void)(size))
#endif

#if defined(LEAK_SANITIZER)
#include <sanitizer/lsan_interface.h>
#else
#define __lsan_register_root_region(addr, size) ((void)(addr), (void)(size))
#define __lsan_unregister_root_region(addr, size) ((void)(addr), (void)(size))
#endif

// TODO(sof): Have to handle (ADDRESS_SANITIZER && _WIN32) differently as it
// uses both Clang (which supports the __attribute__ syntax) and CL (which doesn't)
// as long as we use "clang-cl /fallback". This shouldn't be needed when Clang
// handles all the code without falling back to CL.
#if defined(ADDRESS_SANITIZER) && (!OS(WIN) || COMPILER(CLANG))
#define NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address))
#if ENABLE(LAZY_SWEEPING)
#define NO_LAZY_SWEEP_SANITIZE_ADDRESS NO_SANITIZE_ADDRESS
#else
#define NO_LAZY_SWEEP_SANITIZE_ADDRESS
#endif
#else
#define NO_SANITIZE_ADDRESS
#define NO_LAZY_SWEEP_SANITIZE_ADDRESS
#endif

#endif // WTF_AddressSanitizer_h


text:
#include "transport_manager/bluetooth/bluetooth_device_scanner.h"

#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <sstream>
#include <vector>
#include "transport_manager/bluetooth/bluetooth_device.h"
#include "transport_manager/bluetooth/bluetooth_transport_adapter.h"

#include "utils/logger.h"
#include "utils/threads/thread.h"

namespace transport_manager {
namespace transport_adapter {

SDL_CREATE_LOG_VARIABLE("TransportManager")

namespace {
char* SplitToAddr(char* dev_list_entry) {
  char* bl_address = strtok(dev_list_entry, "()");
  if (bl_address != NULL) {
    bl_address = strtok(NULL, "()");
    return bl_address;
  } else {
    return NULL;
  }
}

int FindPairedDevs(std::vector<bdaddr_t>* result) {
  SDL_LOG_TRACE("enter. result address: " << result);
  DCHECK(result != NULL);

  const char* cmd = "bt-device -l";

  FILE* pipe = popen(cmd, "r");
  if (!pipe) {
    SDL_LOG_TRACE("exit -1. Condition: !pipe");
    return -1;
  }
  char* buffer = new char[1028];
  size_t counter = 0;
  while (fgets(buffer, 1028, pipe) != NULL) {
    if (0 < counter++) {  //  skip first line
      char* bt_address = SplitToAddr(buffer);
      if (bt_address) {
        bdaddr_t address;
        str2ba(bt_address, &address);
        result->push_back(address);
      }
    }
    delete[] buffer;
    buffer = new char[1028];
  }
  int status = pclose(pipe);
  SDL_LOG_TRACE("exit with 0");
  delete[] buffer;
  return status;
}
}  //  namespace

BluetoothDeviceScanner::BluetoothDeviceScanner(
    TransportAdapterController* controller,
    bool auto_repeat_search,
    int auto_repeat_pause_sec)
    : controller_(controller)
    , thread_(NULL)
    , shutdown_requested_(false)
    , ready_(true)
    , device_scan_requested_(false)
    , device_scan_requested_lock_()
    , terminate_lock_()
    , device_scan_requested_cv_()
    , auto_repeat_search_(auto_repeat_search)
    , auto_repeat_pause_sec_(auto_repeat_pause_sec) {
  uint8_t smart_device_link_service_uuid_data[] = {0x93,
                                                   0x6D,
                                                   0xA0,
                                                   0x1F,
                                                   0x9A,
                                                   0xBD,
                                                   0x4D,
                                                   0x9D,
                                                   0x80,
                                                   0xC7,
                                                   0x02,
                                                   0xAF,
                                                   0x85,
                                                   0xC8,
                                                   0x22,
                                                   0xA8};
  sdp_uuid128_create(&smart_device_link_service_uuid_,
                     smart_device_link_service_uuid_data);
  thread_ = threads::CreateThread("BT Device Scanner",
                                  new BluetoothDeviceScannerDelegate(this));
}

BluetoothDeviceScanner::BluetoothDeviceScanner(
    TransportAdapterController* controller,
    bool auto_repeat_search,
    int auto_repeat_pause_sec,
    const uint8_t* smart_device_link_service_uuid_data)
    : controller_(controller)
    , thread_(NULL)
    , shutdown_requested_(false)
    , ready_(true)
    , device_scan_requested_(false)
    , device_scan_requested_lock_()
    , terminate_lock_()
    , device_scan_requested_cv_()
    , auto_repeat_search_(auto_repeat_search)
    , auto_repeat_pause_sec_(auto_repeat_pause_sec) {
  sdp_uuid128_create(&smart_device_link_service_uuid_,
                     smart_device_link_service_uuid_data);
  thread_ = threads::CreateThread("BT Device Scanner",
                                  new BluetoothDeviceScannerDelegate(this));
}

BluetoothDeviceScanner::~BluetoothDeviceScanner() {
  thread_->Stop(threads::Thread::kThreadSoftStop);
  delete thread_->GetDelegate();
  threads::DeleteThread(thread_);
}

bool BluetoothDeviceScanner::IsInitialised() const {
  return thread_ && thread_->IsRunning();
}

void BluetoothDeviceScanner::UpdateTotalDeviceList() {
  SDL_LOG_AUTO_TRACE();
  DeviceVector devices;
  devices.insert(devices.end(),
                 paired_devices_with_sdl_.begin(),
                 paired_devices_with_sdl_.end());
  controller_->SearchDeviceDone(devices);
}

void BluetoothDeviceScanner::DoInquiry() {
  SDL_LOG_AUTO_TRACE();

  const int device_id = hci_get_route(0);
  if (device_id < 0) {
    SDL_LOG_INFO("HCI device is not available");
    shutdown_requested_ = true;
    controller_->SearchDeviceFailed(SearchDeviceError());
    return;
  }

  int device_handle = hci_open_dev(device_id);
  if (device_handle < 0) {
    controller_->SearchDeviceFailed(SearchDeviceError());
    return;
  }

  if (paired_devices_.empty()) {
    SDL_LOG_INFO("Searching for paired devices.");
    if (-1 == FindPairedDevs(&paired_devices_)) {
      SDL_LOG_ERROR("Failed to retrieve list of paired devices.");
      controller_->SearchDeviceFailed(SearchDeviceError());
    }
  }

  SDL_LOG_INFO("Check rfcomm channel on " << paired_devices_.size()
                                          << " paired devices.");

  CheckSDLServiceOnDevices(
      paired_devices_, device_handle, &paired_devices_with_sdl_);
  const bool new_connect =
      paired_devices_with_sdl_.end() !=
      std::find_if(paired_devices_with_sdl_.begin(),
                   paired_devices_with_sdl_.end(),
                   [](DeviceSptr devicePtr) {
                     return devicePtr->connection_status() !=
                            ConnectionStatus::CONNECTED;
                   });
  if (new_connect) {
    UpdateTotalDeviceList();
  }

  controller_->FindNewApplicationsRequest();

  close(device_handle);
}

void BluetoothDeviceScanner::CheckSDLServiceOnDevices(
    const std::vector<bdaddr_t>& bd_addresses,
    int device_handle,
    DeviceVector* discovered_devices) {
  SDL_LOG_TRACE("enter. bd_addresses: "
                << &bd_addresses << ", device_handle: " << device_handle
                << ", discovered_devices: " << discovered_devices);
  std::vector<RfcommChannelVector> sdl_rfcomm_channels =
      DiscoverSmartDeviceLinkRFCOMMChannels(bd_addresses);

  for (size_t i = 0; i < bd_addresses.size(); ++i) {
    if (sdl_rfcomm_channels[i].empty()) {
      continue;
    }

    const bdaddr_t& bd_address = bd_addresses[i];
    char deviceName[256];
    int hci_read_remote_name_ret =
        hci_read_remote_name(device_handle,
                             &bd_address,
                             sizeof(deviceName) / sizeof(deviceName[0]),
                             deviceName,
                             0);

    if (hci_read_remote_name_ret != 0) {
      SDL_LOG_ERROR_WITH_ERRNO("hci_read_remote_name failed");
      int name_len = sizeof(deviceName) / sizeof(deviceName[0]);
      strncpy(deviceName,
              BluetoothDevice::GetUniqueDeviceId(bd_address).c_str(),
              name_len - 1);
      deviceName[name_len - 1] = '\0';
    }

    auto it_device =
        std::find_if(discovered_devices->begin(),
                     discovered_devices->end(),
                     [bd_address](DeviceSptr device) {
                       return device->unique_device_id() ==
                              BluetoothDevice::GetUniqueDeviceId(bd_address);
                     });

    const bool is_new_device = (it_device == discovered_devices->end());
    const bool is_new_rfcomm_channel =
        !is_new_device && (*it_device)->GetApplicationList().size() !=
                              sdl_rfcomm_channels[i].size();
    if (is_new_device || is_new_rfcomm_channel) {
      if (!is_new_device) {
        discovered_devices->erase(it_device);
      }
      auto bluetooth_device = std::make_shared<BluetoothDevice>(
          bd_address, deviceName, sdl_rfcomm_channels[i]);
      if (bluetooth_device) {
        SDL_LOG_INFO("Bluetooth device created successfully");
        discovered_devices->push_back(bluetooth_device);
      } else {
        SDL_LOG_WARN("Can't create bluetooth device " << deviceName);
      }
    }
  }
  SDL_LOG_TRACE("exit");
}

std::vector<BluetoothDeviceScanner::RfcommChannelVector>
BluetoothDeviceScanner::DiscoverSmartDeviceLinkRFCOMMChannels(
    const std::vector<bdaddr_t>& device_addresses) {
  SDL_LOG_TRACE("enter device_addresses: " << &device_addresses);
  const size_t size = device_addresses.size();
  std::vector<RfcommChannelVector> result(size);

  static const int attempts = 4;
  static const int attempt_timeout = 5;
  std::vector<bool> processed(size, false);
  unsigned processed_count = 0;
  for (int nattempt = 0; nattempt < attempts; ++nattempt) {
    for (size_t i = 0; i < size; ++i) {
      if (processed[i]) {
        continue;
      }
      const bool final = DiscoverSmartDeviceLinkRFCOMMChannels(
          device_addresses[i], &result[i]);
      if (final) {
        processed[i] = true;
        ++processed_count;
      }
    }
    if (++processed_count >= size) {
      break;
    }
    sleep(attempt_timeout);
  }
  SDL_LOG_TRACE(
      "exit with vector<RfcommChannelVector>: size = " << result.size());
  return result;
}

bool BluetoothDeviceScanner::DiscoverSmartDeviceLinkRFCOMMChannels(
    const bdaddr_t& device_address, RfcommChannelVector* channels) {
  SDL_LOG_TRACE("enter. device_address: " << &device_address
                                          << ", channels: " << channels);
  static bdaddr_t any_address = {{0, 0, 0, 0, 0, 0}};

  sdp_session_t* sdp_session = sdp_connect(
      &any_address, &device_address, SDP_RETRY_IF_BUSY | SDP_WAIT_ON_CLOSE);
  if (sdp_session == 0) {
    bool result = !(errno == 31 || errno == 16 || errno == 117 || errno == 114);
    if (result) {
      SDL_LOG_TRACE("exit with TRUE. Condition: sdp_session == 0");
    } else {
      SDL_LOG_TRACE("exit with FALSE. Condition: sdp_session == 0");
    }
    return result;
  }

  sdp_list_t* search_list =
      sdp_list_append(0, &smart_device_link_service_uuid_);
  uint32_t range = 0x0000ffff;
  sdp_list_t* attr_list = sdp_list_append(0, &range);
  sdp_list_t* response_list = 0;

  if (0 == sdp_service_search_attr_req(sdp_session,
                                       search_list,
                                       SDP_ATTR_REQ_RANGE,
                                       attr_list,
                                       &response_list)) {
    for (sdp_list_t* r = response_list; 0 != r; r = r->next) {
      sdp_record_t* sdp_record = static_cast<sdp_record_t*>(r->data);
      sdp_list_t* proto_list = 0;

      if (0 == sdp_get_access_protos(sdp_record, &proto_list)) {
        for (sdp_list_t* p = proto_list; 0 != p; p = p->next) {
          sdp_list_t* pdsList = static_cast<sdp_list_t*>(p->data);

          for (sdp_list_t* pds = pdsList; 0 != pds; pds = pds->next) {
            sdp_data_t* sdpData = static_cast<sdp_data_t*>(pds->data);
            int proto = 0;

            for (sdp_data_t* d = sdpData; 0 != d; d = d->next) {
              switch (d->dtd) {
                case SDP_UUID16:
                case SDP_UUID32:
                case SDP_UUID128:
                  proto = sdp_uuid_to_proto(&d->val.uuid);
                  break;

                case SDP_UINT8:
                  if (RFCOMM_UUID == proto) {
                    channels->push_back(d->val.uint8);
                  }
                  break;
              }
            }
          }

          sdp_list_free(pdsList, 0);
        }

        sdp_list_free(proto_list, 0);
      }
    }
  }
  sdp_list_free(search_list, 0);
  sdp_list_free(attr_list, 0);
  sdp_list_free(response_list, 0);
  sdp_close(sdp_session);

  if (!channels->empty()) {
    SDL_LOG_INFO("channels not empty");
    std::stringstream rfcomm_channels_string;

    for (RfcommChannelVector::const_iterator it = channels->begin();
         it != channels->end();
         ++it) {
      if (it != channels->begin()) {
        rfcomm_channels_string << ", ";
      }
      rfcomm_channels_string << static_cast<uint32_t>(*it);
    }

    SDL_LOG_INFO("SmartDeviceLink service was discovered on device "
                 << BluetoothDevice::GetUniqueDeviceId(device_address)
                 << " at channel(s): " << rfcomm_channels_string.str().c_str());
  } else {
    SDL_LOG_INFO("SmartDeviceLink service was not discovered on device "
                 << BluetoothDevice::GetUniqueDeviceId(device_address));
  }
  SDL_LOG_TRACE("exit with TRUE");
  return true;
}

void BluetoothDeviceScanner::Thread() {
  SDL_LOG_AUTO_TRACE();
  ready_ = true;
  if (auto_repeat_search_) {
    while (!shutdown_requested_) {
      DoInquiry();
      {
        sync_primitives::AutoLock auto_lock(device_scan_requested_lock_);
        device_scan_requested_ = false;
      }
      TimedWaitForDeviceScanRequest();
    }
  } else {  // search only on demand
    while (true) {
      {
        sync_primitives::AutoLock auto_lock(device_scan_requested_lock_);
        while (!(device_scan_requested_ || shutdown_requested_)) {
          device_scan_requested_cv_.Wait(auto_lock);
        }
      }
      if (shutdown_requested_) {
        break;
      }
      DoInquiry();
      device_scan_requested_ = false;
    }
  }
}

void BluetoothDeviceScanner::TimedWaitForDeviceScanRequest() {
  SDL_LOG_AUTO_TRACE();

  if (auto_repeat_pause_sec_ == 0) {
    SDL_LOG_TRACE("exit. Condition: auto_repeat_pause_sec_ == 0");
    return;
  }

  if (shutdown_requested_) {
    SDL_LOG_INFO("Bluetooth scanner Condition: shutdown_requested_ == true");
    return;
  }

  {
    sync_primitives::AutoLock auto_lock(device_scan_requested_lock_);
    while (!(device_scan_requested_ || shutdown_requested_)) {
      if (!terminate_lock_.Try()) {
        // Lock is taken by terminate thread, return
        return;
      }
      const sync_primitives::ConditionalVariable::WaitStatus wait_status =
          device_scan_requested_cv_.WaitFor(auto_lock,
                                            auto_repeat_pause_sec_ * 1000);
      terminate_lock_.Release();
      if (wait_status == sync_primitives::ConditionalVariable::kTimeout) {
        SDL_LOG_INFO("Bluetooth scanner timeout, performing scan");
        device_scan_requested_ = true;
      }
    }
  }
}

TransportAdapter::Error BluetoothDeviceScanner::Init() {
  SDL_LOG_AUTO_TRACE();
  if (!thread_->Start()) {
    SDL_LOG_ERROR("Bluetooth device scanner thread start failed");
    return TransportAdapter::FAIL;
  }
  SDL_LOG_INFO("Bluetooth device scanner thread started");
  return TransportAdapter::OK;
}

void BluetoothDeviceScanner::Terminate() {
  SDL_LOG_AUTO_TRACE();
  if (shutdown_requested_)
    return;
  shutdown_requested_ = true;
  if (thread_) {
    device_scan_requested_cv_.NotifyOne();
    {
      sync_primitives::AutoLock auto_lock(device_scan_requested_lock_);
      device_scan_requested_ = false;
    }
    sync_primitives::AutoLock auto_lock(terminate_lock_);
    SDL_LOG_INFO("Waiting for bluetooth device scanner thread termination");
    thread_->Stop(threads::Thread::kThreadStopDelegate);
    SDL_LOG_INFO("Bluetooth device scanner thread stopped");
  }
}

TransportAdapter::Error BluetoothDeviceScanner::Scan() {
  SDL_LOG_AUTO_TRACE();
  if ((!IsInitialised()) || shutdown_requested_) {
    SDL_LOG_WARN("BAD_STATE");
    return TransportAdapter::BAD_STATE;
  }
  if (auto_repeat_pause_sec_ == 0) {
    return TransportAdapter::OK;
  }
  TransportAdapter::Error ret = TransportAdapter::OK;

  sync_primitives::AutoLock auto_lock(device_scan_requested_lock_);
  if (!device_scan_requested_) {
    SDL_LOG_TRACE("Requesting device Scan");
    device_scan_requested_ = true;
    device_scan_requested_cv_.NotifyOne();
  } else {
    ret = TransportAdapter::BAD_STATE;
    SDL_LOG_WARN("BAD_STATE");
  }
  return ret;
}

BluetoothDeviceScanner::BluetoothDeviceScannerDelegate::
    BluetoothDeviceScannerDelegate(BluetoothDeviceScanner* scanner)
    : scanner_(scanner) {}

void BluetoothDeviceScanner::BluetoothDeviceScannerDelegate::threadMain() {
  SDL_LOG_AUTO_TRACE();
  DCHECK(scanner_);
  scanner_->Thread();
}

}  // namespace transport_adapter
}  // namespace transport_manager


text:
* Author(s): [Authors]
* Date: [yyyy-mm-dd]
* Relevant Issue: [Issue URL]
---

# TL;DR

Required.

TL;DR stands for *too long; didn't read*, so make sure to put only the most essential information here and keep it short.

# Background

Highly recommended.

Your audiences understand your proposal better if they can understand the problem domain first.

# Goals

Required.

* Be very specific about the goals this RFC is aiming for: Given the problem definition, which aspects will be discussed/resolved in this RFC?
* You should almost always write this section as a bullet list.
* To further help the readers focus on the goals, you can add an additional *Non-Goals* section below.

# Detailed Design

Required.

Explain your concrete design with sufficient details in this section. Consider including materials like sample API code snippet, pseudo code of the algorithm, system flowchart, etc. Make sure to think critically and discuss both the pros and cons of the design. If applicable, please place image or other forms of asset files under [`res/`](res/).

While this section would usually comprise the major portion of the RFC, you should still strive for keeping it succinct. Present your ideas clearly, and no more.

## Risks

Optional.

## Testing plan

Optional.

## Migration plan

Optional.

# Alternatives

Highly recommended.

A great solution often stands out from a few good ones.

# FAQ

Optional.

Any questions you foresee from your readers.

# References

Optional.

A list of materials providing additional context.


text:
class AddTwitterToUsers < ActiveRecord::Migration
  def change
    add_column :users, :twitter, :string
  end
end


text:
using OSIsoft.AF;
using OSIsoft.AF.Asset;
using OSIsoft.AF.Data;
using OSIsoft.AF.PI;
using OSIsoft.AF.Time;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace pieventsnovo
{
    public class ExecuteCommand
    {
        internal void Execute(string command, PIPointList pointsList, AFTime st, AFTime et,
                               AFTimeSpan summaryDuration, string[] times, string addlparam1, PIServer myServer)
        {
            try
            {
                Console.WriteLine();
                switch (command)
                {
                    case "snap":
                        {
                            Snap(pointsList);
                            break;
                        }
                    case "arclist":
                        {
                            Arclist(pointsList, st, et, addlparam1);
                            break;
                        }
                    case "plot":
                        {
                            Plot(pointsList, st, et, addlparam1);
                            break;
                        }
                    case "interp":
                        {
                            Interpolated(pointsList, st, et, summaryDuration, addlparam1);
                            break;
                        }
                    case "summaries":
                        {
                            Summaries(pointsList, ref st, ref et, addlparam1);
                            break;
                        }
                    case "update":
                    case "annotate":
                    case "uploadcsv":
                        {
                            UploadAnnotate(command, pointsList, times, addlparam1);
                            break;
                        }
                    case "downloadcsv":
                        {
                            // Clamp pageSize
                            int Clamp(int value, int min, int max, int def)
                            {
                                if (value == 0) return def;
                                else return (value < min) ? min : (value > max) ? max : value;
                            }
                            if (!Int32.TryParse(addlparam1, out int pageSize))
                                pageSize = 0;
                            pageSize = Clamp(pageSize, GlobalConfig.DwnPageSizeMin, GlobalConfig.DwnPageSizeMax,
                                                                                GlobalConfig.DwnPageSizeDef);
                            var sb = new StringBuilder();
                            sb.AppendLine("Downloading archive data into csv file(s)");
                            sb.AppendLine(new string('-', 45));
                            sb.AppendLine($"Download PageSize: {pageSize:N0}");
                            string folder = GlobalConfig.OutputFolder;
                            if (!String.IsNullOrEmpty(folder))
                            {
                                if (!Directory.Exists(folder))
                                {
                                    throw new Exception("Directory for output does not exist");
                                }
                            }
                            else
                            {
                                folder = Directory.GetCurrentDirectory();
                            }
                            sb.AppendLine($"Output directory: {folder}");
                            sb.AppendLine();
                            sb.AppendLine("Extracting data set(s) ...");
                            Console.Write(sb.ToString());
                            try
                            {
                                var ioPermission = new FileIOPermission(FileIOPermissionAccess.Write, folder);
                            }
                            catch (SecurityException sx)
                            {
                                throw new Exception("No write permissions " + sx.Message);
                            }

                            Parallel.ForEach(pointsList, (point) =>
                            {
                               var csvGen = new DownloadCSVFile(point, st, et, pageSize, folder);
                               csvGen.GenerateFile();
                            });
                            Console.WriteLine();
                            break;
                        }
                    case "delete":
                        {
                            Delete(pointsList, st, et, addlparam1, myServer);
                            break;
                        }
                    case "pointchanges":
                        {
                            PointChanges(pointsList, myServer);
                            break;
                        }
                    case "sign,t":
                        {
                            Dictionary<PIPoint, int> errPoints = pointsList.ToDictionary(key => key, value => 0);
                            //if (Int32.TryParse(myServer.ServerVersion.Substring(4, 3), out int srvbuild) && srvbuild >= 395);
                            if (myServer.Supports(PIServerFeature.TimeSeriesDataPipe))
                            {
                                PIDataPipe timeSeriesDatapipe = new PIDataPipe(AFDataPipeType.TimeSeries);
                                Console.WriteLine("Signing up for TimeSeries events");
                                var listResults = timeSeriesDatapipe.AddSignupsWithInitEvents(pointsList);
                                if (listResults != null)
                                {
                                    foreach (var e in listResults.Errors)
                                    {
                                        Console.WriteLine($"Failed timeseries signup: {e.Key}, {e.Value.Message}");
                                        errPoints[e.Key]++;
                                    }
                                    foreach (var ep in errPoints)
                                    {
                                        if (ep.Value >= 1) pointsList.Remove(ep.Key);
                                    }
                                    if (pointsList.Count == 0)
                                    {
                                        Console.WriteLine("No more valid PI Points available to continue");
                                        if (timeSeriesDatapipe != null)
                                        {
                                            timeSeriesDatapipe.Close();
                                            timeSeriesDatapipe.Dispose();
                                        }
                                        Console.WriteLine();
                                        return;
                                    }
                                }
                                Console.WriteLine(new string('-', 45));
                                foreach (var result in listResults.Results)
                                {
                                    var v = result.Value;
                                    Console.WriteLine($"Tms, {v.PIPoint.Name,-12}, {v.Timestamp}, {v.Value}, {{{result.Action}, {DateTime.Now}}}");
                                }
                                timeSeriesDatapipe.Subscribe(new DataPipeObserver("Tms", listResults.Count));

                                //Fetch timeseries events till user termination
                                while (!GlobalConfig.CancelSignups)
                                {
                                    timeSeriesDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents);
                                    Thread.Sleep(GlobalConfig.PipeCheckFreq);
                                }
                                Console.WriteLine("Cancelling signups ...");
                                if (timeSeriesDatapipe != null)
                                {
                                    timeSeriesDatapipe.Close();
                                    timeSeriesDatapipe.Dispose();
                                }
                            }
                            else
                            {
                                Console.WriteLine($"Time series not supported in Archive version {myServer.ServerVersion}");
                            }
                            break;
                        }
                    case "sign,as":
                    case "sign,sa":
                    case "sign,a":
                    case "sign,s":
                        {
                            bool snapSubscribe = false;
                            bool archSubscribe = false;
                            PIDataPipe snapDatapipe = null;
                            PIDataPipe archDatapipe = null;
                            Dictionary<PIPoint, int> errPoints = pointsList.ToDictionary(key => key, value => 0);
                            if (command.Substring(5).Contains("s"))
                            {
                                snapSubscribe = true;
                                snapDatapipe = new PIDataPipe(AFDataPipeType.Snapshot);
                                Console.WriteLine("Signing up for Snapshot events");
                                var errs = snapDatapipe.AddSignups(pointsList);
                                if (errs != null)
                                {
                                    foreach (var e in errs.Errors)
                                    {
                                        Console.WriteLine($"Failed snapshot signup: {e.Key}, {e.Value.Message}");
                                        errPoints[e.Key]++;
                                    }
                                }
                                snapDatapipe.Subscribe(new DataPipeObserver("Snp", 0));
                            }
                            if (command.Substring(5).Contains("a"))
                            {
                                archSubscribe = true;
                                archDatapipe = new PIDataPipe(AFDataPipeType.Archive);
                                Console.WriteLine("Signing up for Archive events");
                                var errs = archDatapipe.AddSignups(pointsList);
                                if (errs != null)
                                {
                                    foreach (var e in errs.Errors)
                                    {
                                        Console.WriteLine($"Failed archive signup: {e.Key}, {e.Value.Message}");
                                        errPoints[e.Key]++;
                                    }
                                }
                                archDatapipe.Subscribe(new DataPipeObserver("Arc", 0));
                            }

                            //remove unsubscribable points
                            int errorLimit = snapSubscribe ? 1 : 0;
                            if (archSubscribe) errorLimit++;
                            foreach (var ep in errPoints)
                            {
                                if (ep.Value >= errorLimit)
                                    pointsList.Remove(ep.Key);
                            }
                            if (pointsList.Count == 0)
                            {
                                Console.WriteLine("No more valid PI Points available to continue");
                                if (snapDatapipe != null)
                                {
                                    snapDatapipe.Close();
                                    snapDatapipe.Dispose();
                                }
                                if (archDatapipe != null)
                                {
                                    archDatapipe.Close();
                                    archDatapipe.Dispose();
                                }
                                Console.WriteLine();
                                return;
                            }
                            Console.WriteLine("Subscribed Points (current value): ");
                            //foreach (var p in pointsList)
                            //{
                            //    Console.WriteLine($"{p.Name,-12}, {p.EndOfStream().Timestamp}, {p.EndOfStream()}");
                            //}
                            AFListResults<PIPoint, AFValue> results = pointsList.EndOfStream();
                            if (results.HasErrors)
                            {
                                foreach (var e in results.Errors)
                                    Console.WriteLine($"{e.Key}: {e.Value}");
                            }
                            foreach (var v in results.Results)
                            {
                                if (!results.Errors.ContainsKey(v.PIPoint))
                                {
                                    Console.WriteLine($"{v.PIPoint.Name,-12}, {v.Timestamp}, {v.Value}");
                                }
                            }
                            Console.WriteLine(new string('-', 45));

                            //Fetch events from the data pipes
                            while (!GlobalConfig.CancelSignups)
                            {
                                if (snapSubscribe)
                                    snapDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents1);
                                if (archSubscribe)
                                    archDatapipe.GetObserverEvents(GlobalConfig.PipeMaxEvtCount, out bool hasMoreEvents2);
                                Thread.Sleep(GlobalConfig.PipeCheckFreq);
                            }
                            Console.WriteLine("Cancelling signups ...");
                            if (snapDatapipe != null)
                            {
                                snapDatapipe.Close();
                                snapDatapipe.Dispose();
                            }
                            if (archDatapipe != null)
                            {
                                archDatapipe.Close();
                                archDatapipe.Dispose();
                            }
                        }
                        break;
                }
            }
            catch
            {
                throw;
            }
        }

        private static void PointChanges(PIPointList pointsList, PIServer myServer)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("Monitoring PI Point Changes");

            // Cookie used to get changes since the last call
            PIPointChangesCookie cookie = null;
            // Used to serialize / deserialize the cookie
            var formatter = new BinaryFormatter();
            // File used to persist the cookie while the process is not running.
            FileStream cookieFile = null;
            try
            {
                if (File.Exists("cookie.dat"))
                {
                    using (cookieFile = new FileStream("cookie.dat", FileMode.Open))
                    {
                        // Try to read the cookie from the file
                        cookie = (PIPointChangesCookie)formatter.Deserialize(cookieFile);
                        sb.AppendLine("Previously cached cookie file read");
                        cookieFile.Close();
                    }
                }
            }
            catch (FileNotFoundException ex) //should not hit
            {
                throw new FileNotFoundException("Cookie has never been persisted " + ex.Message);
            }
            catch (SerializationException ex)
            {
                throw new SerializationException("Cookie could not be read " + ex.Message);

            }
            catch (SecurityException ex)
            {
                throw new SecurityException("No permission to read cookie file " + ex.Message);
            }
            catch (IOException ex)
            {
                throw new IOException("I/O Exception " + ex.Message);
            }
            sb.AppendLine("Point Name (Point Id)");
            sb.AppendLine(new string('-', 45));
            pointsList.ToList().ForEach(p => sb.AppendLine($"{p.Name} ({p.ID})"));
            sb.AppendLine();
            Console.Write(sb.ToString());

            // If the cookie is null, initialize it to start monitoring changes
            if (cookie is null)
                myServer.FindChangedPIPoints(GlobalConfig.MaxPointChange, null, out cookie, pointsList);

            //check version if IsRename is supported in AFSDK 2.10+
            bool isRenameSupported = false;
            var assembly = AppDomain.CurrentDomain.GetAssemblies().First(x => x.GetName().Name == "OSIsoft.AFSDK");
            var pdtversionstring = FileVersionInfo.GetVersionInfo(new Uri(assembly.CodeBase).LocalPath).ProductVersion;
            if (Version.TryParse(pdtversionstring, out Version result1) && Version.TryParse("2.10", out Version result2))
                if (result1.CompareTo(result2) >= 0) // https://msdn.microsoft.com/en-us/library/s3bf0xb2(v=vs.110).aspx
                    isRenameSupported = true;

            while (!GlobalConfig.CancelSignups)
            {
                // Log changes that have occurred since the last call
                IList<PIPointChangeInfo> changes = myServer.FindChangedPIPoints(GlobalConfig.MaxPointChange,
                                                                                cookie, out cookie, pointsList);
                if (!(changes is null))
                {
                    foreach (PIPointChangeInfo change in changes)
                    {
                        Console.WriteLine($"ID: {change.ID,-3}, Action: {change.Action}, {DateTime.Now}");
                        if (isRenameSupported && change.IsRenameEvent(out string oldname, out string newname))
                        {
                            Console.WriteLine($"\tRename Event PointID: {change.ID}, NewName: {newname} OldName: {oldname}");
                        }
                    }
                }
                Thread.Sleep(GlobalConfig.PointChangeChkFreq);
            }
            try
            {
                using (cookieFile = new FileStream("cookie.dat", FileMode.Create))
                {
                    // Write the cookie to the file
                    formatter.Serialize(cookieFile, cookie);
                    cookieFile.Close();
                    Console.WriteLine("Point changes cache saved to cookie file");
                }
            }
            catch (SerializationException ex)
            {
                throw new SerializationException("Cookie could not be read " + ex.Message);

            }
            catch (SecurityException ex)
            {
                throw new SecurityException("No permission to read cookie file " + ex.Message);
            }
            catch (IOException ex)
            {
                throw new IOException("I/O Exception " + ex.Message);
            }
        }

        private static void Delete(PIPointList pointsList, AFTime st, AFTime et, string addlparam1, PIServer myServer)
        {
            AFTimeRange timeRange = new AFTimeRange(st, et);
            var bufOption = AFBufferOption.BufferIfPossible;
            switch (addlparam1)
            {
                case "dnb":
                    bufOption = AFBufferOption.DoNotBuffer;
                    break;
                case "buf":
                    bufOption = AFBufferOption.Buffer;
                    break;
            }

            if (myServer.Supports(PIServerFeature.DeleteRange))
            {
                foreach (var pt in pointsList)
                {
                    int delcount = 0;
                    var sb = new StringBuilder();
                    bool revTime = false;
                    if (st > et)
                    {
                        timeRange = new AFTimeRange(et, st);
                        revTime = true;
                    }
                    var intervalDefinitions = new AFTimeIntervalDefinition(timeRange, 1);

                    //getting the count of events - optional
                    IDictionary<AFSummaryTypes, AFValues> summaries = pt.Summaries(new List<AFTimeIntervalDefinition>() {
                                                                                intervalDefinitions },
                                                                               reverseTime: revTime,
                                                                               summaryType: AFSummaryTypes.Count,
                                                                               calcBasis: AFCalculationBasis.EventWeighted,
                                                                               timeType: AFTimestampCalculation.Auto
                                                                               );
                    foreach (var s in summaries)
                    {
                        AFValues vals = s.Value;
                        vals = s.Value;
                        foreach (var v in vals)
                        {
                            if (v.Value.GetType() != typeof(PIException))
                                delcount = v.ValueAsInt32(); //count
                        }
                    }
                    if (delcount > 0)
                    {
                        var errs = pt.ReplaceValues(timeRange, new List<AFValue>() { }, bufOption);
                        if (errs != null)
                        {
                            foreach (var e in errs.Errors)
                            {
                                sb.AppendLine($"{e.Key}: {e.Value}");
                                delcount--;
                            }
                        }
                    }
                    sb.AppendLine($"Point: {pt.Name}");
                    sb.AppendLine(new string('-', 45));
                    sb.AppendLine($"Deleted {delcount} events");
                    sb.AppendLine();
                    Console.Write(sb.ToString());
                }
            }
            else
            {
                foreach (var pt in pointsList)
                {
                    int delcount = 0;
                    var sb = new StringBuilder();
                    AFValues vals = pt.RecordedValues(timeRange: timeRange,
                                                      boundaryType: AFBoundaryType.Inside,
                                                      filterExpression: null,
                                                      includeFilteredValues: false,
                                                      maxCount: 0
                                                      );
                    delcount = vals.Count;
                    if (delcount > 0)
                    {
                        var errs = pt.UpdateValues(values: vals,
                                               updateOption: AFUpdateOption.Remove,
                                               bufferOption: bufOption);
                        if (errs != null)
                        {
                            foreach (var e in errs.Errors)
                            {
                                sb.AppendLine($"{e.Key}: {e.Value}");
                                delcount--;
                            }
                        }
                    }
                    sb.AppendLine($"Point: {pt.Name}");
                    sb.AppendLine(new string('-', 45));
                    sb.AppendLine($"Deleted {delcount} events");
                    sb.AppendLine();
                    Console.Write(sb.ToString());
                }
            }
        }

        private static void UploadAnnotate(string command, PIPointList pointsList, string[] times, string addlparam1)
        {
            string addlparam2 = string.Empty;
            AFUpdateOption updOption = AFUpdateOption.Replace;
            AFBufferOption bufOption = AFBufferOption.BufferIfPossible;
            if (times.Length > 0)
            {
                addlparam1 = times[0];
                if (times.Length > 1)
                {
                    addlparam2 = times[1];
                }
            }
            switch (addlparam1)
            {
                case "r":
                    updOption = AFUpdateOption.Replace;
                    break;
                case "i":
                    updOption = AFUpdateOption.Insert;
                    break;
                case "nr":
                    updOption = AFUpdateOption.NoReplace;
                    break;
                case "ro":
                    updOption = AFUpdateOption.ReplaceOnly;
                    break;
                case "inc":
                    updOption = AFUpdateOption.InsertNoCompression;
                    break;
                case "rm":
                    updOption = AFUpdateOption.Remove;
                    break;
            }
            switch (addlparam2)
            {
                case "dnb":
                    bufOption = AFBufferOption.DoNotBuffer;
                    break;
                case "buf":
                    bufOption = AFBufferOption.Buffer;
                    break;
            }

            if (command == "uploadcsv")
            {
                string v;
                var values = new List<AFValue>();
                int linescount = 0;
                int linesparsed = 0;
                Console.WriteLine($"Point: {pointsList[0].Name} Uploading values ({updOption} {bufOption})");
                Console.WriteLine(new string('-', 45));

                while ((v = Console.ReadLine()) != null)  // read till end of file
                {
                    linescount++;
                    var timevalue = v.Split(new char[] { ',' });
                    if (timevalue.Length > 1
                        && DateTime.TryParse(timevalue[0], out DateTime ts))
                    {
                        // use datetime as string in AFTime to be treated as localtime
                        values.Add(new AFValue(timevalue[1], new AFTime(ts.ToString())));
                        if (GlobalConfig.Debug)
                            Console.WriteLine($"{timevalue[0]}, {timevalue[1]}");
                        linesparsed++;
                    }
                }
                Console.WriteLine($"Lines read from file    : {linescount}");
                Console.WriteLine($"Succcesfully parsed     : {linesparsed}");
                AFErrors<AFValue> errors = pointsList[0].UpdateValues(values, updOption, bufOption);
                Console.WriteLine($"Uploaded {linesparsed - (errors != null ? errors.Errors.Count : 0)} values");
                if (errors != null && errors.HasErrors)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine($"Total Errors: {errors.Errors.Count}");
                    foreach (var e in errors.Errors)
                    {
                        sb.AppendLine($"{e.Key} : {e.Value}");
                    }
                    sb.AppendLine();
                    Console.Write(sb.ToString());
                }
                if (GlobalConfig.Debug && bufOption != AFBufferOption.DoNotBuffer)
                    Console.WriteLine($"Note: Currently, using PIBufSS has no error feedback to the caller");
            }
            else
            {
                foreach (var pt in pointsList)
                {
                    AFValue val;
                    Console.WriteLine($"Point: {pt.Name} {command} ({updOption} {bufOption})");
                    Console.WriteLine(new string('-', 45));
                    Console.Write("Enter timestamp: ");
                    var time = Console.ReadLine();

                    if (!AFTime.TryParse(time, out AFTime ts))
                    {
                        Console.WriteLine("Invalid Timestamp");
                        break;
                    }
                    if (command == "update" ||
                        !(pt.RecordedValuesAtTimes(new List<AFTime>() { ts }, AFRetrievalMode.Exact)[0].IsGood))
                    {
                        Console.Write("Enter new value: ");
                        var data = Console.ReadLine();
                        if (!Double.TryParse(data, out var value))
                        {
                            Console.WriteLine("Invalid numerical data");
                            break;
                        }
                        val = new AFValue(value, ts);
                    }
                    else
                    {
                        val = pt.RecordedValuesAtTimes(new List<AFTime>() { ts }, AFRetrievalMode.Exact)[0];
                    }
                    if (command == "annotate")
                    {
                        Console.Write("Enter annotation: ");
                        var ann = Console.ReadLine();
                        pt.SetAnnotation(val, ann);
                    }
                    /*buffering data through PIBufSS has a limitation where error feedback from PI Data Archive
                    cannot be returned to the caller*/
                    pt.UpdateValue(value: val, option: updOption, bufferOption: bufOption);
                    Console.WriteLine($"Successfully {command}d");
                    if (GlobalConfig.Debug && bufOption != AFBufferOption.DoNotBuffer)
                        Console.WriteLine($"Note: Currently, using PIBufSS has no error feedback to the caller");
                    Console.WriteLine();
                }
            }
            Console.WriteLine();
        }

        private static void Summaries(PIPointList pointsList, ref AFTime st, ref AFTime et, string addlparam1)
        {
            var timeRange = new AFTimeRange(st, et);
            bool revTime = false;
            if (st > et) //summaries AFTimeIntervalDefinition cannot handle reversed times
            {
                timeRange = new AFTimeRange(et, st);
                revTime = true;
            }

            var intervalDefinitions = new AFTimeIntervalDefinition(timeRange, 1);
            AFCalculationBasis calculationBasis = AFCalculationBasis.EventWeighted;
            if (addlparam1 == "t")
                calculationBasis = AFCalculationBasis.TimeWeighted;

            foreach (var pt in pointsList)
            {
                var summaryType = AFSummaryTypes.All;
                if (pt.PointType == PIPointType.Digital
                                    || pt.PointType == PIPointType.Timestamp
                                    || pt.PointType == PIPointType.Blob
                                    || pt.PointType == PIPointType.String
                                    || pt.PointType == PIPointType.Null)
                {
                    summaryType = AFSummaryTypes.AllForNonNumeric;
                }
                IDictionary<AFSummaryTypes, AFValues> summaries = pt.Summaries(new List<AFTimeIntervalDefinition>() {
                                                                                intervalDefinitions },
                                                                               reverseTime: revTime,
                                                                               summaryType: summaryType,
                                                                               calcBasis: calculationBasis,
                                                                               timeType: AFTimestampCalculation.Auto
                                                                               );

                //var timeSpan = new AFTimeSpan(st.UtcTime.Subtract(et.UtcTime));
                //IDictionary<AFSummaryTypes, AFValues> summaries = pt.Summaries(timeRange: timeRange,
                //                                                              summaryDuration:timeSpan, //with timespan
                //                                                              summaryType: summaryType,
                //                                                              calcBasis: calculationBasis,
                //                                                              timeType: AFTimestampCalculation.Auto
                //                                                              );
                var sb = new StringBuilder();
                sb.AppendLine($"Point: {pt.Name} {calculationBasis} Summary");
                sb.AppendLine(new string('-', 45));
                foreach (var s in summaries)
                {
                    AFValues vals = s.Value;
                    foreach (var v in vals)
                    {
                        if (v.Value.GetType() != typeof(PIException))
                        {
                            if (string.Compare(s.Key.ToString(), "Minimum", true) == 0
                                     || string.Compare(s.Key.ToString(), "Maximum", true) == 0)
                                sb.AppendLine($"{s.Key,-16}: {v.Value,-20} {v.Timestamp}");
                            else
                                sb.AppendLine($"{s.Key,-16}: {v.Value}");
                        }
                        else
                            sb.AppendLine($"{s.Key,-16}: {v}");
                    }
                }
                sb.AppendLine();
                Console.Write(sb.ToString());
            }
            /*
            Non numeric tags in pointsList requires splitting of queries so the above is preferred.
            The below implementation works when there are no non-numeric types or one particular summary needs to be run
            */
            //var resultsMap = new Dictionary<PIPoint, AFValues>();
            //var pagingConfig = new PIPagingConfiguration(PIPageType.EventCount, GlobalConfig.PageSize);
            //var listResults = pointsList.Summaries(new List<AFTimeIntervalDefinition>() {
            //                                                               intervalDefinitions },
            //                                                               reverseTime: false,
            //                                                               summaryTypes: AFSummaryTypes.All,
            //                                                               calculationBasis: calculationBasis,
            //                                                               timeType: AFTimestampCalculation.Auto,
            //                                                               pagingConfig: pagingConfig
            //                                                               );
            //foreach (IDictionary<AFSummaryTypes, AFValues> summaries in listResults)
            //{
            //     foreach (IDictionary<AFSummaryTypes, AFValues> pointResults in listResults)
            //    {
            //            AFValues pointValues = pointResults[AFSummaryTypes.Average];
            //            PIPoint point = pointValues.PIPoint;
            //           //Map the results back to the point
            //           resultsMap[point] = pointValues;
            //     }
            //}
        }

        private static void Interpolated(PIPointList pointsList, AFTime st, AFTime et, AFTimeSpan summaryDuration, string addlparam1)
        {
            AFTimeRange timeRange = new AFTimeRange(st, et);
            var resultsMap = new Dictionary<PIPoint, AFValues>();
            var pagingConfig = new PIPagingConfiguration(PIPageType.EventCount, GlobalConfig.PageSize);

            if (addlparam1.StartsWith("c="))
            {
                if (!Int32.TryParse(addlparam1.Substring(2), out int count))
                    count = 10; //default count

                IEnumerable<AFValues> listResults = pointsList.InterpolatedValuesByCount(timeRange: timeRange,
                                                                numberOfValues: count,
                                                                filterExpression: null,
                                                                includeFilteredValues: false,
                                                                pagingConfig: pagingConfig
                                                               );
                foreach (var pointResults in listResults) resultsMap[pointResults.PIPoint] = pointResults;
                foreach (var pointValues in resultsMap)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine($"Point: {pointValues.Key} Interpolated Values " +
                        $"Count: {pointValues.Value.Count}");
                    sb.AppendLine(new string('-', 45));
                    pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}"));
                    sb.AppendLine();
                    Console.Write(sb.ToString());
                }
            }
            else
            {
                if (!AFTimeSpan.TryParse(addlparam1, out AFTimeSpan interval) || interval == new AFTimeSpan(0))
                    interval = summaryDuration;

                IEnumerable<AFValues> listResults = pointsList.InterpolatedValues(timeRange: timeRange,
                                                               interval: interval,
                                                               filterExpression: null,
                                                               includeFilteredValues: false,
                                                               pagingConfig: pagingConfig
                                                              );
                foreach (var pointResults in listResults)
                    resultsMap[pointResults.PIPoint] = pointResults;
                foreach (var pointValues in resultsMap)
                {
                    var sb = new StringBuilder();
                    sb.AppendLine($"Point: {pointValues.Key} Interpolated Values " +
                        $"Interval: {interval.ToString()}");
                    sb.AppendLine(new string('-', 45));
                    pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}"));
                    sb.AppendLine();
                    Console.Write(sb.ToString());
                }
            }
        }

        private static void Plot(PIPointList pointsList, AFTime st, AFTime et, string addlparam1)
        {
            AFTimeRange timeRange = new AFTimeRange(st, et);
            if (!Int32.TryParse(addlparam1, out int intervals))
                intervals = 640; //horizontal pixels in the trend

            var resultsMap = new Dictionary<PIPoint, AFValues>();
            var pagingConfig = new PIPagingConfiguration(PIPageType.EventCount, GlobalConfig.PageSize);
            IEnumerable<AFValues> listResults = pointsList.PlotValues(timeRange: timeRange,
                                                  intervals: intervals,
                                                  pagingConfig: pagingConfig
                                                  );
            foreach (var pointResults in listResults)
                resultsMap[pointResults.PIPoint] = pointResults;
            foreach (var pointValues in resultsMap)
            {
                var sb = new StringBuilder();
                sb.AppendLine($"Point: {pointValues.Key} Plot Values Interval: {intervals}" +
                    $" Count: {pointValues.Value.Count}");
                sb.AppendLine(new string('-', 45));
                pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}"));
                sb.AppendLine();
                Console.Write(sb.ToString());
            }
        }

        private static void Arclist(PIPointList pointsList, AFTime st, AFTime et, string addlparam1)
        {
            AFTimeRange timeRange = new AFTimeRange(st, et);
            if (!Int32.TryParse(addlparam1, out int maxcount))
                maxcount = 0;

            // Holds the results keyed on the associated point
            var resultsMap = new Dictionary<PIPoint, AFValues>();
            var pagingConfig = new PIPagingConfiguration(PIPageType.EventCount, GlobalConfig.PageSize);
            IEnumerable<AFValues> listResults = pointsList.RecordedValues(timeRange: timeRange,
                                                  boundaryType: AFBoundaryType.Inside,
                                                  filterExpression: null,
                                                  includeFilteredValues: false,
                                                  pagingConfig: pagingConfig,
                                                  maxCount: maxcount
                                                  );
            foreach (var pointResults in listResults)
                resultsMap[pointResults.PIPoint] = pointResults;
            foreach (var pointValues in resultsMap)
            {
                var sb = new StringBuilder();
                sb.AppendLine($"Point: {pointValues.Key} Archive Values " +
                    $"Count: {pointValues.Value.Count}");
                sb.AppendLine(new string('-', 45));
                pointValues.Value.ForEach(v => sb.AppendLine($"{v.Timestamp}, {v.Value}"));
                sb.AppendLine();
                Console.Write(sb.ToString());
            }
        }

        private static void Snap(PIPointList pointsList)
        {
            var sb = new StringBuilder();
            sb.AppendLine($"Point Name(Point Id), Timestamp, Current Value");
            sb.AppendLine(new string('-', 45));
            AFListResults<PIPoint, AFValue> results = pointsList.EndOfStream();
            if (results.HasErrors)
            {
                foreach (var e in results.Errors) sb.AppendLine($"{e.Key}: {e.Value}");
            }
            foreach (var v in results.Results)
            {
                if (!results.Errors.ContainsKey(v.PIPoint))
                {
                    sb.AppendLine($"{string.Concat($"{v.PIPoint.Name} ({v.PIPoint.ID})"),-15}," +
                        $" {v.Timestamp}, {v.Value}");
                }
            }
            sb.AppendLine();
            Console.Write(sb.ToString());
        }
    }
}


text:
import { Font } from './../extras/core/Font';
import { ExtrudeGeometry, ExtrudeBufferGeometry } from './ExtrudeGeometry';

export interface TextGeometryParameters {
	font: Font;
	size?: number;
	height?: number;
	curveSegments?: number;
	bevelEnabled?: boolean;
	bevelThickness?: number;
	bevelSize?: number;
	bevelOffset?: number;
	bevelSegments?: number;
}

export class TextBufferGeometry extends ExtrudeBufferGeometry {

	constructor( text: string, parameters: TextGeometryParameters );

	parameters: {
		font: Font;
		size: number;
		height: number;
		curveSegments: number;
		bevelEnabled: boolean;
		bevelThickness: number;
		bevelSize: number;
		bevelOffset: number;
		bevelSegments: number;
	};

}

export class TextGeometry extends ExtrudeGeometry {

	constructor( text: string, parameters: TextGeometryParameters );

	parameters: {
		font: Font;
		size: number;
		height: number;
		curveSegments: number;
		bevelEnabled: boolean;
		bevelThickness: number;
		bevelSize: number;
		bevelOffset: number;
		bevelSegments: number;
	};

}


text:
Kaminari.configure do |config|
  config.default_per_page = Foundationstone::Config.kaminari_default
  # config.window = 4
  # config.outer_window = 0
  # config.left = 0
  # config.right = 0
  # config.page_method_name = :page
  # config.param_name = :page
end if defined? Kaminari


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
class AMPFORWP_Blurb_Widget extends WP_Widget {
	/*--------------------------------------------------*/
	/* Constructor
	/*--------------------------------------------------*/

	/**
	 * Specifies the classname and description, instantiates the widget,
	 * loads localization files, and includes necessary stylesheets and JavaScript.
	 */
	public function __construct() {

		// Hooks fired when the Widget is activated and deactivated
		register_activation_hook( __FILE__, array( $this, 'activate' ) );
		register_deactivation_hook( __FILE__, array( $this, 'deactivate' ) );

		parent::__construct(
			'ampforwp-blurb',
			esc_html__( 'AMP Blurb Module', 'accelerated-mobile-pages' ),
			array( //
				'classname'		=>	'ampforwp-blurb',
				'description'	=>	esc_html__( 'Displays Icon, headline and description. Best for showing features.', 'accelerated-mobile-pages' )
			)
		);

		add_action( 'admin_enqueue_scripts', array( $this, 'register_admin_scripts' ) );

	} // end constructor

	/*--------------------------------------------------*/
	/* Widget API Functions
	/*--------------------------------------------------*/

	/**
	 * Outputs the content of the widget.
	 *
	 * @param	array	args		The array of form elements
	 * @param	array	instance	The current instance of the widget
	 */
	public function widget( $args, $instance ) {
        $output = "";

		extract( $args, EXTR_SKIP );

		$title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : '';
		$title = apply_filters( 'widget_title', $title, $instance, $this->id_base );

		$features = ( ! empty( $instance['features'] ) ) ? $instance['features'] : array();

        echo $before_widget;

        $output .= '
';

		if ( $title ) {
            $output .=  '
';
            $output .=  esc_html( $title );
            $output .=  '
';
            }

        $output .= '
';

		foreach( $features as $feature ) {
			$output .= '
';
				if ( $feature['image'] ) {
					$output .= '';
				}
                $output .= '
';
                $output .= '
'.esc_html( $feature['title']).'
';
				$output .= '
' .esc_html( $feature['description']).'
';
				$output .= '
';
			$output .= '
';
		}
            $output .=  '

'; // flex-grid & amp_cb_module
		$sanitizer = new AMPFORWP_Content( $output, array(),
			apply_filters( 'ampforwp_content_sanitizers',array( 'AMP_Img_Sanitizer' => array(),'AMP_Style_Sanitizer' => array() ) ) );
		$sanitized_output 		= $sanitizer->get_amp_content();

		if( $sanitized_output ) {
			echo $sanitized_output; // amphtml content, no kses
		}

		echo $after_widget;

	} // end widget

	/**
	 * Processes the widget's options to be saved.
	 *
	 * @param	array	new_instance	The new instance of values to be generated via the update.
	 * @param	array	old_instance	The previous instance of values before the update.
	 */
	public function update( $new_instance, $old_instance ) {

		$instance = $old_instance;

		$instance['title'] = strip_tags($new_instance['title']);

		foreach($new_instance['features'] as $feature){
			$feature['title'] = strip_tags($feature['title']);
			$feature['description'] = strip_tags($feature['description']);
			$feature['image'] = strip_tags($feature['image']);
		}
		$instance['features'] = $new_instance['features'];

		return $instance;

	} // end widget

	/**
	 * Generates the administration form for the widget.
	 *
	 * @param	array	instance	The array of keys and values for the widget.
	 */
	public function form( $instance ) {

		$instance = wp_parse_args(
			(array) $instance
		);

		$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : ''; ?>

<label for="<?php echo esc_attr($this->get_field_id( 'title' )); ?>"><?php esc_attr_e( 'Title:' ); ?>
		<input class="widefat" id="<?php echo esc_attr($this->get_field_id( 'title' )); ?>" name="<?php echo esc_attr($this->get_field_name( 'title' )); ?>" type="text" value="<?php echo esc_attr($title); ?>" />

		<?php

		$features = ( ! empty( $instance['features'] ) ) ? $instance['features'] : array(); ?>

			<?php
		    $c = 0;
		    if ( count( $features ) > 0 ) {
		        foreach( $features as $feature ) {
		            if ( isset( $feature['title'] ) || isset( $feature['description'] ) ) { ?>

<?php echo esc_attr($feature['title']);?>

								<label for="<?php echo esc_attr($this->get_field_name( 'features' )) . '['.$c.'][title]'; ?>"><?php esc_attr_e( 'Title:' ); ?>
								<input class="widefat" id="<?php echo esc_attr($this->get_field_id( 'features' )) .'-'. $c.'-title'; ?>" name="<?php echo esc_attr($this->get_field_name( 'features' )) . '['.$c.'][title]'; ?>" type="text" value="<?php echo esc_attr($feature['title']); ?>" />
								<label for="<?php echo esc_attr($this->get_field_name( 'features' )) . '['.$c.'][description]'; ?>"><?php esc_attr_e( 'Description:' ); ?>

								<textarea  class="widefat" id="<?php echo esc_attr($this->get_field_id( 'features' )) .'-'. $c.'-description'; ?>" name="<?php echo esc_attr($this->get_field_name( 'features' )) . '['.$c.'][description]'; ?>" rows="6" cols="50"><?php echo esc_attr($feature['description']); ?></textarea>

								<label for="<?php echo esc_attr($this->get_field_name( 'features' )) . '['.$c.'][image]'; ?>"><?php esc_attr_e( 'Image:' ); ?>
								<input type="button" class="select-img-<?php echo esc_attr($c);?> button left" style="width:auto;" value="Select Image" onclick="ampSelectImage('<?php echo esc_attr($c);?>');"/>
								<input type="button" style="display:none" name="removeimg" id="remove-img-<?php echo esc_attr($c);?>" class="button button-secondary remove-img-button" data-count-type="<?php echo esc_attr($c);?>"  value="Remove Image" onclick="removeImage('<?php echo esc_attr($c);?>')">
								<img src="<?php echo esc_url($instance['features']["$c"]['image'])  ?>" class="preview-image block-image-<?php echo esc_attr($c);?>" >
								<input type="hidden" id="amp-img-field-<?php echo esc_attr($c);?>" class="img<?php echo esc_attr($c);?>" style="width:auto;" name="<?php echo esc_attr($this->get_field_name( 'features' )) . '['.$c.'][image]'; ?>" id="<?php echo esc_attr($this->get_field_name( 'features' )) . '['.$c.'][image]';?>'" value="<?php echo esc_attr($instance['features']["$c"]['image'])  ?>" />

	<?php esc_attr_e('Remove Feature','accelerated-mobile-pages')?>

					<?php
		                $c = $c +1;
		            }
		        }
		    }  ?>

		  <?php esc_attr_e('Add Feature','accelerated-mobile-pages'); ?>

		<?php

	} // end form

	/*--------------------------------------------------*/
	/* Public Functions
	/*--------------------------------------------------*/

	/**
	 * Registers and enqueues admin-specific JavaScript.
	 */
	public function register_admin_scripts() {

        wp_enqueue_script('media-upload');
        wp_enqueue_script('thickbox');
        wp_enqueue_style('thickbox');
        $builder_data['amp_icon_check'] = AMPFORWP_IMAGE_DIR . '/amp-icon-check.png';
        wp_localize_script( 'ampforwp-builder-script', 'builder_script_data', $builder_data );
		wp_enqueue_script( 'ampforwp-builder-script',  plugins_url('/modules/js/amp.js' , dirname(__FILE__) ) , array( 'jquery' ), false, true );

	} // end register_admin_scripts

} // end class

add_action( 'widgets_init', 'ampforwp_register_blurb_widget' );
function ampforwp_register_blurb_widget(){
	register_widget( 'AMPFORWP_Blurb_Widget' );
}


text:
cask 'data-integration' do
  version '8.0.0.0-28'
  sha256 '52333d725523c9f3cb86b66eee768872660462484feabc78e9d402a4506fb5a6'

  # sourceforge.net/pentaho was verified as official when first introduced to the cask
  url "https://downloads.sourceforge.net/pentaho/pdi-ce-#{version}.zip"
  appcast 'https://sourceforge.net/projects/pentaho/rss?path=/Data%20Integration',
          checkpoint: '41154713ae8665c1087df19b6beb4038a17c2e4fbfcf0215e9094cc9d98efa05'
  name 'Pentaho Data Integration'
  homepage 'http://community.pentaho.com/'

  app 'data-integration/Data Integration.app'
end


text:
package org.w3c.domts.level1.core;

import org.w3c.dom.*;

import org.w3c.domts.DOMTestCase;
import org.w3c.domts.DOMTestDocumentBuilderFactory;

/**
 *     The "getLength()" method returns the number of nodes
 *    in the list.(Test for EMPTY list)
 *
 *    Create a list of all the children of the Text node
 *    inside the first child of the third employee and
 *    invoke the "getLength()" method.   It should contain
 *    the value 0.
* @author NIST
* @author Mary Brady
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core#ID-203510337
*/
public final class nodelistindexgetlengthofemptylist extends DOMTestCase {

   /**
    * Constructor.
    * @param factory document factory, may not be null
    * @throws org.w3c.domts.DOMTestIncompatibleException Thrown if test is not compatible with parser configuration
    */
   public nodelistindexgetlengthofemptylist(final DOMTestDocumentBuilderFactory factory)  throws org.w3c.domts.DOMTestIncompatibleException {
      super(factory);

    //
    //   check if loaded documents are supported for content type
    //
    String contentType = getContentType();
    preload(contentType, "staff", false);
    }

   /**
    * Runs the test case.
    * @throws Throwable Any uncaught exception causes test to fail
    */
   public void runTest() throws Throwable {
      Document doc;
      NodeList elementList;
      Node employeeNode;
      NodeList employeeList;
      Node childNode;
      Node textNode;
      NodeList textList;
      doc = (Document) load("staff", false);
      elementList = doc.getElementsByTagName("employee");
      employeeNode = elementList.item(2);
      employeeList = employeeNode.getChildNodes();
      childNode = employeeList.item(1);
      textNode = childNode.getFirstChild();
      textList = textNode.getChildNodes();
      assertSize("nodelistIndexGetLengthOfEmptyListAssert", 0, textList);
      }
   /**
    *  Gets URI that identifies the test.
    *  @return uri identifier of test
    */
   public String getTargetURI() {
      return "http://www.w3.org/2001/DOM-Test-Suite/level1/core/nodelistindexgetlengthofemptylist";
   }
   /**
    * Runs this test from the command line.
    * @param args command line arguments
    */
   public static void main(final String[] args) {
        DOMTestCase.doMain(nodelistindexgetlengthofemptylist.class, args);
   }
}


text:
<!DOCTYPE html>

		<title>Finesse Fitness</title>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

		<link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet">

		<link rel="stylesheet" type="text/css" href="AllAround3.css">

      				<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

      			</button>
      				Finesse

Home

Warm up

Featured

Filter

Contact Us

			Your search results...

			<button type="button" class="btn btn-default btn-block">View More</button>


text:
package com.library.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

/**
 * 带选中,和点击效果 的  ImageView
 * Created by hais1992 on 15-5-6.
 */
public class ImagesFocus extends ImageView{
    private Paint paint;
    private boolean select_state =false;    //选中状态
    private String select_color = "#400D17FF";     //选中颜色

    public ImagesFocus(Context context) {
        super(context);
        init();
    }

    public ImagesFocus(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public ImagesFocus(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){

        paint = new Paint();
        paint.setAlpha(0x40); //设置透明程度

        paint.setStyle(Paint.Style.FILL);
        paint.setColor(Color.parseColor(select_color));
        paint.setAntiAlias(true);
        this.setDrawingCacheEnabled(true);
        this.setClickable(true);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);

        if (paint!=null && select_state) {
            canvas.drawRect(0, 0, getWidth(), getHeight(), paint);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                select_state = true;        //设置当前需求为 选中 状态
                invalidate();                   //重新绘图
                break;
            case MotionEvent.ACTION_UP:
                select_state = false;       //设置当前需求为 未选中 状态
                invalidate();               //重新绘图
                break;
        }
        return super.onTouchEvent(event);
    }
}


text:
import os
import re
import sys
import logging
import yaml
import subprocess
from distutils.dir_util import copy_tree
from distutils.file_util import copy_file

def init_logger():
    """
    Add logging.StreamHandler() to print logs on debug screen.
    """
    root_logger = logging.getLogger()
    console_handler = logging.StreamHandler()
    root_logger.addHandler(console_handler)
    root_logger.setLevel(logging.DEBUG)

def copy(src, dest):
    """
    Copy all files under src to dest.

    :param str src: source directory
    :param str dest: destination directory
    """
    filenames = convert_single_item_to_list(src)
    for l in filenames:
        if os.path.isdir(l):
            copy_tree(src, dest)
        else:
            copy_file(src, dest)

def decode(byte, encoding='ISO-8859-1'):
    """
    decode byte string to unicode string.

    :param str byte: byte string
    :param str encoding: encoding
    """
    unicodestr = byte.decode(encoding) if isinstance(byte, bytes) else byte
    return unicodestr

def create_instance(clsname, fromstr, *args, **kwargs):
    """
    import a module dynamically and create an instance.

    :param str clsname: module name which you want to create an instance
    :param str fromstr: location of the module

    :returns module instance: created instance
    """
    fromstr = '{}.{}'.format(fromstr, clsname)
    __import__(fromstr)
    return getattr(sys.modules[fromstr], clsname)(*args, **kwargs)

def check_output(cmd, timeout=None, encoding='ISO-8859-1', shell=False,
                 stderr=None):
    """
    Run command with arguments and return its output.
    This is a wrapper of subprocess.check_output().

    Example:
        >>> litmus.core.util.check_output(["echo", "Hello World"])
        b'Hello World!\\n'
    """
    outs = None
    try:
        outs = subprocess.check_output(cmd, timeout=timeout, shell=shell,
                                       stderr=stderr)
        if outs:
            outs = decode(outs, encoding=encoding)
    except subprocess.TimeoutExpired as e:
        logging.debug('command {} timed out : {}'.format(e.cmd, e.output))
        exc = sys.exc_info()
        raise exc[1].with_traceback(exc[2])
    except subprocess.CalledProcessError as e:
        logging.debug('command {} return non-zero : {}'.format(e.cmd,
                                                               e.output))
    except Exception:
        exc = sys.exc_info()
        raise exc[1].with_traceback(exc[2])

    return outs

def call(cmd, timeout=None, shell=False,
         stdout=None, stderr=None):
    """
    Run the command described by args.
    Wait for command to complete, then return the returncode attribute.
    This is a wrapper of subprocess.call().

    Example:
        >>> litmus.core.util.call(["ls", "-l"])
        0
    """
    ret = None
    try:
        ret = subprocess.call(cmd, timeout=timeout, shell=shell,
                              stdout=stdout, stderr=stderr)
    except subprocess.TimeoutExpired:
        logging.debug('command {} timed out'.format(cmd))
        exc = sys.exc_info()
        raise exc[1].with_traceback(exc[2])
    except Exception:
        exc = sys.exc_info()
        raise exc[1].with_traceback(exc[2])

    return ret

def convert_single_item_to_list(item):
    """
    Convert a item to list and return it.
    If item is already list then return the item without change.
    """
    return [item] if type(item) is not list else item

def find_pattern(pattern, data, groupindex=0):
    """
    Find a first match to a regular expression from data buffer.
    This also supports groupindex.

    :param str pattern: regular expression
    :param str data: data buffer
    :param int groupindex: group index

    :returns str: found string from data
    """
    if not data:
        data = ' '

    p = re.compile(pattern)
    result = p.search(data)
    if result:
        result = result.group(groupindex)
    return result

def find_all_pattern(pattern, data):
    """
    Find all matches to a regular expression from data buffer.

    :param str pattern: regular expression
    :param str data: data buffer

    :returns str: found string from data
    """
    if not data:
        data = ' '
    p = re.compile(pattern)
    result = p.findall(data)
    return result

def load_yaml(filename):
    """
    load a yaml file.

    :param str filename: a yaml filename

    :returns dict: parsed yaml data
    """
    with open(os.path.expanduser(filename), 'r') as stream:
        data = yaml.load(stream)
    return data


text:
#include "Water/IslandRadialWater.h"

UIslandRadialWater::UIslandRadialWater()
{
	Bumps = 3;
	StartAngle = 1.0f;
	AngleOffset = 1.0f;
	MinAngle = 0.5f;
	LandScale = 1.25f;
}

bool UIslandRadialWater::IsPointLand_Implementation(FPointIndex Point, UTriangleDualMesh* Mesh, const FVector2D& HalfMeshSize, const FVector2D& Offset, const FIslandShape& Shape) const
{
	FVector2D point = Mesh->r_pos(Point) - HalfMeshSize;
	point.X = LandScale * 2.0f * (point.X / (HalfMeshSize.X * 2.0f));
	point.Y = LandScale * 2.0f * (point.Y / (HalfMeshSize.Y * 2.0f));
	// Get the angle of the point from the center of the island
	float angle = FMath::Atan2(point.Y, point.X);
	// Get the normalized length of whichever axis is longer
	float length = 0.5f * (FMath::Max(FMath::Abs(point.X), FMath::Abs(point.Y)) + FVector2D::Distance(FVector2D::ZeroVector, point));
	// The inner radius has to be smaller than the length for this to be land
	float innerRadius;
	// The outer radius has to be larger than the length for this to be land
	float outerRadius;

	if ((FMath::Abs(angle - (AngleOffset * PI)) < MinAngle
		 || FMath::Abs(angle - (AngleOffset * PI) + 2.0f * PI) < MinAngle
		 || FMath::Abs(angle - (AngleOffset * PI) - 2.0f * PI) < MinAngle))
	{
		// Our angle is less than the minimum angle
		innerRadius = 0.2f;
		outerRadius = 0.2f;
	}
	else
	{
		innerRadius = 0.5f + 0.4f * FMath::Sin((StartAngle * PI) + Bumps * angle + FMath::Cos((Bumps + 3) * angle));
		outerRadius = 0.7f - 0.2f * FMath::Sin((StartAngle * PI) + Bumps * angle - FMath::Sin((Bumps + 2) * angle));
	}

	return !((length + WaterCutoff < innerRadius) || (length + WaterCutoff > innerRadius * Shape.IslandFragmentation && length + WaterCutoff < outerRadius));
}


text:
namespace Gallio.Icarus.Specifications
{
    public class OrSpecification<T> : Specification<T>
    {
        private readonly ISpecification<T> left;
        private readonly ISpecification<T> right;

        public OrSpecification(ISpecification<T> left, ISpecification<T> right)
        {
            this.left = left;
            this.right = right;
        }

        public override bool Matches(T item)
        {
            return left.Matches(item) || right.Matches(item);
        }
    }
}