text:
import React, { Component, PropTypes } from 'react';
import { Tabs, Tab } from 'material-ui/Tabs';
import AutoComplete from 'material-ui/AutoComplete';
import Slider from 'material-ui/Slider';
import RaisedButton from 'material-ui/RaisedButton';
import FlatButton from 'material-ui/FlatButton';
import IconButton from 'material-ui/IconButton';
import FontIcon from 'material-ui/FontIcon';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Paper from 'material-ui/Paper';
import { green700 } from 'material-ui/styles/colors';
import ReachabilityTab from './ReachabilityTab';

const MILES_TO_KM = 1.609344;
const KM_TO_MILES = 1 / 1.609344;

const styles = {
  container: {
    display: 'flex',
    zIndex: 1,
    minWidth: '300px'
  },

  tabs: {
    flex: '1',
    display: 'flex',
    flexDirection: 'column'
  },

  tabsContainer: {
    flex: '1',
    display: 'flex',
    flexDirection: 'column',
    overflowY: 'auto'
  },

  menu: {
    margin: '10px 20px 30px'
  },

  slider: {
    marginBottom: '25px'
  },

  reachabilitySlider: {
    marginBottom: '0px'
  },

  autoCompleteWrapper: {
    position: 'relative',
    display: 'flex'
  },

  stopoversInput: {
    paddingRight: '45px',
  },

  removeStopoverBtn: {
    position: 'absolute',
    right: 0,
    bottom: '5px'
  },

  addStopoverBtn: {
    margin: '10px 0'
  },

  batteryLevel: {
    display: 'flex',
    justifyContent: 'space-between'
  },

  batteryLevelValue: {
    fontWeight: 'bold',
    color: green700,
    fontSize: '14px'
  },

  textField: {
    display: 'inherit',
    position: 'relative',
    marginBottom: '25px'
  }
};

export default class Menu extends Component {
  constructor(props) {
    super(props);
    this.state = {
      vehicle: 0,
      open: this.props.open,
      dataSource: [],
      autoCompletes: [{ id: 1, label: 'From', route: '' }, { id: 2, label: 'To', route: '' }],
      batteryPecentage: 100,
      batteryLevel: 1.0,
      remainingRange: 0,
    };
    this.autoCompleteId = 3;
    this.xhr = new XMLHttpRequest();
  }

  getVehicles = () => [
    'Fiat Fiorino',
    'Smart Roadster',
    'Sam',
    'Citysax',
    'MUTE',
    'Spyder-S',
    'Think',
    'Luis',
    'STROMOS',
    'Karabag Fiat 500E',
    'Lupower Fiat 500E'
  ]

  getRoute = () => {
    const autoCompletes = this.state.autoCompletes;
    if (autoCompletes.every(elem => elem.route !== '')) {
      const routes = autoCompletes.map(elem => elem.route);
      this.props.getRoutes(routes);
    }
    else {
      this.props.handleIndicateStartSnackbarOpen();
    }
  }

  getRangeVisualisation = () => {
    if (this.state.remainingRange > 0) {
      if (this.props.unitsType === 1) {
        this.props.getRangeVisualisation(this.state.remainingRange * MILES_TO_KM);
      }
      else {
        this.props.getRangeVisualisation(this.state.remainingRange);
      }
    }
    else {
      this.props.handleRemainingRangeSnackbarOpen();
    }
  }

  getAllAutoCompletes = () => {
    const dataSourceConfig = {
      text: 'text',
      value: 'data',
    };
    const allAutoCompletes =
      this.state.autoCompletes.map(autoComplete => (
        <div style={styles.autoCompleteWrapper} key={`wrapper-${autoComplete.id}`}>
          <AutoComplete
            inputStyle={
              this.isStopover(autoComplete.id) ? styles.stopoversInput : {}
            }
            key={autoComplete.id}
            floatingLabelText={autoComplete.label}
            onNewRequest={(req, index) => {
              // if index is not -1 and multiple suggestions with same value exits
              // then select the first one
              const route = index === -1 ? '' : this.state.dataSource[0].data.osm_id;
              const updatedAutoCompletes =
                this.state.autoCompletes.map((autoCompleteElem) => {
                  if (autoCompleteElem.id === autoComplete.id) {
                    return Object.assign({}, autoCompleteElem, { route });
                  }
                  return autoCompleteElem;
                });
              this.setState({ autoCompletes: updatedAutoCompletes });
            }}
            dataSource={this.state.dataSource}
            onUpdateInput={this.handleUpdate}
            dataSourceConfig={dataSourceConfig}
            fullWidth
          />
          {this.isStopover(autoComplete.id) ?
            <IconButton
              style={styles.removeStopoverBtn}
              onClick={() => {
                setTimeout(() => {
                  this.setState(
                    {
                      autoCompletes:
                        this.state.autoCompletes.filter(elem => elem.id !== autoComplete.id)
                    }
                  );
                }, 200);
              }}
            >
              <FontIcon className="material-icons">remove_circle</FontIcon>
            </IconButton>
            : ''
          }

      ));
    return allAutoCompletes;
  }

  isStopover = id => (id !== 1 && id !== 2)

  handleUpdate = (address) => {
    // dont make any req if autocomplete is empty
    if (!address.length) {
      return;
    }

    if (this.xhr.readyState !== 0 || this.xhr.readyState !== 4) {
      this.xhr.abort();
    }

    this.xhr.onreadystatechange = () => {
      if (this.xhr.readyState === 4 && this.xhr.status === 200) {
        const places = JSON.parse(this.xhr.responseText).map(place => (
          {
            text: place.display_name,
            data: {
              osm_id: place.osm_id,
              longitude: place.lon,
              latitude: place.lat
            }
          }
        ));
        this.setState({
          dataSource: places
        });
      }
    };

    this.xhr.open('GET', `${this.props.autoCompleteAddress}search/${address}`, true);
    this.xhr.send();
  }

  toggle = (callback) => {
    this.setState({ open: !this.state.open }, callback);
  }

  vehicleChange = (event, index, value) => {
    this.setState({ vehicle: value });
  }

  convertUnits = (newUnitsType) => {
    if (newUnitsType !== this.props.unitsType && this.state.remainingRange > 0) {
      if (newUnitsType === 1) {
        this.setState(prevState => ({
          remainingRange: prevState.remainingRange * KM_TO_MILES
        }));
      }
      else {
        this.setState(prevState => ({
          remainingRange: prevState.remainingRange * MILES_TO_KM
        }));
      }
    }
  }

  updateBatterySlider = (event, value) => {
    // TODO: Set remainingRange to distance in km/miles based on batteryLevel and car model
    this.setState({
      batteryPecentage: parseInt(value * 100, 10),
      batteryLevel: value,
      remainingRange: parseInt(value * 100, 10),
    });
  }

  updateRemainingRange = (event, value) => {
    // TODO: Set remainingRange to distance in km/miles based on batteryLevel and car model
    this.setState({ remainingRange: parseFloat(value) });
  }

  render() {
    return (
      <Paper style={this.state.open ? styles.container : { display: 'none' }} zDepth={5} rounded={false}>
        <Tabs
          contentContainerStyle={styles.tabsContainer}
          inkBarStyle={styles.active}
          style={styles.tabs}
        >
          <Tab label="Route">

              {this.getAllAutoCompletes()}

                <FlatButton
                  style={styles.addStopoverBtn}
                  label="Add Stopover"
                  onClick={() => {
                    const soLength = this.state.autoCompletes.length;
                    this.setState(
                      {
                        autoCompletes: [
                          ...this.state.autoCompletes.slice(0, soLength - 1),
                          { id: this.autoCompleteId, label: 'Over', route: '' },
                          this.state.autoCompletes[soLength - 1]
                        ]
                      },
                      () => {
                        this.autoCompleteId += 1;
                      }
                    );
                  }}
                  labelStyle={{ textTransform: 'none' }}
                  icon={<FontIcon className="material-icons">add_circle</FontIcon>}
                />

              <SelectField
                floatingLabelText="Vehicle"
                value={this.state.vehicle}
                onChange={this.vehicleChange}
                maxHeight={210}
                fullWidth
              >
                {this.getVehicles().map((vehicle, index) => (
                  <MenuItem key={vehicle} value={index} primaryText={vehicle} />
                ))}
              </SelectField>

                Battery Level
                 (this.batteryLevel = node)}
                >
                  {`${this.state.batteryPecentage}%`}

              <Slider
                onChange={this.updateBatterySlider}
                value={this.state.batteryLevel}
                sliderStyle={styles.slider}
              />
              <RaisedButton
                label="Get Route"
                onClick={this.getRoute}
                icon={<FontIcon className="material-icons">near_me</FontIcon>}
              />

          </Tab>
          <Tab
            label="Reachability"
            style={styles.tab}
          >
            <ReachabilityTab
              batteryLevel={this.state.batteryLevel}
              batteryPecentage={this.state.batteryPecentage}
              remainingRange={this.state.remainingRange}
              updateRemainingRange={this.updateRemainingRange}
              updateBatterySlider={this.updateBatterySlider}
              rangePolygonVisible={this.props.rangePolygonVisible}
              getRangeVisualisation={this.getRangeVisualisation}
              hideRangeVisualisation={this.props.hideRangeVisualisation}
              getVehicles={this.getVehicles}
              vehicle={this.state.vehicle}
              vehicleChange={this.vehicleChange}
              updateRangeFromField={val => this.props.updateRangeFromField(val)}
              updateRangeFromSelected={e => this.props.updateRangeFromSelected(e)}
              rangeFromField={this.props.rangeFromField}
              updateRangeToField={val => this.props.updateRangeToField(val)}
              updateRangeToSelected={e => this.props.updateRangeToSelected(e)}
              rangeToField={this.props.rangeToField}
              setRangePolygonAutocompleteOrigin={val =>
                this.props.setRangePolygonAutocompleteOrigin(val)}
              setRangePolygonAutocompleteDestination={val =>
                this.props.setRangePolygonAutocompleteDestination(val)}
            />
          </Tab>
        </Tabs>
      </Paper>
    );
  }
}

