text:
<?php

namespace FormBuilder;

use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module implements AutoloaderProviderInterface
{
    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\ClassMapAutoloader' => array(
                __DIR__ . '/autoload_classmap.php',
            ),
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
		    // if we're in a namespace deeper than one level we need to fix the \ in the path
                    __NAMESPACE__ => __DIR__ . '/src/' . str_replace('\\', '/' , __NAMESPACE__),
                ),
            ),
        );
    }

    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function onBootstrap(MvcEvent $e)
    {
        // You may not need to do this if you're doing it elsewhere in your
        // application
        $eventManager        = $e->getApplication()->getEventManager();
        $eventManager->getSharedManager()->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) {
            $controller      = $e->getTarget();
            $controllerClass = get_class($controller);
            $moduleNamespace = substr($controllerClass, 0, strpos($controllerClass, '\\'));
            $config          = $e->getApplication()->getServiceManager()->get('config');
            if (isset($config['module_layouts'][$moduleNamespace])) {
                $controller->layout($config['module_layouts'][$moduleNamespace]);
            }
        }, 100);
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getServiceConfig() {
        return array(
            'factories' => array(
                'FormBuilder\Model\FormBuilderTable' => function($sm) {
                    $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                    $table = new Model\FormBuilderTable($dbAdapter);
                    return $table;
                },
            ),
        );
    }
}


text:
<?php

/**
 * DooVertxSessionServer acts as a session server that stores, retrieve and delete session data. Use @see DooVertxSessionServerVerticle to deploy the session server.
 *
 * @author Leng Sheng Hong <darkredz@gmail.com>
 * @package doo.session
 * @since 2.0
 */
class DooVertxSharedSessionServer extends DooVertxSessionServer
{

    public function getData($sid, callable $callback)
    {
        \SharedJson::get(getVertx(), $this->getNamespace(), $sid, function ($result) use ($callback, $sid) {
            if (empty($result)) {
                $callback(null);
                return;
            }
            $serializeObj = \jfrom($result);
            if ($serializeObj == null) {
                $callback(null);
            } else {
                //update timestamp when it's being accessed
                $this->resetTimer($sid);
                $callback($serializeObj['php']);
            }
        });
    }

    public function resetTimer($sid)
    {
        \SharedJson::get(getVertx(), $this->getNamespace() . '.gc', $sid, function ($result) {
            if (empty($result)) {
                return;
            }
            $serializeObj = \jfrom($result);
            if ($serializeObj == null) {
            } else {
                getVertx()->cancelTimer($serializeObj['timerID']);
            }
        });

        $timerID = getVertx()->setTimer($this->timeout, g(function ($tid) use ($sid) {
            \SharedJson::remove(getVertx(), $this->getNamespace(), $sid, function ($result) use ($sid) {
                $this->log('Session delete expired ' . $result . ' ' . $sid);
            });

            \SharedJson::remove(getVertx(), $this->getNamespace() . '.gc', $sid, function ($result) use ($sid) {
                $this->log('Session delete expired GC ' . $result . ' ' . $sid);
            });
        }));

        \SharedJson::put(getVertx(), $this->getNamespace() . '.gc', $sid, \jto(['timerID' => $timerID]),
            function ($result) use ($sid) {
                $this->log('Session resetTimer GC ' . $result . ' ' . $sid);
            });

        return $timerID;
    }

    public function saveData($sid, $serializeObj, callable $callback = null)
    {
        if (!$serializeObj || empty($sid)) {
            if ($callback != null) {
                $callback(false);
            }
            return false;
        }

        \SharedJson::put(getVertx(), $this->getNamespace(), $sid, \jto(['php' => $serializeObj]),
            function ($result) use ($sid) {
                $this->log('Session put data ' . $result . ' ' . $sid);
                $this->resetTimer($sid);
            });

        if ($callback != null) {
            $callback(true);
        }
        return true;
    }

    public function destroyData($sid, callable $callback = null)
    {
        if (empty($sid)) {
            if ($callback != null) {
                $callback(false);
            }
            return false;
        }

        \SharedJson::remove(getVertx(), $this->getNamespace(), $sid, function ($result) use ($sid) {
            $this->log('delete session ' . $result . '  ' . $sid);

            \SharedJson::remove(getVertx(), $this->getNamespace() . '.gc', $sid, function ($result) use ($sid) {
                if ($result != null) {
                    $serializeObj = \jfrom($result);
                    if ($serializeObj == null) {
                    } else {
                        getVertx()->cancelTimer($serializeObj['timerID']);
                    }
                    $this->log('delete session gc' . $result . '  ' . $sid . '  ' . $serializeObj['timerID']);
                } else {
                    $this->log('delete session gc' . $result . '  ' . $sid);
                }
            });
        });

        if ($callback != null) {
            $callback(true);
        }
        return true;
    }

