code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
package uk.gov.dvsa.motr.web.formatting;
import com.amazonaws.util.StringUtils;
import uk.gov.dvsa.motr.remote.vehicledetails.VehicleDetails;
public class MakeModelFormatter {
private static String UNKNOWN_VALUE = "UNKNOWN";
public static String getMakeModelString(String make, String model, String makeInFull) {
boolean makeValid = !StringUtils.isNullOrEmpty(make) && !make.equalsIgnoreCase(UNKNOWN_VALUE);
boolean modelValid = !StringUtils.isNullOrEmpty(model) && !model.equalsIgnoreCase(UNKNOWN_VALUE);
if (!makeValid && !modelValid) {
if (StringUtils.isNullOrEmpty(makeInFull)) {
return "";
}
return makeInFull.toUpperCase();
}
if (makeValid && !modelValid) {
return make.toUpperCase();
}
if (!makeValid && modelValid) {
return model.toUpperCase();
}
return (make + " " + model).toUpperCase();
}
public static String getMakeModelDisplayStringFromVehicleDetails(VehicleDetails vehicleDetails, String endDelimeter) {
String makeModel =
MakeModelFormatter.getMakeModelString(vehicleDetails.getMake(), vehicleDetails.getModel(), vehicleDetails.getMakeInFull());
if (endDelimeter == null) {
return makeModel;
}
return makeModel.equals("") ? makeModel : makeModel + endDelimeter;
}
}
| dvsa/motr-webapp | webapp/src/main/java/uk/gov/dvsa/motr/web/formatting/MakeModelFormatter.java | Java | mit | 1,423 |
<?php
/* WebProfilerBundle:Profiler:toolbar_redirect.html.twig */
class __TwigTemplate_76d5100a24a797f44c4c78afddbb3ca32310a1272d9ad67227fbe6b4fb04239d extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
try {
$this->parent = $this->env->loadTemplate("TwigBundle::layout.html.twig");
} catch (Twig_Error_Loader $e) {
$e->setTemplateFile($this->getTemplateName());
$e->setTemplateLine(1);
throw $e;
}
$this->blocks = array(
'title' => array($this, 'block_title'),
'body' => array($this, 'block_body'),
);
}
protected function doGetParent(array $context)
{
return "TwigBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_title($context, array $blocks = array())
{
echo "Redirection Intercepted";
}
// line 5
public function block_body($context, array $blocks = array())
{
// line 6
echo " <div class=\"sf-reset\">
<div class=\"block-exception\">
<h1>This request redirects to <a href=\"";
// line 8
echo twig_escape_filter($this->env, (isset($context["location"]) ? $context["location"] : $this->getContext($context, "location")), "html", null, true);
echo "\">";
echo twig_escape_filter($this->env, (isset($context["location"]) ? $context["location"] : $this->getContext($context, "location")), "html", null, true);
echo "</a>.</h1>
<p>
<small>
The redirect was intercepted by the web debug toolbar to help debugging.
For more information, see the \"intercept-redirects\" option of the Profiler.
</small>
</p>
</div>
</div>
";
}
public function getTemplateName()
{
return "WebProfilerBundle:Profiler:toolbar_redirect.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 50 => 8, 46 => 6, 43 => 5, 37 => 3, 11 => 1,);
}
}
| bhupendrakanojiya/mediapackage | app/cache/dev/twig/76/d5/100a24a797f44c4c78afddbb3ca32310a1272d9ad67227fbe6b4fb04239d.php | PHP | mit | 2,377 |
describe('A Feature', function() {
it('A Scenario', function() {
// ### Given missing code
});
});
| BonsaiDen/featureful | test/validator/step/tests/missingCode.test.js | JavaScript | mit | 121 |
<?php
/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014 - 2015, British Columbia Institute of Technology
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author EllisLab Dev Team
* @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/)
* @copyright Copyright (c) 2014 - 2015, British Columbia Institute of Technology (http://bcit.ca/)
* @license http://opensource.org/licenses/MIT MIT License
* @link http://codeigniter.com
* @since Version 3.0.0
* @filesource
*/
defined('BASEPATH') OR exit('No direct script access allowed');
$lang['migration_none_found'] = 'No migrations were found.';
$lang['migration_not_found'] = 'No migration could be found with the version number: %s.';
$lang['migration_sequence_gap'] = 'There is a gap in the migration sequence near version number: %s.';
$lang['migration_multiple_version'] = 'There are multiple migrations with the same version number: %s.';
$lang['migration_class_doesnt_exist'] = 'The migration class "%s" could not be found.';
$lang['migration_missing_up_method'] = 'The migration class "%s" is missing an "up" method.';
$lang['migration_missing_down_method'] = 'The migration class "%s" is missing a "down" method.';
$lang['migration_invalid_filename'] = 'Migration "%s" has an invalid filename.';
| mashfiqcse13/Publication | system/language/english/migration_lang.php | PHP | mit | 2,449 |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Typeset.Domain.Git")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("664be847-82ba-4cdf-8812-82aa1aa8cbd0")]
| typeset/typeset | Typeset.Domain.Git/Properties/AssemblyInfo.cs | C# | mit | 241 |
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-top-nav',
templateUrl: './top-nav.component.html',
styleUrls: ['./top-nav.component.css']
})
export class TopNavComponent implements OnInit {
title = 'Blogging Application';
constructor() { }
ngOnInit() {
}
}
| softgandhi/ng2-blogs | src/app/top-nav/top-nav.component.ts | TypeScript | mit | 306 |
<!DOCTYPE html>
<html lang="ru">
<head>
<title><?=$seo['SeoTitle']?></title>
<meta name="description" content="<?=$seo['SeoDescription']?>" />
<meta name="keywords" content="<?=$seo['SeoKeyword']?>" />
<meta name="author" content="">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="format-detection" content="telephone=no" />
<link rel="shortcut icon" href="favicon.ico" />
<link rel="stylesheet" type="text/css" href="/files/site/site/css/jquery.bxslider.css"/>
<link rel="stylesheet" type="text/css" href="/files/site/site/css/animations.css"/>
<link rel="stylesheet" type="text/css" href="/files/site/site/css/flexslider.css"/>
<link rel="stylesheet" type="text/css" href="/files/site/site/css/jquery.fancybox.css"/>
<link rel="stylesheet" type="text/css" href="/files/site/site/css/grid.css"/>
<link rel="stylesheet" type="text/css" href="/files/site/site/css/style.css"/>
<link rel="stylesheet" type="text/css" href="/files/site/base/css/froala.css"/>
<script src="/files/site/site/js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&language=ru"></script>
<script src="/files/site/site/js/jquery.bxslider.js" type="text/javascript" charset="utf-8"></script>
<script src="/files/site/site/js/jquery.flexslider.js" type="text/javascript" charset="utf-8"></script>
<script src="/files/site/site/js/jquery.fancybox.min.js" type="text/javascript" charset="utf-8"></script>
<script src="/files/site/all/func.js"></script>
<script src="/files/site/site/js/script.js" type="text/javascript" charset="utf-8"></script>
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if IE]>
<link rel="stylesheet" href="/files/site/site/css/css_ie.css" type="text/css" media="screen">
<script src="/files/site/site/js/html5shiv.js" type="text/javascript" charset="utf-8"></script>
<script src="/files/site/site/js/respond.js" type="text/javascript" charset="utf-8"></script>
<script src="/files/site/site/js/PIE.js" type="text/javascript" charset="utf-8"></script>
<![endif]-->
</head>
<body>
<!--<div id="anchor2"></div>-->
<div id="allBox">
<div id="all">
<section class="header header-in" style="<?=$fon?>">
<div class="nav-wrap">
<div class="wrapper">
<div class="nav">
<?= $menu ?>
</div>
<div class="logo-field">
<div class="logo">
<a href="/"><img src="/files/site/site/images/logo.png" alt=""></a>
</div>
<div class="phone">
<i class="icon icon-phone"></i><?=$vstavka[0]['Description']?>
</div>
</div>
</div>
</div>
</section>
<div class="clear"></div>
| sereg/mebel | application/views/site/base/header.php | PHP | mit | 3,391 |
import Fs from 'fs'
import Path from 'path'
import XmlParser from 'xml2js'
const Zip = require('node-zip')
/**
* This represents an entry in the zip file. If the entry comes from an existing archive previously loaded, the content will be automatically decompressed/converted first.
* @see https://stuk.github.io/jszip/documentation/api_zipobject.html
*/
export type ZipObject = {
/** the absolute path of the file. */
name: string
/** `true` if this is a directory. */
dir: boolean
/** the last modification date. */
date: Date
/** the comment for this file. */
comment: string
/** The UNIX permissions of the file, if any. 16 bits number. */
unixPermissions: number
/** The DOS permissions of the file, if any. 6 bits number. */
dosPermissions: number
/** the options of the file. The available options. */
options: {
compression: (
name: string,
data:
| string
| ArrayBuffer
| Uint8Array
| Buffer
| Blob
| Promise<any>
| WritableStream
) => void
}
/** Files. */
files: any
}
/** Sheet data. */
export type SheetData = {
/** Sheet name. */
name: string
/** Data obtained by converting the XML of the sheet to the JavaScript Object. */
sheet: any
/** Data obtained by converting the XML of the shared strings to the JavaScript Object. */
strings?: any
}
/** Sheet size. */
export type SheetSize = {
/** Row of sheet. */
row: {
/** Minimum value of row. */
min: number
/** Maximum value of row. */
max: number
}
/** Column of sheet. */
col: {
/** Minimum value of column. */
min: number
/** Maximum value of column. */
max: number
}
}
/** It is a cell in a sheet. */
export type Cell = {
/** Row position. */
row: number
/** Column position. */
col: number
/** Type.. */
type: string
/** Value string. */
value: string
}
/** It is the position of the cell. */
type Position = {
/** Row position. */
row: number
/** Column position. */
col: number
}
/** The maximum number of sheets (Excel 97). */
const MaxSheets = 256
/** Defines the file path in the XLSX. */
const FilePaths = {
WorkBook: 'xl/workbook.xml',
SharedStrings: 'xl/sharedStrings.xml',
SheetBase: 'xl/worksheets/sheet'
}
/**
* Create a empty cells.
* @param rows Rows count.
* @param cols Columns count.
* @return Cells.
*/
export const createEmptyCells = (rows: number, cols: number): string[][] => {
const arr = []
for (let i = 0; i < rows; ++i) {
const row = []
for (let j = 0; j < cols; ++j) {
row.push('')
}
arr.push(row)
}
return arr
}
/**
* Get a cells from a rows.
* @param rows Rows.
* @return Cells.
*/
export const getCells = (rows: any[]): Cell[] => {
const cells: Cell[] = []
rows
.filter((row) => {
return row.c && 0 < row.c.length
})
.forEach((row) => {
row.c.forEach((cell: any) => {
const position = getPosition(cell.$.r)
cells.push({
row: position.row,
col: position.col,
type: cell.$.t ? cell.$.t : '',
value: cell.v && 0 < cell.v.length ? cell.v[0] : ''
})
})
})
return cells
}
/**
* Get the coordinates of the cell.
* @param text Position text. Such as "A1" and "U109".
* @return Position.
*/
export const getPosition = (text: string): Position => {
// 'A1' -> [A, 1]
const units = text.split(/([0-9]+)/)
if (units.length < 2) {
return { row: 0, col: 0 }
}
return {
row: parseInt(units[1], 10),
col: numOfColumn(units[0])
}
}
/**
* Get a sheet name.
* @param zip Extract data of XLSX (Zip) file.
* @param index Index of sheet. Range of from 1 to XlsxExtractor.count.
* @returns Sheet name.
*/
const getSheetName = async (zip: ZipObject, index: number): Promise<string> => {
const root = await parseXML(zip.files[FilePaths.WorkBook].asText())
let name = ''
if (
root &&
root.workbook &&
root.workbook.sheets &&
0 < root.workbook.sheets.length &&
root.workbook.sheets[0].sheet
) {
root.workbook.sheets[0].sheet.some((sheet: any) => {
const id = Number(sheet.$.sheetId)
if (id === index) {
name = sheet.$.name || ''
return true
}
return false
})
}
return name
}
/**
* Get a sheet data.
* @param zip Extract data of XLSX (Zip) file.
* @param index Index of sheet. Range of from 1 to XlsxExtractor.count.
* @returns Sheet data.
*/
export const getSheetData = async (
zip: ZipObject,
index: number
): Promise<SheetData> => {
const data: SheetData = {
name: '',
sheet: {}
}
data.name = await getSheetName(zip, index)
data.sheet = await parseXML(
zip.files[FilePaths.SheetBase + index + '.xml'].asText()
)
if (zip.files[FilePaths.SharedStrings]) {
data.strings = await parseXML(zip.files[FilePaths.SharedStrings].asText())
}
return data
}
/**
* Gets the number of sheets.
* @param zip Extract data of XLSX (Zip) file.
* @returns Number of sheets
*/
export const getSheetInnerCount = (zip: ZipObject): number => {
let count = 0
for (let i = 1; i < MaxSheets; ++i) {
const path = FilePaths.SheetBase + i + '.xml'
if (!zip.files[path]) {
break
}
++count
}
return count
}
/**
* Get the range of the sheet.
* @param sheet Sheet data.
* @param cells Cells.
* @return Range.
*/
export const getSheetSize = (sheet: any, cells: any[]): SheetSize => {
// Get the there if size is defined
if (
sheet &&
sheet.worksheet &&
sheet.worksheet.dimension &&
0 <= sheet.worksheet.dimension.length
) {
const range = sheet.worksheet.dimension[0].$.ref.split(':')
if (range.length === 2) {
const min = getPosition(range[0])
const max = getPosition(range[1])
return {
row: { min: min.row, max: max.row },
col: { min: min.col, max: max.col }
}
}
}
const ascend = (a: number, b: number) => a - b
const rows = cells.map((cell) => cell.row).sort(ascend)
const cols = cells.map((cell) => cell.col).sort(ascend)
return {
row: { min: rows[0], max: rows[rows.length - 1] },
col: { min: cols[0], max: cols[cols.length - 1] }
}
}
/**
* Convert the column text to number.
* @param text Column text, such as A" and "AA".
* @return Column number, otherwise -1.
*/
export const numOfColumn = (text: string): number => {
const letters = [
'',
'A',
'B',
'C',
'D',
'E',
'F',
'G',
'H',
'I',
'J',
'K',
'L',
'M',
'N',
'O',
'P',
'Q',
'R',
'S',
'T',
'U',
'V',
'W',
'X',
'Y',
'Z'
]
const col = text.trim().split('')
let num = 0
for (let i = 0, max = col.length; i < max; ++i) {
num *= 26
num += letters.indexOf(col[i])
}
return num
}
/**
* Parse the `r` element of XML.
* @param r `r` elements.
* @return Parse result.
*/
export const parseR = (r: any[]): string => {
let value = ''
r.forEach((obj) => {
if (obj.t) {
value += parseT(obj.t)
}
})
return value
}
/**
* Parse the `t` element of XML.
* @param t `t` elements.
* @return Parse result.
*/
export const parseT = (t: any[]): string => {
let value = ''
t.forEach((obj) => {
switch (typeof obj) {
case 'string':
value += obj
break
// The value of xml:space="preserve" is stored in the underscore
case 'object':
if (obj._ && typeof obj._ === 'string') {
value += obj._
}
break
default:
break
}
})
return value
}
/**
* Parse the XML text.
* @param xml XML text.
* @return XML parse task.
*/
export const parseXML = (xml: string): Promise<any> => {
return new Promise((resolve, reject) => {
XmlParser.parseString(xml, (err, obj) => {
return err ? reject(err) : resolve(obj)
})
})
}
/**
* Extract a zip file.
* @param path Zip file path.
* @return If success zip object, otherwise null.
* @throws Failed to expand the XLSX file.
*/
export const unzip = (path: string): ZipObject => {
try {
const file = Fs.readFileSync(Path.resolve(path))
return Zip(file)
} catch (err) {
throw new Error('Failed to expand the XLSX file.')
}
}
/**
* Get a value from the cell strings.
*
* @param str Cell strings.
*
* @return Value.
*/
export const valueFromStrings = (str: any): string => {
let value = ''
const keys = Object.keys(str)
keys.forEach((key) => {
switch (key) {
case 't':
value += parseT(str[key])
break
case 'r':
value += parseR(str[key])
break
default:
break
}
})
return value
}
| akabekobeko/npm-xlsx-extractor | src/lib/xlsx-util.ts | TypeScript | mit | 8,722 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Core
* @copyright Copyright (c) 2006-2019 Magento, Inc. (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
class Mage_Core_Model_Layout_Element extends Varien_Simplexml_Element
{
public function prepare($args)
{
switch ($this->getName()) {
case 'layoutUpdate':
break;
case 'layout':
break;
case 'update':
break;
case 'remove':
break;
case 'block':
$this->prepareBlock($args);
break;
case 'reference':
$this->prepareReference($args);
break;
case 'action':
$this->prepareAction($args);
break;
default:
$this->prepareActionArgument($args);
break;
}
$children = $this->children();
foreach ($this as $child) {
$child->prepare($args);
}
return $this;
}
public function getBlockName()
{
$tagName = (string)$this->getName();
if ('block'!==$tagName && 'reference'!==$tagName || empty($this['name'])) {
return false;
}
return (string)$this['name'];
}
public function prepareBlock($args)
{
$type = (string)$this['type'];
$name = (string)$this['name'];
$className = (string)$this['class'];
if (!$className) {
$className = Mage::getConfig()->getBlockClassName($type);
$this->addAttribute('class', $className);
}
$parent = $this->getParent();
if (isset($parent['name']) && !isset($this['parent'])) {
$this->addAttribute('parent', (string)$parent['name']);
}
return $this;
}
public function prepareReference($args)
{
return $this;
}
public function prepareAction($args)
{
$parent = $this->getParent();
$this->addAttribute('block', (string)$parent['name']);
return $this;
}
public function prepareActionArgument($args)
{
return $this;
}
}
| portchris/NaturalRemedyCompany | src/app/code/core/Mage/Core/Model/Layout/Element.php | PHP | mit | 2,987 |
using System;
using umbraco.cms.businesslogic.datatype;
using umbraco.interfaces;
using Umbraco.Core;
namespace InfoCaster.Umbraco.TextFieldPreviewable.DataType
{
public class DataType : BaseDataType, IDataType
{
static readonly Guid _guid = new Guid("7a5355a6-684c-4813-9c0d-8487852bd08b");
IDataEditor _editor;
IData _baseData;
IDataPrevalue _prevalueeditor;
public override IDataEditor DataEditor
{
get
{
if (_editor == null)
_editor = new DataEditor(Data, ((PrevalueEditor)PrevalueEditor).Configuration);
return _editor;
}
}
public override IData Data
{
get
{
if (_baseData == null)
_baseData = new DefaultData(this);
return _baseData;
}
}
public override Guid Id
{
get { return _guid; }
}
public override string DataTypeName
{
get { return "Textbox Previewable"; }
}
public override IDataPrevalue PrevalueEditor
{
get
{
if (_prevalueeditor == null)
_prevalueeditor = new PrevalueEditor(this);
return _prevalueeditor;
}
}
}
} | kipusoep/TextFieldPreviewable | DataType/DataType.cs | C# | mit | 1,055 |
from app.app_and_db import app
from flask import Blueprint, jsonify, render_template
import datetime
import random
import requests
dashboard = Blueprint('dashboard', __name__)
cumtd_endpoint = 'https://developer.cumtd.com/api/{0}/{1}/{2}'
cumtd_endpoint = cumtd_endpoint.format('v2.2', 'json', 'GetDeparturesByStop')
wunderground_endpoint = 'http://api.wunderground.com/api/{0}/hourly/q/{1}/{2}.json'
wunderground_endpoint = wunderground_endpoint.format(app.config['WUNDERGROUND_API_KEY'], 'IL', 'Champaign')
@dashboard.route('/')
def index():
time=datetime.datetime.now().time().strftime('%I:%M').lstrip('0')
return render_template('pages/dashboard.html', image_number=random.randrange(1, 9), time=time)
#Query no more than once a minute
@dashboard.route('/bus')
def bus_schedule():
params = {'key' : app.config['CUMTD_API_KEY'],
'stop_id' : 'GRN4TH',
'count' : '5'}
response = requests.get(cumtd_endpoint, params=params)
json = response.json()
departures = []
for departure in json['departures'] :
if departure['trip']['direction'] == 'East':
departures.append(departure)
return jsonify(departures=departures)
#Query no more than once every three minutes
@dashboard.route('/weather')
def weather():
response = requests.get(wunderground_endpoint)
json = response.json()
return jsonify(json)
app.register_blueprint(dashboard, url_prefix='/dashboard') | nickofbh/kort2 | app/dashboard/views.py | Python | mit | 1,414 |
package main
import (
"fmt"
"net/http"
)
func main() {
var m map[string]string
fmt.Printf("len(m):%2d\n", len(m)) // 0
for k, _ := range m { // nil map iterates zero times
fmt.Println(k)
}
v, ok := m["2"]
fmt.Printf("v:%s, ok:%v\n\n", v, ok) // zero(string), false
// m["foo"] = "bar" // panic: assignment to entry in nil map
//----------------------------------------------------------
//
req, err := NewGet(
"http://www.baidu.com",
map[string]string{
"USER-AGENT": "golang/gopher", // 末尾,或}
}, // 末尾,或)
)
fmt.Println("_______________________")
fmt.Println(req.Method) // GET
fmt.Println(req.URL) // http://www.baidu.com
fmt.Println(req.Header) // map[User-Agent:[golang/gopher]]
fmt.Println(err) // nil
fmt.Println("_______________________")
//----------------------------------------------------------
req2, err := NewGet("http://www.baidu.com", map[string]string{}) // ok
fmt.Println(req2)
//----------------------------------------------------------
// nil maps are valid empty maps
req3, err := NewGet("http://www.baidu.com", nil) // ok
fmt.Println(req3)
//----------------------------------------------------------
// make map
var m1 map[int]int // nil map
fmt.Println(m1 == nil)
fmt.Println("=============")
m2 := make(map[int]int, 0) // not nil map, but empty map
fmt.Println(m2 == nil)
m2[5] = 55 // write to empty map is ok
fmt.Println(m2) // map[5:55]
}
func NewGet(url string, headers map[string]string) (*http.Request, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
for k, v := range headers {
req.Header.Set(k, v)
}
return req, nil
}
| fivezh/Keepgoing | golang/nil/nilMap.go | GO | mit | 1,693 |
$(document).ready(function(){
//The user will be prompted to continue and go down the page by clicking on an HTML element
//The result will be a smooth transition of the word ">>>Continue" and then a smooth scroll down the page
//to the next stage of the user's process in the application: making an account(probably done through Google and Facebook)
$(document).ready(function(){
$('#userPrompt>span:nth-child(1)').delay(350).fadeTo(450,1.0);
$('#userPrompt>span:nth-child(2)').delay(450).fadeTo(450,1.0);
$('#userPrompt>span:nth-child(3)').delay(550).fadeTo(450,1.0); //this div represents the bottom option, or the 'quick presentation div'
$('#Continue').delay(700).fadeTo(850,1.0); //Continue button
});
/*$('#userPrompt').click(function(){
$('#promptOverlay').fadeTo(850,0.0);
$(this).delay(850).animate({marginLeft: '900px'}, 850)
$(this).delay(100).fadeOut(850);
});
The "#promptOverlay" div is not longer in use, and as a result, we do not need to use this line of code...
Let's keep things....simpler...
*/
$('#userPrompt').one("click",function(){
$(this).fadeTo(850,0);
//Scroll Down
var height = $("#navBar").css('height');
$('html , body').animate({
scrollTop: 725
}, 1250);
//Create Options on Options Bar div, first by making a dividing line
$('#imagine').delay(1250).animate({
height: '330px'
});
//Create Third option by making it now visible...
$('#quick').delay(1850).fadeTo(300, 1);
//Time to make options visible...
$('.heading').delay(2000).fadeTo(300, 1);
});
//With options now created, we can create some functionality to those options, making the user's experience both meaningful and aesthetically pleasing.
/*$('#returner, #imagine').click(function(){
//alert("Log into account"); Test
$('.heading').fadeTo(850, 0);
$('#quick').fadeOut();
$('#imagine').delay(250).animate({
height: '0px'
});
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
$('#optionsBar');
});*/
/*$('#newUser').one("click", function(){
//alert("Make account"); Test
$('#optionsBar>div').fadeOut(850);
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
var welcomeHeader = '<h3 margin-top="20px" class="heading">Welcome to ShowCase. Please Log In Below...</h3>';
var inputTypeOne = '<input type="text/plain">keep'
//$('h3').delay(1900).html("Welcome to ShowCase. Please Log In Below...").appendTo("#optionsBar");
$(welcomeHeader).hide().delay(2000).appendTo('#optionsBar').fadeIn(100);
var styles = {
fontFamily: 'Lato',
color: 'rgba(16,16,14,0.65)',
paddingTop: '10px',
};
// $(welcomeHeader).css(headerStyle);
$('#optionsBar').css(styles);
});//End of Account Creation Process...*
$('#quick').click(function(){
//alert("I just don't care."); Test
$('.heading').fadeTo(850, 0);
$('#quick').fadeOut();
$('#imagine').delay(250).animate({
height: '0px'
});
$('#optionsBar').delay(1400).css("background-color", "rgb(215,215,215)");
});*/
}); | clutchRoy/treeBranc | script.js | JavaScript | mit | 3,028 |
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include "utils/VerticalLinearizer2D.hpp"
#include <cstdlib>
void verticalLinearizer2D_test_array(const std::size_t width, const std::size_t height)
{
VerticalLinearizer2D linearizer (width, height, -10, -20);
std::size_t linearized = 0;
for(int y = -20; y < height; ++y) {
for(int x = -10; x < width; ++x) {
BOOST_REQUIRE(linearizer.getX(linearized) == x);
BOOST_REQUIRE(linearizer.getY(linearized) == y);
BOOST_REQUIRE(linearizer.linearize(x, y) == linearized);
linearized += 1;
}
}
}
BOOST_AUTO_TEST_CASE( VerticalLinearizer2DTest )
{
verticalLinearizer2D_test_array(0, 0);
verticalLinearizer2D_test_array(10, 10);
verticalLinearizer2D_test_array(20, 60);
verticalLinearizer2D_test_array(60, 20);
}
| cedric-demongivert/robot-valley | robot-valley-tests/VerticalLinearizer2DTest.cpp | C++ | mit | 818 |
#include <seqan/sequence.h>
#include <seqan/index.h>
using namespace seqan;
int main()
{
String<Dna5> genome = "TTATTAAGCGTATAGCCCTATAAATATAA";
Index<String<Dna5>, IndexEsa<> > esaIndex(genome);
Finder<Index<String<Dna5>, IndexEsa<> > > esaFinder(esaIndex);
while(find(esaFinder, "TATAA")){
std::cout << position(esaFinder) << '\n'; // -> 0
}
} | bkahlert/seqan-research | raw/pmsb13/pmsb13-data-20130530/sources/zsrreplh0s7rggp4/2013-04-11T09-44-00.424+0200/sandbox/my_sandbox/apps/Indices1/Indices1.cpp | C++ | mit | 379 |
<section>
<?php
echo getClientPage(10);
?>
</section> | piggy1979/redbike | page-clients.php | PHP | mit | 57 |
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { jqxCheckBoxComponent } from 'components/angular_jqxcheckbox';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, jqxCheckBoxComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
| coderFirework/app | js/jqwidgets-4.4.0/demos/angular2/app/checkbox/twowaydatabinding/app.module.ts | TypeScript | mit | 449 |
import AnswerRating from './answerRating';
import FeedBackResults from './feedbackResults';
import './less/feedback.less';
// Check if bar rating should be initialized
const ratingWrapper = document.querySelector('.rating-wrapper');
if (ratingWrapper !== null) {
AnswerRating();
}
// Check if feed back results charts should be initialized
const feedBackResultsElement = document.getElementById('feedback-results');
if (feedBackResultsElement !== null) {
FeedBackResults();
}
| dotKom/onlineweb4 | assets/feedback/index.js | JavaScript | mit | 483 |
from __future__ import print_function
import sys
sys.path.append('..') # help python find cyton.py relative to scripts folder
from openbci import cyton as bci
import logging
import time
def printData(sample):
# os.system('clear')
print("----------------")
print("%f" % (sample.id))
print(sample.channel_data)
print(sample.aux_data)
print("----------------")
if __name__ == '__main__':
# port = '/dev/tty.OpenBCI-DN008VTF'
port = '/dev/tty.usbserial-DB00JAM0'
# port = '/dev/tty.OpenBCI-DN0096XA'
baud = 115200
logging.basicConfig(filename="test.log", format='%(asctime)s - %(levelname)s : %(message)s', level=logging.DEBUG)
logging.info('---------LOG START-------------')
board = bci.OpenBCICyton(port=port, scaled_output=False, log=True)
print("Board Instantiated")
board.ser.write('v')
time.sleep(10)
board.start_streaming(printData)
board.print_bytes_in()
| OpenBCI/OpenBCI_Python | scripts/test.py | Python | mit | 937 |
package com.tazine.container.collection.set.cases.stud;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* @author frank
* @since 1.0.0
*/
public class Client {
public static void main(String[] args) {
Set<Student> set = new HashSet<>();
Student s1 = new Student(1, "kobe");
Student s2 = new Student(1, "james");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
set.add(s1);
System.out.println(set);
s1.setSno(2);
Iterator<Student> it = set.iterator();
System.out.println(s1.equals(it.next()));
set.add(s1);
System.out.println(set);
}
}
| BookFrank/CodePlay | codeplay-container/src/main/java/com/tazine/container/collection/set/cases/stud/Client.java | Java | mit | 700 |
// Copyright © 2018 Wave Engine S.L. All rights reserved. Use is subject to license terms.
#region Using Statements
using System;
using WaveEngine.Common.Math;
using WaveEngine.Framework;
using WaveEngine.Framework.Graphics;
#endregion
namespace WaveEngine.Components.GameActions
{
/// <summary>
/// Game action which animates an 3D entity
/// </summary>
public class MoveTo3DGameAction : Vector3AnimationGameAction
{
/// <summary>
/// The transform
/// </summary>
private Transform3D transform;
/// <summary>
/// If the animation is in local coordinates.
/// </summary>
private bool local;
/// <summary>
/// Initializes a new instance of the <see cref="MoveTo3DGameAction"/> class.
/// </summary>
/// <param name="entity">The target entity</param>
/// <param name="to">The target position</param>
/// <param name="time">Animation duration</param>
/// <param name="ease">The ease function</param>
/// <param name="local">If the position is in local coordinates.</param>
public MoveTo3DGameAction(Entity entity, Vector3 to, TimeSpan time, EaseFunction ease = EaseFunction.None, bool local = false)
: base(entity, Vector3.Zero, to, time, ease)
{
this.local = local;
if (local)
{
this.updateAction = this.LocalMoveAction;
}
else
{
this.updateAction = this.MoveAction;
}
this.transform = entity.FindComponent<Transform3D>();
}
/// <summary>
/// Performs the run operation
/// </summary>
protected override void PerformRun()
{
this.from = this.local ? this.transform.LocalPosition : this.transform.Position;
base.PerformRun();
}
/// <summary>
/// Move action
/// </summary>
/// <param name="delta">The delta movement</param>
private void MoveAction(Vector3 delta)
{
this.transform.Position = delta;
}
/// <summary>
/// Move action
/// </summary>
/// <param name="delta">The delta movement</param>
private void LocalMoveAction(Vector3 delta)
{
this.transform.LocalPosition = delta;
}
}
}
| WaveEngine/Components | Shared/GameActions/Animations/MoveTo3DGameAction.cs | C# | mit | 2,419 |
function initialize(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
exec: {
build: {
command: 'make build'
},
// 'build-types': { command: 'make build-types' },
'build-style': { command: 'make build-style' },
'build-server': { command: 'make build-server' },
'build-client': { command: 'make build-client' },
// 'database-shell': {
// command: "echo 'mongo --username client --password testing christian.mongohq.com:10062/Beta-CitizenDish'"
// }
},
watch: {
types: {
files: [ 'types/egyptian-number-system.d.ts'],
tasks: [ 'exec:build-types'],
spawn: false
},
style: {
files: [ 'style/less/*.less', 'style/less/**/*.less','public/less/**/*.less' ],
tasks: [ 'exec:build-style'],
spawn: false
},
server: {
files: [ 'server/**/*.ts', 'server/*.ts', ],
tasks: [ 'exec:build-server' ],
spawn: false
},
client: {
files: [ 'client/**/*.ts', 'client/*.ts'],
tasks: [ 'exec:build-client' ],
spawn: false
}
},
nodemon: {
application: {
script: 'server/api.js',
options: {
ext: 'js',
watch: ['server'],
ignore: ['server/**'],
delay: 2000,
legacyWatch: false
}
},
developer: {
script: 'server/developer-api.js',
options: {
ext: 'js',
watch: ['server'],
// ignore: ['server/**'],
delay: 3000,
legacyWatch: false
}
}
} ,
concurrent: {
options: {
logConcurrentOutput: true
},
developer: {
tasks: [ 'exec:build', 'nodemon:developer', 'watch:style', 'watch:server', 'watch:client' ]
// tasks: [ 'exec:build', 'nodemon:server', 'watch:types', 'watch:style', 'watch:server', 'watch:client' ]
},
application: {
tasks: [ 'exec:build', 'nodemon:application', 'watch:style', 'watch:server', 'watch:client' ]
// tasks: [ 'exec:build', 'nodemon:server', 'watch:types', 'watch:style', 'watch:server', 'watch:client' ]
}
}
}) ;
grunt.loadNpmTasks('grunt-exec');
grunt.loadNpmTasks('grunt-nodemon');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-concurrent');
grunt.registerTask('default', ['concurrent:application']) ;
grunt.registerTask('developer', ['concurrent:developer']) ;
grunt.option('debug', true);
// grunt.option('force', true);
}
module.exports = initialize; | davidkleriga/egyptian-number-system | Gruntfile.js | JavaScript | mit | 3,137 |
__author__ = 'mengpeng'
import os
from unittest import TestCase
from pycrawler.scraper import DefaultScraper
from pycrawler.handler import Handler
from pycrawler.utils.tools import gethash
from test_scraper import SpiderTest
class TestTempHandler(TestCase):
def test_setargs(self):
h = Handler.get('TempHandler')(SpiderTest('testspider'))
self.assertEqual('./tmp/testspider/', h.args['path'])
args = {'path': './newpath/'}
h.setargs(args)
self.assertEqual('./newpath/testspider/', h.args['path'])
def test_parse(self):
h = Handler.get('TempHandler')(SpiderTest('testspider'))
h.parse('conent', 'testurl1')
self.assertTrue(os.path.exists(h._tmpfilename('testurl1')))
def test__tmpfilename(self):
h = Handler.get('TempHandler')(SpiderTest('testspider'))
self.assertEqual('./tmp/testspider/' + str(gethash('sample')) + '.html', h._tmpfilename('sample'))
self.assertTrue(os.path.exists('./tmp/')) | ymero/PyCrawler | test/test_handler.py | Python | mit | 996 |
<?php namespace Fbf\LaravelSimpleFaqs;
use Eloquent;
class Faq extends Eloquent {
const DRAFT = 'DRAFT';
const APPROVED = 'APPROVED';
protected $table = 'fbf_laravel_simple_faqs';
public static $sluggable = array(
'build_from' => 'question',
'save_to' => 'slug',
'unique' => true,
);
} | FbF/Laravel-Simple-Faqs | src/models/Faq.php | PHP | mit | 303 |
#include "include/global.h"
#include "alinous.lock/ConcurrentGate.h"
#include "alinous.db.table.lockmonitor/IDatabaseLock.h"
#include "alinous.db.table.lockmonitor/RowLock.h"
#include "alinous.db.table.lockmonitor/IThreadLocker.h"
#include "alinous.db.table/IDatabaseTable.h"
#include "alinous.db.table.lockmonitor.db/RowLockManager.h"
namespace alinous {namespace db {namespace table {namespace lockmonitor {namespace db {
bool RowLockManager::__init_done = __init_static_variables();
bool RowLockManager::__init_static_variables(){
Java2CppSystem::getSelf();
ThreadContext* ctx = ThreadContext::newThreadContext();
{
GCNotifier __refobj1(ctx, __FILEW__, __LINE__, L"RowLockManager", L"__init_static_variables");
}
ctx->localGC();
delete ctx;
return true;
}
RowLockManager::RowLockManager(IDatabaseTable* table, long long oid, ConcurrentGate* concurrentGate, ThreadContext* ctx) throw() : IObject(ctx), table(nullptr), oid(0), list(GCUtils<ArrayList<RowLock> >::ins(this, (new(ctx) ArrayList<RowLock>(ctx)), ctx, __FILEW__, __LINE__, L"")), concurrentGate(nullptr)
{
__GC_MV(this, &(this->table), table, IDatabaseTable);
this->oid = oid;
__GC_MV(this, &(this->concurrentGate), concurrentGate, ConcurrentGate);
}
void RowLockManager::__construct_impl(IDatabaseTable* table, long long oid, ConcurrentGate* concurrentGate, ThreadContext* ctx) throw()
{
__GC_MV(this, &(this->table), table, IDatabaseTable);
this->oid = oid;
__GC_MV(this, &(this->concurrentGate), concurrentGate, ConcurrentGate);
}
RowLockManager::~RowLockManager() throw()
{
ThreadContext *ctx = ThreadContext::getCurentContext();
if(ctx != nullptr){ctx->incGcDenial();}
__releaseRegerences(false, ctx);
if(ctx != nullptr){ctx->decGcDenial();}
}
void RowLockManager::__releaseRegerences(bool prepare, ThreadContext* ctx) throw()
{
ObjectEraser __e_obj1(ctx, __FILEW__, __LINE__, L"RowLockManager", L"~RowLockManager");
__e_obj1.add(this->table, this);
table = nullptr;
__e_obj1.add(this->list, this);
list = nullptr;
__e_obj1.add(this->concurrentGate, this);
concurrentGate = nullptr;
if(!prepare){
return;
}
}
ConcurrentGate* RowLockManager::getConcurrentGate(ThreadContext* ctx) throw()
{
return concurrentGate;
}
RowLock* RowLockManager::newLock(IThreadLocker* locker, bool update, ThreadContext* ctx) throw()
{
ArrayList<RowLock>* list = this->list;
int maxLoop = list->size(ctx);
for(int i = 0; i != maxLoop; ++i)
{
RowLock* lock = list->get(i, ctx);
if(lock->locker == locker)
{
return lock;
}
}
RowLock* lock = (new(ctx) RowLock(this->table, this->oid, update, locker, this->concurrentGate, ctx));
this->list->add(lock, ctx);
return lock;
}
RowLock* RowLockManager::releaseLock(IThreadLocker* locker, ThreadContext* ctx) throw()
{
ArrayList<RowLock>* list = this->list;
int maxLoop = list->size(ctx);
for(int i = 0; i != maxLoop; ++i)
{
RowLock* lock = list->get(i, ctx);
if(lock->locker == locker)
{
if(lock->count == 1)
{
this->list->remove(i, ctx);
}
return lock;
}
}
return nullptr;
}
void RowLockManager::__cleanUp(ThreadContext* ctx){
}
}}}}}
| alinous-core/alinous-elastic-db | lib/src_java/alinous.db.table.lockmonitor.db/RowLockManager.cpp | C++ | mit | 3,119 |
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2013 The paccoin developer
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include "base58.h"
#include "paccoinrpc.h"
#include "db.h"
#include "init.h"
#include "main.h"
#include "net.h"
#include "wallet.h"
using namespace std;
using namespace boost;
using namespace boost::assign;
using namespace json_spirit;
void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out)
{
txnouttype type;
vector<CTxDestination> addresses;
int nRequired;
out.push_back(Pair("asm", scriptPubKey.ToString()));
out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end())));
if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired))
{
out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD)));
return;
}
out.push_back(Pair("reqSigs", nRequired));
out.push_back(Pair("type", GetTxnOutputType(type)));
Array a;
BOOST_FOREACH(const CTxDestination& addr, addresses)
a.push_back(CpaccoinAddress(addr).ToString());
out.push_back(Pair("addresses", a));
}
void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry)
{
entry.push_back(Pair("txid", tx.GetHash().GetHex()));
entry.push_back(Pair("version", tx.nVersion));
entry.push_back(Pair("time", (boost::int64_t)tx.nTime));
entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime));
if (tx.nVersion >= 2)
{
entry.push_back(Pair("tx-comment", tx.strTxComment));
}
Array vin;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
Object in;
if (tx.IsCoinBase())
in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
else
{
in.push_back(Pair("txid", txin.prevout.hash.GetHex()));
in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n));
Object o;
o.push_back(Pair("asm", txin.scriptSig.ToString()));
o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end())));
in.push_back(Pair("scriptSig", o));
}
in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence));
vin.push_back(in);
}
entry.push_back(Pair("vin", vin));
Array vout;
for (unsigned int i = 0; i < tx.vout.size(); i++)
{
const CTxOut& txout = tx.vout[i];
Object out;
out.push_back(Pair("value", ValueFromAmount(txout.nValue)));
out.push_back(Pair("n", (boost::int64_t)i));
Object o;
ScriptPubKeyToJSON(txout.scriptPubKey, o);
out.push_back(Pair("scriptPubKey", o));
vout.push_back(out);
}
entry.push_back(Pair("vout", vout));
if (hashBlock != 0)
{
entry.push_back(Pair("blockhash", hashBlock.GetHex()));
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second)
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
{
entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight));
entry.push_back(Pair("time", (boost::int64_t)pindex->nTime));
entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime));
}
else
entry.push_back(Pair("confirmations", 0));
}
}
}
Value getrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getrawtransaction <txid> [verbose=0]\n"
"If verbose=0, returns a string that is\n"
"serialized, hex-encoded data for <txid>.\n"
"If verbose is non-zero, returns an Object\n"
"with information about <txid>.");
uint256 hash;
hash.SetHex(params[0].get_str());
bool fVerbose = false;
if (params.size() > 1)
fVerbose = (params[1].get_int() != 0);
CTransaction tx;
uint256 hashBlock = 0;
if (!GetTransaction(hash, tx, hashBlock))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction");
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
string strHex = HexStr(ssTx.begin(), ssTx.end());
if (!fVerbose)
return strHex;
Object result;
result.push_back(Pair("hex", strHex));
TxToJSON(tx, hashBlock, result);
return result;
}
Value listunspent(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 3)
throw runtime_error(
"listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n"
"Returns array of unspent transaction outputs\n"
"with between minconf and maxconf (inclusive) confirmations.\n"
"Optionally filtered to only include txouts paid to specified addresses.\n"
"Results are an array of Objects, each of which has:\n"
"{txid, vout, scriptPubKey, amount, confirmations}");
RPCTypeCheck(params, list_of(int_type)(int_type)(array_type));
int nMinDepth = 1;
if (params.size() > 0)
nMinDepth = params[0].get_int();
int nMaxDepth = 9999999;
if (params.size() > 1)
nMaxDepth = params[1].get_int();
set<CpaccoinAddress> setAddress;
if (params.size() > 2)
{
Array inputs = params[2].get_array();
BOOST_FOREACH(Value& input, inputs)
{
CpaccoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid paccoin address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
}
}
Array results;
vector<COutput> vecOutputs;
pwalletMain->AvailableCoins(vecOutputs, false);
BOOST_FOREACH(const COutput& out, vecOutputs)
{
if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth)
continue;
if(setAddress.size())
{
CTxDestination address;
if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address))
continue;
if (!setAddress.count(address))
continue;
}
int64 nValue = out.tx->vout[out.i].nValue;
const CScript& pk = out.tx->vout[out.i].scriptPubKey;
Object entry;
entry.push_back(Pair("txid", out.tx->GetHash().GetHex()));
entry.push_back(Pair("vout", out.i));
entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end())));
entry.push_back(Pair("amount",ValueFromAmount(nValue)));
entry.push_back(Pair("confirmations",out.nDepth));
results.push_back(entry);
}
return results;
}
Value createrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n"
"Create a transaction spending given inputs\n"
"(array of objects containing transaction id and output number),\n"
"sending to given address(es).\n"
"Returns hex-encoded raw transaction.\n"
"Note that the transaction's inputs are not signed, and\n"
"it is not stored in the wallet or transmitted to the network.");
RPCTypeCheck(params, list_of(array_type)(obj_type));
Array inputs = params[0].get_array();
Object sendTo = params[1].get_obj();
CTransaction rawTx;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
CTxIn in(COutPoint(uint256(txid), nOutput));
rawTx.vin.push_back(in);
}
set<CpaccoinAddress> setAddress;
BOOST_FOREACH(const Pair& s, sendTo)
{
CpaccoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid paccoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
setAddress.insert(address);
CScript scriptPubKey;
scriptPubKey.SetDestination(address.Get());
int64 nAmount = AmountFromValue(s.value_);
CTxOut out(nAmount, scriptPubKey);
rawTx.vout.push_back(out);
}
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << rawTx;
return HexStr(ss.begin(), ss.end());
}
Value decoderawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"decoderawtransaction <hex string>\n"
"Return a JSON object representing the serialized, hex-encoded transaction.");
RPCTypeCheck(params, list_of(str_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
Object result;
TxToJSON(tx, 0, result);
return result;
}
Value signrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 4)
throw runtime_error(
"signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n"
"Sign inputs for raw transaction (serialized, hex-encoded).\n"
"Second optional argument (may be null) is an array of previous transaction outputs that\n"
"this transaction depends on but may not yet be in the blockchain.\n"
"Third optional argument (may be null) is an array of base58-encoded private\n"
"keys that, if given, will be the only keys used to sign the transaction.\n"
"Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n"
"ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n"
"Returns json object with keys:\n"
" hex : raw transaction with signature(s) (hex-encoded string)\n"
" complete : 1 if transaction has a complete set of signature (0 if not)"
+ HelpRequiringPassphrase());
RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true);
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
vector<CTransaction> txVariants;
while (!ssData.empty())
{
try {
CTransaction tx;
ssData >> tx;
txVariants.push_back(tx);
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
}
if (txVariants.empty())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction");
// mergedTx will end up with all the signatures; it
// starts as a clone of the rawtx:
CTransaction mergedTx(txVariants[0]);
bool fComplete = true;
// Fetch previous transactions (inputs):
map<COutPoint, CScript> mapPrevOut;
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTransaction tempTx;
MapPrevTx mapPrevTx;
CTxDB txdb("r");
map<uint256, CTxIndex> unused;
bool fInvalid;
// FetchInputs aborts on failure, so we go one at a time.
tempTx.vin.push_back(mergedTx.vin[i]);
tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid);
// Copy results into mapPrevOut:
BOOST_FOREACH(const CTxIn& txin, tempTx.vin)
{
const uint256& prevHash = txin.prevout.hash;
if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n)
mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey;
}
}
// Add previous txouts given in the RPC call:
if (params.size() > 1 && params[1].type() != null_type)
{
Array prevTxs = params[1].get_array();
BOOST_FOREACH(Value& p, prevTxs)
{
if (p.type() != obj_type)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
Object prevOut = p.get_obj();
RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type));
string txidHex = find_value(prevOut, "txid").get_str();
if (!IsHex(txidHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal");
uint256 txid;
txid.SetHex(txidHex);
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
string pkHex = find_value(prevOut, "scriptPubKey").get_str();
if (!IsHex(pkHex))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal");
vector<unsigned char> pkData(ParseHex(pkHex));
CScript scriptPubKey(pkData.begin(), pkData.end());
COutPoint outpoint(txid, nOut);
if (mapPrevOut.count(outpoint))
{
// Complain if scriptPubKey doesn't match
if (mapPrevOut[outpoint] != scriptPubKey)
{
string err("Previous output scriptPubKey mismatch:\n");
err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+
scriptPubKey.ToString();
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err);
}
}
else
mapPrevOut[outpoint] = scriptPubKey;
}
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && params[2].type() != null_type)
{
fGivenKeys = true;
Array keys = params[2].get_array();
BOOST_FOREACH(Value k, keys)
{
CpaccoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key");
CKey key;
bool fCompressed;
CSecret secret = vchSecret.GetSecret(fCompressed);
key.SetSecret(secret, fCompressed);
tempKeystore.AddKey(key);
}
}
else
EnsureWalletIsUnlocked();
const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain);
int nHashType = SIGHASH_ALL;
if (params.size() > 3 && params[3].type() != null_type)
{
static map<string, int> mapSigHashValues =
boost::assign::map_list_of
(string("ALL"), int(SIGHASH_ALL))
(string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))
(string("NONE"), int(SIGHASH_NONE))
(string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY))
(string("SINGLE"), int(SIGHASH_SINGLE))
(string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY))
;
string strHashType = params[3].get_str();
if (mapSigHashValues.count(strHashType))
nHashType = mapSigHashValues[strHashType];
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param");
}
bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE);
// Sign what we can:
for (unsigned int i = 0; i < mergedTx.vin.size(); i++)
{
CTxIn& txin = mergedTx.vin[i];
if (mapPrevOut.count(txin.prevout) == 0)
{
fComplete = false;
continue;
}
const CScript& prevPubKey = mapPrevOut[txin.prevout];
txin.scriptSig.clear();
// Only sign SIGHASH_SINGLE if there's a corresponding output:
if (!fHashSingle || (i < mergedTx.vout.size()))
SignSignature(keystore, prevPubKey, mergedTx, i, nHashType);
// ... and merge in other signatures:
BOOST_FOREACH(const CTransaction& txv, txVariants)
{
txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig);
}
if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, true, 0))
fComplete = false;
}
Object result;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << mergedTx;
result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end())));
result.push_back(Pair("complete", fComplete));
return result;
}
Value sendrawtransaction(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 1)
throw runtime_error(
"sendrawtransaction <hex string>\n"
"Submits raw transaction (serialized, hex-encoded) to local node and network.");
RPCTypeCheck(params, list_of(str_type));
// parse hex string from parameter
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
// deserialize binary data stream
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint256 hashTx = tx.GetHash();
// See if the transaction is already in a block
// or in the memory pool:
CTransaction existingTx;
uint256 hashBlock = 0;
if (GetTransaction(hashTx, existingTx, hashBlock))
{
if (hashBlock != 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex());
// Not in block, but already in the memory pool; will drop
// through to re-relay it.
}
else
{
// push to local node
CTxDB txdb("r");
if (!tx.AcceptToMemoryPool(txdb))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected");
SyncWithWallets(tx, NULL, true);
}
RelayMessage(CInv(MSG_TX, hashTx), tx);
return hashTx.GetHex();
}
| wmcorless/paccoin | src/rpcrawtransaction.cpp | C++ | mit | 19,860 |
<?php
class PostsController extends AppController {
var $name = 'Posts';
var $uses = array('Post', 'User', 'Answer', 'History', 'Setting', 'Tag', 'PostTag', 'Vote', 'Widget');
var $components = array('Auth', 'Session', 'Markdownify', 'Markdown', 'Cookie', 'Email', 'Recaptcha', 'Htmlfilter');
var $helpers = array('Javascript', 'Time', 'Cache', 'Thumbnail', 'Recaptcha', 'Session');
//var $cacheAction = "1 hour";
public function beforeRender() {
$this->getWidgets();
$this->underMaintenance();
}
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('ask', 'view', 'answer', 'display', 'miniSearch', 'maintenance');
$this->isAdmin($this->Auth->user('id'));
$this->Cookie->name = 'user_cookie';
$this->Cookie->time = 604800; // or '1 hour'
$this->Cookie->path = '/';
$this->Cookie->domain = $_SERVER['SERVER_NAME'];
$this->Cookie->key = 'MZca3*f113vZ^%v ';
/**
* If a user leaves the site and the session ends they will be relogged in with their cookie information if available.
*/
if($this->Cookie->read('User')) {
$this->Auth->login($this->Cookie->read('User'));
}
}
public function afterFilter() {
$this->Session->delete('errors');
}
public function delete($id) {
if(!$this->isAdmin($this->Auth->user('id'))) {
$this->Session->setFlash(__('You do not have permission to access that..',true), 'error');
$this->redirect('/');
}
$this->Post->delete($id);
$this->Session->setFlash(__('Post deleted',true), 'error');
$this->redirect('/');
}
public function ask() {
$this->set('title_for_layout', __('Ask a question',true));
if(!empty($this->data)) {
/**
* reCAPTCHA Check
*/
$this->data['reCAPTCHA'] = $this->params['form'];
$this->__validatePost($this->data, '/questions/ask', true);
/**
* If the user is not logged in create an account for them.
*/
if(!empty($this->data['User'])) {
$user = $this->__userSave(array('User' => $this->data['User']));
$this->Auth->login($user);
}
/**
* Add in required Post data
*/
if(!empty($user)) {
$userId = $user['User']['id'];
} else {
$userId = $this->Auth->user('id');
}
$post = $this->__postSave('question', $userId, $this->data);
$this->redirect('/questions/' . $post['public_key'] . '/' . $post['url_title']);
}
}
public function answer($public_key) {
$question = $this->Post->findByPublicKey($public_key);
if(!empty($this->data)) {
$this->data['reCAPTCHA'] = $this->params['form'];
$this->__validatePost($this->data, '/questions/' . $question['Post']['public_key'] . '/' . $question['Post']['url_title'] . '#user_answer', true);
if(!empty($this->data['User'])) {
$user = $this->__userSave(array('User' => $this->data['User']));
$this->Auth->login($user);
}
if(!empty($user)) {
$userId = $user['User']['id'];
$username = $user['User']['username'];
} else {
$userId = $this->Auth->user('id');
$username = $this->Auth->user('username');
}
$flag_limit = $this->Setting->find(
'first', array(
'conditions' => array('name' => 'flag_display_limit')
)
);
$post = $this->__postSave('answer', $userId, $this->data, $question['Post']['id']);
if(($question['Post']['notify'] == 1) && ($post['flags'] < $flag_limit['Setting']['value'])) {
$user = $this->User->find(
'first', array(
'conditions' => array(
'User.id' => $question['Post']['user_id']
),
'fields' => array('User.email', 'User.username')
)
);
$this->set('question', $question);
$this->set('username', $username);
$this->set('dear', $user['User']['username']);
$this->set('answer', $this->data['Post']['content']);
$this->Email->from = 'Answerman <answers@' . $_SERVER['SERVER_NAME'] . '>';
$this->Email->to = $user['User']['email'];
$this->Email->subject = __('Your question has been answered!',true);
$this->Email->template = 'notification';
$this->Email->sendAs = 'both';
$this->Email->send();
}
$this->redirect('/questions/' . $question['Post']['public_key'] . '/' . $question['Post']['url_title']);
}
}
/**
* Validates the Post data.
* Since Posts need to validate for both logged in and non logged in accounts a separate validation technique was needed.
*
* @param string $data
* @param string $redirectUrl
* @return void
*/
public function __validatePost($data, $redirectUrl, $reCaptcha = false) {
$this->Post->set($data);
$this->User->set($data);
$errors = array();
$recaptchaErrors = array();
if($reCaptcha == true) {
if(!$this->Recaptcha->valid($data['reCAPTCHA'])) {
$data['Post']['content'] = $this->Markdownify->parseString($data['Post']['content']);
$recaptchaErrors = array('recaptcha' => __('Invalid reCAPTCHA entered.',true));
$errors = array(
'errors' => $recaptchaErrors,
'data' => $data
);
$this->Session->write(array('errors' => $errors));
$this->redirect($redirectUrl);
}
}
if(!$this->Post->validates() || !$this->User->validates()) {
$data['Post']['content'] = $this->Markdownify->parseString($data['Post']['content']);
$validationErrors = array_merge($this->Post->invalidFields(), $this->User->invalidFields(), $recaptchaErrors);
$errors = array(
'errors' => $validationErrors,
'data' => $data
);
$this->Session->write(array('errors' => $errors));
$this->redirect($redirectUrl);
}
}
/**
* Saves the Post data for a user
*
* @param string $type Either question or answer
* @param string $userId the ID of the user posting
* @param string $data $this->data
* @return array $post The saved Post data.
*/
public function __postSave($type, $userId, $data, $relatedId = null) {
/**
* Add in required Post data
*/
$this->data['Post']['type'] = $type;
$this->data['Post']['user_id'] = $userId;
$this->data['Post']['timestamp'] = time();
if($type == 'question') {
$this->data['Post']['url_title'] = $this->Post->niceUrl($this->data['Post']['title']);
}
if($type == 'answer') {
$this->data['Post']['related_id'] = $relatedId;
}
$this->data['Post']['public_key'] = uniqid();
if(!empty($this->data['Post']['tags'])) {
$this->Post->Behaviors->attach('Tag', array('table_label' => 'tags', 'tags_label' => 'tag', 'separator' => ', '));
}
/**
* Filter out any nasty XSS
*/
Configure::write('debug', 0);
$this->data['Post']['content'] = str_replace('<code>', '<code class="prettyprint">', $this->data['Post']['content']);
$this->data['Post']['content'] = @$this->Htmlfilter->filter($this->data['Post']['content']);
/**
* Spam Protection
*/
$flags = 0;
$content = strip_tags($this->data['Post']['content']);
// Get links in the content
$links = preg_match_all("#(^|[\n ])(?:(?:http|ftp|irc)s?:\/\/|www.)(?:[-A-Za-z0-9]+\.)+[A-Za-z]{2,4}(?:[-a-zA-Z0-9._\/&=+%?;\#]+)#is", $content, $matches);
$links = $matches[0];
$totalLinks = count($links);
$length = strlen($content);
// How many links are in the body
// +2 if less than 2, -1 per link if over 2
if ($totalLinks > 2) {
$flags = $flags + $totalLinks;
} else {
$flags = $flags - 1;
}
// How long is the body
// +2 if more then 20 chars and no links, -1 if less then 20
if ($length >= 20 && $totalLinks <= 0) {
$flags = $flags - 1;
} else if ($length >= 20 && $totalLinks == 1) {
++$flags;
} else if ($length < 20) {
$flags = $flags + 2;
}
// Keyword search
$blacklistKeywords = $this->Setting->find('first', array('conditions' => array('name' => 'blacklist')));
$blacklistKeywords = unserialize($blacklistKeywords['Setting']['description']);
foreach ($blacklistKeywords as $keyword) {
if (stripos($content, $keyword) !== false) {
$flags = $flags + substr_count(strtolower($content), $keyword);
}
}
$blacklistWords = array('.html', '.info', '?', '&', '.de', '.pl', '.cn');
foreach ($links as $link) {
foreach ($blacklistWords as $word) {
if (stripos($link, $word) !== false) {
++$flags;
}
}
foreach ($blacklistKeywords as $keyword) {
if (stripos($link, $keyword) !== false) {
++$flags;
}
}
if (strlen($link) >= 30) {
++$flags;
}
}
// Body starts with...
// -10 flags
$firstWord = substr($content, 0, stripos($content, ' '));
$firstDisallow = array_merge($blacklistKeywords, array('interesting', 'cool', 'sorry'));
if (in_array(strtolower($firstWord), $firstDisallow)) {
$flags = $flags + 10;
}
$manyTimes = $this->Post->find('count', array(
'conditions' => array('Post.content' => $this->data['Post']['content'])
));
// Random character match
// -1 point per 5 consecutive consonants
$consonants = preg_match_all('/[^aAeEiIoOuU\s]{5,}+/i', $content, $matches);
$totalConsonants = count($matches[0]);
if ($totalConsonants > 0) {
$flags = $flags + $totalConsonants;
}
$flags = $flags + $manyTimes;
$this->data['Post']['flags'] = $flags;
if($flags >= $this->Setting->getValue('flag_display_limit')) {
$this->data['Post']['tags'] = '';
}
/**
* Save the Data
*/
if($this->Post->save($this->data)) {
if($type == 'question') {
$this->History->record('asked', $this->Post->id, $this->Auth->user('id'));
}elseif($type == 'answer') {
$this->History->record('answered', $this->Post->id, $this->Auth->user('id'));
}
$user_info = $this->User->find('first', array('conditions' => array('id' => $userId)));
if($type == 'question') {
$this->User->save(array('id' => $userId, 'question_count' => $user_info['User']['question_count'] + 1));
}elseif($type == 'answer') {
$this->User->save(array('id' => $userId, 'answer_count' => $user_info['User']['answer_count'] + 1));
}
$post = $this->data['Post'];
/**
* Hack to normalize data.
* Note this should be added to the Tag Behavior at some point.
* This was but in because the behavior would delete the relations as soon as they put them in.
*/
$this->Post->Behaviors->detach('Tag');
$tags = array(
'id' => $this->Post->id,
'tags' => ''
);
$this->Post->save($tags);
return $post;
} else {
return false;
}
}
/**
* Saves the user data and creates a new user account for them.
*
* @param string $data
* @return void
* @todo this should be moved to the model at some point
*/
public function __userSave($data) {
$data['User']['public_key'] = uniqid();
$data['User']['password'] = $this->Auth->password(uniqid('p'));
$data['User']['joined'] = time();
$data['User']['url_title'] = $this->Post->niceUrl($data['User']['username']);
/**
* Set up cookie data incase they leave the site and the session ends and they have not registered yet
*/
$this->Cookie->write(array('User' => $data['User']));
/**
* Save the data
*/
$this->User->save($data);
$data['User']['id'] = $this->User->id;
return $data;
}
/**
* Allowes the user to view a question.
* If a user tries to view a Post that is a answer type they will be redirected.
*
* @param string $public_key
* @return void
*/
public function view($public_key) {
/**
* Set the Post model to recursive 2 so we can pull back the User's information with each comment.
*/
$this->Post->recursive = 2;
/**
* Change to contains. Limit to just question and comment data, no answers.
*/
$this->Post->unbindModel(
array('hasMany' => array('Answer'))
);
$question = $this->Post->findByPublicKey($public_key);
/*
* Look up the flag limit.
*/
$flag_check = $this->Setting->find(
'first', array(
'conditions' => array(
'name' => 'flag_display_limit'
),
'fields' => array('value'),
'recursive' => -1
)
);
/**
* Check to see if the post is spam or not.
* If so redirect.
*/
if($question['Post']['flags'] >= $flag_check['Setting']['value'] && $this->Setting->repCheck($this->Auth->user('id'), 'rep_edit')) {
$this->Session->setFlash(__('The question you are trying to view no longer exists.',true), 'error');
$this->redirect('/');
}
/**
* Even though Post can return an array of answers through associations
* we cannot order or sort this data as we need to
*/
$this->Answer->recursive = 3;
$answers = $this->Answer->find('all', array(
'conditions' => array(
'Answer.related_id' => $question['Post']['id'],
'Answer.flags <' => $flag_check['Setting']['value']
),
'order' => 'Answer.status DESC'
));
if(!empty($question)) {
$views = array(
'id' => $question['Post']['id'],
'views' => $question['Post']['views'] + 1
);
$this->Post->save($views);
}
if($this->Auth->user('id') && !$this->Setting->repCheck($this->Auth->user('id'), 'rep_edit')) {
$this->set('rep_rights', 'yeah!');
}
$this->set('title_for_layout', $question['Post']['title']);
$this->set('question', $question);
$this->set('answers', $answers);
}
public function edit($public_key) {
$question = $this->Post->findByPublicKey($public_key);
$this->set('title_for_layout', $question['Post']['title']);
$redirect = $question;
if(empty($redirect['Post']['title'])) {
$redirect = $this->Post->findById($redirect['Post']['related_id']);
}
if($question['Post']['user_id'] != $this->Auth->user('id') && !$this->isAdmin($this->Auth->user('id')) && !$this->Setting->repCheck($this->Auth->user('id'), 'rep_edit')) {
$this->Session->setFlash(__('That is not your question to edit, and you need more reputation!',true), 'error');
$this->redirect('/questions/' . $redirect['Post']['public_key'] . '/' . $redirect['Post']['url_title']);
}
if(!empty($question['Post']['title'])) {
$tags = $this->PostTag->find(
'all', array(
'conditions' => array(
'PostTag.post_id' => $question['Post']['id']
)
)
);
$this->Tag->recursive = -1;
foreach($tags as $key => $value) {
$tag_names[$key] = $this->Tag->find(
'first', array(
'conditions' => array(
'Tag.id' => $tags[$key]['PostTag']['tag_id']
),
'fields' => array('Tag.tag')
)
);
if($key == 0) {
$tag_list = $tag_names[$key]['Tag']['tag'];
}else {
$tag_list = $tag_list . ', ' . $tag_names[$key]['Tag']['tag'];
}
}
$this->set('tags', $tag_list);
}
if(!empty($this->data['Post']['tags'])) {
$this->Post->Behaviors->attach('Tag', array('table_label' => 'tags', 'tags_label' => 'tag', 'separator' => ', '));
}
if(!empty($this->data)) {
$this->data['Post']['id'] = $question['Post']['id'];
if(!empty($this->data['Post']['title'])) {
$this->data['Post']['url_title'] = $this->Post->niceUrl($this->data['Post']['title']);
}
$this->data['Post']['last_edited_timestamp'] = time();
if($this->Post->save($this->data)) {
$this->History->record('edited', $this->Post->id, $this->Auth->user('id'));
$this->redirect('/questions/' . $redirect['Post']['public_key'] . '/' . $redirect['Post']['url_title']);
}
} else {
$question['Post']['content'] = $this->Markdownify->parseString($question['Post']['content']);
$this->set('question', $question);
}
}
public function display($type='recent', $page=1) {
$this->set('title_for_layout', ucwords($type) . ' Questions');
$this->Post->recursive = -1;
if(isset($this->passedArgs['type'])) {
$search = $this->passedArgs['search'];
if($search == 'yes') {
$type = array(
'needle' => $this->passedArgs['type']
);
}else {
$type = $this->passedArgs['type'];
}
$page = $this->passedArgs['page'];
}elseif(!empty($this->data['Post'])) {
$type = $this->data['Post'];
$search = 'yes';
}else {
$search = 'no';
}
if($page <= 1) {
$page = 1;
}else{
$previous = $page - 1;
$this->set('previous', $previous);
}
$questions = $this->Post->monsterSearch($type, $page, $search);
$count = $this->Post->monsterSearchCount($type, $search);
if($count['0']['0']['count'] % 15 == 0) {
$end_page = $count['0']['0']['count'] / 15;
}else {
$end_page = floor($count['0']['0']['count'] / 15) + 1;
}
if(($count['0']['0']['count'] - ($page * 15)) > 0) {
$next = $page + 1;
$this->set('next', $next);
}
$keywords = array('hot', 'week', 'month', 'recent', 'solved', 'unanswered');
if(($search == 'no') && (!in_array($type, $keywords))) {
$this->Session->setFlash(__('Invalid search type.',true), 'error');
$this->redirect('/');
}
if(empty($questions)) {
if(isset($type['needle'])) {
$this->Session->setFlash(__('No results for',true) . ' "' . $type['needle'] . '"!', 'error');
}else {
$this->Session->setFlash(__('No results for',true) . ' "' . $type . '"!', 'error');
}
if($this->Post->find('count') > 0) {
$this->redirect('/');
}
}
if($search == 'yes') {
$this->set('type', $type['needle']);
}else {
$this->set('type', $type);
}
$this->set('questions', $questions);
$this->set('end_page', $end_page);
$this->set('current', $page);
$this->set('search', $search);
}
public function miniSearch() {
Configure::write('debug', 0);
$this->autoLayout = false;
$questions = $this->Post->monsterSearch(array('needle' => $_GET['query']), 1, 'yes');
$this->set('questions', $questions);
}
public function markCorrect($public_key) {
$answer = $this->Post->findByPublicKey($public_key);
/**
* Check to make sure the Post is an answer
*/
if($answer['Post']['type'] != 'answer') {
$this->Session->setFlash(__('What are you trying to do?',true), 'error');
$this->redirect('/');
}
$question = $this->Post->findById($answer['Post']['related_id']);
/**
* Check to make sure the logged in user is authorized to edit this Post
*/
if($question['Post']['user_id'] != $this->Auth->user('id')) {
$this->Session->setFlash(__('You are not allowed to edit that.',true));
$this->redirect('/questions/' . $question['Post']['public_key'] . '/' . $question['Post']['url_title']);
}
$rep = $this->User->find(
'first', array(
'conditions' => array(
'User.id' => $answer['Post']['user_id']
),
'fields' => array('User.reputation', 'User.id')
)
);
/**
* Set the Post as correct, and its question as closed.
*/
$quest = array(
'id' => $question['Post']['id'],
'status' => 'closed'
);
$answ = array(
'id' => $answer['Post']['id'],
'status' => 'correct'
);
$user = array(
'User' => array(
'id' => $rep['User']['id'],
'reputation' => $rep['User']['reputation'] + 15
)
);
$this->Post->save($answ);
$this->Post->save($quest);
$this->User->save($user);
$this->redirect('/questions/' . $question['Post']['public_key'] . '/' . $question['Post']['url_title'] . '#a_' . $answer['Post']['public_key']);
}
public function flag($public_key) {
$redirect = $this->Post->correctRedirect($public_key);
if(!$this->Auth->user('id')) {
$this->Session->setFlash(__('You need to be logged in to do that!',true), 'error');
$this->redirect('/questions/' . $redirect['Post']['public_key'] . '/' . $redirect['Post']['url_title']);
}elseif(!$this->Setting->repCheck($this->Auth->user('id'), 'rep_flag')) {
$this->Session->setFlash(__('You need more reputation to do that.',true), 'error');
$this->redirect('/questions/' . $redirect['Post']['public_key'] . '/' . $redirect['Post']['url_title']);
}else{
$flag = $this->Vote->throwFlag($this->Auth->user('id'), $public_key);
if($flag == 'exists') {
$this->Session->setFlash(__('You have already flagged that.',true), 'error');
$this->redirect('/questions/' . $redirect['Post']['public_key'] . '/' . $redirect['Post']['url_title']);
}elseif($flag == 'success') {
$this->Session->setFlash(__('Post flagged.',true), 'error');
$this->redirect('/questions/' . $redirect['Post']['public_key'] . '/' . $redirect['Post']['url_title']);
}
}
}
public function maintenance() {
}
}
?> | mcka1n/study-group-forum | app/controllers/posts_controller.php | PHP | mit | 22,597 |
package game;
import game.ItemWindow.ItemOption;
import java.util.ArrayList;
import org.unbiquitous.uImpala.engine.asset.AssetManager;
import org.unbiquitous.uImpala.engine.asset.Text;
import org.unbiquitous.uImpala.engine.core.GameRenderers;
import org.unbiquitous.uImpala.engine.io.MouseSource;
import org.unbiquitous.uImpala.engine.io.Screen;
import org.unbiquitous.uImpala.util.Corner;
import org.unbiquitous.uImpala.util.observer.Event;
import org.unbiquitous.uImpala.util.observer.Observation;
import org.unbiquitous.uImpala.util.observer.Subject;
public class RecipeWindow extends SelectionWindow {
static final int WINDOW_WIDTH = 13;
static final int WINDOW_HEIGHT = 22;
static final int OPTION_OFFSET_X = 32;
static final int OPTION_OFFSET_Y = 32;
private ArrayList<Recipe> list;
public RecipeWindow(AssetManager assets, String frame, int x, int y, ArrayList<Recipe> list) {
super(assets, frame, x, y, WINDOW_WIDTH, WINDOW_HEIGHT);
mouse.connect(MouseSource.EVENT_BUTTON_DOWN, new Observation(this, "OnButtonDown"));
mouse.connect(MouseSource.EVENT_BUTTON_UP, new Observation(this, "OnButtonUp"));
this.list = list;
for (int i = 0; i < list.size(); ++i) {
Recipe r = list.get(i);
options.add(new RecipeOption(assets, i, i, x + OPTION_OFFSET_X, y + OPTION_OFFSET_Y,
WINDOW_WIDTH * this.frame.getWidth() / 3 - OPTION_OFFSET_X * 2,
(int) (this.frame.getHeight() * 1.0), r));
}
}
@Override
public void Swap(int index1, int index2) {
Option o1 = options.get(index1);
Option o2 = options.get(index2);
Recipe r1 = list.get(o1.originalIndex);
Recipe r2 = list.get(o2.originalIndex);
list.set(o1.originalIndex, r2);
list.set(o2.originalIndex, r1);
o1.index = index2;
o2.index = index1;
options.set(index2, o1);
options.set(index1, o2);
int oindex1 = o1.originalIndex;
o1.originalIndex = o2.originalIndex;
o2.originalIndex = oindex1;
}
public Recipe GetSelectedRecipe() {
if (selected == null) {
return null;
}
else {
return ((RecipeOption) selected).recipe;
}
}
@Override
protected void wakeup(Object... args) {
// TODO Auto-generated method stub
}
@Override
protected void destroy() {
// TODO Auto-generated method stub
}
@Override
public void OnButtonDown(Event event, Subject subject) {
super.OnButtonDown(event, subject);
}
@Override
public void OnButtonUp(Event event, Subject subject) {
super.OnButtonUp(event, subject);
}
private class RecipeOption extends ItemOption {
ArrayList<Text> components;
Recipe recipe;
public RecipeOption(AssetManager assets, int _index, int _originalIndex, int _baseX, int _baseY, int _w,
int _h, Recipe _recipe) {
super(assets, _index, _originalIndex, _baseX, _baseY, _w, _h, false, Item.GetItem(_recipe.itemID), 1, 0);
recipe = _recipe;
System.out.println("Recipe for item " + recipe.itemID + "(" + recipe.components.size() + " components)");
components = new ArrayList<Text>();
for (Integer component : recipe.components) {
Item i = Item.GetItem(component);
components.add(assets.newText("font/seguisb.ttf", i.GetName()));
}
}
@Override
public void Render(GameRenderers renderers, Screen screen) {
super.Render(renderers, screen);
int mx = screen.getMouse().getX();
int my = screen.getMouse().getY();
if (box.IsInside(mx, my)) {
int h = components.get(0).getHeight();
for (int i = 0; i < components.size(); ++i) {
components.get(i).render(screen, mx, my + i * h, Corner.TOP_LEFT);
}
}
}
@Override
public void CheckClick(int x, int y) {
if (box.IsInside(x, y)) {
selected = true;
}
}
}
}
| LBNunes/uRPG | Game/src/main/java/game/RecipeWindow.java | Java | mit | 4,468 |
import datetime
def suffix(d):
return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
def custom_strftime(format, t):
return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))
print "Welcome to GenerateUpdateLines, the nation's favourite automatic update line generator."
start = int(raw_input("Enter initial day number: "))
stop = int(raw_input("Enter final day number: "))
t0 = datetime.date(2018, 3, 24)
for d in range(start, stop+1):
date = t0 + datetime.timedelta(d-1)
print "| "+str(d)+" | "+custom_strftime("%a {S} %B", date)+" | | |"
# from datetime import datetime as dt
#
# def suffix(d):
# return 'th' if 11<=d<=13 else {1:'st',2:'nd',3:'rd'}.get(d%10, 'th')
#
# def custom_strftime(format, t):
# return t.strftime(format).replace('{S}', str(t.day) + suffix(t.day))
#
# print custom_strftime('%B {S}, %Y', dt.now())
| ArthurStart/arthurstart.github.io | GenerateUpdateLines.py | Python | mit | 889 |
require "scss_shorthand/version"
require "scss_shorthand/railtie"
| mustangostang/scss-shorthand | lib/scss_shorthand.rb | Ruby | mit | 66 |
/*
* Copyright (c) 2014 Jose Carlos Lama. www.typedom.org
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the \"Software\"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
* OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* The {{#crossLink "Ol"}}{{/crossLink}} Defines an ordered list
*
* @class Ol
* @extends Container
* @constructor
**/
class Ol extends Container<Ol, HTMLOListElement>
{
public static OL: string = 'ol';
constructor();
constructor(id: string)
constructor(attributes: Object)
constructor(element: HTMLOListElement)
constructor(idOrAttributesOrElement?: any) {
super(idOrAttributesOrElement, Ol.OL);
}
} | xLama/TypeDOM | src/ClassByTag/Specific/Ol.ts | TypeScript | mit | 1,491 |
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { IGuest } from '../../core';
@Component({
selector: 'wd-guest-form',
styles: [require('./guest-form.css').toString()],
template: require('./guest-form.html')
})
export class GuestFormComponent {
@Input() title: string;
@Input() guest: IGuest;
@Input() submitting: boolean;
@Output() submitForm: EventEmitter<any> = new EventEmitter();
@Output() cancel: EventEmitter<any> = new EventEmitter();
constructor() {
}
}
| eddedd88/wedding | src/app/components/guest-form/guest-form.component.ts | TypeScript | mit | 516 |
#!/usr/bin/python
import praw
import re
import os
import pickle
from array import *
import random
#REPLY = "I want all the bacon and eggs you have."
REPLY = array('i',["I want all the bacon and eggs you have", "I know what I'm about son", "I'm not interested in caring about people", "Is this not rap?"])
if not os.path.isfile("inigo_config.txt"):
print "You must create the file swanson_config.txt with the pickled credentials."
exit(1)
else:
print "Loading credentials"
user_data = pickle.load( open("swanson_config.txt","rb"))
#print user_data
user_agent = ("Swanson bot 0.1 created by /u/dcooper2.")
r = praw.Reddit(user_agent=user_agent)
r.login(user_data[0], user_data[1])
del user_data
print "Successfully logged in"
# Check for previous replies
if not os.path.isfile("replies.txt"):
replies = []
else:
print "Loading previous reply ids"
with open("replies.txt", "r") as f:
replies = f.read()
replies = replies.split("\n")
replies = filter(None, replies)
# Check for new items to reply to
subreddit = r.get_subreddit('umw_cpsc470Z')
print "Checking for new posts"
for submission in subreddit.get_hot(limit=10):
print "Checking submission ", submission.id
if submission.id not in replies:
if re.search("Ron Swanson", submission.title, re.IGNORECASE) or re.search("Ron Swanson", submission.selftext, re.IGNORECASE):
x = random.randint(0,3)
submission.add_comment(REPLY[x])
print "Bot replying to submission: ", submission.id
replies.append(submission.id)
print "Checking comments"
flat_comments = praw.helpers.flatten_tree(submission.comments)
for comment in flat_comments:
if comment.id not in replies:
if re.search("Ron Swanson", comment.body, re.IGNORECASE):
y = random.randint(0,3)
print "Bot replying to comment: ", comment.id
comment.reply(REPLY[y])
replies.append(comment.id)
# Save new replies
print "Saving ids to file"
with open("replies.txt", "w") as f:
for i in replies:
f.write(i + "\n")
| dcooper2/Swanson_Bot | swanson_bot.py | Python | mit | 2,143 |
// Copyright (C) 2000 Per M.A. Bothner.
// This is free software; for terms and warranty disclaimer see ../../COPYING.
package kawa.standard;
import gnu.expr.*;
import gnu.lists.*;
import gnu.mapping.*;
import gnu.kawa.io.InPort;
import gnu.kawa.lispexpr.*;
import kawa.lang.*;
import java.io.File;
public class define_autoload extends Syntax
{
public static final define_autoload define_autoload
= new define_autoload("define-autoload", false);
public static final define_autoload define_autoloads_from_file
= new define_autoload("define-autoloads-from-file", true);
boolean fromFile;
public define_autoload (String name, boolean fromFile)
{
super(name);
this.fromFile = fromFile;
}
@Override
public boolean scanForDefinitions (Pair st, ScopeExp defs, Translator tr)
{
if (! (st.getCdr() instanceof Pair))
return super.scanForDefinitions(st, defs, tr);
Pair p = (Pair) st.getCdr();
if (fromFile)
{
for (;;)
{
/* #ifdef use:java.lang.CharSequence */
if (! (p.getCar() instanceof CharSequence))
break;
/* #else */
// if (! (p.getCar() instanceof String || p.getCar() instanceof CharSeq))
// break;
/* #endif */
if (! scanFile(p.getCar().toString(), defs, tr))
return false;
Object rest = p.getCdr();
if (rest == LList.Empty)
return true;
if (! (rest instanceof Pair))
break;
p = (Pair) p.getCdr();
}
tr.syntaxError("invalid syntax for define-autoloads-from-file");
return false;
}
Object names = p.getCar();
Object filename = null;
if (p.getCdr() instanceof Pair)
{
p = (Pair) p.getCdr();
filename = p.getCar();
return process(names, filename, defs, tr);
}
tr.syntaxError("invalid syntax for define-autoload");
return false;
}
public boolean scanFile(String filespec, ScopeExp defs, Translator tr)
{
if (filespec.endsWith(".el"))
;
File file = new File(filespec);
if (! file.isAbsolute())
file = new File(new File(tr.getFileName()).getParent(), filespec);
String filename = file.getPath();
int dot = filename.lastIndexOf('.');
Language language;
if (dot >= 0)
{
String extension = filename.substring(dot);
language = Language.getInstance(extension);
if (language == null)
{
tr.syntaxError("unknown extension for "+filename);
return true;
}
gnu.text.Lexer lexer;
/*
// Since (module-name ...) is not handled in this pass,
// we won't see it until its too late. FIXME.
ModuleExp module = tr.getModule();
String prefix = module == null ? null : module.getName();
System.err.println("module:"+module);
if (prefix == null)
prefix = kawa.repl.compilationPrefix;
else
{
int i = prefix.lastIndexOf('.');
if (i < 0)
prefix = null;
else
prefix = prefix.substring(0, i+1);
}
*/
String prefix = tr.classPrefix;
int extlen = extension.length();
int speclen = filespec.length();
String cname = filespec.substring(0, speclen - extlen);
while (cname.startsWith("../"))
{
int i = prefix.lastIndexOf('.', prefix.length() - 2);
if (i < 0)
{
tr.syntaxError("cannot use relative filename \"" + filespec
+ "\" with simple prefix \"" + prefix + "\"");
return false;
}
prefix = prefix.substring(0, i+1);
cname = cname.substring(3);
}
String classname = (prefix + cname).replace('/', '.');
try
{
InPort port = InPort.openFile(filename);
lexer = language.getLexer(port, tr.getMessages());
findAutoloadComments((LispReader) lexer, classname, defs, tr);
}
catch (Exception ex)
{
tr.syntaxError("error reading "+filename+": "+ex);
return true;
}
}
return true;
}
public static void findAutoloadComments (LispReader in, String filename,
ScopeExp defs, Translator tr)
throws java.io.IOException, gnu.text.SyntaxException
{
boolean lineStart = true;
String magic = ";;;###autoload";
int magicLength = magic.length();
mainLoop:
for (;;)
{
int ch = in.peek();
if (ch < 0)
return;
if (ch == '\n' || ch == '\r')
{
in.read();
lineStart = true;
continue;
}
if (lineStart && ch == ';')
{
int i = 0;
for (;;)
{
if (i == magicLength)
break;
ch = in.read();
if (ch < 0)
return;
if (ch == '\n' || ch == '\r')
{
lineStart = true;
continue mainLoop;
}
if (i < 0 || ch == magic.charAt(i++))
continue;
i = -1; // No match.
}
if (i > 0)
{
Object form = in.readObject();
if (form instanceof Pair)
{
Pair pair = (Pair) form;
Object value = null;
String name = null;
Object car = pair.getCar();
String command
= car instanceof String ? car.toString()
: car instanceof Symbol ? ((Symbol) car).getName()
: null;
if (command == "defun")
{
name = ((Pair)pair.getCdr()).getCar().toString();
value = new AutoloadProcedure(name, filename,
tr.getLanguage());
}
else
tr.error('w', "unsupported ;;;###autoload followed by: "
+ pair.getCar());
if (value != null)
{
Declaration decl = defs.getDefine(name, tr);
Expression ex = new QuoteExp(value);
decl.setFlag(Declaration.IS_CONSTANT);
decl.noteValue(ex);
}
}
lineStart = false;
continue;
}
}
lineStart = false;
in.skip();
if (ch == '#')
{
if (in.peek() == '|')
{
in.skip();
in.readNestedComment('#', '|');
continue;
}
}
if (Character.isWhitespace ((char)ch))
;
else
{
Object skipped = in.readObject(ch);
if (skipped == Sequence.eofValue)
return;
}
}
}
public static boolean process(Object names, Object filename,
ScopeExp defs, Translator tr)
{
if (names instanceof Pair)
{
Pair p = (Pair) names;
return (process(p.getCar(), filename, defs, tr)
&& process(p.getCdr(), filename, defs, tr));
}
if (names == LList.Empty)
return true;
String fn;
int len;
/*
if (names == "*" && filename instanceof String
&& (len = (fn = (String) filename).length()) > 2
&& fn.charAt(0) == '<' && fn.charAt(len-1) == '>')
{
fn = fn.substring(1, len-1);
try
{
Class fclass = Class.forName(fn);
Object instance = require.find(ctype, env);
...;
}
catch (ClassNotFoundException ex)
{
tr.syntaxError("class <"+fn+"> not found");
return false;
}
}
*/
if (names instanceof String || names instanceof Symbol)
{
String name = names.toString();
Declaration decl = defs.getDefine(name, tr);
if (filename instanceof SimpleSymbol
&& (len = (fn = filename.toString()).length()) > 2
&& fn.charAt(0) == '<' && fn.charAt(len-1) == '>')
filename = fn.substring(1, len-1);
Object value = new AutoloadProcedure(name, filename.toString(),
tr.getLanguage());
Expression ex = new QuoteExp(value);
decl.setFlag(Declaration.IS_CONSTANT);
decl.noteValue(ex);
return true;
}
return false;
}
public Expression rewriteForm (Pair form, Translator tr)
{
return null;
}
}
| maoueh/kawa-fork | kawa/standard/define_autoload.java | Java | mit | 7,247 |
<?php
/**
* This file has been @generated by a phing task from CLDR version 31.0.1.
* See [README.md](README.md#generating-data) for more information.
*
* @internal Please do not require this file directly.
* It may change location/format between versions
*
* Do not modify this file directly!
*/
return array (
'AD' => 'Andoora',
'AE' => 'Laaraw Imaarawey Margantey',
'AF' => 'Afgaanistan',
'AG' => 'Antigua nda Barbuuda',
'AI' => 'Angiiya',
'AL' => 'Albaani',
'AM' => 'Armeeni',
'AO' => 'Angoola',
'AR' => 'Argentine',
'AS' => 'Ameriki Samoa',
'AT' => 'Otriši',
'AU' => 'Ostraali',
'AW' => 'Aruuba',
'AZ' => 'Azerbaayijaŋ',
'BA' => 'Bosni nda Herzegovine',
'BB' => 'Barbaados',
'BD' => 'Bangladeši',
'BE' => 'Belgiiki',
'BF' => 'Burkina faso',
'BG' => 'Bulgaari',
'BH' => 'Bahareen',
'BI' => 'Burundi',
'BJ' => 'Beniŋ',
'BM' => 'Bermuda',
'BN' => 'Bruunee',
'BO' => 'Boolivi',
'BR' => 'Breezil',
'BS' => 'Bahamas',
'BT' => 'Buutaŋ',
'BW' => 'Botswaana',
'BY' => 'Biloriši',
'BZ' => 'Beliizi',
'CA' => 'Kanaada',
'CD' => 'Kongoo demookaratiki laboo',
'CF' => 'Centraafriki koyra',
'CG' => 'Kongoo',
'CH' => 'Swisu',
'CI' => 'Kudwar',
'CK' => 'Kuuk gungey',
'CL' => 'Šiili',
'CM' => 'Kameruun',
'CN' => 'Šiin',
'CO' => 'Kolombi',
'CR' => 'Kosta rika',
'CU' => 'Kuuba',
'CV' => 'Kapuver gungey',
'CY' => 'Šiipur',
'CZ' => 'Cek labo',
'DE' => 'Almaaɲe',
'DJ' => 'Jibuuti',
'DK' => 'Danemark',
'DO' => 'Doominiki laboo',
'DZ' => 'Alžeeri',
'EC' => 'Ekwateer',
'EE' => 'Estooni',
'EG' => 'Misra',
'ER' => 'Eritree',
'ES' => 'Espaaɲe',
'ET' => 'Ecioopi',
'FI' => 'Finlandu',
'FJ' => 'Fiji',
'FK' => 'Kalkan gungey',
'FM' => 'Mikronezi',
'FR' => 'Faransi',
'GA' => 'Gaabon',
'GB' => 'Albaasalaama Marganta',
'GD' => 'Grenaada',
'GE' => 'Gorgi',
'GF' => 'Faransi Guyaan',
'GH' => 'Gaana',
'GI' => 'Gibraltar',
'GL' => 'Grinland',
'GM' => 'Gambi',
'GN' => 'Gine',
'GP' => 'Gwadeluup',
'GQ' => 'Ginee Ekwatorial',
'GR' => 'Greece',
'GT' => 'Gwatemaala',
'GU' => 'Guam',
'GW' => 'Gine-Bisso',
'GY' => 'Guyaane',
'HN' => 'Honduras',
'HR' => 'Krwaasi',
'HT' => 'Haiti',
'HU' => 'Hungaari',
'ID' => 'Indoneezi',
'IE' => 'Irlandu',
'IL' => 'Israyel',
'IN' => 'Indu laboo',
'IO' => 'Britiši Indu teekoo laama',
'IQ' => 'Iraak',
'IR' => 'Iraan',
'IS' => 'Ayseland',
'IT' => 'Itaali',
'JM' => 'Jamaayik',
'JO' => 'Urdun',
'JP' => 'Jaapoŋ',
'KE' => 'Keeniya',
'KG' => 'Kyrgyzstan',
'KH' => 'kamboogi',
'KI' => 'Kiribaati',
'KM' => 'Komoor',
'KN' => 'Seŋ Kitts nda Nevis',
'KP' => 'Gurma Kooree',
'KR' => 'Hawsa Kooree',
'KW' => 'Kuweet',
'KY' => 'Kayman gungey',
'KZ' => 'Kaazakstan',
'LA' => 'Laawos',
'LB' => 'Lubnaan',
'LC' => 'Seŋ Lussia',
'LI' => 'Liechtenstein',
'LK' => 'Srilanka',
'LR' => 'Liberia',
'LS' => 'Leesoto',
'LT' => 'Lituaani',
'LU' => 'Luxembourg',
'LV' => 'Letooni',
'LY' => 'Liibi',
'MA' => 'Maarok',
'MC' => 'Monako',
'MD' => 'Moldovi',
'MG' => 'Madagascar',
'MH' => 'Maršal gungey',
'MK' => 'Maacedooni',
'ML' => 'Maali',
'MM' => 'Maynamar',
'MN' => 'Mongooli',
'MP' => 'Mariana Gurma Gungey',
'MQ' => 'Martiniiki',
'MR' => 'Mooritaani',
'MS' => 'Montserrat',
'MT' => 'Malta',
'MU' => 'Mooris gungey',
'MV' => 'Maldiivu',
'MW' => 'Malaawi',
'MX' => 'Mexiki',
'MY' => 'Maleezi',
'MZ' => 'Mozambik',
'NA' => 'Naamibi',
'NC' => 'Kaaledooni Taagaa',
'NE' => 'Nižer',
'NF' => 'Norfolk Gungoo',
'NG' => 'Naajiriia',
'NI' => 'Nikaragwa',
'NL' => 'Hollandu',
'NO' => 'Norveej',
'NP' => 'Neepal',
'NR' => 'Nauru',
'NU' => 'Niue',
'NZ' => 'Zeelandu Taaga',
'OM' => 'Omaan',
'PA' => 'Panama',
'PE' => 'Peeru',
'PF' => 'Faransi Polineezi',
'PG' => 'Papua Ginee Taaga',
'PH' => 'Filipine',
'PK' => 'Paakistan',
'PL' => 'Poloɲe',
'PM' => 'Seŋ Piyer nda Mikelon',
'PN' => 'Pitikarin',
'PR' => 'Porto Riko',
'PS' => 'Palestine Dangay nda Gaaza',
'PT' => 'Portugaal',
'PW' => 'Palu',
'PY' => 'Paraguwey',
'QA' => 'Kataar',
'RE' => 'Reenioŋ',
'RO' => 'Rumaani',
'RU' => 'Iriši laboo',
'RW' => 'Rwanda',
'SA' => 'Saudiya',
'SB' => 'Solomon Gungey',
'SC' => 'Seešel',
'SD' => 'Suudaŋ',
'SE' => 'Sweede',
'SG' => 'Singapur',
'SH' => 'Seŋ Helena',
'SI' => 'Sloveeni',
'SK' => 'Slovaaki',
'SL' => 'Seera Leon',
'SM' => 'San Marino',
'SN' => 'Senegal',
'SO' => 'Somaali',
'SR' => 'Surinaam',
'ST' => 'Sao Tome nda Prinsipe',
'SV' => 'Salvador laboo',
'SY' => 'Suuria',
'SZ' => 'Swaziland',
'TC' => 'Turk nda Kayikos Gungey',
'TD' => 'Caadu',
'TG' => 'Togo',
'TH' => 'Taayiland',
'TJ' => 'Taažikistan',
'TK' => 'Tokelau',
'TL' => 'Timoor hawsa',
'TM' => 'Turkmenistaŋ',
'TN' => 'Tunizi',
'TO' => 'Tonga',
'TR' => 'Turki',
'TT' => 'Trinidad nda Tobaago',
'TV' => 'Tuvalu',
'TW' => 'Taayiwan',
'TZ' => 'Tanzaani',
'UA' => 'Ukreen',
'UG' => 'Uganda',
'US' => 'Ameriki Laabu Margantey',
'UY' => 'Uruguwey',
'UZ' => 'Uzbeekistan',
'VA' => 'Vaatikan Laama',
'VC' => 'Seŋvinsaŋ nda Grenadine',
'VE' => 'Veneezuyeela',
'VG' => 'Britiši Virgin gungey',
'VI' => 'Ameerik Virgin Gungey',
'VN' => 'Vietnaam',
'VU' => 'Vanautu',
'WF' => 'Wallis nda Futuna',
'WS' => 'Samoa',
'YE' => 'Yaman',
'YT' => 'Mayooti',
'ZA' => 'Hawsa Afriki Laboo',
'ZM' => 'Zambi',
'ZW' => 'Zimbabwe',
);
| 42php/42php | vendor/Giggsey/Locale/data/dje.php | PHP | mit | 5,534 |
module.exports = middleware;
var states = {
STANDBY: 0,
BUSY: 1
};
function middleware(options) {
var regio = require('regio'),
tessel = require('tessel'),
camera = require('camera-vc0706').use(tessel.port[options.port]),
app = regio.router(),
hwReady = false,
current;
camera.on('ready', function() {
hwReady = true;
current = states.STANDBY;
});
app.get('/', handler);
function handler(req, res) {
if (hwReady) {
if (current === states.STANDBY) {
current = states.BUSY;
camera.takePicture(function (err, image) {
res.set('Content-Type', 'image/jpeg');
res.set('Content-Length', image.length);
res.status(200).end(image);
current = states.STANDBY;
});
} else {
res.set('Retry-After', 100);
res.status(503).end();
}
} else {
res.status(503).end();
}
}
return app;
}
| vstirbu/regio-camera | index.js | JavaScript | mit | 944 |
package api
import (
"errors"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("Error", func() {
Context("Marshalling", func() {
It("will be marshalled correctly with a wrapped error", func() {
apiErr := WrapErr(errors.New("boom!"), 500)
result := []byte(apiErr.HTTPBody())
expected := []byte(`{"errors":[{"status":"500","title":"boom!"}]}`)
Expect(result).To(MatchJSON(expected))
})
It("will be marshalled correctly with one error", func() {
apiErr := &Error{Title: "Bad Request", Status: "400"}
result := []byte(apiErr.HTTPBody())
expected := []byte(`{"errors":[{"status":"400","title":"Bad Request"}]}`)
Expect(result).To(MatchJSON(expected))
})
It("will be marshalled correctly with several errors", func() {
errorOne := &Error{Title: "Bad Request", Status: "400"}
errorTwo := &Error{
ID: "001",
Href: "http://bla/blub",
Status: "500",
Code: "001",
Title: "Title must not be empty",
Detail: "Never occures in real life",
Path: "#titleField",
}
apiErr := errorOne.Add(errorTwo)
result := []byte(apiErr.HTTPBody())
expected := []byte(`{"errors":[
{"status":"400","title":"Bad Request"},
{"id":"001","href":"http://bla/blub","status":"500","code":"001","title":"Title must not be empty","detail":"Never occures in real life","path":"#titleField"}
]}`)
Expect(result).To(MatchJSON(expected))
})
})
})
| olivoil/api.v2 | error_test.go | GO | mit | 1,444 |
import { gql } from '@apollo/client'
import fullBlockShareFragment from 'v2/components/FullBlock/components/FullBlockShare/fragments/fullBlockShare'
export default gql`
fragment FullBlockActions on Konnectable {
__typename
... on Image {
find_original_url
downloadable_image: resized_image_url(downloadable: true)
}
... on Text {
find_original_url
}
... on ConnectableInterface {
source {
title
url
}
}
... on Block {
can {
mute
potentially_edit_thumbnail
edit_thumbnail
}
}
...FullBlockShare
}
${fullBlockShareFragment}
`
| aredotna/ervell | src/v2/components/FullBlock/components/FullBlockActions/fragments/fullBlockActions.ts | TypeScript | mit | 653 |
'use strict';
var ObjectUtil, self;
module.exports = ObjectUtil = function () {
self = this;
};
/**
* @method promiseWhile
* @reference http://blog.victorquinn.com/javascript-promise-while-loop
*/
ObjectUtil.prototype.promiseWhile = function () {
};
| IyadAssaf/portfol.io | app/util/object.js | JavaScript | mit | 261 |
var assert = require('chai').assert;
var Pad = require('../lib/pad');
describe('Pad', function() {
it('should be an object', function() {
var pad = new Pad();
assert.isObject(pad);
});
it('should have a x coordinate of 310 by default', function() {
var terminator = new Pad();
assert.equal(terminator.x, 310);
});
it('should have a y coordinate of 470 by default', function() {
var jon = new Pad();
assert.equal(jon.y, 470);
});
it('should have a r value of 23 by default', function() {
var terminator = new Pad();
assert.equal(terminator.r, 23);
});
it('should have a sAngle value of 0 by default', function() {
var jon = new Pad();
assert.equal(jon.sAngle, 0);
});
it('should have an eAngle value of 2*Math.PI by default', function() {
var jon = new Pad();
assert.equal(jon.eAngle, 2*Math.PI);
});
it('should have a draw function', function(){
var jon = new Pad();
assert.isFunction(jon.draw);
});
});
| jonwille/Frogger | test/pad-test.js | JavaScript | mit | 995 |
<?php
class Db{
//member variables
private static $_con = null,
$_driver = "sqlsrv",
$_host = "localhost",
$_user = "arsan",
$_pass = "a1254n",
$_db = "APDPLN",
$_error = false;
//established connection to the database
private function setConnection(){
try{
self::$_con = new PDO(self::$_driver.":Server=".self::$_host.";database=".self::$_db,self::$_user,self::$_pass);
//self::$_con = new PDO("mysql:host=".self::$_host.";dbname=".self::$_db,self::$_user,self::$_pass);
// set the PDO error mode to exception
self::$_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $e){
die("PDOException {$e}");
}
}
/*
* Return the connection variable if connection is established
* else
* make a new connection then return the connection variable
* */
public static function getConnection(){
//established connection
if(self::$_con == null){
self::setConnection();
}
return self::$_con;
}
//unset connection
public static function unsetConnection(){
self::$_con = null;
}
//set error
private function setError($value = true){
self::$_error = $value;
}
//get error
public static function getError(){
return self::$_error;
}
//query method with bind functionality
private static function query($sql,$bindPrams = array()){
//get connection
$con = self::getConnection();
//set error to false
self::setError(false); //no error
//check sql is not empty
if(empty($sql))
die("Invalid Sql Query");
$stmt = $con->prepare($sql);
//bind params
$i = 1;
foreach($bindPrams as $params){
$stmt->bindValue($i,$params);
$i++;
}
//set the error
if($stmt->execute() == true)
self::setError(false);
else
self::setError(true);
return $stmt; //return PDO statement
}
//insert method
public static function insert($tableName,$value = array()){
//make KEYS && Values to bind
$valueKey = array_keys($value); //get keys of $value
$keyString = "";
$bindString = "";
$i = 1;
foreach($valueKey as $key){
$keyString .= "`".$key."`";
$bindString .= "?";
//if we are not on the last element
if($i < count($valueKey)){
$keyString .= ", ";
$bindString .= ",";
}
$i++;
}
//execulte the query
self::query("INSERT INTO `{$tableName}` ({$keyString}) VALUES({$bindString})",array_values($value));
return self::getError(); //return the error bolean value set the query method
}
//update method
public static function update($tableName,$update = array(),$where = array()){
$updateKeys = array_keys($update);
$updateString = "";
$i = 1;
foreach($updateKeys as $updateKey){
$updateString .= $updateKey." = ?";
//check if we are not on the last element of the array
if($i < count($updateKeys)){
$updateString .= " , ";
}
$i++;
}
//generate where clause
if(count($where) < 3){
die("Invalid Where clause");
}
$whereString = "";
foreach($where as $whr) {
$whereString .= $whr;
}
self::query("UPDATE `{$tableName}` SET {$updateString} WHERE {$whereString}",array_values($update));
return self::getError();
}
//delete method
public static function delete($tableName,$whereArray = array()){
//check table name
if(empty($tableName))
die("Empty Table name");
if(count($whereArray) < 3)
die("Invalid where clause");
//generate where clause
$whereString = "";
foreach($whereArray as $where){
$whereString .= $where;
}
self::query("DELETE FROM {$tableName} WHERE {$whereString}",array());
return self::getError();
}
//fetch method
public static function fetch($tableName,$whereArray = array(),$operator){
if(empty($tableName))
die("Enter table name");
if( ($whereArray=="") && ($operator=="") ) {
$stmt = self::query("SELECT * FROM {$tableName}");
}
else {
//check operator is valid
$validOperator = array("=", "!=", ">", "<", ">=", "<=");
if (!in_array($operator, $validOperator))
die("Invalid Operator");
if (count($whereArray) != 1)
die("Invalid Where Array");
//generate where string
$whereString = "";
foreach (array_keys($whereArray) as $where) {
$whereString .= $where;
}
$whereString .= $operator . "?";
echo $whereString;
exit;
//execute the query
$stmt = self::query("SELECT * FROM {$tableName} WHERE {$whereString}", array_values($whereArray));
}
if(self::getError() == false){ //no error
return $stmt->fetch(PDO::FETCH_NUM);
}else{
return self::getError(); //return true (means their is a error)
}
}
} | arsan-irianto/apdpln | library/Db.php | PHP | mit | 5,580 |
using PoppertechCalculator.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PoppertechCalculator.Processors
{
public class ForecastGraphCalculations : IForecastGraphCalculations
{
private const decimal _leftTail = 10;
private const decimal _rightTail = 10;
private static decimal _normal = 100 - _leftTail - _rightTail;
private static decimal _leftNormal, _rightNormal;
private static decimal _xMin, _xWorst, _xLikely, _xBest, _xMax;
private static decimal _hWorst, _hLikely, _hBest;
private static decimal _m1, _m2, _m3, _m4;
private static decimal _b1, _b2, _b3, _b4;
public IEnumerable<SimulationContext> GetSimulationContext(Forecast forecast)
{
_xMin = forecast.Minimum;
_xWorst = forecast.Worst;
_xLikely = forecast.Likely;
_xBest = forecast.Best;
_xMax = forecast.Maximum;
_hWorst = CalculateWorstCaseHeight();
_hBest = CalculateBestCaseHeight();
_hLikely = CalculateMostLikelyHeight();
_leftNormal = CalculateLeftNormal();
_rightNormal = CalculateRightNormal();
_m1 = CalculateSlope1();
_m2 = CalculateSlope2();
_m3 = CalculateSlope3();
_m4 = CalculateSlope4();
_b1 = CalculateIntercept1();
_b2 = CalculateIntercept2();
_b3 = CalculateIntercept3();
_b4 = CalculateIntercept4();
var context1 = new SimulationContext() { XLower = _xMin, AreaLower = 0, Intercept = _b1, Slope = _m1 };
var context2 = new SimulationContext() { XLower = _xWorst, AreaLower = _leftTail, Intercept = _b2, Slope = _m2 };
var context3 = new SimulationContext() { XLower = _xLikely, AreaLower = _leftTail + _leftNormal, Intercept = _b3, Slope = _m3 };
var context4 = new SimulationContext() { XLower = _xBest, AreaLower = _leftTail + _normal, Intercept = _b4, Slope = _m4 };
var context5 = new SimulationContext() { XLower = _xMax };
return new[] { context1, context2, context3, context4, context5 };
}
private static decimal CalculateWorstCaseHeight()
{
return 2 * _leftTail / (_xWorst - _xMin);
}
private static decimal CalculateBestCaseHeight()
{
return 2 * _rightTail / (_xMax - _xBest);
}
private static decimal CalculateMostLikelyHeight()
{
return (2 * _normal - _hWorst * (_xLikely - _xWorst) - _hBest * (_xBest - _xLikely)) / (_xBest - _xWorst);
}
private static decimal CalculateLeftNormal()
{
return (_hWorst + _hLikely) * (_xLikely - _xWorst) / 2;
}
private static decimal CalculateRightNormal()
{
return (_hLikely + _hBest) * (_xBest - _xLikely) / 2;
}
private static decimal CalculateSlope1()
{
return _hWorst / (_xWorst - _xMin);
}
private static decimal CalculateSlope2()
{
return (_hLikely - _hWorst) / (_xLikely - _xWorst);
}
private static decimal CalculateSlope3()
{
return (_hBest - _hLikely) / (_xBest - _xLikely);
}
private static decimal CalculateSlope4()
{
return -_hBest / (_xMax - _xBest);
}
private static decimal CalculateIntercept1()
{
return _hWorst - (_m1 * _xWorst);
}
private static decimal CalculateIntercept2()
{
return _hLikely - (_m2 * _xLikely);
}
private static decimal CalculateIntercept3()
{
return _hLikely - (_m3 * _xLikely);
}
private static decimal CalculateIntercept4()
{
return _hBest - (_m4 * _xBest);
}
}
} | poppertech/Goal-based-Calculator | PoppertechCalculator/Logic/Processors/ForecastGraph/ForecastGraphCalculations.cs | C# | mit | 3,987 |
module Conratewebshop
class ProductsController < ApplicationController
helper Btemplater::ApplicationHelper
helper Btemplater::IndexHelper
helper Btemplater::ShowHelper
helper Btemplater::NewHelper
helper Btemplater::EditHelper
include Btemplater::Tools
def show
@obj = Conratewebshop::Product.find(params[:id])
end
def new
@obj = Conratewebshop::Product.new
@obj.category_id = params[:category_id]
end
def create
do_create(params, Conratewebshop::Product, conratewebshop.category_path(params[:category_id]))
end
def edit
@obj = Conratewebshop::Product.find(params[:id])
end
def update
do_update(params, Conratewebshop::Product, conratewebshop.category_path(params[:category_id]))
end
# def before_save_create(obj)
# obj.category_id = params[:category_id]
# end
def destroy
do_destroy(params, Conratewebshop::Product, conratewebshop.category_path(params[:category_id]))
end
end
end
| muskovicsnet/conrate | vendor/engines/webshop/app/controllers/conratewebshop/products_controller.rb | Ruby | mit | 1,021 |
package space.harbour.l111.ehcache;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
/**
* Created by tully.
*/
public class EhcacheHelper {
static final int MAX_ENTRIES = 10;
static final int LIFE_TIME_SEC = 1;
static final int IDLE_TIME_SEC = 1;
static Cache createLifeCache(CacheManager manager, String name) {
CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES);
configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)
.timeToLiveSeconds(LIFE_TIME_SEC);
Cache cache = new Cache(configuration);
manager.addCache(cache);
return cache;
}
static Cache createIdleCache(CacheManager manager, String name) {
CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES);
configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)
.timeToIdleSeconds(IDLE_TIME_SEC);
Cache cache = new Cache(configuration);
manager.addCache(cache);
return cache;
}
static Cache createEternalCache(CacheManager manager, String name) {
CacheConfiguration configuration = new CacheConfiguration(name, MAX_ENTRIES);
configuration.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)
.eternal(true);
Cache cache = new Cache(configuration);
manager.addCache(cache);
return cache;
}
}
| vitaly-chibrikov/harbour_java_2017_05 | L11.1/src/main/java/space/harbour/l111/ehcache/EhcacheHelper.java | Java | mit | 1,571 |
#include "Image.h"
// to avoid compiler confusion, python.hpp must be include before Halide headers
#include <boost/format.hpp>
#include <boost/python.hpp>
#define USE_NUMPY
#ifdef USE_NUMPY
#ifdef USE_BOOST_NUMPY
#include <boost/numpy.hpp>
#else
// we use Halide::numpy
#include "../numpy/numpy.hpp"
#endif
#endif // USE_NUMPY
#include <boost/cstdint.hpp>
#include <boost/functional/hash/hash.hpp>
#include <boost/mpl/list.hpp>
#include "../../src/runtime/HalideBuffer.h"
#include "Func.h"
#include "Type.h"
#include <functional>
#include <string>
#include <unordered_map>
#include <vector>
namespace h = Halide;
namespace p = boost::python;
#ifdef USE_NUMPY
#ifdef USE_BOOST_NUMPY
namespace bn = boost::numpy;
#else
namespace bn = Halide::numpy;
#endif
#endif // USE_NUMPY
template <typename Ret, typename T, typename... Args>
Ret buffer_call_operator(h::Buffer<T> &that, Args... args) {
return that(args...);
}
template <typename T>
h::Expr buffer_call_operator_tuple(h::Buffer<T> &that, p::tuple &args_passed) {
std::vector<h::Expr> expr_args;
for (ssize_t i = 0; i < p::len(args_passed); i++) {
expr_args.push_back(p::extract<h::Expr>(args_passed[i]));
}
return that(expr_args);
}
template <typename T>
T buffer_to_setitem_operator0(h::Buffer<T> &that, int x, T value) {
return that(x) = value;
}
template <typename T>
T buffer_to_setitem_operator1(h::Buffer<T> &that, int x, int y, T value) {
return that(x, y) = value;
}
template <typename T>
T buffer_to_setitem_operator2(h::Buffer<T> &that, int x, int y, int z, T value) {
return that(x, y, z) = value;
}
template <typename T>
T buffer_to_setitem_operator3(h::Buffer<T> &that, int x, int y, int z, int w, T value) {
return that(x, y, z, w) = value;
}
template <typename T>
T buffer_to_setitem_operator4(h::Buffer<T> &that, p::tuple &args_passed, T value) {
std::vector<int> int_args;
const size_t args_len = p::len(args_passed);
for (size_t i = 0; i < args_len; i += 1) {
p::object o = args_passed[i];
p::extract<int> int32_extract(o);
if (int32_extract.check()) {
int_args.push_back(int32_extract());
}
}
if (int_args.size() != args_len) {
for (size_t j = 0; j < args_len; j += 1) {
p::object o = args_passed[j];
const std::string o_str = p::extract<std::string>(p::str(o));
printf("buffer_to_setitem_operator4 args_passed[%lu] == %s\n", j, o_str.c_str());
}
throw std::invalid_argument("buffer_to_setitem_operator4 only handles "
"a tuple of (convertible to) int.");
}
switch (int_args.size()) {
case 1:
return that(int_args[0]) = value;
case 2:
return that(int_args[0], int_args[1]) = value;
case 3:
return that(int_args[0], int_args[1], int_args[2]) = value;
case 4:
return that(int_args[0], int_args[1], int_args[2], int_args[3]) = value;
default:
printf("buffer_to_setitem_operator4 receive a tuple with %zu integers\n", int_args.size());
throw std::invalid_argument("buffer_to_setitem_operator4 only handles 1 to 4 dimensional tuples");
}
return 0; // this line should never be reached
}
template <typename T>
const T *buffer_data(const h::Buffer<T> &buffer) {
return buffer.data();
}
template <typename T>
void buffer_set_min1(h::Buffer<T> &im, int m0) {
im.set_min(m0);
}
template <typename T>
void buffer_set_min2(h::Buffer<T> &im, int m0, int m1) {
im.set_min(m0, m1);
}
template <typename T>
void buffer_set_min3(h::Buffer<T> &im, int m0, int m1, int m2) {
im.set_min(m0, m1, m2);
}
template <typename T>
void buffer_set_min4(h::Buffer<T> &im, int m0, int m1, int m2, int m3) {
im.set_min(m0, m1, m2, m3);
}
template <typename T>
std::string buffer_repr(const h::Buffer<T> &buffer) {
std::string repr;
h::Type t = halide_type_of<T>();
std::string suffix = "_???";
if (t.is_float()) {
suffix = "_float";
} else if (t.is_int()) {
suffix = "_int";
} else if (t.is_uint()) {
suffix = "_uint";
} else if (t.is_bool()) {
suffix = "_bool";
} else if (t.is_handle()) {
suffix = "_handle";
}
boost::format f("<halide.Buffer%s%i; element_size %i bytes; "
"extent (%i %i %i %i); min (%i %i %i %i); stride (%i %i %i %i)>");
repr = boost::str(f % suffix % t.bits() % t.bytes() % buffer.extent(0) % buffer.extent(1) % buffer.extent(2) % buffer.extent(3) % buffer.min(0) % buffer.min(1) % buffer.min(2) % buffer.min(3) % buffer.stride(0) % buffer.stride(1) % buffer.stride(2) % buffer.stride(3));
return repr;
}
template <typename T>
boost::python::object get_type_function_wrapper() {
std::function<h::Type(h::Buffer<T> &)> return_type_func =
[&](h::Buffer<T> &that) -> h::Type { return halide_type_of<T>(); };
auto call_policies = p::default_call_policies();
typedef boost::mpl::vector<h::Type, h::Buffer<T> &> func_sig;
return p::make_function(return_type_func, call_policies, p::arg("self"), func_sig());
}
template <typename T>
void buffer_copy_to_host(h::Buffer<T> &im) {
im.copy_to_host();
}
template <typename T>
void defineBuffer_impl(const std::string suffix, const h::Type type) {
using h::Buffer;
using h::Expr;
auto buffer_class =
p::class_<Buffer<T>>(
("Buffer" + suffix).c_str(),
"A reference-counted handle on a dense multidimensional array "
"containing scalar values of type T. Can be directly accessed and "
"modified. May have up to four dimensions. Color images are "
"represented as three-dimensional, with the third dimension being "
"the color channel. In general we store color images in "
"color-planes, as opposed to packed RGB, because this tends to "
"vectorize more cleanly.",
p::init<>(p::arg("self"), "Construct an undefined buffer handle"));
// Constructors
buffer_class
.def(p::init<int>(
p::args("self", "x"),
"Allocate an buffer with the given dimensions."))
.def(p::init<int, int>(
p::args("self", "x", "y"),
"Allocate an buffer with the given dimensions."))
.def(p::init<int, int, int>(
p::args("self", "x", "y", "z"),
"Allocate an buffer with the given dimensions."))
.def(p::init<int, int, int, int>(
p::args("self", "x", "y", "z", "w"),
"Allocate an buffer with the given dimensions."))
.def(p::init<h::Realization &>(
p::args("self", "r"),
"Wrap a single-element realization in an Buffer object."))
.def(p::init<buffer_t>(
p::args("self", "b"),
"Wrap a buffer_t in an Buffer object, so that we can access its pixels."));
buffer_class
.def("__repr__", &buffer_repr<T>, p::arg("self"));
buffer_class
.def("data", &buffer_data<T>, p::arg("self"),
p::return_value_policy<p::return_opaque_pointer>(), // not sure this will do what we want
"Get a pointer to the element at the min location.")
.def("copy_to_host", &buffer_copy_to_host<T>, p::arg("self"),
"Manually copy-back data to the host, if it's on a device. ")
.def("set_host_dirty", &Buffer<T>::set_host_dirty,
(p::arg("self"), p::arg("dirty") = true),
"Mark the buffer as dirty-on-host. ")
.def("type", get_type_function_wrapper<T>(),
"Return Type instance for the data type of the buffer.")
.def("channels", &Buffer<T>::channels, p::arg("self"),
"Get the extent of dimension 2, which by convention we use as"
"the number of color channels (often 3). Unlike extent(2), "
"returns one if the buffer has fewer than three dimensions.")
.def("dimensions", &Buffer<T>::dimensions, p::arg("self"),
"Get the dimensionality of the data. Typically two for grayscale images, and three for color images.")
.def("stride", &Buffer<T>::stride, p::args("self", "dim"),
"Get the number of elements in the buffer between two adjacent "
"elements in the given dimension. For example, the stride in "
"dimension 0 is usually 1, and the stride in dimension 1 is "
"usually the extent of dimension 0. This is not necessarily true though.")
.def("extent", &Buffer<T>::extent, p::args("self", "dim"),
"Get the size of a dimension.")
.def("min", &Buffer<T>::min, p::args("self", "dim"),
"Get the min coordinate of a dimension. The top left of the "
"buffer represents this point in a function that was realized "
"into this buffer.");
buffer_class
.def("set_min", &buffer_set_min1<T>,
p::args("self", "m0"),
"Set the coordinates corresponding to the host pointer.")
.def("set_min", &buffer_set_min2<T>,
p::args("self", "m0", "m1"),
"Set the coordinates corresponding to the host pointer.")
.def("set_min", &buffer_set_min3<T>,
p::args("self", "m0", "m1", "m2"),
"Set the coordinates corresponding to the host pointer.")
.def("set_min", &buffer_set_min4<T>,
p::args("self", "m0", "m1", "m2", "m3"),
"Set the coordinates corresponding to the host pointer.");
buffer_class
.def("width", &Buffer<T>::width, p::arg("self"),
"Get the extent of dimension 0, which by convention we use as "
"the width of the image. Unlike extent(0), returns one if the "
"buffer is zero-dimensional.")
.def("height", &Buffer<T>::height, p::arg("self"),
"Get the extent of dimension 1, which by convention we use as "
"the height of the image. Unlike extent(1), returns one if the "
"buffer has fewer than two dimensions.")
.def("left", &Buffer<T>::left, p::arg("self"),
"Get the minimum coordinate in dimension 0, which by convention "
"is the coordinate of the left edge of the image. Returns zero "
"for zero-dimensional images.")
.def("right", &Buffer<T>::right, p::arg("self"),
"Get the maximum coordinate in dimension 0, which by convention "
"is the coordinate of the right edge of the image. Returns zero "
"for zero-dimensional images.")
.def("top", &Buffer<T>::top, p::arg("self"),
"Get the minimum coordinate in dimension 1, which by convention "
"is the top of the image. Returns zero for zero- or "
"one-dimensional images.")
.def("bottom", &Buffer<T>::bottom, p::arg("self"),
"Get the maximum coordinate in dimension 1, which by convention "
"is the bottom of the image. Returns zero for zero- or "
"one-dimensional images.");
const char *get_item_doc =
"Construct an expression which loads from this buffer. ";
// Access operators (to Expr, and to actual value)
buffer_class
.def("__getitem__", &buffer_call_operator<Expr, T, Expr>,
p::args("self", "x"),
get_item_doc);
buffer_class
.def("__getitem__", &buffer_call_operator<Expr, T, Expr, Expr>,
p::args("self", "x", "y"),
get_item_doc);
buffer_class
.def("__getitem__", &buffer_call_operator<Expr, T, Expr, Expr, Expr>,
p::args("self", "x", "y", "z"),
get_item_doc)
.def("__getitem__", &buffer_call_operator<Expr, T, Expr, Expr, Expr, Expr>,
p::args("self", "x", "y", "z", "w"),
get_item_doc)
.def("__getitem__", &buffer_call_operator_tuple<T>,
p::args("self", "tuple"),
get_item_doc)
// Note that we return copy values (not references like in the C++ API)
.def("__getitem__", &buffer_call_operator<T, T>,
p::arg("self"),
"Assuming this buffer is zero-dimensional, get its value")
.def("__call__", &buffer_call_operator<T, T, int>,
p::args("self", "x"),
"Assuming this buffer is one-dimensional, get the value of the element at position x")
.def("__call__", &buffer_call_operator<T, T, int, int>,
p::args("self", "x", "y"),
"Assuming this buffer is two-dimensional, get the value of the element at position (x, y)")
.def("__call__", &buffer_call_operator<T, T, int, int, int>,
p::args("self", "x", "y", "z"),
"Assuming this buffer is three-dimensional, get the value of the element at position (x, y, z)")
.def("__call__", &buffer_call_operator<T, T, int, int, int, int>,
p::args("self", "x", "y", "z", "w"),
"Assuming this buffer is four-dimensional, get the value of the element at position (x, y, z, w)")
.def("__setitem__", &buffer_to_setitem_operator0<T>, p::args("self", "x", "value"),
"Assuming this buffer is one-dimensional, set the value of the element at position x")
.def("__setitem__", &buffer_to_setitem_operator1<T>, p::args("self", "x", "y", "value"),
"Assuming this buffer is two-dimensional, set the value of the element at position (x, y)")
.def("__setitem__", &buffer_to_setitem_operator2<T>, p::args("self", "x", "y", "z", "value"),
"Assuming this buffer is three-dimensional, set the value of the element at position (x, y, z)")
.def("__setitem__", &buffer_to_setitem_operator3<T>, p::args("self", "x", "y", "z", "w", "value"),
"Assuming this buffer is four-dimensional, set the value of the element at position (x, y, z, w)")
.def("__setitem__", &buffer_to_setitem_operator4<T>, p::args("self", "tuple", "value"),
"Assuming this buffer is one to four-dimensional, "
"set the value of the element at position indicated by tuple (x, y, z, w)");
p::implicitly_convertible<Buffer<T>, h::Argument>();
return;
}
p::object buffer_to_python_object(const h::Buffer<> &im) {
PyObject *obj = nullptr;
if (im.type() == h::UInt(8)) {
p::manage_new_object::apply<h::Buffer<uint8_t> *>::type converter;
obj = converter(new h::Buffer<uint8_t>(im));
} else if (im.type() == h::UInt(16)) {
p::manage_new_object::apply<h::Buffer<uint16_t> *>::type converter;
obj = converter(new h::Buffer<uint16_t>(im));
} else if (im.type() == h::UInt(32)) {
p::manage_new_object::apply<h::Buffer<uint32_t> *>::type converter;
obj = converter(new h::Buffer<uint32_t>(im));
} else if (im.type() == h::Int(8)) {
p::manage_new_object::apply<h::Buffer<int8_t> *>::type converter;
obj = converter(new h::Buffer<int8_t>(im));
} else if (im.type() == h::Int(16)) {
p::manage_new_object::apply<h::Buffer<int16_t> *>::type converter;
obj = converter(new h::Buffer<int16_t>(im));
} else if (im.type() == h::Int(32)) {
p::manage_new_object::apply<h::Buffer<int32_t> *>::type converter;
obj = converter(new h::Buffer<int32_t>(im));
} else if (im.type() == h::Float(32)) {
p::manage_new_object::apply<h::Buffer<float> *>::type converter;
obj = converter(new h::Buffer<float>(im));
} else if (im.type() == h::Float(64)) {
p::manage_new_object::apply<h::Buffer<double> *>::type converter;
obj = converter(new h::Buffer<double>(im));
} else {
throw std::invalid_argument("buffer_to_python_object received an Buffer of unsupported type.");
}
return p::object(p::handle<>(obj));
}
h::Buffer<> python_object_to_buffer(p::object obj) {
p::extract<h::Buffer<uint8_t>> buffer_extract_uint8(obj);
p::extract<h::Buffer<uint16_t>> buffer_extract_uint16(obj);
p::extract<h::Buffer<uint32_t>> buffer_extract_uint32(obj);
p::extract<h::Buffer<int8_t>> buffer_extract_int8(obj);
p::extract<h::Buffer<int16_t>> buffer_extract_int16(obj);
p::extract<h::Buffer<int32_t>> buffer_extract_int32(obj);
p::extract<h::Buffer<float>> buffer_extract_float(obj);
p::extract<h::Buffer<double>> buffer_extract_double(obj);
if (buffer_extract_uint8.check()) {
return buffer_extract_uint8();
} else if (buffer_extract_uint16.check()) {
return buffer_extract_uint16();
} else if (buffer_extract_uint32.check()) {
return buffer_extract_uint32();
} else if (buffer_extract_int8.check()) {
return buffer_extract_int8();
} else if (buffer_extract_int16.check()) {
return buffer_extract_int16();
} else if (buffer_extract_int32.check()) {
return buffer_extract_int32();
} else if (buffer_extract_float.check()) {
return buffer_extract_float();
} else if (buffer_extract_double.check()) {
return buffer_extract_double();
} else {
throw std::invalid_argument("python_object_to_buffer received an object that is not an Buffer<T>");
}
return h::Buffer<>();
}
#ifdef USE_NUMPY
bn::dtype type_to_dtype(const h::Type &t) {
if (t == h::UInt(8)) return bn::dtype::get_builtin<uint8_t>();
if (t == h::UInt(16)) return bn::dtype::get_builtin<uint16_t>();
if (t == h::UInt(32)) return bn::dtype::get_builtin<uint32_t>();
if (t == h::Int(8)) return bn::dtype::get_builtin<int8_t>();
if (t == h::Int(16)) return bn::dtype::get_builtin<int16_t>();
if (t == h::Int(32)) return bn::dtype::get_builtin<int32_t>();
if (t == h::Float(32)) return bn::dtype::get_builtin<float>();
if (t == h::Float(64)) return bn::dtype::get_builtin<double>();
throw std::runtime_error("type_to_dtype received a Halide::Type with no known numpy dtype equivalent");
return bn::dtype::get_builtin<uint8_t>();
}
h::Type dtype_to_type(const bn::dtype &t) {
if (t == bn::dtype::get_builtin<uint8_t>()) return h::UInt(8);
if (t == bn::dtype::get_builtin<uint16_t>()) return h::UInt(16);
if (t == bn::dtype::get_builtin<uint32_t>()) return h::UInt(32);
if (t == bn::dtype::get_builtin<int8_t>()) return h::Int(8);
if (t == bn::dtype::get_builtin<int16_t>()) return h::Int(16);
if (t == bn::dtype::get_builtin<int32_t>()) return h::Int(32);
if (t == bn::dtype::get_builtin<float>()) return h::Float(32);
if (t == bn::dtype::get_builtin<double>()) return h::Float(64);
throw std::runtime_error("dtype_to_type received a numpy type with no known Halide type equivalent");
return h::Type();
}
/// Will create a Halide::Buffer object pointing to the array data
p::object ndarray_to_buffer(bn::ndarray &array) {
h::Type t = dtype_to_type(array.get_dtype());
const int dims = array.get_nd();
void *host = reinterpret_cast<void *>(array.get_data());
halide_dimension_t shape[dims];
for (int i = 0; i < dims; i++) {
shape[i].min = 0;
shape[i].extent = array.shape(i);
shape[i].stride = array.strides(i) / t.bytes();
}
return buffer_to_python_object(h::Buffer<>(t, host, dims, shape));
}
bn::ndarray buffer_to_ndarray(p::object buffer_object) {
h::Buffer<> im = python_object_to_buffer(buffer_object);
user_assert(im.data() != nullptr)
<< "buffer_to_ndarray received an buffer without host data";
std::vector<int32_t> extent(im.dimensions()), stride(im.dimensions());
for (int i = 0; i < im.dimensions(); i++) {
extent[i] = im.dim(i).extent();
stride[i] = im.dim(i).stride() * im.type().bytes();
}
return bn::from_data(
im.host_ptr(),
type_to_dtype(im.type()),
extent,
stride,
buffer_object);
}
#endif
struct BufferFactory {
template <typename T, typename... Args>
static p::object create_buffer_object(Args... args) {
typedef h::Buffer<T> BufferType;
typedef typename p::manage_new_object::apply<BufferType *>::type converter_t;
converter_t converter;
PyObject *obj = converter(new BufferType(args...));
return p::object(p::handle<>(obj));
}
template <typename... Args>
static p::object create_buffer_impl(h::Type t, Args... args) {
if (t == h::UInt(8)) return create_buffer_object<uint8_t>(args...);
if (t == h::UInt(16)) return create_buffer_object<uint16_t>(args...);
if (t == h::UInt(32)) return create_buffer_object<uint32_t>(args...);
if (t == h::Int(8)) return create_buffer_object<int8_t>(args...);
if (t == h::Int(16)) return create_buffer_object<int16_t>(args...);
if (t == h::Int(32)) return create_buffer_object<int32_t>(args...);
if (t == h::Float(32)) return create_buffer_object<float>(args...);
if (t == h::Float(64)) return create_buffer_object<double>(args...);
throw std::invalid_argument("BufferFactory::create_buffer_impl received type not handled");
return p::object();
}
static p::object create_buffer0(h::Type type) {
return create_buffer_impl(type);
}
static p::object create_buffer1(h::Type type, int x) {
return create_buffer_impl(type, x);
}
static p::object create_buffer2(h::Type type, int x, int y) {
return create_buffer_impl(type, x, y);
}
static p::object create_buffer3(h::Type type, int x, int y, int z) {
return create_buffer_impl(type, x, y, z);
}
static p::object create_buffer4(h::Type type, int x, int y, int z, int w) {
return create_buffer_impl(type, x, y, z, w);
}
static p::object create_buffer_from_realization(h::Type type, h::Realization &r) {
return create_buffer_impl(type, r);
}
static p::object create_buffer_from_buffer(h::Type type, buffer_t b) {
return create_buffer_impl(type, b);
}
};
void defineBuffer() {
defineBuffer_impl<uint8_t>("_uint8", h::UInt(8));
defineBuffer_impl<uint16_t>("_uint16", h::UInt(16));
defineBuffer_impl<uint32_t>("_uint32", h::UInt(32));
defineBuffer_impl<int8_t>("_int8", h::Int(8));
defineBuffer_impl<int16_t>("_int16", h::Int(16));
defineBuffer_impl<int32_t>("_int32", h::Int(32));
defineBuffer_impl<float>("_float32", h::Float(32));
defineBuffer_impl<double>("_float64", h::Float(64));
// "Buffer" will look as a class, but instead it will be simply a factory method
p::def("Buffer", &BufferFactory::create_buffer0,
p::args("type"),
"Construct a zero-dimensional buffer of type T");
p::def("Buffer", &BufferFactory::create_buffer1,
p::args("type", "x"),
"Construct a one-dimensional buffer of type T");
p::def("Buffer", &BufferFactory::create_buffer2,
p::args("type", "x", "y"),
"Construct a two-dimensional buffer of type T");
p::def("Buffer", &BufferFactory::create_buffer3,
p::args("type", "x", "y", "z"),
"Construct a three-dimensional buffer of type T");
p::def("Buffer", &BufferFactory::create_buffer4,
p::args("type", "x", "y", "z", "w"),
"Construct a four-dimensional buffer of type T");
p::def("Buffer", &BufferFactory::create_buffer_from_realization,
p::args("type", "r"),
p::with_custodian_and_ward_postcall<0, 2>(), // the realization reference count is increased
"Wrap a single-element realization in an Buffer object of type T.");
p::def("Buffer", &BufferFactory::create_buffer_from_buffer,
p::args("type", "b"),
p::with_custodian_and_ward_postcall<0, 2>(), // the buffer_t reference count is increased
"Wrap a buffer_t in an Buffer object of type T, so that we can access its pixels.");
#ifdef USE_NUMPY
bn::initialize();
p::def("ndarray_to_buffer", &ndarray_to_buffer,
p::args("array"),
p::with_custodian_and_ward_postcall<0, 1>(), // the array reference count is increased
"Converts a numpy array into a Halide::Buffer."
"Will take into account the array size, dimensions, and type."
"Created Buffer refers to the array data (no copy).");
p::def("Buffer", &ndarray_to_buffer,
p::args("array"),
p::with_custodian_and_ward_postcall<0, 1>(), // the array reference count is increased
"Wrap numpy array in a Halide::Buffer."
"Will take into account the array size, dimensions, and type."
"Created Buffer refers to the array data (no copy).");
p::def("buffer_to_ndarray", &buffer_to_ndarray,
p::args("buffer"),
p::with_custodian_and_ward_postcall<0, 1>(), // the buffer reference count is increased
"Creates a numpy array from a Halide::Buffer."
"Will take into account the Buffer size, dimensions, and type."
"Created ndarray refers to the Buffer data (no copy).");
#endif
return;
}
| ronen/Halide | python_bindings/python/Image.cpp | C++ | mit | 25,082 |
version https://git-lfs.github.com/spec/v1
oid sha256:fd2ad8a08df37f7b13dad35da22197faf51ef6887162bf5f74ce30df59fdba0f
size 15638
| yogeshsaroya/new-cdnjs | ajax/libs/deck.js/1.0.0/core/deck.core.js | JavaScript | mit | 130 |
module Kakin
class Configuration
def self.tenant
@@_tenant
end
def self.setup
config = {
'auth_url' => ENV['OS_AUTH_URL'],
'tenant' => ENV['OS_TENANT_NAME'] || ENV['OS_PROJECT_NAME'],
'username' => ENV['OS_USERNAME'],
'password' => ENV['OS_PASSWORD'],
'client_cert' => ENV['OS_CERT'],
'client_key' => ENV['OS_KEY'],
'identity_api_version' => ENV['OS_IDENTITY_API_VERSION'],
'user_domain_name' => ENV['OS_USER_DOMAIN_NAME'],
'project_domain_name' => ENV['OS_PROJECT_DOMAIN_NAME'],
'timeout' => ENV['YAO_TIMEOUT'],
'management_url' => ENV['YAO_MANAGEMENT_URL'],
'debug' => ENV['YAO_DEBUG'] || false,
}
file_path = File.expand_path('~/.kakin')
if File.exist?(file_path)
yaml = YAML.load_file(file_path)
config.merge!(yaml)
end
@@_tenant = config['tenant']
Yao.configure do
auth_url config['auth_url']
tenant_name config['tenant']
username config['username']
password config['password']
timeout config['timeout'].to_i if config['timeout']
client_cert config['client_cert'] if config['client_cert']
client_key config['client_key'] if config['client_key']
identity_api_version config['identity_api_version'] if config['identity_api_version']
user_domain_name config['user_domain_name'] if config['user_domain_name']
project_domain_name config['project_domain_name'] if config['project_domain_name']
debug config['debug']
end
end
end
end
| buty4649/kakin | lib/kakin/configuration.rb | Ruby | mit | 1,718 |
const R = require('ramda');
const {thread} = require('davis-shared').fp;
const DataLoader = require('dataloader');
const Task = require('data.task');
const Async = require('control.async')(Task);
const when = require('when');
const task2Promise = Async.toPromise(when.promise);
module.exports = (entityRepository, entityTypes) => thread(entityTypes,
R.map(entityType => ([
entityType,
new DataLoader(ids => task2Promise(
entityRepository.queryById(entityType, ids).map(entities => {
const indexedEntities = R.indexBy(R.prop('id'), entities);
return ids.map(R.propOr(null, R.__, indexedEntities));
})))])),
R.fromPairs);
| thedavisproject/davis-web | src/resolvers/entityLoaderFactory.js | JavaScript | mit | 661 |
<?php
if(isset($_GET['pemail']))
{
$pemail=$_GET['pemail'];
}
else
{
$pemail = '';
}
//echo $pemail;
//exit;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Diesel Subscribe</title>
<link href="<?=base_url();?>css/newsletter.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="<?=base_url();?>css/MyFontsWebfontsKit.min.css"/>
<style>
body{background:none;overflow: hidden!important;}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["email", "postcode", "fname", "lname", "male", "female"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
postcode = $("#postcode");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "REQUIRED";
emailerror = "ENTER VALID EMAIL ADDRESS";
posterror = "INVALID POSTCODE";
$("form").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val("");
input.attr("placeholder", emptyerror);
/*if( input.attr("type") == "password" ) {
input.attr("placeholder", passwerror );
}*/
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val("");
email.attr("placeholder", emailerror);
}
if (!/^\d{4}$/.test(postcode.val())){
postcode.addClass("needsfilled");
postcode.val("");
postcode.attr("placeholder", posterror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
});
</script>
<style type="text/css">.fancybox-overlay{background:rgba(0, 0, 0, 0.70); }</style>
</head>
<body>
<div class="main-popup">
<div class="images-left">
<img src="<?=base_url();?>images/newsletter-new.png" />
</div>
<div id="signup">
<?php if(isset($msg) && $msg != '') {
if($msg == 'Newsletter Successfully Subscribed!!') { ?>
<!-- success -->
<div class="heading-newsletter subscribe-new">thanks for joining <br /> diesel tribe</div>
<table border="0" cellspacing="0" cellpadding="0" style="width:100%">
<tr>
<td width="50%"></td><td width="50%"></td>
</tr>
<tr>
<td width="100%" colspan="2"><p class="text1 subscribe-text1">Check your inbox for an email to <br />confirm your subscription. </p></td>
</tr>
<tr>
<td width="100%" colspan="2"><p class="text1">Your <b>15% OFF</b> code will be <br /> emailed to you following.</p></td>
</tr>
</table>
<?php } elseif ($msg == 'You are already subscribed') { ?>
<!-- subscribe -->
<div class="heading-newsletter subscribe-new">you clearly have style!</div>
<table border="0" cellspacing="0" cellpadding="0" style="width:100%">
<tr>
<td width="50%"></td><td width="50%"></td>
</tr>
<tr>
<td width="100%" colspan="2"><p class="text1 subscribe-text1"> You’re already subscribed <br /> to Diesel Tribe.</p></td>
</tr>
<tr>
<td width="100%" colspan="2"><p class="text1">Keep an eye on your <br /> inbox for more style news <br /> and offers shortly</p></td>
</tr>
</table>
<?php } else { ?>
<!-- fail -->
<p class="success"><?=$msg?><br></p>
<?php } ?>
<?php } else { ?>
<form id="form1" method="post" action="<?=base_url();?>newsletter/signupprocess" name="form1">
<center>
<input type="hidden" name="Testform hidden" value="1" />
<div class="heading-newsletter">LIVE MORE SUCCESSFULLY</div>
<table border="0" cellspacing="0" cellpadding="0" style="width:100%">
<tr>
<td width="50%"></td><td width="50%"></td>
</tr>
<tr>
<td width="100%" colspan="2"><p class="text1">Join the Diesel Tribe and <br /> get <b>15% off</b> your first purchase online.</p></td>
</tr>
<tr>
<td colspan="2"><p class="ftxtarea name-txt"><span class="txt_field"><input placeholder="EMAIL ADDRESS" onfocus="this.placeholder = ''" onblur="this.placeholder = 'EMAIL ADDRESS'" name="email" id="email" type="text" value="<?=$pemail?>" style="width:99%;margin:0 auto;text-align:center;" /></span></p></td>
</tr>
<tr>
<td><p class="ftxtarea name-txt"><span class="txt_field"><input placeholder="FIRST NAME" onfocus="this.placeholder = ''" onblur="this.placeholder = 'FIRST NAME'" name="fname" id="fname" type="text" value="<?=$pemail?>" style="width: 95%;float: left;text-align:center;" /></span></p></td>
<td><p class="ftxtarea name-txt"><span class="txt_field"><input placeholder="LAST NAME" onfocus="this.placeholder = ''" onblur="this.placeholder = 'LAST NAME'" name="lname" id="lname" type="text" value="<?=$pemail?>" style="width: 95%;float: right;text-align:center;" /></span></p></td>
</tr>
<tr>
<td><p class="ftxtarea radiotext-m"><input placeholder="MALE" name="gender" id="male" type="radio" value="Male" style="" checked="checked" /> <label class="txt_field radio_txt" for="male">MALE</label></p></td>
<td><p class="ftxtarea radiotext-f"><input placeholder="FEMALE" name="gender" id="female" type="radio" value="Female" style="" /> <label class="txt_field radio_txt" for="female">FEMALE</label></p></td>
</tr>
<tr>
<td colspan="2">
<div class="main-fields">
<p class="ftxtarea ftext1"><span class="txt_field"><input placeholder="POSTCODE" onfocus="this.placeholder = ''" onblur="this.placeholder = 'POSTCODE'" name="postcode" id="postcode" type="text" value="<?php /*?><?=$postcode?><?php */?>" maxlength="4" style=" width: 191px;text-align: center;" /></span></p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="Submit" value="SUBSCRIBE" class="subscribe-newsignup" />
</td>
</tr>
<tr>
<td colspan="2">
<a href="<?=base_url();?>info/policy" class="info-a" target="_blank">information on privacy</a>
</td>
</tr>
</table>
</center>
</form>
<?php } ?>
</div>
</div> <!-- ------------- main popup ------------- -->
</body>
</html>
| sygcom/diesel_2016 | application/views/newsletter/signup_view-06-12-2016.php | PHP | mit | 7,492 |
'use strict';
var spawn = require('child_process').spawn;
var font2svg = require('../');
var fs = require('graceful-fs');
var noop = require('nop');
var rimraf = require('rimraf');
var test = require('tape');
var xml2js = require('xml2js');
var parseXML = xml2js.parseString;
var fontPath = 'test/SourceHanSansJP-Normal.otf';
var fontBuffer = fs.readFileSync(fontPath);
var pkg = require('../package.json');
rimraf.sync('test/tmp');
test('font2svg()', function(t) {
t.plan(22);
font2svg(fontBuffer, {include: 'Hello,☆世界★(^_^)b!'}, function(err, buf) {
t.error(err, 'should create a font buffer when `include` option is a string.');
parseXML(buf.toString(), function(err, result) {
t.error(err, 'should create a valid SVG buffer.');
var glyphs = result.svg.font[0].glyph;
var unicodes = glyphs.map(function(glyph) {
return glyph.$.unicode;
});
t.deepEqual(
unicodes, [
String.fromCharCode('57344'),
'!', '(', ')', ',', 'H', '^', '_', 'b', 'e', 'l', 'o', '★', '☆', '世', '界'
], 'should create glyphs including private use area automatically.'
);
t.strictEqual(glyphs[0].$.d, undefined, 'should place `.notdef` at the first glyph');
});
});
font2svg(fontBuffer, {
include: ['\u0000', '\ufffe', '\uffff'],
encoding: 'utf8'
}, function(err, str) {
t.error(err, 'should create a font buffer when `include` option is an array.');
parseXML(str, function(err, result) {
t.error(err, 'should create a valid SVG string when the encoding is utf8.');
var glyphs = result.svg.font[0].glyph;
t.equal(glyphs.length, 1, 'should ignore glyphs which are not included in CMap.');
});
});
font2svg(fontBuffer, {encoding: 'base64'}, function(err, str) {
t.error(err, 'should create a font buffer even if `include` option is not specified.');
parseXML(new Buffer(str, 'base64').toString(), function(err, result) {
t.error(err, 'should encode the result according to `encoding` option.');
t.equal(
result.svg.font[0].glyph.length, 1,
'should create a SVG including at least one glyph.'
);
});
});
font2svg(fontBuffer, null, function(err) {
t.error(err, 'should not throw errors even if `include` option is falsy value.');
});
font2svg(fontBuffer, {include: 1}, function(err) {
t.error(err, 'should not throw errors even if `include` option is not an array or a string.');
});
font2svg(fontBuffer, {include: 'a', maxBuffer: 1}, function(err) {
t.equal(err.message, 'stdout maxBuffer exceeded.', 'should pass an error of child_process.');
});
font2svg(fontBuffer, {
include: 'foo',
fontFaceAttr: {
'font-weight': 'bold',
'underline-position': '-100'
}
}, function(err, buf) {
t.error(err, 'should accept `fontFaceAttr` option.');
parseXML(buf.toString(), function(err, result) {
t.error(err, 'should create a valid SVG buffer when `fontFaceAttr` option is enabled.');
var fontFace = result.svg.font[0]['font-face'][0];
t.equal(
fontFace.$['font-weight'], 'bold',
'should change the property of the `font-face` element, using `fontFaceAttr` option.'
);
t.equal(
fontFace.$['underline-position'], '-100',
'should change the property of the `font-face` element, using `fontFaceAttr` option.'
);
});
});
t.throws(
font2svg.bind(null, new Buffer('foo'), noop), /out/,
'should throw an error when the buffer doesn\'t represent a font.'
);
t.throws(
font2svg.bind(null, 'foo', {include: 'a'}, noop), /is not a buffer/,
'should throw an error when the first argument is not a buffer.'
);
t.throws(
font2svg.bind(null, fontBuffer, {include: 'a'}, [noop]), /TypeError/,
'should throw a type error when the last argument is not a function.'
);
t.throws(
font2svg.bind(null, fontBuffer, {fontFaceAttr: 'bold'}, noop), /TypeError/,
'should throw a type error when the `fontFaceAttr` is not an object.'
);
t.throws(
font2svg.bind(null, fontBuffer, {
fontFaceAttr: {foo: 'bar'}
}, noop), /foo is not a valid attribute name/,
'should throw an error when the `fontFaceAttr` has an invalid property..'
);
});
test('"font2svg" command inside a TTY context', function(t) {
t.plan(20);
var cmd = function(args) {
var tmpCp = spawn('node', [pkg.bin].concat(args), {
stdio: [process.stdin, null, null]
});
tmpCp.stdout.setEncoding('utf8');
tmpCp.stderr.setEncoding('utf8');
return tmpCp;
};
cmd([fontPath])
.stdout.on('data', function(data) {
t.ok(/<\/svg>/.test(data), 'should print font data to stdout.');
});
cmd([fontPath, 'test/tmp/foo.svg']).on('close', function() {
fs.exists('test/tmp/foo.svg', function(result) {
t.ok(result, 'should create a font file.');
});
});
cmd([fontPath, '--include', 'abc'])
.stdout.on('data', function(data) {
t.ok(/<\/svg>/.test(data), 'should accept --include flag.');
});
cmd([fontPath, '--in', '123'])
.stdout.on('data', function(data) {
t.ok(/<\/svg>/.test(data), 'should use --in flag as an alias of --include.');
});
cmd([fontPath, '-i', 'あ'])
.stdout.on('data', function(data) {
t.ok(/<\/svg>/.test(data), 'should use -i flag as an alias of --include.');
});
cmd([fontPath, '-g', '亜'])
.stdout.on('data', function(data) {
t.ok(/<\/svg>/.test(data), 'should use -g flag as an alias of --include.');
});
cmd([fontPath, '--font-weight', 'bold'])
.stdout.on('data', function(data) {
t.ok(
/font-weight="bold"/.test(data),
'should set the property of font-face element, using property name flag.'
);
});
cmd(['--help'])
.stdout.on('data', function(data) {
t.ok(/Usage/.test(data), 'should print usage information with --help flag.');
});
cmd(['-h'])
.stdout.on('data', function(data) {
t.ok(/Usage/.test(data), 'should use -h flag as an alias of --help.');
});
cmd(['--version'])
.stdout.on('data', function(data) {
t.equal(data, pkg.version + '\n', 'should print version with --version flag.');
});
cmd(['-v'])
.stdout.on('data', function(data) {
t.equal(data, pkg.version + '\n', 'should use -v as an alias of --version.');
});
cmd([])
.stdout.on('data', function(data) {
t.ok(/Usage/.test(data), 'should print usage information when it takes no arguments.');
});
var unsupportedErr = '';
cmd(['cli.js'])
.on('close', function(code) {
t.notEqual(code, 0, 'should fail when it cannot parse the input.');
t.ok(
/Unsupported/.test(unsupportedErr),
'should print `Unsupported OpenType` error message to stderr.'
);
})
.stderr.on('data', function(data) {
unsupportedErr += data;
});
var invalidAttrErr = '';
cmd([fontPath, '--font-eight', 'bold', '--font-smile'])
.on('close', function(code) {
t.notEqual(code, 0, 'should fail when it takes invalid flags.');
t.ok(
/font-eight is not a valid attribute name/.test(invalidAttrErr),
'should print `invalid attribute` error message to stderr.'
);
})
.stderr.on('data', function(data) {
invalidAttrErr += data;
});
var enoentErr = '';
cmd(['foo'])
.on('close', function(code) {
t.notEqual(code, 0, 'should fail when the file doesn\'t exist.');
t.ok(/ENOENT/.test(enoentErr), 'should print ENOENT error message to stderr.');
})
.stderr.on('data', function(data) {
enoentErr += data;
});
var eisdirErr = '';
cmd([fontPath, 'node_modules'])
.on('close', function(code) {
t.notEqual(code, 0, 'should fail when a directory exists in the destination path.');
t.ok(/EISDIR/.test(eisdirErr), 'should print EISDIR error message to stderr.');
})
.stderr.on('data', function(data) {
eisdirErr += data;
});
});
test('"font2svg" command outside a TTY context', function(t) {
t.plan(4);
var cmd = function(args) {
var tmpCp = spawn('node', [pkg.bin].concat(args), {
stdio: ['pipe', null, null]
});
tmpCp.stdout.setEncoding('utf8');
tmpCp.stderr.setEncoding('utf8');
return tmpCp;
};
var cp = cmd([]);
cp.stdout.on('data', function(data) {
t.ok(/<\/svg>/.test(data), 'should parse stdin and print SVG data.');
});
cp.stdin.end(fontBuffer);
cmd(['test/tmp/bar.svg', '--include', 'ア'])
.on('close', function() {
fs.exists('test/tmp/bar.svg', function(result) {
t.ok(result, 'should write a SVG file.');
});
})
.stdin.end(fontBuffer);
var err = '';
var cpErr = cmd([]);
cpErr.on('close', function(code) {
t.notEqual(code, 0, 'should fail when stdin receives unsupported file buffer.');
t.ok(
/Unsupported/.test(err),
'should print an error when stdin receives unsupported file buffer.'
);
});
cpErr.stderr.on('data', function(output) {
err += output;
});
cpErr.stdin.end(new Buffer('invalid data'));
});
| shinnn/node-font2svg | test/test.js | JavaScript | mit | 9,142 |
<?php
/**
* This file is part of Terminalor.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* Terminalor core application class responsible for managing user defined
* commands.
*
* @package Terminalor
* @subpackage Application
* @author Bernard Baltrusaitis <bernard@runawaylover.info>
* @link http://terminalor.runawaylover.info
*/
class Terminalor_Application extends Terminalor_Application_Abstract
{
/**
* Check if command with given name exists
*
* @param string $offset user defined command name
* @return boolean
*/
public function offsetExists($offset)
{
return array_key_exists($offset, $this->_commands);
}
/**
* Get command's body by given name
*
* @param string $offset command name
* @return Closure command body
*/
public function offsetGet($offset)
{
try {
if ($this->offsetExists($offset)) {
$command = $this->_commands[$offset];
return $command;
} else {
throw new InvalidArgumentException(
sprintf('Can\'t execute `%s` command. It doesn\'t exists.', $offset));
}
} catch (InvalidArgumentException $e) {
$this->getResponse()->message($e->getMessage(), 'error');
}
}
/**
* Register new command
* <code>
* $terminalor['command_name'] = function(Terminalor_Application_Interface $terminalor){
* $terminalor->getResponse()->message('Hello world');
* };
* </code>
*
* @param string $offset command name
* @param Closure $value command body
* @return null
*/
public function offsetSet($offset, $value)
{
try {
if ($this->offsetExists($offset)) {
throw new InvalidArgumentException(
sprintf('Can\'t create `%s` command. It\'s already exists.',
$offset));
}
if (!($value instanceof Closure)) {
throw new InvalidArgumentException(
sprintf('Can\'t create `%s` command. Value `%s` is not closure.',
$offset, $value));
}
$this->_commands[$offset] = $value;
} catch (InvalidArgumentException $e) {
$this->getResponse()->message($e->getMessage(), 'error');
}
}
/**
* Remove command with given name
*
* @param string $offset command name
* @return null
*/
public function offsetUnset($offset)
{
try {
if (!$this->offsetExists($offset)) {
throw new InvalidArgumentException(
sprintf('Can\'t delete `%s` command. It doesn\'t exists.', $offset));
}
unset($this->_commands[$offset]);
} catch (InvalidArgumentException $e) {
$this->getResponse()->message($e->getMessage(), 'error');
}
}
/**
* Calculate number of defined commands
*
* @return int number of commands
*/
public function count()
{
return count($this->_commands);
}
/**
* Retriew current command
*
* @return Closure
*/
public function current()
{
return current($this->_commands);
}
/**
* Retriew next command
*
* @return Closure
*/
public function next()
{
return next($this->_commands);
}
/**
* Get current command name
*
* @return string
*/
public function key()
{
return key($this->_commands);
}
/**
* Check if command with given key exists
*
* @return boolean true if command exists
*/
public function valid()
{
$offset = $this->key();
return $this->offsetExists($offset);
}
/**
* Set internal commands pointer to the first command
*
* @return null
*/
public function rewind()
{
reset($this->_commands);
}
/**
* Remove all defined commands
*
* @return Terminalor_Application_Interface
*/
public function flush()
{
$this->_commands = array();
return $this;
}
/**
* Dispatches application
*
* @return null
*/
public function __toString()
{
if (!defined('_TERMINALOR_BUILDER_')) {
parent::__toString();
}
}
}
| b-b3rn4rd/Terminalor | library/Terminalor/Application.php | PHP | mit | 4,584 |
import {
propValues,
isConstructor,
initializeProps,
parseAttributeValue,
ICustomElement,
ConstructableComponent,
FunctionComponent,
PropsDefinition,
} from "./utils";
let currentElement: HTMLElement & ICustomElement;
export function getCurrentElement() {
return currentElement;
}
export function noShadowDOM() {
Object.defineProperty(currentElement, "renderRoot", {
value: currentElement,
});
}
export function createElementType<T>(
BaseElement: typeof HTMLElement,
propDefinition: PropsDefinition<T>
) {
const propKeys = Object.keys(propDefinition) as Array<
keyof PropsDefinition<T>
>;
return class CustomElement extends BaseElement implements ICustomElement {
[prop: string]: any;
__initialized?: boolean;
__released: boolean;
__releaseCallbacks: any[];
__propertyChangedCallbacks: any[];
__updating: { [prop: string]: any };
props: { [prop: string]: any };
static get observedAttributes() {
return propKeys.map((k) => propDefinition[k].attribute);
}
constructor() {
super();
this.__initialized = false;
this.__released = false;
this.__releaseCallbacks = [];
this.__propertyChangedCallbacks = [];
this.__updating = {};
this.props = {};
}
connectedCallback() {
if (this.__initialized) return;
this.__releaseCallbacks = [];
this.__propertyChangedCallbacks = [];
this.__updating = {};
this.props = initializeProps(this as any, propDefinition);
const props = propValues<T>(this.props as PropsDefinition<T>),
ComponentType = this.Component as
| Function
| { new (...args: any[]): any },
outerElement = currentElement;
try {
currentElement = this;
this.__initialized = true;
if (isConstructor(ComponentType))
new (ComponentType as ConstructableComponent<T>)(props, {
element: this as ICustomElement,
});
else
(ComponentType as FunctionComponent<T>)(props, {
element: this as ICustomElement,
});
} finally {
currentElement = outerElement;
}
}
async disconnectedCallback() {
// prevent premature releasing when element is only temporarely removed from DOM
await Promise.resolve();
if (this.isConnected) return;
this.__propertyChangedCallbacks.length = 0;
let callback = null;
while ((callback = this.__releaseCallbacks.pop())) callback(this);
delete this.__initialized;
this.__released = true;
}
attributeChangedCallback(name: string, oldVal: string, newVal: string) {
if (!this.__initialized) return;
if (this.__updating[name]) return;
name = this.lookupProp(name)!;
if (name in propDefinition) {
if (newVal == null && !this[name]) return;
this[name] = propDefinition[name as keyof T].parse
? parseAttributeValue(newVal)
: newVal;
}
}
lookupProp(attrName: string) {
if (!propDefinition) return;
return propKeys.find(
(k) => attrName === k || attrName === propDefinition[k].attribute
) as string | undefined;
}
get renderRoot() {
return this.shadowRoot || this.attachShadow({ mode: "open" });
}
addReleaseCallback(fn: () => void) {
this.__releaseCallbacks.push(fn);
}
addPropertyChangedCallback(fn: (name: string, value: any) => void) {
this.__propertyChangedCallbacks.push(fn);
}
};
}
| ryansolid/component-register | src/element.ts | TypeScript | mit | 3,536 |
'use strict';
var should = require('should'),
request = require('supertest'),
app = require('../../server'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Rawrecords3 = mongoose.model('Rawrecords3'),
agent = request.agent(app);
/**
* Globals
*/
var credentials, user, rawrecords3;
/**
* Rawrecords3 routes tests
*/
describe('Rawrecords3 CRUD tests', function() {
beforeEach(function(done) {
// Create user credentials
credentials = {
username: 'username',
password: 'password'
};
// Create a new user
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: credentials.username,
password: credentials.password,
provider: 'local'
});
// Save a user to the test db and create new Rawrecords3
user.save(function() {
rawrecords3 = {
name: 'Rawrecords3 Name'
};
done();
});
});
it('should be able to save Rawrecords3 instance if logged in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Rawrecords3
agent.post('/rawrecords3s')
.send(rawrecords3)
.expect(200)
.end(function(rawrecords3SaveErr, rawrecords3SaveRes) {
// Handle Rawrecords3 save error
if (rawrecords3SaveErr) done(rawrecords3SaveErr);
// Get a list of Rawrecords3s
agent.get('/rawrecords3s')
.end(function(rawrecords3sGetErr, rawrecords3sGetRes) {
// Handle Rawrecords3 save error
if (rawrecords3sGetErr) done(rawrecords3sGetErr);
// Get Rawrecords3s list
var rawrecords3s = rawrecords3sGetRes.body;
// Set assertions
(rawrecords3s[0].user._id).should.equal(userId);
(rawrecords3s[0].name).should.match('Rawrecords3 Name');
// Call the assertion callback
done();
});
});
});
});
it('should not be able to save Rawrecords3 instance if not logged in', function(done) {
agent.post('/rawrecords3s')
.send(rawrecords3)
.expect(401)
.end(function(rawrecords3SaveErr, rawrecords3SaveRes) {
// Call the assertion callback
done(rawrecords3SaveErr);
});
});
it('should not be able to save Rawrecords3 instance if no name is provided', function(done) {
// Invalidate name field
rawrecords3.name = '';
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Rawrecords3
agent.post('/rawrecords3s')
.send(rawrecords3)
.expect(400)
.end(function(rawrecords3SaveErr, rawrecords3SaveRes) {
// Set message assertion
(rawrecords3SaveRes.body.message).should.match('Please fill Rawrecords3 name');
// Handle Rawrecords3 save error
done(rawrecords3SaveErr);
});
});
});
it('should be able to update Rawrecords3 instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Rawrecords3
agent.post('/rawrecords3s')
.send(rawrecords3)
.expect(200)
.end(function(rawrecords3SaveErr, rawrecords3SaveRes) {
// Handle Rawrecords3 save error
if (rawrecords3SaveErr) done(rawrecords3SaveErr);
// Update Rawrecords3 name
rawrecords3.name = 'WHY YOU GOTTA BE SO MEAN?';
// Update existing Rawrecords3
agent.put('/rawrecords3s/' + rawrecords3SaveRes.body._id)
.send(rawrecords3)
.expect(200)
.end(function(rawrecords3UpdateErr, rawrecords3UpdateRes) {
// Handle Rawrecords3 update error
if (rawrecords3UpdateErr) done(rawrecords3UpdateErr);
// Set assertions
(rawrecords3UpdateRes.body._id).should.equal(rawrecords3SaveRes.body._id);
(rawrecords3UpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
});
it('should be able to get a list of Rawrecords3s if not signed in', function(done) {
// Create new Rawrecords3 model instance
var rawrecords3Obj = new Rawrecords3(rawrecords3);
// Save the Rawrecords3
rawrecords3Obj.save(function() {
// Request Rawrecords3s
request(app).get('/rawrecords3s')
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Array.with.lengthOf(1);
// Call the assertion callback
done();
});
});
});
it('should be able to get a single Rawrecords3 if not signed in', function(done) {
// Create new Rawrecords3 model instance
var rawrecords3Obj = new Rawrecords3(rawrecords3);
// Save the Rawrecords3
rawrecords3Obj.save(function() {
request(app).get('/rawrecords3s/' + rawrecords3Obj._id)
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Object.with.property('name', rawrecords3.name);
// Call the assertion callback
done();
});
});
});
it('should be able to delete Rawrecords3 instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Rawrecords3
agent.post('/rawrecords3s')
.send(rawrecords3)
.expect(200)
.end(function(rawrecords3SaveErr, rawrecords3SaveRes) {
// Handle Rawrecords3 save error
if (rawrecords3SaveErr) done(rawrecords3SaveErr);
// Delete existing Rawrecords3
agent.delete('/rawrecords3s/' + rawrecords3SaveRes.body._id)
.send(rawrecords3)
.expect(200)
.end(function(rawrecords3DeleteErr, rawrecords3DeleteRes) {
// Handle Rawrecords3 error error
if (rawrecords3DeleteErr) done(rawrecords3DeleteErr);
// Set assertions
(rawrecords3DeleteRes.body._id).should.equal(rawrecords3SaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
it('should not be able to delete Rawrecords3 instance if not signed in', function(done) {
// Set Rawrecords3 user
rawrecords3.user = user;
// Create new Rawrecords3 model instance
var rawrecords3Obj = new Rawrecords3(rawrecords3);
// Save the Rawrecords3
rawrecords3Obj.save(function() {
// Try deleting Rawrecords3
request(app).delete('/rawrecords3s/' + rawrecords3Obj._id)
.expect(401)
.end(function(rawrecords3DeleteErr, rawrecords3DeleteRes) {
// Set message assertion
(rawrecords3DeleteRes.body.message).should.match('User is not logged in');
// Handle Rawrecords3 error error
done(rawrecords3DeleteErr);
});
});
});
afterEach(function(done) {
User.remove().exec();
Rawrecords3.remove().exec();
done();
});
}); | hhkk/141118UsToDoV3 | app/tests/rawrecords3.server.routes.test.js | JavaScript | mit | 7,186 |
namespace SharpCompress.Compressor.LZMA
{
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
internal class BitVector
{
private uint[] mBits;
private int mLength;
public BitVector(List<bool> bits) : this(bits.Count)
{
for (int i = 0; i < bits.Count; i++)
{
if (bits[i])
{
this.SetBit(i);
}
}
}
public BitVector(int length)
{
this.mLength = length;
this.mBits = new uint[(length + 0x1f) >> 5];
}
public BitVector(int length, bool initValue)
{
this.mLength = length;
this.mBits = new uint[(length + 0x1f) >> 5];
if (initValue)
{
for (int i = 0; i < this.mBits.Length; i++)
{
this.mBits[i] = uint.MaxValue;
}
}
}
internal bool GetAndSet(int index)
{
if ((index < 0) || (index >= this.mLength))
{
throw new ArgumentOutOfRangeException("index");
}
uint num = this.mBits[index >> 5];
uint num2 = ((uint) 1) << index;
this.mBits[index >> 5] |= num2;
return ((num & num2) != 0);
}
public void SetBit(int index)
{
if ((index < 0) || (index >= this.mLength))
{
throw new ArgumentOutOfRangeException("index");
}
this.mBits[index >> 5] |= ((uint) 1) << index;
}
public bool[] ToArray()
{
bool[] flagArray = new bool[this.mLength];
for (int i = 0; i < flagArray.Length; i++)
{
flagArray[i] = this[i];
}
return flagArray;
}
public override string ToString()
{
StringBuilder builder = new StringBuilder(this.mLength);
for (int i = 0; i < this.mLength; i++)
{
builder.Append(this[i] ? 'x' : '.');
}
return builder.ToString();
}
public bool this[int index]
{
get
{
if ((index < 0) || (index >= this.mLength))
{
throw new ArgumentOutOfRangeException("index");
}
return ((this.mBits[index >> 5] & (((int) 1) << index)) != 0);
}
}
public int Length
{
get
{
return this.mLength;
}
}
}
}
| RainsSoft/sharpcompress | SharpCompressForUnity3D/SharpCompress/Compressor/LZMA/BitVector.cs | C# | mit | 2,725 |
version https://git-lfs.github.com/spec/v1
oid sha256:b63ef97b9f85b0d4a07926b186083c9952568e26bbb65d610b592d15208f79a9
size 24953
| yogeshsaroya/new-cdnjs | ajax/libs/underscore.js/1.0.4/underscore.js | JavaScript | mit | 130 |
package proxy
import (
"bytes"
"net/http"
)
type Response interface {
Status() int
Header() http.Header
Body() []byte
}
type WriterRecorder struct {
http.ResponseWriter
status int
body bytes.Buffer
}
func (w *WriterRecorder) WriteHeader(status int) {
w.ResponseWriter.WriteHeader(status)
w.status = status
}
func (w *WriterRecorder) Write(body []byte) (n int, err error) {
if n, err := w.body.Write(body); err != nil {
return n, err
}
return w.ResponseWriter.Write(body)
}
func (w *WriterRecorder) Body() []byte {
return w.body.Bytes()
}
func (w *WriterRecorder) Status() int {
if w.status == 0 {
return 200
}
return w.status
}
| gchaincl/swagger-proxy | writer.go | GO | mit | 659 |
/* UnaryOperator Copyright (C) 1998-2002 Jochen Hoenicke.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; see the file COPYING.LESSER. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id: UnaryOperator.java,v 2.13.4.2 2002/05/28 17:34:06 hoenicke Exp $
*/
package alterrs.jode.expr;
import alterrs.jode.decompiler.Options;
import alterrs.jode.decompiler.TabbedPrintWriter;
import alterrs.jode.type.Type;
public class UnaryOperator extends Operator {
public UnaryOperator(Type type, int op) {
super(type, op);
initOperands(1);
}
public int getPriority() {
return 700;
}
public Expression negate() {
if (getOperatorIndex() == LOG_NOT_OP) {
if (subExpressions != null)
return subExpressions[0];
else
return new NopOperator(Type.tBoolean);
}
return super.negate();
}
public void updateSubTypes() {
subExpressions[0].setType(Type.tSubType(type));
}
public void updateType() {
updateParentType(Type.tSuperType(subExpressions[0].getType()));
}
public boolean opEquals(Operator o) {
return (o instanceof UnaryOperator) && o.operatorIndex == operatorIndex;
}
public void dumpExpression(TabbedPrintWriter writer)
throws java.io.IOException {
writer.print(getOperatorString());
if ((Options.outputStyle & Options.GNU_SPACING) != 0)
writer.print(" ");
subExpressions[0].dumpExpression(writer, 700);
}
}
| AlterRS/Deobfuscator | deps/alterrs/jode/expr/UnaryOperator.java | Java | mit | 1,963 |
<?php
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = [
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\SecurityBundle\SecurityBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle(),
new Symfony\Bundle\MonologBundle\MonologBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\AsseticBundle\AsseticBundle(),
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
new Braincrafted\Bundle\BootstrapBundle\BraincraftedBootstrapBundle(),
new HWI\Bundle\OAuthBundle\HWIOAuthBundle(),
new JMS\I18nRoutingBundle\JMSI18nRoutingBundle(),
new JMS\TranslationBundle\JMSTranslationBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
new EasyCorp\Bundle\EasySecurityBundle\EasySecurityBundle(),
new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
new Exercise\HTMLPurifierBundle\ExerciseHTMLPurifierBundle(),
new WhiteOctober\PagerfantaBundle\WhiteOctoberPagerfantaBundle(),
new EWZ\Bundle\RecaptchaBundle\EWZRecaptchaBundle(),
new Symfony\Bundle\WebServerBundle\WebServerBundle,
new Http\HttplugBundle\HttplugBundle(),
new BaseBundle\BaseBundle(),
new AppBundle\AppBundle(),
new AdminBundle\AdminBundle(),
];
if (in_array($this->getEnvironment(), ['dev', 'test'])) {
$bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
$bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
$bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
$bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
}
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}
| ninsuo/symfony-quickstart | app/AppKernel.php | PHP | mit | 2,254 |
using System;
using Computers.Common.Contracts;
namespace Computers.Common.Models.Components
{
public abstract class Cpu : MotherboardComponent, ICpu
{
private const int MinValue = 0;
private const string NumberTooLow = "Number too low.";
private const string NumberTooHigh = "Number too high.";
private static readonly Random Random = new Random();
public Cpu(byte numberOfCores)
{
this.NumberOfCores = numberOfCores;
}
public byte NumberOfCores { get; private set; }
public virtual void SquareNumber()
{
var data = Motherboard.LoadRamValue();
if (MinValue > data)
{
Motherboard.DrawOnVideoCard(NumberTooLow);
}
else if (data > this.GetMaxNumber())
{
Motherboard.DrawOnVideoCard(NumberTooHigh);
}
else
{
var result = data * data;
Motherboard.DrawOnVideoCard($"Square of {data} is {result}.");
}
}
public virtual void GenerateRandomNumber(int min, int max)
{
var randomNumber = Random.Next(min, max);
Motherboard.SaveRamValue(randomNumber);
}
public abstract int GetMaxNumber();
}
} | dushka-dragoeva/TelerikSeson2016 | Exam Preparations/HQC -Part 2/Computers/Problem/Computers.Common/Models/Components/Cpu.cs | C# | mit | 1,346 |
/* globals Promise:true */
var _ = require('lodash')
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var LRU = require('lru-cache')
var Promise = require('bluebird')
var Snapshot = require('./snapshot')
var errors = require('../errors')
var util = require('../util')
/**
* @event Blockchain#error
* @param {Error} error
*/
/**
* @event Blockchain#syncStart
*/
/**
* @event Blockchain#syncStop
*/
/**
* @event Blockchain#newBlock
* @param {string} hash
* @param {number} height
*/
/**
* @event Blockchain#touchAddress
* @param {string} address
*/
/**
* @class Blockchain
* @extends events.EventEmitter
*
* @param {Connector} connector
* @param {Object} [opts]
* @param {string} [opts.networkName=livenet]
* @param {number} [opts.txCacheSize=100]
*/
function Blockchain (connector, opts) {
var self = this
EventEmitter.call(self)
opts = _.extend({
networkName: 'livenet',
txCacheSize: 100
}, opts)
self.connector = connector
self.networkName = opts.networkName
self.latest = {hash: util.zfill('', 64), height: -1}
self._txCache = LRU({max: opts.txCacheSize, allowSlate: true})
self._isSyncing = false
self.on('syncStart', function () { self._isSyncing = true })
self.on('syncStop', function () { self._isSyncing = false })
}
inherits(Blockchain, EventEmitter)
Blockchain.prototype._syncStart = function () {
if (!this.isSyncing()) this.emit('syncStart')
}
Blockchain.prototype._syncStop = function () {
if (this.isSyncing()) this.emit('syncStop')
}
/**
* @param {errors.Connector} err
* @throws {errors.Connector}
*/
Blockchain.prototype._rethrow = function (err) {
var nerr
switch (err.name) {
case 'ErrorBlockchainJSConnectorHeaderNotFound':
nerr = new errors.Blockchain.HeaderNotFound()
break
case 'ErrorBlockchainJSConnectorTxNotFound':
nerr = new errors.Blockchain.TxNotFound()
break
case 'ErrorBlockchainJSConnectorTxSendError':
nerr = new errors.Blockchain.TxSendError()
break
default:
nerr = err
break
}
nerr.message = err.message
throw nerr
}
/**
* Return current syncing status
*
* @return {boolean}
*/
Blockchain.prototype.isSyncing = function () {
return this._isSyncing
}
/**
* @return {Promise<Snapshot>}
*/
Blockchain.prototype.getSnapshot = function () {
return Promise.resolve(new Snapshot(this))
}
/**
* @abstract
* @param {(number|string)} id height or hash
* @return {Promise<Connector~HeaderObject>}
*/
Blockchain.prototype.getHeader = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.getHeader'))
}
/**
* @abstract
* @param {string} txid
* @return {Promise<string>}
*/
Blockchain.prototype.getTx = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.getTx'))
}
/**
* @typedef {Object} Blockchain~TxBlockHashObject
* @property {string} source `blocks` or `mempool`
* @property {Object} [block] defined only when source is blocks
* @property {string} data.hash
* @property {number} data.height
*/
/**
* @abstract
* @param {string} txid
* @return {Promise<Blockchain~TxBlockHashObject>}
*/
Blockchain.prototype.getTxBlockHash = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.getTxBlockHash'))
}
/**
* @abstract
* @param {string} rawtx
* @return {Promise<string>}
*/
Blockchain.prototype.sendTx = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.sendTx'))
}
/**
* @abstract
* @param {string[]} addresses
* @param {Object} [opts]
* @param {string} [opts.source] `blocks` or `mempool`
* @param {(string|number)} [opts.from] `hash` or `height`
* @param {(string|number)} [opts.to] `hash` or `height`
* @param {string} [opts.status]
* @return {Promise<Connector~AddressesQueryObject>}
*/
Blockchain.prototype.addressesQuery = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.addressesQuery'))
}
/**
* @abstract
* @param {string} address
* @return {Promise}
*/
Blockchain.prototype.subscribeAddress = function () {
return Promise.reject(new errors.NotImplemented('Blockchain.subscribeAddress'))
}
module.exports = Blockchain
| chromaway/blockchainjs | lib/blockchain/blockchain.js | JavaScript | mit | 4,218 |
#--
# Copyright (c) 2017 Michael Berkovich, theiceberk@gmail.com
#
# __ __ ____ _ _ _____ ____ _ ______ ___ ____
# | |__| || || | | | | || || | | | / _]| \
# | | | | | | | | | | | __| | | | | | | / [_ | D )
# | | | | | | | |___ | |___ | |_ | | | |___|_| |_|| _]| /
# | ` ' | | | | || | | _] | | | | | | | [_ | \
# \ / | | | || | | | | | | | | | | || . \
# \_/\_/ |____||_____||_____| |__| |____||_____| |__| |_____||__|\_|
#
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
module WillFilter
VERSION = '5.1.4.4'
end
| skryking/will_filter | lib/will_filter/version.rb | Ruby | mit | 1,718 |
import { Cache } from '../cache/cache';
import { BoundedCache } from '../cache/bounded';
import { KeyType } from '../cache/key-type';
import { BoundlessCache } from '../cache/boundless';
import { Weigher } from '../cache/weigher';
import { DefaultLoadingCache } from '../cache/loading';
import { ExpirationCache } from '../cache/expiration';
import { MetricsCache } from '../cache/metrics/index';
import { RemovalListener } from '../cache/removal-listener';
import { Loader } from '../cache/loading/loader';
import { MaxAgeDecider } from '../cache/expiration/max-age-decider';
import { LoadingCache } from '../cache/loading/loading-cache';
import { Expirable } from '../cache/expiration/expirable';
export interface CacheBuilder<K extends KeyType, V> {
/**
* Set a listener that will be called every time something is removed
* from the cache.
*/
withRemovalListener(listener: RemovalListener<K, V>): this;
/**
* Set the maximum number of items to keep in the cache before evicting
* something.
*/
maxSize(size: number): this;
/**
* Set a function to use to determine the size of a cached object.
*/
withWeigher(weigher: Weigher<K, V>): this;
/**
* Change to a cache where get can also resolve values if provided with
* a function as the second argument.
*/
loading(): LoadingCacheBuilder<K, V>;
/**
* Change to a loading cache, where the get-method will return instances
* of Promise and automatically load unknown values.
*/
withLoader(loader: Loader<K, V>): LoadingCacheBuilder<K, V>;
/**
* Set that the cache should expire items some time after they have been
* written to the cache.
*/
expireAfterWrite(time: number | MaxAgeDecider<K, V>): this;
/**
* Set that the cache should expire items some time after they have been
* read from the cache.
*/
expireAfterRead(time: number | MaxAgeDecider<K, V>): this;
/**
* Activate tracking of metrics for this cache.
*/
metrics(): this;
/**
* Build the cache.
*/
build(): Cache<K, V>;
}
export interface LoadingCacheBuilder<K extends KeyType, V> extends CacheBuilder<K, V> {
/**
* Build the cache.
*/
build(): LoadingCache<K, V>;
}
/**
* Builder for cache instances.
*/
export class CacheBuilderImpl<K extends KeyType, V> implements CacheBuilder<K, V> {
private optRemovalListener?: RemovalListener<K, V>;
private optMaxSize?: number;
private optWeigher?: Weigher<K, V>;
private optMaxWriteAge?: MaxAgeDecider<K, V>;
private optMaxNoReadAge?: MaxAgeDecider<K, V>;
private optMetrics: boolean = false;
/**
* Set a listener that will be called every time something is removed
* from the cache.
*/
public withRemovalListener(listener: RemovalListener<K, V>) {
this.optRemovalListener = listener;
return this;
}
/**
* Set the maximum number of items to keep in the cache before evicting
* something.
*/
public maxSize(size: number) {
this.optMaxSize = size;
return this;
}
/**
* Set a function to use to determine the size of a cached object.
*/
public withWeigher(weigher: Weigher<K, V>) {
if(typeof weigher !== 'function') {
throw new Error('Weigher should be a function that takes a key and value and returns a number');
}
this.optWeigher = weigher;
return this;
}
/**
* Change to a cache where get can also resolve values if provided with
* a function as the second argument.
*/
public loading(): LoadingCacheBuilder<K, V> {
return new LoadingCacheBuilderImpl(this, null);
}
/**
* Change to a loading cache, where the get-method will return instances
* of Promise and automatically load unknown values.
*/
public withLoader(loader: Loader<K, V>): LoadingCacheBuilder<K, V> {
if(typeof loader !== 'function') {
throw new Error('Loader should be a function that takes a key and returns a value or a promise that resolves to a value');
}
return new LoadingCacheBuilderImpl(this, loader);
}
/**
* Set that the cache should expire items after some time.
*/
public expireAfterWrite(time: number | MaxAgeDecider<K, V>) {
let evaluator;
if(typeof time === 'function') {
evaluator = time;
} else if(typeof time === 'number') {
evaluator = () => time;
} else {
throw new Error('expireAfterWrite needs either a maximum age as a number or a function that returns a number');
}
this.optMaxWriteAge = evaluator;
return this;
}
/**
* Set that the cache should expire items some time after they have been read.
*/
public expireAfterRead(time: number | MaxAgeDecider<K, V>): this {
let evaluator;
if(typeof time === 'function') {
evaluator = time;
} else if(typeof time === 'number') {
evaluator = () => time;
} else {
throw new Error('expireAfterRead needs either a maximum age as a number or a function that returns a number');
}
this.optMaxNoReadAge = evaluator;
return this;
}
/**
* Activate tracking of metrics for this cache.
*/
public metrics(): this {
this.optMetrics = true;
return this;
}
/**
* Build and return the cache.
*/
public build() {
let cache: Cache<K, V>;
if(typeof this.optMaxWriteAge !== 'undefined' || typeof this.optMaxNoReadAge !== 'undefined') {
/*
* Requested expiration - wrap the base cache a bit as it needs
* custom types, a custom weigher if used and removal listeners
* are added on the expiration cache instead.
*/
let parentCache: Cache<K, Expirable<V>>;
if(this.optMaxSize) {
parentCache = new BoundedCache({
maxSize: this.optMaxSize,
weigher: createExpirableWeigher(this.optWeigher)
});
} else {
parentCache = new BoundlessCache({});
}
cache = new ExpirationCache({
maxNoReadAge: this.optMaxNoReadAge,
maxWriteAge: this.optMaxWriteAge,
removalListener: this.optRemovalListener,
parent: parentCache
});
} else {
if(this.optMaxSize) {
cache = new BoundedCache({
maxSize: this.optMaxSize,
weigher: this.optWeigher,
removalListener: this.optRemovalListener
});
} else {
cache = new BoundlessCache({
removalListener: this.optRemovalListener
});
}
}
if(this.optMetrics) {
// Collect metrics if requested
cache = new MetricsCache({
parent: cache
});
}
return cache;
}
}
class LoadingCacheBuilderImpl<K extends KeyType, V> implements LoadingCacheBuilder<K, V> {
private parent: CacheBuilder<K, V>;
private loader: Loader<K, V> | null;
constructor(parent: CacheBuilder<K, V>, loader: Loader<K, V> | null) {
this.parent = parent;
this.loader = loader;
}
public withRemovalListener(listener: RemovalListener<K, V>): this {
this.parent.withRemovalListener(listener);
return this;
}
public maxSize(size: number): this {
this.parent.maxSize(size);
return this;
}
public withWeigher(weigher: Weigher<K, V>): this {
this.parent.withWeigher(weigher);
return this;
}
public loading(): LoadingCacheBuilder<K, V> {
throw new Error('Already building a loading cache');
}
public withLoader(loader: Loader<K, V>): LoadingCacheBuilder<K, V> {
throw new Error('Already building a loading cache');
}
public expireAfterWrite(time: number | MaxAgeDecider<K, V>): this {
this.parent.expireAfterWrite(time);
return this;
}
public expireAfterRead(time: number | MaxAgeDecider<K, V>): this {
this.parent.expireAfterRead(time);
return this;
}
public metrics(): this {
this.parent.metrics();
return this;
}
public build(): LoadingCache<K, V> {
return new DefaultLoadingCache({
loader: this.loader,
parent: this.parent.build()
});
}
}
function createExpirableWeigher<K extends KeyType, V>(w: Weigher<K, V> | undefined): Weigher<K, Expirable<V>> | null {
if(! w) return null;
return (key, node) => w(key, node.value as V);
}
| aholstenson/transitory | src/builder/unified-builder.ts | TypeScript | mit | 7,739 |
using Microsoft.Azure.AppService.ApiApps.Service;
using System.Collections.Generic;
using System.IO;
namespace FileWatcher.Models
{
// A simple in-memory trigger store.
public class InMemoryTriggerStore
{
private static InMemoryTriggerStore instance;
private IDictionary<string, FileSystemWatcher> _store;
private InMemoryTriggerStore()
{
_store = new Dictionary<string, FileSystemWatcher>();
}
public static InMemoryTriggerStore Instance
{
get
{
if (instance == null)
{
instance = new InMemoryTriggerStore();
}
return instance;
}
}
// Register a push trigger.
public void RegisterTrigger(string triggerId, string rootPath,
TriggerInput<string, FileInfoWrapper> triggerInput)
{
// Use FileSystemWatcher to listen to file change event.
var filter = string.IsNullOrEmpty(triggerInput.inputs) ? "*" : triggerInput.inputs;
var watcher = new FileSystemWatcher(rootPath, filter);
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
watcher.NotifyFilter = NotifyFilters.LastAccess;
// When some file is changed, fire the push trigger.
watcher.Changed +=
(sender, e) => watcher_Changed(sender, e,
Runtime.FromAppSettings(),
triggerInput.GetCallback());
// Assoicate the FileSystemWatcher object with the triggerId.
_store[triggerId] = watcher;
}
// Fire the assoicated push trigger when some file is changed.
void watcher_Changed(object sender, FileSystemEventArgs e,
// AppService runtime object needed to invoke the callback.
Runtime runtime,
// The callback to invoke.
ClientTriggerCallback<FileInfoWrapper> callback)
{
// Helper method provided by AppService service SDK to invoke a push trigger callback.
callback.InvokeAsync(runtime, FileInfoWrapper.FromFileInfo(new FileInfo(e.FullPath)));
}
}
} | guangyang/apiapp-samples | csharp/FileWatcher/FileWatcher/Models/InMemoryTriggerStore.cs | C# | mit | 2,327 |
<?php
namespace Application\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\ManyToOne;
/**
* Person entity.
* Each person may have zero or more contacts.
* Each person must have at least one instance of credentials.
* That is not really checked by the application at the moment.
* It is just not exposed to the end user that such an entity exists in the system
* and there is no legal way for an end-user to create or destroy instance of this entity.
* Each person may have zero or more e-mail addresses.
* Each person may have zero or more phone numbers.
* @Entity(repositoryClass="PersonRepository")
*/
class Person
{
/**
* @var int
* @Id
* @GeneratedValue
* @Column(type="integer")
*/
private $id;
/**
* @var Credentials[]
* @OneToMany(targetEntity="Credentials",mappedBy="owner")
*/
private $credentials;
/**
* @var PhoneNumber[]
* @OneToMany(targetEntity="PhoneNumber",mappedBy="owner")
*/
private $phoneNumbers;
/**
* @var EMailAddress[]
* @OneToMany(targetEntity="EMailAddress",mappedBy="owner")
*/
private $emailAddresses;
/**
* @var Contact[]
* @OneToMany(targetEntity="Contact",mappedBy="source")
*/
private $contacts;
public function __construct ( )
{
$this->credentials = new ArrayCollection ( );
$this->phoneNumbers = new ArrayCollection ( );
$this->emailAddresses = new ArrayCollection ( );
$this->contacts = new ArrayCollection ( );
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add credentials
*
* @param \Application\Entity\Credentials $credentials
* @return Person
*/
public function addCredential(\Application\Entity\Credentials $credentials)
{
$this->credentials[] = $credentials;
return $this;
}
/**
* Remove credentials
*
* @param \Application\Entity\Credentials $credentials
*/
public function removeCredential(\Application\Entity\Credentials $credentials)
{
$this->credentials->removeElement($credentials);
}
/**
* Get credentials
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getCredentials()
{
return $this->credentials;
}
/**
* Add phoneNumbers
*
* @param \Application\Entity\PhoneNumber $phoneNumbers
* @return Person
*/
public function addPhoneNumber(\Application\Entity\PhoneNumber $phoneNumbers)
{
$this->phoneNumbers[] = $phoneNumbers;
return $this;
}
/**
* Remove phoneNumbers
*
* @param \Application\Entity\PhoneNumber $phoneNumbers
*/
public function removePhoneNumber(\Application\Entity\PhoneNumber $phoneNumbers)
{
$this->phoneNumbers->removeElement($phoneNumbers);
}
/**
* Get phoneNumbers
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getPhoneNumbers()
{
return $this->phoneNumbers;
}
/**
* Add contacts
*
* @param \Application\Entity\Contact $contacts
* @return Person
*/
public function addContact(\Application\Entity\Contact $contacts)
{
$this->contacts[] = $contacts;
return $this;
}
/**
* Remove contacts
*
* @param \Application\Entity\Contact $contacts
*/
public function removeContact(\Application\Entity\Contact $contacts)
{
$this->contacts->removeElement($contacts);
}
/**
* Get contacts
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getContacts()
{
return $this->contacts;
}
/**
* Add emailAddresses
*
* @param \Application\Entity\EMailAddress $emailAddresses
* @return Person
*/
public function addEmailAddress(\Application\Entity\EMailAddress $emailAddresses)
{
$this->emailAddresses[] = $emailAddresses;
return $this;
}
/**
* Remove emailAddresses
*
* @param \Application\Entity\EMailAddress $emailAddresses
*/
public function removeEmailAddress(\Application\Entity\EMailAddress $emailAddresses)
{
$this->emailAddresses->removeElement($emailAddresses);
}
/**
* Get emailAddresses
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getEmailAddresses()
{
return $this->emailAddresses;
}
}
| Wbondar/Buddies | module/Application/src/Application/Entity/Person.php | PHP | mit | 4,758 |
# Dev shit
if ENV["BAK_SHELL_DEV_SHIT"] == "devshit"
require "awesome_print" rescue nil
end
# Standard lib shit
require "fileutils"
# Require gems shit
require "gli"
require "rainbow/ext/string"
module BakShell
BACKUP_DIR = File.expand_path(File.join(ENV["HOME"], "bak"))
end
require_relative "./bak-shell/version"
require_relative "./bak-shell/exceptions"
require_relative "./bak-shell/indexer"
require_relative "./bak-shell/cli"
| RobertAudi/bak-shell | lib/bak-shell.rb | Ruby | mit | 439 |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { StyleSheet, css } from 'aphrodite';
import { changeTimeSignature } from '../../actions/track';
import HoverableText from './HoverableText';
const styles = StyleSheet.create({
text: {
fontFamily: 'Optima, Segoe, Segoe UI, Candara, Calibri, Arial, sans-serif'
},
popoverContainer: {
background: '#FEFBF7',
height: 200,
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-between'
},
templateRow: {
display: 'flex',
justifyContent: 'space-around',
paddingTop: 10
},
timeSigRow: { display: 'flex', justifyContent: 'center', flexShrink: 10 },
checkboxRow: {
display: 'flex',
justifyContent: 'space-around',
paddingBottom: 10,
paddingLeft: 5,
paddingRight: 5
},
beats: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingTop: 15,
alignItems: 'flex-end',
flexBasis: '55%'
},
beatType: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingBottom: 15,
alignItems: 'flex-end',
flexBasis: '55%'
},
numberText: { fontSize: 40, paddingRight: 10 },
topArrows: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingTop: 15,
flexBasis: '45%'
},
bottomArrows: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
paddingBottom: 15,
flexBasis: '45%'
},
checkboxText: { fontWeight: 300, fontSize: 12, paddingTop: 3 }
});
class TimeSignaturePopover extends Component {
constructor(props) {
super(props);
this.state = {
timeSignature: Object.assign({}, props.timeSignature),
toEndChecked: false,
allChecked: false
};
}
componentWillUnmount() {
const { timeSignature, toEndChecked, allChecked } = this.state;
this.props.changeTimeSignature(
{ measureIndex: this.props.measureIndex },
timeSignature,
toEndChecked,
allChecked
);
}
onTwoFourClick = () => {
// TODO extract these things into a component
this.setState({ timeSignature: { beats: 2, beatType: 4 } });
};
onFourFourClick = () => {
this.setState({ timeSignature: { beats: 4, beatType: 4 } });
};
onSixEightClick = () => {
this.setState({ timeSignature: { beats: 6, beatType: 8 } });
};
onIncrementBeats = () => {
if (this.state.timeSignature.beats < 32) {
this.setState({
timeSignature: {
beats: this.state.timeSignature.beats + 1,
beatType: this.state.timeSignature.beatType
}
});
}
};
onIncrementBeatType = () => {
if (this.state.timeSignature.beatType < 32) {
this.setState({
timeSignature: {
beats: this.state.timeSignature.beats,
beatType: this.state.timeSignature.beatType * 2
}
});
}
};
onDecrementBeats = () => {
if (this.state.timeSignature.beats > 1) {
this.setState({
timeSignature: {
beats: this.state.timeSignature.beats - 1,
beatType: this.state.timeSignature.beatType
}
});
}
};
onDecrementBeatType = () => {
if (this.state.timeSignature.beatType > 1) {
this.setState({
timeSignature: {
beats: this.state.timeSignature.beats,
beatType: this.state.timeSignature.beatType / 2
}
});
}
};
toEndChanged = () => {
this.setState({ toEndChecked: !this.state.toEndChecked });
};
allChanged = () => {
this.setState({ allChecked: !this.state.allChecked });
};
render() {
return (
<div className={css(styles.popoverContainer)}>
<span className={css(styles.templateRow)}>
<HoverableText onClick={this.onTwoFourClick} text="2/4" />
<HoverableText onClick={this.onFourFourClick} text="4/4" />
<HoverableText onClick={this.onSixEightClick} text="6/8" />
</span>
<div className={css(styles.timeSigRow)}>
<span className={css(styles.beats)}>
<h3 className={css(styles.text, styles.numberText)}>
{this.state.timeSignature.beats}
</h3>
</span>
<span className={css(styles.topArrows)}>
<HoverableText onClick={this.onIncrementBeats} text="▲" />
<HoverableText onClick={this.onDecrementBeats} text="▼" />
</span>
</div>
<div className={css(styles.timeSigRow)}>
<span className={css(styles.beatType)}>
<h3 className={css(styles.text, styles.numberText)}>
{this.state.timeSignature.beatType}
</h3>
</span>
<span className={css(styles.bottomArrows)}>
<HoverableText onClick={this.onIncrementBeatType} text="▲" />
<HoverableText onClick={this.onDecrementBeatType} text="▼" />
</span>
</div>
<span className={css(styles.checkboxRow)}>
<small className={css(styles.text, styles.checkboxText)}>
To End
</small>
<input
type="checkbox"
value={this.state.toEndChecked}
onChange={this.toEndChanged}
/>
<small className={css(styles.text, styles.checkboxText)}>
All Measures
</small>
<input
type="checkbox"
value={this.state.allChecked}
onChange={this.allChanged}
/>
</span>
</div>
);
}
}
export default connect(null, { changeTimeSignature })(TimeSignaturePopover);
| calesce/tab-editor | src/components/editor/TimeSignaturePopover.js | JavaScript | mit | 5,636 |
<?php
/**
* To rebuild the `snapshots` directory after changing
* files in `source`, run `php tests/rebuild.php`.
*/
shell_exec('./jigsaw build testing');
removeDirectory('tests/snapshots');
rename('tests/build-testing', 'tests/snapshots');
function removeDirectory($path)
{
if (! $path) {
exit("Path to the 'tests/snapshots' directory is missing");
}
$files = glob($path . '/{,.}[!.,!..]*', GLOB_MARK|GLOB_BRACE);
foreach ($files as $file) {
is_dir($file) ? removeDirectory($file) : unlink($file);
}
rmdir($path);
return;
}
| quickliketurtle/jigsaw | tests/rebuild.php | PHP | mit | 578 |
/*
The MIT License (MIT)
Copyright (c) <2010-2020> <wenshengming>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "LClientManager.h"
#include "LClient.h"
#include "LLoginServerMainLogic.h"
LClientManager::~LClientManager()
{
m_pLSMainLogic = NULL;
}
LClientManager::LClientManager()
{
}
// 初始化连接
bool LClientManager::Initialize(unsigned int unMaxClientServ)
{
if (m_pLSMainLogic == NULL)
{
return false;
}
if (unMaxClientServ == 0)
{
unMaxClientServ = 1000;
}
for (unsigned int ui = 0; ui < unMaxClientServ; ++ui)
{
LClient *pClient = new LClient;
if (pClient == NULL)
{
return false;
}
m_queueClientPool.push(pClient);
}
return true;
}
// 网络层SessionID,tsa连接信息
bool LClientManager::AddNewUpSession(uint64_t u64SessionID, t_Session_Accepted& tsa)
{
map<uint64_t, LClient*>::iterator _ito = m_mapClientManagerBySessionID.find(u64SessionID);
if (_ito != m_mapClientManagerBySessionID.end())
{
return false;
}
LClient* pClient = GetOneClientFromPool();
if (pClient == NULL)
{
return false;
}
pClient->SetClientInfo(u64SessionID, tsa);
m_mapClientManagerBySessionID[u64SessionID] = pClient;
return true;
}
void LClientManager::RemoveOneSession(uint64_t u64SessionID)
{
map<uint64_t, LClient*>::iterator _ito = m_mapClientManagerBySessionID.find(u64SessionID);
if (_ito != m_mapClientManagerBySessionID.end())
{
FreeOneClientToPool(_ito->second);
m_mapClientManagerBySessionID.erase(_ito);
}
}
LClient* LClientManager::GetOneClientFromPool()
{
if (m_queueClientPool.empty())
{
return NULL;
}
LClient* pClient = m_queueClientPool.front();
m_queueClientPool.pop();
return pClient;
}
void LClientManager::FreeOneClientToPool(LClient* pClient)
{
if (pClient == NULL)
{
return ;
}
m_queueClientPool.push(pClient);
}
LClient* LClientManager::FindClientBySessionID(uint64_t u64SessionID)
{
map<uint64_t, LClient*>::iterator _ito = m_mapClientManagerBySessionID.find(u64SessionID);
if (_ito == m_mapClientManagerBySessionID.end())
{
return NULL;
}
return _ito->second;
}
void LClientManager::SetLSMainLogic(LLoginServerMainLogic* plsml)
{
m_pLSMainLogic = plsml;
}
LLoginServerMainLogic* LClientManager::GetLSMainLogic()
{
return m_pLSMainLogic;
}
unsigned int LClientManager::GetClientCount()
{
return m_mapClientManagerBySessionID.size();
}
| MBeanwenshengming/linuxgameserver | LoginServer/LClientManager.cpp | C++ | mit | 3,333 |
package fr.univ_tln.trailscommunity.utilities.validators;
import java.util.Calendar;
/**
* Project TrailsCommunity.
* Package fr.univ_tln.trailscommunity.utilities.validators.
* File DateValidator.java.
* Created by Ysee on 26/11/2016 - 15:54.
* www.yseemonnier.com
* https://github.com/YMonnier
*/
public class DateValidator {
/**
* Test if the calendar date is not a past date.
* @param calendar calendar for validation.
* @return true if time calendar in millisecond is
* greater than current system time.
*/
public static boolean validate(Calendar calendar) {
Calendar currentCalendar = Calendar.getInstance();
if (currentCalendar == null)
return false;
currentCalendar.setTimeInMillis(System.currentTimeMillis());
return calendar.get(Calendar.YEAR) >= currentCalendar.get(Calendar.YEAR)
&& calendar.get(Calendar.MONTH) >= currentCalendar.get(Calendar.MONTH)
&& calendar.get(Calendar.DATE) >= currentCalendar.get(Calendar.DATE);
}
}
| YMonnier/TrailsCommunity | app/android/TrailsCommunity/app/src/main/java/fr/univ_tln/trailscommunity/utilities/validators/DateValidator.java | Java | mit | 1,060 |
package io.inbot.utils.maps;
import java.util.Collection;
import java.util.function.Supplier;
public interface RichMultiMap<K, V> extends RichMap<K,Collection<V>> {
Supplier<Collection<V>> supplier();
default Collection<V> putValue(K key, V value) {
Collection<V> collection = getOrCreate(key, supplier());
collection.add(value);
return collection;
}
@SuppressWarnings("unchecked")
default void putValue(Entry<K,V>...entries) {
for(Entry<K, V> e: entries) {
putValue(e.getKey(),e.getValue());
}
}
} | Inbot/inbot-utils | src/main/java/io/inbot/utils/maps/RichMultiMap.java | Java | mit | 578 |
using System;
using UnityEditor.Graphing;
using UnityEngine;
using Object = UnityEngine.Object;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Slots
{
class TextureSlotControlView : VisualElement
{
Texture2DInputMaterialSlot m_Slot;
public TextureSlotControlView(Texture2DInputMaterialSlot slot)
{
m_Slot = slot;
styleSheets.Add(Resources.Load<StyleSheet>("Styles/Controls/TextureSlotControlView"));
var objectField = new ObjectField { objectType = typeof(Texture), value = m_Slot.texture };
objectField.RegisterValueChangedCallback(OnValueChanged);
Add(objectField);
}
void OnValueChanged(ChangeEvent<Object> evt)
{
var texture = evt.newValue as Texture;
if (texture != m_Slot.texture)
{
m_Slot.owner.owner.owner.RegisterCompleteObjectUndo("Change Texture");
m_Slot.texture = texture;
m_Slot.owner.Dirty(ModificationScope.Node);
}
}
}
}
| Unity-Technologies/ScriptableRenderLoop | com.unity.shadergraph/Editor/Drawing/Views/Slots/TextureSlotControlView.cs | C# | mit | 1,120 |
using System;
using System.Diagnostics;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.HDPipeline
{
// This enum is just here to centralize UniqueID values for skies provided with HDRP
public enum SkyType
{
HDRISky = 1,
ProceduralSky = 2,
Gradient = 3,
}
public enum SkyAmbientMode
{
Static,
Dynamic,
}
[Serializable, DebuggerDisplay(k_DebuggerDisplay)]
public sealed class SkyAmbientModeParameter : VolumeParameter<SkyAmbientMode>
{
public SkyAmbientModeParameter(SkyAmbientMode value, bool overrideState = false)
: base(value, overrideState) { }
}
// Keep this class first in the file. Otherwise it seems that the script type is not registered properly.
[Serializable, VolumeComponentMenu("Visual Environment")]
public sealed class VisualEnvironment : VolumeComponent
{
public IntParameter skyType = new IntParameter(0);
public SkyAmbientModeParameter skyAmbientMode = new SkyAmbientModeParameter(SkyAmbientMode.Static);
public FogTypeParameter fogType = new FogTypeParameter(FogType.None);
public void PushFogShaderParameters(HDCamera hdCamera, CommandBuffer cmd)
{
if ((fogType.value != FogType.Volumetric) || (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.Volumetrics)))
{
// If the volumetric fog is not used, we need to make sure that all rendering passes
// (not just the atmospheric scattering one) receive neutral parameters.
VolumetricFog.PushNeutralShaderParameters(cmd);
}
if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.AtmosphericScattering))
{
cmd.SetGlobalInt(HDShaderIDs._AtmosphericScatteringType, (int)FogType.None);
return;
}
switch (fogType.value)
{
case FogType.None:
{
cmd.SetGlobalInt(HDShaderIDs._AtmosphericScatteringType, (int)FogType.None);
break;
}
case FogType.Linear:
{
var fogSettings = VolumeManager.instance.stack.GetComponent<LinearFog>();
fogSettings.PushShaderParameters(hdCamera, cmd);
break;
}
case FogType.Exponential:
{
var fogSettings = VolumeManager.instance.stack.GetComponent<ExponentialFog>();
fogSettings.PushShaderParameters(hdCamera, cmd);
break;
}
case FogType.Volumetric:
{
if (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Volumetrics))
{
var fogSettings = VolumeManager.instance.stack.GetComponent<VolumetricFog>();
fogSettings.PushShaderParameters(hdCamera, cmd);
}
break;
}
}
}
}
}
| Unity-Technologies/ScriptableRenderLoop | com.unity.render-pipelines.high-definition/Runtime/Sky/VisualEnvironment.cs | C# | mit | 3,134 |
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
#define ADJACENT_DIGITS_NUM 4
#define ROW_COL_LENGTH 20
int digits[ROW_COL_LENGTH][ROW_COL_LENGTH] = {
{ 8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8 },
{ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0 },
{ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65 },
{ 52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91 },
{ 22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80 },
{ 24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50 },
{ 32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70 },
{ 67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21 },
{ 24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72 },
{ 21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95 },
{ 78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92 },
{ 16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57 },
{ 86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58 },
{ 19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40 },
{ 4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66 },
{ 88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69 },
{ 4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36 },
{ 20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16 },
{ 20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54 },
{ 1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48 }
};
int main(int argc, char** argv) {
unsigned long highestProduct = 0;
int startI = 0, startJ = 0;
for (int i = 0; i < ROW_COL_LENGTH; i++) {
for (int j = 0; j < ROW_COL_LENGTH; j++) {
if (i < ROW_COL_LENGTH - ADJACENT_DIGITS_NUM &&
j < ROW_COL_LENGTH - ADJACENT_DIGITS_NUM) {
unsigned long productDiagonalLeftToRight =
digits[i][j] *
digits[i + 1][j + 1] *
digits[i + 2][j + 2] *
digits[i + 3][j + 3];
unsigned long productDiagonalRightToLeft =
digits[i][j + 3] *
digits[i + 1][j + 2] *
digits[i + 2][j + 1] *
digits[i + 3][j];
if (productDiagonalLeftToRight > highestProduct) {
highestProduct = productDiagonalLeftToRight;
startI = i;
startJ = j;
}
if (productDiagonalRightToLeft > highestProduct) {
highestProduct = productDiagonalRightToLeft;
startI = i;
startJ = j;
}
}
if (i < ROW_COL_LENGTH - ADJACENT_DIGITS_NUM) {
unsigned long productAcross =
digits[i][j] * digits[i + 1][j] * digits[i + 2][j] * digits[i + 3][j];
if (productAcross > highestProduct) {
highestProduct = productAcross;
startI = i;
startJ = j;
}
}
if (j < ROW_COL_LENGTH - ADJACENT_DIGITS_NUM) {
unsigned long productDown =
digits[i][j] * digits[i][j + 1] * digits[i][j + 2] * digits[i][j + 3];
if (productDown > highestProduct) {
highestProduct = productDown;
startI = i;
startJ = j;
}
}
}
}
cout << "Highest product: " << highestProduct << endl;
cout << "Start at: " << startI << ", " << startJ << endl;
return 0;
}
| DouglasSherk/project-euler | 11.cpp | C++ | mit | 3,679 |
package event
type Event interface {
// IsCancellable returns true if the current event may be cancelled.
IsCancellable() bool
// SetCancelled makes the event cancelled or not. The value is taken
// into account only if the event is cancellable - you can determine
// it by reading its documentation or calling the IsCancellable function.
SetCancelled(bool)
// IsCancelled returns true if the current event will be cancelled.
// (If the event is cancellable.)
IsCancelled() bool
}
| olsdavis/goelan | plugin/event/event.go | GO | mit | 493 |
<?php
setcookie('accessToken', ' ', time()-3600);
$_SESSION['REQUEST_URI'] = $_SERVER['REQUEST_URI'];
$parts = parse_url($_SERVER['REQUEST_URI']);
$context = substr($parts["path"], 0, strrpos($parts["path"], "/"));
header("Location: " . $context . "/login.html");
exit();
?> | coder229/php-sandbox | logout.php | PHP | mit | 299 |
<?php
namespace Behat\Mink\Tests\Driver\Basic;
use Behat\Mink\Tests\Driver\TestCase;
class BasicAuthTest extends TestCase
{
/**
* @dataProvider setBasicAuthDataProvider
*/
public function testSetBasicAuth($user, $pass, $pageText)
{
$session = $this->getSession();
$session->setBasicAuth($user, $pass);
$session->visit($this->pathTo('/basic_auth.php'));
$this->assertStringContainsString($pageText, $session->getPage()->getContent());
}
public function setBasicAuthDataProvider()
{
return array(
array('mink-user', 'mink-password', 'is authenticated'),
array('', '', 'is not authenticated'),
);
}
public function testBasicAuthInUrl()
{
$session = $this->getSession();
$url = $this->pathTo('/basic_auth.php');
$url = str_replace('://', '://mink-user:mink-password@', $url);
$session->visit($url);
$this->assertStringContainsString('is authenticated', $session->getPage()->getContent());
$url = $this->pathTo('/basic_auth.php');
$url = str_replace('://', '://mink-user:wrong@', $url);
$session->visit($url);
$this->assertStringContainsString('is not authenticated', $session->getPage()->getContent());
}
public function testResetBasicAuth()
{
$session = $this->getSession();
$session->setBasicAuth('mink-user', 'mink-password');
$session->visit($this->pathTo('/basic_auth.php'));
$this->assertStringContainsString('is authenticated', $session->getPage()->getContent());
$session->setBasicAuth(false);
$session->visit($this->pathTo('/headers.php'));
$this->assertStringNotContainsString('PHP_AUTH_USER', $session->getPage()->getContent());
}
public function testResetWithBasicAuth()
{
$session = $this->getSession();
$session->setBasicAuth('mink-user', 'mink-password');
$session->visit($this->pathTo('/basic_auth.php'));
$this->assertStringContainsString('is authenticated', $session->getPage()->getContent());
$session->reset();
$session->visit($this->pathTo('/headers.php'));
$this->assertStringNotContainsString('PHP_AUTH_USER', $session->getPage()->getContent());
}
}
| minkphp/driver-testsuite | tests/Basic/BasicAuthTest.php | PHP | mit | 2,323 |
export default from './unview.container'
| fabienjuif/react-redux-codelab | src/components/TVShow/Episodes/Episode/UnView/index.js | JavaScript | mit | 41 |
package io.smartlogic.smartchat.hypermedia;
import com.fasterxml.jackson.annotation.JsonProperty;
public class HalSmsVerification {
@JsonProperty("verification_code")
private String verificationCode;
@JsonProperty("verification_phone_number")
private String verificationPhoneNumber;
public String getVerificationCode() {
return verificationCode;
}
public String getVerificationPhoneNumber() {
return verificationPhoneNumber;
}
}
| smartlogic/smartchat-android | SmartChat/src/main/java/io/smartlogic/smartchat/hypermedia/HalSmsVerification.java | Java | mit | 482 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ManualRevisionAPI.Models
{
public class Role
{
public int ID { get; set; }
public String RoleName { get; set; }
}
}
| Lindennerd/manual-revision | ManualRevision/ManualRevisionAPI/Models/UserRole.cs | C# | mit | 244 |
// jslint.js
// 2009-03-28
// TO DO: In ADsafe, make lib run only.
/*
Copyright (c) 2002 Douglas Crockford (www.JSLint.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
JSLINT is a global function. It takes two parameters.
var myResult = JSLINT(source, option);
The first parameter is either a string or an array of strings. If it is a
string, it will be split on '\n' or '\r'. If it is an array of strings, it
is assumed that each string represents one line. The source can be a
JavaScript text, or HTML text, or a Konfabulator text.
The second parameter is an optional object of options which control the
operation of JSLINT. Most of the options are booleans: They are all are
optional and have a default value of false.
If it checks out, JSLINT returns true. Otherwise, it returns false.
If false, you can inspect JSLINT.errors to find out the problems.
JSLINT.errors is an array of objects containing these members:
{
line : The line (relative to 0) at which the lint was found
character : The character (relative to 0) at which the lint was found
reason : The problem
evidence : The text line in which the problem occurred
raw : The raw message before the details were inserted
a : The first detail
b : The second detail
c : The third detail
d : The fourth detail
}
If a fatal error was found, a null will be the last element of the
JSLINT.errors array.
You can request a Function Report, which shows all of the functions
and the parameters and vars that they use. This can be used to find
implied global variables and other problems. The report is in HTML and
can be inserted in an HTML <body>.
var myReport = JSLINT.report(limited);
If limited is true, then the report will be limited to only errors.
*/
/*jslint
evil: true, nomen: false, onevar: false, regexp: false , strict: true
*/
/*global JSLINT*/
/*members "\b", "\t", "\n", "\f", "\r", "\"", "%", "(begin)",
"(breakage)", "(context)", "(error)", "(global)", "(identifier)",
"(line)", "(loopage)", "(name)", "(onevar)", "(params)", "(scope)",
"(verb)", ")", "++", "--", "\/", ADSAFE, Array, Boolean, COM, Canvas,
CustomAnimation, Date, Debug, E, Error, EvalError, FadeAnimation, Flash,
FormField, Frame, Function, HotKey, Image, JSON, LN10, LN2, LOG10E,
LOG2E, MAX_VALUE, MIN_VALUE, Math, MenuItem, MoveAnimation,
NEGATIVE_INFINITY, Number, Object, Option, PI, POSITIVE_INFINITY, Point,
RangeError, Rectangle, ReferenceError, RegExp, ResizeAnimation,
RotateAnimation, SQRT1_2, SQRT2, ScrollBar, String, Style, SyntaxError,
System, Text, TextArea, Timer, TypeError, URIError, URL, Web, Window,
XMLDOM, XMLHttpRequest, "\\", "]", a, abbr, acronym, active, address,
adsafe, after, alert, aliceblue, animator, antiquewhite, appleScript,
applet, apply, approved, aqua, aquamarine, area, arguments, arity,
autocomplete, azure, b, background, "background-attachment",
"background-color", "background-image", "background-position",
"background-repeat", base, bdo, beep, before, beige, big, bisque,
bitwise, black, blanchedalmond, block, blockquote, blue, blueviolet,
blur, body, border, "border-bottom", "border-bottom-color",
"border-bottom-style", "border-bottom-width", "border-collapse",
"border-color", "border-left", "border-left-color", "border-left-style",
"border-left-width", "border-right", "border-right-color",
"border-right-style", "border-right-width", "border-spacing",
"border-style", "border-top", "border-top-color", "border-top-style",
"border-top-width", "border-width", bottom, br, brown, browser,
burlywood, button, bytesToUIString, c, cadetblue, call, callee, caller,
canvas, cap, caption, "caption-side", cases, center, charAt, charCodeAt,
character, chartreuse, chocolate, chooseColor, chooseFile, chooseFolder,
cite, clear, clearInterval, clearTimeout, clip, close, closeWidget,
closed, cm, code, col, colgroup, color, comment, condition, confirm,
console, constructor, content, convertPathToHFS, convertPathToPlatform,
coral, cornflowerblue, cornsilk, "counter-increment", "counter-reset",
create, crimson, css, cursor, cyan, d, darkblue, darkcyan,
darkgoldenrod, darkgray, darkgreen, darkkhaki, darkmagenta,
darkolivegreen, darkorange, darkorchid, darkred, darksalmon,
darkseagreen, darkslateblue, darkslategray, darkturquoise, darkviolet,
dd, debug, decodeURI, decodeURIComponent, deeppink, deepskyblue,
defaultStatus, defineClass, del, deserialize, dfn, dimgray, dir,
direction, display, div, dl, document, dodgerblue, dt, else, em, embed,
empty, "empty-cells", encodeURI, encodeURIComponent, entityify, eqeqeq,
errors, escape, eval, event, evidence, evil, ex, exec, exps, fieldset,
filesystem, firebrick, first, "first-child", "first-letter",
"first-line", float, floor, floralwhite, focus, focusWidget, font,
"font-face", "font-family", "font-size", "font-size-adjust",
"font-stretch", "font-style", "font-variant", "font-weight",
forestgreen, forin, form, fragment, frame, frames, frameset, from,
fromCharCode, fuchsia, fud, funct, function, g, gainsboro, gc,
getComputedStyle, ghostwhite, gold, goldenrod, gray, green, greenyellow,
h1, h2, h3, h4, h5, h6, hasOwnProperty, head, height, help, history,
honeydew, hotpink, hover, hr, html, i, iTunes, id, identifier, iframe,
img, immed, import, in, include, indent, indexOf, indianred, indigo,
init, input, ins, isAlpha, isApplicationRunning, isDigit, isFinite,
isNaN, ivory, join, kbd, khaki, konfabulatorVersion, label, labelled,
lang, lavender, lavenderblush, lawngreen, laxbreak, lbp, led, left,
legend, lemonchiffon, length, "letter-spacing", li, lib, lightblue,
lightcoral, lightcyan, lightgoldenrodyellow, lightgreen, lightpink,
lightsalmon, lightseagreen, lightskyblue, lightslategray,
lightsteelblue, lightyellow, lime, limegreen, line, "line-height",
linen, link, "list-style", "list-style-image", "list-style-position",
"list-style-type", load, loadClass, location, log, m, magenta, map,
margin, "margin-bottom", "margin-left", "margin-right", "margin-top",
"marker-offset", maroon, match, "max-height", "max-width", md5, media,
mediumaquamarine, mediumblue, mediumorchid, mediumpurple,
mediumseagreen, mediumslateblue, mediumspringgreen, mediumturquoise,
mediumvioletred, menu, message, meta, midnightblue, "min-height",
"min-width", mintcream, mistyrose, mm, moccasin, moveBy, moveTo, name,
navajowhite, navigator, navy, new, newcap, noframes, nomen, noscript,
nud, object, ol, oldlace, olive, olivedrab, on, onblur, onerror, onevar,
onfocus, onload, onresize, onunload, opacity, open, openURL, opener,
opera, optgroup, option, orange, orangered, orchid, outer, outline,
"outline-color", "outline-style", "outline-width", overflow, p, padding,
"padding-bottom", "padding-left", "padding-right", "padding-top", page,
palegoldenrod, palegreen, paleturquoise, palevioletred, papayawhip,
param, parent, parseFloat, parseInt, passfail, pc, peachpuff, peru,
pink, play, plum, plusplus, pop, popupMenu, position, powderblue, pre,
predef, preferenceGroups, preferences, print, prompt, prototype, pt,
purple, push, px, q, quit, quotes, random, range, raw, reach, readFile,
readUrl, reason, red, regexp, reloadWidget, replace, report, reserved,
resizeBy, resizeTo, resolvePath, resumeUpdates, rhino, right, rosybrown,
royalblue, runCommand, runCommandInBg, saddlebrown, safe, salmon, samp,
sandybrown, saveAs, savePreferences, screen, script, scroll, scrollBy,
scrollTo, seagreen, seal, search, seashell, select, self, serialize,
setInterval, setTimeout, shift, showWidgetPreferences, sidebar, sienna,
silver, skyblue, slateblue, slategray, sleep, slice, small, snow, sort,
span, spawn, speak, split, springgreen, src, status, steelblue, strict,
strong, style, styleproperty, sub, substr, sup, supplant,
suppressUpdates, sync, system, table, "table-layout", tan, tbody, td,
teal, tellWidget, test, "text-align", "text-decoration", "text-indent",
"text-shadow", "text-transform", textarea, tfoot, th, thead, thistle,
title, toLowerCase, toString, toUpperCase, toint32, token, tomato, top,
tr, tt, turquoise, type, u, ul, undef, unescape, "unicode-bidi",
unwatch, updateNow, value, valueOf, var, version, "vertical-align",
violet, visibility, visited, watch, wheat, white, "white-space",
whitesmoke, widget, width, window, "word-spacing", yahooCheckLogin,
yahooLogin, yahooLogout, yellow, yellowgreen, "z-index"
*/
// We build the application inside a function so that we produce only a single
// global variable. The function will be invoked, its return value is the JSLINT
// application itself.
"use strict";
JSLINT = (function () {
var adsafe_id, // The widget's ADsafe id.
adsafe_may, // The widget may load approved scripts.
adsafe_went, // ADSAFE.go has been called.
anonname, // The guessed name for anonymous functions.
approved, // ADsafe approved urls.
atrule = {
'import' : true,
media : true,
'font-face': true,
page : true
},
badbreak = {
')': true,
']': true,
'++': true,
'--': true
},
// These are members that should not be permitted in third party ads.
banned = { // the member names that ADsafe prohibits.
apply : true,
'arguments' : true,
call : true,
callee : true,
caller : true,
constructor : true,
'eval' : true,
prototype : true,
unwatch : true,
valueOf : true,
watch : true
},
// These are the JSLint boolean options.
boolOptions = {
adsafe : true, // if ADsafe should be enforced
bitwise : true, // if bitwise operators should not be allowed
browser : true, // if the standard browser globals should be predefined
cap : true, // if upper case HTML should be allowed
css : true, // if CSS workarounds should be tolerated
debug : true, // if debugger statements should be allowed
eqeqeq : true, // if === should be required
evil : true, // if eval should be allowed
forin : true, // if for in statements must filter
fragment : true, // if HTML fragments should be allowed
immed : true, // if immediate invocations must be wrapped in parens
laxbreak : true, // if line breaks should not be checked
newcap : true, // if constructor names must be capitalized
nomen : true, // if names should be checked
on : true, // if HTML event handlers should be allowed
onevar : true, // if only one var statement per function should be allowed
passfail : true, // if the scan should stop on first error
plusplus : true, // if increment/decrement should not be allowed
regexp : true, // if the . should not be allowed in regexp literals
rhino : true, // if the Rhino environment globals should be predefined
undef : true, // if variables should be declared before used
safe : true, // if use of some browser features should be restricted
sidebar : true, // if the System object should be predefined
strict : true, // require the "use strict"; pragma
sub : true, // if all forms of subscript notation are tolerated
white : true, // if strict whitespace rules apply
widget : true // if the Yahoo Widgets globals should be predefined
},
// browser contains a set of global names which are commonly provided by a
// web browser environment.
browser = {
alert : true,
blur : true,
clearInterval : true,
clearTimeout : true,
close : true,
closed : true,
confirm : true,
console : true,
Debug : true,
defaultStatus : true,
document : true,
event : true,
focus : true,
frames : true,
getComputedStyle: true,
history : true,
Image : true,
length : true,
location : true,
moveBy : true,
moveTo : true,
name : true,
navigator : true,
onblur : true,
onerror : true,
onfocus : true,
onload : true,
onresize : true,
onunload : true,
open : true,
opener : true,
opera : true,
Option : true,
parent : true,
print : true,
prompt : true,
resizeBy : true,
resizeTo : true,
screen : true,
scroll : true,
scrollBy : true,
scrollTo : true,
self : true,
setInterval : true,
setTimeout : true,
status : true,
top : true,
window : true,
XMLHttpRequest : true
},
cssAttributeData,
cssAny,
cssColorData = {
"aliceblue": true,
"antiquewhite": true,
"aqua": true,
"aquamarine": true,
"azure": true,
"beige": true,
"bisque": true,
"black": true,
"blanchedalmond": true,
"blue": true,
"blueviolet": true,
"brown": true,
"burlywood": true,
"cadetblue": true,
"chartreuse": true,
"chocolate": true,
"coral": true,
"cornflowerblue": true,
"cornsilk": true,
"crimson": true,
"cyan": true,
"darkblue": true,
"darkcyan": true,
"darkgoldenrod": true,
"darkgray": true,
"darkgreen": true,
"darkkhaki": true,
"darkmagenta": true,
"darkolivegreen": true,
"darkorange": true,
"darkorchid": true,
"darkred": true,
"darksalmon": true,
"darkseagreen": true,
"darkslateblue": true,
"darkslategray": true,
"darkturquoise": true,
"darkviolet": true,
"deeppink": true,
"deepskyblue": true,
"dimgray": true,
"dodgerblue": true,
"firebrick": true,
"floralwhite": true,
"forestgreen": true,
"fuchsia": true,
"gainsboro": true,
"ghostwhite": true,
"gold": true,
"goldenrod": true,
"gray": true,
"green": true,
"greenyellow": true,
"honeydew": true,
"hotpink": true,
"indianred": true,
"indigo": true,
"ivory": true,
"khaki": true,
"lavender": true,
"lavenderblush": true,
"lawngreen": true,
"lemonchiffon": true,
"lightblue": true,
"lightcoral": true,
"lightcyan": true,
"lightgoldenrodyellow": true,
"lightgreen": true,
"lightpink": true,
"lightsalmon": true,
"lightseagreen": true,
"lightskyblue": true,
"lightslategray": true,
"lightsteelblue": true,
"lightyellow": true,
"lime": true,
"limegreen": true,
"linen": true,
"magenta": true,
"maroon": true,
"mediumaquamarine": true,
"mediumblue": true,
"mediumorchid": true,
"mediumpurple": true,
"mediumseagreen": true,
"mediumslateblue": true,
"mediumspringgreen": true,
"mediumturquoise": true,
"mediumvioletred": true,
"midnightblue": true,
"mintcream": true,
"mistyrose": true,
"moccasin": true,
"navajowhite": true,
"navy": true,
"oldlace": true,
"olive": true,
"olivedrab": true,
"orange": true,
"orangered": true,
"orchid": true,
"palegoldenrod": true,
"palegreen": true,
"paleturquoise": true,
"palevioletred": true,
"papayawhip": true,
"peachpuff": true,
"peru": true,
"pink": true,
"plum": true,
"powderblue": true,
"purple": true,
"red": true,
"rosybrown": true,
"royalblue": true,
"saddlebrown": true,
"salmon": true,
"sandybrown": true,
"seagreen": true,
"seashell": true,
"sienna": true,
"silver": true,
"skyblue": true,
"slateblue": true,
"slategray": true,
"snow": true,
"springgreen": true,
"steelblue": true,
"tan": true,
"teal": true,
"thistle": true,
"tomato": true,
"turquoise": true,
"violet": true,
"wheat": true,
"white": true,
"whitesmoke": true,
"yellow": true,
"yellowgreen": true
},
cssBorderStyle,
cssLengthData = {
'%': true,
'cm': true,
'em': true,
'ex': true,
'in': true,
'mm': true,
'pc': true,
'pt': true,
'px': true
},
escapes = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'/' : '\\/',
'\\': '\\\\'
},
funct, // The current function
functions, // All of the functions
global, // The global scope
htmltag = {
a: {},
abbr: {},
acronym: {},
address: {},
applet: {},
area: {empty: true, parent: ' map '},
b: {},
base: {empty: true, parent: ' head '},
bdo: {},
big: {},
blockquote: {},
body: {parent: ' html noframes '},
br: {empty: true},
button: {},
canvas: {parent: ' body p div th td '},
caption: {parent: ' table '},
center: {},
cite: {},
code: {},
col: {empty: true, parent: ' table colgroup '},
colgroup: {parent: ' table '},
dd: {parent: ' dl '},
del: {},
dfn: {},
dir: {},
div: {},
dl: {},
dt: {parent: ' dl '},
em: {},
embed: {},
fieldset: {},
font: {},
form: {},
frame: {empty: true, parent: ' frameset '},
frameset: {parent: ' html frameset '},
h1: {},
h2: {},
h3: {},
h4: {},
h5: {},
h6: {},
head: {parent: ' html '},
html: {parent: '*'},
hr: {empty: true},
i: {},
iframe: {},
img: {empty: true},
input: {empty: true},
ins: {},
kbd: {},
label: {},
legend: {parent: ' fieldset '},
li: {parent: ' dir menu ol ul '},
link: {empty: true, parent: ' head '},
map: {},
menu: {},
meta: {empty: true, parent: ' head noframes noscript '},
noframes: {parent: ' html body '},
noscript: {parent: ' body head noframes '},
object: {},
ol: {},
optgroup: {parent: ' select '},
option: {parent: ' optgroup select '},
p: {},
param: {empty: true, parent: ' applet object '},
pre: {},
q: {},
samp: {},
script: {empty: true, parent: ' body div frame head iframe p pre span '},
select: {},
small: {},
span: {},
strong: {},
style: {parent: ' head ', empty: true},
sub: {},
sup: {},
table: {},
tbody: {parent: ' table '},
td: {parent: ' tr '},
textarea: {},
tfoot: {parent: ' table '},
th: {parent: ' tr '},
thead: {parent: ' table '},
title: {parent: ' head '},
tr: {parent: ' table tbody thead tfoot '},
tt: {},
u: {},
ul: {},
'var': {}
},
ids, // HTML ids
implied, // Implied globals
inblock,
indent,
jsonmode,
lines,
lookahead,
member,
membersOnly,
nexttoken,
noreach,
option,
predefined, // Global variables defined by option
prereg,
prevtoken,
pseudorule = {
'first-child': true,
link : true,
visited : true,
hover : true,
active : true,
focus : true,
lang : true,
'first-letter' : true,
'first-line' : true,
before : true,
after : true
},
rhino = {
defineClass : true,
deserialize : true,
gc : true,
help : true,
load : true,
loadClass : true,
print : true,
quit : true,
readFile : true,
readUrl : true,
runCommand : true,
seal : true,
serialize : true,
spawn : true,
sync : true,
toint32 : true,
version : true
},
scope, // The current scope
sidebar = {
System : true
},
src,
stack,
// standard contains the global names that are provided by the
// ECMAScript standard.
standard = {
Array : true,
Boolean : true,
Date : true,
decodeURI : true,
decodeURIComponent : true,
encodeURI : true,
encodeURIComponent : true,
Error : true,
'eval' : true,
EvalError : true,
Function : true,
isFinite : true,
isNaN : true,
JSON : true,
Math : true,
Number : true,
Object : true,
parseInt : true,
parseFloat : true,
RangeError : true,
ReferenceError : true,
RegExp : true,
String : true,
SyntaxError : true,
TypeError : true,
URIError : true
},
standard_member = {
E : true,
LN2 : true,
LN10 : true,
LOG2E : true,
LOG10E : true,
PI : true,
SQRT1_2 : true,
SQRT2 : true,
MAX_VALUE : true,
MIN_VALUE : true,
NEGATIVE_INFINITY : true,
POSITIVE_INFINITY : true
},
syntax = {},
tab,
token,
urls,
warnings,
// widget contains the global names which are provided to a Yahoo
// (fna Konfabulator) widget.
widget = {
alert : true,
animator : true,
appleScript : true,
beep : true,
bytesToUIString : true,
Canvas : true,
chooseColor : true,
chooseFile : true,
chooseFolder : true,
closeWidget : true,
COM : true,
convertPathToHFS : true,
convertPathToPlatform : true,
CustomAnimation : true,
escape : true,
FadeAnimation : true,
filesystem : true,
Flash : true,
focusWidget : true,
form : true,
FormField : true,
Frame : true,
HotKey : true,
Image : true,
include : true,
isApplicationRunning : true,
iTunes : true,
konfabulatorVersion : true,
log : true,
md5 : true,
MenuItem : true,
MoveAnimation : true,
openURL : true,
play : true,
Point : true,
popupMenu : true,
preferenceGroups : true,
preferences : true,
print : true,
prompt : true,
random : true,
Rectangle : true,
reloadWidget : true,
ResizeAnimation : true,
resolvePath : true,
resumeUpdates : true,
RotateAnimation : true,
runCommand : true,
runCommandInBg : true,
saveAs : true,
savePreferences : true,
screen : true,
ScrollBar : true,
showWidgetPreferences : true,
sleep : true,
speak : true,
Style : true,
suppressUpdates : true,
system : true,
tellWidget : true,
Text : true,
TextArea : true,
Timer : true,
unescape : true,
updateNow : true,
URL : true,
Web : true,
widget : true,
Window : true,
XMLDOM : true,
XMLHttpRequest : true,
yahooCheckLogin : true,
yahooLogin : true,
yahooLogout : true
},
// xmode is used to adapt to the exceptions in html parsing.
// It can have these states:
// false .js script file
// html
// outer
// script
// style
// scriptstring
// styleproperty
xmode,
xquote,
// unsafe comment or string
ax = /@cc|<\/?|script|\]*s\]|<\s*!|</i,
// unsafe characters that are silently deleted by one or more browsers
cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/,
// token
tx = /^\s*([(){}\[.,:;'"~\?\]#@]|==?=?|\/(\*(global|extern|jslint|member|members)?|=|\/)?|\*[\/=]?|\+[+=]?|-[\-=]?|%=?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=!]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/,
// html token
hx = /^\s*(['"=>\/&#]|<(?:\/|\!(?:--)?)?|[a-zA-Z][a-zA-Z0-9_\-]*|[0-9]+|--|.)/,
// outer html token
ox = /[>&]|<[\/!]?|--/,
// star slash
lx = /\*\/|\/\*/,
// identifier
ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/,
// javascript url
jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i,
// url badness
ux = /&|\+|\u00AD|\.\.|\/\*|%[^;]|base64|url|expression|data|mailto/i,
// style
sx = /^\s*([{:#*%.=,>+\[\]@()"';*]|[a-zA-Z0-9_][a-zA-Z0-9_\-]*|<\/|\/\*)/,
ssx = /^\s*([@#!"'};:\-\/%.=,+\[\]()*_]|[a-zA-Z][a-zA-Z0-9._\-]*|\d+(?:\.\d+)?|<\/)/,
// query characters
qx = /[\[\]\/\\"'*<>.&:(){}+=#_]/,
// query characters for ids
dx = /[\[\]\/\\"'*<>.&:(){}+=#]/,
rx = {
outer: hx,
html: hx,
style: sx,
styleproperty: ssx
};
function F() {}
if (typeof Object.create !== 'function') {
Object.create = function (o) {
F.prototype = o;
return new F();
};
}
function combine(t, o) {
var n;
for (n in o) {
if (o.hasOwnProperty(n)) {
t[n] = o[n];
}
}
}
String.prototype.entityify = function () {
return this.
replace(/&/g, '&').
replace(/</g, '<').
replace(/>/g, '>');
};
String.prototype.isAlpha = function () {
return (this >= 'a' && this <= 'z\uffff') ||
(this >= 'A' && this <= 'Z\uffff');
};
String.prototype.isDigit = function () {
return (this >= '0' && this <= '9');
};
String.prototype.supplant = function (o) {
return this.replace(/\{([^{}]*)\}/g, function (a, b) {
var r = o[b];
return typeof r === 'string' || typeof r === 'number' ? r : a;
});
};
String.prototype.name = function () {
// If the string looks like an identifier, then we can return it as is.
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.
if (ix.test(this)) {
return this;
}
if (/[&<"\/\\\x00-\x1f]/.test(this)) {
return '"' + this.replace(/[&<"\/\\\x00-\x1f]/g, function (a) {
var c = escapes[a];
if (c) {
return c;
}
c = a.charCodeAt();
return '\\u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
}) + '"';
}
return '"' + this + '"';
};
function assume() {
if (!option.safe) {
if (option.rhino) {
combine(predefined, rhino);
}
if (option.browser || option.sidebar) {
combine(predefined, browser);
}
if (option.sidebar) {
combine(predefined, sidebar);
}
if (option.widget) {
combine(predefined, widget);
}
}
}
// Produce an error warning.
function quit(m, l, ch) {
throw {
name: 'JSLintError',
line: l,
character: ch,
message: m + " (" + Math.floor((l / lines.length) * 100) +
"% scanned)."
};
}
function warning(m, t, a, b, c, d) {
var ch, l, w;
t = t || nexttoken;
if (t.id === '(end)') { // `~
t = token;
}
l = t.line || 0;
ch = t.from || 0;
w = {
id: '(error)',
raw: m,
evidence: lines[l] || '',
line: l,
character: ch,
a: a,
b: b,
c: c,
d: d
};
w.reason = m.supplant(w);
JSLINT.errors.push(w);
if (option.passfail) {
quit('Stopping. ', l, ch);
}
warnings += 1;
if (warnings === 50) {
quit("Too many errors.", l, ch);
}
return w;
}
function warningAt(m, l, ch, a, b, c, d) {
return warning(m, {
line: l,
from: ch
}, a, b, c, d);
}
function error(m, t, a, b, c, d) {
var w = warning(m, t, a, b, c, d);
quit("Stopping, unable to continue.", w.line, w.character);
}
function errorAt(m, l, ch, a, b, c, d) {
return error(m, {
line: l,
from: ch
}, a, b, c, d);
}
// lexical analysis
var lex = (function lex() {
var character, from, line, s;
// Private lex methods
function nextLine() {
var at;
line += 1;
if (line >= lines.length) {
return false;
}
character = 0;
s = lines[line].replace(/\t/g, tab);
at = s.search(cx);
if (at >= 0) {
warningAt("Unsafe character.", line, at);
}
return true;
}
// Produce a token object. The token inherits from a syntax symbol.
function it(type, value) {
var i, t;
if (type === '(color)') {
t = {type: type};
} else if (type === '(punctuator)' ||
(type === '(identifier)' && syntax.hasOwnProperty(value))) {
t = syntax[value] || syntax['(error)'];
// Mozilla bug workaround.
if (!t.id) {
t = syntax[type];
}
} else {
t = syntax[type];
}
t = Object.create(t);
if (type === '(string)' || type === '(range)') {
if (jx.test(value)) {
warningAt("Script URL.", line, from);
}
}
if (type === '(identifier)') {
t.identifier = true;
if (option.nomen && value.charAt(0) === '_') {
warningAt("Unexpected '_' in '{a}'.", line, from, value);
}
}
t.value = value;
t.line = line;
t.character = character;
t.from = from;
i = t.id;
if (i !== '(endline)') {
prereg = i &&
(('(,=:[!&|?{};'.indexOf(i.charAt(i.length - 1)) >= 0) ||
i === 'return');
}
return t;
}
// Public lex methods
return {
init: function (source) {
if (typeof source === 'string') {
lines = source.
replace(/\r\n/g, '\n').
replace(/\r/g, '\n').
split('\n');
} else {
lines = source;
}
line = -1;
nextLine();
from = 0;
},
range: function (begin, end) {
var c, value = '';
from = character;
if (s.charAt(0) !== begin) {
errorAt("Expected '{a}' and instead saw '{b}'.",
line, character, begin, s.charAt(0));
}
for (;;) {
s = s.slice(1);
character += 1;
c = s.charAt(0);
switch (c) {
case '':
errorAt("Missing '{a}'.", line, character, c);
break;
case end:
s = s.slice(1);
character += 1;
return it('(range)', value);
case xquote:
case '\\':
case '\'':
case '"':
warningAt("Unexpected '{a}'.", line, character, c);
}
value += c;
}
},
// token -- this is called by advance to get the next token.
token: function () {
var b, c, captures, d, depth, high, i, l, low, q, t;
function match(x) {
var r = x.exec(s), r1;
if (r) {
l = r[0].length;
r1 = r[1];
c = r1.charAt(0);
s = s.substr(l);
character += l;
from = character - r1.length;
return r1;
}
}
function string(x) {
var c, j, r = '';
if (jsonmode && x !== '"') {
warningAt("Strings must use doublequote.",
line, character);
}
if (xquote === x || (xmode === 'scriptstring' && !xquote)) {
return it('(punctuator)', x);
}
function esc(n) {
var i = parseInt(s.substr(j + 1, n), 16);
j += n;
if (i >= 32 && i <= 126 &&
i !== 34 && i !== 92 && i !== 39) {
warningAt("Unnecessary escapement.", line, character);
}
character += n;
c = String.fromCharCode(i);
}
j = 0;
for (;;) {
while (j >= s.length) {
j = 0;
if (xmode !== 'html' || !nextLine()) {
errorAt("Unclosed string.", line, from);
}
}
c = s.charAt(j);
if (c === x) {
character += 1;
s = s.substr(j + 1);
return it('(string)', r, x);
}
if (c < ' ') {
if (c === '\n' || c === '\r') {
break;
}
warningAt("Control character in string: {a}.",
line, character + j, s.slice(0, j));
} else if (c === xquote) {
warningAt("Bad HTML string", line, character + j);
} else if (c === '<') {
if (option.safe && xmode === 'html') {
warningAt("ADsafe string violation.",
line, character + j);
} else if (s.charAt(j + 1) === '/' && (xmode || option.safe)) {
warningAt("Expected '<\\/' and instead saw '</'.", line, character);
} else if (s.charAt(j + 1) === '!' && (xmode || option.safe)) {
warningAt("Unexpected '<!' in a string.", line, character);
}
} else if (c === '\\') {
if (xmode === 'html') {
if (option.safe) {
warningAt("ADsafe string violation.",
line, character + j);
}
} else if (xmode === 'styleproperty') {
j += 1;
character += 1;
c = s.charAt(j);
if (c !== x) {
warningAt("Escapement in style string.",
line, character + j);
}
} else {
j += 1;
character += 1;
c = s.charAt(j);
switch (c) {
case xquote:
warningAt("Bad HTML string", line,
character + j);
break;
case '\\':
case '\'':
case '"':
case '/':
break;
case 'b':
c = '\b';
break;
case 'f':
c = '\f';
break;
case 'n':
c = '\n';
break;
case 'r':
c = '\r';
break;
case 't':
c = '\t';
break;
case 'u':
esc(4);
break;
case 'v':
c = '\v';
break;
case 'x':
if (jsonmode) {
warningAt("Avoid \\x-.", line, character);
}
esc(2);
break;
default:
warningAt("Bad escapement.", line, character);
}
}
}
r += c;
character += 1;
j += 1;
}
}
for (;;) {
if (!s) {
return it(nextLine() ? '(endline)' : '(end)', '');
}
while (xmode === 'outer') {
i = s.search(ox);
if (i === 0) {
break;
} else if (i > 0) {
character += 1;
s = s.slice(i);
break;
} else {
if (!nextLine()) {
return it('(end)', '');
}
}
}
t = match(rx[xmode] || tx);
if (!t) {
if (xmode === 'html') {
return it('(error)', s.charAt(0));
} else {
t = '';
c = '';
while (s && s < '!') {
s = s.substr(1);
}
if (s) {
errorAt("Unexpected '{a}'.",
line, character, s.substr(0, 1));
}
}
} else {
// identifier
if (c.isAlpha() || c === '_' || c === '$') {
return it('(identifier)', t);
}
// number
if (c.isDigit()) {
if (xmode !== 'style' && !isFinite(Number(t))) {
warningAt("Bad number '{a}'.",
line, character, t);
}
if (xmode !== 'styleproperty' && s.substr(0, 1).isAlpha()) {
warningAt("Missing space after '{a}'.",
line, character, t);
}
if (c === '0') {
d = t.substr(1, 1);
if (d.isDigit()) {
if (token.id !== '.' && xmode !== 'styleproperty') {
warningAt("Don't use extra leading zeros '{a}'.",
line, character, t);
}
} else if (jsonmode && (d === 'x' || d === 'X')) {
warningAt("Avoid 0x-. '{a}'.",
line, character, t);
}
}
if (t.substr(t.length - 1) === '.') {
warningAt(
"A trailing decimal point can be confused with a dot '{a}'.",
line, character, t);
}
return it('(number)', t);
}
switch (t) {
// string
case '"':
case "'":
return string(t);
// // comment
case '//':
if (src || (xmode && xmode !== 'script')) {
warningAt("Unexpected comment.", line, character);
} else if (xmode === 'script' && /<\s*\//i.test(s)) {
warningAt("Unexpected <\/ in comment.", line, character);
} else if ((option.safe || xmode === 'script') && ax.test(s)) {
warningAt("Dangerous comment.", line, character);
}
s = '';
token.comment = true;
break;
// /* comment
case '/*':
if (src || (xmode && xmode !== 'script' && xmode !== 'style' && xmode !== 'styleproperty')) {
warningAt("Unexpected comment.", line, character);
}
if (option.safe && ax.test(s)) {
warningAt("ADsafe comment violation.", line, character);
}
for (;;) {
i = s.search(lx);
if (i >= 0) {
break;
}
if (!nextLine()) {
errorAt("Unclosed comment.", line, character);
} else {
if (option.safe && ax.test(s)) {
warningAt("ADsafe comment violation.", line, character);
}
}
}
character += i + 2;
if (s.substr(i, 1) === '/') {
errorAt("Nested comment.", line, character);
}
s = s.substr(i + 2);
token.comment = true;
break;
// /*global /*extern /*members /*jslint */
case '/*global':
case '/*extern':
case '/*members':
case '/*member':
case '/*jslint':
case '*/':
return {
value: t,
type: 'special',
line: line,
character: character,
from: from
};
case '':
break;
// /
case '/':
if (prereg) {
depth = 0;
captures = 0;
l = 0;
for (;;) {
b = true;
c = s.charAt(l);
l += 1;
switch (c) {
case '':
errorAt("Unclosed regular expression.", line, from);
return;
case '/':
if (depth > 0) {
warningAt("Unescaped '{a}'.", line, from + l, '/');
}
c = s.substr(0, l - 1);
q = {
g: true,
i: true,
m: true
};
while (q[s.charAt(l)] === true) {
q[s.charAt(l)] = false;
l += 1;
}
character += l;
s = s.substr(l);
return it('(regexp)', c);
case '\\':
c = s.charAt(l);
if (c < ' ') {
warningAt("Unexpected control character in regular expression.", line, from + l);
} else if (c === '<') {
warningAt("Unexpected escaped character '{a}' in regular expression.", line, from + l, c);
}
l += 1;
break;
case '(':
depth += 1;
b = false;
if (s.charAt(l) === '?') {
l += 1;
switch (s.charAt(l)) {
case ':':
case '=':
case '!':
l += 1;
break;
default:
warningAt("Expected '{a}' and instead saw '{b}'.", line, from + l, ':', s.charAt(l));
}
} else {
captures += 1;
}
break;
case ')':
if (depth === 0) {
warningAt("Unescaped '{a}'.", line, from + l, ')');
} else {
depth -= 1;
}
break;
case ' ':
q = 1;
while (s.charAt(l) === ' ') {
l += 1;
q += 1;
}
if (q > 1) {
warningAt("Spaces are hard to count. Use {{a}}.", line, from + l, q);
}
break;
case '[':
if (s.charAt(l) === '^') {
l += 1;
}
q = false;
klass: do {
c = s.charAt(l);
l += 1;
switch (c) {
case '[':
case '^':
warningAt("Unescaped '{a}'.", line, from + l, c);
q = true;
break;
case '-':
if (q) {
q = false;
} else {
warningAt("Unescaped '{a}'.", line, from + l, '-');
q = true;
}
break;
case ']':
if (!q) {
warningAt("Unescaped '{a}'.", line, from + l - 1, '-');
}
break klass;
case '\\':
c = s.charAt(l);
if (c < ' ') {
warningAt("Unexpected control character in regular expression.", line, from + l);
} else if (c === '<') {
warningAt("Unexpected escaped character '{a}' in regular expression.", line, from + l, c);
}
l += 1;
q = true;
break;
case '/':
warningAt("Unescaped '{a}'.", line, from + l - 1, '/');
q = true;
break;
case '<':
if (xmode === 'script') {
c = s.charAt(l);
if (c === '!' || c === '/') {
warningAt("HTML confusion in regular expression '<{a}'.", line, from + l, c);
}
}
q = true;
break;
default:
q = true;
}
} while (c);
break;
case '.':
if (option.regexp) {
warningAt("Unexpected '{a}'.", line, from + l, c);
}
break;
case ']':
case '?':
case '{':
case '}':
case '+':
case '*':
warningAt("Unescaped '{a}'.", line, from + l, c);
break;
case '<':
if (xmode === 'script') {
c = s.charAt(l);
if (c === '!' || c === '/') {
warningAt("HTML confusion in regular expression '<{a}'.", line, from + l, c);
}
}
}
if (b) {
switch (s.charAt(l)) {
case '?':
case '+':
case '*':
l += 1;
if (s.charAt(l) === '?') {
l += 1;
}
break;
case '{':
l += 1;
c = s.charAt(l);
if (c < '0' || c > '9') {
warningAt("Expected a number and instead saw '{a}'.", line, from + l, c);
}
l += 1;
low = +c;
for (;;) {
c = s.charAt(l);
if (c < '0' || c > '9') {
break;
}
l += 1;
low = +c + (low * 10);
}
high = low;
if (c === ',') {
l += 1;
high = Infinity;
c = s.charAt(l);
if (c >= '0' && c <= '9') {
l += 1;
high = +c;
for (;;) {
c = s.charAt(l);
if (c < '0' || c > '9') {
break;
}
l += 1;
high = +c + (high * 10);
}
}
}
if (s.charAt(l) !== '}') {
warningAt("Expected '{a}' and instead saw '{b}'.", line, from + l, '}', c);
} else {
l += 1;
}
if (s.charAt(l) === '?') {
l += 1;
}
if (low > high) {
warningAt("'{a}' should not be greater than '{b}'.", line, from + l, low, high);
}
}
}
}
c = s.substr(0, l - 1);
character += l;
s = s.substr(l);
return it('(regexp)', c);
}
return it('(punctuator)', t);
// punctuator
case '#':
if (xmode === 'html' || xmode === 'styleproperty') {
for (;;) {
c = s.charAt(0);
if ((c < '0' || c > '9') &&
(c < 'a' || c > 'f') &&
(c < 'A' || c > 'F')) {
break;
}
character += 1;
s = s.substr(1);
t += c;
}
if (t.length !== 4 && t.length !== 7) {
warningAt("Bad hex color '{a}'.", line,
from + l, t);
}
return it('(color)', t);
}
return it('(punctuator)', t);
default:
if (xmode === 'outer' && c === '&') {
character += 1;
s = s.substr(1);
for (;;) {
c = s.charAt(0);
character += 1;
s = s.substr(1);
if (c === ';') {
break;
}
if (!((c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'z') ||
c === '#')) {
errorAt("Bad entity", line, from + l,
character);
}
}
break;
}
return it('(punctuator)', t);
}
}
}
}
};
}());
function addlabel(t, type) {
if (t === 'hasOwnProperty') {
error("'hasOwnProperty' is a really bad name.");
}
if (option.safe && funct['(global)']) {
warning('ADsafe global: ' + t + '.', token);
}
// Define t in the current function in the current scope.
if (funct.hasOwnProperty(t)) {
warning(funct[t] === true ?
"'{a}' was used before it was defined." :
"'{a}' is already defined.",
nexttoken, t);
}
funct[t] = type;
if (type === 'label') {
scope[t] = funct;
} else if (funct['(global)']) {
global[t] = funct;
if (implied.hasOwnProperty(t)) {
warning("'{a}' was used before it was defined.", nexttoken, t);
delete implied[t];
}
} else {
funct['(scope)'][t] = funct;
}
}
function doOption() {
var b, obj, filter, o = nexttoken.value, t, v;
switch (o) {
case '*/':
error("Unbegun comment.");
break;
case '/*global':
case '/*extern':
if (option.safe) {
warning("ADsafe restriction.");
}
obj = predefined;
break;
case '/*members':
case '/*member':
o = '/*members';
if (!membersOnly) {
membersOnly = {};
}
obj = membersOnly;
break;
case '/*jslint':
if (option.safe) {
warning("ADsafe restriction.");
}
obj = option;
filter = boolOptions;
}
for (;;) {
t = lex.token();
if (t.id === ',') {
t = lex.token();
}
while (t.id === '(endline)') {
t = lex.token();
}
if (t.type === 'special' && t.value === '*/') {
break;
}
if (t.type !== '(string)' && t.type !== '(identifier)' &&
o !== '/*members') {
error("Bad option.", t);
}
if (filter) {
if (filter[t.value] !== true) {
error("Bad option.", t);
}
v = lex.token();
if (v.id !== ':') {
error("Expected '{a}' and instead saw '{b}'.",
t, ':', t.value);
}
v = lex.token();
if (v.value === 'true') {
b = true;
} else if (v.value === 'false') {
b = false;
} else {
error("Expected '{a}' and instead saw '{b}'.",
t, 'true', t.value);
}
} else {
b = true;
}
obj[t.value] = b;
}
if (filter) {
assume();
}
}
// We need a peek function. If it has an argument, it peeks that much farther
// ahead. It is used to distinguish
// for ( var i in ...
// from
// for ( var i = ...
function peek(p) {
var i = p || 0, j = 0, t;
while (j <= i) {
t = lookahead[j];
if (!t) {
t = lookahead[j] = lex.token();
}
j += 1;
}
return t;
}
// Produce the next token. It looks for programming errors.
function advance(id, t) {
var l;
switch (token.id) {
case '(number)':
if (nexttoken.id === '.') {
warning(
"A dot following a number can be confused with a decimal point.", token);
}
break;
case '-':
if (nexttoken.id === '-' || nexttoken.id === '--') {
warning("Confusing minusses.");
}
break;
case '+':
if (nexttoken.id === '+' || nexttoken.id === '++') {
warning("Confusing plusses.");
}
break;
}
if (token.type === '(string)' || token.identifier) {
anonname = token.value;
}
if (id && nexttoken.id !== id) {
if (t) {
if (nexttoken.id === '(end)') {
warning("Unmatched '{a}'.", t, t.id);
} else {
warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.",
nexttoken, id, t.id, t.line + 1, nexttoken.value);
}
} else if (nexttoken.type !== '(identifier)' ||
nexttoken.value !== id) {
warning("Expected '{a}' and instead saw '{b}'.",
nexttoken, id, nexttoken.value);
}
}
prevtoken = token;
token = nexttoken;
for (;;) {
nexttoken = lookahead.shift() || lex.token();
if (nexttoken.id === '(end)' || nexttoken.id === '(error)') {
return;
}
if (nexttoken.type === 'special') {
doOption();
} else {
if (nexttoken.id !== '(endline)') {
break;
}
l = !xmode && !option.laxbreak &&
(token.type === '(string)' || token.type === '(number)' ||
token.type === '(identifier)' || badbreak[token.id]);
}
}
if (!option.evil && nexttoken.value === 'eval') {
warning("eval is evil.", nexttoken);
}
if (l) {
switch (nexttoken.id) {
case '{':
case '}':
case ']':
case '.':
break;
case ')':
switch (token.id) {
case ')':
case '}':
case ']':
break;
default:
warning("Line breaking error '{a}'.", token, ')');
}
break;
default:
warning("Line breaking error '{a}'.",
token, token.value);
}
}
}
// This is the heart of JSLINT, the Pratt parser. In addition to parsing, it
// is looking for ad hoc lint patterns. We add to Pratt's model .fud, which is
// like nud except that it is only used on the first token of a statement.
// Having .fud makes it much easier to define JavaScript. I retained Pratt's
// nomenclature.
// .nud Null denotation
// .fud First null denotation
// .led Left denotation
// lbp Left binding power
// rbp Right binding power
// They are key to the parsing method called Top Down Operator Precedence.
function parse(rbp, initial) {
var left, o;
if (nexttoken.id === '(end)') {
error("Unexpected early end of program.", token);
}
advance();
if (option.safe && predefined[token.value] === true &&
(nexttoken.id !== '(' && nexttoken.id !== '.')) {
warning('ADsafe violation.', token);
}
if (initial) {
anonname = 'anonymous';
funct['(verb)'] = token.value;
}
if (initial === true && token.fud) {
left = token.fud();
} else {
if (token.nud) {
o = token.exps;
left = token.nud();
} else {
if (nexttoken.type === '(number)' && token.id === '.') {
warning(
"A leading decimal point can be confused with a dot: '.{a}'.",
token, nexttoken.value);
advance();
return token;
} else {
error("Expected an identifier and instead saw '{a}'.",
token, token.id);
}
}
while (rbp < nexttoken.lbp) {
o = nexttoken.exps;
advance();
if (token.led) {
left = token.led(left);
} else {
error("Expected an operator and instead saw '{a}'.",
token, token.id);
}
}
if (initial && !o) {
warning(
"Expected an assignment or function call and instead saw an expression.",
token);
}
}
return left;
}
// Functions for conformance of style.
function abut(left, right) {
left = left || token;
right = right || nexttoken;
if (left.line !== right.line || left.character !== right.from) {
warning("Unexpected space after '{a}'.", right, left.value);
}
}
function adjacent(left, right) {
left = left || token;
right = right || nexttoken;
if (option.white || xmode === 'styleproperty' || xmode === 'style') {
if (left.character !== right.from && left.line === right.line) {
warning("Unexpected space after '{a}'.", right, left.value);
}
}
}
function nospace(left, right) {
left = left || token;
right = right || nexttoken;
if (option.white && !left.comment) {
if (left.line === right.line) {
adjacent(left, right);
}
}
}
function nonadjacent(left, right) {
left = left || token;
right = right || nexttoken;
if (option.white) {
if (left.character === right.from) {
warning("Missing space after '{a}'.",
nexttoken, left.value);
}
}
}
function indentation(bias) {
var i;
if (option.white && nexttoken.id !== '(end)') {
i = indent + (bias || 0);
if (nexttoken.from !== i) {
warning("Expected '{a}' to have an indentation of {b} instead of {c}.",
nexttoken, nexttoken.value, i, nexttoken.from);
}
}
}
function nolinebreak(t) {
if (t.line !== nexttoken.line) {
warning("Line breaking error '{a}'.", t, t.id);
}
}
// Parasitic constructors for making the symbols that will be inherited by
// tokens.
function symbol(s, p) {
var x = syntax[s];
if (!x || typeof x !== 'object') {
syntax[s] = x = {
id: s,
lbp: p,
value: s
};
}
return x;
}
function delim(s) {
return symbol(s, 0);
}
function stmt(s, f) {
var x = delim(s);
x.identifier = x.reserved = true;
x.fud = f;
return x;
}
function blockstmt(s, f) {
var x = stmt(s, f);
x.block = true;
return x;
}
function reserveName(x) {
var c = x.id.charAt(0);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
x.identifier = x.reserved = true;
}
return x;
}
function prefix(s, f) {
var x = symbol(s, 150);
reserveName(x);
x.nud = (typeof f === 'function') ? f : function () {
if (option.plusplus && (this.id === '++' || this.id === '--')) {
warning("Unexpected use of '{a}'.", this, this.id);
}
this.right = parse(150);
this.arity = 'unary';
return this;
};
return x;
}
function type(s, f) {
var x = delim(s);
x.type = s;
x.nud = f;
return x;
}
function reserve(s, f) {
var x = type(s, f);
x.identifier = x.reserved = true;
return x;
}
function reservevar(s, v) {
return reserve(s, function () {
if (this.id === 'this') {
if (option.safe) {
warning("ADsafe violation.", this);
}
}
return this;
});
}
function infix(s, f, p) {
var x = symbol(s, p);
reserveName(x);
x.led = (typeof f === 'function') ? f : function (left) {
nonadjacent(prevtoken, token);
nonadjacent(token, nexttoken);
this.left = left;
this.right = parse(p);
return this;
};
return x;
}
function relation(s, f) {
var x = symbol(s, 100);
x.led = function (left) {
nonadjacent(prevtoken, token);
nonadjacent(token, nexttoken);
var right = parse(100);
if ((left && left.id === 'NaN') || (right && right.id === 'NaN')) {
warning("Use the isNaN function to compare with NaN.", this);
} else if (f) {
f.apply(this, [left, right]);
}
this.left = left;
this.right = right;
return this;
};
return x;
}
function isPoorRelation(node) {
return (node.type === '(number)' && !+node.value) ||
(node.type === '(string)' && !node.value) ||
node.type === 'true' ||
node.type === 'false' ||
node.type === 'undefined' ||
node.type === 'null';
}
function assignop(s, f) {
symbol(s, 20).exps = true;
return infix(s, function (left) {
var l;
this.left = left;
nonadjacent(prevtoken, token);
nonadjacent(token, nexttoken);
if (option.safe) {
l = left;
do {
if (predefined[l.value] === true) {
warning('ADsafe violation.', l);
}
l = l.left;
} while (l);
}
if (left) {
if (left.id === '.' || left.id === '[') {
if (left.left.value === 'arguments') {
warning('Bad assignment.', this);
}
this.right = parse(19);
return this;
} else if (left.identifier && !left.reserved) {
if (funct[left.value] === 'exception') {
warning("Do not assign to the exception parameter.", left);
}
this.right = parse(19);
return this;
}
if (left === syntax['function']) {
warning(
"Expected an identifier in an assignment and instead saw a function invocation.",
token);
}
}
error("Bad assignment.", this);
}, 20);
}
function bitwise(s, f, p) {
var x = symbol(s, p);
reserveName(x);
x.led = (typeof f === 'function') ? f : function (left) {
if (option.bitwise) {
warning("Unexpected use of '{a}'.", this, this.id);
}
nonadjacent(prevtoken, token);
nonadjacent(token, nexttoken);
this.left = left;
this.right = parse(p);
return this;
};
return x;
}
function bitwiseassignop(s) {
symbol(s, 20).exps = true;
return infix(s, function (left) {
if (option.bitwise) {
warning("Unexpected use of '{a}'.", this, this.id);
}
nonadjacent(prevtoken, token);
nonadjacent(token, nexttoken);
if (left) {
if (left.id === '.' || left.id === '[' ||
(left.identifier && !left.reserved)) {
parse(19);
return left;
}
if (left === syntax['function']) {
warning(
"Expected an identifier in an assignment, and instead saw a function invocation.",
token);
}
}
error("Bad assignment.", this);
}, 20);
}
function suffix(s, f) {
var x = symbol(s, 150);
x.led = function (left) {
if (option.plusplus) {
warning("Unexpected use of '{a}'.", this, this.id);
}
this.left = left;
return this;
};
return x;
}
function optionalidentifier() {
if (nexttoken.reserved && nexttoken.value !== 'arguments') {
warning("Expected an identifier and instead saw '{a}' (a reserved word).",
nexttoken, nexttoken.id);
}
if (nexttoken.identifier) {
advance();
return token.value;
}
}
function identifier() {
var i = optionalidentifier();
if (i) {
return i;
}
if (token.id === 'function' && nexttoken.id === '(') {
warning("Missing name in function statement.");
} else {
error("Expected an identifier and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
}
function reachable(s) {
var i = 0, t;
if (nexttoken.id !== ';' || noreach) {
return;
}
for (;;) {
t = peek(i);
if (t.reach) {
return;
}
if (t.id !== '(endline)') {
if (t.id === 'function') {
warning(
"Inner functions should be listed at the top of the outer function.", t);
break;
}
warning("Unreachable '{a}' after '{b}'.", t, t.value, s);
break;
}
i += 1;
}
}
function statement(noindent) {
var i = indent, r, s = scope, t = nexttoken;
// We don't like the empty statement.
if (t.id === ';') {
warning("Unnecessary semicolon.", t);
advance(';');
return;
}
// Is this a labelled statement?
if (t.identifier && !t.reserved && peek().id === ':') {
advance();
advance(':');
scope = Object.create(s);
addlabel(t.value, 'label');
if (!nexttoken.labelled) {
warning("Label '{a}' on {b} statement.",
nexttoken, t.value, nexttoken.value);
}
if (jx.test(t.value + ':')) {
warning("Label '{a}' looks like a javascript url.",
t, t.value);
}
nexttoken.label = t.value;
t = nexttoken;
}
// Parse the statement.
if (!noindent) {
indentation();
}
r = parse(0, true);
// Look for the final semicolon.
if (!t.block) {
if (nexttoken.id !== ';') {
warningAt("Missing semicolon.", token.line,
token.from + token.value.length);
} else {
adjacent(token, nexttoken);
advance(';');
nonadjacent(token, nexttoken);
}
}
// Restore the indentation.
indent = i;
scope = s;
return r;
}
function use_strict() {
if (nexttoken.type === '(string)' &&
/^use +strict(?:,.+)?$/.test(nexttoken.value)) {
advance();
advance(';');
return true;
} else {
return false;
}
}
function statements(begin) {
var a = [], f, p;
if (begin && !use_strict() && option.strict) {
warning('Missing "use strict" statement.', nexttoken);
}
if (option.adsafe) {
switch (begin) {
case 'script':
if (!adsafe_may) {
if (nexttoken.value !== 'ADSAFE' ||
peek(0).id !== '.' ||
(peek(1).value !== 'id' &&
peek(1).value !== 'go')) {
error('ADsafe violation: Missing ADSAFE.id or ADSAFE.go.',
nexttoken);
}
}
if (nexttoken.value === 'ADSAFE' &&
peek(0).id === '.' &&
peek(1).value === 'id') {
if (adsafe_may) {
error('ADsafe violation.', nexttoken);
}
advance('ADSAFE');
advance('.');
advance('id');
advance('(');
if (nexttoken.value !== adsafe_id) {
error('ADsafe violation: id does not match.', nexttoken);
}
advance('(string)');
advance(')');
advance(';');
adsafe_may = true;
}
break;
case 'lib':
if (nexttoken.value === 'ADSAFE') {
advance('ADSAFE');
advance('.');
advance('lib');
advance('(');
advance('(string)');
advance(',');
f = parse(0);
if (f.id !== 'function') {
error('The second argument to lib must be a function.', f);
}
p = f.funct['(params)'];
if (p && p !== 'lib') {
error("Expected '{a}' and instead saw '{b}'.",
f, 'lib', p);
}
advance(')');
advance(';');
return a;
} else {
error("ADsafe lib violation.");
}
}
}
while (!nexttoken.reach && nexttoken.id !== '(end)') {
if (nexttoken.id === ';') {
warning("Unnecessary semicolon.");
advance(';');
} else {
a.push(statement());
}
}
return a;
}
function block(f) {
var a, b = inblock, s = scope, t;
inblock = f;
if (f) {
scope = Object.create(scope);
}
nonadjacent(token, nexttoken);
t = nexttoken;
if (nexttoken.id === '{') {
advance('{');
if (nexttoken.id !== '}' || token.line !== nexttoken.line) {
indent += option.indent;
if (!f && nexttoken.from === indent + option.indent) {
indent += option.indent;
}
if (!f) {
use_strict();
}
a = statements();
indent -= option.indent;
indentation();
}
advance('}', t);
} else {
warning("Expected '{a}' and instead saw '{b}'.",
nexttoken, '{', nexttoken.value);
noreach = true;
a = [statement()];
noreach = false;
}
funct['(verb)'] = null;
scope = s;
inblock = b;
return a;
}
// An identity function, used by string and number tokens.
function idValue() {
return this;
}
function countMember(m) {
if (membersOnly && membersOnly[m] !== true) {
warning("Unexpected /*member '{a}'.", nexttoken, m);
}
if (typeof member[m] === 'number') {
member[m] += 1;
} else {
member[m] = 1;
}
}
function note_implied(token) {
var name = token.value, line = token.line + 1, a = implied[name];
if (typeof a === 'function') {
a = false;
}
if (!a) {
a = [line];
implied[name] = a;
} else if (a[a.length - 1] !== line) {
a.push(line);
}
}
// CSS parsing.
function cssName() {
if (nexttoken.identifier) {
advance();
return true;
}
}
function cssNumber() {
if (nexttoken.id === '-') {
advance('-');
advance('(number)');
}
if (nexttoken.type === '(number)') {
advance();
return true;
}
}
function cssString() {
if (nexttoken.type === '(string)') {
advance();
return true;
}
}
function cssColor() {
var i, number;
if (nexttoken.identifier) {
if (nexttoken.value === 'rgb') {
advance();
advance('(');
for (i = 0; i < 3; i += 1) {
number = nexttoken.value;
if (nexttoken.type !== '(number)' || number < 0) {
warning("Expected a positive number and instead saw '{a}'",
nexttoken, number);
advance();
} else {
advance();
if (nexttoken.id === '%') {
advance('%');
if (number > 100) {
warning("Expected a percentage and instead saw '{a}'",
token, number);
}
} else {
if (number > 255) {
warning("Expected a small number and instead saw '{a}'",
token, number);
}
}
}
}
advance(')');
return true;
} else if (cssColorData[nexttoken.value] === true) {
advance();
return true;
}
} else if (nexttoken.type === '(color)') {
advance();
return true;
}
return false;
}
function cssLength() {
if (nexttoken.id === '-') {
advance('-');
adjacent();
}
if (nexttoken.type === '(number)') {
advance();
if (nexttoken.type !== '(string)' &&
cssLengthData[nexttoken.value] === true) {
adjacent();
advance();
} else if (+token.value !== 0) {
warning("Expected a linear unit and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
return true;
}
return false;
}
function cssLineHeight() {
if (nexttoken.id === '-') {
advance('-');
adjacent();
}
if (nexttoken.type === '(number)') {
advance();
if (nexttoken.type !== '(string)' &&
cssLengthData[nexttoken.value] === true) {
adjacent();
advance();
}
return true;
}
return false;
}
function cssWidth() {
if (nexttoken.identifier) {
switch (nexttoken.value) {
case 'thin':
case 'medium':
case 'thick':
advance();
return true;
}
} else {
return cssLength();
}
}
function cssMargin() {
if (nexttoken.identifier) {
if (nexttoken.value === 'auto') {
advance();
return true;
}
} else {
return cssLength();
}
}
function cssAttr() {
if (nexttoken.identifier && nexttoken.value === 'attr') {
advance();
advance('(');
if (!nexttoken.identifier) {
warning("Expected a name and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
advance();
advance(')');
return true;
}
return false;
}
function cssCommaList() {
while (nexttoken.id !== ';') {
if (!cssName() && !cssString()) {
warning("Expected a name and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
if (nexttoken.id !== ',') {
return true;
}
advance(',');
}
}
function cssCounter() {
if (nexttoken.identifier && nexttoken.value === 'counter') {
advance();
advance('(');
if (!nexttoken.identifier) {
}
advance();
if (nexttoken.id === ',') {
advance(',');
if (nexttoken.type !== '(string)') {
warning("Expected a string and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
advance();
}
advance(')');
return true;
}
if (nexttoken.identifier && nexttoken.value === 'counters') {
advance();
advance('(');
if (!nexttoken.identifier) {
warning("Expected a name and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
advance();
if (nexttoken.id === ',') {
advance(',');
if (nexttoken.type !== '(string)') {
warning("Expected a string and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
advance();
}
if (nexttoken.id === ',') {
advance(',');
if (nexttoken.type !== '(string)') {
warning("Expected a string and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
advance();
}
advance(')');
return true;
}
return false;
}
function cssShape() {
var i;
if (nexttoken.identifier && nexttoken.value === 'rect') {
advance();
advance('(');
for (i = 0; i < 4; i += 1) {
if (!cssLength()) {
warning("Expected a number and instead saw '{a}'.",
nexttoken, nexttoken.value);
break;
}
}
advance(')');
return true;
}
return false;
}
function cssUrl() {
var url;
if (nexttoken.identifier && nexttoken.value === 'url') {
nexttoken = lex.range('(', ')');
url = nexttoken.value;
advance();
if (option.safe && ux.test(url)) {
error("ADsafe URL violation.");
}
urls.push(url);
return true;
}
return false;
}
cssAny = [cssUrl, function () {
for (;;) {
if (nexttoken.identifier) {
switch (nexttoken.value.toLowerCase()) {
case 'url':
cssUrl();
break;
case 'expression':
warning("Unexpected expression '{a}'.",
nexttoken, nexttoken.value);
advance();
break;
default:
advance();
}
} else {
if (nexttoken.id === ';' || nexttoken.id === '!' ||
nexttoken.id === '(end)' || nexttoken.id === '}') {
return true;
}
advance();
}
}
}];
cssBorderStyle = [
'none', 'hidden', 'dotted', 'dashed', 'solid', 'double', 'ridge',
'inset', 'outset'
];
cssAttributeData = {
background: [
true, 'background-attachment', 'background-color',
'background-image', 'background-position', 'background-repeat'
],
'background-attachment': ['scroll', 'fixed'],
'background-color': ['transparent', cssColor],
'background-image': ['none', cssUrl],
'background-position': [
2, [cssLength, 'top', 'bottom', 'left', 'right', 'center']
],
'background-repeat': [
'repeat', 'repeat-x', 'repeat-y', 'no-repeat'
],
'border': [true, 'border-color', 'border-style', 'border-width'],
'border-bottom': [true, 'border-bottom-color', 'border-bottom-style', 'border-bottom-width'],
'border-bottom-color': cssColor,
'border-bottom-style': cssBorderStyle,
'border-bottom-width': cssWidth,
'border-collapse': ['collapse', 'separate'],
'border-color': ['transparent', 4, cssColor],
'border-left': [
true, 'border-left-color', 'border-left-style', 'border-left-width'
],
'border-left-color': cssColor,
'border-left-style': cssBorderStyle,
'border-left-width': cssWidth,
'border-right': [
true, 'border-right-color', 'border-right-style', 'border-right-width'
],
'border-right-color': cssColor,
'border-right-style': cssBorderStyle,
'border-right-width': cssWidth,
'border-spacing': [2, cssLength],
'border-style': [4, cssBorderStyle],
'border-top': [
true, 'border-top-color', 'border-top-style', 'border-top-width'
],
'border-top-color': cssColor,
'border-top-style': cssBorderStyle,
'border-top-width': cssWidth,
'border-width': [4, cssWidth],
bottom: [cssLength, 'auto'],
'caption-side' : ['bottom', 'left', 'right', 'top'],
clear: ['both', 'left', 'none', 'right'],
clip: [cssShape, 'auto'],
color: cssColor,
content: [
'open-quote', 'close-quote', 'no-open-quote', 'no-close-quote',
cssString, cssUrl, cssCounter, cssAttr
],
'counter-increment': [
cssName, 'none'
],
'counter-reset': [
cssName, 'none'
],
cursor: [
cssUrl, 'auto', 'crosshair', 'default', 'e-resize', 'help', 'move',
'n-resize', 'ne-resize', 'nw-resize', 'pointer', 's-resize',
'se-resize', 'sw-resize', 'w-resize', 'text', 'wait'
],
direction: ['ltr', 'rtl'],
display: [
'block', 'compact', 'inline', 'inline-block', 'inline-table',
'list-item', 'marker', 'none', 'run-in', 'table', 'table-caption',
'table-column', 'table-column-group', 'table-footer-group',
'table-header-group', 'table-row', 'table-row-group'
],
'empty-cells': ['show', 'hide'],
'float': ['left', 'none', 'right'],
font: [
'caption', 'icon', 'menu', 'message-box', 'small-caption', 'status-bar',
true, 'font-size', 'font-style', 'font-weight', 'font-family'
],
'font-family': cssCommaList,
'font-size': [
'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large',
'xx-large', 'larger', 'smaller', cssLength
],
'font-size-adjust': ['none', cssNumber],
'font-stretch': [
'normal', 'wider', 'narrower', 'ultra-condensed',
'extra-condensed', 'condensed', 'semi-condensed',
'semi-expanded', 'expanded', 'extra-expanded'
],
'font-style': [
'normal', 'italic', 'oblique'
],
'font-variant': [
'normal', 'small-caps'
],
'font-weight': [
'normal', 'bold', 'bolder', 'lighter', cssNumber
],
height: [cssLength, 'auto'],
left: [cssLength, 'auto'],
'letter-spacing': ['normal', cssLength],
'line-height': ['normal', cssLineHeight],
'list-style': [
true, 'list-style-image', 'list-style-position', 'list-style-type'
],
'list-style-image': ['none', cssUrl],
'list-style-position': ['inside', 'outside'],
'list-style-type': [
'circle', 'disc', 'square', 'decimal', 'decimal-leading-zero',
'lower-roman', 'upper-roman', 'lower-greek', 'lower-alpha',
'lower-latin', 'upper-alpha', 'upper-latin', 'hebrew', 'katakana',
'hiragana-iroha', 'katakana-oroha', 'none'
],
margin: [4, cssMargin],
'margin-bottom': cssMargin,
'margin-left': cssMargin,
'margin-right': cssMargin,
'margin-top': cssMargin,
'marker-offset': [cssLength, 'auto'],
'max-height': [cssLength, 'none'],
'max-width': [cssLength, 'none'],
'min-height': cssLength,
'min-width': cssLength,
opacity: cssNumber,
outline: [true, 'outline-color', 'outline-style', 'outline-width'],
'outline-color': ['invert', cssColor],
'outline-style': [
'dashed', 'dotted', 'double', 'groove', 'inset', 'none',
'outset', 'ridge', 'solid'
],
'outline-width': cssWidth,
overflow: ['auto', 'hidden', 'scroll', 'visible'],
padding: [4, cssLength],
'padding-bottom': cssLength,
'padding-left': cssLength,
'padding-right': cssLength,
'padding-top': cssLength,
position: ['absolute', 'fixed', 'relative', 'static'],
quotes: [8, cssString],
right: [cssLength, 'auto'],
'table-layout': ['auto', 'fixed'],
'text-align': ['center', 'justify', 'left', 'right'],
'text-decoration': ['none', 'underline', 'overline', 'line-through', 'blink'],
'text-indent': cssLength,
'text-shadow': ['none', 4, [cssColor, cssLength]],
'text-transform': ['capitalize', 'uppercase', 'lowercase', 'none'],
top: [cssLength, 'auto'],
'unicode-bidi': ['normal', 'embed', 'bidi-override'],
'vertical-align': [
'baseline', 'bottom', 'sub', 'super', 'top', 'text-top', 'middle',
'text-bottom', cssLength
],
visibility: ['visible', 'hidden', 'collapse'],
'white-space': ['normal', 'pre', 'nowrap'],
width: [cssLength, 'auto'],
'word-spacing': ['normal', cssLength],
'z-index': ['auto', cssNumber]
};
function styleAttribute() {
var v;
while (nexttoken.id === '*' || nexttoken.id === '#' || nexttoken.value === '_') {
if (!option.css) {
warning("Unexpected '{a}'.", nexttoken, nexttoken.value);
}
advance();
}
if (nexttoken.id === '-') {
if (!option.css) {
warning("Unexpected '{a}'.", nexttoken, nexttoken.value);
}
advance('-');
if (!nexttoken.identifier) {
warning("Expected a non-standard style attribute and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
advance();
return cssAny;
} else {
if (!nexttoken.identifier) {
warning("Excepted a style attribute, and instead saw '{a}'.",
nexttoken, nexttoken.value);
} else {
if (cssAttributeData.hasOwnProperty(nexttoken.value)) {
v = cssAttributeData[nexttoken.value];
} else {
v = cssAny;
if (!option.css) {
warning("Unrecognized style attribute '{a}'.",
nexttoken, nexttoken.value);
}
}
}
advance();
return v;
}
}
function styleValue(v) {
var i = 0,
n,
once,
match,
round,
start = 0,
vi;
switch (typeof v) {
case 'function':
return v();
case 'string':
if (nexttoken.identifier && nexttoken.value === v) {
advance();
return true;
}
return false;
}
for (;;) {
if (i >= v.length) {
return false;
}
vi = v[i];
i += 1;
if (vi === true) {
break;
} else if (typeof vi === 'number') {
n = vi;
vi = v[i];
i += 1;
} else {
n = 1;
}
match = false;
while (n > 0) {
if (styleValue(vi)) {
match = true;
n -= 1;
} else {
break;
}
}
if (match) {
return true;
}
}
start = i;
once = [];
for (;;) {
round = false;
for (i = start; i < v.length; i += 1) {
if (!once[i]) {
if (styleValue(cssAttributeData[v[i]])) {
match = true;
round = true;
once[i] = true;
break;
}
}
}
if (!round) {
return match;
}
}
}
function substyle() {
var v;
for (;;) {
if (nexttoken.id === '}' || nexttoken.id === '(end)' ||
xquote && nexttoken.id === xquote) {
return;
}
while (nexttoken.id === ';') {
warning("Misplaced ';'.");
advance(';');
}
v = styleAttribute();
advance(':');
if (nexttoken.identifier && nexttoken.value === 'inherit') {
advance();
} else {
styleValue(v);
}
while (nexttoken.id !== ';' && nexttoken.id !== '!' &&
nexttoken.id !== '}' && nexttoken.id !== '(end)' &&
nexttoken.id !== xquote) {
warning("Unexpected token '{a}'.", nexttoken, nexttoken.value);
advance();
}
if (nexttoken.id === '!') {
advance('!');
adjacent();
if (nexttoken.identifier && nexttoken.value === 'important') {
advance();
} else {
warning("Expected '{a}' and instead saw '{b}'.",
nexttoken, 'important', nexttoken.value);
}
}
if (nexttoken.id === '}' || nexttoken.id === xquote) {
warning("Missing '{a}'.", nexttoken, ';');
} else {
advance(';');
}
}
}
function stylePattern() {
var name;
if (nexttoken.id === '{') {
warning("Expected a style pattern, and instead saw '{a}'.", nexttoken,
nexttoken.id);
} else if (nexttoken.id === '@') {
advance('@');
name = nexttoken.value;
if (nexttoken.identifier && atrule[name] === true) {
advance();
return name;
}
warning("Expected an at-rule, and instead saw @{a}.", nexttoken, name);
}
for (;;) {
if (nexttoken.identifier) {
if (!htmltag.hasOwnProperty(nexttoken.value)) {
warning("Expected a tagName, and instead saw {a}.",
nexttoken, nexttoken.value);
}
advance();
} else {
switch (nexttoken.id) {
case '>':
case '+':
advance();
if (!nexttoken.identifier ||
!htmltag.hasOwnProperty(nexttoken.value)) {
warning("Expected a tagName, and instead saw {a}.",
nexttoken, nexttoken.value);
}
advance();
break;
case ':':
advance(':');
if (pseudorule[nexttoken.value] !== true) {
warning("Expected a pseudo, and instead saw :{a}.",
nexttoken, nexttoken.value);
}
advance();
if (nexttoken.value === 'lang') {
advance('(');
if (!nexttoken.identifier) {
warning("Expected a lang code, and instead saw :{a}.",
nexttoken, nexttoken.value);
}
advance(')');
}
break;
case '#':
advance('#');
if (!nexttoken.identifier) {
warning("Expected an id, and instead saw #{a}.",
nexttoken, nexttoken.value);
}
advance();
break;
case '*':
advance('*');
break;
case '.':
advance('.');
if (!nexttoken.identifier) {
warning("Expected a class, and instead saw #.{a}.",
nexttoken, nexttoken.value);
}
advance();
break;
case '[':
advance('[');
if (!nexttoken.identifier) {
warning("Expected an attribute, and instead saw [{a}].",
nexttoken, nexttoken.value);
}
advance();
if (nexttoken.id === '=' || nexttoken.id === '~=' ||
nexttoken.id === '|=') {
advance();
if (nexttoken.type !== '(string)') {
warning("Expected a string, and instead saw {a}.",
nexttoken, nexttoken.value);
}
advance();
}
advance(']');
break;
default:
error("Expected a CSS selector, and instead saw {a}.",
nexttoken, nexttoken.value);
}
}
if (nexttoken.id === '</' || nexttoken.id === '{' ||
nexttoken.id === '(end)') {
return '';
}
if (nexttoken.id === ',') {
advance(',');
}
}
}
function styles() {
while (nexttoken.id !== '</' && nexttoken.id !== '(end)') {
stylePattern();
xmode = 'styleproperty';
if (nexttoken.id === ';') {
advance(';');
} else {
advance('{');
substyle();
xmode = 'style';
advance('}');
}
}
}
// HTML parsing.
function doBegin(n) {
if (n !== 'html' && !option.fragment) {
if (n === 'div' && option.adsafe) {
error("ADSAFE: Use the fragment option.");
} else {
error("Expected '{a}' and instead saw '{b}'.",
token, 'html', n);
}
}
if (option.adsafe) {
if (n === 'html') {
error("Currently, ADsafe does not operate on whole HTML documents. It operates on <div> fragments and .js files.", token);
}
if (option.fragment) {
if (n !== 'div') {
error("ADsafe violation: Wrap the widget in a div.", token);
}
} else {
error("Use the fragment option.", token);
}
}
option.browser = true;
assume();
}
function doAttribute(n, a, v) {
var u, x;
if (a === 'id') {
u = typeof v === 'string' ? v.toUpperCase() : '';
if (ids[u] === true) {
warning("Duplicate id='{a}'.", nexttoken, v);
}
if (option.adsafe) {
if (adsafe_id) {
if (v.slice(0, adsafe_id.length) !== adsafe_id) {
warning("ADsafe violation: An id must have a '{a}' prefix",
nexttoken, adsafe_id);
} else if (!/^[A-Z]+_[A-Z]+$/.test(v)) {
warning("ADSAFE violation: bad id.");
}
} else {
adsafe_id = v;
if (!/^[A-Z]+_$/.test(v)) {
warning("ADSAFE violation: bad id.");
}
}
}
x = v.search(dx);
if (x >= 0) {
warning("Unexpected character '{a}' in {b}.", token, v.charAt(x), a);
}
ids[u] = true;
} else if (a === 'class' || a === 'type' || a === 'name') {
x = v.search(qx);
if (x >= 0) {
warning("Unexpected character '{a}' in {b}.", token, v.charAt(x), a);
}
ids[u] = true;
} else if (a === 'href' || a === 'background' ||
a === 'content' || a === 'data' ||
a.indexOf('src') >= 0 || a.indexOf('url') >= 0) {
if (option.safe && ux.test(v)) {
error("ADsafe URL violation.");
}
urls.push(v);
} else if (a === 'for') {
if (option.adsafe) {
if (adsafe_id) {
if (v.slice(0, adsafe_id.length) !== adsafe_id) {
warning("ADsafe violation: An id must have a '{a}' prefix",
nexttoken, adsafe_id);
} else if (!/^[A-Z]+_[A-Z]+$/.test(v)) {
warning("ADSAFE violation: bad id.");
}
} else {
warning("ADSAFE violation: bad id.");
}
}
} else if (a === 'name') {
if (option.adsafe && v.indexOf('_') >= 0) {
warning("ADsafe name violation.");
}
}
}
function doTag(n, a) {
var i, t = htmltag[n], x;
src = false;
if (!t) {
error("Unrecognized tag '<{a}>'.",
nexttoken,
n === n.toLowerCase() ? n :
n + ' (capitalization error)');
}
if (stack.length > 0) {
if (n === 'html') {
error("Too many <html> tags.", token);
}
x = t.parent;
if (x) {
if (x.indexOf(' ' + stack[stack.length - 1].name + ' ') < 0) {
error("A '<{a}>' must be within '<{b}>'.",
token, n, x);
}
} else if (!option.adsafe && !option.fragment) {
i = stack.length;
do {
if (i <= 0) {
error("A '<{a}>' must be within '<{b}>'.",
token, n, 'body');
}
i -= 1;
} while (stack[i].name !== 'body');
}
}
switch (n) {
case 'div':
if (option.adsafe && stack.length === 1 && !adsafe_id) {
warning("ADSAFE violation: missing ID_.");
}
break;
case 'script':
xmode = 'script';
advance('>');
indent = nexttoken.from;
if (a.lang) {
warning("lang is deprecated.", token);
}
if (option.adsafe && stack.length !== 1) {
warning("ADsafe script placement violation.", token);
}
if (a.src) {
if (option.adsafe && (!adsafe_may || !approved[a.src])) {
warning("ADsafe unapproved script source.", token);
}
if (a.type) {
warning("type is unnecessary.", token);
}
} else {
if (adsafe_went) {
error("ADsafe script violation.", token);
}
statements('script');
}
xmode = 'html';
advance('</');
if (!nexttoken.identifier && nexttoken.value !== 'script') {
warning("Expected '{a}' and instead saw '{b}'.",
nexttoken, 'script', nexttoken.value);
}
advance();
xmode = 'outer';
break;
case 'style':
xmode = 'style';
advance('>');
styles();
xmode = 'html';
advance('</');
if (!nexttoken.identifier && nexttoken.value !== 'style') {
warning("Expected '{a}' and instead saw '{b}'.",
nexttoken, 'style', nexttoken.value);
}
advance();
xmode = 'outer';
break;
case 'input':
switch (a.type) {
case 'radio':
case 'checkbox':
case 'text':
case 'button':
case 'file':
case 'reset':
case 'submit':
case 'password':
case 'file':
case 'hidden':
case 'image':
break;
default:
warning("Bad input type.");
}
if (option.adsafe && a.autocomplete !== 'off') {
warning("ADsafe autocomplete violation.");
}
break;
case 'applet':
case 'body':
case 'embed':
case 'frame':
case 'frameset':
case 'head':
case 'iframe':
case 'img':
case 'noembed':
case 'noframes':
case 'object':
case 'param':
if (option.adsafe) {
warning("ADsafe violation: Disallowed tag: " + n);
}
break;
}
}
function closetag(n) {
return '</' + n + '>';
}
function html() {
var a, attributes, e, n, q, t, v, w = option.white, wmode;
xmode = 'html';
xquote = '';
stack = null;
for (;;) {
switch (nexttoken.value) {
case '<':
xmode = 'html';
advance('<');
attributes = {};
t = nexttoken;
if (!t.identifier) {
warning("Bad identifier {a}.", t, t.value);
}
n = t.value;
if (option.cap) {
n = n.toLowerCase();
}
t.name = n;
advance();
if (!stack) {
stack = [];
doBegin(n);
}
v = htmltag[n];
if (typeof v !== 'object') {
error("Unrecognized tag '<{a}>'.", t, n);
}
e = v.empty;
t.type = n;
for (;;) {
if (nexttoken.id === '/') {
advance('/');
if (nexttoken.id !== '>') {
warning("Expected '{a}' and instead saw '{b}'.",
nexttoken, '>', nexttoken.value);
}
break;
}
if (nexttoken.id && nexttoken.id.substr(0, 1) === '>') {
break;
}
if (!nexttoken.identifier) {
if (nexttoken.id === '(end)' || nexttoken.id === '(error)') {
error("Missing '>'.", nexttoken);
}
warning("Bad identifier.");
}
option.white = true;
nonadjacent(token, nexttoken);
a = nexttoken.value;
option.white = w;
advance();
if (!option.cap && a !== a.toLowerCase()) {
warning("Attribute '{a}' not all lower case.", nexttoken, a);
}
a = a.toLowerCase();
xquote = '';
if (attributes.hasOwnProperty(a)) {
warning("Attribute '{a}' repeated.", nexttoken, a);
}
if (a.slice(0, 2) === 'on') {
if (!option.on) {
warning("Avoid HTML event handlers.");
}
xmode = 'scriptstring';
advance('=');
q = nexttoken.id;
if (q !== '"' && q !== "'") {
error("Missing quote.");
}
xquote = q;
wmode = option.white;
option.white = false;
advance(q);
statements('on');
option.white = wmode;
if (nexttoken.id !== q) {
error("Missing close quote on script attribute.");
}
xmode = 'html';
xquote = '';
advance(q);
v = false;
} else if (a === 'style') {
xmode = 'scriptstring';
advance('=');
q = nexttoken.id;
if (q !== '"' && q !== "'") {
error("Missing quote.");
}
xmode = 'styleproperty';
xquote = q;
advance(q);
substyle();
xmode = 'html';
xquote = '';
advance(q);
v = false;
} else {
if (nexttoken.id === '=') {
advance('=');
v = nexttoken.value;
if (!nexttoken.identifier &&
nexttoken.id !== '"' &&
nexttoken.id !== '\'' &&
nexttoken.type !== '(string)' &&
nexttoken.type !== '(number)' &&
nexttoken.type !== '(color)') {
warning("Expected an attribute value and instead saw '{a}'.", token, a);
}
advance();
} else {
v = true;
}
}
attributes[a] = v;
doAttribute(n, a, v);
}
doTag(n, attributes);
if (!e) {
stack.push(t);
}
xmode = 'outer';
advance('>');
break;
case '</':
xmode = 'html';
advance('</');
if (!nexttoken.identifier) {
warning("Bad identifier.");
}
n = nexttoken.value;
if (option.cap) {
n = n.toLowerCase();
}
advance();
if (!stack) {
error("Unexpected '{a}'.", nexttoken, closetag(n));
}
t = stack.pop();
if (!t) {
error("Unexpected '{a}'.", nexttoken, closetag(n));
}
if (t.name !== n) {
error("Expected '{a}' and instead saw '{b}'.",
nexttoken, closetag(t.name), closetag(n));
}
if (nexttoken.id !== '>') {
error("Missing '{a}'.", nexttoken, '>');
}
xmode = 'outer';
advance('>');
break;
case '<!':
if (option.safe) {
warning("ADsafe HTML violation.");
}
xmode = 'html';
for (;;) {
advance();
if (nexttoken.id === '>' || nexttoken.id === '(end)') {
break;
}
if (nexttoken.id === '--') {
warning("Unexpected --.");
}
}
xmode = 'outer';
advance('>');
break;
case '<!--':
xmode = 'html';
if (option.safe) {
warning("ADsafe HTML violation.");
}
for (;;) {
advance();
if (nexttoken.id === '(end)') {
error("Missing '-->'.");
}
if (nexttoken.id === '<!' || nexttoken.id === '<!--') {
error("Unexpected '<!' in HTML comment.");
}
if (nexttoken.id === '--') {
advance('--');
break;
}
}
abut();
xmode = 'outer';
advance('>');
break;
case '(end)':
return;
default:
if (nexttoken.id === '(end)') {
error("Missing '{a}'.", nexttoken,
'</' + stack[stack.length - 1].value + '>');
} else {
advance();
}
}
if (stack && stack.length === 0 && (option.adsafe ||
!option.fragment || nexttoken.id === '(end)')) {
break;
}
}
if (nexttoken.id !== '(end)') {
error("Unexpected material after the end.");
}
}
// Build the syntax table by declaring the syntactic elements of the language.
type('(number)', idValue);
type('(string)', idValue);
syntax['(identifier)'] = {
type: '(identifier)',
lbp: 0,
identifier: true,
nud: function () {
var v = this.value,
s = scope[v];
if (typeof s === 'function') {
s = false;
}
// The name is in scope and defined in the current function.
if (s && (s === funct || s === funct['(global)'])) {
// If we are not also in the global scope, change 'unused' to 'var',
// and reject labels.
if (!funct['(global)']) {
switch (funct[v]) {
case 'unused':
funct[v] = 'var';
break;
case 'label':
warning("'{a}' is a statement label.", token, v);
break;
}
}
// The name is not defined in the function. If we are in the global scope,
// then we have an undefined variable.
} else if (funct['(global)']) {
if (option.undef) {
warning("'{a}' is not defined.", token, v);
}
note_implied(token);
// If the name is already defined in the current
// function, but not as outer, then there is a scope error.
} else {
switch (funct[v]) {
case 'closure':
case 'function':
case 'var':
case 'unused':
warning("'{a}' used out of scope.", token, v);
break;
case 'label':
warning("'{a}' is a statement label.", token, v);
break;
case 'outer':
case true:
break;
default:
// If the name is defined in an outer function, make an outer entry, and if
// it was unused, make it var.
if (s === true) {
funct[v] = true;
} else if (typeof s !== 'object') {
if (option.undef) {
warning("'{a}' is not defined.", token, v);
} else {
funct[v] = true;
}
note_implied(token);
} else {
switch (s[v]) {
case 'function':
case 'var':
case 'unused':
s[v] = 'closure';
funct[v] = 'outer';
break;
case 'closure':
case 'parameter':
funct[v] = 'outer';
break;
case 'label':
warning("'{a}' is a statement label.", token, v);
}
}
}
}
return this;
},
led: function () {
error("Expected an operator and instead saw '{a}'.",
nexttoken, nexttoken.value);
}
};
type('(regexp)', function () {
return this;
});
delim('(endline)');
delim('(begin)');
delim('(end)').reach = true;
delim('</').reach = true;
delim('<!');
delim('<!--');
delim('-->');
delim('(error)').reach = true;
delim('}').reach = true;
delim(')');
delim(']');
delim('"').reach = true;
delim("'").reach = true;
delim(';');
delim(':').reach = true;
delim(',');
delim('#');
delim('@');
reserve('else');
reserve('case').reach = true;
reserve('catch');
reserve('default').reach = true;
reserve('finally');
reservevar('arguments');
reservevar('eval');
reservevar('false');
reservevar('Infinity');
reservevar('NaN');
reservevar('null');
reservevar('this');
reservevar('true');
reservevar('undefined');
assignop('=', 'assign', 20);
assignop('+=', 'assignadd', 20);
assignop('-=', 'assignsub', 20);
assignop('*=', 'assignmult', 20);
assignop('/=', 'assigndiv', 20).nud = function () {
error("A regular expression literal can be confused with '/='.");
};
assignop('%=', 'assignmod', 20);
bitwiseassignop('&=', 'assignbitand', 20);
bitwiseassignop('|=', 'assignbitor', 20);
bitwiseassignop('^=', 'assignbitxor', 20);
bitwiseassignop('<<=', 'assignshiftleft', 20);
bitwiseassignop('>>=', 'assignshiftright', 20);
bitwiseassignop('>>>=', 'assignshiftrightunsigned', 20);
infix('?', function (left) {
this.left = left;
this.right = parse(10);
advance(':');
this['else'] = parse(10);
return this;
}, 30);
infix('||', 'or', 40);
infix('&&', 'and', 50);
bitwise('|', 'bitor', 70);
bitwise('^', 'bitxor', 80);
bitwise('&', 'bitand', 90);
relation('==', function (left, right) {
if (option.eqeqeq) {
warning("Expected '{a}' and instead saw '{b}'.",
this, '===', '==');
} else if (isPoorRelation(left)) {
warning("Use '{a}' to compare with '{b}'.",
this, '===', left.value);
} else if (isPoorRelation(right)) {
warning("Use '{a}' to compare with '{b}'.",
this, '===', right.value);
}
return this;
});
relation('===');
relation('!=', function (left, right) {
if (option.eqeqeq) {
warning("Expected '{a}' and instead saw '{b}'.",
this, '!==', '!=');
} else if (isPoorRelation(left)) {
warning("Use '{a}' to compare with '{b}'.",
this, '!==', left.value);
} else if (isPoorRelation(right)) {
warning("Use '{a}' to compare with '{b}'.",
this, '!==', right.value);
}
return this;
});
relation('!==');
relation('<');
relation('>');
relation('<=');
relation('>=');
bitwise('<<', 'shiftleft', 120);
bitwise('>>', 'shiftright', 120);
bitwise('>>>', 'shiftrightunsigned', 120);
infix('in', 'in', 120);
infix('instanceof', 'instanceof', 120);
infix('+', function (left) {
nonadjacent(prevtoken, token);
nonadjacent(token, nexttoken);
var right = parse(130);
if (left && right && left.id === '(string)' && right.id === '(string)') {
left.value += right.value;
left.character = right.character;
if (jx.test(left.value)) {
warning("JavaScript URL.", left);
}
return left;
}
this.left = left;
this.right = right;
return this;
}, 130);
prefix('+', 'num');
infix('-', 'sub', 130);
prefix('-', 'neg');
infix('*', 'mult', 140);
infix('/', 'div', 140);
infix('%', 'mod', 140);
suffix('++', 'postinc');
prefix('++', 'preinc');
syntax['++'].exps = true;
suffix('--', 'postdec');
prefix('--', 'predec');
syntax['--'].exps = true;
prefix('delete', function () {
var p = parse(0);
if (p.id !== '.' && p.id !== '[') {
warning("Expected '{a}' and instead saw '{b}'.",
nexttoken, '.', nexttoken.value);
}
}).exps = true;
prefix('~', function () {
if (option.bitwise) {
warning("Unexpected '{a}'.", this, '~');
}
parse(150);
return this;
});
prefix('!', 'not');
prefix('typeof', 'typeof');
prefix('new', function () {
var c = parse(155), i;
if (c && c.id !== 'function') {
if (c.identifier) {
c['new'] = true;
switch (c.value) {
case 'Object':
warning("Use the object literal notation {}.", token);
break;
case 'Array':
warning("Use the array literal notation [].", token);
break;
case 'Number':
case 'String':
case 'Boolean':
case 'Math':
warning("Do not use {a} as a constructor.", token, c.value);
break;
case 'Function':
if (!option.evil) {
warning("The Function constructor is eval.");
}
break;
case 'Date':
case 'RegExp':
break;
default:
if (c.id !== 'function') {
i = c.value.substr(0, 1);
if (option.newcap && (i < 'A' || i > 'Z')) {
warning(
"A constructor name should start with an uppercase letter.",
token);
}
}
}
} else {
if (c.id !== '.' && c.id !== '[' && c.id !== '(') {
warning("Bad constructor.", token);
}
}
} else {
warning("Weird construction. Delete 'new'.", this);
}
adjacent(token, nexttoken);
if (nexttoken.id !== '(') {
warning("Missing '()' invoking a constructor.");
}
this.first = c;
return this;
});
syntax['new'].exps = true;
infix('.', function (left) {
adjacent(prevtoken, token);
var t = this, m = identifier();
if (typeof m === 'string') {
countMember(m);
}
t.left = left;
t.right = m;
if (!option.evil && left && left.value === 'document' &&
(m === 'write' || m === 'writeln')) {
warning("document.write can be a form of eval.", left);
}
if (option.adsafe) {
if (left && left.value === 'ADSAFE') {
if (m === 'id' || m === 'lib') {
warning("ADsafe violation.", this);
} else if (m === 'go') {
if (xmode !== 'script') {
warning("ADsafe violation.", this);
} else if (adsafe_went || nexttoken.id !== '(' ||
peek(0).id !== '(string)' ||
peek(0).value !== adsafe_id ||
peek(1).id !== ',') {
error("ADsafe violation: go.", this);
}
adsafe_went = true;
adsafe_may = false;
}
}
}
if (option.safe) {
for (;;) {
if (banned[m] === true) {
warning("ADsafe restricted word '{a}'.", token, m);
}
if (predefined[left.value] !== true ||
nexttoken.id === '(') {
break;
}
if (standard_member[m] === true) {
if (nexttoken.id === '.') {
warning("ADsafe violation.", this);
}
break;
}
if (nexttoken.id !== '.') {
warning("ADsafe violation.", this);
break;
}
advance('.');
token.left = t;
token.right = m;
t = token;
m = identifier();
if (typeof m === 'string') {
countMember(m);
}
}
}
return t;
}, 160);
infix('(', function (left) {
adjacent(prevtoken, token);
nospace();
var n = 0,
p = [];
if (left) {
if (left.type === '(identifier)') {
if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) {
if (left.value !== 'Number' && left.value !== 'String' &&
left.value !== 'Boolean' && left.value !== 'Date') {
if (left.value === 'Math') {
warning("Math is not a function.", left);
} else if (option.newcap) {
warning("Missing 'new' prefix when invoking a constructor.",
left);
}
}
}
} else if (left.id === '.') {
if (option.safe && left.left.value === 'Math' &&
left.right === 'random') {
warning("ADsafe violation.", left);
}
}
}
if (nexttoken.id !== ')') {
for (;;) {
p[p.length] = parse(10);
n += 1;
if (nexttoken.id !== ',') {
break;
}
advance(',');
nonadjacent(token, nexttoken);
}
}
advance(')');
if (option.immed && left.id === 'function' && nexttoken.id !== ')') {
warning("Wrap the entire immediate function invocation in parens.",
this);
}
nospace(prevtoken, token);
if (typeof left === 'object') {
if (left.value === 'parseInt' && n === 1) {
warning("Missing radix parameter.", left);
}
if (!option.evil) {
if (left.value === 'eval' || left.value === 'Function' ||
left.value === 'execScript') {
warning("eval is evil.", left);
} else if (p[0] && p[0].id === '(string)' &&
(left.value === 'setTimeout' ||
left.value === 'setInterval')) {
warning(
"Implied eval is evil. Pass a function instead of a string.", left);
}
}
if (!left.identifier && left.id !== '.' && left.id !== '[' &&
left.id !== '(' && left.id !== '&&' && left.id !== '||' &&
left.id !== '?') {
warning("Bad invocation.", left);
}
}
this.left = left;
return this;
}, 155).exps = true;
prefix('(', function () {
nospace();
var v = parse(0);
advance(')', this);
nospace(prevtoken, token);
if (option.immed && v.id === 'function') {
if (nexttoken.id === '(') {
warning(
"Move the invocation into the parens that contain the function.", nexttoken);
} else {
warning(
"Do not wrap function literals in parens unless they are to be immediately invoked.",
this);
}
}
return v;
});
infix('[', function (left) {
nospace();
var e = parse(0), s;
if (e && e.type === '(string)') {
if (option.safe && banned[e.value] === true) {
warning("ADsafe restricted word '{a}'.", this, e.value);
}
countMember(e.value);
if (!option.sub && ix.test(e.value)) {
s = syntax[e.value];
if (!s || !s.reserved) {
warning("['{a}'] is better written in dot notation.",
e, e.value);
}
}
} else if (!e || (e.type !== '(number)' &&
(e.id !== '+' || e.arity !== 'unary'))) {
if (option.safe) {
warning('ADsafe subscripting.');
}
}
advance(']', this);
nospace(prevtoken, token);
this.left = left;
this.right = e;
return this;
}, 160);
prefix('[', function () {
if (nexttoken.id === ']') {
advance(']');
return;
}
var b = token.line !== nexttoken.line;
if (b) {
indent += option.indent;
if (nexttoken.from === indent + option.indent) {
indent += option.indent;
}
}
for (;;) {
if (b && token.line !== nexttoken.line) {
indentation();
}
parse(10);
if (nexttoken.id === ',') {
adjacent(token, nexttoken);
advance(',');
if (nexttoken.id === ',') {
warning("Extra comma.", token);
} else if (nexttoken.id === ']') {
warning("Extra comma.", token);
break;
}
nonadjacent(token, nexttoken);
} else {
if (b) {
indent -= option.indent;
indentation();
}
break;
}
}
advance(']', this);
return;
}, 160);
(function (x) {
x.nud = function () {
var b, i, s, seen = {};
b = token.line !== nexttoken.line;
if (b) {
indent += option.indent;
if (nexttoken.from === indent + option.indent) {
indent += option.indent;
}
}
for (;;) {
if (nexttoken.id === '}') {
break;
}
if (b) {
indentation();
}
i = optionalidentifier(true);
if (!i) {
if (nexttoken.id === '(string)') {
i = nexttoken.value;
if (ix.test(i)) {
s = syntax[i];
}
advance();
} else if (nexttoken.id === '(number)') {
i = nexttoken.value.toString();
advance();
} else {
error("Expected '{a}' and instead saw '{b}'.",
nexttoken, '}', nexttoken.value);
}
}
if (seen[i] === true) {
warning("Duplicate member '{a}'.", nexttoken, i);
}
seen[i] = true;
countMember(i);
advance(':');
nonadjacent(token, nexttoken);
parse(10);
if (nexttoken.id === ',') {
adjacent(token, nexttoken);
advance(',');
if (nexttoken.id === ',' || nexttoken.id === '}') {
warning("Extra comma.", token);
}
nonadjacent(token, nexttoken);
} else {
break;
}
}
if (b) {
indent -= option.indent;
indentation();
}
advance('}', this);
return;
};
x.fud = function () {
error("Expected to see a statement and instead saw a block.", token);
};
}(delim('{')));
function varstatement(prefix) {
// JavaScript does not have block scope. It only has function scope. So,
// declaring a variable in a block can have unexpected consequences.
if (funct['(onevar)'] && option.onevar) {
warning("Too many var statements.");
} else if (!funct['(global)']) {
funct['(onevar)'] = true;
}
for (;;) {
nonadjacent(token, nexttoken);
addlabel(identifier(), 'unused');
if (prefix) {
return;
}
if (nexttoken.id === '=') {
nonadjacent(token, nexttoken);
advance('=');
nonadjacent(token, nexttoken);
if (peek(0).id === '=') {
error("Variable {a} was not declared correctly.",
nexttoken, nexttoken.value);
}
parse(20);
}
if (nexttoken.id !== ',') {
return;
}
adjacent(token, nexttoken);
advance(',');
nonadjacent(token, nexttoken);
}
}
stmt('var', varstatement);
stmt('new', function () {
error("'new' should not be used as a statement.");
});
function functionparams() {
var i, t = nexttoken, p = [];
advance('(');
nospace();
if (nexttoken.id === ')') {
advance(')');
nospace(prevtoken, token);
return;
}
for (;;) {
i = identifier();
p.push(i);
addlabel(i, 'parameter');
if (nexttoken.id === ',') {
advance(',');
nonadjacent(token, nexttoken);
} else {
advance(')', t);
nospace(prevtoken, token);
return p.join(', ');
}
}
}
function doFunction(i) {
var s = scope;
scope = Object.create(s);
funct = {
'(name)' : i || '"' + anonname + '"',
'(line)' : nexttoken.line + 1,
'(context)' : funct,
'(breakage)': 0,
'(loopage)' : 0,
'(scope)' : scope
};
token.funct = funct;
functions.push(funct);
if (i) {
addlabel(i, 'function');
}
funct['(params)'] = functionparams();
block(false);
scope = s;
funct = funct['(context)'];
}
blockstmt('function', function () {
if (inblock) {
warning(
"Function statements cannot be placed in blocks. Use a function expression or move the statement to the top of the outer function.", token);
}
var i = identifier();
adjacent(token, nexttoken);
addlabel(i, 'unused');
doFunction(i);
if (nexttoken.id === '(' && nexttoken.line === token.line) {
error(
"Function statements are not invocable. Wrap the whole function invocation in parens.");
}
});
prefix('function', function () {
var i = optionalidentifier();
if (i) {
adjacent(token, nexttoken);
} else {
nonadjacent(token, nexttoken);
}
doFunction(i);
if (funct['(loopage)'] && nexttoken.id !== '(') {
warning("Be careful when making functions within a loop. Consider putting the function in a closure.");
}
return this;
});
blockstmt('if', function () {
var t = nexttoken;
advance('(');
nonadjacent(this, t);
nospace();
parse(20);
if (nexttoken.id === '=') {
warning("Expected a conditional expression and instead saw an assignment.");
advance('=');
parse(20);
}
advance(')', t);
nospace(prevtoken, token);
block(true);
if (nexttoken.id === 'else') {
nonadjacent(token, nexttoken);
advance('else');
if (nexttoken.id === 'if' || nexttoken.id === 'switch') {
statement(true);
} else {
block(true);
}
}
return this;
});
blockstmt('try', function () {
var b, e, s;
if (option.adsafe) {
warning("ADsafe try violation.", this);
}
block(false);
if (nexttoken.id === 'catch') {
advance('catch');
nonadjacent(token, nexttoken);
advance('(');
s = scope;
scope = Object.create(s);
e = nexttoken.value;
if (nexttoken.type !== '(identifier)') {
warning("Expected an identifier and instead saw '{a}'.",
nexttoken, e);
} else {
addlabel(e, 'exception');
}
advance();
advance(')');
block(false);
b = true;
scope = s;
}
if (nexttoken.id === 'finally') {
advance('finally');
block(false);
return;
} else if (!b) {
error("Expected '{a}' and instead saw '{b}'.",
nexttoken, 'catch', nexttoken.value);
}
});
blockstmt('while', function () {
var t = nexttoken;
funct['(breakage)'] += 1;
funct['(loopage)'] += 1;
advance('(');
nonadjacent(this, t);
nospace();
parse(20);
if (nexttoken.id === '=') {
warning("Expected a conditional expression and instead saw an assignment.");
advance('=');
parse(20);
}
advance(')', t);
nospace(prevtoken, token);
block(true);
funct['(breakage)'] -= 1;
funct['(loopage)'] -= 1;
}).labelled = true;
reserve('with');
blockstmt('switch', function () {
var t = nexttoken,
g = false;
funct['(breakage)'] += 1;
advance('(');
nonadjacent(this, t);
nospace();
this.condition = parse(20);
advance(')', t);
nospace(prevtoken, token);
nonadjacent(token, nexttoken);
t = nexttoken;
advance('{');
nonadjacent(token, nexttoken);
indent += option.indent;
this.cases = [];
for (;;) {
switch (nexttoken.id) {
case 'case':
switch (funct['(verb)']) {
case 'break':
case 'case':
case 'continue':
case 'return':
case 'switch':
case 'throw':
break;
default:
warning(
"Expected a 'break' statement before 'case'.",
token);
}
indentation(-option.indent);
advance('case');
this.cases.push(parse(20));
g = true;
advance(':');
funct['(verb)'] = 'case';
break;
case 'default':
switch (funct['(verb)']) {
case 'break':
case 'continue':
case 'return':
case 'throw':
break;
default:
warning(
"Expected a 'break' statement before 'default'.",
token);
}
indentation(-option.indent);
advance('default');
g = true;
advance(':');
break;
case '}':
indent -= option.indent;
indentation();
advance('}', t);
if (this.cases.length === 1 || this.condition.id === 'true' ||
this.condition.id === 'false') {
warning("This 'switch' should be an 'if'.", this);
}
funct['(breakage)'] -= 1;
funct['(verb)'] = undefined;
return;
case '(end)':
error("Missing '{a}'.", nexttoken, '}');
return;
default:
if (g) {
switch (token.id) {
case ',':
error("Each value should have its own case label.");
return;
case ':':
statements();
break;
default:
error("Missing ':' on a case clause.", token);
}
} else {
error("Expected '{a}' and instead saw '{b}'.",
nexttoken, 'case', nexttoken.value);
}
}
}
}).labelled = true;
stmt('debugger', function () {
if (!option.debug) {
warning("All 'debugger' statements should be removed.");
}
});
stmt('do', function () {
funct['(breakage)'] += 1;
funct['(loopage)'] += 1;
block(true);
advance('while');
var t = nexttoken;
nonadjacent(token, t);
advance('(');
nospace();
parse(20);
if (nexttoken.id === '=') {
warning("Expected a conditional expression and instead saw an assignment.");
advance('=');
parse(20);
}
advance(')', t);
nospace(prevtoken, token);
funct['(breakage)'] -= 1;
funct['(loopage)'] -= 1;
}).labelled = true;
blockstmt('for', function () {
var s, t = nexttoken;
funct['(breakage)'] += 1;
funct['(loopage)'] += 1;
advance('(');
nonadjacent(this, t);
nospace();
if (peek(nexttoken.id === 'var' ? 1 : 0).id === 'in') {
if (nexttoken.id === 'var') {
advance('var');
varstatement(true);
} else {
advance();
}
advance('in');
parse(20);
advance(')', t);
s = block(true);
if (!option.forin && (s.length > 1 || typeof s[0] !== 'object' ||
s[0].value !== 'if')) {
warning("The body of a for in should be wrapped in an if statement to filter unwanted properties from the prototype.", this);
}
funct['(breakage)'] -= 1;
funct['(loopage)'] -= 1;
return this;
} else {
if (nexttoken.id !== ';') {
if (nexttoken.id === 'var') {
advance('var');
varstatement();
} else {
for (;;) {
parse(0, 'for');
if (nexttoken.id !== ',') {
break;
}
advance(',');
}
}
}
advance(';');
if (nexttoken.id !== ';') {
parse(20);
if (nexttoken.id === '=') {
warning("Expected a conditional expression and instead saw an assignment.");
advance('=');
parse(20);
}
}
advance(';');
if (nexttoken.id === ';') {
error("Expected '{a}' and instead saw '{b}'.",
nexttoken, ')', ';');
}
if (nexttoken.id !== ')') {
for (;;) {
parse(0, 'for');
if (nexttoken.id !== ',') {
break;
}
advance(',');
}
}
advance(')', t);
nospace(prevtoken, token);
block(true);
funct['(breakage)'] -= 1;
funct['(loopage)'] -= 1;
}
}).labelled = true;
stmt('break', function () {
var v = nexttoken.value;
if (funct['(breakage)'] === 0) {
warning("Unexpected '{a}'.", nexttoken, this.value);
}
nolinebreak(this);
if (nexttoken.id !== ';') {
if (token.line === nexttoken.line) {
if (funct[v] !== 'label') {
warning("'{a}' is not a statement label.", nexttoken, v);
} else if (scope[v] !== funct) {
warning("'{a}' is out of scope.", nexttoken, v);
}
advance();
}
}
reachable('break');
});
stmt('continue', function () {
var v = nexttoken.value;
if (funct['(breakage)'] === 0) {
warning("Unexpected '{a}'.", nexttoken, this.value);
}
nolinebreak(this);
if (nexttoken.id !== ';') {
if (token.line === nexttoken.line) {
if (funct[v] !== 'label') {
warning("'{a}' is not a statement label.", nexttoken, v);
} else if (scope[v] !== funct) {
warning("'{a}' is out of scope.", nexttoken, v);
}
advance();
}
}
reachable('continue');
});
stmt('return', function () {
nolinebreak(this);
if (nexttoken.id === '(regexp)') {
warning("Wrap the /regexp/ literal in parens to disambiguate the slash operator.");
}
if (nexttoken.id !== ';' && !nexttoken.reach) {
nonadjacent(token, nexttoken);
parse(20);
}
reachable('return');
});
stmt('throw', function () {
nolinebreak(this);
nonadjacent(token, nexttoken);
parse(20);
reachable('throw');
});
reserve('void');
// Superfluous reserved words
reserve('class');
reserve('const');
reserve('enum');
reserve('export');
reserve('extends');
reserve('float');
reserve('goto');
reserve('import');
reserve('let');
reserve('super');
function jsonValue() {
function jsonObject() {
var t = nexttoken;
advance('{');
if (nexttoken.id !== '}') {
for (;;) {
if (nexttoken.id === '(end)') {
error("Missing '}' to match '{' from line {a}.",
nexttoken, t.line + 1);
} else if (nexttoken.id === '}') {
warning("Unexpected comma.", token);
break;
} else if (nexttoken.id === ',') {
error("Unexpected comma.", nexttoken);
} else if (nexttoken.id !== '(string)') {
warning("Expected a string and instead saw {a}.",
nexttoken, nexttoken.value);
}
advance();
advance(':');
jsonValue();
if (nexttoken.id !== ',') {
break;
}
advance(',');
}
}
advance('}');
}
function jsonArray() {
var t = nexttoken;
advance('[');
if (nexttoken.id !== ']') {
for (;;) {
if (nexttoken.id === '(end)') {
error("Missing ']' to match '[' from line {a}.",
nexttoken, t.line + 1);
} else if (nexttoken.id === ']') {
warning("Unexpected comma.", token);
break;
} else if (nexttoken.id === ',') {
error("Unexpected comma.", nexttoken);
}
jsonValue();
if (nexttoken.id !== ',') {
break;
}
advance(',');
}
}
advance(']');
}
switch (nexttoken.id) {
case '{':
jsonObject();
break;
case '[':
jsonArray();
break;
case 'true':
case 'false':
case 'null':
case '(number)':
case '(string)':
advance();
break;
case '-':
advance('-');
if (token.character !== nexttoken.from) {
warning("Unexpected space after '-'.", token);
}
adjacent(token, nexttoken);
advance('(number)');
break;
default:
error("Expected a JSON value.", nexttoken);
}
}
// The actual JSLINT function itself.
var itself = function (s, o) {
var a, i;
JSLINT.errors = [];
predefined = Object.create(standard);
if (o) {
a = o.predef;
if (a instanceof Array) {
for (i = 0; i < a.length; i += 1) {
predefined[a[i]] = true;
}
}
if (o.adsafe) {
o.safe = true;
}
if (o.safe) {
o.browser = false;
o.css = false;
o.debug = false;
o.eqeqeq = true;
o.evil = false;
o.forin = false;
o.nomen = true;
o.on = false;
o.rhino = false;
o.safe = true;
o.sidebar = false;
o.strict = true;
o.sub = false;
o.undef = true;
o.widget = false;
predefined.Date = false;
predefined['eval'] = false;
predefined.Function = false;
predefined.Object = false;
predefined.ADSAFE = true;
predefined.lib = true;
}
option = o;
} else {
option = {};
}
option.indent = option.indent || 4;
adsafe_id = '';
adsafe_may = false;
adsafe_went = false;
approved = {};
if (option.approved) {
for (i = 0; i < option.approved.length; i += 1) {
approved[option.approved[i]] = option.approved[i];
}
}
approved.test = 'test'; ///////////////////////////////////////
tab = '';
for (i = 0; i < option.indent; i += 1) {
tab += ' ';
}
indent = 0;
global = Object.create(predefined);
scope = global;
funct = {
'(global)': true,
'(name)': '(global)',
'(scope)': scope,
'(breakage)': 0,
'(loopage)': 0
};
functions = [];
ids = {};
urls = [];
src = false;
xmode = false;
stack = null;
member = {};
membersOnly = null;
implied = {};
inblock = false;
lookahead = [];
jsonmode = false;
warnings = 0;
lex.init(s);
prereg = true;
prevtoken = token = nexttoken = syntax['(begin)'];
assume();
try {
advance();
if (nexttoken.value.charAt(0) === '<') {
html();
if (option.adsafe && !adsafe_went) {
warning("ADsafe violation: Missing ADSAFE.go.", this);
}
} else {
switch (nexttoken.id) {
case '{':
case '[':
option.laxbreak = true;
jsonmode = true;
jsonValue();
break;
case '@':
case '*':
case '#':
case '.':
case ':':
xmode = 'style';
advance();
if (token.id !== '@' || !nexttoken.identifier ||
nexttoken.value !== 'charset') {
error('A css file should begin with @charset "UTF-8";');
}
advance();
if (nexttoken.type !== '(string)' &&
nexttoken.value !== 'UTF-8') {
error('A css file should begin with @charset "UTF-8";');
}
advance();
advance(';');
styles();
break;
default:
if (option.adsafe && option.fragment) {
warning("ADsafe violation.", this);
}
statements('lib');
}
}
advance('(end)');
} catch (e) {
if (e) {
JSLINT.errors.push({
reason : e.message,
line : e.line || nexttoken.line,
character : e.character || nexttoken.from
}, null);
}
}
return JSLINT.errors.length === 0;
};
function to_array(o) {
var a = [], k;
for (k in o) {
if (o.hasOwnProperty(k)) {
a.push(k);
}
}
return a;
}
// Report generator.
itself.report = function (option, sep) {
var a = [], c, e, f, i, k, l, m = '', n, o = [], s, v,
cl, ex, va, un, ou, gl, la;
function detail(h, s, sep) {
if (s.length) {
o.push('<div><i>' + h + '</i> ' +
s.sort().join(sep || ', ') + '</div>');
}
}
s = to_array(implied);
k = JSLINT.errors.length;
if (k || s.length > 0) {
o.push('<div id=errors><i>Error:</i>');
if (s.length > 0) {
s.sort();
for (i = 0; i < s.length; i += 1) {
s[i] = '<code>' + s[i] + '</code> <i>' +
implied[s[i]].join(' ') +
'</i>';
}
o.push('<p><i>Implied global:</i> ' + s.join(', ') + '</p>');
c = true;
}
for (i = 0; i < k; i += 1) {
c = JSLINT.errors[i];
if (c) {
e = c.evidence || '';
o.push('<p>Problem' + (isFinite(c.line) ? ' at line ' + (c.line + 1) +
' character ' + (c.character + 1) : '') +
': ' + c.reason.entityify() +
'</p><p class=evidence>' +
(e && (e.length > 80 ? e.slice(0, 77) + '...' :
e).entityify()) + '</p>');
}
}
o.push('</div>');
if (!c) {
return o.join('');
}
}
if (!option) {
o.push('<br><div id=functions>');
if (urls.length > 0) {
detail("URLs<br>", urls, '<br>');
}
s = to_array(scope);
if (s.length === 0) {
if (jsonmode) {
if (k === 0) {
o.push('<p>JSON: good.</p>');
} else {
o.push('<p>JSON: bad.</p>');
}
} else {
o.push('<div><i>No new global variables introduced.</i></div>');
}
} else {
o.push('<div><i>Global</i> ' + s.sort().join(', ') + '</div>');
}
for (i = 0; i < functions.length; i += 1) {
f = functions[i];
cl = [];
ex = [];
va = [];
un = [];
ou = [];
gl = [];
la = [];
for (k in f) {
if (f.hasOwnProperty(k) && k.charAt(0) !== '(') {
v = f[k];
switch (v) {
case 'closure':
cl.push(k);
break;
case 'exception':
ex.push(k);
break;
case 'var':
va.push(k);
break;
case 'unused':
un.push(k);
break;
case 'label':
la.push(k);
break;
case 'outer':
ou.push(k);
break;
case true:
gl.push(k);
break;
}
}
}
o.push('<br><div class=function><i>' + f['(line)'] + '</i> ' +
(f['(name)'] || '') + '(' +
(f['(params)'] || '') + ')</div>');
detail('Closure', cl);
detail('Variable', va);
detail('Exception', ex);
detail('Outer', ou);
detail('Global', gl);
detail('<big><b>Unused</b></big>', un);
detail('Label', la);
}
a = [];
for (k in member) {
if (typeof member[k] === 'number') {
a.push(k);
}
}
if (a.length) {
a = a.sort();
m = '<br><pre>/*members ';
l = 10;
for (i = 0; i < a.length; i += 1) {
k = a[i];
n = k.name();
if (l + n.length > 72) {
o.push(m + '<br>');
m = ' ';
l = 1;
}
l += n.length + 2;
if (member[k] === 1) {
n = '<i>' + n + '</i>';
}
if (i < a.length - 1) {
n += ', ';
}
m += n;
}
o.push(m + '<br>*/</pre>');
}
o.push('</div>');
}
return o.join('');
};
return itself;
}());
| ept/bespin-on-rails | public/jsparse/fulljslint.js | JavaScript | mit | 175,398 |
package eu.bcvsolutions.idm.core.api.rest.lookup;
import java.io.IOException;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.GenericTypeResolver;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
import eu.bcvsolutions.idm.core.api.domain.Codeable;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;
import eu.bcvsolutions.idm.core.api.dto.BaseDto;
import eu.bcvsolutions.idm.core.api.exception.ResultCodeException;
import eu.bcvsolutions.idm.core.eav.api.domain.PersistentType;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormProjectionDto;
import eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto;
import eu.bcvsolutions.idm.core.eav.api.service.FormService;
/**
* Find {@link IdmFormProjectionDto} by uuid identifier or by {@link Codeable} identifier.
*
* @author Radek Tomiška
* @param <T> dto
* @since 11.0.0
*/
public abstract class AbstractFormProjectionLookup<DTO extends BaseDto> implements FormProjectionLookup<DTO> {
@Autowired private ObjectMapper mapper;
//
private final Class<?> domainType;
/**
* Creates a new {@link AbstractFormProjectionLookup} instance discovering the supported type from the generics signature.
*/
public AbstractFormProjectionLookup() {
this.domainType = GenericTypeResolver.resolveTypeArgument(getClass(), FormProjectionLookup.class);
}
/*
* (non-Javadoc)
* @see org.springframework.plugin.core.Plugin#supports(java.lang.Object)
*/
@Override
public boolean supports(Class<?> delimiter) {
return domainType.equals(delimiter);
}
@Override
public IdmFormDefinitionDto lookupBasicFieldsDefinition(DTO dto) {
return getBasicFieldsDefinition(dto);
}
@Override
public IdmFormDefinitionDto lookupFormDefinition(DTO dto, IdmFormDefinitionDto formDefinition) {
return getFormDefinition(dto, formDefinition);
}
/**
* Construct basic fields form definition.
*
* @param dto basic fields owner
* @return basic fields form definition
*/
protected IdmFormDefinitionDto getBasicFieldsDefinition(DTO dto) {
return getFormDefinition(dto, null); // null ~ basicFileds ~ without form definition
}
/**
* Get overriden / configured form definition by projection.
* @param dto projection owner
* @param formDefinition form definition to load
* @return overriden form definition
*
* @since 12.0.0
*/
protected IdmFormDefinitionDto getFormDefinition(DTO dto, IdmFormDefinitionDto formDefinition) {
IdmFormProjectionDto formProjection = lookupProjection(dto);
if (formProjection == null) {
return null;
}
String formValidations = formProjection.getFormValidations();
if (StringUtils.isEmpty(formValidations)) {
return null;
}
//
if (formDefinition == null) { // ~ basic fields
formDefinition = new IdmFormDefinitionDto();
formDefinition.setCode(FormService.FORM_DEFINITION_CODE_BASIC_FIELDS);
}
IdmFormDefinitionDto overridenDefinition = new IdmFormDefinitionDto(); // clone ~ prevent to change input (e.g. cache can be modified)
overridenDefinition.setId(formDefinition.getId());
overridenDefinition.setCode(formDefinition.getCode());
// transform form attributes from json
try {
List<IdmFormAttributeDto> attributes = mapper.readValue(formValidations, new TypeReference<List<IdmFormAttributeDto>>() {});
attributes
.stream()
.filter(attribute -> Objects.equals(attribute.getFormDefinition(), overridenDefinition.getId()))
.forEach(attribute -> {
if (attribute.getId() == null) {
// we need artificial id to find attributes in definition / instance
attribute.setId(UUID.randomUUID());
}
overridenDefinition.addFormAttribute(attribute);
});
//
return overridenDefinition;
} catch (IOException ex) {
throw new ResultCodeException(
CoreResultCode.FORM_PROJECTION_WRONG_VALIDATION_CONFIGURATION,
ImmutableMap.of("formProjection", formProjection.getCode()),
ex
);
}
}
/**
* Add value, if it's filled into filled values.
*
* @param filledValues filled values
* @param formDefinition fields form definition (e.g. basic fields form definition)
* @param attributeCode attribute code
* @param attributeValue attribute value
*/
protected void appendAttributeValue(
List<IdmFormValueDto> filledValues,
IdmFormDefinitionDto formDefinition,
String attributeCode,
Serializable attributeValue) {
if (attributeValue == null) {
return;
}
IdmFormAttributeDto attribute = formDefinition.getMappedAttributeByCode(attributeCode);
if (attribute == null) {
return;
}
if (attribute.getPersistentType() == null) {
if (attributeValue instanceof UUID) {
attribute.setPersistentType(PersistentType.UUID);
} else if (attributeValue instanceof LocalDate) {
attribute.setPersistentType(PersistentType.DATE);
} else {
// TODO: support other persistent types (unused now)
attribute.setPersistentType(PersistentType.TEXT);
}
}
//
IdmFormValueDto value = new IdmFormValueDto(attribute);
value.setValue(attributeValue);
filledValues.add(value);
}
} | bcvsolutions/CzechIdMng | Realization/backend/core/core-api/src/main/java/eu/bcvsolutions/idm/core/api/rest/lookup/AbstractFormProjectionLookup.java | Java | mit | 5,497 |
module EchoNest
module Xml
class AudioDoc
include HappyMapper
tag :doc
element :artist_id, String
element :foreign_artist_id, String
element :artist, String
element :release, String
element :title, String
element :url, String
element :link, String
element :date, String
element :length, String
end
end
end
| gingerhendrix/echonest | lib/echonest/xml/audio_doc.rb | Ruby | mit | 399 |
from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth import urls as djangoauth_urls
from search import views as search_views
from blog import views as blog_views
from wagtail.wagtailadmin import urls as wagtailadmin_urls
from wagtail.wagtailcore import urls as wagtail_urls
from wagtail.wagtaildocs import urls as wagtaildocs_urls
urlpatterns = [
url(r'^', include(djangoauth_urls)),
url(r'^django-admin/', include(admin.site.urls)),
url(r'^admin/', include(wagtailadmin_urls)),
url(r'^documents/', include(wagtaildocs_urls)),
url(r'^search/$', search_views.search, name='search'),
# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
url(r'', include(wagtail_urls)),
# Alternatively, if you want Wagtail pages to be served from a subpath
# of your site, rather than the site root:
# url(r'^pages/', include(wagtail_urls)),
]
if settings.DEBUG:
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
# Serve static and media files from development server
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
| philba/myblog | myblog/urls.py | Python | mit | 1,474 |
/* -*- mode:C++; -*- */
/* MIT License -- MyThOS: The Many-Threads Operating System
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Copyright 2016 Robert Kuban, Randolf Rotta, and contributors, BTU Cottbus-Senftenberg
*/
#include "objects/CapEntry.hh"
#include "objects/mlog.hh"
#include "util/error-trace.hh"
namespace mythos {
void CapEntry::initRoot(Cap c)
{
ASSERT(isKernelAddress(this));
ASSERT(c.isUsable());
ASSERT(cap().isEmpty());
Link loopLink(this);
_next.store(loopLink.value());
_prev.store(loopLink.value());
_cap.store(c.value());
}
bool CapEntry::tryAcquire()
{
auto expected = Cap::asEmpty().value();
const auto desired = Cap::asAllocated().value();
return _cap.compare_exchange_strong(expected, desired);
}
optional<void> CapEntry::acquire()
{
if (tryAcquire()) RETURN(Error::SUCCESS);
else THROW(Error::CAP_NONEMPTY);
}
void CapEntry::commit(const Cap& cap)
{
ASSERT(isLinked());
_cap.store(cap.value());
}
void CapEntry::reset()
{
ASSERT(isUnlinked() || cap().isAllocated());
_prev.store(Link().value());
_next.store(Link().value());
// mark as empty
_cap.store(Cap().value());
}
void CapEntry::setPrevPreserveFlags(CapEntry* ptr)
{
auto expected = _prev.load();
uintlink_t desired;
do {
desired = Link(expected).withPtr(ptr).value();
} while (!_prev.compare_exchange_weak(expected, desired));
}
optional<void> CapEntry::moveTo(CapEntry& other)
{
ASSERT(other.cap().isAllocated());
ASSERT(!other.isLinked());
if (!lock_prev()) {
other.reset();
THROW(Error::GENERIC_ERROR);
}
lock();
auto thisCap = cap();
if (isRevoking() || !thisCap.isUsable()) {
other.reset();
unlock();
unlock_prev();
THROW(Error::INVALID_CAPABILITY);
}
auto next= Link(_next).withoutFlags();
auto prev= Link(_prev).withoutFlags();
next->setPrevPreserveFlags(&other);
other._next.store(next.value());
// deleted or revoking can not be set in other._prev
// as we allocated other for moving
other._prev.store(prev.value());
prev->_next.store(Link(&other).value());
other.commit(thisCap);
_prev.store(Link().value());
_next.store(Link().value());
_cap.store(Cap().value());
RETURN(Error::SUCCESS);
}
bool CapEntry::kill()
{
auto expected = _cap.load();
Cap curCap;
do {
curCap = Cap(expected);
MLOG_DETAIL(mlog::cap, this, ".kill", DVAR(curCap));
if (!curCap.isUsable()) {
return curCap.isZombie() ? true : false;
}
} while (!_cap.compare_exchange_strong(expected, curCap.asZombie().value()));
return true;
}
optional<void> CapEntry::unlink()
{
auto next = Link(_next).withoutFlags();
auto prev = Link(_prev).withoutFlags();
next->_prev.store(prev.value());
prev->_next.store(next.value());
_prev.store(Link().value());
_next.store(Link().value());
RETURN(Error::SUCCESS);
}
Error CapEntry::try_lock_prev()
{
auto prev = Link(_prev).ptr();
if (!prev) {
return Error::GENERIC_ERROR;
}
if (prev->try_lock()) {
if (Link(_prev.load()).ptr() == prev) {
return Error::SUCCESS;
} else { // my _prev has changed in the mean time
prev->unlock();
return Error::RETRY;
}
} else return Error::RETRY;
}
bool CapEntry::lock_prev()
{
Error result;
for (result = try_lock_prev(); result == Error::RETRY; result = try_lock_prev()) {
hwthread_pause();
}
return result == Error::SUCCESS;
}
} // namespace mythos
| ManyThreads/mythos | kernel/objects/capability-spinning/objects/CapEntry.cc | C++ | mit | 4,691 |
<?php
use Winged\Model\Model;
/**
* Class Cidades
*
* @package Winged\Model
*/
class Cidades extends Model
{
public function __construct()
{
parent::__construct();
return $this;
}
/** @var $id_cidade integer */
public $id_cidade;
/** @var $id_estado integer */
public $id_estado;
/** @var $cidade string */
public $cidade;
/**
* @return string
*/
public static function tableName()
{
return "cidades";
}
/**
* @return string
*/
public static function primaryKeyName()
{
return "id_cidade";
}
/**
* @param bool $pk
*
* @return $this|int|Model
*/
public function primaryKey($pk = false)
{
if ($pk && (is_int($pk) || intval($pk) != 0)) {
$this->id_cidade = $pk;
return $this;
}
return $this->id_cidade;
}
/**
* @return array
*/
public function behaviors()
{
return [];
}
/**
* @return array
*/
public function reverseBehaviors()
{
return [];
}
/**
* @return array
*/
public function labels()
{
return [
'cidade' => 'Nome da cidade: ',
'id_estado' => 'Estado em que está localizada: ',
];
}
/**
* @return array
*/
public function messages()
{
return [
'cidade' => [
'required' => 'Esse campo é obrigatório',
],
'id_estado' => [
'required' => 'Esse campo é obrigatório',
],
];
}
/**
* @return array
*/
public function rules()
{
return [
'id_estado' => [
'required' => true,
],
'cidade' => [
'required' => true,
]
];
}
} | matheuswf/winged-framework | projects/admin/models/Cidades.php | PHP | mit | 1,918 |
(function () {
angular.module('travelApp', ['toursApp'])
.service('dateParse', function () {
this.myDateParse = function (value) {
var pattern = /Date\(([^)]+)\)/;
var results = pattern.exec(value);
var dt = new Date(parseFloat(results[1]));
return dt;
}
})
.filter('myDateFormat', [
'dateParse', function (dateParse) {
return function (x) {
return dateParse.myDateParse(x);
};
}
]);
})();
| safaridato/travelite | assets/js/ng/ap.js | JavaScript | mit | 591 |
<?php
# MetInfo Enterprise Content Management System
# Copyright (C) MetInfo Co.,Ltd (http://www.metinfo.cn). All rights reserved.
$depth='../';
require_once $depth.'../login/login_check.php';
require_once ROOTPATH.'include/export.func.php';
if($action=='code'){
$met_file='/sms/code.php';
$post=array('total_pass'=>$total_pass,'total_email'=>$total_email,'total_weburl'=>$total_weburl,'total_code'=>$total_code);
$re = curl_post($post,30);
if($re=='error_no'){
$lang_re=$lang_smstips79;
}elseif($re=='error_use'){
$lang_re=$lang_smstips80;
}elseif($re=='error_time'){
$lang_re=$lang_smstips81;
}else{
$lang_re=$lang_smstips82;
}
metsave("../app/sms/index.php?lang=$lang&anyid=$anyid&cs=$cs",$lang_re,$depth);
}
$total_passok = $db->get_one("SELECT * FROM $met_otherinfo WHERE lang='met_sms'");
if($total_passok['authpass']==''){
if($action=='savedata'){
$query = "delete from $met_otherinfo where lang='met_sms'";
$db->query($query);
$query = "INSERT INTO $met_otherinfo SET
authpass = '$total_pass',
lang = 'met_sms'";
$db->query($query);
echo 'ok';
die();
}
}
if(!function_exists('fsockopen')&&!function_exists('pfsockopen')&&!get_extension_funcs('curl')){
$disable="disabled=disabled";
$fstr.=$lang_smstips77;
}
$css_url=$depth."../templates/".$met_skin."/css";
$img_url=$depth."../templates/".$met_skin."/images";
include template('app/sms/index');footer();
# This program is an open source system, commercial use, please consciously to purchase commercial license.
# Copyright (C) MetInfo Co., Ltd. (http://www.metinfo.cn). All rights reserved.
?> | maicong/OpenAPI | MetInfo5.2/admin/app/sms/index.php | PHP | mit | 1,617 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="fr_CA" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About People</source>
<translation>Au sujet de People</translation>
</message>
<message>
<location line="+39"/>
<source><b>People</b> version</source>
<translation>Version de <b>People</b></translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2014-%1 The People developers</source>
<translation type="unfinished"/>
</message>
<message>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2014-[CLIENT_LAST_COPYRIGHT] The People developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:eay@cryptsoft.com">eay@cryptsoft.com</a>) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+218"/>
<source>Label</source>
<translation>Étiquette</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>pubkey</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>stealth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
<message>
<location line="+4"/>
<source>Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>n/a</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Dialogue de phrase de passe</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Saisir la phrase de passe</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nouvelle phrase de passe</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Répéter la phrase de passe</translation>
</message>
<message>
<location line="+33"/>
<location line="+16"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>Sert à désactiver les transactions sortantes si votre compte de système d'exploitation est compromis. Ne procure pas de réelle sécurité.</translation>
</message>
<message>
<location line="-13"/>
<source>For staking only</source>
<translation>Pour "staking" seulement</translation>
</message>
<message>
<location line="+16"/>
<source>Enable messaging</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+39"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Saisir la nouvelle phrase de passe pour le portefeuille. <br/>Veuillez utiliser une phrase de passe de <b>10 caractères aléatoires ou plus</b>, ou de <b>huit mots ou plus</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Crypter le portefeuille</translation>
</message>
<message>
<location line="+11"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déverrouiller le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Déverrouiller le portefeuille</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Cette opération nécessite votre phrase de passe pour déchiffrer le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Déchiffrer le portefeuille</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Changer la phrase de passe</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Saisir l’ancienne et la nouvelle phrase de passe du portefeuille</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Confirmer le cryptage du portefeuille</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation>ATTENTION : Si vous cryptez votre portefeuille et perdez votre passphrase, vous ne pourrez plus accéder à vos People</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Êtes-vous sûr de vouloir crypter votre portefeuille ?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT : Toute sauvegarde précédente de votre fichier de portefeuille devrait être remplacée par le nouveau fichier de portefeuille crypté. Pour des raisons de sécurité, les sauvegardes précédentes de votre fichier de portefeuille non crypté deviendront inutilisables dès lors que vous commencerez à utiliser le nouveau portefeuille crypté.</translation>
</message>
<message>
<location line="+104"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Attention : la touche Verr. Maj. est activée !</translation>
</message>
<message>
<location line="-134"/>
<location line="+61"/>
<source>Wallet encrypted</source>
<translation>Portefeuille crypté</translation>
</message>
<message>
<location line="-59"/>
<source>People will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation>L'application People va désormais se terminer afin de finaliser le processus de cryptage. Merci de noter que le cryptage du portefeuille ne garantit pas de se prémunir du vol via l'utilisation de malware, qui auraient pu infecter votre ordinateur. </translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+45"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Le cryptage du portefeuille a échoué</translation>
</message>
<message>
<location line="-57"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Le cryptage du portefeuille a échoué en raison d'une erreur interne. Votre portefeuille n'a pas été crypté.</translation>
</message>
<message>
<location line="+7"/>
<location line="+51"/>
<source>The supplied passphrases do not match.</source>
<translation>Les phrases de passe saisies ne correspondent pas.</translation>
</message>
<message>
<location line="-39"/>
<source>Wallet unlock failed</source>
<translation>Le déverrouillage du portefeuille a échoué</translation>
</message>
<message>
<location line="+1"/>
<location line="+13"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La phrase de passe saisie pour décrypter le portefeuille était incorrecte.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Le décryptage du portefeuille a échoué</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>La phrase de passe du portefeuille a été modifiée avec succès.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+137"/>
<source>Network Alert</source>
<translation>Alerte réseau</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Fonctions de contrôle des monnaies</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Quantité :</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Octets :</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Montant :</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Priorité :</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Frais :</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Sortie faible :</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+528"/>
<location line="+30"/>
<source>no</source>
<translation>non</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Après les frais :</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Monnaie :</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>Tout (dé)sélectionner</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Mode arborescence</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Mode liste</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Intitulé</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Confirmations</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Confirmée</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Priorité</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-520"/>
<source>Copy address</source>
<translation>Copier l’adresse</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copier l’étiquette</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Copier le montant</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>Copier l'ID de la transaction</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Copier la quantité</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Copier les frais</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Copier le montant après les frais</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Copier les octets</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Copier la priorité</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Copier la sortie faible</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Copier la monnaie</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>la plus élevée</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>élevée</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>moyennement-élevée</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>moyenne</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>moyennement-basse</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>basse</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>la plus basse</translation>
</message>
<message>
<location line="+130"/>
<location line="+30"/>
<source>DUST</source>
<translation>DUST</translation>
</message>
<message>
<location line="-30"/>
<location line="+30"/>
<source>yes</source>
<translation>oui</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>Cet intitulé passe au rouge, si la taille de la transaction est supérieure à 10000 bytes.
Cela implique que des frais à hauteur d'au moins %1 par kb seront nécessaires.
Ceux-ci Peuvent varier de +/- 1 Byte par entrée.</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation>Les transactions avec une priorité haute ont plus de chances d'être traitées en un block.
Rouge si votre priorité est plus petite que "moyenne".
Cela veut dire que des frais d'un minimum de %1 par kb sont requis</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Ce label passe au rouge, Lorsqu'un destinataire reçoit un montant inférieur à %1.
Cela implique que des frais à hauteur de %2 seront nécessaire
Les montants inférieurs à 0.546 fois les frais minimum de relais apparaissent en tant que DUST.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Ce label passe au rouge, lorsque la différence est inférieure à %1.
Cela implique que des frais à hauteur d'au moins %2 seront nécessaires.</translation>
</message>
<message>
<location line="+40"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(aucune étiquette)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>monnaie de %1 (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(monnaie)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Modifier l'adresse</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Étiquette</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>L'intitulé associé à cette entrée du carnet d'adresse</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresse</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>L'intitulé associé à cette entrée du carnet d'adresse. Seules les adresses d'envoi peuvent être modifiées.</translation>
</message>
<message>
<location line="+7"/>
<source>&Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Nouvelle adresse de réception</translation>
</message>
<message>
<location line="+7"/>
<source>New sending address</source>
<translation>Nouvelle adresse d’envoi</translation>
</message>
<message>
<location line="+4"/>
<source>Edit receiving address</source>
<translation>Modifier l’adresse de réception</translation>
</message>
<message>
<location line="+7"/>
<source>Edit sending address</source>
<translation>Modifier l’adresse d'envoi</translation>
</message>
<message>
<location line="+82"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>L’adresse fournie « %1 » est déjà présente dans le carnet d'adresses.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid People address.</source>
<translation>L'adresse "%1" renseignée n'est pas une adresse People valide.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Impossible de déverrouiller le portefeuille.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Échec de génération de la nouvelle clef.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+526"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+0"/>
<location line="+12"/>
<source>People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Usage:</source>
<translation>Utilisation:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>Options de ligne de commande</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Options graphiques</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Définir la langue, par exemple « fr_FR » (par défaut : la langue du système)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Démarrer en mode réduit</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Affichage de l'écran de démarrage (défaut: 1)</translation>
</message>
</context>
<context>
<name>MessageModel</name>
<message>
<location filename="../messagemodel.cpp" line="+376"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Sent Date Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Received Date Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>To Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>From Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send Secure Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send failed: %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+1"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start people: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<location filename="../peertablemodel.cpp" line="+118"/>
<source>Address/Hostname</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>User Agent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Ping Time</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../guiutil.cpp" line="-470"/>
<source>%1 d</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 h</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 m</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<location line="+55"/>
<source>%1 s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>None</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>%1 ms</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nom du client</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+36"/>
<location line="+23"/>
<location line="+23"/>
<location line="+491"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<location line="+23"/>
<source>N/A</source>
<translation>N.D.</translation>
</message>
<message>
<location line="-1062"/>
<source>Client version</source>
<translation>Version du client</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informations</translation>
</message>
<message>
<location line="-10"/>
<source>People - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>People Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Using OpenSSL version</source>
<translation>Version d'OpenSSL utilisée</translation>
</message>
<message>
<location line="+26"/>
<source>Using BerkeleyDB version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Heure de démarrage</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Réseau</translation>
</message>
<message>
<location line="+7"/>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Number of connections</source>
<translation>Nombre de connexions</translation>
</message>
<message>
<location line="+157"/>
<source>Show the People help message to get a list with possible People command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+99"/>
<source>&Network Traffic</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Totals</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<location filename="../rpcconsole.cpp" line="+396"/>
<source>In:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+80"/>
<location filename="../rpcconsole.cpp" line="+1"/>
<source>Out:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>&Peers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<location filename="../rpcconsole.cpp" line="-167"/>
<location line="+328"/>
<source>Select a peer to view detailed information.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Peer ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Direction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>User Agent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Services</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Starting Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Sync Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Ban Score</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Connection Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Bytes Sent</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Bytes Received</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Ping Time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Time Offset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-866"/>
<source>Block chain</source>
<translation>Chaîne de blocks</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Nombre actuel de blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Nombre total estimé de blocks</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Horodatage du dernier block</translation>
</message>
<message>
<location line="+49"/>
<source>Open the People debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Open</source>
<translation>&Ouvrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Options de ligne de commande</translation>
</message>
<message>
<location line="+10"/>
<source>&Show</source>
<translation>&Afficher</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Console</translation>
</message>
<message>
<location line="-266"/>
<source>Build date</source>
<translation>Date de compilation</translation>
</message>
<message>
<location line="+206"/>
<source>Debug log file</source>
<translation>Journal de débogage</translation>
</message>
<message>
<location line="+109"/>
<source>Clear console</source>
<translation>Nettoyer la console</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-197"/>
<source>Welcome to the People Core RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Utiliser les touches de curseur pour naviguer dans l'historique et <b>Ctrl-L</b> pour effacer l'écran.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Taper <b>help</b> pour afficher une vue générale des commandes disponibles.</translation>
</message>
<message>
<location line="+233"/>
<source>via %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+1"/>
<source>never</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Inbound</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Outbound</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Unknown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<location line="+1"/>
<source>Fetching...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PeopleBridge</name>
<message>
<location filename="../peoplebridge.cpp" line="+410"/>
<source>Incoming Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+58"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source><b>%1</b> to PEOPLE %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source><b>%1</b> PEOPLE, ring size %2 to PEOPLE %3 (%4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source><b>%1</b> PEOPLE, ring size %2 to MEN %3 (%4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<location line="+10"/>
<location line="+12"/>
<location line="+8"/>
<source>Error:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Unknown txn type detected %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Input types must match for all recipients.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Ring sizes must match for all recipients.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Ring size outside range [%1, %2].</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<location line="+9"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Are you sure you want to send?
Ring size of one is not anonymous, and harms the network.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+9"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<location line="+25"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>The change address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<location line="+376"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-371"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<location line="+365"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-360"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Narration is too long.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Ring Size Error.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Input Type Error.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Must be in full mode to send anon.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Invalid Stealth Address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your people balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error generating transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error generating transaction: %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+304"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>The message can't be empty.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Error: Message creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The message was rejected.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+98"/>
<source>Sanity Error!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: a sanity check prevented the transfer of a non-group private key, please close your wallet and report this error to the development team as soon as possible.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bridgetranslations.h" line="+8"/>
<source>Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Notifications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Management</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add New Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Import Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Advanced</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change Passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(Un)lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Tools</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chain Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Block Explorer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Debug</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>About People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>About QT</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>QR code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Narration:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>MEN</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>WOMEN</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>µMEN</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Peoplehi</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add new receive address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Add Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add a new contact</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Lookup</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Normal</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Stealth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>BIP32</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Public Key</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction Hash</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recent Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Market</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Advanced Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Make payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balance transfer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>LowOutput:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>From account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>PUBLIC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>PRIVATE</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Ring Size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>To account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Pay to</source>
<translation type="unfinished"/>
</message>
<message>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+135"/>
<source>Tor connection offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>i2p connection offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet is encrypted and currently locked</source>
<translation type="unfinished"/>
</message>
<message>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open chat list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Values</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Outputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a PeopleCash address to sign the message with (e.g. SaKYqfD8J3vw4RTnqtgk2K9B67CBaL3mhV)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the message you want to sign</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Click sign message to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy the signed message signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a PeopleCash address to verify the message with (e.g. SaKYqfD8J3vw4RTnqtgk2K9B67CBaL3mhV)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the message you want to verify</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a PeopleCash signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Paste signature from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Your total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Balances overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recent in/out transactions or stakes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select inputs to spend</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Optional address to receive transaction change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Current spendable send payment balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Current spendable balance to account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>The address to transfer the balance to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The label for this address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount to transfer</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Double click to edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Short payment note.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The address to send the payment to (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a public key for the address above</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Name for this Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a password</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Would you like to create a bip44 path?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Your recovery phrase (Keep this safe!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Make Default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Activate/Deactivate</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set as Master</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>0 active connections to People network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>The address to send the payment to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a label for this address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter a short note to send with payment (max 24 characters)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Wallet Name for recovered account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the password for the wallet you are trying to recover</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Is this a bip44 path?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-66"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-122"/>
<source>Narration</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Default Stealth Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Clear All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Suggest Ring Size</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>RECEIVE</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Filter by type..</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>TRANSACTIONS</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ADDRESSBOOK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Delete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Private Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Name:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Public Key:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Choose identity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Identity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start Group Conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Group name:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Create Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite others</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite others to group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite to Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invite</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>GROUP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>BOOK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start private conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start group conversation</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>CHAT</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Leave Group</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>CHAIN DATA</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Coin Value</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Owned (Mature)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>System (Mature)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Spends</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Least Depth</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>BLOCK EXPLORER</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Refresh</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Hash</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Height</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Value Out</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>OPTIONS</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>I2P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Tor</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start People on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Pay transaction fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Most transactions are 1kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enable Staking</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Reserve:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimum Stake Interval</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimum Ring size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum Ring size:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Automatically select ring size</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enable Secure messaging</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Mode (Requires Restart)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Full Index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Thin Index Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Map port using UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Proxy IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>SOCKS Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Minimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>User Interface language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rows per page:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Notifications:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Visible Transaction Types:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>I2P (coming soon)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>TOR (coming soon)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Ok</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lets create a New Wallet and Account to get you started!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Password</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Add an optional Password to secure the Recovery Phrase (shown on next page)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Would you like to create a Multi-Account HD Key? (BIP44)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Language</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>English</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>French</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Japanese</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Spanish</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chinese (Simplified)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Chinese (Traditional)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Next Step</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Write your Wallet Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Important!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need the Wallet Recovery Phrase to restore this wallet. Write it down and keep them somewhere safe.
You will be asked to confirm the Wallet Recovery Phrase in the next screen to ensure you have written it down correctly</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Back</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Please confirm your Wallet Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Congratulations! You have successfully created a New Wallet and Account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You can now use your Account to send and receive funds :)
Remember to keep your Wallet Recovery Phrase and Password (if set) safe in case you ever need to recover your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Lets import your Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>The Wallet Recovery Phrase could require a password to be imported</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Is this a Multi-Account HD Key (BIP44)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Recovery Phrase (Usually 24 words)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Congratulations! You have successfully imported your Wallet from your Recovery Phrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You can now use your Account to send and receive funds :)
Remember to keep your Wallet Recovery Phrase and Password safe in case you ever need to recover your wallet again!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Accounts</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Created</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Active Account</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet Keys</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Path</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Active</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Master</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PeopleGUI</name>
<message>
<location filename="../people.cpp" line="+111"/>
<source>A fatal error occurred. People can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../peoplegui.cpp" line="+89"/>
<location line="+178"/>
<source>Hpeople</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-178"/>
<source>Client</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&About People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Modify configuration options for People</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<location line="+9"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+74"/>
<source>Hpeople client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+63"/>
<source>%n active connection(s) to People network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>header</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>headers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<location line="+22"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Downloading filtered blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>~%1 filtered block(s) remaining (%2% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Importing blocks...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+5"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+13"/>
<location line="+4"/>
<source>Imported</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<location line="+4"/>
<source>Downloaded</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-3"/>
<source>%1 of %2 %3 of transaction history (%4% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>%1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+23"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+3"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+7"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Last received %1 was generated %2.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<location line="+15"/>
<source>Incoming Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
From Address: %2
To Address: %3
Message: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid People address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking and messaging only.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for messaging only.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking only.</source>
<translation type="unfinished"/>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b> for staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet must first be encrypted to be locked.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+69"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+1"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+9"/>
<source>Staking.
Your weight is %1
Network weight is %2
Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Not staking because wallet is in thin mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking, staking is disabled</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../transactionrecord.cpp" line="+23"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received people</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent people</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+79"/>
<source>KB/s</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation><numerusform>Ouvert pour %n bloc</numerusform><numerusform>Ouvert pour %n blocks</numerusform></translation>
</message>
<message>
<location line="+7"/>
<source>conflicted</source>
<translation>en conflit</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/hors ligne</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/non confirmée</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmations</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>État</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, diffusée à travers %n nœud</numerusform><numerusform>, diffusée à travers %n nœuds</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Source</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Généré</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<location line="+20"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="-19"/>
<location line="+20"/>
<location line="+23"/>
<location line="+57"/>
<source>To</source>
<translation>À</translation>
</message>
<message>
<location line="-96"/>
<location line="+2"/>
<location line="+18"/>
<location line="+2"/>
<source>own address</source>
<translation>votre propre adresse</translation>
</message>
<message>
<location line="-22"/>
<location line="+20"/>
<source>label</source>
<translation>étiquette</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+44"/>
<location line="+20"/>
<location line="+40"/>
<source>Credit</source>
<translation>Crédit</translation>
</message>
<message numerus="yes">
<location line="-114"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>arrive à maturité dans %n bloc de plus</numerusform><numerusform>arrive à maturité dans %n blocks supplémentaires</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>refusé</translation>
</message>
<message>
<location line="+43"/>
<location line="+8"/>
<location line="+16"/>
<location line="+42"/>
<source>Debit</source>
<translation>Débit</translation>
</message>
<message>
<location line="-52"/>
<source>Transaction fee</source>
<translation>Frais de transaction</translation>
</message>
<message>
<location line="+19"/>
<source>Net amount</source>
<translation>Montant net</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Message</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Commentaire</translation>
</message>
<message>
<location line="+12"/>
<source>Transaction ID</source>
<translation>ID de la transaction</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Informations de débogage</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaction</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Entrants</translation>
</message>
<message>
<location line="+44"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>vrai</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>faux</translation>
</message>
<message>
<location line="-266"/>
<source>, has not been successfully broadcast yet</source>
<translation>, n’a pas encore été diffusée avec succès</translation>
</message>
<message>
<location line="+36"/>
<location line="+20"/>
<source>unknown</source>
<translation>inconnu</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Détails de la transaction</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ce panneau affiche une description détaillée de la transaction</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+217"/>
<source>Date</source>
<translation>Date</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresse</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Montant</translation>
</message>
<message>
<location line="+54"/>
<source>Open until %1</source>
<translation>Ouvert jusqu'à %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmée (%1 confirmations)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ouvert pour %n bloc de plus</numerusform><numerusform>Ouvert pour %n blocs de plus</numerusform></translation>
</message>
<message>
<location line="-51"/>
<source>Narration</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>Offline</source>
<translation>Hors ligne</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Non confirmé</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Confirmation (%1 sur %2 confirmations recommandées)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>En conflit</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Immature (%1 confirmations, sera disponible après %2)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ce bloc n’a été reçu par aucun autre nœud et ne sera probablement pas accepté !</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Généré mais pas accepté</translation>
</message>
<message>
<location line="+49"/>
<source>(n/a)</source>
<translation>(n.d)</translation>
</message>
<message>
<location line="+202"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>État de la transaction. Laissez le pointeur de la souris sur ce champ pour voir le nombre de confirmations.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Date et heure de réception de la transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Type de transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>L’adresse de destination de la transaction.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Montant ajouté ou enlevé au solde.</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+393"/>
<location line="+246"/>
<source>Sending...</source>
<translation>Envoi...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>People version</source>
<translation>Version People</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Utilisation :</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or peopled</source>
<translation>Envoyer commande à -server ou peopled</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Lister les commandes</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Obtenir de l’aide pour une commande</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Options :</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: people.conf)</source>
<translation>Spécifier le fichier de configuration (defaut: people.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: peopled.pid)</source>
<translation>Spécifier le fichier pid (defaut: peopled.pid)
</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Spécifiez le fichier de portefeuille (dans le répertoire de données)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Spécifier le répertoire de données</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Définir la taille du tampon en mégaoctets (par défaut : 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Définir la taille du tampon en mégaoctets (par défaut : 100)</translation>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 51737 or testnet: 51997)</source>
<translation>Écouter les connexions sur le <port> (default: 51737 or testnet: 51997)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Garder au plus <n> connexions avec les pairs (par défaut : 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Se connecter à un nœud pour obtenir des adresses de pairs puis se déconnecter</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Spécifier votre propre adresse publique</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Connexion à l'adresse fournie. Utiliser la notation [machine]:port pour les adresses IPv6</translation>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation>Stacker vos monnaies afin de soutenir le réseau et d'obtenir des intérêts (default: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Seuil de déconnexion des pairs de mauvaise qualité (par défaut : 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Délai en secondes de refus de reconnexion aux pairs de mauvaise qualité (par défaut : 86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Une erreur est survenue lors du réglage du port RPC %u pour écouter sur IPv4 : %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation>Détacher la base de donnée des blocks et adresses. Augmente le temps de fermeture (default: 0)</translation>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Erreur: La transaction a été rejetée. Cela peut se produire si une quantité d'argent de votre portefeuille a déjà été dépensée, comme dans le cas où une copie du fichier wallet.dat aurait été utilisée afin d'effectuer des dépenses, à la place du fichier courant.</translation>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation>Erreur: Cette transaction requière des frais minimum de %s a cause de son montant, de sa complexité ou de l'utilisation de fonds récemment reçus.</translation>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 51736 or testnet: 51996)</source>
<translation>Écouter les connexions JSON-RPC sur le <port> (default: 51736 or testnet: 51996)</translation>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accepter les commandes de JSON-RPC et de la ligne de commande</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation>Erreur: La création de cette transaction à échouée</translation>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation>Erreur: Portefeuille verrouillé, impossible d'effectuer cette transaction</translation>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation>Importation du fichier blockchain</translation>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation>Importation du fichier blockchain</translation>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Fonctionner en arrière-plan en tant que démon et accepter les commandes</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Utiliser le réseau de test</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accepter les connexions entrantes (par défaut : 1 si aucun -proxy ou -connect )</translation>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>Une erreur est survenue lors du réglage du port RPC %u pour écouter sur IPv6, retour à IPv4 : %s</translation>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation>Erreur lors de l'initialisation de l'environnement de base de données %s! Afin de procéder à la récupération, une SAUVEGARDE DE CE REPERTOIRE est nécessaire, puis, supprimez le contenu entier de ce répertoire, à l'exception du fichier wallet.dat </translation>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Fixer la taille maximale d'un block en bytes (default: 27000)</translation>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Attention : -paytxfee est réglée sur un montant très élevé ! Il s'agit des frais de transaction que vous payerez si vous envoyez une transaction.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong People will not work properly.</source>
<translation>Avertissement: Veuillez vérifier la date et l'heure de votre ordinateur. People ne pourra pas fonctionner correctement si l'horloge est réglée de façon incorrecte</translation>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Avertissement : une erreur est survenue lors de la lecture de wallet.dat ! Toutes les clefs ont été lues correctement mais les données de transaction ou les entrées du carnet d'adresses sont peut-être incorrectes ou manquantes.</translation>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Avertissement : wallet.dat corrompu, données récupérées ! Le fichier wallet.dat original a été enregistré en tant que wallet.{timestamp}.bak dans %s ; si votre solde ou transactions sont incorrects vous devriez effectuer une restauration depuis une sauvegarde.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Tenter de récupérer les clefs privées d'un wallet.dat corrompu</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Options de création de bloc :</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Ne se connecter qu'au(x) nœud(s) spécifié(s)</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Découvrir sa propre adresse IP (par défaut : 1 lors de l'écoute et si aucun -externalip)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Échec de l'écoute sur un port quelconque. Utilisez -listen=0 si vous voulez ceci.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation>Trouvez des peers utilisant DNS lookup (default: 1)</translation>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation>Politique de synchronisation des checkpoints (default: strict)</translation>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation>Adresse -tor invalide: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>Montant incorrect pour -reservebalance=<montant></translation>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Tampon maximal de réception par « -connection » <n>*1 000 octets (par défaut : 5 000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Tampon maximal d'envoi par « -connection », <n>*1 000 octets (par défaut : 1 000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Se connecter uniquement aux nœuds du réseau <net> (IPv4, IPv6 ou Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Voir les autres informations de débogage. Implique toutes les autres options -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Voir les autres informations de débogage du réseau</translation>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation>Horodater les messages de debug</translation>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>Options SSL : (voir le Wiki de Bitcoin pour les instructions de configuration du SSL)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Sélectionner la version du proxy socks à utiliser (4-5, par défaut: 5)</translation>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Envoyer les informations de débogage/trace à la console au lieu du fichier debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Envoyer les informations de débogage/trace à la console au lieu du fichier debug.log</translation>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Fixer la taille maximale d'un block en bytes (default: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Définir la taille minimale de bloc en octets (par défaut : 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Réduire le fichier debug.log lors du démarrage du client (par défaut : 1 lorsque -debug n'est pas présent)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Spécifier le délai d'expiration de la connexion en millisecondes (par défaut : 5 000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation>Impossible de "signer" le checkpoint, mauvaise clef de checkpoint?
</translation>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Utiliser l'UPnP pour rediriger le port d'écoute (par défaut : 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Utiliser l'UPnP pour rediriger le port d'écoute (par défaut : 1 lors de l'écoute)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utiliser un proxy pour atteindre les services cachés (défaut: équivalent à -proxy)</translation>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Nom d'utilisateur pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation>Vérification d'intégrité de la base de données...</translation>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation>ATTENTION : violation du checkpoint de synchronisation, mais ignorée!</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation>Avertissement: Espace disque faible!</translation>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Avertissement : cette version est obsolète, une mise à niveau est nécessaire !</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrompu, la récupération a échoué</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Mot de passe pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=peoplerpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "People Alert" admin@foo.com
</source>
<translation>%s, vous devez définir un mot de passe rpc 'rpcpassword' au sein du fichier de configuration:
%s
Il est recommandé d'utiliser le mot de passe aléatoire suivant:
rpcuser=peoplerpc
rpcpassword=%s
(il n'est pas nécessaire de retenir ce mot de passe)
Le nom d'utilisateur et le mot de passe doivent IMPERATIVEMENT être différents.
Si le fichier n'existe pas, il est nécessaire de le créer, avec les droit de lecture au propriétaire seulement.
Il est également recommandé d'utiliser l'option alertnotify afin d'être notifié des problèmes;
par exemple: alertnotify=echo %%s | mail -s "Alerte People" admin@foo.com
</translation>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation>Find peers using internet relay chat (default: 1) {0)?}</translation>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Synchronisation de l'horloge avec d'autres noeuds. Désactiver si votre serveur est déjà synchronisé avec le protocole NTP (défaut: 1)</translation>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>Lors de la création de transactions, ignore les entrées dont la valeur sont inférieures (défaut: 0.01)</translation>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Autoriser les connexions JSON-RPC depuis l'adresse IP spécifiée</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Envoyer des commandes au nœud fonctionnant sur <ip> (par défaut : 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Exécuter la commande lorsque le meilleur bloc change (%s dans cmd est remplacé par le hachage du bloc)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Exécuter la commande lorsqu'une transaction de portefeuille change (%s dans la commande est remplacée par TxID)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Nécessite a confirmations pour modification (défaut: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation>Force les scripts de transaction à utiliser des opérateurs PUSH canoniques (défaut: 1)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Exécute une commande lorsqu'une alerte correspondante est reçue (%s dans la commande est remplacé par message)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Mettre à niveau le portefeuille vers le format le plus récent</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Régler la taille de la réserve de clefs sur <n> (par défaut : 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Réanalyser la chaîne de blocs pour les transactions de portefeuille manquantes</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation>Nombre de blocs à vérifier loes du démarrage (défaut: 2500, 0 = tous)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Niveau d'approfondissement de la vérification des blocs (0-6, default: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Importe les blocs d'un fichier externe blk000?.dat</translation>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Utiliser OpenSSL (https) pour les connexions JSON-RPC</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Fichier de certificat serveur (par défaut : server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clef privée du serveur (par défaut : server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Algorithmes de chiffrements acceptés (défaut: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Erreur: Portefeuille déverrouillé uniquement pour "stacking" , impossible d'effectuer cette transaction</translation>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation>AVERTISSEMENT: point de contrôle invalide! Les transactions affichées peuvent être incorrectes! Il est peut-être nécessaire d'effectuer une mise à jour, ou d'avertir les développeurs du projet.</translation>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Ce message d'aide</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Le portefeuille %s réside en dehors répertoire de données %s</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. People is probably already running.</source>
<translation>Echec lors de la tentative de verrouillage des données du répertoire %s. L'application People est probablement déjà en cours d'exécution</translation>
</message>
<message>
<location line="-98"/>
<source>People</source>
<translation>People</translation>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Impossible de se lier à %s sur cet ordinateur (bind a retourné l'erreur %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation>Se connecter à travers un proxy socks</translation>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Autoriser les recherches DNS pour -addnode, -seednode et -connect</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Chargement des adresses…</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation>Erreur de chargement du fichier blkindex.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Erreur lors du chargement de wallet.dat : portefeuille corrompu</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of People</source>
<translation>Erreur de chargement du fichier wallet.dat: le portefeuille nécessite une version plus récente de l'application People</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart People to complete</source>
<translation>le portefeuille nécessite d'être réédité : Merci de relancer l'application People</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Erreur lors du chargement de wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Adresse -proxy invalide : « %s »</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Réseau inconnu spécifié sur -onlynet : « %s »</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Version inconnue de serveur mandataire -socks demandée : %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Impossible de résoudre l'adresse -bind : « %s »</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Impossible de résoudre l'adresse -externalip : « %s »</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Montant invalide pour -paytxfee=<montant> : « %s »</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation>Erreur: Impossible de démarrer le noeud</translation>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation>Envoi...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Montant invalide</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Fonds insuffisants</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Chargement de l’index des blocs…</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Ajouter un nœud auquel se connecter et tenter de garder la connexion ouverte</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. People is probably already running.</source>
<translation>Connexion au port %s impossible. L'application People est probablement déjà en cours d'exécution</translation>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Frais par KB à ajouter à vos transactions sortantes</translation>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>Montant invalide pour -mininput=<amount>: '%s'</translation>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Chargement du portefeuille…</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Impossible de revenir à une version inférieure du portefeuille</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation>Impossible d'initialiser la "keypool"</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Impossible d'écrire l'adresse par défaut</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Nouvelle analyse…</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Chargement terminé</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>Pour utiliser l'option %s</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Erreur</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>Vous devez ajouter la ligne rpcpassword=<mot-de-passe> au fichier de configuration :
%s
Si le fichier n'existe pas, créez-le avec les droits de lecture seule accordés au propriétaire.</translation>
</message>
</context>
</TS> | peopleproject/people | src/qt/locale/people_fr_CA.ts | TypeScript | mit | 143,532 |
using System;
namespace Glympse.EnRoute.iOS
{
class CustomerPickupManager : GCustomerPickupManager, EventSink.GGlyEventSink
{
private GlyCustomerPickupManager _raw;
private EventSink _eventSink;
public CustomerPickupManager(GlyCustomerPickupManager raw)
{
_raw = raw;
_eventSink = new EventSink(this);
}
/**
* GCustomerPickupManager section
*/
public bool arrived()
{
return _raw.arrived();
}
public GArray<GChatMessage> getChatMessages()
{
return new Array<GChatMessage>(_raw.getChatMessages());
}
public GCustomerPickup getCurrentPickup()
{
return (GCustomerPickup)ClassBinder.bind(_raw.getCurrentPickup());
}
public bool holdPickup()
{
return _raw.holdPickup();
}
public bool sendArrivalData(GPickupArrivalData arrivalData)
{
return _raw.sendArrivalData((GlyPickupArrivalData)arrivalData);
}
public bool sendChatMessage(string message)
{
return _raw.sendChatMessage(message);
}
public bool sendFeedback(int customerRating, string customerComment, bool canContactCustomer)
{
return _raw.sendFeedback(customerRating, customerComment, canContactCustomer);
}
public void setForeignId(string foreignId)
{
_raw.setForeignId(foreignId);
}
public void setInviteCode(string inviteCode)
{
_raw.setInviteCode(inviteCode);
}
public bool setManualETA(long eta)
{
return _raw.setManualETA(eta);
}
/**
* GEventSink section
*/
public bool addListener(GEventListener eventListener)
{
return _eventSink.addListener(eventListener);
}
public bool removeListener(GEventListener eventListener)
{
return _eventSink.removeListener(eventListener);
}
public bool addListener(GlyEventListener listener)
{
return _raw.addListener(listener);
}
public bool removeListener(GlyEventListener listener)
{
return _raw.removeListener(listener);
}
/**
* GCommon section
*/
public object raw()
{
return _raw;
}
}
}
| Glympse/enroute-xamarin-sdk | source/EnRouteApiiOS/Source/CustomerPickupManager.cs | C# | mit | 2,498 |
package sword.bitstream;
public interface DiffSupplierCreator<T> {
FunctionWithIOException<T, T> create(InputBitStream stream);
}
| carlos-sancho-ramirez/android-java-langbook | bitstream/src/main/java/sword/bitstream/DiffSupplierCreator.java | Java | mit | 135 |
using System;
using System.Collections.Generic;
using System.Text;
namespace Nohros.Data
{
/// <summary>
/// Represents an class that can be serialized using the json format. Classes
/// that implement this interface is usually used to transfer json encoded
/// data from the data access layer to another layer (usually a web
/// front-end).
/// </summary>
public interface IDataTransferObject
{
/// <summary>
/// Gets a json-compliant string of characters that represents the
/// underlying class and is formatted like a json array element.
/// </summary>
/// <example>
/// The example uses the AsJsonArray to serialize the MyDataTransferObject
/// to a string that represents an json array.
/// <code>
/// class MyDataTransferObject : IDataTransferObject {
/// string first_name_, las_name;
///
/// public MyDataTransferObject(string first_name, string last_name) {
/// first_name_ = first_name;
/// last_name_ = last_name;
/// }
///
/// public string AsJsonArray() {
/// return "['" + first_name + "','" + last_name + "']"
/// }
/// }
/// </code>
/// </example>
/// <returns>
/// A json compliant string of characters formatted like a json array
/// element.
/// </returns>
string AsJsonArray();
/// <summary>
/// Gets a json-compliant string of characters that represents the
/// underlying class and is formatted like a json object.
/// </summary>
/// <example>
/// The example uses the AsJsonObject method to serialize the
/// MyDataTransferObject to a string that represents an json object.
/// <code>
/// class MyDataTransferObject : IDataTransferObject {
/// string first_name_, las_name;
///
/// public MyDataTransferObject(string first_name, string last_name) {
/// first_name_ = first_name;
/// last_name_ = last_name;
/// }
///
/// public string AsJsonObject() {
/// return "{\"first_name\":\"" + first_name + "\",\"last_name\":\"" + last_name + "\"}";
/// }
/// }
/// </code>
/// </example>
/// <returns>
/// A json compliant string of characters formatted like a json object.
/// </returns>
string AsJsonObject();
}
}
| nohros/must | src/base/common/data/transferobjects/IDataTransferObject.cs | C# | mit | 2,431 |
import getDevTool from './devtool'
import getTarget from './target'
import getEntry from './entry'
import getOutput from './output'
import getResolve from './resolve'
import getResolveLoader from './resolveLoader'
import getModule from './module'
import getExternals from './externals'
import getPlugins from './plugins'
import getPostcss from './postcss'
import getNode from './node'
export default function make(name) {
if(typeof name !== 'string')
throw new Error('Name is required.')
return { name
, context: __dirname
, cache: true
, target: getTarget(name)
, devtool: getDevTool(name)
, entry: getEntry(name)
, output: getOutput(name)
, resolve: getResolve(name)
, resolveLoader: getResolveLoader(name)
, module: getModule(name)
, externals: getExternals(name)
, plugins: getPlugins(name)
, node: getNode(name)
, postcss: getPostcss(name)
}
}
| cchamberlain/redux-webpack-boilerplate | src/webpack/make.js | JavaScript | mit | 1,031 |
from django.conf.urls import patterns, url
from links import views
urlpatterns = patterns('links.views',
url(r'^link/settings/$', views.settings, name = 'settings'),
url(r'^link/donate/(?P<url>[\d\w.]+)$', views.kintera_redirect, name = 'donate'),
url(r'^link/rider/(?P<url>[\d\w.]+)$', views.t4k_redirect, name = 'profile'),
) | ethanperez/t4k-rms | links/urls.py | Python | mit | 340 |
import Ember from 'ember';
export default Ember.Controller.extend({
shortcuts:
[
{
title: "Task Editor",
combos: [
{
set: [["ctl","sh","del"]],
description: "delete focused task"
},
{
set: [["ctl","sh","ent"], ["ctl","+"]],
description: "create new task and edit it"
},
{
set: [["ctl","sh","h"], ["ctl", "sh", "⥢"],["esc"]],
description: "focus left into task list"
},
]
},
{
title: "Task List",
combos: [
{
set: [["down"], ["j"]],
description: "move down"
},
{
set: [["up"], ["k"]],
description: "move up"
},
{
set: [["o"], ["e"], ["ent"], ["space"]],
description: "toggle task in editor"
},
{
set: [["l"], ["⥤"]],
description: "display task in editor"
},
{
set: [["ctl", "sh", "l"],["ctl", "sh", "⥤"]],
description: "display task in editor and edit it"
},
{
set: [["h"], ["⥢"]],
description: "hide task from editor"
},
{
set: [["ctl","sh","del"]],
description: "delete focused task"
},
{
set: [["ctl","sh","ent"], ["ctl","sh","="]],
description: "create new task and edit it"
},
]
},
]
});
| mrmicahcooper/taskdown | ember/app/controllers/shortcuts.js | JavaScript | mit | 1,568 |
package feihua.jdbc.api.dao;
import feihua.jdbc.api.pojo.BasePo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* Created by feihua on 2015/6/29.
* 增
*/
public interface InsertDao<PO extends BasePo,PK> extends BaseDao<PO,PK> {
/**
* 创建(增加)数据,自动生成id
* @param entity 创建的数据内容
* @return 1:增加数据成功
* 0:增加数据失败
*/
public int insert(PO entity);
/**
* 创建(增加)数据,请指定id
* @param entity 创建的数据内容
* @return 1:增加数据成功
* 0:增加数据失败
*/
public int insertWithPrimaryKey(PO entity);
/**
* 创建(增加)数据,自动生成id
* @param entity 创建的数据内容
* @return 1:增加数据成功
* 0:增加数据失败
*/
public int insertSelective(PO entity);
/**
* 创建(增加)数据,请指定id
* @param entity 创建的数据内容
* @return 1:增加数据成功
* 0:增加数据失败
*/
public int insertSelectiveWithPrimaryKey(PO entity);
/**
* 批量插入,自动生成id
* @param entities
* @return
*/
public int insertBatch(@Param("entities") List<PO> entities);
/**
* 批量插入,请指定id
* @param entities
* @return
*/
public int insertBatchWithPrimaryKey(@Param("entities") List<PO> entities);
}
| feihua666/feihua-jdbc-api | src/main/java/feihua/jdbc/api/dao/InsertDao.java | Java | mit | 1,498 |
/**
* @fileoverview Rule to flag on declaring variables already declared in the outer scope
* @author Ilya Volodin
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
let astUtils = require("../ast-utils");
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow `var` declarations from shadowing variables in the outer scope",
category: "Variables",
recommended: false
},
schema: [
{
type: "object",
properties: {
builtinGlobals: {type: "boolean"},
hoist: {enum: ["all", "functions", "never"]},
allow: {
type: "array",
items: {
type: "string"
}
}
},
additionalProperties: false
}
]
},
create: function(context) {
let options = {
builtinGlobals: Boolean(context.options[0] && context.options[0].builtinGlobals),
hoist: (context.options[0] && context.options[0].hoist) || "functions",
allow: (context.options[0] && context.options[0].allow) || []
};
/**
* Check if variable name is allowed.
*
* @param {ASTNode} variable The variable to check.
* @returns {boolean} Whether or not the variable name is allowed.
*/
function isAllowed(variable) {
return options.allow.indexOf(variable.name) !== -1;
}
/**
* Checks if a variable of the class name in the class scope of ClassDeclaration.
*
* ClassDeclaration creates two variables of its name into its outer scope and its class scope.
* So we should ignore the variable in the class scope.
*
* @param {Object} variable The variable to check.
* @returns {boolean} Whether or not the variable of the class name in the class scope of ClassDeclaration.
*/
function isDuplicatedClassNameVariable(variable) {
let block = variable.scope.block;
return block.type === "ClassDeclaration" && block.id === variable.identifiers[0];
}
/**
* Checks if a variable is inside the initializer of scopeVar.
*
* To avoid reporting at declarations such as `var a = function a() {};`.
* But it should report `var a = function(a) {};` or `var a = function() { function a() {} };`.
*
* @param {Object} variable The variable to check.
* @param {Object} scopeVar The scope variable to look for.
* @returns {boolean} Whether or not the variable is inside initializer of scopeVar.
*/
function isOnInitializer(variable, scopeVar) {
let outerScope = scopeVar.scope;
let outerDef = scopeVar.defs[0];
let outer = outerDef && outerDef.parent && outerDef.parent.range;
let innerScope = variable.scope;
let innerDef = variable.defs[0];
let inner = innerDef && innerDef.name.range;
return (
outer &&
inner &&
outer[0] < inner[0] &&
inner[1] < outer[1] &&
((innerDef.type === "FunctionName" && innerDef.node.type === "FunctionExpression") || innerDef.node.type === "ClassExpression") &&
outerScope === innerScope.upper
);
}
/**
* Get a range of a variable's identifier node.
* @param {Object} variable The variable to get.
* @returns {Array|undefined} The range of the variable's identifier node.
*/
function getNameRange(variable) {
let def = variable.defs[0];
return def && def.name.range;
}
/**
* Checks if a variable is in TDZ of scopeVar.
* @param {Object} variable The variable to check.
* @param {Object} scopeVar The variable of TDZ.
* @returns {boolean} Whether or not the variable is in TDZ of scopeVar.
*/
function isInTdz(variable, scopeVar) {
let outerDef = scopeVar.defs[0];
let inner = getNameRange(variable);
let outer = getNameRange(scopeVar);
return (
inner &&
outer &&
inner[1] < outer[0] &&
// Excepts FunctionDeclaration if is {"hoist":"function"}.
(options.hoist !== "functions" || !outerDef || outerDef.node.type !== "FunctionDeclaration")
);
}
/**
* Checks the current context for shadowed variables.
* @param {Scope} scope - Fixme
* @returns {void}
*/
function checkForShadows(scope) {
let variables = scope.variables;
for (let i = 0; i < variables.length; ++i) {
let variable = variables[i];
// Skips "arguments" or variables of a class name in the class scope of ClassDeclaration.
if (variable.identifiers.length === 0 ||
isDuplicatedClassNameVariable(variable) ||
isAllowed(variable)
) {
continue;
}
// Gets shadowed variable.
let shadowed = astUtils.getVariableByName(scope.upper, variable.name);
if (shadowed &&
(shadowed.identifiers.length > 0 || (options.builtinGlobals && "writeable" in shadowed)) &&
!isOnInitializer(variable, shadowed) &&
!(options.hoist !== "all" && isInTdz(variable, shadowed))
) {
context.report({
node: variable.identifiers[0],
message: "'{{name}}' is already declared in the upper scope.",
data: variable
});
}
}
}
return {
"Program:exit": function() {
let globalScope = context.getScope();
let stack = globalScope.childScopes.slice();
let scope;
while (stack.length) {
scope = stack.pop();
stack.push.apply(stack, scope.childScopes);
checkForShadows(scope);
}
}
};
}
};
| lauracurley/2016-08-ps-react | node_modules/eslint/lib/rules/no-shadow.js | JavaScript | mit | 6,853 |
require 'bundler/setup'
require 'rails/version'
require 'rails/railtie'
require 'jblazer'
| Everlane/jblazer | spec/spec_helper.rb | Ruby | mit | 92 |
<footer>
<div class="footer-top">
<h3>Need help with building your email list? <a class="lets-talk">let's talk</a></h3>
</div>
<div class="footer-bottom">
<div class="container">
<div class="row">
<div class="col-md-4 col-sm-4">
<a href="#" class="footer-menu">Terms & Conditions</a> |
<a href="#" class="footer-menu">Privacy</a> |
<a href="#" class="footer-menu">Contact</a>
</div>
<div class="col-md-4 col-sm-4">
<p>©2015 ListGuru</p>
</div>
<div class="col-md-4 col-sm-4">
<p><i class="fa fa-twitter"></i> <i class="fa fa-envelope-o"></i></p>
</div>
</div>
</div>
</div>
</footer> | streetcoder/custom-responsive-wordpress-theme | templates/footer.php | PHP | mit | 864 |
require 'punchout/puncher'
module Punchout
class Fabricator
def initialize(factory)
@puncher = Puncher.new
@factory = factory
end
def add(matchable)
@puncher.add(matchable)
end
def can_punch?(type)
true
end
def punch(type)
if @puncher.can_punch?(type)
@puncher.punch(type)
else
matchable = @factory.build(type)
@puncher.add(matchable)
matchable.thing
end
end
end
end
| azanar/punchout | lib/punchout/fabricator.rb | Ruby | mit | 482 |
namespace Spinner.Fody.Weaving
{
internal enum StateMachineKind
{
None,
Iterator,
Async
}
} | Inverness/Spinner | Spinner.Fody/Weaving/StateMachineKind.cs | C# | mit | 127 |