Menu.propTypes = {
  open: PropTypes.bool,
  unitsType: PropTypes.number.isRequired,
  autoCompleteAddress: PropTypes.string.isRequired,
  rangePolygonVisible: PropTypes.bool.isRequired,
  getRoutes: PropTypes.func.isRequired,
  getRangeVisualisation: PropTypes.func.isRequired,
  hideRangeVisualisation: PropTypes.func.isRequired,
  rangeFromField: PropTypes.string.isRequired,
  updateRangeFromField: PropTypes.func.isRequired,
  updateRangeFromSelected: PropTypes.func.isRequired,
  rangeToField: PropTypes.string.isRequired,
  updateRangeToField: PropTypes.func.isRequired,
  updateRangeToSelected: PropTypes.func.isRequired,
  setRangePolygonAutocompleteOrigin: PropTypes.func.isRequired,
  setRangePolygonAutocompleteDestination: PropTypes.func.isRequired,
  handleIndicateStartSnackbarOpen: PropTypes.func.isRequired,
  handleRemainingRangeSnackbarOpen: PropTypes.func.isRequired,
};

Menu.defaultProps = {
  open: true
};


text:
namespace Google.Cloud.PubSub.V1.Snippets
{
    // [START pubsub_v1_generated_SubscriberServiceApi_GetSubscription_sync_flattened]
    using Google.Cloud.PubSub.V1;

    public sealed partial class GeneratedSubscriberServiceApiClientSnippets
    {
        /// <summary>Snippet for GetSubscription</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void GetSubscription()
        {
            // Create client
            SubscriberServiceApiClient subscriberServiceApiClient = SubscriberServiceApiClient.Create();
            // Initialize request argument(s)
            string subscription = "projects/[PROJECT]/subscriptions/[SUBSCRIPTION]";
            // Make the request
            Subscription response = subscriberServiceApiClient.GetSubscription(subscription);
        }
    }
    // [END pubsub_v1_generated_SubscriberServiceApi_GetSubscription_sync_flattened]
}

redpajama_set_name: RedPajamaGithub


text:
package util

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"runtime"

	"github.com/b3log/wide/log"
)

// Logger.
var logger = log.NewLogger(os.Stdout)

var (
	dunno     = []byte("???")
	centerDot = []byte("·")
	dot       = []byte(".")
	slash     = []byte("/")
)

// Recover recovers a panic.
func Recover() {
	if re := recover(); nil != re {
		stack := stack()
		logger.Errorf("PANIC RECOVERED: %v\n\t%s\n", re, stack)
	}
}

// stack implements Stack, skipping 2 frames.
func stack() []byte {
	buf := &bytes.Buffer{} // the returned data
	// As we loop, we open files and read them. These variables record the currently
	// loaded file.
	var lines [][]byte
	var lastFile string
	for i := 2; ; i++ { // Caller we care about is the user, 2 frames up
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		// Print this much at least.  If we can't find the source, it won't show.
		fmt.Fprintf(buf, "%s:%d (0x%x)\n", file, line, pc)
		if file != lastFile {
			data, err := ioutil.ReadFile(file)
			if err != nil {
				continue
			}
			lines = bytes.Split(data, []byte{'\n'})
			lastFile = file
		}
		line-- // in stack trace, lines are 1-indexed but our array is 0-indexed
		fmt.Fprintf(buf, "\t%s: %s\n", function(pc), source(lines, line))
	}
	return buf.Bytes()
}

// source returns a space-trimmed slice of the n'th line.
func source(lines [][]byte, n int) []byte {
	if n < 0 || n >= len(lines) {
		return dunno
	}
	return bytes.Trim(lines[n], " \t")
}

// function returns, if possible, the name of the function containing the PC.
func function(pc uintptr) []byte {
	fn := runtime.FuncForPC(pc)
	if fn == nil {
		return dunno
	}
	name := []byte(fn.Name())
	// The name includes the path name to the package, which is unnecessary
	// since the file name is already included.  Plus, it has center dots.
	// That is, we see
	//	runtime/debug.*T·ptrmethod
	// and want
	//	*T.ptrmethod
	// Since the package path might contains dots (e.g. code.google.com/...),
	// we first remove the path prefix if there is one.
	if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
		name = name[lastslash+1:]
	}
	if period := bytes.Index(name, dot); period >= 0 {
		name = name[period+1:]
	}
	name = bytes.Replace(name, centerDot, dot, -1)
	return name
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AecCloud.Service.Vaults
{
    public interface IMFilesPerformService
    {
        List<PerformanceRateModel> GetPerformRate(List<PerformanceRateModel> list,Dictionary<string,string> guidAndIps, string username, string pwd, int year, int month);

        List<UnitPerformaceModel> GetPerformRateUnit(Dictionary<string, string> guidAndIps, string username, string pwd, int year, int month, string compName);
    }
}


text:
import {BUTTON_CLICK} from '../constants';

export function handleClick() {
  return {type: BUTTON_CLICK};
}


text:
<?php

namespace Backend\Core\Engine;

use Symfony\Component\HttpKernel\KernelInterface;

use MatthiasMullie\Minify;

use Backend\Core\Engine\Model as BackendModel;
use Backend\Core\Engine\Language as BL;

/**
 * This class will be used to alter the head-part of the HTML-document that will be created by he Backend
 * Therefore it will handle meta-stuff (title, including JS, including CSS, ...)
 *
 * @author Tijs Verkoyen <tijs@sumocoders.be>
 * @author Matthias Mullie <forkcms@mullie.eu>
 */
class Header extends Base\Object
{
    /**
     * All added CSS-files
     *
     * @var array
     */
    private $cssFiles = array();

    /**
     * Data that will be passed to js
     *
     * @var array
     */
    private $jsData = array();

    /**
     * All added JS-files
     *
     * @var    array
     */
    private $jsFiles = array();

    /**
     * Template instance
     *
     * @var    Template
     */
    private $tpl;

    /**
     * URL-instance
     *
     * @var    Url
     */
    private $URL;

    /**
     * @param KernelInterface $kernel
     */
    public function __construct(KernelInterface $kernel)
    {
        parent::__construct($kernel);

        $this->getContainer()->set('header', $this);

        // grab from the reference
        $this->URL = $this->getContainer()->get('url');
        $this->tpl = $this->getContainer()->get('template');

    }

    /**
     * Add a CSS-file.
     *
     * If you don't specify a module, the current one will be used to automatically create the path to the file.
     * Automatic creation of the filename will result in
     *   src/Backend/Modules/MODULE/Layout/Css/FILE (for modules)
     *   src/Backend/Core/Layout/Css/FILE (for core)
     *
     * If you set overwritePath to true, the above-described automatic path creation will not happen, instead the
     * file-parameter will be used as path; which we then expect to be a full path (It has to start with a slash '/')
     *
     * @param string $file          The name of the file to load.
     * @param string $module        The module wherein the file is located.
     * @param bool   $overwritePath Should we overwrite the full path?
     * @param bool   $minify        Should the CSS be minified?
     * @param bool   $addTimestamp  May we add a timestamp for caching purposes?
     */
    public function addCSS($file, $module = null, $overwritePath = false, $minify = true, $addTimestamp = false)
    {
        $file = (string) $file;
        $module = (string) ($module !== null) ? $module : $this->URL->getModule();
        $overwritePath = (bool) $overwritePath;
        $minify = (bool) $minify;
        $addTimestamp = (bool) $addTimestamp;

        // no actual path given: create
        if (!$overwritePath) {
            // we have to build the path, but core is a special one
            if ($module !== 'Core') {
                $file = '/src/Backend/Modules/' . $module . '/Layout/Css/' . $file;
            } else {
                // core is special because it isn't a real module
                $file = '/src/Backend/Core/Layout/Css/' . $file;
            }
        }

        // no minifying when debugging
        if (SPOON_DEBUG) {
            $minify = false;
        }

        // try to minify
        if ($minify) {
            $file = $this->minifyCSS($file);
        }

        // in array
        $inArray = false;

        // check if the file already exists in the array
        foreach ($this->cssFiles as $row) {
            if ($row['file'] == $file) {
                $inArray = true;
            }
        }

        // add to array if it isn't there already
        if (!$inArray) {
            // build temporary array
            $temp['file'] = (string) $file;
            $temp['add_timestamp'] = $addTimestamp;

            // add to files
            $this->cssFiles[] = $temp;
        }
    }