    public function destroyAll(callable $callback = null)
    {
        //remove session from store
//        $gcmap = $this->getGcMap();
//        $map = $this->getMap();
//        $map->clear();
//
//        $size = $gcmap->size();
//        if($size > 0){
//            foreach($gcmap as $sid=>$timerId){
//                getVertx()->cancelTimer($timerId);
//            }
//        }
//
//        $gcmap->clear();

        if ($callback != null) {
            $callback(0);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using UnityEngine.UI;

public class LevelUpSpellItem : MonoBehaviour
{
    public Image SpellIcon;
    public Text SpellName;
    public Text Damage;
    public Text UpgradeDamage;

    public SpellUpgradeController spellUpgradeBar;

    public Transform lockedIcon;
    public Text unlockedLevel;
    public Transform lockedMessage;
    public Button UpgradeButton;

    //public ChoseButton
    private UB_SpellDetail baseSpell = null;
    private UB_Spell spell = null;

    public void LoadSpell(string sName, UB_SpellDetail sp, int lvl)
    {
        baseSpell = sp;
        spell = new UB_Spell()
        {
            SpellName = sName,
            Description = sp.Description,
            Icon = sp.Icon,
            Dmg = sp.BaseDmg,
            Level = 0,
            UpgradeLevels = sp.UpgradeLevels,
            FX = sp.FX,
            Cooldown = sp.Cooldown,
            LevelReq = sp.LevelReq,
            ApplyStatus = sp.ApplyStatus
        };

        SpellIcon.overrideSprite = GameController.Instance.iconManager.GetIconById(sp.Icon, IconManager.IconTypes.Spell);

        if (lvl > 0)
            UpgradeSpell(lvl);
        spellUpgradeBar.LoadBar(lvl, sp.UpgradeLevels);

        if (PF_PlayerData.activeCharacter.characterData.CharacterLevel < spell.LevelReq)
        {
            unlockedLevel.text = "Unlocked at level: " + spell.LevelReq;
            lockedIcon.gameObject.SetActive(true);
            lockedMessage.gameObject.SetActive(true);
            UpgradeButton.interactable = false;
        }
        else
        {
            lockedIcon.gameObject.SetActive(false);
            lockedMessage.gameObject.SetActive(false);
            UpgradeButton.interactable = true;
        }

        SpellName.text = spell.SpellName;
        Damage.text = "" + spell.Dmg;
        UpgradeDamage.text = "" + Mathf.CeilToInt((1f + baseSpell.UpgradePower) * (float)spell.Dmg);
    }

    void UpgradeSpell(int level)
    {
        for (int z = 0; z < level; z++)
        {
            spell.Dmg = Mathf.CeilToInt((1f + baseSpell.UpgradePower) * (float)spell.Dmg);

            if (spell.ApplyStatus != null)
            {
                spell.ApplyStatus.ChanceToApply *= 1.0f + baseSpell.UpgradePower;
                spell.ApplyStatus.ModifyAmount *= 1.0f + baseSpell.UpgradePower;
            }
        }
    }
}


text:
/* See LICENSE for licensing information */

/**
 * \file policies.h
 * \brief Header file for policies.c.
 **/

#ifndef TOR_POLICIES_H
#define TOR_POLICIES_H

/* (length of
 * "accept6 [ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]/128:65535-65535\n"
 * plus a terminating NUL, rounded up to a nice number.)
 */
#define POLICY_BUF_LEN 72

#define EXIT_POLICY_IPV6_ENABLED             (1 << 0)
#define EXIT_POLICY_REJECT_PRIVATE           (1 << 1)
#define EXIT_POLICY_ADD_DEFAULT              (1 << 2)
#define EXIT_POLICY_REJECT_LOCAL_INTERFACES  (1 << 3)
#define EXIT_POLICY_OPTION_MAX             EXIT_POLICY_REJECT_LOCAL_INTERFACES
/* All options set: used for unit testing */
#define EXIT_POLICY_OPTION_ALL             ((EXIT_POLICY_OPTION_MAX << 1) - 1)

typedef enum firewall_connection_t {
  FIREWALL_OR_CONNECTION      = 0,
  FIREWALL_DIR_CONNECTION     = 1
} firewall_connection_t;

typedef int exit_policy_parser_cfg_t;

int firewall_is_fascist_or(void);
int firewall_is_fascist_dir(void);
int fascist_firewall_use_ipv6(const or_options_t *options);
int fascist_firewall_prefer_ipv6_orport(const or_options_t *options);
int fascist_firewall_prefer_ipv6_dirport(const or_options_t *options);

int fascist_firewall_allows_address_addr(const tor_addr_t *addr,
                                         uint16_t port,
                                         firewall_connection_t fw_connection,
                                         int pref_only, int pref_ipv6);

int fascist_firewall_allows_rs(const routerstatus_t *rs,
                               firewall_connection_t fw_connection,
                               int pref_only);
int fascist_firewall_allows_node(const node_t *node,
                                 firewall_connection_t fw_connection,
                                 int pref_only);
int fascist_firewall_allows_dir_server(const dir_server_t *ds,
                                       firewall_connection_t fw_connection,
                                       int pref_only);

int fascist_firewall_choose_address_rs(const routerstatus_t *rs,
                                       firewall_connection_t fw_connection,
                                       int pref_only, tor_addr_port_t* ap);
int fascist_firewall_choose_address_node(const node_t *node,
                                         firewall_connection_t fw_connection,
                                         int pref_only, tor_addr_port_t* ap);
int fascist_firewall_choose_address_dir_server(const dir_server_t *ds,
                                          firewall_connection_t fw_connection,
                                          int pref_only, tor_addr_port_t* ap);

int dir_policy_permits_address(const tor_addr_t *addr);
int socks_policy_permits_address(const tor_addr_t *addr);
int authdir_policy_permits_address(uint32_t addr, uint16_t port);
int authdir_policy_valid_address(uint32_t addr, uint16_t port);
int authdir_policy_badexit_address(uint32_t addr, uint16_t port);

int validate_addr_policies(const or_options_t *options, char **msg);
void policy_expand_private(smartlist_t **policy);
void policy_expand_unspec(smartlist_t **policy);
int policies_parse_from_options(const or_options_t *options);

addr_policy_t *addr_policy_get_canonical_entry(addr_policy_t *ent);
int addr_policies_eq(const smartlist_t *a, const smartlist_t *b);
MOCK_DECL(addr_policy_result_t, compare_tor_addr_to_addr_policy,
    (const tor_addr_t *addr, uint16_t port, const smartlist_t *policy));
addr_policy_result_t compare_tor_addr_to_node_policy(const tor_addr_t *addr,
                              uint16_t port, const node_t *node);

int policies_parse_exit_policy_from_options(
                                          const or_options_t *or_options,
                                          uint32_t local_address,
                                          const tor_addr_t *ipv6_local_address,
                                          smartlist_t **result);
int policies_parse_exit_policy(config_line_t *cfg, smartlist_t **dest,
                               exit_policy_parser_cfg_t options,
                               const smartlist_t *configured_addresses);
void policies_parse_exit_policy_reject_private(
                                      smartlist_t **dest,
                                      int ipv6_exit,
                                      const smartlist_t *configured_addresses,
                                      int reject_interface_addresses,
                                      int reject_configured_port_addresses);
void policies_exit_policy_append_reject_star(smartlist_t **dest);
void addr_policy_append_reject_addr(smartlist_t **dest,
                                    const tor_addr_t *addr);
void addr_policy_append_reject_addr_list(smartlist_t **dest,
                                         const smartlist_t *addrs);
void policies_set_node_exitpolicy_to_reject_all(node_t *exitrouter);
int exit_policy_is_general_exit(smartlist_t *policy);
int policy_is_reject_star(const smartlist_t *policy, sa_family_t family,
                          int reject_by_default);
char * policy_dump_to_string(const smartlist_t *policy_list,
                             int include_ipv4,
                             int include_ipv6);
int getinfo_helper_policies(control_connection_t *conn,
                            const char *question, char **answer,
                            const char **errmsg);
int policy_write_item(char *buf, size_t buflen, const addr_policy_t *item,
                      int format_for_desc);

void addr_policy_list_free(smartlist_t *p);
void addr_policy_free(addr_policy_t *p);
void policies_free_all(void);

char *policy_summarize(smartlist_t *policy, sa_family_t family);

short_policy_t *parse_short_policy(const char *summary);
char *write_short_policy(const short_policy_t *policy);
void short_policy_free(short_policy_t *policy);
int short_policy_is_reject_star(const short_policy_t *policy);
addr_policy_result_t compare_tor_addr_to_short_policy(
                          const tor_addr_t *addr, uint16_t port,
                          const short_policy_t *policy);

#ifdef POLICIES_PRIVATE
STATIC void append_exit_policy_string(smartlist_t **policy, const char *more);
STATIC int fascist_firewall_allows_address(const tor_addr_t *addr,
                                           uint16_t port,
                                           smartlist_t *firewall_policy,
                                           int pref_only, int pref_ipv6);
STATIC const tor_addr_port_t * fascist_firewall_choose_address(
                                          const tor_addr_port_t *a,
                                          const tor_addr_port_t *b,
                                          int want_a,
                                          firewall_connection_t fw_connection,
                                          int pref_only, int pref_ipv6);

#endif

#endif


text:
#ifndef START_MATCH_DEBUG_H
#define START_MATCH_DEBUG_H

#include "startMatch.h"

#include "../../common/io/outputStream.h"

/**
 * Print a table to debug the start of Match structure.
 * @param outputStream where we print the table
 */
void printStartMatchTable(OutputStream* outputStream, StartMatch* startMatch);

#endif


text:
const kelda = require('kelda');
const infrastructure = require('../../../config/infrastructure.js');

const infra = infrastructure.createTestInfrastructure();

const numContainers = parseInt(process.argv[2], 10);
const name = process.argv[3];

for (let i = 0; i < numContainers; i += 1) {
  const container = new kelda.Container(name, 'google/pause');
  container.deploy(infra);
}


text:
#ifndef PCL_ML_FERNS_FERN_EVALUATOR_H_
#define PCL_ML_FERNS_FERN_EVALUATOR_H_

#include <pcl/common/common.h>

#include <pcl/ml/ferns/fern.h>
#include <pcl/ml/feature_handler.h>
#include <pcl/ml/stats_estimator.h>

#include <vector>

namespace pcl
{

  /** \brief Utility class for evaluating a fern. */
  template <
    class FeatureType,
    class DataSet,
    class LabelType,
    class ExampleIndex,
    class NodeType >
  class FernEvaluator
  {

  public:

    /** \brief Constructor. */
    FernEvaluator();
    /** \brief Destructor. */
    virtual
    ~FernEvaluator();

    /** \brief Evaluates the specified examples using the supplied tree.
      * \param[in] tree The decision tree.
      * \param[in] feature_handler The feature handler used to train the tree.
      * \param[in] stats_estimator The statistics estimation instance used while training the tree.
      * \param[in] data_set The data set used for evaluation.
      * \param[in] examples The examples that have to be evaluated.
      * \param[out] label_data The destination for the resulting label data.
      */
    void
    evaluate (pcl::Fern<FeatureType, NodeType> & fern,
              pcl::FeatureHandler<FeatureType, DataSet, ExampleIndex> & feature_handler,
              pcl::StatsEstimator<LabelType, NodeType, DataSet, ExampleIndex> & stats_estimator,
              DataSet & data_set,
              std::vector<ExampleIndex> & examples,
              std::vector<LabelType> & label_data);

    /** \brief Evaluates the specified examples using the supplied tree and adds the results to the supplied results array.
      * \param[in] tree The decision tree.
      * \param[in] feature_handler The feature handler used to train the tree.
      * \param[in] stats_estimator The statistics estimation instance used while training the tree.
      * \param[in] data_set The data set used for evaluation.
      * \param[in] examples The examples that have to be evaluated.
      * \param[out] label_data The destination where the resulting label data is added to.
      */
    void
    evaluateAndAdd (pcl::Fern<FeatureType, NodeType> & fern,
                    pcl::FeatureHandler<FeatureType, DataSet, ExampleIndex> & feature_handler,
                    pcl::StatsEstimator<LabelType, NodeType, DataSet, ExampleIndex> & stats_estimator,
                    DataSet & data_set,
                    std::vector<ExampleIndex> & examples,
                    std::vector<LabelType> & label_data);

    /** \brief Evaluates the specified examples using the supplied tree.
      * \param[in] tree The decision tree.
      * \param[in] feature_handler The feature handler used to train the tree.
      * \param[in] stats_estimator The statistics estimation instance used while training the tree.
      * \param[in] data_set The data set used for evaluation.
      * \param[in] examples The examples that have to be evaluated.
      * \param[out] nodes The leaf-nodes reached while evaluation.
      */
    void
    getNodes (pcl::Fern<FeatureType, NodeType> & fern,
              pcl::FeatureHandler<FeatureType, DataSet, ExampleIndex> & feature_handler,
              pcl::StatsEstimator<LabelType, NodeType, DataSet, ExampleIndex> & stats_estimator,
              DataSet & data_set,
              std::vector<ExampleIndex> & examples,
              std::vector<NodeType*> & nodes);

  };

}

#include <pcl/ml/impl/ferns/fern_evaluator.hpp>

#endif


text:
package springfox.documentation.swagger1.dto;

public class PrimitiveDataType implements SwaggerDataType {
    private String type;

    public PrimitiveDataType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    @Override
    public String getAbsoluteType() {
        return type;
    }
}


text:
// Copyright (c) 2018 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

// Prevent Windows headers from defining min/max macros and instead
// use STL.
#ifndef NOMINMAX
#define NOMINMAX
#endif  // ifndef NOMINMAX
#include <windows.h>

#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>

#include "leveldb/env.h"
#include "leveldb/slice.h"
#include "port/port.h"
#include "port/thread_annotations.h"
#include "util/env_windows_test_helper.h"
#include "util/logging.h"
#include "util/mutexlock.h"
#include "util/windows_logger.h"

#if defined(DeleteFile)
#undef DeleteFile
#endif  // defined(DeleteFile)

namespace leveldb {

namespace {

constexpr const size_t kWritableFileBufferSize = 65536;

// Up to 1000 mmaps for 64-bit binaries; none for 32-bit.
constexpr int kDefaultMmapLimit = sizeof(void*) >= 8 ? 1000 : 0;

// Modified by EnvWindowsTestHelper::SetReadOnlyMMapLimit().
int g_mmap_limit = kDefaultMmapLimit;

std::string GetWindowsErrorMessage(DWORD error_code) {
  std::string message;
  char* error_text = nullptr;
  // Use MBCS version of FormatMessage to match return value.
  size_t error_text_size = ::FormatMessageA(
      FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER |
          FORMAT_MESSAGE_IGNORE_INSERTS,
      nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
      reinterpret_cast<char*>(&error_text), 0, nullptr);
  if (!error_text) {
    return message;
  }
  message.assign(error_text, error_text_size);
  ::LocalFree(error_text);
  return message;
}

Status WindowsError(const std::string& context, DWORD error_code) {
  if (error_code == ERROR_FILE_NOT_FOUND || error_code == ERROR_PATH_NOT_FOUND)
    return Status::NotFound(context, GetWindowsErrorMessage(error_code));
  return Status::IOError(context, GetWindowsErrorMessage(error_code));
}

class ScopedHandle {
 public:
  ScopedHandle(HANDLE handle) : handle_(handle) {}
  ScopedHandle(ScopedHandle&& other) noexcept : handle_(other.Release()) {}
  ~ScopedHandle() { Close(); }

  ScopedHandle& operator=(ScopedHandle&& rhs) noexcept {
    if (this != &rhs) handle_ = rhs.Release();
    return *this;
  }

  bool Close() {
    if (!is_valid()) {
      return true;
    }
    HANDLE h = handle_;
    handle_ = INVALID_HANDLE_VALUE;
    return ::CloseHandle(h);
  }

  bool is_valid() const {
    return handle_ != INVALID_HANDLE_VALUE && handle_ != nullptr;
  }

  HANDLE get() const { return handle_; }

  HANDLE Release() {
    HANDLE h = handle_;
    handle_ = INVALID_HANDLE_VALUE;
    return h;
  }

 private:
  HANDLE handle_;
};

// Helper class to limit resource usage to avoid exhaustion.
// Currently used to limit read-only file descriptors and mmap file usage
// so that we do not run out of file descriptors or virtual memory, or run into
// kernel performance problems for very large databases.
class Limiter {
 public:
  // Limit maximum number of resources to |max_acquires|.
  Limiter(int max_acquires) : acquires_allowed_(max_acquires) {}

  Limiter(const Limiter&) = delete;
  Limiter operator=(const Limiter&) = delete;

  // If another resource is available, acquire it and return true.
  // Else return false.
  bool Acquire() {
    int old_acquires_allowed =
        acquires_allowed_.fetch_sub(1, std::memory_order_relaxed);

    if (old_acquires_allowed > 0)
      return true;

    acquires_allowed_.fetch_add(1, std::memory_order_relaxed);
    return false;
  }

  // Release a resource acquired by a previous call to Acquire() that returned
  // true.
  void Release() {
    acquires_allowed_.fetch_add(1, std::memory_order_relaxed);
  }

 private:
  // The number of available resources.
  //
  // This is a counter and is not tied to the invariants of any other class, so
  // it can be operated on safely using std::memory_order_relaxed.
  std::atomic<int> acquires_allowed_;
};

class WindowsSequentialFile : public SequentialFile {
 public:
  WindowsSequentialFile(std::string fname, ScopedHandle file)
      : filename_(fname), file_(std::move(file)) {}
  ~WindowsSequentialFile() override {}

  Status Read(size_t n, Slice* result, char* scratch) override {
    Status s;
    DWORD bytes_read;
    // DWORD is 32-bit, but size_t could technically be larger. However leveldb
    // files are limited to leveldb::Options::max_file_size which is clamped to
    // 1<<30 or 1 GiB.
    assert(n <= std::numeric_limits<DWORD>::max());
    if (!::ReadFile(file_.get(), scratch, static_cast<DWORD>(n), &bytes_read,
                    nullptr)) {
      s = WindowsError(filename_, ::GetLastError());
    } else {
      *result = Slice(scratch, bytes_read);
    }
    return s;
  }

  Status Skip(uint64_t n) override {
    LARGE_INTEGER distance;
    distance.QuadPart = n;
    if (!::SetFilePointerEx(file_.get(), distance, nullptr, FILE_CURRENT)) {
      return WindowsError(filename_, ::GetLastError());
    }
    return Status::OK();
  }

 private:
  std::string filename_;
  ScopedHandle file_;
};

class WindowsRandomAccessFile : public RandomAccessFile {
 public:
  WindowsRandomAccessFile(std::string fname, ScopedHandle handle)
      : filename_(fname), handle_(std::move(handle)) {}

  ~WindowsRandomAccessFile() override = default;

  Status Read(uint64_t offset, size_t n, Slice* result,
              char* scratch) const override {
    DWORD bytes_read = 0;
    OVERLAPPED overlapped = {0};

    overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32);
    overlapped.Offset = static_cast<DWORD>(offset);
    if (!::ReadFile(handle_.get(), scratch, static_cast<DWORD>(n), &bytes_read,
                    &overlapped)) {
      DWORD error_code = ::GetLastError();
      if (error_code != ERROR_HANDLE_EOF) {
        *result = Slice(scratch, 0);
        return Status::IOError(filename_, GetWindowsErrorMessage(error_code));
      }
    }

    *result = Slice(scratch, bytes_read);
    return Status::OK();
  }

 private:
  std::string filename_;
  ScopedHandle handle_;
};

class WindowsMmapReadableFile : public RandomAccessFile {
 public:
  // base[0,length-1] contains the mmapped contents of the file.
  WindowsMmapReadableFile(std::string fname, void* base, size_t length,
                          Limiter* limiter)
      : filename_(std::move(fname)),
        mmapped_region_(base),
        length_(length),
        limiter_(limiter) {}

  ~WindowsMmapReadableFile() override {
    ::UnmapViewOfFile(mmapped_region_);
    limiter_->Release();
  }

  Status Read(uint64_t offset, size_t n, Slice* result,
              char* scratch) const override {
    Status s;
    if (offset + n > length_) {
      *result = Slice();
      s = WindowsError(filename_, ERROR_INVALID_PARAMETER);
    } else {
      *result = Slice(reinterpret_cast<char*>(mmapped_region_) + offset, n);
    }
    return s;
  }

 private:
  std::string filename_;
  void* mmapped_region_;
  size_t length_;
  Limiter* limiter_;
};

class WindowsWritableFile : public WritableFile {
 public:
  WindowsWritableFile(std::string fname, ScopedHandle handle)
      : filename_(std::move(fname)), handle_(std::move(handle)), pos_(0) {}

  ~WindowsWritableFile() override = default;

  Status Append(const Slice& data) override {
    size_t n = data.size();
    const char* p = data.data();

    // Fit as much as possible into buffer.
    size_t copy = std::min(n, kWritableFileBufferSize - pos_);
    memcpy(buf_ + pos_, p, copy);
    p += copy;
    n -= copy;
    pos_ += copy;
    if (n == 0) {
      return Status::OK();
    }

    // Can't fit in buffer, so need to do at least one write.
    Status s = FlushBuffered();
    if (!s.ok()) {
      return s;
    }

    // Small writes go to buffer, large writes are written directly.
    if (n < kWritableFileBufferSize) {
      memcpy(buf_, p, n);
      pos_ = n;
      return Status::OK();
    }
    return WriteRaw(p, n);
  }

  Status Close() override {
    Status result = FlushBuffered();
    if (!handle_.Close() && result.ok()) {
      result = WindowsError(filename_, ::GetLastError());
    }
    return result;
  }

  Status Flush() override { return FlushBuffered(); }

  Status Sync() override {
    // On Windows no need to sync parent directory. It's metadata will be
    // updated via the creation of the new file, without an explicit sync.
    return FlushBuffered();
  }

 private:
  Status FlushBuffered() {
    Status s = WriteRaw(buf_, pos_);
    pos_ = 0;
    return s;
  }

  Status WriteRaw(const char* p, size_t n) {
    DWORD bytes_written;
    if (!::WriteFile(handle_.get(), p, static_cast<DWORD>(n), &bytes_written,
                     nullptr)) {
      return Status::IOError(filename_,
                             GetWindowsErrorMessage(::GetLastError()));
    }
    return Status::OK();
  }

  // buf_[0, pos_-1] contains data to be written to handle_.
  const std::string filename_;
  ScopedHandle handle_;
  char buf_[kWritableFileBufferSize];
  size_t pos_;
};

// Lock or unlock the entire file as specified by |lock|. Returns true
// when successful, false upon failure. Caller should call ::GetLastError()
// to determine cause of failure
bool LockOrUnlock(HANDLE handle, bool lock) {
  if (lock) {
    return ::LockFile(handle,
                      /*dwFileOffsetLow=*/0, /*dwFileOffsetHigh=*/0,
                      /*nNumberOfBytesToLockLow=*/MAXDWORD,
                      /*nNumberOfBytesToLockHigh=*/MAXDWORD);
  } else {
    return ::UnlockFile(handle,
                        /*dwFileOffsetLow=*/0, /*dwFileOffsetHigh=*/0,
                        /*nNumberOfBytesToLockLow=*/MAXDWORD,
                        /*nNumberOfBytesToLockHigh=*/MAXDWORD);
  }
}

class WindowsFileLock : public FileLock {
 public:
  WindowsFileLock(ScopedHandle handle, std::string name)
      : handle_(std::move(handle)), name_(std::move(name)) {}

  ScopedHandle& handle() { return handle_; }
  const std::string& name() const { return name_; }

 private:
  ScopedHandle handle_;
  std::string name_;
};

class WindowsEnv : public Env {
 public:
  WindowsEnv();
  ~WindowsEnv() override {
    static char msg[] = "Destroying Env::Default()\n";
    fwrite(msg, 1, sizeof(msg), stderr);
    abort();
  }

  Status NewSequentialFile(const std::string& fname,
                           SequentialFile** result) override {
    *result = nullptr;
    DWORD desired_access = GENERIC_READ;
    DWORD share_mode = FILE_SHARE_READ;
    ScopedHandle handle =
        ::CreateFileA(fname.c_str(), desired_access, share_mode, nullptr,
                      OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (!handle.is_valid()) {
      return WindowsError(fname, ::GetLastError());
    }
    *result = new WindowsSequentialFile(fname, std::move(handle));
    return Status::OK();
  }

  Status NewRandomAccessFile(const std::string& fname,
                             RandomAccessFile** result) override {
    *result = nullptr;
    DWORD desired_access = GENERIC_READ;
    DWORD share_mode = FILE_SHARE_READ;
    DWORD file_flags = FILE_ATTRIBUTE_READONLY;

    ScopedHandle handle =
        ::CreateFileA(fname.c_str(), desired_access, share_mode, nullptr,
                      OPEN_EXISTING, file_flags, nullptr);
    if (!handle.is_valid()) {
      return WindowsError(fname, ::GetLastError());
    }
    if (!mmap_limiter_.Acquire()) {
      *result = new WindowsRandomAccessFile(fname, std::move(handle));
      return Status::OK();
    }

    LARGE_INTEGER file_size;
    if (!::GetFileSizeEx(handle.get(), &file_size)) {
      return WindowsError(fname, ::GetLastError());
    }

    ScopedHandle mapping =
        ::CreateFileMappingA(handle.get(),
                             /*security attributes=*/nullptr, PAGE_READONLY,
                             /*dwMaximumSizeHigh=*/0,
                             /*dwMaximumSizeLow=*/0, nullptr);
    if (mapping.is_valid()) {
      void* base = MapViewOfFile(mapping.get(), FILE_MAP_READ, 0, 0, 0);
      if (base) {
        *result = new WindowsMmapReadableFile(
            fname, base, static_cast<size_t>(file_size.QuadPart),
            &mmap_limiter_);
        return Status::OK();
      }
    }
    Status s = WindowsError(fname, ::GetLastError());

    if (!s.ok()) {
      mmap_limiter_.Release();
    }
    return s;
  }

  Status NewWritableFile(const std::string& fname,
                         WritableFile** result) override {
    DWORD desired_access = GENERIC_WRITE;
    DWORD share_mode = 0;

    ScopedHandle handle =
        ::CreateFileA(fname.c_str(), desired_access, share_mode, nullptr,
                      CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
    if (!handle.is_valid()) {
      *result = nullptr;
      return WindowsError(fname, ::GetLastError());
    }

    *result = new WindowsWritableFile(fname, std::move(handle));
    return Status::OK();
  }

  Status NewAppendableFile(const std::string& fname,
                           WritableFile** result) override {
    ScopedHandle handle =
        ::CreateFileA(fname.c_str(), FILE_APPEND_DATA, 0, nullptr, OPEN_ALWAYS,
                      FILE_ATTRIBUTE_NORMAL, nullptr);
    if (!handle.is_valid()) {
      *result = nullptr;
      return WindowsError(fname, ::GetLastError());
    }

    *result = new WindowsWritableFile(fname, std::move(handle));
    return Status::OK();
  }

  bool FileExists(const std::string& fname) override {
    return GetFileAttributesA(fname.c_str()) != INVALID_FILE_ATTRIBUTES;
  }

  Status GetChildren(const std::string& dir,
                     std::vector<std::string>* result) override {
    const std::string find_pattern = dir + "\\*";
    WIN32_FIND_DATAA find_data;
    HANDLE dir_handle = ::FindFirstFileA(find_pattern.c_str(), &find_data);
    if (dir_handle == INVALID_HANDLE_VALUE) {
      DWORD last_error = ::GetLastError();
      if (last_error == ERROR_FILE_NOT_FOUND) {
        return Status::OK();
      }
      return WindowsError(dir, last_error);
    }
    do {
      char base_name[_MAX_FNAME];
      char ext[_MAX_EXT];

      if (!_splitpath_s(find_data.cFileName, nullptr, 0, nullptr, 0, base_name,
                        ARRAYSIZE(base_name), ext, ARRAYSIZE(ext))) {
        result->emplace_back(std::string(base_name) + ext);
      }
    } while (::FindNextFileA(dir_handle, &find_data));
    DWORD last_error = ::GetLastError();
    ::FindClose(dir_handle);
    if (last_error != ERROR_NO_MORE_FILES) {
      return WindowsError(dir, last_error);
    }
    return Status::OK();
  }

  Status DeleteFile(const std::string& fname) override {
    if (!::DeleteFileA(fname.c_str())) {
      return WindowsError(fname, ::GetLastError());
    }
    return Status::OK();
  }

  Status CreateDir(const std::string& name) override {
    if (!::CreateDirectoryA(name.c_str(), nullptr)) {
      return WindowsError(name, ::GetLastError());
    }
    return Status::OK();
  }

  Status DeleteDir(const std::string& name) override {
    if (!::RemoveDirectoryA(name.c_str())) {
      return WindowsError(name, ::GetLastError());
    }
    return Status::OK();
  }

  Status GetFileSize(const std::string& fname, uint64_t* size) override {
    WIN32_FILE_ATTRIBUTE_DATA attrs;
    if (!::GetFileAttributesExA(fname.c_str(), GetFileExInfoStandard, &attrs)) {
      return WindowsError(fname, ::GetLastError());
    }
    ULARGE_INTEGER file_size;
    file_size.HighPart = attrs.nFileSizeHigh;
    file_size.LowPart = attrs.nFileSizeLow;
    *size = file_size.QuadPart;
    return Status::OK();
  }

  Status RenameFile(const std::string& src,
                    const std::string& target) override {
    // Try a simple move first.  It will only succeed when |to_path| doesn't
    // already exist.
    if (::MoveFileA(src.c_str(), target.c_str())) {
      return Status::OK();
    }
    DWORD move_error = ::GetLastError();

    // Try the full-blown replace if the move fails, as ReplaceFile will only
    // succeed when |to_path| does exist. When writing to a network share, we
    // may not be able to change the ACLs. Ignore ACL errors then
    // (REPLACEFILE_IGNORE_MERGE_ERRORS).
    if (::ReplaceFileA(target.c_str(), src.c_str(), nullptr,
                       REPLACEFILE_IGNORE_MERGE_ERRORS, nullptr, nullptr)) {
      return Status::OK();
    }
    DWORD replace_error = ::GetLastError();
    // In the case of FILE_ERROR_NOT_FOUND from ReplaceFile, it is likely
    // that |to_path| does not exist. In this case, the more relevant error
    // comes from the call to MoveFile.
    if (replace_error == ERROR_FILE_NOT_FOUND ||
        replace_error == ERROR_PATH_NOT_FOUND) {
      return WindowsError(src, move_error);
    } else {
      return WindowsError(src, replace_error);
    }
  }

  Status LockFile(const std::string& fname, FileLock** lock) override {
    *lock = nullptr;
    Status result;
    ScopedHandle handle = ::CreateFileA(
        fname.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ,
        /*lpSecurityAttributes=*/nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL,
        nullptr);
    if (!handle.is_valid()) {
      result = WindowsError(fname, ::GetLastError());
    } else if (!LockOrUnlock(handle.get(), true)) {
      result = WindowsError("lock " + fname, ::GetLastError());
    } else {
      *lock = new WindowsFileLock(std::move(handle), std::move(fname));
    }
    return result;
  }

  Status UnlockFile(FileLock* lock) override {
    std::unique_ptr<WindowsFileLock> my_lock(
        reinterpret_cast<WindowsFileLock*>(lock));
    Status result;
    if (!LockOrUnlock(my_lock->handle().get(), false)) {
      result = WindowsError("unlock", ::GetLastError());
    }
    return result;
  }

  void Schedule(void (*function)(void*), void* arg) override;

  void StartThread(void (*function)(void* arg), void* arg) override {
    std::thread t(function, arg);
    t.detach();
  }

  Status GetTestDirectory(std::string* result) override {
    const char* env = getenv("TEST_TMPDIR");
    if (env && env[0] != '\0') {
      *result = env;
      return Status::OK();
    }

    char tmp_path[MAX_PATH];
    if (!GetTempPathA(ARRAYSIZE(tmp_path), tmp_path)) {
      return WindowsError("GetTempPath", ::GetLastError());
    }
    std::stringstream ss;
    ss << tmp_path << "leveldbtest-" << std::this_thread::get_id();
    *result = ss.str();

    // Directory may already exist
    CreateDir(*result);
    return Status::OK();
  }

  Status NewLogger(const std::string& filename, Logger** result) override {
    std::FILE* fp = std::fopen(filename.c_str(), "w");
    if (fp == nullptr) {
      *result = nullptr;
      return WindowsError("NewLogger", ::GetLastError());
    } else {
      *result = new WindowsLogger(fp);
      return Status::OK();
    }
  }

  uint64_t NowMicros() override {
    // GetSystemTimeAsFileTime typically has a resolution of 10-20 msec.
    // TODO(cmumford): Switch to GetSystemTimePreciseAsFileTime which is
    // available in Windows 8 and later.
    FILETIME ft;
    ::GetSystemTimeAsFileTime(&ft);
    // Each tick represents a 100-nanosecond intervals since January 1, 1601
    // (UTC).
    uint64_t num_ticks =
        (static_cast<uint64_t>(ft.dwHighDateTime) << 32) + ft.dwLowDateTime;
    return num_ticks / 10;
  }

  void SleepForMicroseconds(int micros) override {
    std::this_thread::sleep_for(std::chrono::microseconds(micros));
  }

 private:
  // BGThread() is the body of the background thread
  void BGThread();

  std::mutex mu_;
  std::condition_variable bgsignal_;
  bool started_bgthread_;

  // Entry per Schedule() call
  struct BGItem {
    void* arg;
    void (*function)(void*);
  };
  typedef std::deque<BGItem> BGQueue;
  BGQueue queue_;

  Limiter mmap_limiter_;
};

// Return the maximum number of concurrent mmaps.
int MaxMmaps() {
  if (g_mmap_limit >= 0) {
    return g_mmap_limit;
  }
  // Up to 1000 mmaps for 64-bit binaries; none for smaller pointer sizes.
  g_mmap_limit = sizeof(void*) >= 8 ? 1000 : 0;
  return g_mmap_limit;
}

WindowsEnv::WindowsEnv()
    : started_bgthread_(false), mmap_limiter_(MaxMmaps()) {}

void WindowsEnv::Schedule(void (*function)(void*), void* arg) {
  std::lock_guard<std::mutex> guard(mu_);

  // Start background thread if necessary
  if (!started_bgthread_) {
    started_bgthread_ = true;
    std::thread t(&WindowsEnv::BGThread, this);
    t.detach();
  }

  // If the queue is currently empty, the background thread may currently be
  // waiting.
  if (queue_.empty()) {
    bgsignal_.notify_one();
  }

  // Add to priority queue
  queue_.push_back(BGItem());
  queue_.back().function = function;
  queue_.back().arg = arg;
}

void WindowsEnv::BGThread() {
  while (true) {
    // Wait until there is an item that is ready to run
    std::unique_lock<std::mutex> lk(mu_);
    bgsignal_.wait(lk, [this] { return !queue_.empty(); });

    void (*function)(void*) = queue_.front().function;
    void* arg = queue_.front().arg;
    queue_.pop_front();

    lk.unlock();
    (*function)(arg);
  }
}

}  // namespace

static std::once_flag once;
static Env* default_env;
static void InitDefaultEnv() { default_env = new WindowsEnv(); }

void EnvWindowsTestHelper::SetReadOnlyMMapLimit(int limit) {
  assert(default_env == nullptr);
  g_mmap_limit = limit;
}

Env* Env::Default() {
  std::call_once(once, InitDefaultEnv);
  return default_env;
}

}  // namespace leveldb


text:
var url = require('url');
var semver = require('semver');
var nijs = require('nijs');
var inherit = require('nijs/lib/ast/util/inherit.js').inherit;
var base64js = require('base64-js');

/**
 * Creates a new source instance. This function should never be used directly,
 * instead use: Source.constructSource to construct a source object.
 *
 * @class Source
 * @extends NixASTNode
 * @classdesc Represents a file that is obtained from an external source
 *
 * @constructor
 * @param {String} baseDir Directory in which the referrer's package.json configuration resides
 * @param {String} dependencyName Name of the dependency
 * @param {String} versionSpec Version specifier of the Node.js package to fetch
 */
function Source(baseDir, dependencyName, versionSpec) {
    this.baseDir = baseDir;
    this.dependencyName = dependencyName;
    this.versionSpec = versionSpec;
}

/* Source inherits from NixASTNode */
inherit(nijs.NixASTNode, Source);

/**
 * Constructs a specific kind of source by inspecting the version specifier.
 *
 * @param {Registry[]} registries
 * @param {String} baseDir Directory in which the referrer's package.json configuration resides
 * @param {String} outputDir Directory in which the nix expression will be written
 * @param {String} dependencyName Name of the dependency
 * @param {String} versionSpec Version specifier of the Node.js package to fetch
 * @param {Boolean} stripOptionalDependencies When enabled, the optional
 *   dependencies are stripped from the regular dependencies in the NPM registry
 */
Source.constructSource = function(registries, baseDir, outputDir, dependencyName, versionSpec, stripOptionalDependencies) {
    // Load modules here, to prevent cycles in the include process
    var GitSource = require('./GitSource.js').GitSource;
    var HTTPSource = require('./HTTPSource.js').HTTPSource;
    var LocalSource = require('./LocalSource.js').LocalSource;
    var NPMRegistrySource = require('./NPMRegistrySource.js').NPMRegistrySource;

    var parsedVersionSpec = semver.validRange(versionSpec, true);
    var parsedUrl = url.parse(versionSpec);

    if(parsedVersionSpec !== null) { // If the version is valid semver range, fetch the package from the NPM registry
        return new NPMRegistrySource(baseDir, dependencyName, parsedVersionSpec, registries, stripOptionalDependencies);
    } else if(parsedUrl.protocol == "github:") { // If the version is a GitHub repository, compose the corresponding Git URL and do a Git checkout
        return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("git+https://github.com", parsedUrl));
    } else if(parsedUrl.protocol == "gist:") { // If the version is a GitHub gist repository, compose the corresponding Git URL and do a Git checkout
        return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("git+https://gist.github.com", parsedUrl));
    } else if(parsedUrl.protocol == "bitbucket:") { // If the version is a Bitbucket repository, compose the corresponding Git URL and do a Git checkout
        return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("git+https://bitbucket.org", parsedUrl));
    } else if(parsedUrl.protocol == "gitlab:") { // If the version is a Gitlab repository, compose the corresponding Git URL and do a Git checkout
        return new GitSource(baseDir, dependencyName, GitSource.composeGitURL("git+https://gitlab.com", parsedUrl));
    } else if(typeof parsedUrl.protocol == "string" && parsedUrl.protocol.substr(0, 3) == "git") { // If the version is a Git URL do a Git checkout
        return new GitSource(baseDir, dependencyName, versionSpec);
    } else if(parsedUrl.protocol == "http:" || parsedUrl.protocol == "https:") { // If the version is an HTTP URL do a download
        return new HTTPSource(baseDir, dependencyName, versionSpec);
    } else if(versionSpec.match(/^[a-zA-Z0-9_\-]+\/[a-zA-Z0-9\.]+([#[a-zA-Z0-9_\-]|pull\/[0-9]+\/[a-zA-Z0-9\.]+[#[a-zA-Z0-9_\-]+)+]?$/)) { // If the version is a GitHub repository, compose the corresponding Git URL and do a Git checkout
        return new GitSource(baseDir, dependencyName, "git+https://github.com/"+versionSpec);
    } else if(parsedUrl.protocol == "file:") { // If the version is a file URL, simply compose a Nix path
        return new LocalSource(baseDir, dependencyName, outputDir, parsedUrl.path);
    } else if(versionSpec.substr(0, 3) == "../" || versionSpec.substr(0, 2) == "~/" || versionSpec.substr(0, 2) == "./" || versionSpec.substr(0, 1) == "/") { // If the version is a path, simply compose a Nix path
        return new LocalSource(baseDir, dependencyName, outputDir, versionSpec);
    } else { // In all other cases, just try the registry. Sometimes invalid semver ranges are encountered or a tag has been provided (e.g. 'latest', 'unstable')
        return new NPMRegistrySource(baseDir, dependencyName, versionSpec, registries, stripOptionalDependencies);
    }
};

/**
 * Fetches the package metadata from the external source.
 *
 * @method
 * @param {function(String)} callback Callback that gets invoked when the work
 *     is done. In case of an error, it will set the first parameter to contain
 *     an error message.
 */
Source.prototype.fetch = function(callback) {
    callback("fetch() is not implemented, please use a prototype that inherits from Source");
};

/**
 * Takes a dependency object from a lock file and converts it into a source object.
 *
 * @param {Object} dependencyObj Dependency object from the lock file
 * @param {function(String)} callback Callback that gets invoked when the work
 *     is done. In case of an error, it will set the first parameter to contain
 *     an error message.
 */
Source.prototype.convertFromLockedDependency = function(dependencyObj, callback) {
    callback("convertFromLockedDependency() is not implemented, please use a prototype that inherits from Source");
};

/**
 * Converts NPM's integrity strings that have the following format:
 * <algorithm>-<base64 hash> to a hash representation that Nix understands.
 *
 * @method
 * @param {String} integrity NPM integrity string
 */
Source.prototype.convertIntegrityStringToNixHash = function(integrity) {
    if(integrity.substr(0, 5) === "sha1-") {
        var hash = base64js.toByteArray(integrity.substring(5));
        this.hashType = "sha1";
        this.sha1 = Buffer.from(hash).toString('hex');
    } else if(integrity.substr(0, 7) === "sha512-") {
        this.hashType = "sha512";
        this.sha512 = integrity.substring(7);
    } else {
        throw "Unknown integrity string: "+integrity;
    }
};

/**
 * @see NixASTNode#toNixAST
 */
Source.prototype.toNixAST = function() {
    return {
        name: this.config.name.replace("@", "_at_").replace("/", "_slash_"), // Escape characters from scoped package names that aren't allowed
        packageName: this.config.name,
        version: this.config.version
    };
};

exports.Source = Source;


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:security="http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                           http://www.springframework.org/schema/tx
                           http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
                           http://www.springframework.org/schema/context
                           http://www.springframework.org/schema/context/spring-context-3.1.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
                           http://www.springframework.org/schema/security
                           http://www.springframework.org/schema/security/spring-security-3.1.xsd">

	<context:annotation-config />
	<context:spring-configured />
	<tx:jta-transaction-manager />
	<tx:annotation-driven transaction-manager="transactionManager" />

	<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.MessageDigestPasswordEncoder">
    	<constructor-arg value="MD5"/>
	</bean>

	<bean id="notificationTemplateMessage" class="org.springframework.mail.SimpleMailMessage">
		<property name="from" value="a.vincelli@gmail.com"/>
	</bean>

	<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
		<property name="basename" value="classpath:it/av/youeat/web/YoueatApplication"/>
		<property name="fallbackToSystemLocale" value="true" />
		<property name="cacheSeconds" value="-1"/>
	</bean>

	<bean id="javaMailSender" class="it.av.youeat.web.util.MockJavaMailSender" >
		<!-- <property name="host" value="127.0.0.1"/> -->
	</bean>

	<bean id="mailService" class="it.av.youeat.service.system.MailServiceImpl" />

	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="youeatPersistence" />
		<property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"/>
	</bean>

	<!-- <bean id="entityManagerFactoryStaticData" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="persistenceUnitName" value="staticDataPersistance" />
		<property name="persistenceXmlLocation" value="classpath:META-INF/persistenceStaticData.xml"></property>
	</bean> -->

	<!--
		PostProcessors to perform resource injection according to the JPA specification
		(@PersistenceContext, @PersistenceUnit).
	-->
	<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

	<!-- turn on @Required annotation checks -->
	<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>

	<!--
		PostProcessors to perform exception translation on @Repository classes (from native
		exceptions such as JPA PersistenceExceptions to Spring's DataAccessException hierarchy).
	-->
	<!-- Transaction manager for a single JPA EntityManagerFactory (alternative to JTA) -->
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
		<property name="nestedTransactionAllowed" value="false"></property>
	</bean>

<!--  	<bean id="wicketApplication" class="it.av.youeat.web.YouetApplicationMock">
		<property name="applicationURL" value="http://www.youeat.org"/>
	</bean> -->

	<bean id="eaterService" class="it.av.youeat.service.impl.EaterServiceHibernate" />

	<bean id="commentService" class="it.av.youeat.service.impl.CommentServiceHibernate"/>

	<bean id="eaterProfileService" class="it.av.youeat.service.impl.EaterProfileServiceHibernate"/>

	<bean id="activityService" class="it.av.youeat.service.impl.ActivityServiceHibernate" />

	<bean id="activityRistoranteService" class="it.av.youeat.service.impl.ActivityRistoranteServiceHibernate" />

	<bean id="tagService" class="it.av.youeat.service.impl.TagServiceHibernate" />

	<bean id="ristoranteRevisionService" class="it.av.youeat.service.impl.RistoranteRevisionServiceHibernate"/>

	<bean id="rateRistoranteService" class="it.av.youeat.service.impl.RateRistoranteServiceHibernate"/>

	<bean id="ristoranteService" class="it.av.youeat.service.impl.RistoranteServiceHibernate" />

    <bean id="ristorantePositionService" class="it.av.youeat.service.impl.RistorantePositionServiceHibernate"/>

	<!--<bean id="jcrRistoranteService" class="it.av.youeat.service.impl.JcrRistoranteServiceJackrabbit">
		<property name="jcrMappingtemplate" ref="jcrMappingTemplateGeneric" />
		<property name="basePath" value="/ristoranti" />
	</bean>-->

	<bean id="eaterRelationService" class="it.av.youeat.service.impl.EaterRelationServiceHibernate" />

	<bean id="activityRelationService" class="it.av.youeat.service.impl.ActivityRelationServiceHibernate" />

	<bean id="dataRistoranteService" class="it.av.youeat.service.impl.DataRistoranteServiceHibernate" />

	<bean id="countryRegionService" class="it.av.youeat.service.impl.CountryRegionServiceHibernate" />

	<bean id="countryService" class="it.av.youeat.service.impl.CountryServiceHibernate" />

	<bean id="cityService" class="it.av.youeat.service.impl.CityServiceHibernate" />

	<bean id="languageService" class="it.av.youeat.service.impl.LanguageServiceHibernate" />

	<bean id="messageService" class="it.av.youeat.service.impl.MessageServiceHibernate" />

	<bean id="dialogService" class="it.av.youeat.service.impl.DialogServiceHibernate" />

	<bean id="ristorantePictureHibernate" class="it.av.youeat.service.impl.RistorantePictureHibernate" />

	<bean id="userDetailsService" class="it.av.youeat.web.security.UserDetailsServiceImpl" scope="prototype">
		<property name="service" ref="eaterService" />
	</bean>

	<bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
		<property name="userDetailsService" ref="userDetailsService" />
		<property name="passwordEncoder" ref="passwordEncoder" />
		<property name="saltSource">
			<bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
				<property name="userPropertyToUse" value="passwordSalt"></property>
			</bean>
		</property>
	</bean>

	<bean id="facebookAuthenticationProvider" class="it.av.youeat.web.security.FacebookAuthenticationProvider"/>

	<bean id="authenticationProvider" class="it.av.youeat.web.security.AuthenticationProvider">
		<constructor-arg ref="daoAuthenticationProvider" />
		<constructor-arg ref="facebookAuthenticationProvider" />
	</bean>

	<bean id="serverGeocoder" class="it.av.youeat.util.ServerGeocoder">
		<constructor-arg value="ABQIAAAAEpqZyWLxrLSc1icxiiTLyBRjFP5Ion2TodTauLHyn40LiCPQaRSoBSldN1pDUDTAPEK5AlXpouSLuA"></constructor-arg>
	</bean>

	<bean id="periodUtil" class="it.av.youeat.util.PeriodUtil"/>

	<bean id="templateUtil" class="it.av.youeat.util.TemplateUtil"/>

	<bean id="socialServiceFacebook" class="it.av.youeat.service.impl.SocialServiceFacebook">
		<property name="apiKey" value=""/>
		<property name="secret" value=""/>
		<property name="applicationID" value=""/>
	</bean>

    <bean id="prepareMessage" class="it.av.youeat.service.support.PrepareMessage"/>

	<bean id="faceBookAuthHandler" class="it.av.youeat.web.security.FaceBookAuthHandler">
		<property name="apiKey" value=""/>
		<property name="secret" value=""/>
	</bean>

	<bean id="googleSitemapGenerator" class="it.av.youeat.web.xml.GoogleSitemapGenerator">
    	<property name="baseURL" value="http://www.youeat.org"></property>
    </bean>

    <bean id="youetGeneratorURL" class="it.av.youeat.web.url.YouetGeneratorURL">
    	<property name="baseURL" value="http://www.youeat.org"></property>
    </bean>

	<bean id="atomGenerator" class="it.av.youeat.web.xml.AtomGenerator"/>

    <bean id="jaxbObjectMapper" class="it.av.youeat.web.rest.JaxbObjectMapper" />

    <bean id="mappingJacksonJsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
        <property name="objectMapper" ref="jaxbObjectMapper"/>
    </bean>

</beans>


text:
  Vélu est
       un village
       géographiquement positionné dans le département des Pas-de-Calais en Nord-Pas-de-Calais. On dénombrait 129 habitants en 2008.

À coté de Vélu sont positionnées géographiquement les communes de
Frémicourt située à 4 km, 316 habitants,
Beugny localisée à 3 km, 312 habitants,
Barastre localisée à 4 km, 241 habitants,
Doignies localisée à 3 km, 254 habitants,
Morchies située à 3 km, 180 habitants,
Haplincourt localisée à 3 km, 200 habitants,
 entre autres. De plus, Vélu est située à seulement 29 km de Douai.

Le parc de logements, à Vélu, était réparti en 2011 en zero appartements et 67 maisons soit
 un marché plutôt équilibré.

Si vous pensez venir habiter à Vélu, vous pourrez aisément trouver une maison à vendre.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>User</title>
<meta name="date" content="2015-10-02">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

type

Class User

java.lang.Object

type.User

public class User
extends java.lang.Object

ˈ

Author:

Geurney

Field Summary

Fields

Modifier and Type
Field and Description

private java.lang.String
blogFolder

ÎÄÕ±£´æĿ¼

private java.util.List<java.lang.String>
blogInfo

²©¿ÍÐÅÏ¢(·ÃÎÊ¡¢ÅÅÃû¡¢»ý·Ö¡¢Ô´´¡¢×ªÔØ¡¢ÒëÎĺÍÆÀÂÛ)

private java.util.List<Category>
categoreis

ÎÄÕ·ÖÀà

private java.lang.String
name

̞

private java.lang.String
path

Óû§±£´æ·¾¶

private java.lang.String
profileImage

Í·ÏñͼƬµØÖ·

private java.lang.String
url

²©¿ÍÊ×Ò³

Constructor Summary

Constructors

Constructor and Description

User()

User¹¹Ô캯Êý

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.String
getBlogFolder()

»ñÈ¡Óû§ÎÄÕÂĿ¼

java.util.List<java.lang.String>
getBlogInfo()

»ñÈ¡Óû§²©¿ÍÐÅÏ¢

java.util.List<Category>
getCategoreis()

»ñÈ¡Óû§ÎÄÕ·ÖÀà

java.lang.String
getName()

»ñÈ¡Óû§Ãû

java.lang.String
getPath()

»ñÈ¡Óû§±£´æ·¾¶

java.lang.String
getProfileImage()

»ñÈ¡Óû§Í·Ïñ±£´æ·¾¶

java.lang.String
getUrl()

»ñÈ¡Óû§²©¿ÍÊ×Ò³url

void
setBlogFolder(java.lang.String blogFolder)

¡®
 ÉèÖÃÓû§ÎÄÕÂĿ¼

void
setBlogInfo(java.util.List<java.lang.String> blogInfo)

ÉèÖÃÓû§²©¿ÍÐÅÏ¢

void
setCategoreis(java.util.List<Category> categoreis)

ÉèÖÃÓû§ÎÄÕ·ÖÀà

void
setName(java.lang.String name)

ÉèÖÃÓû§Ãû

void
setPath(java.lang.String path)

ÉèÖÃÓû§±£´æ·¾¶

void
setProfileImage(java.lang.String profileImage)

ÉèÖÃÓû§Í·Ïñ±£´æ·¾¶

void
setUrl(java.lang.String url)

ÉèÖÃÓû§²©¿ÍÊ×Ò³url

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

name

private java.lang.String name

̞

url

private java.lang.String url

²©¿ÍÊ×Ò³

path

private java.lang.String path

Óû§±£´æ·¾¶

blogFolder

private java.lang.String blogFolder

ÎÄÕ±£´æĿ¼

blogInfo

private java.util.List<java.lang.String> blogInfo

²©¿ÍÐÅÏ¢(·ÃÎÊ¡¢ÅÅÃû¡¢»ý·Ö¡¢Ô´´¡¢×ªÔØ¡¢ÒëÎĺÍÆÀÂÛ)

profileImage

private java.lang.String profileImage

Í·ÏñͼƬµØÖ·

categoreis

private java.util.List<Category> categoreis

ÎÄÕ·ÖÀà

Constructor Detail

User

public User()

User¹¹Ô캯Êý

Method Detail

getName

public java.lang.String getName()

»ñÈ¡Óû§Ãû

Returns:

̞

setName

public void setName(java.lang.String name)

ÉèÖÃÓû§Ãû

Parameters:

name - ̞

getPath

public java.lang.String getPath()

»ñÈ¡Óû§±£´æ·¾¶

Returns:

Óû§±£´æ·¾¶

setPath

public void setPath(java.lang.String path)

ÉèÖÃÓû§±£´æ·¾¶

Parameters:

path - Óû§±£´æ·¾¶

getBlogFolder

public java.lang.String getBlogFolder()

»ñÈ¡Óû§ÎÄÕÂĿ¼

Returns:

Óû§ÎÄÕÂĿ¼

setBlogFolder

public void setBlogFolder(java.lang.String blogFolder)

¡®
 ÉèÖÃÓû§ÎÄÕÂĿ¼

Parameters:

blogFolder - Óû§ÎÄÕÂĿ¼

getBlogInfo

public java.util.List<java.lang.String> getBlogInfo()

»ñÈ¡Óû§²©¿ÍÐÅÏ¢

Returns:

Óû§²©¿ÍÐÅÏ¢

setBlogInfo

public void setBlogInfo(java.util.List<java.lang.String> blogInfo)

ÉèÖÃÓû§²©¿ÍÐÅÏ¢

Parameters:

blogInfo - Óû§²©¿ÍÐÅÏ¢

getProfileImage

public java.lang.String getProfileImage()

»ñÈ¡Óû§Í·Ïñ±£´æ·¾¶

Returns:

Óû§Í·Ïñ±£´æ·¾¶

setProfileImage

public void setProfileImage(java.lang.String profileImage)

ÉèÖÃÓû§Í·Ïñ±£´æ·¾¶

Parameters:

profileImage - Óû§Í·Ïñ±£´æ·¾¶

getCategoreis

public java.util.List<Category> getCategoreis()

»ñÈ¡Óû§ÎÄÕ·ÖÀà

Returns:

Óû§ÎÄÕ·ÖÀà

setCategoreis

public void setCategoreis(java.util.List<Category> categoreis)

ÉèÖÃÓû§ÎÄÕ·ÖÀà

Parameters:

categoreis - Óû§ÎÄÕ·ÖÀà

getUrl

public java.lang.String getUrl()

»ñÈ¡Óû§²©¿ÍÊ×Ò³url

Returns:

Óû§²©¿ÍÊ×Ò³url

setUrl

public void setUrl(java.lang.String url)

ÉèÖÃÓû§²©¿ÍÊ×Ò³url

Parameters:

url - Óû§²©¿ÍÊ×Ò³url

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace HighSolutions\LangImportExport;

use Illuminate\Support\ServiceProvider;
use HighSolutions\LangImportExport\Console\ExportToCsvCommand;
use HighSolutions\LangImportExport\Console\ImportFromCsvCommand;

class LangImportExportServiceProvider extends ServiceProvider
{

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->registerExportToCsvCommand();
		$this->registerImportFromCsvCommand();
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app->singleton('LangImportExportLangListService', function() {
			return new LangListService;
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return [
			'lang-export.csv', 'lang-import.csv'
		];
	}

	private function registerExportToCsvCommand()
	{
		$this->app->singleton('lang-export.csv', function($app)	{
			return new ExportToCsvCommand();
		});

		$this->commands('lang-export.csv');
	}

	private function registerImportFromCsvCommand()
	{
		$this->app->singleton('lang-import.csv', function($app) {
			return new ImportFromCsvCommand();
		});

		$this->commands('lang-import.csv');
	}

}


text:
import { module, test } from 'qunit';
import Hmacsha1 from 'cryptojs/hmac-sha1';

module('Hmac-sha1 as an ES6 module', function() {
  test('it has been imported', function(assert) {
    assert.ok(Hmacsha1);
  });

  test('test hash function', function(assert) {
    let hash = new Hmacsha1("Test123", "secret");
    assert.equal(hash, 'b128b6ba2d199f368eab53f0e425bf9e73c2ac7b');
  });
});


text:
import React from 'react';
import R from 'ramda';
import {
  Link
} from 'react-router';
import AllStats from './stats/AllStats.js';
import SummaryStats from './stats/SummaryStats.js';
import AccuracyGraphComponent from './stats/AccuracyGraphComponent.jsx';

class StatsComponent extends React.Component {
  constructor(props, context) {
    super(props, context);
  }

  render() {
    const results = this.props.data;

    if (R.findIndex(R.propEq('guess', 'none'), results) == 0){
      return (

No data has been gathered…yet.

              <Link className="pure-button button-success button-candidate" to="/play">Play Now!</Link>

      );
    }

    return (

        <SummaryStats results={results} />
        <AccuracyGraphComponent results={results} />
        <AllStats results={results} />

    );
  }
}

export default StatsComponent;


text:
<?php

namespace Goteo\Controller\Admin {

    use Goteo\Core\View,
        Goteo\Core\Redirection,
        Goteo\Core\Error,
		Goteo\Library\Text,
        Goteo\Library\Message,
		Goteo\Library\Template,
        Goteo\Library\Newsletter as Boletin,
		Goteo\Library\Sender;

    class Newsletter {

        public static function process ($action = 'list', $id = null, $filters = array()) {

            switch ($action) {
                case 'init':
                    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

                        // plantilla
                        $template = $_POST['template'];

                        // destinatarios
                        if ($_POST['test']) {
                            $users = Boletin::getTesters();
                        } elseif ($template == 33) {
                            // los destinatarios de newsletter
                            $users = Boletin::getReceivers();
                        } elseif ($template == 35) {
                            // los destinatarios para testear a subscriptores
                            $users = Boletin::getReceivers();
                        }

                        // sin idiomas
                        $nolang = $_POST['nolang'];
                        if ($nolang) {
                            $receivers[LANG] = $users;
                        } else {
                            // separamos destinatarios en idiomas
                            $receivers = array();
                            foreach ($users as $usr) {
                                if (empty($usr->lang) || $usr->lang == LANG) {
                                    $receivers[LANG][] = $usr;
                                } else {
                                    $receivers[$usr->lang][] = $usr;
                                }
                            }
                        }

                        // idiomas que vamos a enviar
                        $langs = array_keys($receivers);

                        // para cada idioma
                        foreach ($langs as $lang) {

                            // destinatarios
                            $recipients = $receivers[$lang];

                            // datos de la plantilla
                            $tpl = Template::get($template, $lang);

                            // contenido de newsletter
                            $content = ($template == 33) ? Boletin::getContent($tpl->text, $lang) : $content = $tpl->text;

                            // asunto
                            $subject = $tpl->title;

                            // creamos instancia
                            $sql = "INSERT INTO mail (id, email, html, template) VALUES ('', :email, :html, :template)";
                            $values = array (
                                ':email' => 'any',
                                ':html' => $content,
                                ':template' => $template
                            );
                            $query = \Goteo\Core\Model::query($sql, $values);
                            $mailId = \Goteo\Core\Model::insertId();

                            // inicializamos el envío
                            if (Sender::initiateSending($mailId, $subject, $recipients, true)) {
                                // ok...
                            } else {
                                Message::Error('No se ha podido iniciar el mailing con asunto "'.$subject.'"');
                            }
                        }

                    }

                    throw new Redirection('/admin/newsletter');

                    break;
                case 'activate':
                    if (Sender::activateSending($id)) {
                        Message::Info('Se ha activado un nuevo envío automático');
                    } else {
                        Message::Error('No se pudo activar el envío. Iniciar de nuevo');
                    }
                    throw new Redirection('/admin/newsletter');
                    break;
                case 'detail':

                    $mailing = Sender::getSending($id);
                    $list = Sender::getDetail($id, $filters['show']);

                    return new View(
                        'view/admin/index.html.php',
                        array(
                            'folder' => 'newsletter',
                            'file' => 'detail',
                            'detail' => $filters['show'],
                            'mailing' => $mailing,
                            'list' => $list
                        )
                    );
                    break;
                default:
                    $list = Sender::getMailings();

                    return new View(
                        'view/admin/index.html.php',
                        array(
                            'folder' => 'newsletter',
                            'file' => 'list',
                            'list' => $list
                        )
                    );
            }

        }
    }

}


text:
#if NETFX_PHONE
//-----------------------------------------------------------------------
// <copyright file="ValidationResult.cs" company="Marimer LLC">
//     Copyright (c) Marimer LLC. All rights reserved.
//     Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Results of a validation operation.</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.ComponentModel.DataAnnotations
{
  /// <summary>
  /// Results of a validation operation.
  /// </summary>
  public class ValidationResult
  {
    /// <summary>
    /// Creates an instance of the object.
    /// </summary>
    /// <param name="errorMessage">The error message for the validation.</param>
    public ValidationResult(string errorMessage)
    {
      ErrorMessage = errorMessage;
    }

    /// <summary>
    /// Creates an instance of the object.
    /// </summary>
    /// <param name="errorMessage">The error message for the validation.</param>
    /// <param name="memberNames">The collection of member names that indicate
    /// which fields have validation errors.</param>
    public ValidationResult(string errorMessage, IEnumerable<string> memberNames)
      : this(errorMessage)
    {
      MemberNames = memberNames;
    }

    /// <summary>
    /// Gets the error message for the validation.
    /// </summary>
    public string ErrorMessage { get; protected set; }
    /// <summary>
    /// Gets the collection of member names that indicate which
    /// fields have validation errors.
    /// </summary>
    public IEnumerable<string> MemberNames { get; protected set; }
  }
}
#else
[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(System.ComponentModel.DataAnnotations.ValidationResult))]
#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Divergent.Sales.Data.Models;

namespace Divergent.Sales.Data.Migrations
{
    internal static class SeedData
    {
        static int thePhantomMenace = 7;
        static int attackOfTheClones = 1;
        static int revengeOfTheSith = 2;
        static int aNewHope = 3;
        static int theEmpireStrikesBack = 4;
        static int returnOfTheJedi = 5;
        static int theForceAwakens = 6;

        static Product theForceAwakensProduct = new Product() { Id = theForceAwakens, Name = "Star Wars : The Force Awakens" };
        static Product aNewHopeProduct = new Product() { Id = aNewHope, Name = "Star Wars : A New Hope" };

        internal static List<Product> Products()
        {
            return new List<Product>()
            {
                new Product() {Id = thePhantomMenace, Name = "Star Wars : The Phantom Menace"},
                new Product() {Id = attackOfTheClones, Name = "Star Wars : Attack of the Clones"},
                new Product() {Id = revengeOfTheSith, Name = "Star Wars : Revenge of the Sith"},
                aNewHopeProduct,
                new Product() {Id = theEmpireStrikesBack, Name = "Star Wars : The Empire Strikes Back"},
                new Product() {Id = returnOfTheJedi, Name = "Star Wars : Return of the Jedi"},
                theForceAwakensProduct
            };
        }

        internal static List<Order> Orders()
        {
            var particularId = 1;
            var particularOrderId = 1;

            var nserviceBusId = 2;
            var nserivceBusOrderId = 2;

            //
            // 'orderlines' for particular order
            //
            var particularItems = new Item[]
            {
                new Item()
                {
                    Product = theForceAwakensProduct
                },
                new Item()
                {
                    Product = aNewHopeProduct
                }
            };

            //
            // 'orderline' for nservicebus order
            //
            var nservicebusItems = new Item[]
            {
                new Item()
                {
                    Product = theForceAwakensProduct
                }
            };

            return new List<Order>()
            {
                new Order() { CustomerId = particularId, DateTimeUtc = new DateTime(2016, 01, 01), State = "Payment Succeeded", Id = particularOrderId, Items = particularItems},
                new Order() { CustomerId = nserviceBusId, DateTimeUtc = new DateTime(2016, 01, 02), State = "Payment awaiting", Id = nserivceBusOrderId, Items = nservicebusItems }
            };
        }

    }
}


text:
<?xml version='1.0' encoding='utf-8'?>
<widget id="id.co.asyst.flightmonitoring.mobile" version="1.0-SNAPSHOT"
        xmlns="http://www.w3.org/ns/widgets"
        xmlns:cdv="http://cordova.apache.org/ns/1.0"
        xmlns:gap = "http://phonegap.com/ns/1.0">
    <name>Flight Monitoring</name>
    <description>
        Flight Monitoring mobile apps
    </description>
    <author email="dev@asyst.co.id" href="http://www.asyst.co.id">
        Asyst Dev Team
    </author>

    <feature name="http://api.phonegap.com/1.0/device" />
    <preference name="permissions"                value="none"/>

    <!-- Customize your app and platform with the preference element. -->
    <!--  <preference name="phonegap-version"      value="3.4.0" />   -->     <!-- all: current version of PhoneGap -->
    <preference name="orientation"                value="landscape" />        <!-- all: default means both landscape and portrait are enabled -->
    <preference name="target-device"              value="universal" />      <!-- all: possible values handset, tablet, or universal -->
    <preference name="fullscreen"                 value="true" />           <!-- all: hides the status bar at the top of the screen -->
    <preference name="webviewbounce"              value="true" />           <!-- ios: control whether the screen 'bounces' when scrolled beyond the top -->
    <preference name="prerendered-icon"           value="true" />           <!-- ios: if icon is prerendered, iOS will not apply it's gloss to the app's icon on the user's home screen -->
    <preference name="stay-in-webview"            value="false" />          <!-- ios: external links should open in the default browser, 'true' would use the webview the app lives in -->
    <preference name="ios-statusbarstyle"         value="black-opaque" />   <!-- ios: black-translucent will appear black because the PhoneGap webview doesn't go beneath the status bar -->
    <preference name="detect-data-types"          value="true" />           <!-- ios: controls whether data types (such as phone no. and dates) are automatically turned into links by the system -->
    <preference name="exit-on-suspend"            value="false" />          <!-- ios: if set to true, app will terminate when home button is pressed -->
    <preference name="show-splash-screen-spinner" value="true" />           <!-- ios: if set to false, the spinner won't appear on the splash screen during app loading -->
    <preference name="auto-hide-splash-screen"    value="true" />           <!-- ios: if set to false, the splash screen must be hidden using a JavaScript API -->
    <preference name="disable-cursor"             value="false" />          <!-- blackberry: prevents a mouse-icon/cursor from being displayed on the app -->
    <preference name="android-minSdkVersion"      value="7" />              <!-- android: MIN SDK version supported on the target device. MAX version is blank by default. -->
    <preference name="android-installLocation"    value="auto" />           <!-- android: app install location. 'auto' will choose. 'internalOnly' is device memory. 'preferExternal' is SDCard. -->
    <preference name="load-url-timeout" value="1800000" />
    <preference name="loadUrlTimeoutValue" value="1800000"/>

    <icon src="icon.png" />

    <!-- iPhone / iPod Touch  -->
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="60" height="60" />
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="120" height="120" />

	<!-- iPad -->
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="76" height="76" />
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="152" height="152" />

	<!-- Settings Icon -->
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="29" height="29" />
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="58" height="58" />

	<!-- Spotlight Icon -->
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="40" height="40" />
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="80" height="80" />

	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="57" height="57" />
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="114" height="114" />

	<!-- iPad -->
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="72" height="72" />
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="144" height="144" />

	<!-- iPhone Spotlight and Settings Icon -->
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="29" height="29" />
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="58" height="58" />

	<!-- iPad Spotlight and Settings Icon -->
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="50" height="50" />
	<icon src="img/logo_ga_96x96.png" gap:platform="ios" width="100" height="100" />

    <icon src="img/logo_ga_96x96.png" gap:platform="android" gap:density="ldpi" />
	<icon src="img/logo_ga_96x96.png" gap:platform="android" gap:density="mdpi" />
	<icon src="img/logo_ga_96x96.png" gap:platform="android" gap:density="hdpi" />
	<icon src="img/logo_ga_96x96.png" gap:platform="android" gap:density="xhdpi" />
	<icon src="img/logo_ga_96x96.png" gap:platform="android" gap:density="xxhdpi" />
    <icon src="img/logo_ga_96x96.png" gap:platform="winphone" />
    <icon src="img/logo_ga_96x96.png" gap:platform="winphone" gap:role="background" />

    <gap:splash src="splash.png" />

    <gap:splash src="img/logo_ga_200x200.png" gap:platform="ios" width="320" height="480" />
	<!-- iPhone and iPod touch -->
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="ios" width="320" height="480" />
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="ios" width="640" height="960" />

	<!-- iPhone 5 / iPod Touch (5th Generation) -->
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="ios" width="640" height="1136" />

	<!-- iPad -->
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="ios" width="768" height="1024" />
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="ios" width="1024" height="768" />

	<!-- Retina iPad -->
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="ios" width="1536" height="2048" />
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="ios" width="2048" height="1536" />
    <gap:splash src="img/logo_ga_200x200.png" gap:platform="android" gap:density="ldpi" />
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="android" gap:density="mdpi" />
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="android" gap:density="hdpi" />
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="android" gap:density="xhdpi" />
	<gap:splash src="img/logo_ga_200x200.png" gap:platform="android" gap:density="xxhdpi" />
    <gap:splash src="img/logo_ga_200x200.png" gap:platform="winphone" />

    <content src="index.html" />
    <access origin="*" />

</widget>


text:
{% load i18n %}

{{ package.name }} {% if package.slug in packages_already_added_list %}(in grid already){% endif %}

{% trans "Added" %} {{ package.created|timesince }} ago

{{ package.pypi_downloads }}

{{ package.repo_watchers }}

{{ package.repo_description }}


text:
#region file_header

// QuickVideoInfo - YTII.Android.App - StreamableVideoInfoActivity.cs
//
// This file is licensed to you under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied.  See the License for the specific language governing permissions and limitations under the License.
//

#endregion

using System;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;
using YTII.Droid.App.Caches;
using YTII.ModelFactory.Models;
using Exception = Java.Lang.Exception;

namespace YTII.Droid.App.Activities
{
    [Activity(Label = "Quick Video Info", Theme = "@style/TranslucentActivity", MainLauncher = false, Icon = "@drawable/icon", ResizeableActivity = true)]
    [IntentFilter(new[] { Intent.ActionView }, DataScheme = "http", DataHost = "*.streamable.com", DataPathPrefix = "", Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable })]
    [IntentFilter(new[] { Intent.ActionView }, DataScheme = "http", DataHost = "streamable.com", DataPathPrefix = "", Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable })]
    [IntentFilter(new[] { Intent.ActionView }, DataScheme = "https", DataHost = "streamable.com", DataPathPrefix = "", Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable })]
    [IntentFilter(new[] { Intent.ActionView }, DataScheme = "https", DataHost = "*.streamable.com", DataPathPrefix = "", Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable })]
    public class StreamableVideoInfoActivity : BaseVideoInfoActivity<StreamableVideoModel>
    {
        StreamableVideoModel vid;