    /**
     * Add a JS-file.
     * If you don't specify a module, the current one will be used
     * If you set overwritePath to true we expect a full path (It has to start with a /)
     *
     * @param string $file          The file to load.
     * @param string $module        The module wherein the file is located.
     * @param bool   $minify        Should the module be minified?
     * @param bool   $overwritePath Should we overwrite the full path?
     * @param bool   $addTimestamp  May we add a timestamp for caching purposes?
     */
    public function addJS($file, $module = null, $minify = true, $overwritePath = false, $addTimestamp = false)
    {
        $file = (string) $file;
        $module = (string) ($module !== null) ? $module : $this->URL->getModule();
        $minify = (bool) $minify;
        $overwritePath = (bool) $overwritePath;
        $addTimestamp = (bool) $addTimestamp;

        // no minifying when debugging
        if (SPOON_DEBUG) {
            $minify = false;
        }

        // is the given path the real path?
        if (!$overwritePath) {
            // we have to build the path, but core is a special one
            if ($module !== 'Core') {
                $file = '/src/Backend/Modules/' . $module . '/Js/' . $file;
            } else {
                // core is special because it isn't a real module
                $file = '/src/Backend/Core/Js/' . $file;
            }
        }

        // try to minify
        if ($minify) {
            $file = $this->minifyJS($file);
        }

        // already in array?
        if (!in_array(array('file' => $file, 'add_timestamp' => $addTimestamp), $this->jsFiles)) {
            // add to files
            $this->jsFiles[] = array('file' => $file, 'add_timestamp' => $addTimestamp);
        }
    }

    /**
     * Add data into the jsData
     *
     * @param string $module The name of the module.
     * @param string $key    The key whereunder the value will be stored.
     * @param mixed  $value  The value
     */
    public function addJsData($module, $key, $value)
    {
        $this->jsData[$module][$key] = $value;
    }

    /**
     * Get all added CSS files
     *
     * @return array
     */
    public function getCSSFiles()
    {
        // fetch files
        return $this->cssFiles;
    }

    /**
     * get all added javascript files
     *
     * @return array
     */
    public function getJSFiles()
    {
        return $this->jsFiles;
    }

    /**
     * Minify a CSS-file
     *
     * @param string $file The file to be minified.
     * @return string
     */
    private function minifyCSS($file)
    {
        // create unique filename
        $fileName = md5($file) . '.css';
        $finalURL = BACKEND_CACHE_URL . '/MinifiedCss/' . $fileName;
        $finalPath = BACKEND_CACHE_PATH . '/MinifiedCss/' . $fileName;

        // check that file does not yet exist or has been updated already
        if (!is_file($finalPath) || filemtime(PATH_WWW . $file) > filemtime($finalPath)) {
            // minify the file
            $css = new Minify\CSS(PATH_WWW . $file);
            $css->minify($finalPath);
        }

        return $finalURL;
    }

    /**
     * Minify a JS-file
     *
     * @param string $file The file to be minified.
     * @return string
     */
    private function minifyJS($file)
    {
        // create unique filename
        $fileName = md5($file) . '.js';
        $finalURL = BACKEND_CACHE_URL . '/MinifiedJs/' . $fileName;
        $finalPath = BACKEND_CACHE_PATH . '/MinifiedJs/' . $fileName;

        // check that file does not yet exist or has been updated already
        if (!is_file($finalPath) || filemtime(PATH_WWW . $file) > filemtime($finalPath)) {
            // minify the file
            $js = new Minify\JS(PATH_WWW . $file);
            $js->minify($finalPath);
        }

        return $finalURL;
    }

    /**
     * Parse the header into the template
     */
    public function parse()
    {
        // put the page title in the <title>
        $this->tpl->assign('page_title', BL::getLabel($this->URL->getModule()));

        // parse CSS
        $this->parseCSS();

        // parse JS
        $this->parseJS();
    }

    /**
     * Parse the CSS-files
     */
    public function parseCSS()
    {
        // init var
        $cssFiles = array();
        $existingCSSFiles = $this->getCSSFiles();

        // if there aren't any JS-files added we don't need to do something
        if (!empty($existingCSSFiles)) {
            foreach ($existingCSSFiles as $file) {
                // add lastmodified time
                if ($file['add_timestamp'] !== false) {
                    $file['file'] .= (strpos($file['file'], '?') !== false) ?
                        '&m=' . LAST_MODIFIED_TIME :
                        '?m=' . LAST_MODIFIED_TIME
                    ;
                }

                // add
                $cssFiles[] = $file;
            }
        }

        // css-files
        $this->tpl->assign('cssFiles', $cssFiles);
    }