        /// <summary>
        ///     The name of the activity. Used for identifying it in log messages
        /// </summary>
        protected override string ActivityName => nameof(StreamableVideoInfoActivity);

        /// <summary>
        ///     This is a prefix used to distinguish the origin source of thumbnails (e.g., YT[videoID] for YouTube, ST[videoID]
        ///     for Streamable.com)
        /// </summary>
        protected override string TypePrefix => @"ST";

        /// <summary>
        ///     The <see cref="Caches.VideoModelCache{T}" /> where the results of recently previewed video models are stored
        /// </summary>
        protected override VideoModelCache<StreamableVideoModel> ModelCache => retainedFragment.StreamableVideoCache;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Log.Debug("YTII.StreamableIntentUrl", Intent.DataString);
            Log.Debug("YTII.StreamableIntentUrl", GetVideoIdFromIntentDataString(Intent.DataString));
            // FIRST NEED TO CONFIRM THIS IS A STREAMABLE.COM VIDEO URL; ALL OTHERS REDIRECT TO BROWSER
            if (GetVideoIdFromIntentDataString(Intent.DataString).Length > 5)
            {
                SendUrlToBrowser(Intent.DataString);
                FinishAfterTransition();
                FinishAndRemoveTask();
                return;
            }

            var extraDetailsRow = FindViewById<GridLayout>(Resource.Id.gridDetails);
            extraDetailsRow.Visibility = ViewStates.Gone;
        }

        /// <summary>
        ///     This method is where the actual work of requesting/loading the video info from the API
        /// </summary>
        /// <returns>N/A</returns>
        protected override async Task LoadVideo()
        {
            var sourceText = FindViewById<TextView>(Resource.Id.sourceText);
            sourceText.Text = @"streamable.com";

            try
            {
                videoId = GetVideoIdFromIntentDataString(Intent.DataString);

                if (ModelCache.IsCached(videoId))
                    vid = ModelCache.GetItem(videoId);
                else
                    vid = await VideoInfoRequestor.GetStreamableVideoModel(videoId).ConfigureAwait(true);

                if (vid != null)
                {
                    vid.VideoFullUrl = Intent.DataString;
                    LoadVideoDetails(vid);

                    if (!vid.IsErrorModel)
                        ModelCache.Add(vid);
                }
                else
                {
                    UnableToLoadVideoInfo();
                }
            }
            catch (Exception ex)
            {
                Log.Error($"YTII.{nameof(OnCreate)}", ex.Message);
                UnableToLoadVideoInfo(ex);
            }
        }

        /// <summary>
        ///     Populates the activity controls with the details from the supplied <see cref="IVideoModel" />
        /// </summary>
        /// <param name="video">The <see cref="IVideoModel" /> to load the details into the layout for</param>
        protected override void LoadVideoDetails(StreamableVideoModel video)
        {
            try
            {
                var videoTitle = FindViewById<TextView>(Resource.Id.textView1);

                if (video.Title != string.Empty)
                    videoTitle.Text = video.Title;
                else
                    videoTitle.Text = Resources.GetString(Resource.String.NoVideoTitle);

                var videoDuration = FindViewById<TextView>(Resource.Id.videoDuration);
                videoDuration.Text = video.VideoDurationString;

                LoadVideoThumbnail(video);
            }
            catch (Exception ex)
            {
                Log.Error($"YTII.{nameof(LoadVideoDetails)}", ex.Message);
                UnableToLoadVideoInfo(ex);
            }
        }