    /**
     * Parse the JS-files
     */
    public function parseJS()
    {
        $jsFiles = array();
        $existingJSFiles = $this->getJSFiles();

        // if there aren't any JS-files added we don't need to do something
        if (!empty($existingJSFiles)) {
            // some files should be cached, even if we don't want cached (mostly libraries)
            $ignoreCache = array(
                '/src/Backend/Core/Js/jquery/jquery.js',
                '/src/Backend/Core/Js/jquery/jquery.ui.js',
                '/src/Backend/Core/Js/ckeditor/jquery.ui.dialog.patch.js',
                '/src/Backend/Core/Js/jquery/jquery.tools.js',
                '/src/Backend/Core/Js/jquery/jquery.backend.js',
                '/src/Backend/Core/Js/ckeditor/ckeditor.js',
                '/src/Backend/Core/Js/ckeditor/adapters/jquery.js',
                '/src/Backend/Core/Js/ckfinder/ckfinder.js'
            );

            foreach ($existingJSFiles as $file) {
                // some files shouldn't be uncachable
                if (in_array($file['file'], $ignoreCache)
                    || $file['add_timestamp'] === false
                ) {
                    $file = array('file' => $file['file']);
                } else {
                    if (substr($file['file'], 0, 11) == '/frontend/js') {
                        $file = array('file' => $file['file'] . '&m=' . time());
                    } else {
                        $modifiedTime = (strpos($file['file'], '?') !== false) ?
                            '&m=' . LAST_MODIFIED_TIME :
                            '?m=' . LAST_MODIFIED_TIME
                        ;
                        $file = array('file' => $file['file'] . $modifiedTime);
                    }
                }

                // add
                $jsFiles[] = $file;
            }
        }

        // assign JS-files
        $this->tpl->assign('jsFiles', $jsFiles);

        // fetch preferred interface language
        if (Authentication::getUser()->isAuthenticated()) {
            $interfaceLanguage = (string) Authentication::getUser()->getSetting('interface_language');
        } else {
            $interfaceLanguage = Language::getInterfaceLanguage();
        }

        // some default stuff
        $this->jsData['debug'] = SPOON_DEBUG;
        $this->jsData['site']['domain'] = SITE_DOMAIN;
        $this->jsData['editor']['language'] = $interfaceLanguage;
        $this->jsData['interface_language'] = $interfaceLanguage;

        // is the user object filled?
        if (Authentication::getUser()->isAuthenticated()) {
            $this->jsData['editor']['language'] = (string) Authentication::getUser()->getSetting('interface_language');
        }

        // CKeditor has support for simplified Chinese, but the language is called zh-cn instead of zn
        if ($this->jsData['editor']['language'] == 'zh') {
            $this->jsData['editor']['language'] = 'zh-cn';
        }

        // theme
        if (BackendModel::getModuleSetting('Core', 'theme') !== null) {
            $this->jsData['theme']['theme'] = BackendModel::getModuleSetting('Core', 'theme');
            $this->jsData['theme']['path'] = FRONTEND_PATH . '/Themes/' .
                                             BackendModel::getModuleSetting(
                                                 'Core',
                                                 'theme'
                                             );
            $this->jsData['theme']['has_css'] = (is_file(
                FRONTEND_PATH . '/Themes/' .
                BackendModel::getModuleSetting(
                    'Core',
                    'theme'
                ) . '/Core/Layout/Css/screen.css'
            ));
            $this->jsData['theme']['has_editor_css'] = (is_file(
                FRONTEND_PATH . '/Themes/' .
                BackendModel::getModuleSetting(
                    'Core',
                    'theme'
                ) . '/Core/Layout/Css/editor_content.css'
            ));
        }

        // encode and add
        $jsData = json_encode($this->jsData);
        $this->tpl->assign('jsData', 'var jsData = ' . $jsData . ';' . "\n");
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace Badr.Server.Utils
{
    public static class Helper
    {
        public static PropertyInfo GetPublicProperty(this Type type, string propertyName)
        {
            PropertyInfo pi = type.GetProperty(propertyName);
            if (pi != null && pi.DeclaringType == type)
                return pi;

            return null;
        }

        public static int GenericCompare(object o1, object o2)
        {
            int compResult;

            if (o1 == null)
                compResult = o2 == null ? 0 : -1;
            else if (o2 == null)
                compResult = 1;
            else
                compResult = NumericCompare(o1, o2);

            if (compResult == -2)
                if (o1 is IComparable)
                    compResult = (o1 as IComparable).CompareTo(o2);

            return compResult;
        }

        public static int NumericCompare(object o1, object o2)
        {
            if (!IsNumeric(o1) || !IsNumeric(o2))
                return -2;

            int res = Convert.ToDouble(o1).CompareTo(Convert.ToDouble(o2));
            if (res < 0) return -1;
            if (res > 0) return 1;
            return 0;
        }

        public static bool IsNumeric(object o)
        {
            if (o == null)
                return false;

            switch (Type.GetTypeCode(o.GetType()))
            {
                case TypeCode.Byte:
                case TypeCode.Decimal:
                case TypeCode.Double:
                case TypeCode.Int16:
                case TypeCode.Int32:
                case TypeCode.Int64:
                case TypeCode.SByte:
                case TypeCode.Single:
                case TypeCode.UInt16:
                case TypeCode.UInt32:
                case TypeCode.UInt64:
                    return true;

                case TypeCode.Boolean:
                case TypeCode.Char:
                case TypeCode.DBNull:
                case TypeCode.DateTime:
                case TypeCode.Empty:
                case TypeCode.Object:
                case TypeCode.String:
                default:
                    return false;
            }

        }

		public static string ReplaceRecur(this string str, string oldValue, string newValue)
		{
			if(str != null)
				while(str.Contains(oldValue))
				{
					str = str.Replace(oldValue, newValue);
				}

			return str;
		}
    }
}


text:
'use strict'
var assert = require('assert')
var path = require('path')
var url = require('url')
var semver = require('semver')
var asyncMap = require('slide').asyncMap
var chain = require('slide').chain
var union = require('lodash.union')
var iferr = require('iferr')
var npa = require('npm-package-arg')
var validate = require('aproba')
var realizePackageSpecifier = require('realize-package-specifier')
var dezalgo = require('dezalgo')
var fetchPackageMetadata = require('../fetch-package-metadata.js')
var andAddParentToErrors = require('./and-add-parent-to-errors.js')
var addShrinkwrap = require('../fetch-package-metadata.js').addShrinkwrap
var addBundled = require('../fetch-package-metadata.js').addBundled
var readShrinkwrap = require('./read-shrinkwrap.js')
var inflateShrinkwrap = require('./inflate-shrinkwrap.js')
var inflateBundled = require('./inflate-bundled.js')
var andFinishTracker = require('./and-finish-tracker.js')
var npm = require('../npm.js')
var flatName = require('./flatten-tree.js').flatName
var createChild = require('./node.js').create
var resetMetadata = require('./node.js').reset
var andIgnoreErrors = require('./and-ignore-errors.js')
var isInstallable = require('./validate-args.js').isInstallable
var packageId = require('../utils/package-id.js')
var moduleName = require('../utils/module-name.js')

exports.test = {} // used to hold functions for testing by unit tests

// The export functions in this module mutate a dependency tree, adding
// items to them.

function isDep (tree, child) {
  if (child.fromShrinkwrap) return true
  var name = moduleName(child)
  var requested = isProdDep(tree, name)
  var matches
  if (requested) matches = doesChildVersionMatch(child, requested, tree)
  if (matches) return matches
  requested = isDevDep(tree, name)
  if (!requested) return
  return doesChildVersionMatch(child, requested, tree)
}

function isDevDep (tree, name) {
  var devDeps = tree.package.devDependencies || {}
  var reqVer = devDeps[name]
  if (reqVer == null) return
  return npa(name + '@' + reqVer)
}

function isProdDep (tree, name) {
  var deps = tree.package.dependencies || {}
  var reqVer = deps[name]
  if (reqVer == null) return false
  return npa(name + '@' + reqVer)
}

var registryTypes = { range: true, version: true }

function doesChildVersionMatch (child, requested, requestor) {
  // we always consider deps provided by a shrinkwrap as "correct" or else
  // we'll subvert them if they're intentionally "invalid"
  if (child.parent === requestor && child.fromShrinkwrap) return true
  // ranges of * ALWAYS count as a match, because when downloading we allow
  // prereleases to match * if there are ONLY prereleases
  if (requested.spec === '*') return true

  var childReq = child.package._requested
  if (childReq) {
    if (childReq.rawSpec === requested.rawSpec) return true
    if (childReq.type === requested.type && childReq.spec === requested.spec) return true
  }
  if (!registryTypes[requested.type]) return requested.rawSpec === child.package._from
  return semver.satisfies(child.package.version, requested.spec)
}

exports.recalculateMetadata = function (tree, log, next) {
  recalculateMetadata(tree, log, {}, next)
}

function recalculateMetadata (tree, log, seen, next) {
  validate('OOOF', arguments)
  if (seen[tree.path]) return next()
  seen[tree.path] = true
  if (tree.parent == null) resetMetadata(tree)
  function markDeps (spec, done) {
    validate('SF', arguments)
    realizePackageSpecifier(spec, packageRelativePath(tree), function (er, req) {
      if (er || !req.name) return done()
      var child = findRequirement(tree, req.name, req)
      if (child) {
        resolveWithExistingModule(child, tree, log, andIgnoreErrors(done))
      } else if (tree.package.dependencies[req.name] != null) {
        tree.missingDeps[req.name] = req.rawSpec
        done()
      } else if (tree.package.devDependencies[req.name] != null) {
        tree.missingDevDeps[req.name] = req.rawSpec
        done()
      } else {
        done()
      }
    })
  }
  function specs (deps) {
    return Object.keys(deps).map(function (depname) { return depname + '@' + deps[depname] })
  }
  var tomark = specs(tree.package.dependencies)
  if (!tree.parent && (npm.config.get('dev') || !npm.config.get('production'))) {
    tomark = union(tomark, specs(tree.package.devDependencies))
  }
  tree.children = tree.children.filter(function (child) { return !child.failed })
  chain([
    [asyncMap, tomark, markDeps],
    [asyncMap, tree.children, function (child, done) { recalculateMetadata(child, log, seen, done) }]
  ], function () {
    tree.userRequired = tree.package._requiredBy.some(function (req) { req === '#USER' })
    tree.existing = tree.package._requiredBy.some(function (req) { req === '#EXISTING' })
    tree.package._location = flatNameFromTree(tree)
    next(null, tree)
  })
}

function addRequiredDep (tree, child) {
  if (!isDep(tree, child)) return false
  var name = isProdDep(tree, moduleName(child)) ? flatNameFromTree(tree) : '#DEV:' + flatNameFromTree(tree)
  replaceModuleName(child.package, '_requiredBy', name)
  replaceModule(child, 'requiredBy', tree)
  replaceModule(tree, 'requires', child)
  return true
}

function removeObsoleteDep (child) {
  if (child.removed) return
  child.removed = true
  var requires = child.requires || []
  requires.forEach(function (requirement) {
    requirement.requiredBy = requirement.requiredBy.filter(function (reqBy) { reqBy !== child })
    if (requirement.requiredBy.length === 0) removeObsoleteDep(requirement)
  })
}

function matchingDep (tree, name) {
  if (tree.package.dependencies && tree.package.dependencies[name]) return tree.package.dependencies[name]
  if (tree.package.devDependencies && tree.package.devDependencies[name]) return tree.package.devDependencies[name]
  return
}

function packageRelativePath (tree) {
  if (!tree) return ''
  var requested = tree.package._requested || {}
  var isLocal = requested.type === 'directory' || requested.type === 'local'
  return isLocal ? requested.spec : tree.path
}

function getShrinkwrap (tree, name) {
  return tree.package._shrinkwrap && tree.package._shrinkwrap.dependencies && tree.package._shrinkwrap.dependencies[name]
}

exports.getAllMetadata = function (args, tree, next) {
  asyncMap(args, function (spec, done) {
    if (tree && spec.lastIndexOf('@') <= 0) {
      var sw = getShrinkwrap(tree, spec)
      if (sw) {
        // FIXME: This is duplicated in inflate-shrinkwrap and should be factoed
        // into a shared function
        spec = sw.resolved
             ? spec + '@' + sw.resolved
             : (sw.from && url.parse(sw.from).protocol)
             ? spec + '@' + sw.from
             : spec + '@' + sw.version
      } else {
        var version = matchingDep(tree, spec)
        if (version != null) {
          spec += '@' + version
        }
      }
    }
    fetchPackageMetadata(spec, packageRelativePath(tree), done)
  }, next)
}

// Add a list of args to tree's top level dependencies
exports.loadRequestedDeps = function (args, tree, saveToDependencies, log, next) {
  validate('AOOF', [args, tree, log, next])
  asyncMap(args, function (pkg, done) {
    var depLoaded = andAddParentToErrors(tree, done)
    resolveWithNewModule(pkg, tree, log.newGroup('loadRequestedDeps'), iferr(depLoaded, function (child, tracker) {
      validate('OO', arguments)
      if (npm.config.get('global')) {
        child.isGlobal = true
      }
      var childName = moduleName(child)
      if (saveToDependencies) {
        tree.package[saveToDependencies][childName] =
          child.package._requested.rawSpec || child.package._requested.spec
      }
      if (saveToDependencies && saveToDependencies !== 'devDependencies') {
        tree.package.dependencies[childName] =
          child.package._requested.rawSpec || child.package._requested.spec
      }
      child.directlyRequested = true
      child.save = saveToDependencies

      // For things the user asked to install, that aren't a dependency (or
      // won't be when we're done), flag it as "depending" on the user
      // themselves, so we don't remove it as a dep that no longer exists
      if (!addRequiredDep(tree, child)) {
        replaceModuleName(child.package, '_requiredBy', '#USER')
        child.directlyRequested = true
      }
      depLoaded(null, child, tracker)
    }))
  }, andForEachChild(loadDeps, andFinishTracker(log, next)))
}

function moduleNameMatches (name) {
  return function (child) { return moduleName(child) === name }
}

function noModuleNameMatches (name) {
  return function (child) { return moduleName(child) !== name }
}

// while this implementation does not require async calling, doing so
// gives this a consistent interface with loadDeps et al
exports.removeDeps = function (args, tree, saveToDependencies, log, next) {
  validate('AOOF', [args, tree, log, next])
  args.forEach(function (pkg) {
    var pkgName = moduleName(pkg)
    if (saveToDependencies) {
      var toRemove = tree.children.filter(moduleNameMatches(pkgName))
      replaceModule(tree, 'removed', toRemove[0])
      toRemove.forEach(function (parent) {
        parent.save = saveToDependencies
      })
    }
    tree.children = tree.children.filter(noModuleNameMatches(pkgName))
  })
  log.finish()
  next()
}

function andForEachChild (load, next) {
  validate('F', [next])
  next = dezalgo(next)
  return function (er, children, logs) {
    // when children is empty, logs won't be passed in at all (asyncMap is weird)
    // so shortcircuit before arg validation
    if (!er && (!children || children.length === 0)) return next()
    validate('EAA', arguments)
    if (er) return next(er)
    assert(children.length === logs.length)
    var cmds = []
    for (var ii = 0; ii < children.length; ++ii) {
      cmds.push([load, children[ii], logs[ii]])
    }
    var sortedCmds = cmds.sort(function installOrder (aa, bb) {
      return moduleName(aa[1]).localeCompare(moduleName(bb[1]))
    })
    chain(sortedCmds, next)
  }
}

function isDepOptional (tree, name) {
  if (!tree.package.optionalDependencies) return false
  if (tree.package.optionalDependencies[name] != null) return true
  return false
}

var failedDependency = exports.failedDependency = function (tree, name_pkg) {
  var name, pkg
  if (typeof name_pkg === 'string') {
    name = name_pkg
  } else {
    pkg = name_pkg
    name = moduleName(pkg)
  }

  tree.children = tree.children.filter(noModuleNameMatches(name))

  if (isDepOptional(tree, name)) {
    return false
  }

  tree.failed = true

  if (!tree.parent) return true

  for (var ii = 0; ii < tree.requiredBy.length; ++ii) {
    var requireParent = tree.requiredBy[ii]
    if (failedDependency(requireParent, tree.package)) {
      return true
    }
  }
  return false
}

function andHandleOptionalErrors (log, tree, name, done) {
  validate('OOSF', arguments)
  return function (er, child, childLog) {
    if (!er) validate('OO', [child, childLog])
    if (!er) return done(er, child, childLog)
    var isFatal = failedDependency(tree, name)
    if (er && !isFatal) {
      tree.children = tree.children.filter(noModuleNameMatches(name))
      log.warn('install', "Couldn't install optional dependency:", er.message)
      log.verbose('install', er.stack)
      return done()
    } else {
      return done(er, child, childLog)
    }
  }
}

// Load any missing dependencies in the given tree
exports.loadDeps = loadDeps
function loadDeps (tree, log, next) {
  validate('OOF', arguments)
  if (tree.loaded || (tree.parent && tree.parent.failed)) return andFinishTracker.now(log, next)
  if (tree.parent) tree.loaded = true
  if (!tree.package.dependencies) tree.package.dependencies = {}
  asyncMap(Object.keys(tree.package.dependencies), function (dep, done) {
    var version = tree.package.dependencies[dep]
    if (tree.package.optionalDependencies &&
        tree.package.optionalDependencies[dep] &&
        !npm.config.get('optional')) {
      return done()
    }

    addDependency(dep, version, tree, log.newGroup('loadDep:' + dep), andHandleOptionalErrors(log, tree, dep, done))
  }, andForEachChild(loadDeps, andFinishTracker(log, next)))
}

// Load development dependencies into the given tree
exports.loadDevDeps = function (tree, log, next) {
  validate('OOF', arguments)
  if (!tree.package.devDependencies) return andFinishTracker.now(log, next)
  asyncMap(Object.keys(tree.package.devDependencies), function (dep, done) {
    // things defined as both dev dependencies and regular dependencies are treated
    // as the former
    if (tree.package.dependencies[dep]) return done()

    var logGroup = log.newGroup('loadDevDep:' + dep)
    addDependency(dep, tree.package.devDependencies[dep], tree, logGroup, done)
  }, andForEachChild(loadDeps, andFinishTracker(log, next)))
}

exports.loadExtraneous = function loadExtraneous (tree, log, next) {
  var seen = {}
  function loadExtraneous (tree, log, next) {
    validate('OOF', arguments)
    if (seen[tree.path]) return next()
    seen[tree.path] = true
    asyncMap(tree.children.filter(function (child) { return !child.loaded }), function (child, done) {
      resolveWithExistingModule(child, tree, log, done)
    }, andForEachChild(loadExtraneous, andFinishTracker(log, next)))
  }
  loadExtraneous(tree, log, next)
}

exports.loadExtraneous.andResolveDeps = function (tree, log, next) {
  validate('OOF', arguments)
  asyncMap(tree.children.filter(function (child) { return !child.loaded }), function (child, done) {
    resolveWithExistingModule(child, tree, log, done)
  }, andForEachChild(loadDeps, andFinishTracker(log, next)))
}

function addDependency (name, versionSpec, tree, log, done) {
  validate('SSOOF', arguments)
  var next = andAddParentToErrors(tree, done)
  var spec = name + '@' + versionSpec
  realizePackageSpecifier(spec, packageRelativePath(tree), iferr(done, function (req) {
    var child = findRequirement(tree, name, req)
    if (child) {
      resolveWithExistingModule(child, tree, log, iferr(next, function (child, log) {
        if (child.package._shrinkwrap === undefined) {
          readShrinkwrap.andInflate(child, function (er) { next(er, child, log) })
        } else {
          next(null, child, log)
        }
      }))
    } else {
      resolveWithNewModule(req, tree, log, next)
    }
  }))
}

function resolveWithExistingModule (child, tree, log, next) {
  validate('OOOF', arguments)
  addRequiredDep(tree, child)

  if (tree.parent && child.parent !== tree) updatePhantomChildren(tree.parent, child)

  next(null, child, log)
}

var updatePhantomChildren = exports.updatePhantomChildren = function (current, child) {
  validate('OO', arguments)
  while (current && current !== child.parent) {
    // FIXME: phantomChildren doesn't actually belong in the package.json
    if (!current.package._phantomChildren) current.package._phantomChildren = {}
    current.package._phantomChildren[moduleName(child)] = child.package.version
    current = current.parent
  }
}

function flatNameFromTree (tree) {
  validate('O', arguments)
  if (!tree.parent) return '/'
  var path = flatNameFromTree(tree.parent)
  if (path !== '/') path += '/'
  return flatName(path, tree)
}

exports.test.replaceModuleName = replaceModuleName
function replaceModuleName (obj, key, name) {
  validate('OSS', arguments)
  obj[key] = union(obj[key] || [], [name])
}

exports.test.replaceModule = replaceModule
function replaceModule (obj, key, child) {
  validate('OSO', arguments)
  if (!obj[key]) obj[key] = []
  // we replace children with a new array object instead of mutating it
  // because mutating it results in weird failure states.
  // I would very much like to know _why_ this is. =/
  var children = [].concat(obj[key])
  var childName = moduleName(child)
  for (var replaceAt = 0; replaceAt < children.length; ++replaceAt) {
    if (moduleName(children[replaceAt]) === childName) break
  }
  var replacing = children.splice(replaceAt, 1, child)
  obj[key] = children
  return replacing[0]
}

function resolveWithNewModule (pkg, tree, log, next) {
  validate('OOOF', arguments)
  if (pkg.type) {
    return fetchPackageMetadata(pkg, packageRelativePath(tree), log.newItem('fetchMetadata'), iferr(next, function (pkg) {
      resolveWithNewModule(pkg, tree, log, next)
    }))
  }

  if (!pkg._installable) {
    log.silly('resolveWithNewModule', packageId(pkg), 'checking installable status')
    return isInstallable(pkg, iferr(next, function () {
      pkg._installable = true
      resolveWithNewModule(pkg, tree, log, next)
    }))
  }

  if (!pkg._from) {
    pkg._from = pkg._requested.name + '@' + pkg._requested.spec
  }
  addShrinkwrap(pkg, iferr(next, function () {
    addBundled(pkg, iferr(next, function () {
      var parent = earliestInstallable(tree, tree, pkg) || tree
      var child = createChild({
        package: pkg,
        parent: parent,
        path: path.join(parent.path, 'node_modules', pkg.name),
        realpath: path.resolve(parent.realpath, 'node_modules', pkg.name),
        children: pkg._bundled || [],
        isLink: tree.isLink
      })

      var replaced = replaceModule(parent, 'children', child)
      if (replaced) removeObsoleteDep(replaced)
      addRequiredDep(tree, child)
      pkg._location = flatNameFromTree(child)

      if (tree.parent && parent !== tree) updatePhantomChildren(tree.parent, child)

      if (pkg._bundled) {
        inflateBundled(child, child.children)
      }

      if (pkg._shrinkwrap && pkg._shrinkwrap.dependencies) {
        return inflateShrinkwrap(child, pkg._shrinkwrap.dependencies, function (er) {
          next(er, child, log)
        })
      }

      next(null, child, log)
    }))
  }))
}

var validatePeerDeps = exports.validatePeerDeps = function (tree, onInvalid) {
  if (!tree.package.peerDependencies) return
  Object.keys(tree.package.peerDependencies).forEach(function (pkgname) {
    var version = tree.package.peerDependencies[pkgname]
    var match = findRequirement(tree.parent || tree, pkgname, npa(pkgname + '@' + version))
    if (!match) onInvalid(tree, pkgname, version)
  })
}

exports.validateAllPeerDeps = function (tree, onInvalid) {
  validateAllPeerDeps(tree, onInvalid, {})
}

function validateAllPeerDeps (tree, onInvalid, seen) {
  validate('OFO', arguments)
  if (seen[tree.path]) return
  seen[tree.path] = true
  validatePeerDeps(tree, onInvalid)
  tree.children.forEach(function (child) { validateAllPeerDeps(child, onInvalid, seen) })
}

// Determine if a module requirement is already met by the tree at or above
// our current location in the tree.
var findRequirement = exports.findRequirement = function (tree, name, requested, requestor) {
  validate('OSO', [tree, name, requested])
  if (!requestor) requestor = tree
  var nameMatch = function (child) {
    return moduleName(child) === name && child.parent && !child.removed
  }
  var versionMatch = function (child) {
    return doesChildVersionMatch(child, requested, requestor)
  }
  if (nameMatch(tree)) {
    // this *is* the module, but it doesn't match the version, so a
    // new copy will have to be installed
    return versionMatch(tree) ? tree : null
  }

  var matches = tree.children.filter(nameMatch)
  if (matches.length) {
    matches = matches.filter(versionMatch)
    // the module exists as a dependent, but the version doesn't match, so
    // a new copy will have to be installed above here
    if (matches.length) return matches[0]
    return null
  }
  if (!tree.parent) return null
  return findRequirement(tree.parent, name, requested, requestor)
}

// Find the highest level in the tree that we can install this module in.
// If the module isn't installed above us yet, that'd be the very top.
// If it is, then it's the level below where its installed.
var earliestInstallable = exports.earliestInstallable = function (requiredBy, tree, pkg) {
  validate('OOO', arguments)

  function undeletedModuleMatches (child) {
    return !child.removed && moduleName(child) === pkg.name
  }
  if (tree.children.some(undeletedModuleMatches)) return null

  // If any of the children of this tree have conflicting
  // binaries then we need to decline to install this package here.
  var binaryMatches = typeof pkg.bin === 'object' && tree.children.some(function (child) {
    if (child.removed) return false
    if (typeof child.package.bin !== 'object') return false
    return Object.keys(child.package.bin).some(function (bin) {
      return pkg.bin[bin]
    })
  })
  if (binaryMatches) return null

  // if this tree location requested the same module then we KNOW it
  // isn't compatible because if it were findRequirement would have
  // found that version.
  var deps = tree.package.dependencies || {}
  if (!tree.removed && requiredBy !== tree && deps[pkg.name]) {
    return null
  }

  // FIXME: phantomChildren doesn't actually belong in the package.json
  if (tree.package._phantomChildren && tree.package._phantomChildren[pkg.name]) return null

  if (!tree.parent) return tree
  if (tree.isGlobal) return tree

  return (earliestInstallable(requiredBy, tree.parent, pkg) || tree)
}


text:
	Text...

	Text...

		This text is pre-formatted.
		So you can write tags here.
		Variables are evaluated as usual.


text:
package org.apache.sshd.server.auth;

/**
 * @author Apache MINA SSHD Project
 */
public class UserAuthKeyboardInteractiveFactory extends AbstractUserAuthFactory {
    public static final String NAME = KB_INTERACTIVE;
    public static final UserAuthKeyboardInteractiveFactory INSTANCE = new UserAuthKeyboardInteractiveFactory();

    public UserAuthKeyboardInteractiveFactory() {
        super(NAME);
    }

    @Override
    public UserAuth create() {
        return new UserAuthKeyboardInteractive();
    }
}


text:
package zuhause.test;

import java.util.List;
import java.util.Map;
import org.apache.logging.log4j.Logger;
import zuhause.ws.ApiRaspiStats;

/**
 *
 * @author Eduardo Folly
 */
public class RaspiStatsTest extends AbstractTest {

    private final ApiRaspiStats api = new ApiRaspiStats();

    /**
     *
     * @param logger
     */
    public RaspiStatsTest(Logger logger) {
        super(logger);
    }

    /**
     *
     */
    @Override
    public void run() {
        diskTest();
        ramTest();
    }

    /**
     *
     */
    private void diskTest() {
        List<Map<String, Object>> list = null;
        try {
            list = api.diskGet();

            listNotEmpty(list);

            // TODO - Realizar mais teste.
            // print(list);
        } catch (Exception ex) {
            error(ex, list);
        }
    }

    /**
     *
     */
    private void ramTest() {
        List<Map<String, Object>> list = null;
        try {
            list = api.ramGet();

            listSizeEqual(list, 1);

            Map map = list.get(0);

            mapHasKey(map, "shared");
            mapHasKey(map, "total");
            mapHasKey(map, "available");
            mapHasKey(map, "used");
            mapHasKey(map, "free");
            mapHasKey(map, "buff/cache");

        } catch (Exception ex) {
            error(ex, list);
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/C:/Users/Sebastian/AndroidStudioProjects/TCL/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.2.1/res/values-xlarge-land/values-xlarge-land.xml -->
    <eat-comment/>
    <dimen name="abc_search_view_text_min_width">256dip</dimen>
</resources>


text:
enum
{
	SCHED_CROW_IDLE_WALK = LAST_SHARED_SCHEDULE,
	SCHED_CROW_IDLE_FLY,

	//
	// Various levels of wanting to get away from something, selected
	// by current value of m_nMorale.
	//
	SCHED_CROW_WALK_AWAY,
	SCHED_CROW_RUN_AWAY,
	SCHED_CROW_HOP_AWAY,
	SCHED_CROW_FLY_AWAY,

	SCHED_CROW_FLY,
	SCHED_CROW_FLY_FAIL,

	SCHED_CROW_BARNACLED,
};

//
// Custom tasks.
//
enum
{
	TASK_CROW_FIND_FLYTO_NODE = LAST_SHARED_TASK,
	//TASK_CROW_PREPARE_TO_FLY,
	TASK_CROW_TAKEOFF,
	//TASK_CROW_LAND,
	TASK_CROW_FLY,
	TASK_CROW_FLY_TO_HINT,
	TASK_CROW_PICK_RANDOM_GOAL,
	TASK_CROW_PICK_EVADE_GOAL,
	TASK_CROW_HOP,

	TASK_CROW_FALL_TO_GROUND,
	TASK_CROW_PREPARE_TO_FLY_RANDOM,

	TASK_CROW_WAIT_FOR_BARNACLE_KILL,
};

//
// Custom conditions.
//
enum
{
	COND_CROW_ENEMY_TOO_CLOSE = LAST_SHARED_CONDITION,
	COND_CROW_ENEMY_WAY_TOO_CLOSE,
	COND_CROW_FORCED_FLY,
	COND_CROW_BARNACLED,
};

enum FlyState_t
{
	FlyState_Walking = 0,
	FlyState_Flying,
	FlyState_Falling,
	FlyState_Landing,
};

//-----------------------------------------------------------------------------
// The crow class.
//-----------------------------------------------------------------------------
class CNPC_Crow : public CAI_BaseNPC
{
	DECLARE_CLASS( CNPC_Crow, CAI_BaseNPC );

public:

	//
	// CBaseEntity:
	//
	virtual void Spawn( void );
	virtual void Precache( void );

	virtual Vector BodyTarget( const Vector &posSrc, bool bNoisy = true );

	virtual int DrawDebugTextOverlays( void );

	//
	// CBaseCombatCharacter:
	//
	virtual int OnTakeDamage_Alive( const CTakeDamageInfo &info );
	virtual bool CorpseGib( const CTakeDamageInfo &info );
	bool	BecomeRagdollOnClient( const Vector &force );

	//
	// CAI_BaseNPC:
	//
	virtual float MaxYawSpeed( void ) { return 120.0f; }

	virtual Class_T Classify( void );
	virtual void GatherEnemyConditions( CBaseEntity *pEnemy );

	virtual void HandleAnimEvent( animevent_t *pEvent );
	virtual int GetSoundInterests( void );
	virtual int SelectSchedule( void );
	virtual void StartTask( const Task_t *pTask );
	virtual void RunTask( const Task_t *pTask );

	virtual bool HandleInteraction( int interactionType, void *data, CBaseCombatCharacter *sourceEnt );

	virtual void OnChangeActivity( Activity eNewActivity );

	virtual bool OverrideMove( float flInterval );

	virtual bool FValidateHintType( CAI_Hint *pHint );
	virtual Activity GetHintActivity( short sHintType, Activity HintsActivity );

	virtual void PainSound( const CTakeDamageInfo &info );
	virtual void DeathSound( const CTakeDamageInfo &info );
	virtual void IdleSound( void );
	virtual void AlertSound( void );
	virtual void StopLoopingSounds( void );
	virtual void UpdateEfficiency( bool bInPVS );

	virtual bool QueryHearSound( CSound *pSound );

	void InputFlyAway( inputdata_t &inputdata );

	void TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr, CDmgAccumulator *pAccumulator );
	void StartTargetHandling( CBaseEntity *pTargetEnt );

	DEFINE_CUSTOM_AI;
	DECLARE_DATADESC();

	int			m_iBirdType;
	bool		m_bOnJeep;

protected:
	void SetFlyingState( FlyState_t eState );
	inline bool IsFlying( void ) const { return GetNavType() == NAV_FLY; }

	void Takeoff( const Vector &vGoal );
	void FlapSound( void );

	void MoveCrowFly( float flInterval );
	bool Probe( const Vector &vecMoveDir, float flSpeed, Vector &vecDeflect );

	bool IsDeaf() { return m_bIsDeaf; }

protected:
	float m_flGroundIdleMoveTime;

	float m_flEnemyDist;		// Distance to GetEnemy(), cached in GatherEnemyConditions.
	int m_nMorale;				// Used to determine which avoidance schedule to pick. Degrades as I pick avoidance schedules.

	bool m_bReachedMoveGoal;

	float m_flHopStartZ;		// Our Z coordinate when we started a hop. Used to check for accidentally hopping off things.

	bool		m_bPlayedLoopingSound;

private:

	Activity NPC_TranslateActivity( Activity eNewActivity );

	float				m_flSoarTime;
	bool				m_bSoar;
	Vector				m_vLastStoredOrigin;
	float				m_flLastStuckCheck;

	float				m_flDangerSoundTime;

	Vector				m_vDesiredTarget;
	Vector				m_vCurrentTarget;

	bool				m_bIsDeaf;
};

//-----------------------------------------------------------------------------
// Purpose: Seagull. Crow with a different model.
//-----------------------------------------------------------------------------
class CNPC_Seagull : public CNPC_Crow
{
	DECLARE_CLASS( CNPC_Seagull, CNPC_Crow );

public:

	void Spawn( void )
	{
		SetModelName( AllocPooledString("models/seagull.mdl") );
		BaseClass::Spawn();

		m_iBirdType = BIRDTYPE_SEAGULL;
	}

	void PainSound( const CTakeDamageInfo &info )
	{
		EmitSound( "NPC_Seagull.Pain" );
	}

	void DeathSound( const CTakeDamageInfo &info )
	{
		EmitSound( "NPC_Seagull.Pain" );
	}

	void IdleSound( void )
	{
		EmitSound( "NPC_Seagull.Idle" );
	}
};

//-----------------------------------------------------------------------------
// Purpose: Pigeon. Crow with a different model.
//-----------------------------------------------------------------------------
class CNPC_Pigeon : public CNPC_Crow
{
	DECLARE_CLASS( CNPC_Pigeon, CNPC_Crow );

public:
	void Spawn( void )
	{
		SetModelName( AllocPooledString("models/pigeon.mdl") );
		BaseClass::Spawn();

		m_iBirdType = BIRDTYPE_PIGEON;
	}

	void IdleSound( void )
	{
		EmitSound( "NPC_Pigeon.Idle" );
	}
};

#endif // NPC_CROW_H


text:
<?php
namespace Respect\Validation\Exceptions;

class AlwaysValidException extends ValidationException
{
    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => '{{name}} is always valid',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => '{{name}} is always invalid',
        ),
    );
}


text:
namespace boost{ namespace math{ namespace detail{

template <class T, class Policy>
inline typename tools::promote_args<T>::type trunc(const T& v, const Policy& pol, const std::false_type&)
{
   BOOST_MATH_STD_USING
   typedef typename tools::promote_args<T>::type result_type;
   if(!(boost::math::isfinite)(v))
      return policies::raise_rounding_error("boost::math::trunc<%1%>(%1%)", 0, static_cast<result_type>(v), static_cast<result_type>(v), pol);
   return (v >= 0) ? static_cast<result_type>(floor(v)) : static_cast<result_type>(ceil(v));
}

template <class T, class Policy>
inline typename tools::promote_args<T>::type trunc(const T& v, const Policy&, const std::true_type&)
{
   return v;
}

}

template <class T, class Policy>
inline typename tools::promote_args<T>::type trunc(const T& v, const Policy& pol)
{
   return detail::trunc(v, pol, std::integral_constant<bool, detail::is_integer_for_rounding<T>::value>());
}
template <class T>
inline typename tools::promote_args<T>::type trunc(const T& v)
{
   return trunc(v, policies::policy<>());
}
//
// The following functions will not compile unless T has an
// implicit conversion to the integer types.  For user-defined
// number types this will likely not be the case.  In that case
// these functions should either be specialized for the UDT in
// question, or else overloads should be placed in the same
// namespace as the UDT: these will then be found via argument
// dependent lookup.  See our concept archetypes for examples.
//
// Non-standard numeric limits syntax "(std::numeric_limits<int>::max)()"
// is to avoid macro substiution from MSVC
// https://stackoverflow.com/questions/27442885/syntax-error-with-stdnumeric-limitsmax
//
template <class T, class Policy>
inline int itrunc(const T& v, const Policy& pol)
{
   BOOST_MATH_STD_USING
   typedef typename tools::promote_args<T>::type result_type;
   result_type r = boost::math::trunc(v, pol);
   if(r > static_cast<result_type>((std::numeric_limits<int>::max)()) || r < static_cast<result_type>((std::numeric_limits<int>::min)()))
      return static_cast<int>(policies::raise_rounding_error("boost::math::itrunc<%1%>(%1%)", 0, static_cast<result_type>(v), 0, pol));
   return static_cast<int>(r);
}
template <class T>
inline int itrunc(const T& v)
{
   return itrunc(v, policies::policy<>());
}

template <class T, class Policy>
inline long ltrunc(const T& v, const Policy& pol)
{
   BOOST_MATH_STD_USING
   typedef typename tools::promote_args<T>::type result_type;
   result_type r = boost::math::trunc(v, pol);
   if(r > static_cast<result_type>((std::numeric_limits<long>::max)()) || r < static_cast<result_type>((std::numeric_limits<long>::min)()))
      return static_cast<long>(policies::raise_rounding_error("boost::math::ltrunc<%1%>(%1%)", 0, static_cast<result_type>(v), 0L, pol));
   return static_cast<long>(r);
}
template <class T>
inline long ltrunc(const T& v)
{
   return ltrunc(v, policies::policy<>());
}

#ifdef BOOST_HAS_LONG_LONG

template <class T, class Policy>
inline boost::long_long_type lltrunc(const T& v, const Policy& pol)
{
   BOOST_MATH_STD_USING
   typedef typename tools::promote_args<T>::type result_type;
   result_type r = boost::math::trunc(v, pol);
   if(r > static_cast<result_type>((std::numeric_limits<boost::long_long_type>::max)()) ||
      r < static_cast<result_type>((std::numeric_limits<boost::long_long_type>::min)()))
   {
      return static_cast<boost::long_long_type>(policies::raise_rounding_error("boost::math::lltrunc<%1%>(%1%)", 0, v, static_cast<boost::long_long_type>(0), pol));
   }
   return static_cast<boost::long_long_type>(r);
}
template <class T>
inline boost::long_long_type lltrunc(const T& v)
{
   return lltrunc(v, policies::policy<>());
}

#endif

template <class T, class Policy>
inline typename std::enable_if<std::is_constructible<int, T>::value, int>::type
   iconvert(const T& v, const Policy&)
{
   return static_cast<int>(v);
}

template <class T, class Policy>
inline typename boost::disable_if_c<std::is_constructible<int, T>::value, int>::type
   iconvert(const T& v, const Policy& pol)
{
   using boost::math::itrunc;
   return itrunc(v, pol);
}

template <class T, class Policy>
inline typename std::enable_if<std::is_constructible<long, T>::value, long>::type
   lconvert(const T& v, const Policy&)
{
   return static_cast<long>(v);
}

template <class T, class Policy>
inline typename boost::disable_if_c<std::is_constructible<long, T>::value, long>::type
   lconvert(const T& v, const Policy& pol)
{
   using boost::math::ltrunc;
   return ltrunc(v, pol);
}

#ifdef BOOST_HAS_LONG_LONG

template <class T, class Policy>
inline typename std::enable_if<std::is_constructible<boost::long_long_type, T>::value, boost::long_long_type>::type
   llconvertert(const T& v, const Policy&)
{
   return static_cast<boost::long_long_type>(v);
}

template <class T, class Policy>
inline typename boost::disable_if_c<std::is_constructible<boost::long_long_type, T>::value, boost::long_long_type>::type
   llconvertert(const T& v, const Policy& pol)
{
   using boost::math::lltrunc;
   return lltrunc(v, pol);
}

#endif

}} // namespaces

#endif // BOOST_MATH_TRUNC_HPP


text:
[![npm](https://img.shields.io/npm/v/hapi-auth-ip-whitelist.svg)](https://www.npmjs.com/package/hapi-auth-ip-whitelist)

## Usage

### Localhost

Only accept calls from localhost:

```js
server.auth.strategy('localhost', 'ip-whitelist', ['127.0.0.1']);
```

*NOTE: Third parameter of server.auth.strategy is options which must be an object.*

To be used like

```js
server.route({
  method: 'GET',
  path: '/',
  handler(request, h) { return "That was from localhost!" },
  options: { auth: 'localhost' }
});
```

In the route receives a request from a different IP, it will respond a `401 unauthorized` error with the message `192.168.0.102 is not a valid IP`, where `192.168.0.102` is the IP of the request.

### Address ranges

You can also specify several IPs by passing a list instead. [CIDR](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation is supported.

For example, consider the IPs to expect requests from, as specified by [MercadoPago](https://www.mercadopago.com.co/developers/en/api-docs/basics/design-considerations).

```js
server.auth.strategy(
  'mercado-pago-webhook',
  'ip-whitelist',
  ['209.225.49.0/24', '216.33.197.0/24', '216.33.196.0/24', '63.128.82.0/24', '63.128.83.0/24', '63.128.94.0/24']
);
```

### Behind proxy

In case you are behind a proxy, use Hapi plugin `therealyou`.
It will find the "real" IP in X-Forward headers and modify the request.info.remoteAddress.

```js
server.register([
  {
    plugin: require('therealyou')
  },
  {
    plugin: require('hapi-auth-ip-whitelist')
  }
])
```

## Example server

Start local example server with

```bash
npm start
```

then visit [http://localhost:3000](http://localhost:3000).

Successfully authenticated request [http://localhost:3000/authenticated](http://localhost:3000/authenticated).
Unauthenticated request [http://localhost:3000/unauthenticated](http://localhost:3000/unauthenticated).


text:
extern "C" float __akDefaultSampleRate;
extern "C" int __akDefaultChannelCount;

#else

extern float __akDefaultSampleRate;
extern int __akDefaultChannelCount;

#endif


text:
/*global module: false, require: false */

var pongular = require('pongular').pongular;

pongular.module('mongle').run(function(app, passport, auth,
                                       indexCtl, usersCtl, pageCtrl, eventsCtrl, templatesCtrl,
                                       partialsCtrl, contentCtrl, galleryCtrl ) {

  //User Routes
  app.get('/signin', usersCtl.signin);
  app.get('/signup', usersCtl.signup);
  app.get('/signout', usersCtl.signout);
  app.get('/users', auth.requiresLogin, auth.users.routeUnauthorized, usersCtl.list);

  //Setting up the users api
  app.post('/users', usersCtl.create);
  app.post('/users/session', passport.authenticate('local', {
    failureRedirect: '/signin',
    failureFlash: 'Invalid email or password.'
  }), usersCtl.session);
  app.put('/users/:userId', usersCtl.update);
  app.get('/users/me', usersCtl.me);
  app.get('/users/:userId', auth.requiresLogin, auth.users.routeUnauthorized, usersCtl.show);

  //Finish with setting up the userId param
  app.param('userId', usersCtl.user);

  app.get('/pages', auth.requiresLogin, pageCtrl.list);
  app.get('/pages/:pageId', auth.requiresLogin, pageCtrl.show);
  app.delete('/pages/:pageId', auth.requiresLogin, pageCtrl.remove);
  app.post('/pages', auth.requiresLogin, pageCtrl.create);
  app.put('/pages/:pageId', auth.requiresLogin, pageCtrl.update);

  //Finish with setting up the userId param
  app.param('pageId', pageCtrl.page);

  // Templates
  app.get('/templates', auth.requiresLogin, templatesCtrl.list);

  // Partials
  app.get('/partials', auth.requiresLogin, partialsCtrl.list);
  app.get('/partials/:partialName', auth.requiresLogin, partialsCtrl.show);
  app.put('/partials/:partialName', auth.requiresLogin, partialsCtrl.update);

  app.param('partialName', partialsCtrl.partial);

  // Events
  app.get('/events', auth.requiresLogin, eventsCtrl.list);
  app.get('/events/:eventId', auth.requiresLogin, eventsCtrl.show);
  app.put('/events/:eventId', auth.requiresLogin, eventsCtrl.update);
  app.post('/events', auth.requiresLogin, eventsCtrl.create);

  // Gallery
  app.get('/gallery', auth.requiresLogin, galleryCtrl.list);
  app.put('/gallery', auth.requiresLogin, galleryCtrl.upload);

  // Home route
  app.get('/admin', indexCtl.render);

  //Home route
  app.get('/', contentCtrl.homepage);
  app.get('/:contentUrl', contentCtrl.render);
  app.param('contentUrl', contentCtrl.page);

  return {};

});


text:
We'd love to accept your patches and contributions to this project. There are
just a few small guidelines you need to follow.

## Contributor License Agreement

Contributions to this project must be accompanied by a Contributor License
Agreement. You (or your employer) retain the copyright to your contribution;
this simply gives us permission to use and redistribute your contributions as
part of the project. Head over to <https://cla.developers.google.com/> to see
your current agreements on file or to sign a new one.

You generally only need to submit a CLA once, so if you've already submitted one
(even if it was for a different project), you probably don't need to do it
again.

## Code reviews

All submissions, including submissions by project members, require review. We
use GitHub pull requests for this purpose.
Consult [GitHub Help](https://help.github.com/articles/about-pull-requests/)
for more information on using pull requests.

## Community Guidelines

This project follows [Google's Open Source Community Guidelines](https://opensource.google/conduct)

## Code Style

All code must adhere to the [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html).

## How to write a Detector

- Implement the [DetectorConfig](TODO) interface, referring to the Javadoc for
instructions

- Add the detector into the appropriate group of detectors in [Detectors](TODO)

  - Adding a new group of detectors will require changes to [RunnerConfig](TODO)
and [DetectorRunner](TODO)

- Add the detector into the help section of the tool in [Main](Main)

- Add Unit tests