        /// <summary>
        ///     Processes the intent data string (URL) and returns the video ID
        /// </summary>
        /// <param name="intentDataString">The <see cref="P:Android.Content.Intent.DataString" /> passed to the activity.</param>
        /// <returns>The Video ID used to identify the item to request information from the API for</returns>
        protected override string GetVideoIdFromIntentDataString(string intentDataString)
        {
            if (!intentDataString.Contains(@"/s/"))
                return intentDataString.Substring(intentDataString.LastIndexOf(@".com/", StringComparison.InvariantCultureIgnoreCase) + 5).TrimEnd('/');

            var startIndex = intentDataString.LastIndexOf(@"/s/", StringComparison.InvariantCultureIgnoreCase) + 3;
            var endIndex = intentDataString.TrimEnd('/').LastIndexOf(@"/", StringComparison.InvariantCultureIgnoreCase);
            return intentDataString.Substring(startIndex, endIndex - startIndex);

        }

        /// <summary>
        ///     Returns the most appropriate video Thumbnail URL
        /// </summary>
        /// <remarks>
        ///     This was refactored out into its own function to accomodate allowing the user to define a preferred thumbnail
        ///     quality
        /// </remarks>
        /// <param name="vid">The <see cref="IVideoModel" /> whose thumbnail URL is desired</param>
        /// <returns>A URL of the thumbnail to load</returns>
        protected override string GetThumbnailUrl(ref StreamableVideoModel vid)
        {
            return vid.DefaultThumbnailUrl;
        }

        /// <summary>
        ///     The method to execute when the user wants to open the currently previewed video. Implementation will vary depending
        ///     on the explicit <see cref="IVideoModel" /> type
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void OpenButton_Click(object sender, EventArgs e)
        {
            SendUrlToBrowser(vid.VideoFullUrl);
            FinishAfterTransition();
            FinishAndRemoveTask();
        }
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Xunit;
using System.Threading;
using System.Timers;

using TestTimer = System.Timers.Timer;

namespace System.Timers.Tests
{
    public class TimerTests
    {
        [Theory]
        [InlineData(0)]
        [InlineData(-0.5D)]
        [InlineData(-1)]
        [InlineData(double.MinValue)]
        [InlineData(double.MaxValue)]
        public void NegativeTests(double interval)
        {
            AssertExtensions.Throws<ArgumentException>(null, () => new TestTimer(interval));
        }

        [Fact]
        public void Ctor_PropertiesMatchExpectedDefaults()
        {
            using (var timer = new TestTimer(42))
            {
                Assert.Equal(42, timer.Interval);
                Assert.True(timer.AutoReset, "Expected AutoReset to be true");
                Assert.False(timer.Enabled, "Expected Enabled to be false");

                Assert.Null(timer.SynchronizingObject);
                Assert.Null(timer.Site);
            }
        }

        [Fact]
        public void TestTimerStartAutoReset()
        {
            using (var timer = new TestTimer(1))
            {
                var mres = new ManualResetEventSlim();
                int count = 0;
                int target = 1;

                timer.AutoReset = false;
                timer.Elapsed += (sender, e) =>
                {
                    if (Interlocked.Increment(ref count) == target)
                    {
                        mres.Set();
                    }
                };
                timer.Start();

                mres.Wait();
                Assert.False(timer.Enabled, "Auto-reset timer should not be enabled after elapsed");
                Assert.Equal(1, count);

                count = 0;
                target = 10;
                mres.Reset();
                timer.AutoReset = true;
                mres.Wait();

                timer.Stop();
                Assert.InRange(count, target, int.MaxValue);
            }
        }

        [Theory]
        [InlineData(int.MaxValue)]
        [InlineData(0.5D)]
        public void TestInterval(double interval)
        {
            using (var timer = new TestTimer(interval))
            {
                Assert.Equal(Math.Ceiling(interval), timer.Interval);
                timer.Interval = interval;
                Assert.Equal(interval, timer.Interval);
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>JSDoc: Source: keyManager.js</title>

    <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
    <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">

Source: keyManager.js

/**
 * @fileOverview Handles RSA key functions
 * @author Noah Kolossa
 */
//Include dependencies (npm)
const log4js = require('log4js');
const logger = log4js.getLogger();
const fs = require('fs');
const keypair = require('keypair');

//Include local dependencies
const encryptionManager = require('./encryptionManager.js');

/**
 * Generates a new RSA key pair
 * @param {string} user Name of the user
 * @param {number} bits Bits of the RSA key pair
 * @param {string} password Password to encrypt the key pair
 * @param {function} callback
 *
 * @example
 * const username = 'user123';
 * const keyLength = 4096;
 * const password = 'secretPassword';
 *
 * let keyPair;
 *
 * generateKeyPair(username, keyLength, password, function (keyPair) {
 *     this.keyPair = keyPair;
 * });
 */
let generateKeyPair = function (user, bits, password, callback) {
    logger.debug('Generating new KeyPair...');
    const keyPair = keypair(bits);

    //Save the public key
    fs.writeFile('keys/' + user + '.pub', keyPair['public'], function (err) {
        if (err) return console.log(err);
        logger.debug('PublicKey saved');

        //Save the private key, encrypted with the password
        fs.writeFile('keys/' + user + '.key', encryptionManager.encryptSym(keyPair['private'], password), function (err) {
            if (err) return console.log(err);
            logger.debug('PrivateKey saved (encrypted)');

            //Return the keypair
            callback(keyPair);
        });
    });
};

/**
 * Loads an existing RSA key pair
 * @param {string} user Name of the user
 * @param {string} password Password to decrypt the key pair
 * @param {function} callback
 *
 * @example
 * const username = 'user123';
 * const password = 'secretPassword';
 *
 * let keyPair;
 *
 * loadKeyPair(username, password, function (keyPair) {
 *     this.keyPair = keyPair;
 * });
 */
let loadKeyPair = function(user, password, callback) {
    logger.debug('Loading KeyPair ...');

    let keyPair = {};

    //Read the public key
    fs.readFile('keys/' + user + '.pub', 'utf8', function (err, data) {
        if (err) return console.log(err);

        logger.debug('Loaded PublicKey');
        keyPair['public'] = data;

        //Read the encrypted private key
        fs.readFile('keys/' + user + '.key', 'utf8', function (err, data) {
            if (err) return console.log(err);
            logger.debug('Loaded PrivateKey');

            //Decrypt the private key with the password
            keyPair['private'] = encryptionManager.decryptSym(data, password);

            //Return the keypair
            callback(keyPair);
        });
    });
};

//Make the functions accessable for other files
module.exports = {
    generateKeyPair: generateKeyPair,
    loadKeyPair: loadKeyPair
};

Home

Global

addContact

createWindow

decryptAsym

decryptSym

encryptAsym

encryptSym

generateKeyPair

loadContacts

loadKeyPair

onMessage

removeContact

sendMessage

    Documentation generated by JSDoc 3.5.5 on Sat Oct 07 2017 18:05:22 GMT+0100 (BST)


text:
/**
 *     This code was auto-generated by a tool.
 *
 *     Changes to this file may cause incorrect behavior and will be lost if
 *     the code is regenerated.
 */
package com.mozu.api.resources.platform;

import com.mozu.api.ApiContext;
import java.util.List;
import java.util.ArrayList;
import com.mozu.api.MozuClient;
import com.mozu.api.MozuUrl;
import com.mozu.api.Headers;
import com.mozu.api.security.AuthTicket;

/**
 * Use the tenant data resource to store tenant-level information required for a third-party application in the Mozu database.
 *
 */
public class TenantDataResource {
	///
	/// <see cref="Mozu.Api.ApiContext"/>
	///
	private ApiContext _apiContext;
	public TenantDataResource(ApiContext apiContext)
	{
		_apiContext = apiContext;
	}

	/**
	 * Retrieves the value of a record in the Mozu database.
	 *

	 *	TenantData tenantdata = new TenantData();
	 *	string string = tenantdata.GetDBValue( dbEntryQuery);
	 *

	 * @param dbEntryQuery The database entry query string used to retrieve the record information.
	 * @return string
	 * @see string
	 */
	public String getDBValue(String dbEntryQuery) throws Exception
	{
		MozuClient<String> client = com.mozu.api.clients.platform.TenantDataClient.getDBValueClient( dbEntryQuery);
		client.setContext(_apiContext);
		client.executeRequest();
		return client.getResult();

	}

	/**
	 * Creates a new record in the Mozu database based on the information supplied in the request.
	 *

	 *	TenantData tenantdata = new TenantData();
	 *	tenantdata.CreateDBValue( value,  dbEntryQuery);
	 *

	 * @param dbEntryQuery The database entry string to create.
	 * @param value The value string to create.
	 * @return
	 * @see string
	 */
	public void createDBValue(String value, String dbEntryQuery) throws Exception
	{
		MozuClient client = com.mozu.api.clients.platform.TenantDataClient.createDBValueClient( value,  dbEntryQuery);
		client.setContext(_apiContext);
		client.executeRequest();

	}

	/**
	 * Updates a record in the Mozu database based on the information supplied in the request.
	 *

	 *	TenantData tenantdata = new TenantData();
	 *	tenantdata.UpdateDBValue( value,  dbEntryQuery);
	 *

	 * @param dbEntryQuery The database entry query string used to update the record information.
	 * @param value The database value to update.
	 * @return
	 * @see string
	 */
	public void updateDBValue(String value, String dbEntryQuery) throws Exception
	{
		MozuClient client = com.mozu.api.clients.platform.TenantDataClient.updateDBValueClient( value,  dbEntryQuery);
		client.setContext(_apiContext);
		client.executeRequest();

	}

	/**
	 * Removes a previously defined record in the Mozu database.
	 *

	 *	TenantData tenantdata = new TenantData();
	 *	tenantdata.DeleteDBValue( dbEntryQuery);
	 *

	 * @param dbEntryQuery The database entry string to delete.
	 * @return
	 */
	public void deleteDBValue(String dbEntryQuery) throws Exception
	{
		MozuClient client = com.mozu.api.clients.platform.TenantDataClient.deleteDBValueClient( dbEntryQuery);
		client.setContext(_apiContext);
		client.executeRequest();

	}

}