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 |
|---|---|---|---|---|---|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { customElement, html, LitElement, property, } from "lit-element";
import { fireEvent } from "./util/fire-event";
import { getMouseTouchLocation } from "./util/get-mouse-touch-location";
import { getTouchIdentifier } from "./util/get-touch-identifier";
import { matchesSelectorAndParentsTo } from "./util/match-selector";
let LitDraggable = class LitDraggable extends LitElement {
constructor() {
super(...arguments);
this.disabled = false;
this._dragging = false;
}
firstUpdated() {
this.addEventListener("mousedown", this._dragStart.bind(this), {
capture: true,
passive: false,
});
this.addEventListener("touchstart", this._dragStart.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("mousemove", this._drag.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("touchmove", this._drag.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("mouseup", this._dragEnd.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("touchcancel", this._dragEnd.bind(this), {
capture: true,
passive: false,
});
document.addEventListener("touchend", this._dragEnd.bind(this), {
capture: true,
passive: false,
});
}
render() {
return html `<slot></slot>`;
}
_dragStart(ev) {
if ((ev.type.startsWith("mouse") && ev.button !== 0) ||
this.disabled) {
return;
}
console.log(ev);
if (this.handle &&
!matchesSelectorAndParentsTo(ev.currentTarget, this.handle, this.offsetParent)) {
return;
}
ev.preventDefault();
ev.stopPropagation();
if (ev.type === "touchstart") {
this._touchIdentifier = getTouchIdentifier(ev);
}
const pos = getMouseTouchLocation(ev, this._touchIdentifier);
if (!pos) {
return;
}
this.startX = pos.x;
this.startY = pos.y;
this._dragging = true;
fireEvent(this, "dragStart", {
startX: this.startX,
startY: this.startY,
});
}
_drag(ev) {
if (!this._dragging || this.disabled) {
return;
}
ev.preventDefault();
ev.stopPropagation();
const pos = getMouseTouchLocation(ev, this._touchIdentifier);
if (!pos) {
return;
}
let deltaX = pos.x - this.startX;
let deltaY = pos.y - this.startY;
if (this.grid) {
deltaX = Math.round(deltaX / this.grid[0]) * this.grid[0];
deltaY = Math.round(deltaY / this.grid[1]) * this.grid[1];
}
if (!deltaX && !deltaY) {
return;
}
fireEvent(this, "dragging", {
deltaX,
deltaY,
});
}
_dragEnd(ev) {
if (!this._dragging || this.disabled) {
return;
}
ev.preventDefault();
ev.stopPropagation();
this._touchIdentifier = undefined;
this._dragging = false;
fireEvent(this, "dragEnd");
}
};
__decorate([
property({ type: Array })
], LitDraggable.prototype, "grid", void 0);
__decorate([
property({ type: Boolean, reflect: true })
], LitDraggable.prototype, "disabled", void 0);
__decorate([
property()
], LitDraggable.prototype, "handle", void 0);
LitDraggable = __decorate([
customElement("lit-draggable")
], LitDraggable);
export { LitDraggable };
//# sourceMappingURL=lit-draggable.js.map | cdnjs/cdnjs | ajax/libs/lit-grid-layout/1.1.4/lit-draggable.js | JavaScript | mit | 4,479 |
using System;
class A
{
internal string S;
internal void Say()
{
Console.WriteLine(S);
}
}
class Program
{
private static void doit(Action sayit)
{
sayit();
}
static void Main(string[] args)
{
A a = new A();
a.S = "I am one";
A b = new A();
b.S = "I am two";
doit(a.Say);
doit(b.Say);
}
}
| autumn009/TanoCSharpSamples | Chap4/デリゲート型はインスタンスを区別する/デリゲート型はインスタンスを区別する/Program.cs | C# | mit | 398 |
require 'commander'
require 'applyrics/project'
require 'applyrics/lyricsfile'
module Applyrics
class Setup
def run(config = {})
platform = nil
if is_ios?
platform = :ios
elsif is_android?
platform = :android
elsif is_unity?
platform = :unity
else
return
end
Applyrics::Lyricsfile.generate(config)
Applyrics::Project.new(platform)
end
def is_ios?
(Dir["*.xcodeproj"] + Dir["*.xcworkspace"]).count > 0
end
def is_android?
Dir["*.gradle"].count > 0
end
def is_unity?
false
end
end
end
| applyrics/applyrics-gem | lib/applyrics/setup.rb | Ruby | mit | 622 |
<?php
/*
Safe sample
input : backticks interpretation, reading the file /tmp/tainted.txt
sanitize : use mysql_real_escape_string via an object and a classic getter
construction : interpretation with simple quote
*/
/*Copyright 2015 Bertrand STIVALET
Permission is hereby granted, without written agreement or royalty fee, to
use, copy, modify, and distribute this software and its documentation for
any purpose, provided that the above copyright notice and the following
three paragraphs appear in all copies of this software.
IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE
BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT
LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO
OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
MODIFICATIONS.*/
$tainted = `cat /tmp/tainted.txt`;
class Sanitize{
private $data;
public function __construct($input){
$this->data = $input ;
}
public function getData(){
return $this->data;
}
public function sanitize(){
$this->data = mysql_real_escape_string($this->data) ;
}
}
$sanitizer = new Sanitize($tainted) ;
$sanitizer->sanitize();
$tainted = $sanitizer->getData();
$query = "SELECT * FROM ' $tainted '";
$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password)
mysql_select_db('dbname') ;
echo "query : ". $query ."<br /><br />" ;
$res = mysql_query($query); //execution
while($data =mysql_fetch_array($res)){
print_r($data) ;
echo "<br />" ;
}
mysql_close($conn);
?> | stivalet/PHP-Vulnerability-test-suite | Injection/CWE_89/safe/CWE_89__backticks__object-func_mysql_real_escape_stringGetter__select_from-interpretation_simple_quote.php | PHP | mit | 1,889 |
#include <Python.h>
#include <maya/MFnPlugin.h>
#include <maya/MGlobal.h>
#include <maya/MPxNode.h>
#include <maya/MFnTypedAttribute.h>
#include <maya/MFnGenericAttribute.h>
#include <maya/MFnNumericData.h>
#include <maya/MFnNumericAttribute.h>
#include <maya/MFnNumericData.h>
#include <maya/MFnMatrixData.h>
#include <maya/MDataBlock.h>
#include <maya/MArrayDataHandle.h>
#include <maya/MVector.h>
#include <maya/MMatrix.h>
#include <maya/MFnDependencyNode.h>
#ifdef _WIN32
#pragma warning(disable: 4127)
#endif
#define EXPRESPY_NODE_ID 0x00070004 // ൽ©ÆÕË·éÈç«·¦é±ÆB(Free: 0x00000000 ` 0x0007ffff)
#if PY_MAJOR_VERSION < 3
// py2 ÅÍ io.StringIO ÅÍÈ StringIO.StringIO ðgp·é±ÆÅ str Æ unicode ɼγ¹éB
// cStringIO ɵȢÌÍ unicode ðÊ·½ßB
#define STRINGIO_MODULE "StringIO"
#define BUILTINS_MODULE_NAME "__builtin__"
#define PYINT_fromLong PyInt_FromLong
#define PYSTR_fromChar PyString_FromString
#define PYBYTES_asChar PyString_AsString
#define PYBYTES_check PyString_Check
#define PYBYTES_SIZE PyString_GET_SIZE
#else
// py3 ÅÍ io.StringIO ðgpµ unicode ÌÝÉηéB
#define STRINGIO_MODULE "io"
#define BUILTINS_MODULE_NAME "builtins"
#define PYINT_fromLong PyLong_FromLong
#define PYSTR_fromChar PyUnicode_FromString
#define PYBYTES_asChar PyBytes_AsString
#define PYBYTES_check PyBytes_Check
#define PYBYTES_SIZE PyBytes_GET_SIZE
#endif
//=============================================================================
/// Functions.
//=============================================================================
/// W
[ðC|[g·éBPyImport_ImportModule æè
B
static inline PyObject* _importModule(const char* name)
{
PyObject* nameo = PYSTR_fromChar(name);
if (nameo) {
PyObject* mod = PyImport_Import(nameo);
Py_DECREF(nameo);
return mod;
}
return NULL;
}
/// dict ©ç type IuWFNgð¾éB
static inline PyObject* _getTypeObject(PyObject* dict, const char* name)
{
PyObject* o = PyDict_GetItemString(dict, name);
return PyType_Check(o) ? o : NULL;
}
/// lÌQÆðD¢Â dict ÉlðZbg·éB
static inline void _setDictStealValue(PyObject* dic, const char* key, PyObject* valo)
{
if (valo) {
PyDict_SetItemString(dic, key, valo);
Py_DECREF(valo);
} else {
PyDict_SetItemString(dic, key, Py_None);
}
}
/// L[ÆlÌQÆðD¢Â I/O p dict ÉlðZbg·éB
static inline void _setIODictStealValue(PyObject* dic, PyObject* keyo, PyObject* valo)
{
if (valo) {
PyDict_SetItem(dic, keyo, valo);
Py_DECREF(valo);
} else {
PyDict_SetItem(dic, keyo, Py_None);
}
Py_DECREF(keyo);
}
/// dict É int ðL[ÆµÄ PyObject* ðZbg·éB
static inline void _setDictValue(PyObject* dic, int key, PyObject* valo)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
PyDict_SetItem(dic, keyo, valo);
Py_DECREF(keyo);
}
}
/// dict ©ç int ðL[ÆµÄ PyObject* ð¾éB
static inline PyObject* _getDictValue(PyObject* dic, int key)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
PyObject* valo = PyDict_GetItem(dic, keyo);
Py_DECREF(keyo);
return valo;
}
return NULL;
}
/// ^»ÊÏÝÌ sequence Ì PyObject* ©ç double3 Ì data ð¾éB
static inline MObject _getDouble3Value(PyObject* valo)
{
MFnNumericData fnOutData;
MObject data = fnOutData.create(MFnNumericData::k3Double);
fnOutData.setData(
PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0)),
PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1)),
PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2))
);
return data;
}
/// ^»ÊÏÝÌ sequence Ì PyObject* ©ç double4 Ì data ð¾éB
static inline MObject _getDouble4Value(PyObject* valo)
{
MFnNumericData fnOutData;
MObject data = fnOutData.create(MFnNumericData::k3Double);
fnOutData.setData(
PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0)),
PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1)),
PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2)),
PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 3))
);
return data;
}
/// ^»ÊÏÝÌ sequence Ì PyObject* ©ç float3 Ì data ð¾éB
static inline MObject _getFloat3Value(PyObject* valo)
{
MFnNumericData fnOutData;
MObject data = fnOutData.create(MFnNumericData::k3Float);
fnOutData.setData(
static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0))),
static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1))),
static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2)))
);
return data;
}
/// sequence Ì PyObject* ©ç double2, double3, double4, long2, long3 Ì¢¸ê©ð¾éB
static inline MObject _getTypedSequence(PyObject* valo)
{
MObject data;
Py_ssize_t num = PySequence_Length(valo);
if (num < 2 || 4 < num) return data;
bool hasFloat = false;
int ival[4];
double fval[4];
for (Py_ssize_t i=0; i<num; ++i) {
PyObject* v = PySequence_GetItem(valo, i);
if (PyFloat_Check(v)) {
hasFloat = true;
fval[i] = PyFloat_AS_DOUBLE(v);
#if PY_MAJOR_VERSION < 3
} else if (PyInt_Check(v)) {
ival[i] = PyInt_AS_LONG(v);
fval[i] = static_cast<double>(ival[i]);
#endif
} else if (PyLong_Check(v)) {
ival[i] = static_cast<int>(PyLong_AsLong(v)); // TODO: OverflowError ÎôB
fval[i] = static_cast<double>(ival[i]);
} else {
return data;
}
}
MFnNumericData fnOutData;
switch (num) {
case 2:
if (hasFloat) {
data = fnOutData.create(MFnNumericData::k2Double);
fnOutData.setData(fval[0], fval[1]);
} else {
data = fnOutData.create(MFnNumericData::k2Long);
fnOutData.setData(ival[0], ival[1]);
}
break;
case 3:
if (hasFloat) {
data = fnOutData.create(MFnNumericData::k3Double);
fnOutData.setData(fval[0], fval[1], fval[2]);
} else {
data = fnOutData.create(MFnNumericData::k3Long);
fnOutData.setData(ival[0], ival[1], ival[2]);
}
break;
case 4:
data = fnOutData.create(MFnNumericData::k4Double);
fnOutData.setData(fval[0], fval[1], fval[2], fval[3]);
break;
}
return data;
}
/// ^»ÊÏÝÌ PyObject* Ìlð MMatrix ɾéB
static inline void _getMatrixValueFromPyObject(MMatrix& mat, PyObject* valo)
{
PyObject* getElement = PyObject_GetAttrString(valo, "getElement");
if (getElement) {
PyObject* idxs[] = {
PYINT_fromLong(0), PYINT_fromLong(1), PYINT_fromLong(2), PYINT_fromLong(3)
};
PyObject* args = PyTuple_New(2);
for (unsigned i=0; i<4; ++i) {
PyTuple_SET_ITEM(args, 0, idxs[i]);
for (unsigned j=0; j<4; ++j) {
PyTuple_SET_ITEM(args, 1, idxs[j]);
PyObject* vo = PyObject_CallObject(getElement, args);
//PyObject* vo = PyObject_CallFunction(getElement, "(ii)", i, j);
if (vo) {
mat.matrix[i][j] = PyFloat_AS_DOUBLE(vo);
Py_DECREF(vo);
} else {
mat.matrix[i][j] = MMatrix::identity[i][j];
}
}
}
PyTuple_SET_ITEM(args, 0, idxs[0]);
PyTuple_SET_ITEM(args, 1, idxs[1]);
Py_DECREF(args);
Py_DECREF(idxs[2]);
Py_DECREF(idxs[3]);
} else {
mat.setToIdentity();
}
}
//=============================================================================
/// Exprespy node class.
//=============================================================================
class Exprespy : public MPxNode {
PyObject* _base_globals;
PyObject* _input;
PyObject* _output;
PyObject* _globals;
PyCodeObject* _codeobj;
PyObject* _mplug2_input;
PyObject* _mplug2_output;
PyObject* _mplug1_input;
PyObject* _mplug1_output;
PyObject* _api2_dict;
PyObject* _type2_MVector;
PyObject* _type2_MPoint;
PyObject* _type2_MEulerRotation;
PyObject* _type2_MMatrix;
PyObject* _type2_MObject;
PyObject* _type2_MQuaternion;
PyObject* _type2_MColor;
PyObject* _type2_MFloatVector;
PyObject* _type2_MFloatPoint;
PyObject* _api1_dict;
PyObject* _type1_MObject;
PyObject* _type_StringIO;
PyObject* _sys_dict;
PyObject* _sys_stdout;
PyObject* _sys_stderr;
int _count;
MStatus _compileCode(MDataBlock&);
MStatus _executeCode(MDataBlock&);
void _printPythonError();
void _setInputScalar(int key, const double& val);
void _setInputString(int key, const MString& str);
void _setInputShort2(int key, MObject& data);
void _setInputShort3(int key, MObject& data);
void _setInputLong2(int key, MObject& data);
void _setInputLong3(int key, MObject& data);
void _setInputFloat2(int key, MObject& data);
void _setInputFloat3(int key, MObject& data);
void _setInputDouble2(int key, MObject& data);
void _setInputDouble3(int key, MObject& data);
void _setInputDouble4(int key, MObject& data);
void _setInputVector3(int key, MObject& data);
void _setInputMatrix(int key, MObject& data);
void _setInputMObject2(int key);
void _setOutputMObject2(int key, PyObject* valo);
void _preparePyPlug2();
void _setInputMObject1(int key);
void _setOutputMObject1(int key, PyObject* valo);
void _preparePyPlug1();
public:
static MTypeId id;
static MString name;
static MObject aCode;
static MObject aInputsAsApi1Object;
static MObject aCompiled;
static MObject aInput;
static MObject aOutput;
static void* creator() { return new Exprespy; }
static MStatus initialize();
Exprespy();
virtual ~Exprespy();
MStatus compute(const MPlug&, MDataBlock&);
#if MAYA_API_VERSION >= 20160000
SchedulingType schedulingType () const { return MPxNode::kGloballySerial; }
#endif
};
MTypeId Exprespy::id(EXPRESPY_NODE_ID);
MString Exprespy::name("exprespy");
MObject Exprespy::aCode;
MObject Exprespy::aInputsAsApi1Object;
MObject Exprespy::aCompiled;
MObject Exprespy::aInput;
MObject Exprespy::aOutput;
//------------------------------------------------------------------------------
/// Static: Initialization.
//------------------------------------------------------------------------------
MStatus Exprespy::initialize()
{
MFnTypedAttribute fnTyped;
MFnNumericAttribute fnNumeric;
MFnGenericAttribute fnGeneric;
// code
aCode = fnTyped.create("code", "cd", MFnData::kString);
fnTyped.setConnectable(false);
CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aCode) );
// inputsAsApi1Object
aInputsAsApi1Object = fnNumeric.create("inputsAsApi1Object", "iaa1o", MFnNumericData::kBoolean, false);
fnTyped.setConnectable(false);
CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aInputsAsApi1Object) );
// compiled
aCompiled = fnNumeric.create("compile", "cm", MFnNumericData::kBoolean, false);
fnNumeric.setWritable(false);
fnNumeric.setStorable(false);
fnNumeric.setHidden(true);
CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aCompiled) );
// input
aInput = fnGeneric.create("input", "i");
// üÍÌêÍ kAny ¾¯ÅRlNgÍSÄe³êéª setAttr ÅÍe©êĵܤÌÅAÇSÄÌñªKvB
fnGeneric.addDataAccept(MFnData::kAny);
fnGeneric.addDataAccept(MFnData::kNumeric); // ±êͳÄàåäv»¤¾ªêB
fnGeneric.addNumericDataAccept(MFnNumericData::k2Short);
fnGeneric.addNumericDataAccept(MFnNumericData::k3Short);
fnGeneric.addNumericDataAccept(MFnNumericData::k2Long);
fnGeneric.addNumericDataAccept(MFnNumericData::k3Long);
fnGeneric.addNumericDataAccept(MFnNumericData::k2Float);
fnGeneric.addNumericDataAccept(MFnNumericData::k3Float);
fnGeneric.addNumericDataAccept(MFnNumericData::k2Double);
fnGeneric.addNumericDataAccept(MFnNumericData::k3Double);
fnGeneric.addNumericDataAccept(MFnNumericData::k4Double);
fnGeneric.addDataAccept(MFnData::kPlugin);
fnGeneric.addDataAccept(MFnData::kPluginGeometry);
fnGeneric.addDataAccept(MFnData::kString);
fnGeneric.addDataAccept(MFnData::kMatrix);
fnGeneric.addDataAccept(MFnData::kStringArray);
fnGeneric.addDataAccept(MFnData::kDoubleArray);
fnGeneric.addDataAccept(MFnData::kIntArray);
fnGeneric.addDataAccept(MFnData::kPointArray);
fnGeneric.addDataAccept(MFnData::kVectorArray);
fnGeneric.addDataAccept(MFnData::kComponentList);
fnGeneric.addDataAccept(MFnData::kMesh);
fnGeneric.addDataAccept(MFnData::kLattice);
fnGeneric.addDataAccept(MFnData::kNurbsCurve);
fnGeneric.addDataAccept(MFnData::kNurbsSurface);
fnGeneric.addDataAccept(MFnData::kSphere);
fnGeneric.addDataAccept(MFnData::kDynArrayAttrs);
fnGeneric.addDataAccept(MFnData::kSubdSurface);
// ȺÍNbV
·éB
//fnGeneric.addDataAccept(MFnData::kDynSweptGeometry);
//fnGeneric.addDataAccept(MFnData::kNObject);
//fnGeneric.addDataAccept(MFnData::kNId);
fnGeneric.setArray(true);
CHECK_MSTATUS_AND_RETURN_IT(addAttribute(aInput));
// output
aOutput = fnGeneric.create("output", "o");
// oÍÌêÍ kAny ¾¯ÅÍ Numeric Æ NumericData ÈOÌRlNgÍe³êÈ¢B
// setAttr ÍsvÈÌÅAüÍÆá¢ NumericData ÌñÜÅÍsvÆ·éB
fnGeneric.addDataAccept(MFnData::kAny);
//fnGeneric.addDataAccept(MFnData::kNumeric);
//fnGeneric.addNumericDataAccept(MFnNumericData::k2Short);
//fnGeneric.addNumericDataAccept(MFnNumericData::k3Short);
//fnGeneric.addNumericDataAccept(MFnNumericData::k2Long);
//fnGeneric.addNumericDataAccept(MFnNumericData::k3Long);
//fnGeneric.addNumericDataAccept(MFnNumericData::k2Float);
//fnGeneric.addNumericDataAccept(MFnNumericData::k3Float);
//fnGeneric.addNumericDataAccept(MFnNumericData::k2Double);
//fnGeneric.addNumericDataAccept(MFnNumericData::k3Double);
//fnGeneric.addNumericDataAccept(MFnNumericData::k4Double);
fnGeneric.addDataAccept(MFnData::kPlugin);
fnGeneric.addDataAccept(MFnData::kPluginGeometry);
fnGeneric.addDataAccept(MFnData::kString);
fnGeneric.addDataAccept(MFnData::kMatrix);
fnGeneric.addDataAccept(MFnData::kStringArray);
fnGeneric.addDataAccept(MFnData::kDoubleArray);
fnGeneric.addDataAccept(MFnData::kIntArray);
fnGeneric.addDataAccept(MFnData::kPointArray);
fnGeneric.addDataAccept(MFnData::kVectorArray);
fnGeneric.addDataAccept(MFnData::kComponentList);
fnGeneric.addDataAccept(MFnData::kMesh);
fnGeneric.addDataAccept(MFnData::kLattice);
fnGeneric.addDataAccept(MFnData::kNurbsCurve);
fnGeneric.addDataAccept(MFnData::kNurbsSurface);
fnGeneric.addDataAccept(MFnData::kSphere);
fnGeneric.addDataAccept(MFnData::kDynArrayAttrs);
fnGeneric.addDataAccept(MFnData::kSubdSurface);
// ÈºÍ input ÆáÁÄNbV
͵Ȣ椾ªsv¾ë¤B
//fnGeneric.addDataAccept(MFnData::kDynSweptGeometry);
//fnGeneric.addDataAccept(MFnData::kNObject);
//fnGeneric.addDataAccept(MFnData::kNId);
fnGeneric.setWritable(false);
fnGeneric.setStorable(false);
fnGeneric.setArray(true);
fnGeneric.setDisconnectBehavior(MFnAttribute::kDelete);
CHECK_MSTATUS_AND_RETURN_IT(addAttribute(aOutput));
// Set the attribute dependencies.
attributeAffects(aCode, aCompiled);
attributeAffects(aCode, aOutput);
attributeAffects(aInputsAsApi1Object, aOutput);
attributeAffects(aInput, aOutput);
return MS::kSuccess;
}
//------------------------------------------------------------------------------
/// Constructor.
//------------------------------------------------------------------------------
Exprespy::Exprespy() :
_base_globals(NULL),
_input(NULL),
_output(NULL),
_globals(NULL),
_codeobj(NULL),
_mplug2_input(NULL),
_mplug2_output(NULL),
_mplug1_input(NULL),
_mplug1_output(NULL),
_api2_dict(NULL),
_type2_MVector(NULL),
_type2_MPoint(NULL),
_type2_MEulerRotation(NULL),
_type2_MMatrix(NULL),
_type2_MObject(NULL),
_type2_MQuaternion(NULL),
_type2_MColor(NULL),
_type2_MFloatVector(NULL),
_type2_MFloatPoint(NULL),
_api1_dict(NULL),
_type1_MObject(NULL),
_type_StringIO(NULL),
_sys_dict(NULL),
_sys_stdout(NULL),
_sys_stderr(NULL),
_count(0)
{
}
//------------------------------------------------------------------------------
/// Destructor.
//------------------------------------------------------------------------------
Exprespy::~Exprespy()
{
if (_base_globals) {
PyGILState_STATE gil = PyGILState_Ensure();
Py_XDECREF(_sys_stdout);
Py_XDECREF(_sys_stderr);
Py_XDECREF(_mplug2_input);
Py_XDECREF(_mplug2_output);
Py_XDECREF(_mplug1_input);
Py_XDECREF(_mplug1_output);
Py_XDECREF(_codeobj);
Py_XDECREF(_globals);
Py_DECREF(_output);
Py_DECREF(_input);
Py_DECREF(_base_globals);
PyGILState_Release(gil);
}
}
//------------------------------------------------------------------------------
/// Computation.
//------------------------------------------------------------------------------
MStatus Exprespy::compute(const MPlug& plug, MDataBlock& block)
{
if (plug == aCompiled) {
return _compileCode(block);
} else if (plug == aOutput) {
return _executeCode(block);
}
return MS::kUnknownParameter;
}
//------------------------------------------------------------------------------
/// Compile a code.
//------------------------------------------------------------------------------
MStatus Exprespy::_compileCode(MDataBlock& block)
{
MString code = block.inputValue(aCode).asString();
//MGlobal::displayInfo("COMPILE");
// Python ÌJniGILæ¾jB
PyGILState_STATE gil = PyGILState_Ensure();
// êx\zÏÝÈçâRpCÏÝR[hðjüB
if (_base_globals) {
Py_CLEAR(_codeobj);
Py_CLEAR(_globals);
// ßÄÈç«\z·éB
} else {
PyObject* builtins = PyImport_ImportModule(BUILTINS_MODULE_NAME);
if (builtins) {
// [J« (globals) Ìx[Xð\z·éB
// ±êÍ«·¦çêÈ¢æ¤ÉÛµAeR[hü¯Éͱêð¡»µÄp·éB
_base_globals = PyDict_New();
_input = PyDict_New();
_output = PyDict_New();
if (_base_globals && _input && _output) {
// gÝÝ«ðZbgB
_setDictStealValue(_base_globals, "__builtins__", builtins);
_setDictStealValue(_base_globals, "__name__", PYSTR_fromChar("__exprespy__"));
// m[hÌüoÍ̽ßÌ dict ð¶¬B
PyDict_SetItemString(_base_globals, "IN", _input);
PyDict_SetItemString(_base_globals, "OUT", _output);
// W
[ðC|[gµ globals ÉZbgB
PyObject* mod_api2 = _importModule("maya.api.OpenMaya");
_setDictStealValue(_base_globals, "api", mod_api2);
_setDictStealValue(_base_globals, "math", _importModule("math"));
_setDictStealValue(_base_globals, "cmds", _importModule("maya.cmds"));
_setDictStealValue(_base_globals, "mel", _importModule("maya.mel"));
PyObject* mod_api1 = _importModule("maya.OpenMaya");
_setDictStealValue(_base_globals, "api1", mod_api1);
PyObject* mod_sys = _importModule("sys");
_setDictStealValue(_base_globals, "sys", mod_sys);
// Python API ©çNXðæ¾µÄ¨Bu³ÈçÈ¢OñvÅ INCREF ¹¸ÉÛ·éB
// NOTE: ³È鱯àLè¾éiá¦ÎAQÆðjüµÄC|[gµ¼µjÆl¦éÆXë¯ÅÍ éB
if (mod_api2) {
_api2_dict = PyModule_GetDict(mod_api2);
_type2_MVector = _getTypeObject(_api2_dict, "MVector");
_type2_MPoint = _getTypeObject(_api2_dict, "MPoint");
_type2_MEulerRotation = _getTypeObject(_api2_dict, "MEulerRotation");
_type2_MMatrix = _getTypeObject(_api2_dict, "MMatrix");
_type2_MObject = _getTypeObject(_api2_dict, "MObject");
_type2_MQuaternion = _getTypeObject(_api2_dict, "MQuaternion");
_type2_MColor = _getTypeObject(_api2_dict, "MColor");
_type2_MFloatVector = _getTypeObject(_api2_dict, "MFloatVector");
_type2_MFloatPoint = _getTypeObject(_api2_dict, "MFloatPoint");
}
if (mod_api1) {
_api1_dict = PyModule_GetDict(mod_api1);
_type1_MObject = _getTypeObject(_api1_dict, "MObject");
}
// oÍXg[ðæÁæé½ßÌõB
if (mod_sys) {
PyObject* mod_StringIO = _importModule(STRINGIO_MODULE);
if (mod_StringIO) {
_type_StringIO = PyDict_GetItemString(PyModule_GetDict(mod_StringIO), "StringIO");
if (_type_StringIO) {
// stdout Æ stdin Í INCREF µÄ¨©È¢ÆAæÁæÁ½ÉNbV
µ½è·éB
_sys_dict = PyModule_GetDict(mod_sys);
_sys_stdout = PyDict_GetItemString(_sys_dict, "stdout");
if (_sys_stdout) Py_INCREF(_sys_stdout);
_sys_stderr = PyDict_GetItemString(_sys_dict, "stderr");
if (_sys_stderr) Py_INCREF(_sys_stderr);
}
}
}
} else {
// «\zɸsB
Py_CLEAR(_base_globals);
Py_CLEAR(_input);
Py_CLEAR(_output);
}
}
}
// [J«̡»ÆA\[XR[hÌRpCB
if (_base_globals) {
_globals = PyDict_Copy(_base_globals);
if (_globals) {
_codeobj = reinterpret_cast<PyCodeObject*>(Py_CompileString(code.asChar(), "exprespy_code", Py_file_input));
if(PyErr_Occurred()){
//MGlobal::displayInfo("Compile: error!");
Py_CLEAR(_codeobj);
_printPythonError();
}
}
_count = 0;
}
// Python ÌI¹iGILðújB
PyGILState_Release(gil);
// RpC̬ÛðZbgB
//MGlobal::displayInfo(_codeobj ? "successfull" : "failed");
block.outputValue(aCompiled).set(_codeobj ? true : false);
return MS::kSuccess;
}
//------------------------------------------------------------------------------
/// Execute a code.
//------------------------------------------------------------------------------
MStatus Exprespy::_executeCode(MDataBlock& block)
{
block.inputValue(aCompiled);
MArrayDataHandle hArrOutput = block.outputArrayValue(aOutput);
if (_codeobj) {
//MGlobal::displayInfo("EXECUTE");
// GILæ¾OÉã¬]¿ðI¦éB
const bool inputsAsApi1Object = block.inputValue(aInputsAsApi1Object).asBool();
MArrayDataHandle hArrInput = block.inputArrayValue(aInput);
// ±ÌiKÅ㬪]¿³êIíÁÄ¢éB
// Python ÌJniGILæ¾jB
PyGILState_STATE gil = PyGILState_Ensure();
// .input[i] ©çlð¾Ä IN[i] ÉZbg·éB
if (hArrInput.elementCount()) {
do {
const unsigned idx = hArrInput.elementIndex();
MDataHandle hInput = hArrInput.inputValue();
if (hInput.type() == MFnData::kNumeric) {
// generic ÅÍAcOȪçl^ÌÚ×Í»ÊūȢB
_setInputScalar(idx, hInput.asGenericDouble());
} else {
MObject data = hInput.data();
switch (data.apiType()) {
case MFn::kMatrixData: // matrix --> MMatrix (API2)
_setInputMatrix(idx, data);
break;
case MFn::kStringData: // string --> unicode
_setInputString(idx, hInput.asString());
break;
case MFn::kData2Short: // short2 --> list
_setInputShort2(idx, data);
break;
case MFn::kData3Short: // short3 --> list
_setInputShort3(idx, data);
break;
case MFn::kData2Long: // long2 --> list
_setInputLong2(idx, data);
break;
case MFn::kData3Long: // long3 --> list
_setInputLong3(idx, data);
break;
case MFn::kData2Float: // float2 --> list
_setInputFloat2(idx, data);
break;
case MFn::kData3Float: // float3 --> list
_setInputFloat3(idx, data);
break;
case MFn::kData2Double: // double2 --> list
_setInputDouble2(idx, data);
break;
case MFn::kData3Double: // double3 --> MVector (API2)
_setInputVector3(idx, data);
break;
case MFn::kData4Double: // double3 --> list
_setInputDouble4(idx, data);
break;
default: // other data --> MObject (API2 or 1)
//MGlobal::displayInfo(data.apiTypeStr());
if (! data.hasFn(MFn::kData)) {
// Ú±Ì undo ÈÇÉ kInvalid ªéBisNull() Åà»èo½ªAê data ¾¯Ê·æ¤É·éB
_setDictValue(_input, idx, Py_None);
} else if (inputsAsApi1Object) {
_setInputMObject1(idx);
} else {
_setInputMObject2(idx);
}
}
}
} while (hArrInput.next());
}
// JE^[ðZbgB
_setDictStealValue(_globals, "COUNT", PYINT_fromLong(_count));
++_count;
// sys.stdout ð StringIO ÅD¤B
// ½Ì© print ÌoÍsªt]·é±Æª éÌÅAobt@ÉßÄêñÅ write ·éæ¤É·éB
// python Ì print à MGloba::displayInfo à Maya ɧäªÔ³êÈ¢Àè flush ³êÈ¢ÌÅA»Ì_ÍÏíçÈ¢B
// ȨA±Ìt]»ÛÍN«½èN«È©Á½èµAðÍæª©çÈ¢BMaya 2017 win64 Ţ穷ÆÈPÉÄ»o½B
PyObject* stream = NULL;
if (_sys_stdout && _type_StringIO) {
stream = PyObject_CallObject(_type_StringIO, NULL);
if (stream) {
PyDict_SetItemString(_sys_dict, "stdout", stream);
}
}
// RpCÏÝR[hIuWFNgðÀsB
#if PY_MAJOR_VERSION < 3
PyEval_EvalCode(_codeobj, _globals, NULL);
#else
PyEval_EvalCode(reinterpret_cast<PyObject*>(_codeobj), _globals, NULL);
#endif
if(PyErr_Occurred()){
//MGlobal::displayInfo("PyEval_EvalCode: error!");
_printPythonError();
}
// NOTE: py3 ÅÍG[CWP[^ðNA·éOÉ open ÏÝ StringIO ðgp·éÆNbV
·éÌÅÓ!!
// StringIO Ìgð{Ì sys.stdout É«oµAsys.stdout ð³Éß·B
// MGlobal::displayInfo ðp¢È¢ÌÍARg»ð³¹¸É_CNgÉ print ³¹é½ßB
if (stream) {
PyObject* str = PyObject_CallMethod(stream, "getvalue", NULL);
if (str) {
#if PY_MAJOR_VERSION < 3
if ((PyUnicode_Check(str) && PyUnicode_GET_SIZE(str)) || PYBYTES_SIZE(str))
#else
if (PyUnicode_GET_SIZE(str))
#endif
PyObject_CallMethod(_sys_stdout, "write", "(O)", str);
Py_DECREF(str);
}
PyDict_SetItemString(_sys_dict, "stdout", _sys_stdout);
PyObject_CallMethod(stream, "close", NULL);
Py_DECREF(stream);
}
// .output[i] É OUT[i] ÌlðZbg·éB¶ÝµÈ¢àÌⵦȢàÌêͳ·éB
if (hArrOutput.elementCount()) {
MMatrix mat;
do {
const unsigned idx = hArrOutput.elementIndex();
PyObject* valo = _getDictValue(_output, idx); // ۵ȢÌÅ INCREF µÈ¢B
if (! valo) continue;
// float --> double
if (PyFloat_Check(valo)) {
hArrOutput.outputValue().setGenericDouble(PyFloat_AS_DOUBLE(valo), true);
#if PY_MAJOR_VERSION < 3
// int --> int
} else if (PyInt_Check(valo)) {
hArrOutput.outputValue().setGenericInt(PyInt_AS_LONG(valo), true);
#endif
// long int --> int
} else if (PyLong_Check(valo)) {
hArrOutput.outputValue().setGenericInt(PyLong_AsLong(valo), true); // TODO: OverflowError ÎôB
// bool --> bool
} else if (PyBool_Check(valo)) {
hArrOutput.outputValue().setGenericBool(valo == Py_True, true);
// str(bytes) --> string
} else if (PYBYTES_check(valo)) {
hArrOutput.outputValue().set(MString(PYBYTES_asChar(valo)));
// unicode(str) --> string
} else if (PyUnicode_Check(valo)) {
// ±ê¾Æ py3 ¾ÆÊª¨©µApy2 ÅàR[hÌGR[h^CvÉ˶·é±ÆÉÈéB
// Agr
[gÍAOSÆ¾ê²ÆÉèßçê½MayaV[ÌGR[h^Cvª³µ¢B
// Linux or Mac: utf-8, Windowsú{ê=cp932(SJIS), WindowsÈÌê=cp936(GBK)
//PyObject* es = PyUnicode_AsEncodedString(valo, Py_FileSystemDefaultEncoding, NULL);
//if (es) {
// hArrOutput.outputValue().set(MString(PYBYTES_asChar(es)));
// Py_DECREF(es);
//}
// wchar_t ÌÜÜ MString »·éª 3.2 ¢¾Æ API ªÃ¢ÌÅØèª¯éB
#if PY_MAJOR_VERSION < 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 2)
wchar_t* ws = 0;
Py_ssize_t siz = PyUnicode_GET_SIZE(valo);
if (siz) {
++siz;
ws = reinterpret_cast<wchar_t*>(PyMem_Malloc(siz * sizeof(wchar_t)));
}
if (ws) {
PyUnicode_AsWideChar(reinterpret_cast<PyUnicodeObject*>(valo), ws, siz);
#else
wchar_t* ws = PyUnicode_AsWideCharString(valo, NULL);
if (ws) {
#endif
hArrOutput.outputValue().set(MString(ws));
PyMem_Free(ws);
}
else
hArrOutput.outputValue().set(MString());
// MMatrix (API2) --> matrix
} else if (_type2_MMatrix && PyObject_IsInstance(valo, _type2_MMatrix)) {
_getMatrixValueFromPyObject(mat, valo);
hArrOutput.outputValue().set(MFnMatrixData().create(mat));
// MVector, MPoint, MEulerRotation (API2) --> double3
} else if ((_type2_MVector && PyObject_IsInstance(valo, _type2_MVector))
|| (_type2_MPoint && PyObject_IsInstance(valo, _type2_MPoint))
|| (_type2_MEulerRotation && PyObject_IsInstance(valo, _type2_MEulerRotation))) {
hArrOutput.outputValue().set(_getDouble3Value(valo));
// MQuaternion (API2) --> double4
} else if (_type2_MQuaternion && PyObject_IsInstance(valo, _type2_MQuaternion)) {
hArrOutput.outputValue().set(_getDouble4Value(valo));
// MFloatVector, MFloatPoint, MColor (API2) --> float3
} else if ((_type2_MFloatVector && PyObject_IsInstance(valo, _type2_MFloatVector))
|| (_type2_MFloatPoint && PyObject_IsInstance(valo, _type2_MFloatPoint))
|| (_type2_MColor && PyObject_IsInstance(valo, _type2_MColor))) {
hArrOutput.outputValue().set(_getFloat3Value(valo));
// sequence --> double2, double3, double4, long2, long3, or null
} else if (PySequence_Check(valo)) {
hArrOutput.outputValue().set(_getTypedSequence(valo));
// MObject (API2 or 1) --> data
} else if (_type2_MObject && PyObject_IsInstance(valo, _type2_MObject)) {
_setOutputMObject2(idx, valo);
} else if (_type1_MObject && PyObject_IsInstance(valo, _type1_MObject)) {
_setOutputMObject1(idx, valo);
}
} while (hArrOutput.next());
}
// ñ̽ßÉ IN Æ OUT ðNAµÄ¨B
PyDict_Clear(_input);
PyDict_Clear(_output);
// Python ÌI¹iGILðújB
PyGILState_Release(gil);
}
return hArrOutput.setAllClean();
}
//------------------------------------------------------------------------------
/// Python ÌG[ð Maya ÌG[bZ[WƵÄoÍ·éB
/// bZ[WðÔ·é¤ÉA½Ì©s̪t]·éêª éÌðñð·éB
//------------------------------------------------------------------------------
#if PY_MAJOR_VERSION < 3
void Exprespy::_printPythonError()
{
// RȪçARpCG[ÅÍ traceback IuWFNg;çê¸A^CG[Å;çêéB
//PyObject *errtyp, *errval, *tb;
//PyErr_Fetch(&errtyp, &errval, &tb);
//MGlobal::displayInfo(
// MString("errtyp=") + (errtyp ? "1" : "0")
// + ", errval=" + (errval ? "1" : "0")
// + ", tb=" + (tb ? "1" : "0")
//);
//PyErr_Restore(errtyp, errval, tb);
// sys.stderr ð StringIO ÅD¤B
PyObject* stream = NULL;
if (_sys_stderr && _type_StringIO) {
stream = PyObject_CallObject(_type_StringIO, NULL);
if (stream) {
PyDict_SetItemString(_sys_dict, "stderr", stream);
}
}
// »ÝÌG[îñð stderr É«o·B
PyErr_Print();
// StringIO Ìgð{Ì sys.stderr É«oµAsys.stderr ð³Éß·B
if (stream) {
PyObject* str = PyObject_CallMethod(stream, "getvalue", NULL);
if (str) {
if (PYBYTES_SIZE(str)) {
MGlobal::displayError(PYBYTES_asChar(str));
}
Py_DECREF(str);
}
PyDict_SetItemString(_sys_dict, "stderr", _sys_stderr);
PyObject_CallMethod(stream, "close", NULL);
Py_DECREF(stream);
}
}
//------------------------------------------------------------------------------
#else
void Exprespy::_printPythonError()
{
// py3 ÅÍAtraceback IuWFNgÍRpCG[Åà^CG[Åà¾çêÈ¢B
// StringIO ð¶¬µæ¤Æ·éÆ SystemError: <class '_io.StringIO'> returned a result with an error set ÆÈéB
// traceback.format_exc() ÅàG[eLXgð¾çêÈ¢B
// ǤµÄ梩ª©çÈ¢ÌÅ PyErr_Print ð¼ÚÄÔÌÝÆµA»ÌãÌ displayError ÅÔ·éB
PyErr_Print();
MGlobal::displayError("An error has occured.");
#if 0
#if 0
PyObject *errtyp, *errval, *tb;
PyErr_Fetch(&errtyp, &errval, &tb);
MGlobal::displayInfo(
MString("errtyp=") + (errtyp ? "1" : "0")
+ ", errval=" + (errval ? "1" : "0")
+ ", tb=" + (tb ? "1" : "0")
);
if (! tb) {
PyErr_Restore(errtyp, errval, tb);
PyErr_Print();
return;
}
#endif
MGlobal::displayInfo("import traceback");
PyObject* mod_traceback = PyImport_ImportModule("traceback");
if (mod_traceback) {
#if 0
MGlobal::displayInfo("get format_tb");
PyObject* format_tb = PyDict_GetItemString(PyModule_GetDict(mod_traceback), "format_tb"); // borrow
MGlobal::displayInfo(MString("format_tb=") + (format_tb ? "1" : "0"));
PyObject* str = PyObject_CallFunction(format_tb, "(O)", tb);
#else
MGlobal::displayInfo("get format_exc");
PyObject* format_exc = PyDict_GetItemString(PyModule_GetDict(mod_traceback), "format_exc"); // borrow
MGlobal::displayInfo(MString("format_exc=") + (format_exc ? "1" : "0"));
PyObject* str = PyObject_CallObject(format_exc, NULL);
#endif
MGlobal::displayInfo(MString("str=") + (str ? "1" : "0"));
if (str) {
MGlobal::displayInfo("asUTF8");
PyObject* bs = PyUnicode_AsUTF8String(str);
MString mstr;
mstr.setUTF8(PYBYTES_asChar(bs));
MGlobal::displayError(mstr);
Py_DECREF(bs);
Py_DECREF(str);
}
Py_DECREF(mod_traceback);
}
//Py_DECREF(errtyp);
//Py_DECREF(errval);
//Py_DECREF(tb);
#endif
}
#endif
//------------------------------------------------------------------------------
/// _input dict ÉXJ[lðZbg·éB
//------------------------------------------------------------------------------
void Exprespy::_setInputScalar(int key, const double& val)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
// üÍ©ç^»ÊoÈ¢½ßA¹ßÄ®ÆÀð»Ê·éB
int i = static_cast<int>(val);
if (static_cast<double>(i) == val) {
_setIODictStealValue(_input, keyo, PYINT_fromLong(i));
} else {
_setIODictStealValue(_input, keyo, PyFloat_FromDouble(val));
}
}
}
//------------------------------------------------------------------------------
/// _input dict ɶñðZbg·éB
//------------------------------------------------------------------------------
void Exprespy::_setInputString(int key, const MString& str)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
_setIODictStealValue(_input, keyo, PyUnicode_FromString(str.asUTF8()));
}
}
//------------------------------------------------------------------------------
/// _input dict Évfª 2`4 ÂÌlð list ɵÄZbg·éB
//------------------------------------------------------------------------------
void Exprespy::_setInputShort2(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
short x, y;
MFnNumericData(data).getData(x, y);
_setIODictStealValue(_input, keyo, Py_BuildValue("[hh]", x, y));
}
}
void Exprespy::_setInputShort3(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
short x, y, z;
MFnNumericData(data).getData(x, y, z);
_setIODictStealValue(_input, keyo, Py_BuildValue("[hhh]", x, y, z));
}
}
void Exprespy::_setInputLong2(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
int x, y;
MFnNumericData(data).getData(x, y);
_setIODictStealValue(_input, keyo, Py_BuildValue("[ii]", x, y));
}
}
void Exprespy::_setInputLong3(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
int x, y, z;
MFnNumericData(data).getData(x, y, z);
_setIODictStealValue(_input, keyo, Py_BuildValue("[iii]", x, y, z));
}
}
void Exprespy::_setInputFloat2(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
float x, y;
MFnNumericData(data).getData(x, y);
_setIODictStealValue(_input, keyo, Py_BuildValue("[ff]", x, y));
}
}
void Exprespy::_setInputFloat3(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
float x, y, z;
MFnNumericData(data).getData(x, y, z);
_setIODictStealValue(_input, keyo, Py_BuildValue("[fff]", x, y, z));
}
}
void Exprespy::_setInputDouble2(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
double x, y;
MFnNumericData(data).getData(x, y);
_setIODictStealValue(_input, keyo, Py_BuildValue("[dd]", x, y));
}
}
void Exprespy::_setInputDouble3(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
double x, y, z;
MFnNumericData(data).getData(x, y, z);
_setIODictStealValue(_input, keyo, Py_BuildValue("[ddd]", x, y, z));
}
}
void Exprespy::_setInputDouble4(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
double x, y, z, w;
MFnNumericData(data).getData(x, y, z, w);
_setIODictStealValue(_input, keyo, Py_BuildValue("[dddd]", x, y, z, w));
}
}
//------------------------------------------------------------------------------
/// _input dict É double3 ð MVector © list ɵÄZbg·éB
//------------------------------------------------------------------------------
void Exprespy::_setInputVector3(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
double x, y, z;
MFnNumericData(data).getData(x, y, z);
if (_type2_MVector) {
_setIODictStealValue(_input, keyo, PyObject_CallFunction(_type2_MVector, "(ddd)", x, y, z));
} else {
_setIODictStealValue(_input, keyo, Py_BuildValue("[ddd]", x, y, z));
}
}
}
//------------------------------------------------------------------------------
/// _input dict É matrix ð MMatrix © list ɵÄZbg·éB
//------------------------------------------------------------------------------
void Exprespy::_setInputMatrix(int key, MObject& data)
{
PyObject* keyo = PYINT_fromLong(key);
if (keyo) {
MMatrix m = MFnMatrixData(data).matrix();
if (_type2_MMatrix) {
_setIODictStealValue(_input, keyo, PyObject_CallFunction(_type2_MMatrix, "(N)", Py_BuildValue(
"(dddddddddddddddd)",
m.matrix[0][0], m.matrix[0][1], m.matrix[0][2], m.matrix[0][3],
m.matrix[1][0], m.matrix[1][1], m.matrix[1][2], m.matrix[1][3],
m.matrix[2][0], m.matrix[2][1], m.matrix[2][2], m.matrix[2][3],
m.matrix[3][0], m.matrix[3][1], m.matrix[3][2], m.matrix[3][3]
)));
} else {
_setIODictStealValue(_input, keyo, Py_BuildValue(
"[dddddddddddddddd]",
m.matrix[0][0], m.matrix[0][1], m.matrix[0][2], m.matrix[0][3],
m.matrix[1][0], m.matrix[1][1], m.matrix[1][2], m.matrix[1][3],
m.matrix[2][0], m.matrix[2][1], m.matrix[2][2], m.matrix[2][3],
m.matrix[3][0], m.matrix[3][1], m.matrix[3][2], m.matrix[3][3]
));
}
}
}
//------------------------------------------------------------------------------
/// _input dict É Python API 2 MObject f[^ðZbg·éB
/// MObjet ð C++ ©ç Python ÉÏ··éèiª³¢ÌÅAs{ÓȪç MPlug ðpB
//------------------------------------------------------------------------------
void Exprespy::_setInputMObject2(int key)
{
_preparePyPlug2();
if (! _mplug2_input) return;
PyObject* keyo = PYINT_fromLong(key);
if (! keyo) return;
PyObject* mplug = PyObject_CallMethod(_mplug2_input, "elementByLogicalIndex", "(O)", keyo);
if (mplug) {
_setIODictStealValue(_input, keyo, PyObject_CallMethod(mplug, "asMObject", NULL));
Py_DECREF(mplug);
} else {
Py_DECREF(keyo);
}
}
//------------------------------------------------------------------------------
/// _output dict ©ç¾½ Python API 2 MObject f[^ðoÍvOÉZbg·éB
/// MObjet ð Python ©ç C++ ÉÏ··éèiª³¢ÌÅAs{ÓȪç MPlug ðpB
//------------------------------------------------------------------------------
void Exprespy::_setOutputMObject2(int key, PyObject* valo)
{
_preparePyPlug2();
if (! _mplug2_output) return;
PyObject* mplug = PyObject_CallMethod(_mplug2_output, "elementByLogicalIndex", "(i)", key);
if (mplug) {
PyObject_CallMethod(mplug, "setMObject", "(O)", valo);
Py_DECREF(mplug);
}
}
//------------------------------------------------------------------------------
/// MObject f[^üoÍ̽ßÌ Python API 2 MPlug ðæ¾µÄ¨B
//------------------------------------------------------------------------------
void Exprespy::_preparePyPlug2()
{
if (_mplug2_input || ! _api2_dict) return;
PyObject* pysel = PyObject_CallObject(PyDict_GetItemString(_api2_dict, "MSelectionList"), NULL);
if (! pysel) return;
MString nodename = MFnDependencyNode(thisMObject()).name();
PyObject_CallMethod(pysel, "add", "(s)", nodename.asChar());
PyObject* pynode = PyObject_CallMethod(pysel, "getDependNode", "(i)", 0);
Py_DECREF(pysel);
if (! pynode) return;
PyObject* pyfn = PyObject_CallFunction(PyDict_GetItemString(_api2_dict, "MFnDependencyNode"), "(O)", pynode);
Py_DECREF(pynode);
if (! pyfn) return;
PyObject* findPlug = PyObject_GetAttrString(pyfn, "findPlug"); // DECREF svB
_mplug2_input = PyObject_CallFunction(findPlug, "(sO)", "i", Py_False);
_mplug2_output = PyObject_CallFunction(findPlug, "(sO)", "o", Py_False);
Py_DECREF(pyfn);
}
//------------------------------------------------------------------------------
/// _input dict É Python API 1 MObject f[^ðZbg·éB
/// MObjet ð C++ ©ç Python ÉÏ··éèiª³¢ÌÅAs{ÓȪç MPlug ðpB
//------------------------------------------------------------------------------
void Exprespy::_setInputMObject1(int key)
{
_preparePyPlug1();
if (! _mplug1_input) return;
PyObject* keyo = PYINT_fromLong(key);
if (! keyo) return;
PyObject* mplug = PyObject_CallMethod(_mplug1_input, "elementByLogicalIndex", "(O)", keyo);
if (! mplug) { Py_DECREF(keyo); return; }
PyObject* valo = PyObject_CallMethod(mplug, "asMObject", NULL);
Py_DECREF(mplug);
_setIODictStealValue(_input, keyo, valo);
}
//------------------------------------------------------------------------------
/// _output dict ©ç¾½ Python API 1 MObject f[^ðoÍvOÉZbg·éB
/// MObjet ð Python ©ç C++ ÉÏ··éèiª³¢ÌÅAs{ÓȪç MPlug ðpB
//------------------------------------------------------------------------------
void Exprespy::_setOutputMObject1(int key, PyObject* valo)
{
_preparePyPlug1();
if (! _mplug1_output) return;
PyObject* mplug = PyObject_CallMethod(_mplug1_output, "elementByLogicalIndex", "(i)", key);
if (mplug) {
PyObject_CallMethod(mplug, "setMObject", "(O)", valo);
Py_DECREF(mplug);
}
}
//------------------------------------------------------------------------------
/// MObject f[^üoÍ̽ßÌ Python API 1 MPlug ðæ¾µÄ¨B
//------------------------------------------------------------------------------
void Exprespy::_preparePyPlug1()
{
if (_mplug1_input || ! _api1_dict) return;
PyObject* pysel = PyObject_CallObject(PyDict_GetItemString(_api1_dict, "MSelectionList"), NULL);
if (! pysel) return;
MString nodename = MFnDependencyNode(thisMObject()).name();
PyObject_CallMethod(pysel, "add", "(s)", nodename.asChar());
PyObject* pynode = PyObject_CallObject(_type1_MObject, NULL);
if (! pynode) return;
PyObject_CallMethod(pysel, "getDependNode", "(iO)", 0, pynode);
Py_DECREF(pysel);
if (PyObject_CallMethod(pynode, "isNull", NULL) != Py_True) {
PyObject* pyfn = PyObject_CallFunction(PyDict_GetItemString(_api1_dict, "MFnDependencyNode"), "(O)", pynode);
PyObject* findPlug = PyObject_GetAttrString(pyfn, "findPlug"); // DECREF svB
if (findPlug) {
_mplug1_input = PyObject_CallFunction(findPlug, "(sO)", "i", Py_False);
_mplug1_output = PyObject_CallFunction(findPlug, "(sO)", "o", Py_False);
if (PyObject_CallMethod(_mplug1_input, "isNull", NULL) == Py_True) Py_CLEAR(_mplug1_input);
if (PyObject_CallMethod(_mplug1_output, "isNull", NULL) == Py_True) Py_CLEAR(_mplug1_output);
}
Py_DECREF(pyfn);
}
Py_DECREF(pynode);
}
//=============================================================================
// ENTRY POINT FUNCTIONS
//=============================================================================
MStatus initializePlugin(MObject obj)
{
static const char* VERSION = "3.0.0.20210411";
static const char* VENDER = "Ryusuke Sasaki";
MFnPlugin plugin(obj, VENDER, VERSION, "Any");
MStatus stat = plugin.registerNode(Exprespy::name, Exprespy::id, Exprespy::creator, Exprespy::initialize);
CHECK_MSTATUS_AND_RETURN_IT(stat);
return MS::kSuccess;
}
MStatus uninitializePlugin(MObject obj)
{
MStatus stat = MFnPlugin(obj).deregisterNode(Exprespy::id);
CHECK_MSTATUS_AND_RETURN_IT(stat);
return MS::kSuccess;
}
| ryusas/maya_exprespy | srcs/exprespy.cpp | C++ | mit | 49,535 |
import logging
logging.basicConfig(level=logging.DEBUG)
import nengo
import nengo_spinnaker
import numpy as np
def test_probe_ensemble_voltages():
with nengo.Network("Test Network") as network:
# Create an Ensemble with 2 neurons that have known gain and bias. The
# result is that we know how the membrane voltage should change over
# time even with no external stimulus.
ens = nengo.Ensemble(2, 1)
ens.bias = [0.5, 1.0]
ens.gain = [0.0, 0.0]
# Add the voltage probe
probe = nengo.Probe(ens.neurons, "voltage")
# Compute the rise time to 95%
max_t = -ens.neuron_type.tau_rc * np.log(0.05)
# Run the simulation for this period of time
sim = nengo_spinnaker.Simulator(network)
with sim:
sim.run(max_t)
# Compute the ideal voltage curves
c = 1.0 - np.exp(-sim.trange() / ens.neuron_type.tau_rc)
ideal = np.dot(ens.bias[:, np.newaxis], c[np.newaxis, :]).T
# Assert that the ideal curves match the retrieved curves well
assert np.allclose(ideal, sim.data[probe], atol=1e-3)
if __name__ == "__main__":
test_probe_ensemble_voltages()
| project-rig/nengo_spinnaker | regression-tests/test_voltage_probing.py | Python | mit | 1,158 |
using System;
namespace Proxy
{
class RealPhoto : IPhoto
{
private string fileName;
public RealPhoto(string fileName)
{
this.fileName = fileName;
LoadPhoto(fileName);
}
public void Display()
{
Console.WriteLine("Displaying " + fileName);
}
private void LoadPhoto(String fileName)
{
Console.WriteLine("Loading " + fileName);
}
}
}
| IvayloP/TelerikAcademy2016-2017 | HQC/04.DesingPatterns/02.StructuralPatterns/Proxy/RealPhoto.cs | C# | mit | 477 |
<div class="workplace">
<div class="row-fluid">
<div class="span12">
<?php $this->load->view('admin/includes/message'); ?>
<div class="head clearfix">
<div class="isw-grid"></div>
<h1>API Manager</h1>
</div>
<div class="block-fluid table-sorting clearfix">
<table cellpadding="0" cellspacing="0" width="100%" class="table" id="TableDeferLoading">
<thead>
<tr>
<th width="5%">ID</th>
<th width="13%">Title</th>
<th width="24%">Host</th>
<th width="12%">Username</th>
<th width="8%">Api Type</th>
<th width="14%">Updated Date Time</th>
<th width="14%">Created Date Time</th>
<th width="10%">Options</th>
</tr>
</thead>
</table>
</div>
<a href="<?php echo site_url('admin/apimanager/add') ?>"><button class="btn" type="button">Add an api</button></a>
</div>
</div>
<div class="dr"><span></span></div>
<div class="row-fluid">
<div class="span3">
<div class="head clearfix">
<div class="isw-brush"></div>
<h1>Options Icons</h1>
</div>
<div class="block">
<ul class="the-icons clearfix">
<li><i class="isb-cloud"></i> Services List</li>
<li><i class="isb-edit"></i> Edit Record</li>
<li><i class="isb-delete"></i> Delete Record</li>
</ul>
</div>
</div>
</div>
</div>
<script type="text/javascript" charset="utf-8">
$(document).ready(function()
{
$('#TableDeferLoading').dataTable
({
'bProcessing' : true,
'bServerSide' : true,
'bAutoWidth' : false,
'sPaginationType': 'full_numbers',
'sAjaxSource' : '<?php echo site_url('admin/apimanager/listener'); ?>',
'aoColumnDefs': [ { "bSortable": false, "aTargets": [ 7 ] } ],
'sDom' : 'T<"clear">lfrtip', //datatable export buttons
'oTableTools' :
{ //datatable export buttons
"sSwfPath": "<?php echo $this->config->item('assets_url');?>js/plugins/dataTables/media/swf/copy_csv_xls_pdf.swf",
"sRowSelect": "multi"
},
'aoColumns' :
[
{
'bSearchable': false,
'bVisible' : true
},
null,
null,
null,
null,
null,
null,
null
],
'fnServerData': function(sSource, aoData, fnCallback)
{
<?php if($this->config->item('csrf_protection') === TRUE){ ?>
aoData.push({ name : '<?php echo $this->config->item('csrf_token_name'); ?>', value : $.cookie('<?php echo $this->config->item('csrf_cookie_name'); ?>') });
<?php } ?>
$.ajax
({
'dataType': 'json',
'type' : 'POST',
'url' : sSource,
'data' : aoData,
'success' : fnCallback
});
}
});
});
</script> | muhammad-shariq/exclusiveunlock | application/views/admin/apimanager/list.php | PHP | mit | 3,622 |
<div class="nav_menu">
<div>
<div class="top_menu" style="padding-left: 20px;">
<div class="container"><div class="row"><div class="col-md-12">
<div class="top_info"><span><i class="fa fa-phone-square"></i>+91 9829211106</span><span> <i class="fa fa-envelope-o"></i> <a href="mailto:info@vidhyarthidarpan.com" style="color: #ffffff;"> info@vidhyarthidarpan.com</a></span></div>
<div class="right_top_menu">
<button type="button" class="top_m1 navbar-toggle" data-toggle="collapse" data-target=".top_menu2">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
</div></div></div>
</div>
<div class="logo_panel" style="padding-left: 20px;">
<div class="container">
<div class="row">
<div class="col-md-2 col-xs-4 logo1">
<div class="logo"><a href="http://www.vidhyarthidarpan.com/" title="Go to Vidhyarthi Darpan"><img src="http://www.vidhyarthidarpan.com/images/logo.png" class="img-responsive" alt="logo"></a></div>
</div>
<div class="col-md-8">
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
</div>
<nav>
<div class="nav toggle">
<a id="menu_toggle"><i class="fa fa-bars"></i></a>
</div>
<ul class="nav navbar-nav navbar-right">
<li class="">
<a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<img src="<?php /* echo profilepic($_SESSION['manage_session']['profilePhoto']); */ ?>" alt=""><?php echo $_SESSION['manage_session']['iName']; ?>
<span class=" fa fa-angle-down"></span>
</a>
<ul class="dropdown-menu dropdown-usermenu pull-right">
<li><a href="<?php echo base_url('manage/user'); ?>"> Profile</a></li>
<li>
<a href="javascript:;">
<span class="badge bg-red pull-right">50%</span>
<span>Settings</span>
</a>
</li>
<li><a href="javascript:;">Help</a></li>
<li><a href="<?php echo base_url('manage_logout'); ?>"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li>
</ul>
</li>
<!-- <li role="presentation" class="dropdown">
<a href="javascript:;" class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false">
<i class="fa fa-envelope-o"></i>
<span class="badge bg-green">6</span>
</a>
<ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu">
<li>
<a>
<span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span>
<span>
<span>John Smith</span>
<span class="time">3 mins ago</span>
</span>
<span class="message">
Film festivals used to be do-or-die moments for movie makers. They were where...
</span>
</a>
</li>
<li>
<a>
<span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span>
<span>
<span>John Smith</span>
<span class="time">3 mins ago</span>
</span>
<span class="message">
Film festivals used to be do-or-die moments for movie makers. They were where...
</span>
</a>
</li>
<li>
<a>
<span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span>
<span>
<span>John Smith</span>
<span class="time">3 mins ago</span>
</span>
<span class="message">
Film festivals used to be do-or-die moments for movie makers. They were where...
</span>
</a>
</li>
<li>
<a>
<span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span>
<span>
<span>John Smith</span>
<span class="time">3 mins ago</span>
</span>
<span class="message">
Film festivals used to be do-or-die moments for movie makers. They were where...
</span>
</a>
</li>
<li>
<div class="text-center">
<a>
<strong>See All Alerts</strong>
<i class="fa fa-angle-right"></i>
</a>
</div>
</li>
</ul>
</li>-->
</ul>
</nav>
</div> | ajaykumarparashar11/VD | application/views/manage/layout/header.php | PHP | mit | 6,983 |
'use strict';
var Lab = require('lab'),
Hapi = require('hapi'),
Plugin = require('../../../lib/plugins/sugendran');
var describe = Lab.experiment;
var it = Lab.test;
var expect = Lab.expect;
var before = Lab.before;
var after = Lab.after;
describe('sugendran', function() {
var server = new Hapi.Server();
it('Plugin successfully loads', function(done) {
server.pack.register(Plugin, function(err) {
expect(err).to.not.exist;
done();
});
});
it('Plugin registers routes', function(done) {
var table = server.table();
expect(table).to.have.length(1);
expect(table[0].path).to.equal('/sugendran');
done();
});
it('Plugin route responses', function(done) {
var table = server.table();
expect(table).to.have.length(1);
expect(table[0].path).to.equal('/sugendran');
var request = {
method: 'GET',
url: '/sugendran'
};
server.inject(request, function(res) {
expect(res.statusCode).to.equal(200);
expect(res.result).to.equal('don\'t worry, be hapi!');
done();
});
});
});
| nvcexploder/hapi-lxjs | test/plugins/sugendran/index.js | JavaScript | mit | 1,090 |
import app from 'flarum/forum/app';
import { extend } from 'flarum/common/extend';
import DiscussionControls from 'flarum/forum/utils/DiscussionControls';
import DiscussionPage from 'flarum/forum/components/DiscussionPage';
import Button from 'flarum/common/components/Button';
export default function addStickyControl() {
extend(DiscussionControls, 'moderationControls', function (items, discussion) {
if (discussion.canSticky()) {
items.add(
'sticky',
Button.component(
{
icon: 'fas fa-thumbtack',
onclick: this.stickyAction.bind(discussion),
},
app.translator.trans(
discussion.isSticky()
? 'flarum-sticky.forum.discussion_controls.unsticky_button'
: 'flarum-sticky.forum.discussion_controls.sticky_button'
)
)
);
}
});
DiscussionControls.stickyAction = function () {
this.save({ isSticky: !this.isSticky() }).then(() => {
if (app.current.matches(DiscussionPage)) {
app.current.get('stream').update();
}
m.redraw();
});
};
}
| flarum/sticky | js/src/forum/addStickyControl.js | JavaScript | mit | 1,121 |
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostClassifier
from skTMVA import convert_bdt_sklearn_tmva
import cPickle
import numpy as np
from numpy.random import RandomState
RNG = RandomState(21)
# Construct an example dataset for binary classification
n_vars = 2
n_events = 10000
signal = RNG.multivariate_normal(
np.ones(n_vars), np.diag(np.ones(n_vars)), n_events)
background = RNG.multivariate_normal(
np.ones(n_vars) * -1, np.diag(np.ones(n_vars)), n_events)
X = np.concatenate([signal, background])
y = np.ones(X.shape[0])
w = RNG.randint(1, 10, n_events * 2)
y[signal.shape[0]:] *= -1
permute = RNG.permutation(y.shape[0])
X = X[permute]
y = y[permute]
# Use all dataset for training
X_train, y_train, w_train = X, y, w
# Declare BDT - we are going to use AdaBoost Decision Tree
dt = DecisionTreeClassifier(max_depth=3,
min_samples_leaf=int(0.05*len(X_train)))
bdt = AdaBoostClassifier(dt,
algorithm='SAMME',
n_estimators=800,
learning_rate=0.5)
# Train BDT
bdt.fit(X_train, y_train)
# Save BDT to pickle file
with open('bdt_sklearn_to_tmva_example.pkl', 'wb') as fid:
cPickle.dump(bdt, fid)
# Save BDT to TMVA xml file
# Note:
# - declare input variable names and their type
# - variable order is important for TMVA
convert_bdt_sklearn_tmva(bdt, [('var1', 'F'), ('var2', 'F')], 'bdt_sklearn_to_tmva_example.xml')
| yuraic/koza4ok | examples/bdt_sklearn_to_tmva_AdaBoost.py | Python | mit | 1,493 |
# encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2020_08_01
module Models
#
# Defines values for ProcessorArchitecture
#
module ProcessorArchitecture
Amd64 = "Amd64"
X86 = "X86"
end
end
end
| Azure/azure-sdk-for-ruby | management/azure_mgmt_network/lib/2020-08-01/generated/azure_mgmt_network/models/processor_architecture.rb | Ruby | mit | 371 |
'use strict'
import assert from 'assert'
import { btoa } from 'Base64'
import decode from 'jwt-decode'
import token from './data/token'
import tokenTimezone from './data/token-timezone'
import ls from 'local-storage'
import bluebird from 'bluebird'
import sinon from 'sinon'
const setTokenExp = (timestamp) => {
// hacky adjustment of expiration of the token
const decoded = decode(token)
decoded.exp = timestamp / 1000
const [head, , sig] = token.split('.')
return `${head}.${btoa(JSON.stringify(decoded))}.${sig}`
}
describe('Token Store', () => {
const localStorageKey = 'coolKey'
let updatedToken
beforeEach(() => {
// HACK around https://github.com/auth0/jwt-decode/issues/5
global.window = global
// HACK around cookie monster returning undefined when document isn't there
global.document = {}
})
beforeEach(() => {
updatedToken = setTokenExp(Date.now() + 1000)
})
afterEach(() => {
delete global.window
delete global.document
ls.remove(localStorageKey)
})
it('should set user after no token is present', () => {
const tokenStore = require('../src')()
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
})
tokenStore.init()
tokenStore.setToken(token)
})
it('should get the token out of local storage', () => {
ls.set(localStorageKey, token)
const tokenStore = require('../src')({localStorageKey})
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
})
tokenStore.init()
})
it('should catch an exception token is not present in local storage', () => {
ls.set(localStorageKey, undefined)
const tokenStore = require('../src')({localStorageKey})
tokenStore.on('Token received', assert.fail)
tokenStore.init()
})
it('if no token call refresh & set token', done => {
const tokenStore = require('../src')({refresh: () =>
bluebird.resolve(updatedToken)
})
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
done()
})
tokenStore.init()
})
it('if token is expired, call refresh with expired token', done => {
ls.set(localStorageKey, token)
require('../src')({
localStorageKey,
refresh: (t) => {
assert.equal(t, token)
done()
return bluebird.resolve(updatedToken)
}
}).init()
})
it('if token is expired, call refresh & set token', done => {
ls.set(localStorageKey, token)
const tokenStore = require('../src')({
localStorageKey,
refresh: () =>
bluebird.resolve(updatedToken)
})
let callCount = 0
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
if (++callCount === 2) { done() }
})
tokenStore.init()
})
it('if token valid, leave as is', () => {
ls.set(localStorageKey, setTokenExp(Date.now() + 100 * 60 * 1000))
const tokenStore = require('../src')({
localStorageKey,
refresh: () => assert.fail('should not be called')
})
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
})
tokenStore.init()
})
it('if token to expire soon, refresh after interval', done => {
ls.set(localStorageKey, updatedToken)
const tokenStore = require('../src')({
localStorageKey,
refresh: () => bluebird.resolve(updatedToken),
refreshInterval: 1000
})
let callCount = 0
tokenStore.on('Token received', (_, user) => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
if (++callCount === 2) { done() }
})
tokenStore.init()
})
describe('with fake timers', () => {
let clock
beforeEach(() => {
clock = sinon.useFakeTimers()
})
afterEach(() => {
clock.restore()
})
it('doesn\'t refresh if still outside the expiry window', () => {
ls.set(localStorageKey, updatedToken)
const tokenStore = require('../src')({
localStorageKey,
refresh: () => bluebird.resolve(updatedToken),
expiryWindow: 1,
refreshInterval: 10
})
const spy = sinon.spy()
tokenStore.on('Token received', spy)
tokenStore.init()
clock.tick(11)
assert.equal(spy.callCount, 1)
})
})
it('refreshes the token and sets it', done => {
ls.set(localStorageKey, setTokenExp(Date.now() + 100 * 60 * 1000))
const tokenStore = require('../src')({
localStorageKey,
refresh: () => bluebird.resolve(tokenTimezone)
})
let callCount = 0
tokenStore.on('Token received', (_, user) => {
callCount++
if (callCount === 1) {
assert(!user.timezone)
} else if (callCount === 2) {
assert.equal(user.timezone, 'UTC')
done()
} else {
assert.fail('shouldn\'t be called more than twice')
}
})
tokenStore.init()
tokenStore.refreshToken()
})
describe('sad path', () => {
it('should not blow up when cookie is not present', () => {
let tokenStore
assert.doesNotThrow(() => tokenStore = require('../src')())
assert.doesNotThrow(() => tokenStore.init())
})
it('should not blow up when cookie is invalid', () => {
const token = 'g4rBaG3'
require('cookie-monster').set('XSRF-TOKEN', token)
let tokenStore
assert.doesNotThrow(() => tokenStore = require('../src')())
assert.doesNotThrow(() => tokenStore.init())
})
})
describe('default cookie key', () => {
let tokenFromStore
let user
beforeEach(() => {
require('cookie-monster').set('XSRF-TOKEN', token)
const tokenStore = require('../src')()
tokenStore.on('Token received', (t, u) => {
tokenFromStore = t
user = u
})
tokenStore.init()
})
it('should get the XSRF-TOKEN and return it', () => {
assert.equal(tokenFromStore, token)
})
it('should return user', () => {
assert.equal(user.first_name, 'Mike')
assert.equal(user.last_name, 'Atkins')
})
})
describe('override cookie key', () => {
let tokenFromStore
beforeEach(() => {
require('cookie-monster').set('NOT-XSRF-TOKEN', token)
const tokenStore = require('../src')({ cookie: 'NOT-XSRF-TOKEN' })
tokenStore.on('Token received', (t) => {
tokenFromStore = t
})
tokenStore.init()
})
it('should get the NOT-XSRF-TOKEN and return it', () => {
assert.equal(tokenFromStore, token)
})
})
describe('terminate', () => {
let cookieMonster
beforeEach(() => {
cookieMonster = require('cookie-monster')
cookieMonster.set('XSRF-TOKEN', token)
})
it('should set token to undefined on explicit termination', done => {
let callCount = 0
const tokenStore = require('../src')({
refresh: (t) => {
if (callCount === 0) {
cookieMonster.set('XSRF-TOKEN', token, {expires: 'Thu, 01 Jan 1970 00:00:01 GMT'})
assert.equal(t, token)
}
if (callCount === 1) {
assert.equal(t, undefined)
}
callCount++
return bluebird.resolve(t)
}
})
tokenStore.init()
tokenStore.terminate()
tokenStore.refreshToken()
done()
})
it('should not set token to undefined when no explicit termination', done => {
let callCount = 0
const tokenStore = require('../src')({
refresh: (t) => {
if (!t) {
return bluebird.resolve()
}
if (callCount === 0) {
cookieMonster.set('XSRF-TOKEN', token, {expires: 'Thu, 01 Jan 1970 00:00:01 GMT'})
assert.equal(t, token)
}
if (callCount === 1) {
assert.equal(t, token)
}
callCount++
return bluebird.resolve(t)
}
})
tokenStore.init()
tokenStore.refreshToken()
done()
})
})
})
| lanetix/react-jwt-store | test/index.js | JavaScript | mit | 8,273 |
<?php
/**
* This file is part of the fangface/yii2-concord package
*
* For the full copyright and license information, please view
* the file LICENSE.md that was distributed with this source code.
*
* @package fangface/yii2-concord
* @author Fangface <dev@fangface.net>
* @copyright Copyright (c) 2014 Fangface <dev@fangface.net>
* @license https://github.com/fangface/yii2-concord/blob/master/LICENSE.md MIT License
*
*/
namespace fangface\models\eav;
use fangface\db\ActiveRecord;
/**
* Default Active Record class for the attributeEntities table
*
* @method AttributeEntities findOne($condition = null) static
* @method AttributeEntities[] findAll($condition = null) static
* @method AttributeEntities[] findByCondition($condition, $one) static
*/
class AttributeEntities extends ActiveRecord
{
protected $disableAutoBehaviors = true;
}
| fangface/yii2-concord | src/models/eav/AttributeEntities.php | PHP | mit | 865 |
<?php
namespace Acme\PaymentBundle\Controller;
use Payum\Bundle\PayumBundle\Controller\PayumController;
use Payum\Core\Exception\RequestNotSupportedException;
use Payum\Core\Request\BinaryMaskStatusRequest;
use Payum\Core\Request\SyncRequest;
use Symfony\Component\HttpFoundation\Request;
class DetailsController extends PayumController
{
public function viewAction(Request $request)
{
$token = $this->getHttpRequestVerifier()->verify($request);
$payment = $this->getPayum()->getPayment($token->getPaymentName());
try {
$payment->execute(new SyncRequest($token));
} catch (RequestNotSupportedException $e) {}
$status = new BinaryMaskStatusRequest($token);
$payment->execute($status);
return $this->render('AcmePaymentBundle:Details:view.html.twig', array(
'status' => $status,
'paymentTitle' => ucwords(str_replace(array('_', '-'), ' ', $token->getPaymentName()))
));
}
} | a2xchip/SagepayBundleSandbox | src/Acme/PaymentBundle/Controller/DetailsController.php | PHP | mit | 1,005 |
import sys
script, encoding, error = sys.argv
def main(language_file, encoding, errors):
line = language_file.readline()
if line:
print_line(line, encoding, errors)
return main(language_file, encoding, errors)
def print_line(line, encoding, errors):
next_lang = line.strip()
raw_bytes = next_lang.encode(encoding, errors=errors)
cooked_string = raw_bytes.decode(encoding, errors=errors)
print(raw_bytes, "<===>", cooked_string)
languages = open("languages.txt", encoding="utf-8")
main(languages, encoding, error)
| Herne/pythonplayground | lp3thw/ex23.py | Python | mit | 563 |
using System;
using Microsoft.AspNetCore.Mvc;
using Smidge.CompositeFiles;
using Smidge.Models;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Smidge.FileProcessors;
using Smidge.Cache;
using Microsoft.AspNetCore.Authorization;
namespace Smidge.Controllers
{
/// <summary>
/// Controller for handling minified/combined responses
/// </summary>
[AddCompressionHeader(Order = 0)]
[AddExpiryHeaders(Order = 1)]
[CheckNotModified(Order = 2)]
[CompositeFileCacheFilter(Order = 3)]
[AllowAnonymous]
public class SmidgeController : Controller
{
private readonly ISmidgeFileSystem _fileSystem;
private readonly IBundleManager _bundleManager;
private readonly IBundleFileSetGenerator _fileSetGenerator;
private readonly PreProcessPipelineFactory _processorFactory;
private readonly IPreProcessManager _preProcessManager;
private readonly ILogger _logger;
/// <summary>
/// Constructor
/// </summary>
/// <param name="fileSystemHelper"></param>
/// <param name="bundleManager"></param>
/// <param name="fileSetGenerator"></param>
/// <param name="processorFactory"></param>
/// <param name="preProcessManager"></param>
/// <param name="logger"></param>
public SmidgeController(
ISmidgeFileSystem fileSystemHelper,
IBundleManager bundleManager,
IBundleFileSetGenerator fileSetGenerator,
PreProcessPipelineFactory processorFactory,
IPreProcessManager preProcessManager,
ILogger<SmidgeController> logger)
{
_fileSystem = fileSystemHelper ?? throw new ArgumentNullException(nameof(fileSystemHelper));
_bundleManager = bundleManager ?? throw new ArgumentNullException(nameof(bundleManager));
_fileSetGenerator = fileSetGenerator ?? throw new ArgumentNullException(nameof(fileSetGenerator));
_processorFactory = processorFactory ?? throw new ArgumentNullException(nameof(processorFactory));
_preProcessManager = preProcessManager ?? throw new ArgumentNullException(nameof(preProcessManager));
_logger = logger;
}
/// <summary>
/// Handles requests for named bundles
/// </summary>
/// <param name="bundleModel">The bundle model</param>
/// <returns></returns>
public async Task<IActionResult> Bundle(
[FromServices] BundleRequestModel bundleModel)
{
if (!_bundleManager.TryGetValue(bundleModel.FileKey, out Bundle foundBundle))
{
return NotFound();
}
var bundleOptions = foundBundle.GetBundleOptions(_bundleManager, bundleModel.Debug);
var cacheBusterValue = bundleModel.ParsedPath.CacheBusterValue;
//now we need to determine if this bundle has already been created
var cacheFile = _fileSystem.CacheFileSystem.GetCachedCompositeFile(cacheBusterValue, bundleModel.Compression, bundleModel.FileKey, out var cacheFilePath);
if (cacheFile.Exists)
{
_logger.LogDebug($"Returning bundle '{bundleModel.FileKey}' from cache");
if (!string.IsNullOrWhiteSpace(cacheFile.PhysicalPath))
{
//if physical path is available then it's the physical file system, in which case we'll deliver the file with the PhysicalFileResult
//FilePathResult uses IHttpSendFileFeature which is a native host option for sending static files
return PhysicalFile(cacheFile.PhysicalPath, bundleModel.Mime);
}
else
{
return File(cacheFile.CreateReadStream(), bundleModel.Mime);
}
}
//the bundle doesn't exist so we'll go get the files, process them and create the bundle
//TODO: We should probably lock here right?! we don't want multiple threads trying to do this at the same time, we'll need a dictionary of locks to do this effectively
//get the files for the bundle
var files = _fileSetGenerator.GetOrderedFileSet(foundBundle,
_processorFactory.CreateDefault(
//the file type in the bundle will always be the same
foundBundle.Files[0].DependencyType))
.ToArray();
if (files.Length == 0)
{
return NotFound();
}
using (var bundleContext = new BundleContext(cacheBusterValue, bundleModel, cacheFilePath))
{
var watch = new Stopwatch();
watch.Start();
_logger.LogDebug($"Processing bundle '{bundleModel.FileKey}', debug? {bundleModel.Debug} ...");
//we need to do the minify on the original files
foreach (var file in files)
{
await _preProcessManager.ProcessAndCacheFileAsync(file, bundleOptions, bundleContext);
}
//Get each file path to it's hashed location since that is what the pre-processed file will be saved as
var fileInfos = files.Select(x => _fileSystem.CacheFileSystem.GetCacheFile(
x,
() => _fileSystem.GetRequiredFileInfo(x),
bundleOptions.FileWatchOptions.Enabled,
Path.GetExtension(x.FilePath),
cacheBusterValue,
out _));
using (var resultStream = await GetCombinedStreamAsync(fileInfos, bundleContext))
{
//compress the response (if enabled)
var compressedStream = await Compressor.CompressAsync(
//do not compress anything if it's not enabled in the bundle options
bundleOptions.CompressResult ? bundleModel.Compression : CompressionType.None,
resultStream);
//save the resulting compressed file, if compression is not enabled it will just save the non compressed format
// this persisted file will be used in the CheckNotModifiedAttribute which will short circuit the request and return
// the raw file if it exists for further requests to this path
await CacheCompositeFileAsync(_fileSystem.CacheFileSystem, cacheFilePath, compressedStream);
_logger.LogDebug($"Processed bundle '{bundleModel.FileKey}' in {watch.ElapsedMilliseconds}ms");
//return the stream
return File(compressedStream, bundleModel.Mime);
}
}
}
/// <summary>
/// Handles requests for composite files (non-named bundles)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public async Task<IActionResult> Composite(
[FromServices] CompositeFileModel file)
{
if (!file.ParsedPath.Names.Any())
{
return NotFound();
}
var defaultBundleOptions = _bundleManager.GetDefaultBundleOptions(false);
var cacheBusterValue = file.ParsedPath.CacheBusterValue;
var cacheFile = _fileSystem.CacheFileSystem.GetCachedCompositeFile(cacheBusterValue, file.Compression, file.FileKey, out var cacheFilePath);
if (cacheFile.Exists)
{
//this is already processed, return it
if (!string.IsNullOrWhiteSpace(cacheFile.PhysicalPath))
{
//if physical path is available then it's the physical file system, in which case we'll deliver the file with the PhysicalFileResult
//FilePathResult uses IHttpSendFileFeature which is a native host option for sending static files
return PhysicalFile(cacheFile.PhysicalPath, file.Mime);
}
else
{
return File(cacheFile.CreateReadStream(), file.Mime);
}
}
using (var bundleContext = new BundleContext(cacheBusterValue, file, cacheFilePath))
{
var files = file.ParsedPath.Names.Select(filePath =>
_fileSystem.CacheFileSystem.GetRequiredFileInfo(
$"{file.ParsedPath.CacheBusterValue}/{filePath + file.Extension}"));
using (var resultStream = await GetCombinedStreamAsync(files, bundleContext))
{
var compressedStream = await Compressor.CompressAsync(file.Compression, resultStream);
await CacheCompositeFileAsync(_fileSystem.CacheFileSystem, cacheFilePath, compressedStream);
return File(compressedStream, file.Mime);
}
}
}
private static async Task CacheCompositeFileAsync(ICacheFileSystem cacheProvider, string filePath, Stream compositeStream)
{
await cacheProvider.WriteFileAsync(filePath, compositeStream);
if (compositeStream.CanSeek)
compositeStream.Position = 0;
}
/// <summary>
/// Combines files into a single stream
/// </summary>
/// <param name="files"></param>
/// <param name="bundleContext"></param>
/// <returns></returns>
private async Task<Stream> GetCombinedStreamAsync(IEnumerable<IFileInfo> files, BundleContext bundleContext)
{
//TODO: Here we need to be able to prepend/append based on a "BundleContext" (or similar)
List<Stream> inputs = null;
try
{
inputs = files.Where(x => x.Exists)
.Select(x => x.CreateReadStream())
.ToList();
var delimeter = bundleContext.BundleRequest.Extension == ".js" ? ";\n" : "\n";
var combined = await bundleContext.GetCombinedStreamAsync(inputs, delimeter);
return combined;
}
finally
{
if (inputs != null)
{
foreach (var input in inputs)
{
input.Dispose();
}
}
}
}
}
} | Shazwazza/Smidge | src/Smidge/Controllers/SmidgeController.cs | C# | mit | 10,731 |
'use strict';
module.exports = function(grunt) {
require('jit-grunt')(grunt, {
});
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
grunt.initConfig({});
// Automatically inject Bower components into the app
grunt.config.set('wiredep', {
target: {
src: 'src/client/index.html',
ignorePath: '',
exclude: []
}
});
}; | mcortesi/artviz | Gruntfile.js | JavaScript | mit | 408 |
const angular = require('angular');
require('angular-ui-router');
require('bootstrap');
require('bootstrap/dist/css/bootstrap.css');
require('./config');
require('./services');
require('./filters');
require('./layout');
require('./list');
require('./detail');
require('./watchlist');
window.app = angular.module('app', [
'ui.router',
'app.config',
'app.filters',
'app.services',
'app.layout',
'app.list',
'app.watchlist',
'app.detail'
]);
| SCThijsse/angularjs-single-page | app/index.js | JavaScript | mit | 457 |
require './spec/spec_helper'
describe Economic::CashBookEntry do
let(:session) { make_session }
subject { Economic::CashBookEntry.new(:session => session) }
it "inherits from Economic::Entity" do
Economic::CashBookEntry.ancestors.should include(Economic::Entity)
end
describe ".proxy" do
it "should return a CashBookEntryProxy" do
subject.proxy.should be_instance_of(Economic::CashBookEntryProxy)
end
it "should return a proxy owned by session" do
subject.proxy.session.should == session
end
end
describe "#save" do
it 'should save it' do
stub_request('CashBookEntry_CreateFromData', nil, :success)
subject.save
end
end
end
| kongens-net/rconomic | spec/economic/cash_book_entry_spec.rb | Ruby | mit | 698 |
/**
* @file KeyboardButton.cpp
* @brief Contains KeyboardButton class implementation
* @author Khalin Yevhen
* @version 0.0.2
* @date 28.09.17
*/
#include "KeyboardButton.h"
#include "..\khalin03\Button.cpp"
KeyboardButton::KeyboardButton(ButtonForm form, int code, string name) :
Button(form), code(code), name(name)
{
}
KeyboardButton::~KeyboardButton()
{
}
int KeyboardButton::getCode()
{
return code;
}
string KeyboardButton::getName()
{
return name;
}
void KeyboardButton::setData(int & code)
{
this->code = code;
}
void KeyboardButton::setData(string name, int & code)
{
this->code = code;
this->name = name;
}
bool KeyboardButton::operator==(int val)
{
return val == code;
}
void KeyboardButton::operator-=(char c)
{
string newName;
char iter = name[0];
int addedCounter = 0;
for (auto i = 0; i < name.length(); i++) {
iter = name[i];
if (iter != c) {
newName += iter;
}
}
name = newName;
} | kit25a/se-cpp | khalin-yevhen/src/khalin04/keyboardButton.cpp | C++ | mit | 992 |
#include "perspectivecamera.h"
#include <stdexcept>
#include <gtc/matrix_transform.hpp>
using namespace Camera;
PerspectiveCamera::PerspectiveCamera(float verticalFieldOfView, float aspectRatio)
: verticalFieldOfView(verticalFieldOfView), aspectRatio(aspectRatio)
{
changeZoomFactor(glm::vec2(1.0f, 1.0f));
changeProjectionMatrix();
}
PerspectiveCamera::~PerspectiveCamera()
{
}
void PerspectiveCamera::changeZoomFactor(const glm::vec2& zoom)
{
if (!validateZoomFactor(zoom))
throw std::invalid_argument("Zoom factors cannot be negative!");
this->zoom = zoom;
verticalFieldOfView = 2 * std::atan(1.0f / zoom.y);
changeProjectionMatrix();
}
void PerspectiveCamera::changeFieldOfView(float verticalFieldOfView)
{
this->verticalFieldOfView = verticalFieldOfView;
changeProjectionMatrix();
}
void PerspectiveCamera::changeAspectRatio(int width, int height)
{
if (width > 0 && height > 0)
this->aspectRatio = (float)width / (float)height;
else
this->aspectRatio = (float)16 / (float)9;
changeProjectionMatrix();
}
void PerspectiveCamera::changeProjectionMatrix()
{
projection = glm::perspective(verticalFieldOfView, aspectRatio, zNear, zFar);
}
void PerspectiveCamera::contextUpdated(QOpenGLWidget* updatedContext)
{
changeAspectRatio(updatedContext->width(), updatedContext->height());
} | Vaub/uGL | Project/uGL/uGLCore/perspectivecamera.cpp | C++ | mit | 1,319 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
/**
* Validates whether a value is a valid timezone identifier.
*
* @author Javier Spagnoletti <phansys@gmail.com>
* @author Hugo Hamon <hugohamon@neuf.fr>
*/
class TimezoneValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof Timezone) {
throw new UnexpectedTypeException($constraint, Timezone::class);
}
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedValueException($value, 'string');
}
$value = (string) $value;
// @see: https://bugs.php.net/bug.php?id=75928
if ($constraint->countryCode) {
$timezoneIds = \DateTimeZone::listIdentifiers($constraint->zone, $constraint->countryCode);
} else {
$timezoneIds = \DateTimeZone::listIdentifiers($constraint->zone);
}
if ($timezoneIds && \in_array($value, $timezoneIds, true)) {
return;
}
if ($constraint->countryCode) {
$code = Timezone::TIMEZONE_IDENTIFIER_IN_COUNTRY_ERROR;
} elseif (\DateTimeZone::ALL !== $constraint->zone) {
$code = Timezone::TIMEZONE_IDENTIFIER_IN_ZONE_ERROR;
} else {
$code = Timezone::TIMEZONE_IDENTIFIER_ERROR;
}
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->setCode($code)
->addViolation();
}
/**
* {@inheritdoc}
*/
public function getDefaultOption()
{
return 'zone';
}
/**
* {@inheritdoc}
*/
protected function formatValue($value, $format = 0)
{
$value = parent::formatValue($value, $format);
if (!$value || \DateTimeZone::PER_COUNTRY === $value) {
return $value;
}
return array_search($value, (new \ReflectionClass(\DateTimeZone::class))->getConstants(), true) ?: $value;
}
}
| curry684/symfony | src/Symfony/Component/Validator/Constraints/TimezoneValidator.php | PHP | mit | 2,714 |
const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const ExtraWatchWebpackPlugin = require('extra-watch-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const VERSION = require('./package.json').version;
class VersionFilePlugin {
apply() {
fs.writeFileSync(
path.resolve(__dirname, 'lib/mol-plugin/version.js'),
`export var PLUGIN_VERSION = '${VERSION}';\nexport var PLUGIN_VERSION_DATE = new Date(typeof __MOLSTAR_DEBUG_TIMESTAMP__ !== 'undefined' ? __MOLSTAR_DEBUG_TIMESTAMP__ : ${new Date().valueOf()});`);
}
}
const sharedConfig = {
module: {
rules: [
{
test: /\.(html|ico)$/,
use: [{
loader: 'file-loader',
options: { name: '[name].[ext]' }
}]
},
{
test: /\.(s*)css$/,
use: [
MiniCssExtractPlugin.loader,
{ loader: 'css-loader', options: { sourceMap: false } },
{ loader: 'sass-loader', options: { sourceMap: false } },
]
}
]
},
plugins: [
new ExtraWatchWebpackPlugin({
files: [
'./lib/**/*.scss',
'./lib/**/*.html'
],
}),
new webpack.DefinePlugin({
'process.env.DEBUG': JSON.stringify(process.env.DEBUG),
'__MOLSTAR_DEBUG_TIMESTAMP__': webpack.DefinePlugin.runtimeValue(() => `${new Date().valueOf()}`, true)
}),
new MiniCssExtractPlugin({ filename: 'molstar.css' }),
new VersionFilePlugin(),
],
resolve: {
modules: [
'node_modules',
path.resolve(__dirname, 'lib/')
],
fallback: {
fs: false,
crypto: require.resolve('crypto-browserify'),
path: require.resolve('path-browserify'),
stream: require.resolve('stream-browserify'),
}
},
watchOptions: {
aggregateTimeout: 750
}
};
function createEntry(src, outFolder, outFilename, isNode) {
return {
target: isNode ? 'node' : void 0,
entry: path.resolve(__dirname, `lib/${src}.js`),
output: { filename: `${outFilename}.js`, path: path.resolve(__dirname, `build/${outFolder}`) },
...sharedConfig
};
}
function createEntryPoint(name, dir, out, library) {
return {
entry: path.resolve(__dirname, `lib/${dir}/${name}.js`),
output: { filename: `${library || name}.js`, path: path.resolve(__dirname, `build/${out}`), library: library || out, libraryTarget: 'umd' },
...sharedConfig
};
}
function createNodeEntryPoint(name, dir, out) {
return {
target: 'node',
entry: path.resolve(__dirname, `lib/${dir}/${name}.js`),
output: { filename: `${name}.js`, path: path.resolve(__dirname, `build/${out}`) },
externals: {
argparse: 'require("argparse")',
'node-fetch': 'require("node-fetch")',
'util.promisify': 'require("util.promisify")',
xhr2: 'require("xhr2")',
},
...sharedConfig
};
}
function createApp(name, library) { return createEntryPoint('index', `apps/${name}`, name, library); }
function createExample(name) { return createEntry(`examples/${name}/index`, `examples/${name}`, 'index'); }
function createBrowserTest(name) { return createEntryPoint(name, 'tests/browser', 'tests'); }
function createNodeApp(name) { return createNodeEntryPoint('index', `apps/${name}`, name); }
module.exports = {
createApp,
createEntry,
createExample,
createBrowserTest,
createNodeEntryPoint,
createNodeApp
};
| molstar/molstar | webpack.config.common.js | JavaScript | mit | 3,792 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class FigureQuintupleDot11 : Figure
{
private const int score = 5;
public FigureQuintupleDot11(int player): base(player)
{
figure[4, 4] = figure[5, 4] = figure[5, 5] = figure[5, 6] = figure[5, 7] = player;
}
public override void rotate()
{
currentPossition = ++currentPossition % 8;
switch (currentPossition)
{
case 0:
for (short i = 0; i < 8; i++)
{
for (short j = 0; j < 8; j++)
{
figure[i, j] = 0;
}
}
figure[4, 4] = figure[5, 4] = figure[5, 5] = figure[5, 6] = figure[5, 7] = owner;
break;
case 1:
figure[5, 4] = figure[5, 5] = figure[5, 6] = figure[5, 7] = 0;
figure[4, 3] = figure[5, 3] = figure[6, 3] = figure[7, 3] = owner;
break;
case 2:
figure[4, 3] = figure[5, 3] = figure[6, 3] = figure[7, 3] = 0;
figure[3, 1] = figure[3, 2] = figure[3, 3] = figure[3, 4] = owner;
break;
case 3:
figure[3, 1] = figure[3, 2] = figure[3, 3] = figure[3, 4] = 0;
figure[1, 5] = figure[2, 5] = figure[3, 5] = figure[4, 5] = owner;
break;
case 4:
for (short i = 0; i < 8; i++)
{
for (short j = 0; j < 8; j++)
{
figure[i, j] = 0;
}
}
figure[4, 4] = figure[5, 1] = figure[5, 2] = figure[5, 3] = figure[5, 4] = owner;
break;
case 5:
figure[5, 1] = figure[5, 2] = figure[5, 3] = figure[5, 4] = 0;
figure[1, 3] = figure[2, 3] = figure[3, 3] = figure[4, 3] = owner;
break;
case 6:
figure[1, 3] = figure[2, 3] = figure[3, 3] = figure[4, 3] = 0;
figure[3, 4] = figure[3, 5] = figure[3, 6] = figure[3, 7] = owner;
break;
case 7:
figure[3, 4] = figure[3, 5] = figure[3, 6] = figure[3, 7] = 0;
figure[4, 5] = figure[5, 5] = figure[6, 5] = figure[7, 5] = owner;
break;
}
}
}
| siderisltd/Telerik-Academy | All TeamProjects/TeamProject C# 1_ Blokus/Blokus/FigureQuintupleDot11.cs | C# | mit | 2,564 |
using System;
namespace C5
{
[Serializable]
internal class MultiplicityOne<K> : MappedCollectionValue<K, System.Collections.Generic.KeyValuePair<K, int>>
{
public MultiplicityOne(ICollectionValue<K> coll) : base(coll) { }
public override System.Collections.Generic.KeyValuePair<K, int> Map(K k) { return new System.Collections.Generic.KeyValuePair<K, int>(k, 1); }
}
} | sestoft/C5 | C5/Enumerators/MultiplicityOne.cs | C# | mit | 401 |
<?php
// src/Blogger/BlogBundle/Controller/PageController.php
namespace Blogger\BlogBundle\Controller;
use Blogger\BlogBundle\Entity\Enquiry;
use Blogger\BlogBundle\Form\EnquiryType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PageController extends Controller
{
public function indexAction()
{
return $this->render('BloggerBlogBundle:Page:index.html.twig');
}
public function aboutAction()
{
return $this->render('BloggerBlogBundle:Page:about.html.twig');
}
public function contactAction()
{
$enquiry = new Enquiry();
$form = $this->createForm(new EnquiryType(), $enquiry);
$request = $this->getRequest();
if ($request->getMethod() == 'POST') {
$form->bindRequest($request);
if ($form->isValid()) {
$message = \Swift_Message::newInstance()
->setSubject('Contact enquiry from symblog')
->setFrom('leonardo.chaves.freitas@gmail.com')
->setTo('leochaves@gmail.com')
->setBody($this->renderView('BloggerBlogBundle:Page:contactEmail.txt.twig', array('enquiry' => $enquiry)));
$this->get('mailer')->send($message);
$this->get('session')->setFlash('blogger-notice', 'Your contact enquiry was successfully sent. Thank you!');
// Redirect - This is important to prevent users re-posting
// the form if they refresh the page
return $this->redirect($this->generateUrl('BloggerBlogBundle_contact'));
}
}
return $this->render('BloggerBlogBundle:Page:contact.html.twig', array(
'form' => $form->createView()
));
}
}
| leochaves/Blog-Symfony | src/Blogger/BlogBundle/Controller/PageController.php | PHP | mit | 1,713 |
<?php
/*
* This file is part of the Sonata package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\UserBundle\Admin\Entity;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Route\RouteCollection;
class GroupAdmin extends Admin
{
public function getNewInstance()
{
$class = $this->getClass();
return new $class('', array());
}
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('roles')
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('name')
;
}
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('name')
->add('roles', 'sonata_security_roles', array( 'multiple' => true, 'required' => false))
;
}
} | dunglas/SonataUserBundle | Admin/Entity/GroupAdmin.php | PHP | mit | 1,228 |
<?php
namespace Sustain\AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ActivityType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title','text', array('attr' => array('class' => 'text form-control', 'placeholder' => 'Title of your activity'),))
->add('description', 'ckeditor', array('config_name' => 'editor_simple',))
->add('objectives', 'entity', array('class' => 'AppBundle:Objective','property'=>'objective','query_builder' =>
function(\Sustain\AppBundle\Entity\ObjectiveRepository $er) use ($options) {
return $er->createQueryBuilder('o')
->orderBy('o.objective', 'ASC');
}, 'expanded'=>true,'multiple'=>true, 'label' => 'Select Objectives', 'attr' => array('class' => 'checkbox'),
))
->add('tags', 'entity', array('class' => 'AppBundle:Tag','property'=>'name','query_builder' =>
function(\Sustain\AppBundle\Entity\TagRepository $er) use ($options) {
return $er->createQueryBuilder('t')
->orderBy('t.name', 'ASC');
}, 'expanded'=>true,'multiple'=>true, 'label' => 'Select Labels', 'attr' => array('class' => 'checkbox'),
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Sustain\AppBundle\Entity\Activity'
));
}
/**
* @return string
*/
public function getName()
{
return 'sustain_appbundle_activity';
}
}
| rlbaltha/sustain | src/Sustain/AppBundle/Form/ActivityType.php | PHP | mit | 1,979 |
/**
* @file SpriteInterface.cpp
* @author Duncan Campbell
* @version 1.0
*
* @section LICENSE
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Duncan Campbell
*
* 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.
*
* @section DESCRIPTION
*
*
*/
#include "SpriteInterface.hpp"
| dacampbell/PseudoEngine | lib/Luna/src/SpriteInterface.cpp | C++ | mit | 1,312 |
module LightMobile::ApplicationHelper
include AgentHelpers::DetectorHelper
end
| kaspernj/light_mobile | app/helpers/light_mobile/application_helper.rb | Ruby | mit | 81 |
# Install NGINX
include_recipe 'nginx'
# Disable default site
nginx_site 'default' do
enable false
end
# Create web directory
directory node[:site][:webserver][:root] do
recursive true
owner node[:site][:user]
group node[:site][:group]
mode 00755
action :create
end
# Create site directory
directory "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/site" do
recursive true
owner node[:site][:user]
group node[:site][:group]
mode 00755
action :create
end
# Create logs
directory "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/logs" do
recursive true
owner node[:site][:user]
group node[:site][:group]
mode 0755
action :create
end
file "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/logs/access.log" do
owner node[:site][:user]
group node[:site][:group]
mode 0755
action :create
end
file "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/logs/error.log" do
owner node[:site][:user]
group node[:site][:group]
mode 0755
action :create
end
# Create server definition
template "/etc/nginx/sites-available/#{node[:site][:webserver][:sitename]}" do
source "server.erb"
owner "root"
group "root"
mode 0755
end
nginx_site "#{node[:site][:webserver][:sitename]}" do
enable true
notifies :reload, 'service[nginx]'
end
# Create 404 file
template "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/site/404.html" do
source "404.erb.html"
owner node[:site][:user]
group node[:site][:group]
mode 0755
end
# Create 500 file
template "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/site/50x.html" do
source "50x.erb.html"
owner node[:site][:user]
group node[:site][:group]
mode 0755
end
# # Create PHPInfo test file
# template "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/site/index.php" do
# source "test.php.erb"
# owner node[:site][:user]
# group node[:site][:group]
# mode 0755
# end | mattidupre/chef-nginx | recipes/webserver.rb | Ruby | mit | 2,049 |
package org.fluentjava.iwant.api.core;
import org.fluentjava.iwant.api.model.Path;
import org.fluentjava.iwant.api.model.Source;
import org.fluentjava.iwant.api.model.Target;
import org.fluentjava.iwant.apimocks.IwantTestCase;
public class SubPathTest extends IwantTestCase {
public void testParentAndRelativePath() {
Path parent = Source.underWsroot("parent");
SubPath s = new SubPath("s", parent, "rel");
assertSame(parent, s.parent());
assertEquals("rel", s.relativePath());
}
public void testIngredientsAndContentDescriptor() {
Path parent = Source.underWsroot("parent");
Path parent2 = Source.underWsroot("parent2");
SubPath s = new SubPath("s", parent, "rel");
SubPath s2 = new SubPath("s2", parent2, "rel2");
assertEquals("[parent]", s.ingredients().toString());
assertEquals("[parent2]", s2.ingredients().toString());
assertEquals(
"org.fluentjava.iwant.api.core.SubPath\n" + "i:parent:\n"
+ " parent\n" + "p:relativePath:\n" + " rel\n" + "",
s.contentDescriptor().toString());
assertEquals(
"org.fluentjava.iwant.api.core.SubPath\n" + "i:parent:\n"
+ " parent2\n" + "p:relativePath:\n" + " rel2\n" + "",
s2.contentDescriptor().toString());
}
public void testNonDirectorySubPathAsPath() throws Exception {
wsRootHasFile("parent/file", "file content");
Source parent = Source.underWsroot("parent");
Target target = new SubPath("s", parent, "file");
target.path(ctx);
assertEquals("file content", contentOfCached(target));
}
public void testDirectorySubPathAsPath() throws Exception {
wsRootHasFile("parent/subdir/subfile1", "subfile1 content");
wsRootHasFile("parent/subdir/subfile2", "subfile2 content");
Source parent = Source.underWsroot("parent");
Target target = new SubPath("s", parent, "subdir");
target.path(ctx);
assertEquals("subfile1 content", contentOfCached(target, "subfile1"));
assertEquals("subfile2 content", contentOfCached(target, "subfile2"));
}
/**
* SubPath used to copy but it was unnecessary. This tests no copying
* happens.
*/
public void testCachedPathPointsDirectlyUnderOriginal() {
Source source = Source.underWsroot("source");
assertEquals(wsRoot + "/source", ctx.cached(source).getAbsolutePath());
assertEquals(wsRoot + "/source/subdir",
ctx.cached(new SubPath("sourcesub", source, "subdir"))
.getAbsolutePath());
}
/**
* This is important since no copying happens: the parent must not be
* deleted when refreshing a subpath of it.
*/
public void testDeletionOfCachedFileIsNotRequested() {
assertFalse(new SubPath("s", Source.underWsroot("parent"), "sub")
.expectsCachedTargetMissingBeforeRefresh());
}
}
| wipu/iwant | essential/iwant-api-core/src/test/java/org/fluentjava/iwant/api/core/SubPathTest.java | Java | mit | 2,687 |
{
("use strict");
var HTMLElement = scope.wrappers.HTMLElement;
var mixin = scope.mixin;
var registerWrapper = scope.registerWrapper;
var unsafeUnwrap = scope.unsafeUnwrap;
var unwrap = scope.unwrap;
var wrap = scope.wrap;
var contentTable = new WeakMap();
var templateContentsOwnerTable = new WeakMap();
function getTemplateContentsOwner(doc) {
if (!doc.defaultView) return doc;
var d = templateContentsOwnerTable.get(doc);
if (!d) {
d = doc.implementation.createHTMLDocument("");
while (d.lastChild) {
d.removeChild(d.lastChild);
}
templateContentsOwnerTable.set(doc, d);
}
return d;
}
function extractContent(templateElement) {
var doc = getTemplateContentsOwner(templateElement.ownerDocument);
var df = unwrap(doc.createDocumentFragment());
var child;
while ((child = templateElement.firstChild)) {
df.appendChild(child);
}
return df;
}
var OriginalHTMLTemplateElement = window.HTMLTemplateElement;
function HTMLTemplateElement(node) {
HTMLElement.call(this, node);
if (!OriginalHTMLTemplateElement) {
var content = extractContent(node);
contentTable.set(this, wrap(content));
}
}
HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype);
mixin(HTMLTemplateElement.prototype, {
constructor: HTMLTemplateElement,
get content() {
if (OriginalHTMLTemplateElement) return wrap(unsafeUnwrap(this).content);
return contentTable.get(this);
}
});
if (OriginalHTMLTemplateElement)
registerWrapper(OriginalHTMLTemplateElement, HTMLTemplateElement);
scope.wrappers.HTMLTemplateElement = HTMLTemplateElement;
}
| stas-vilchik/bdd-ml | data/6744.js | JavaScript | mit | 1,705 |
// Copyright (c) The Perspex Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System.Linq;
using Perspex.Controls;
using Perspex.Controls.Presenters;
using Perspex.Controls.Primitives;
using Perspex.Controls.Templates;
using Perspex.VisualTree;
using Xunit;
namespace Perspex.Controls.UnitTests
{
public class ScrollViewerTests
{
[Fact]
public void Content_Is_Created()
{
var target = new ScrollViewer
{
Template = new FuncControlTemplate<ScrollViewer>(CreateTemplate),
Content = "Foo",
};
target.ApplyTemplate();
var presenter = target.GetTemplateChild<ScrollContentPresenter>("contentPresenter");
Assert.IsType<TextBlock>(presenter.Child);
}
[Fact]
public void ScrollViewer_In_Template_Sets_Child_TemplatedParent()
{
var target = new ContentControl
{
Template = new FuncControlTemplate<ContentControl>(CreateNestedTemplate),
Content = "Foo",
};
target.ApplyTemplate();
var presenter = target.GetVisualDescendents()
.OfType<ContentPresenter>()
.Single(x => x.Name == "this");
Assert.Equal(target, presenter.TemplatedParent);
}
private Control CreateTemplate(ScrollViewer control)
{
return new Grid
{
ColumnDefinitions = new ColumnDefinitions
{
new ColumnDefinition(1, GridUnitType.Star),
new ColumnDefinition(GridLength.Auto),
},
RowDefinitions = new RowDefinitions
{
new RowDefinition(1, GridUnitType.Star),
new RowDefinition(GridLength.Auto),
},
Children = new Controls
{
new ScrollContentPresenter
{
Name = "contentPresenter",
[~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty],
[~~ScrollContentPresenter.ExtentProperty] = control[~~ScrollViewer.ExtentProperty],
[~~ScrollContentPresenter.OffsetProperty] = control[~~ScrollViewer.OffsetProperty],
[~~ScrollContentPresenter.ViewportProperty] = control[~~ScrollViewer.ViewportProperty],
[~ScrollContentPresenter.CanScrollHorizontallyProperty] = control[~ScrollViewer.CanScrollHorizontallyProperty],
},
new ScrollBar
{
Name = "horizontalScrollBar",
Orientation = Orientation.Horizontal,
[~RangeBase.MaximumProperty] = control[~ScrollViewer.HorizontalScrollBarMaximumProperty],
[~~RangeBase.ValueProperty] = control[~~ScrollViewer.HorizontalScrollBarValueProperty],
[~ScrollBar.ViewportSizeProperty] = control[~ScrollViewer.HorizontalScrollBarViewportSizeProperty],
[~ScrollBar.VisibilityProperty] = control[~ScrollViewer.HorizontalScrollBarVisibilityProperty],
[Grid.RowProperty] = 1,
},
new ScrollBar
{
Name = "verticalScrollBar",
Orientation = Orientation.Vertical,
[~RangeBase.MaximumProperty] = control[~ScrollViewer.VerticalScrollBarMaximumProperty],
[~~RangeBase.ValueProperty] = control[~~ScrollViewer.VerticalScrollBarValueProperty],
[~ScrollBar.ViewportSizeProperty] = control[~ScrollViewer.VerticalScrollBarViewportSizeProperty],
[~ScrollBar.VisibilityProperty] = control[~ScrollViewer.VerticalScrollBarVisibilityProperty],
[Grid.ColumnProperty] = 1,
},
},
};
}
private Control CreateNestedTemplate(ContentControl control)
{
return new ScrollViewer
{
Template = new FuncControlTemplate<ScrollViewer>(CreateTemplate),
Content = new ContentPresenter
{
Name = "this"
}
};
}
}
} | kekekeks/Perspex | tests/Perspex.Controls.UnitTests/ScrollViewerTests.cs | C# | mit | 4,573 |
using System.Web;
using System.Web.Mvc;
namespace ForumSystem.WebApp
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| Zakkgard/ASP.NET-MVC | ForumSystem/Source/Web/ForumSystem.WebApp/App_Start/FilterConfig.cs | C# | mit | 273 |
package golog
import . "fmt"
import . "github.com/mndrix/golog/term"
import . "github.com/mndrix/golog/util"
import "bytes"
import "github.com/mndrix/ps"
// Database is an immutable Prolog database. All write operations on the
// database produce a new database without affecting the previous one.
// A database is a mapping from predicate indicators (foo/3) to clauses.
// The database may or may not implement indexing. It's unusual to
// interact with databases directly. One usually calls methods on Machine
// instead.
type Database interface {
// Asserta adds a term to the database at the start of any existing
// terms with the same name and arity.
Asserta(Term) Database
// Assertz adds a term to the database at the end of any existing
// terms with the same name and arity.
Assertz(Term) Database
// Candidates() returns a list of clauses that might unify with a term.
// Returns error if no predicate with appropriate
// name and arity has been defined.
Candidates(Term) ([]Term, error)
// Candidates_() is like Candidates() but panics on error.
Candidates_(Term) []Term
// ClauseCount returns the number of clauses in the database
ClauseCount() int
// String returns a string representation of the entire database
String() string
}
// NewDatabase returns a new, empty database
func NewDatabase() Database {
var db mapDb
db.clauseCount = 0
db.predicates = ps.NewMap()
return &db
}
type mapDb struct {
clauseCount int // number of clauses in the database
predicates ps.Map // term indicator => *clauses
}
func (self *mapDb) Asserta(term Term) Database {
return self.assert('a', term)
}
func (self *mapDb) Assertz(term Term) Database {
return self.assert('z', term)
}
func (self *mapDb) assert(side rune, term Term) Database {
var newMapDb mapDb
var cs *clauses
// find the indicator under which this term is classified
indicator := term.Indicator()
if IsClause(term) {
// ':-' uses the indicator of its head term
indicator = Head(term).Indicator()
}
oldClauses, ok := self.predicates.Lookup(indicator)
if ok { // clauses exist for this predicate
switch side {
case 'a':
cs = oldClauses.(*clauses).cons(term)
case 'z':
cs = oldClauses.(*clauses).snoc(term)
}
} else { // brand new predicate
cs = newClauses().snoc(term)
}
newMapDb.clauseCount = self.clauseCount + 1
newMapDb.predicates = self.predicates.Set(indicator, cs)
return &newMapDb
}
func (self *mapDb) Candidates_(t Term) []Term {
ts, err := self.Candidates(t)
if err != nil {
panic(err)
}
return ts
}
func (self *mapDb) Candidates(t Term) ([]Term, error) {
indicator := t.Indicator()
cs, ok := self.predicates.Lookup(indicator)
if !ok { // this predicate hasn't been defined
return nil, Errorf("Undefined predicate: %s", indicator)
}
// quick return for an atom term
if !IsCompound(t) {
return cs.(*clauses).all(), nil
}
// ignore clauses that can't possibly unify with our term
candidates := make([]Term, 0)
cs.(*clauses).forEach(func(clause Term) {
if !IsCompound(clause) {
Debugf(" ... discarding. Not compound term\n")
return
}
head := clause
if IsClause(clause) {
head = Head(clause)
}
if t.(*Compound).MightUnify(head.(*Compound)) {
Debugf(" ... adding to candidates: %s\n", clause)
candidates = append(candidates, clause)
}
})
Debugf(" final candidates = %s\n", candidates)
return candidates, nil
}
func (self *mapDb) ClauseCount() int {
return self.clauseCount
}
func (self *mapDb) String() string {
var buf bytes.Buffer
keys := self.predicates.Keys()
for _, key := range keys {
cs, _ := self.predicates.Lookup(key)
cs.(*clauses).forEach(func(t Term) { Fprintf(&buf, "%s.\n", t) })
}
return buf.String()
}
| bransorem/golog | database.go | GO | mit | 3,740 |
from cereal import car
from opendbc.can.packer import CANPacker
from selfdrive.car.mazda import mazdacan
from selfdrive.car.mazda.values import CarControllerParams, Buttons
from selfdrive.car import apply_std_steer_torque_limits
VisualAlert = car.CarControl.HUDControl.VisualAlert
class CarController():
def __init__(self, dbc_name, CP, VM):
self.apply_steer_last = 0
self.packer = CANPacker(dbc_name)
self.steer_rate_limited = False
self.brake_counter = 0
def update(self, c, CS, frame):
can_sends = []
apply_steer = 0
self.steer_rate_limited = False
if c.active:
# calculate steer and also set limits due to driver torque
new_steer = int(round(c.actuators.steer * CarControllerParams.STEER_MAX))
apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last,
CS.out.steeringTorque, CarControllerParams)
self.steer_rate_limited = new_steer != apply_steer
if CS.out.standstill and frame % 5 == 0:
# Mazda Stop and Go requires a RES button (or gas) press if the car stops more than 3 seconds
# Send Resume button at 20hz if we're engaged at standstill to support full stop and go!
# TODO: improve the resume trigger logic by looking at actual radar data
can_sends.append(mazdacan.create_button_cmd(self.packer, CS.CP.carFingerprint, CS.crz_btns_counter, Buttons.RESUME))
if c.cruiseControl.cancel or (CS.out.cruiseState.enabled and not c.enabled):
# If brake is pressed, let us wait >70ms before trying to disable crz to avoid
# a race condition with the stock system, where the second cancel from openpilot
# will disable the crz 'main on'. crz ctrl msg runs at 50hz. 70ms allows us to
# read 3 messages and most likely sync state before we attempt cancel.
self.brake_counter = self.brake_counter + 1
if frame % 10 == 0 and not (CS.out.brakePressed and self.brake_counter < 7):
# Cancel Stock ACC if it's enabled while OP is disengaged
# Send at a rate of 10hz until we sync with stock ACC state
can_sends.append(mazdacan.create_button_cmd(self.packer, CS.CP.carFingerprint, CS.crz_btns_counter, Buttons.CANCEL))
else:
self.brake_counter = 0
self.apply_steer_last = apply_steer
# send HUD alerts
if frame % 50 == 0:
ldw = c.hudControl.visualAlert == VisualAlert.ldw
steer_required = c.hudControl.visualAlert == VisualAlert.steerRequired
# TODO: find a way to silence audible warnings so we can add more hud alerts
steer_required = steer_required and CS.lkas_allowed_speed
can_sends.append(mazdacan.create_alert_command(self.packer, CS.cam_laneinfo, ldw, steer_required))
# send steering command
can_sends.append(mazdacan.create_steering_control(self.packer, CS.CP.carFingerprint,
frame, apply_steer, CS.cam_lkas))
new_actuators = c.actuators.copy()
new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX
return new_actuators, can_sends
| commaai/openpilot | selfdrive/car/mazda/carcontroller.py | Python | mit | 3,112 |
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { RelationComponent } from './relation/relation.component';
const routes: Routes = [{ path: 'relation', component: RelationComponent }];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class DataVRoutingModule {}
| cipchk/ng-alain | src/app/routes/data-v/data-v-routing.module.ts | TypeScript | mit | 365 |
<?php namespace SleepingOwl\Html;
use Illuminate\Html\HtmlBuilder as IlluminateHtmlBuilder;
use SleepingOwl\Admin\Models\Form\FormItem;
use SleepingOwl\DateFormatter\DateFormatter;
use SleepingOwl\Admin\Admin;
use SleepingOwl\Admin\AssetManager\AssetManager;
use Session;
/**
* Class HtmlBuilder
*/
class HtmlBuilder extends IlluminateHtmlBuilder
{
/**
* @var string[]
*/
protected $tagsWithoutContent = [
'input',
'img',
'br',
'hr'
];
/**
* @param $tag
* @param array $attributes
* @param string $content
* @return string
*/
public function tag($tag, $attributes = [], $content = null)
{
return $this->getOpeningTag($tag, $attributes) . $content . $this->getClosingTag($tag);
}
/**
* @param string $key
* @param string $value
* @return string
*/
protected function attributeElement($key, $value)
{
if (is_array($value))
{
$value = implode(' ', $value);
}
return parent::attributeElement($key, $value);
}
/**
* @param $tag
* @param array $attributes
* @return string
*/
protected function getOpeningTag($tag, array $attributes)
{
$result = '<' . $tag;
if ( ! empty($attributes))
{
$result .= $this->attributes($attributes);
}
if ($this->isTagNeedsClosingTag($tag))
{
$result .= '>';
}
return $result;
}
/**
* @param $tag
* @return string
*/
protected function getClosingTag($tag)
{
$closingTag = '/>';
if ($this->isTagNeedsClosingTag($tag))
{
$closingTag = '</' . $tag . '>';
}
return $closingTag;
}
/**
* @param $tag
* @return bool
*/
protected function isTagNeedsClosingTag($tag)
{
return ! in_array($tag, $this->tagsWithoutContent);
}
/**
* This method will generate input type text field
*
* @param $name
* @param string $label
* @param string $value
* @param array $options
* @return $this
*/
public static function text($name, $label = '', $value = '', $options = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/input_text')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('error', self::getError($name));
}
public static function textWithActions($name, $label = '', $value = '', $options = [], $actions = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/input_text')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('actions', $actions)
->with('error', self::getError($name));
}
/**
* @param $name
* @param string $label
* @param int $value
* @param array $options
* @return $this
*/
public static function number($name, $label = '', $value = 0, $options = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
if (empty($options['id']))
$options['id'] = uniqid();
return view('admin::_partials/form_elements/input_number')
->with('value', $value)
->with('name', $name)
->with('label', $label)
->with('options', $options)
->with('error', self::getError($name));
}
/**
* This method will generate input email
*
* @param $name
* @param string $label
* @param string $value
* @param array $options
* @return $this
*/
public static function emailField($name, $label = '', $value = '', $options = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/input_email')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('error', self::getError($name));
}
public static function emailGroupField($name, $label = '', $value = '', $options = [])
{
$values = explode(',', $value);
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/tag-it.js'));
AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/jquery.tagit.css'));
if (empty($options['id']))
$options['id'] = uniqid();
return view('admin::_partials/form_elements/input_email_group')
->with('name', $name)
->with('label', $label)
->with('values', $values)
->with('options', $options)
->with('error', self::getError($name));
}
/**
* This method will generate input type password field
*
* @param $name
* @param string $label
* @param string $value
* @param array $options
* @return $this
*/
public static function password($name, $label = '', $value = '', $options = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/input_password')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('error', self::getError($name));
}
/**
* This method will generate input type text field
*
* @param $name
* @param string $label
* @param string $value
* @param array $options
* @return $this
*/
public static function price($name, $label = '', $value = '', $options = [], $currency = '$')
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/input_price')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('currency', $currency)
->with('error', self::getError($name));
}
/**
* This method will generate input color
*
* @param $name
* @param string $label
* @param string $value
* @param array $options
* @return $this
*/
public static function color($name, $label = '', $value = '', $options = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/bootstrap-colorpicker.js'));
AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/bootstrap-colorpicker.min.css'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
if (empty($options['id'])) {
$options['id'] = uniqid();
}
return view('admin::_partials/form_elements/input_color')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('error', self::getError($name));
}
/**
* @param $name
* @param $label
* @param null $value
* @param array $options
* @return $this
*/
public static function radio($name, $label, $value = null, array $options = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/radio')
->with('name', $name)
->with('label', $label)
->with('value', (is_null($value)) ? 1 : $value)
->with('options', $options)
->with('error', self::getError($name));
}
/**
* @param $name string
* @param $label string
* @param null $value string
* @param array $options
* @param $addonValue string
* @return $this
*/
public static function radioAddon($name, $label, $value = null, array $options = [], $addonValue)
{
return view('admin::_partials/form_elements/radio_addon')
->with('name', $name)
->with('label', $label)
->with('value', (is_null($value)) ? 1 : $value)
->with('options', $options)
->with('addonValue', $addonValue)
->with('error', self::getError($name));
}
/**
* @param $name
* @param $label
* @param null $value
* @param array $options
* @return $this
*/
public static function checkbox($name, $label, $value = null, array $options = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/checkbox')
->with('name', $name)
->with('label', $label)
->with('value', (is_null($value)) ? 1 : $value)
->with('options', $options)
->with('error', self::getError($name));
}
/**
* @param $name string
* @param $label string
* @param null $value string
* @param array $options
* @param $addonValue string
* @return $this
*/
public static function checkboxAddon($name, $label, $value = null, array $options = [], $addonValue)
{
return view('admin::_partials/form_elements/checkbox_addon')
->with('name', $name)
->with('label', $label)
->with('value', (is_null($value)) ? 1 : $value)
->with('options', $options)
->with('addonValue', $addonValue)
->with('error', self::getError($name));
}
/**
* @param $name
* @param $label
* @param array $list
* @param null $value
* @param array $options
* @return $this
*/
public static function select($name, $label, array $list = [], $value = null, array $options = [])
{
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/select')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('list', $list)
->with('options', $options)
->with('id', (!empty($options['id']) ? $options['id'] : $name))
->with('error', self::getError($name));
}
public static function date($name, $label, $value = null, array $options = [], $dateFormat = DateFormatter::SHORT,
$timeFormat = DateFormatter::NONE)
{
$value = DateFormatter::format($value, $dateFormat, $timeFormat, 'dd.MM.y');
if (empty($options['id']))
$options['id'] = uniqid();
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/bootstrap-datepicker.js'));
AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/datepicker.css'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/date')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('format', $dateFormat)
->with('id', $options['id'])
->with('error', self::getError($name));
}
public static function datetime($name, $label, $value = null, array $options = [], $rule = [], $dateFormat = DateFormatter::SHORT, $timeFormat = DateFormatter::SHORT)
{
if ($value) {
$value = DateFormatter::format($value, $dateFormat, $timeFormat, 'dd.MM.y H:mm');
}
if (empty($options['id'])) {
$options['id'] = uniqid();
}
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/moment.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/bootstrap-datetimepicker.min.js'));
AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/bootstrap-datetimepicker.min.css'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/view_filters/datetime')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('date_format', $dateFormat)
->with('time_format', $timeFormat)
->with('id', $options['id'])
->with('rule', $rule)
->with('error', self::getError($name));
}
public static function textarea($name, $label, $value = null, array $options = [])
{
$options['id'] = uniqid();
if (!empty($options['data-editor'])) {
switch ($options['data-editor']) {
case FormItem\Textarea::EDITOR_WYSIHTML:
AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/bootstrap-wysihtml5.css'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/wysihtml5-0.3.0.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/bootstrap-wysihtml5.js'));
break;
}
}
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js'));
AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js'));
return view('admin::_partials/form_elements/textarea')
->with('name', $name)
->with('label', $label)
->with('value', $value)
->with('options', $options)
->with('id', $options['id'])
->with('error', self::getError($name));
}
/**
* Returns error by key
*
* @param $key
* @return string
*/
public static function getError($key)
{
$errors = Session::get('errors');
return $errors ? $errors->has($key) ? $errors->first() : '' : '';
}
} | procoders/admin | src/SleepingOwl/Html/HtmlBuilder.php | PHP | mit | 15,241 |
package cz.pfreiberg.knparser.exporter.oracledatabase;
import java.sql.SQLException;
import java.util.List;
import cz.pfreiberg.knparser.ConnectionParameters;
import cz.pfreiberg.knparser.domain.jednotky.TJednotek;
import cz.pfreiberg.knparser.util.VfkUtil;
public class TJednotekOracleDatabaseJdbcExporter extends
CisOracleDatabaseJdbcExporter {
private final static String name = "T_JEDNOTEK";
private final static String insert = "INSERT INTO " + name + " VALUES"
+ "(?,?,?,?,?)";
public TJednotekOracleDatabaseJdbcExporter(List<TJednotek> tJednotek,
ConnectionParameters connectionParameters) {
super(connectionParameters, name, insert);
prepareStatement(tJednotek, name);
}
@Override
public void insert(String table, Object rawRecord, boolean isRecord)
throws SQLException {
TJednotek record = (TJednotek) rawRecord;
psInsert.setObject(1, record.getKod());
psInsert.setObject(2, record.getNazev());
psInsert.setObject(3,
VfkUtil.convertToDatabaseDate(record.getPlatnostOd()));
psInsert.setObject(4,
VfkUtil.convertToDatabaseDate(record.getPlatnostDo()));
psInsert.setObject(5, record.getZkratka());
}
}
| pfreiberg/knparser | src/main/java/cz/pfreiberg/knparser/exporter/oracledatabase/TJednotekOracleDatabaseJdbcExporter.java | Java | mit | 1,193 |
using System.Collections.Generic;
using System.Text;
namespace DB2DataContextDriver.CodeGen
{
public class ClassDefinition
{
public string Name { get; set; }
public string Inherits { get; set; }
public List<string> Methods { get; set; }
public List<PropertyDefinition> Properties { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
if (string.IsNullOrWhiteSpace(Inherits))
{
sb.AppendFormat("public class {0} {{\n", Name);
}
else
{
sb.AppendFormat("public class {0} : {1} {{\n", Name, Inherits);
}
if (Methods != null)
{
foreach (var method in Methods)
{
sb.AppendLine("\t" + method.ToString());
}
}
if (Properties != null)
{
foreach (var property in Properties)
{
sb.AppendLine("\t" + property.ToString());
}
}
return sb.Append("}\n").ToString();
}
}
}
| treytomes/DB2LinqPadDriver | DB2DataContextDriver/CodeGen/ClassDefinition.cs | C# | mit | 941 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DigitAsWord")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DigitAsWord")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("653800a4-096d-4786-abda-996e996d6ba7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| DJBuro/Telerik | C#1/ConditionalStatements/DigitAsWord/Properties/AssemblyInfo.cs | C# | mit | 1,398 |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using PholioVisualisation.PholioObjects;
namespace PholioVisualisation.ServicesTest
{
[TestClass]
public class EntitiesControllerEndPointTest
{
[TestMethod]
public void TestGetNearestNeighbourTypes()
{
byte[] data = GetData("nearest_neighbour_types");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetNearestNeighbourType()
{
byte[] data = GetData("nearest_neighbour_type?neighbour_type_id=1");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetValueNotes()
{
byte[] data = GetData("value_notes");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetTrendMarkers()
{
byte[] data = GetData("recent_trends");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetSexes()
{
byte[] data = GetData("sexes");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetAges()
{
byte[] data = GetData("ages");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetAge()
{
byte[] data = GetData("age?id=" + AgeIds.From0To4);
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetCategoryTypes()
{
byte[] data = GetData("category_types");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetPolarities()
{
byte[] data = GetData("polarities");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetConfidenceIntervalMethods()
{
byte[] data = GetData("confidence_interval_methods");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetConfidenceIntervalMethod()
{
byte[] data = GetData("confidence_interval_method?id=" + ConfidenceIntervalMethodIds.Byars);
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetComparatorMethods()
{
byte[] data = GetData("comparator_methods");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetComparatorMethod()
{
byte[] data = GetData("comparator_method?id=" +
ComparatorMethodIds.SingleOverlappingCIsForOneCiLevel);
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetComparators()
{
byte[] data = GetData("comparators");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetComparator()
{
byte[] data = GetData("comparator?id=" +
ComparatorIds.Subnational);
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetComparatorSignificances()
{
byte[] data = GetData("comparator_significances?polarity_id=" +
PolarityIds.BlueOrangeBlue);
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetCategories()
{
byte[] data = GetData("categories?" +
"category_type_id=" + CategoryTypeIds.EthnicGroups5);
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetUnits()
{
byte[] data = GetData("units");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetYearTypes()
{
byte[] data = GetData("year_types");
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetYearType()
{
byte[] data = GetData("year_type?id=" + YearTypeIds.Academic);
TestHelper.IsData(data);
}
[TestMethod]
public void TestGetValueTypes()
{
byte[] data = GetData("value_types");
TestHelper.IsData(data);
}
public byte[] GetData(string path)
{
return DataControllerEndPointTest.GetData(path);
}
}
}
| PublicHealthEngland/fingertips-open | PholioVisualisationWS/ServicesTest/EntitiesControllerEndPointTest.cs | C# | mit | 4,435 |
import pprint
from cytoolz import (
assoc,
concatv,
partial,
pipe,
)
from semantic_version import (
Spec,
)
from eth_utils import (
add_0x_prefix,
to_dict,
to_tuple,
)
from solc import (
get_solc_version,
compile_standard,
)
from solc.exceptions import (
ContractsNotFound,
)
from populus.utils.compile import (
load_json_if_string,
normalize_contract_metadata,
)
from populus.utils.linking import (
normalize_standard_json_link_references,
)
from populus.utils.mappings import (
has_nested_key,
get_nested_key,
set_nested_key,
)
from .base import (
BaseCompilerBackend,
)
@to_dict
def build_standard_input_sources(source_file_paths):
for file_path in source_file_paths:
with open(file_path) as source_file:
yield file_path, {'content': source_file.read()}
@to_dict
def normalize_standard_json_contract_data(contract_data):
if 'metadata' in contract_data:
yield 'metadata', normalize_contract_metadata(contract_data['metadata'])
if 'evm' in contract_data:
evm_data = contract_data['evm']
if 'bytecode' in evm_data:
yield 'bytecode', add_0x_prefix(evm_data['bytecode'].get('object', ''))
if 'linkReferences' in evm_data['bytecode']:
yield 'linkrefs', normalize_standard_json_link_references(
evm_data['bytecode']['linkReferences'],
)
if 'deployedBytecode' in evm_data:
yield 'bytecode_runtime', add_0x_prefix(evm_data['deployedBytecode'].get('object', ''))
if 'linkReferences' in evm_data['deployedBytecode']:
yield 'linkrefs_runtime', normalize_standard_json_link_references(
evm_data['deployedBytecode']['linkReferences'],
)
if 'abi' in contract_data:
yield 'abi', load_json_if_string(contract_data['abi'])
if 'userdoc' in contract_data:
yield 'userdoc', load_json_if_string(contract_data['userdoc'])
if 'devdoc' in contract_data:
yield 'devdoc', load_json_if_string(contract_data['devdoc'])
@to_tuple
def normalize_compilation_result(compilation_result):
"""
Take the result from the --standard-json compilation and flatten it into an
iterable of contract data dictionaries.
"""
for source_path, file_contracts in compilation_result['contracts'].items():
for contract_name, raw_contract_data in file_contracts.items():
contract_data = normalize_standard_json_contract_data(raw_contract_data)
yield pipe(
contract_data,
partial(assoc, key='source_path', value=source_path),
partial(assoc, key='name', value=contract_name),
)
REQUIRED_OUTPUT_SELECTION = [
'abi',
'metadata',
'evm.bytecode',
'evm.bytecode.object',
'evm.bytecode.linkReferences',
'evm.deployedBytecode',
'evm.deployedBytecode.object',
'evm.deployedBytecode.linkReferences',
]
OUTPUT_SELECTION_KEY = 'settings.outputSelection.*.*'
class SolcStandardJSONBackend(BaseCompilerBackend):
project_source_glob = ('*.sol', )
test_source_glob = ('Test*.sol', )
def __init__(self, *args, **kwargs):
if get_solc_version() not in Spec('>=0.4.11'):
raise OSError(
"The 'SolcStandardJSONBackend can only be used with solc "
"versions >=0.4.11. The SolcCombinedJSONBackend should be used "
"for all versions <=0.4.8"
)
super(SolcStandardJSONBackend, self).__init__(*args, **kwargs)
def get_compiled_contracts(self, source_file_paths, import_remappings):
self.logger.debug("Import remappings: %s", import_remappings)
self.logger.debug("Compiler Settings PRE: %s", pprint.pformat(self.compiler_settings))
# DEBUG
self.compiler_settings['output_values'] = []
self.logger.debug("Compiler Settings POST: %s", pprint.pformat(self.compiler_settings))
if 'remappings' in self.compiler_settings and import_remappings is not None:
self.logger.warn("Import remappings setting will by overridden by backend settings")
sources = build_standard_input_sources(source_file_paths)
std_input = {
'language': 'Solidity',
'sources': sources,
'settings': {
'remappings': import_remappings,
'outputSelection': {
'*': {
'*': REQUIRED_OUTPUT_SELECTION
}
}
}
}
# solc command line options as passed to solc_wrapper()
# https://github.com/ethereum/py-solc/blob/3a6de359dc31375df46418e6ffd7f45ab9567287/solc/wrapper.py#L20
command_line_options = self.compiler_settings.get("command_line_options", {})
# Get Solidity Input Description settings section
# http://solidity.readthedocs.io/en/develop/using-the-compiler.html#input-description
std_input_settings = self.compiler_settings.get("stdin", {})
std_input['settings'].update(std_input_settings)
# Make sure the output selection has all of the required output values.
if has_nested_key(std_input, OUTPUT_SELECTION_KEY):
current_selection = get_nested_key(std_input, OUTPUT_SELECTION_KEY)
output_selection = list(set(concatv(current_selection, REQUIRED_OUTPUT_SELECTION)))
else:
output_selection = REQUIRED_OUTPUT_SELECTION
set_nested_key(std_input, OUTPUT_SELECTION_KEY, output_selection)
self.logger.debug("std_input sections: %s", std_input.keys())
self.logger.debug("Input Description JSON settings are: %s", std_input["settings"])
self.logger.debug("Command line options are: %s", command_line_options)
try:
compilation_result = compile_standard(std_input, **command_line_options)
except ContractsNotFound:
return {}
compiled_contracts = normalize_compilation_result(compilation_result)
return compiled_contracts
| pipermerriam/populus | populus/compilation/backends/solc_standard_json.py | Python | mit | 6,140 |
import React from 'react';
import moment from 'moment';
import { storiesOf } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import isInclusivelyAfterDay from '../src/utils/isInclusivelyAfterDay';
import isSameDay from '../src/utils/isSameDay';
import SingleDatePickerWrapper from '../examples/SingleDatePickerWrapper';
const datesList = [
moment(),
moment().add(1, 'days'),
moment().add(3, 'days'),
moment().add(9, 'days'),
moment().add(10, 'days'),
moment().add(11, 'days'),
moment().add(12, 'days'),
moment().add(13, 'days'),
];
storiesOf('SDP - Day Props', module)
.add('default', withInfo()(() => (
<SingleDatePickerWrapper autoFocus />
)))
.add('allows all days, including past days', withInfo()(() => (
<SingleDatePickerWrapper
isOutsideRange={() => false}
autoFocus
/>
)))
.add('allows next two weeks only', withInfo()(() => (
<SingleDatePickerWrapper
isOutsideRange={day =>
!isInclusivelyAfterDay(day, moment()) ||
isInclusivelyAfterDay(day, moment().add(2, 'weeks'))
}
autoFocus
/>
)))
.add('with some blocked dates', withInfo()(() => (
<SingleDatePickerWrapper
isDayBlocked={day1 => datesList.some(day2 => isSameDay(day1, day2))}
autoFocus
/>
)))
.add('with some highlighted dates', withInfo()(() => (
<SingleDatePickerWrapper
isDayHighlighted={day1 => datesList.some(day2 => isSameDay(day1, day2))}
autoFocus
/>
)))
.add('blocks fridays', withInfo()(() => (
<SingleDatePickerWrapper
isDayBlocked={day => moment.weekdays(day.weekday()) === 'Friday'}
autoFocus
/>
)))
.add('with custom daily details', withInfo()(() => (
<SingleDatePickerWrapper
numberOfMonths={1}
renderDayContents={day => day.format('ddd')}
autoFocus
/>
)));
| airbnb/react-dates | stories/SingleDatePicker_day.js | JavaScript | mit | 1,865 |
/**
*
*/
package com.forgedui.model.titanium;
import com.forgedui.model.Element;
import com.forgedui.model.titanium.annotations.Composite;
import com.forgedui.model.titanium.annotations.EnumValues;
import com.forgedui.model.titanium.annotations.Review;
import com.forgedui.model.titanium.annotations.SupportedPlatform;
import com.forgedui.model.titanium.annotations.Unmapped;
/**
* @AutoGenerated
*/
public class Window extends TitaniumUIContainer {
/**
*
*/
@Unmapped
private static final long serialVersionUID = 1L;
@Unmapped
public static final String ORIENTATION_MODE_FACE_DOWN = "Titanium.UI.FACE_DOWN";
@Unmapped
public static final String ORIENTATION_MODE_FACE_UP = "Titanium.UI.FACE_UP";
@Unmapped
public static final String ORIENTATION_MODE_PORTRAIT = "Titanium.UI.PORTRAIT";
@Unmapped
public static final String ORIENTATION_MODE_UPSIDE_PORTRAIT = "Titanium.UI.UPSIDE_PORTRAIT";
@Unmapped
public static final String ORIENTATION_MODE_UNKNOWN = "Titanium.UI.UNKNOWN";
@Unmapped
public static final String ORIENTATION_MODE_LANDSCAPE_LEFT = "Titanium.UI.LANDSCAPE_LEFT";
@Unmapped
public static final String ORIENTATION_MODE_LANDSCAPE_RIGHT = "Titanium.UI.LANDSCAPE_RIGHT";
@Unmapped
public static final String MODAL_PROP = "modal";
@Unmapped
public static final String TITLE_BAR_PROP = "titleBar";
@Unmapped
public static final String TABS_HIDDEN_PROP = "tabsGroupHidden";
@Unmapped
public static final String FULL_SCREEN_PROP = "fullScreen";
@Unmapped
public static final String ORIENTATION_MODES_PROP = "orientationModes";
private Boolean exitOnClose;
private Boolean tabBarHidden;
private Boolean navBarHidden;
@Review(note = "What is the highest class in hierarchy for this")
@SupportedPlatform(platforms = "iphone")
private TitaniumUIBoundedElement[] toolbar;
private Boolean translucent;
private String url;
@EnumValues(values = { "Titanium.UI.FACE_DOWN", "Titanium.UI.FACE_UP",
"Titanium.UI.LANDSCAPE_LEFT", "Titanium.UI.LANDSCAPE_RIGHT",
"Titanium.UI.PORTRAIT", "Titanium.UI.UNKNOWN",
"Titanium.UI.UPSIDE_PORTRAIT" }, type = "integer")
private String[] orientationModes;
private Boolean fullscreen;
@Composite
private TitleBar titleBar;
private Boolean modal;
public Window() {
this.type = "Titanium.UI.Window";
}
public Boolean getExitOnClose() {
return exitOnClose;
}
public void setExitOnClose(Boolean exitOnClose) {
this.exitOnClose = exitOnClose;
}
public Boolean getTabBarHidden() {
return tabBarHidden;
}
public void setTabBarHidden(Boolean tabBarHidden) {
Boolean old = this.tabBarHidden;
this.tabBarHidden = tabBarHidden;
listeners.firePropertyChange(TABS_HIDDEN_PROP, old, tabBarHidden);
}
public Boolean getNavBarHidden() {
return navBarHidden;
}
public void setNavBarHidden(Boolean navBarHidden) {
this.navBarHidden = navBarHidden;
}
public TitaniumUIBoundedElement[] getToolbar() {
return toolbar;
}
public void setToolbar(TitaniumUIBoundedElement[] toolbar) {
TitaniumUIBoundedElement[] oldToolbar = toolbar;
if (toolbar != null){
for (TitaniumUIBoundedElement titaniumUIElement : toolbar) {
titaniumUIElement.setParent(null);
}
}
this.toolbar = oldToolbar;
if (toolbar != null){
for (TitaniumUIBoundedElement titaniumUIElement : toolbar) {
titaniumUIElement.setParent(this);
}
}
listeners.firePropertyChange("Window.toolbar", oldToolbar, oldToolbar);
}
public Boolean getTranslucent() {
return translucent;
}
public void setTranslucent(Boolean translucent) {
this.translucent = translucent;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String[] getOrientationModes() {
return orientationModes;
}
public void setOrientationModes(String[] orientationModes) {
this.orientationModes = orientationModes;
}
public Boolean getFullscreen() {
return fullscreen;
}
public void setFullscreen(Boolean fullscreen) {
Boolean old = this.fullscreen;
this.fullscreen = fullscreen;
listeners.firePropertyChange(FULL_SCREEN_PROP, old, fullscreen);
}
public Boolean getModal() {
return modal;
}
public void setModal(Boolean modal) {
Boolean oldValue = this.modal;
this.modal = modal;
listeners.firePropertyChange(MODAL_PROP, oldValue, modal);
}
public void setTitleBar(TitleBar titleBar) {
TitleBar oldTitleBar = this.titleBar;
this.titleBar = titleBar;
fireElementPropertySet(TITLE_BAR_PROP, oldTitleBar, titleBar);
}
public TitleBar getTitleBar() {
return titleBar;
}
@Override
public void setParent(Element parent) {
this.parent = parent;
if (parent != null && name == null){
String fileName = getDiagram().getFile().getName();
if (fileName.indexOf('.') >= 0){
fileName = fileName.substring(0, fileName.indexOf('.'));
}
setName(fileName);
}
}
} | ShoukriKattan/ForgedUI-Eclipse | com.forgedui.core/src/com/forgedui/model/titanium/Window.java | Java | mit | 4,862 |
import datetime
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from ..tasks import trigger_instance
from . import app_settings
from .enums import StateEnum
from .models import Call
@csrf_exempt
@require_POST
def twiml_callback(request, ident):
call = get_object_or_404(Call, ident=ident)
return render(request, 'reminders/calls/twiml_callback.xml', {
'call': call,
}, content_type='text/xml')
@csrf_exempt
@require_POST
def gather_callback(request, ident):
call = get_object_or_404(Call, ident=ident)
# Mark if the user actually pressed a button
if request.POST.get('Digits'):
call.button_pressed = datetime.datetime.utcnow()
call.save(update_fields=('button_pressed',))
return render(
request,
'reminders/calls/gather_callback.xml',
content_type='text/xml'
)
@csrf_exempt
@require_POST
def status_callback(request, ident):
"""
https://www.twilio.com/help/faq/voice/what-do-the-call-statuses-mean
Example POST data:
SipResponseCode: 500
ApiVersion: 2010-04-01
AccountSid: AC7d6b676d2a17527a71a2bb41301b5e6f
Duration: 0
Direction: outbound-api
CallStatus: busy
SequenceNumber: 0
Timestamp: Mon, 16 Nov 2015 16:10:53 +0000
Caller: +441143032046
CallDuration: 0
To: +447753237119
CallbackSource: call-progress-events
Called: +447751231511
From: +441143032046
CallSid: CA19fd373bd82b81b602c75d1ddc7745e7
"""
call = get_object_or_404(Call, ident=ident)
try:
call.state = {
'queued': StateEnum.dialing,
'initiated': StateEnum.dialing,
'ringing': StateEnum.dialing,
'in-progress': StateEnum.answered,
'completed': StateEnum.answered,
'busy': StateEnum.busy,
'no-answer': StateEnum.no_answer,
'cancelled': StateEnum.failed,
'failed': StateEnum.failed,
}[request.POST['CallStatus']]
except KeyError:
call.state = StateEnum.unknown
call.state_updated = datetime.datetime.utcnow()
call.save(update_fields=('state', 'state_updated'))
if not call.button_pressed \
and call.instance.calls.count() < app_settings.RETRY_COUNT:
trigger_instance.apply_async(
args=(call.instance_id,),
countdown=app_settings.RETRY_AFTER_SECONDS,
)
return HttpResponse('')
| takeyourmeds/takeyourmeds-web | takeyourmeds/reminders/reminders_calls/views.py | Python | mit | 2,634 |
package de.kumpelblase2.jhipsterwebsocket.domain.util;
import java.io.IOException;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* Custom Jackson serializer for displaying Joda DateTime objects.
*/
public class CustomDateTimeSerializer extends JsonSerializer<DateTime> {
private static DateTimeFormatter formatter = DateTimeFormat
.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
@Override
public void serialize(DateTime value, JsonGenerator generator,
SerializerProvider serializerProvider)
throws IOException {
generator.writeString(formatter.print(value.toDateTime(DateTimeZone.UTC)));
}
}
| kumpelblase2/jhipster-websocket-example | src/main/java/de/kumpelblase2/jhipsterwebsocket/domain/util/CustomDateTimeSerializer.java | Java | mit | 944 |
require 'couchdb'
| Gimi/couchdb-client | lib/couchdb-client.rb | Ruby | mit | 18 |
namespace CodingDojo
{
public class InterlockedBoolean
{
private readonly bool _value;
private static readonly InterlockedBoolean FalseValue = new InterlockedBoolean(false);
private static readonly InterlockedBoolean TrueValue = new InterlockedBoolean(true);
private InterlockedBoolean(bool value)
{
_value = value;
}
public static InterlockedBoolean Get(bool? value)
{
return value;
}
public static implicit operator bool(InterlockedBoolean interlockedBoolean)
{
return interlockedBoolean._value;
}
public static implicit operator InterlockedBoolean(bool value)
{
return value ? TrueValue : FalseValue;
}
public static InterlockedBoolean operator !(InterlockedBoolean b)
{
return !b._value;
}
public static InterlockedBoolean operator &(InterlockedBoolean a, InterlockedBoolean b)
{
return a._value && b._value;
}
public static bool operator false(InterlockedBoolean a)
{
return !a._value;
}
public static bool operator true(InterlockedBoolean a)
{
return a._value;
}
public static InterlockedBoolean operator |(InterlockedBoolean a, InterlockedBoolean b)
{
return a._value || b._value;
}
public static InterlockedBoolean operator ^(InterlockedBoolean a, InterlockedBoolean b)
{
return a._value ^ b._value;
}
public static InterlockedBoolean operator ==(InterlockedBoolean a, InterlockedBoolean b)
{
if ((object)a == null && (object)b == null) return true;
if ((object)a == null || (object)b == null) return false;
return a._value == b._value;
}
public static InterlockedBoolean operator !=(InterlockedBoolean a, InterlockedBoolean b)
{
return !(a == b);
}
public static InterlockedBoolean operator ==(InterlockedBoolean a, bool b)
{
if ((object)a == null) return false;
return a._value == b;
}
public static InterlockedBoolean operator !=(InterlockedBoolean a, bool b)
{
return !(a == b);
}
public static InterlockedBoolean operator ==(bool a, InterlockedBoolean b)
{
if ((object)b == null) return false;
return a == b._value;
}
public static InterlockedBoolean operator !=(bool a, InterlockedBoolean b)
{
return !(a == b);
}
public override string ToString()
{
return _value.ToString();
}
public override bool Equals(object obj)
{
if (obj is InterlockedBoolean) return _value == (obj as InterlockedBoolean)._value;
return _value.Equals(obj);
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
}
} | JanVoracek/interlocked-boolean | InterlockedBoolean.cs | C# | mit | 3,117 |
require 'active_record'
require "active_record/version"
class ActiveRecord::Base
class << self
################################# Generic where clause and inclusion builder ###########################
# Query specification format
#
# Hash containing association specific query specification,
# each of which will map a param field to its param metadata
# needed to construct where condition. Param metadata involve
# information about the table, column the param maps to and
# the operator that need to applied in the query with the
# table column for the given param value. The operator passed
# is delegated to Arel::Table. So, all operators accepted
# by it are allowed (as mentioned in the example below)
#
# {
# :self =>
# {
# <param_field> =>
# {
# :column => <col_name_sym>
# :filter_operator => <:gt|:lt|:gteq|:lteq|:in|:not_in>,
# }
# }
# :association1 =>
# {
# <param_field> =>
# {
# :column => <col_name_sym>
# :filter_operator => <:gt|:lt|:gteq|:lteq|:in|:not_in>,
# },
# ...
# :join_filter =>
# {
# :table1_column => <column_name>, :table2_column => <column_name>,
# },
# :is_inclusion_mandatory => <true|false>
# },
# ...
# }
# Applies inclusion and where conditions/clauses for the model called upon.
# Where conditions are generated based on the presence of a param value.
def apply_includes_and_where_clauses(params, query_spec)
model = self
inclusions, where_clauses = get_inclusions_and_where_clauses(params, query_spec)
active_record = model.includes(inclusions)
where_clauses.each { |e| active_record = active_record.where(e) }
active_record
end
# Returns association inclusions and where conditions/clauses for the model called upon.
# Association inclusion is based on the presence of related where conditions.
# Where conditions are generated based on the presence of a param value.
def get_inclusions_and_where_clauses(params, query_spec)
result = emit_inclusion_and_filter_details(params, query_spec)
inclusions = result.keys - [:self]
where_clause_filters = result.values.flatten
[inclusions, where_clause_filters]
end
def emit_inclusion_and_filter_details(params, query_spec)
exclusions = [:join_filter, :is_inclusion_mandatory]
query_spec.each_with_object({}) do |(association, association_filter_spec), res|
join_spec, is_inclusion_mandatory = association_filter_spec.values_at(*exclusions)
new_association_filter_spec = association_filter_spec.reject { |e| exclusions.include?(e) }
association_model = get_association_model(association)
join_filter = get_association_join_filter(join_spec, self, association_model)
where_clause_filters =
new_association_filter_spec.each_with_object([]) do |(param_field, filter_spec), filter_res|
value = params[param_field]
if value.present?
filter_res << get_where_clause_filter(filter_spec, value, association_model)
end
end
if where_clause_filters.present?
res[association] = where_clause_filters
res[association] << join_filter if join_filter.present?
elsif is_inclusion_mandatory
res[association] = (join_filter.present?) ? [join_filter] : []
end
end
end
# Obtain ActiveRecord model from the association
def get_association_model(association)
(association == :self) ? self : self.reflect_on_association(association.to_sym).klass
end
private
def get_association_join_filter(join_filter, table1, table2)
return if join_filter.blank?
table1_col, table2_col = join_filter.values_at(:table1_column, :table2_column)
get_where_clause_sql(table2.arel_table[table2_col], table1, table1_col, :eq)
end
def get_where_clause_filter(filter_spec, value, table)
# Hash filters have good equality query abstractions.
# So choosing them over string filters for equality operator
if filter_spec[:filter_operator] == :eq
construct_hash_filter(value, filter_spec, table)
else
construct_str_filter(value, filter_spec, table)
end
end
def construct_str_filter(arg_value, filter_spec, table)
operator, column = filter_spec.values_at(:filter_operator, :column)
get_where_clause_sql(arg_value, table, column, operator)
end
def get_where_clause_sql(arg_value, table, column, operator)
table_arel = table.arel_table
sql = table_arel.where(table_arel[column].send(operator, arg_value)).to_sql
sql.split("WHERE").last
end
def construct_hash_filter(arg_value, filter_spec, table)
column = filter_spec[:column]
hash_filter = {column => arg_value}
(table != :self) ? {table.table_name.to_sym => hash_filter} : hash_filter
end
end
end
| kaushikd49/ar-auto-filter | lib/activerecord-auto_filter.rb | Ruby | mit | 5,309 |
window.onload = () => {
const root = new THREERoot({
fov: 60
});
root.renderer.setClearColor(0x222222);
root.camera.position.set(0, 0, 100);
let light = new THREE.DirectionalLight(0xffffff);
root.add(light);
light = new THREE.DirectionalLight(0xffffff);
light.position.z = 1;
root.add(light);
// mesh / skeleton based on https://threejs.org/docs/scenes/bones-browser.html
const segmentHeight = 8;
const segmentCount = 4;
const height = segmentHeight * segmentCount;
const halfHeight = height * 0.5;
const sizing = {
segmentHeight,
segmentCount,
height,
halfHeight
};
const bones = createBones(sizing);
const geometry = createGeometry(sizing);
const mesh = createMesh(geometry, bones);
const skeletonHelper = new THREE.SkeletonHelper(mesh);
root.add(skeletonHelper);
root.add(mesh);
let time = 0;
root.addUpdateCallback(() => {
time += (1/60);
mesh.material.uniforms.time.value = time % 1;
bones.forEach(bone => {
bone.rotation.z = Math.sin(time) * 0.25;
})
});
};
function createBones(sizing) {
const bones = [];
let prevBone = new THREE.Bone();
bones.push(prevBone);
prevBone.position.y = -sizing.halfHeight;
for (let i = 0; i < sizing.segmentCount; i++) {
const bone = new THREE.Bone();
bone.position.y = sizing.segmentHeight;
bones.push(bone);
prevBone.add(bone);
prevBone = bone;
}
return bones;
}
function createGeometry(sizing) {
let baseGeometry = new THREE.CylinderGeometry(
5, // radiusTop
5, // radiusBottom
sizing.height, // height
8, // radiusSegments
sizing.segmentCount * 4, // heightSegments
true // openEnded
);
baseGeometry = new THREE.Geometry().fromBufferGeometry(baseGeometry);
for (let i = 0; i < baseGeometry.vertices.length; i++) {
const vertex = baseGeometry.vertices[i];
const y = (vertex.y + sizing.halfHeight);
const skinIndex = Math.floor(y / sizing.segmentHeight);
const skinWeight = (y % sizing.segmentHeight) / sizing.segmentHeight;
// skinIndices = indices of up to 4 bones for the vertex to be influenced by
baseGeometry.skinIndices.push(new THREE.Vector4(skinIndex, skinIndex + 1, 0, 0));
// skinWeights = weights for each of the bones referenced by index above (between 0 and 1)
baseGeometry.skinWeights.push(new THREE.Vector4(1 - skinWeight, skinWeight, 0, 0));
}
// create a prefab for each vertex
const prefab = new THREE.TetrahedronGeometry(1);
const prefabCount = baseGeometry.vertices.length;
const geometry = new BAS.PrefabBufferGeometry(prefab, prefabCount);
// position (copy vertex position)
geometry.createAttribute('aPosition', 3, function(data, i) {
baseGeometry.vertices[i].toArray(data);
});
// skin indices, copy from geometry, based on vertex
geometry.createAttribute('skinIndex', 4, (data, i) => {
baseGeometry.skinIndices[i].toArray(data);
});
// skin weights, copy from geometry, based on vertex
geometry.createAttribute('skinWeight', 4, (data, i) => {
baseGeometry.skinWeights[i].toArray(data);
});
// rotation (this is completely arbitrary)
const axis = new THREE.Vector3();
geometry.createAttribute('aAxisAngle', 4, function(data, i) {
BAS.Utils.randomAxis(axis);
axis.toArray(data);
data[3] = Math.PI * 2;
});
return geometry;
}
function createMesh(geometry, bones) {
const material = new BAS.StandardAnimationMaterial({
skinning: true,
side: THREE.DoubleSide,
flatShading: true,
uniforms: {
time: {value: 0},
},
vertexParameters: `
uniform float time;
attribute vec3 aPosition;
attribute vec4 aAxisAngle;
`,
vertexFunctions: [
BAS.ShaderChunk.quaternion_rotation
],
vertexPosition: `
vec4 q = quatFromAxisAngle(aAxisAngle.xyz, aAxisAngle.w * time);
transformed = rotateVector(q, transformed);
transformed += aPosition;
`
});
const mesh = new THREE.SkinnedMesh(geometry, material);
const skeleton = new THREE.Skeleton(bones);
mesh.add(bones[0]);
mesh.bind(skeleton);
return mesh;
}
| zadvorsky/three.bas | examples/skinning_prefabs/main.js | JavaScript | mit | 4,231 |
import imp
import os
tools = []
for name in os.listdir(os.path.dirname(__file__)):
if not name.startswith('_'): # _ in the front indicates that this tool is disabled
directory = os.path.join(os.path.dirname(__file__), name)
if os.path.isdir(directory):
file = os.path.join(directory, name + '.py')
tool = imp.load_source(name, file)
tools.append(getattr(tool, name)) | nullzero/wpcgi | wpcgi/tools/__init__.py | Python | mit | 424 |
#!/usr/bin/env python
# Copyright (c) 2011, 2013 SEOmoz, Inc
#
# 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.
from setuptools import setup
setup(
name='s3po',
version='0.6.1',
description='An uploading daemon for S3',
long_description='''Boto is a wonderful library. This is just a little
help for dealing with multipart uploads, batch uploading with gevent
and getting some help when mocking''',
author='Moz, Inc.',
author_email="turbo@moz.com",
url='http://github.com/seomoz/s3po',
packages=['s3po', 's3po.backends'],
license='MIT',
platforms='Posix; MacOS X',
install_requires=[
'boto3',
'coverage',
'gevent',
'mock',
'nose',
'python_swiftclient',
'six'
],
classifiers=[
'License :: OSI Approved :: MIT License',
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Topic :: Internet :: WWW/HTTP',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
]
)
| seomoz/s3po | setup.py | Python | mit | 2,278 |
module Provision
VERSION = "0.0.1"
end
| chenfisher/provision | lib/provision/version.rb | Ruby | mit | 41 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SysUt14Gr03.Classes;
using SysUt14Gr03.Models;
namespace SysUt14Gr03
{
public partial class RapportTestForm : System.Web.UI.Page
{
protected void Page_PreInit(Object sener, EventArgs e)
{
string master = SessionSjekk.findMaster();
this.MasterPageFile = master;
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Rapport rapport = new Rapport(Rapport.TEAMRAPPORT, 1);
lblTest.Text = rapport.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
Rapport rapport = new Rapport(Rapport.PROSJEKTRAPPORT, 1);
lblTest.Text = rapport.ToString();
}
protected void Button3_Click(object sender, EventArgs e)
{
Rapport rapport = new Rapport(Rapport.INDIVIDRAPPORT, 2);
lblTest.Text = rapport.ToString();
}
}
} | divarsoy/Gruppe3HIN | kode/SysUt14Gr03/SysUt14Gr03/RapportTestForm.aspx.cs | C# | mit | 1,177 |
@extends('admin')
@section('title', 'Promotions')
@section('content')
<div class="row">
<div class="col-md-5">
<h3 class="modal-title">{{ $result->total() }} {{ str_plural('Promotion', $result->count()) }}</h3>
</div>
<div class="col-md-12 page-action text-right">
@can('add_promotions')
<a href="{{ route('promotions.create') }}" class="btn btn-primary btn-sm"> <i class="glyphicon glyphicon-plus-sign"></i> Create</a>
@endcan
</div>
<br><br><br><br>
<!-- /.box-header -->
<div class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Name</th>
<th>Hourly Discount</th>
<th>Daily Discount</th>
<th>Price Discount</th>
<th>Start Date</th>
<th>End Date</th>
@can('edit_promotions', 'delete_promotions')
<th class="text-center">Actions</th>
@endcan
</tr>
</thead>
@foreach($result as $item)
<tr>
<td>{{ $item->name }}</td>
<td>{{ $item->hourlyRatePercentage }}</td>
<td>{{ $item->dailyRatePercentage }}</td>
<td>{{ $item->priceRatePercentage }}</td>
<td>{{ $item->start_date }}</td>
<td>{{ $item->end_date }}</td>
@can('edit_promotions')
<td class="text-center">
@include('shared._actions', [
'entity' => 'promotions',
'id' => $item->id
])
</td>
@endcan
</tr>
@endforeach
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.7 -->
<link rel="stylesheet" href="../../bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="../../bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="../../bower_components/Ionicons/css/ionicons.min.css">
<!-- DataTables -->
<link rel="stylesheet" href="../../bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css">
<!-- <body class="hold-transition skin-blue sidebar-mini"> -->
<!-- jQuery 3 -->
<script src="../../bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="../../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- DataTables -->
<script src="../../bower_components/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="../../bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<!-- SlimScroll -->
<script src="../../bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="../../bower_components/fastclick/lib/fastclick.js"></script>
<!-- page script -->
<script>
$(function () {
$('#example1').DataTable()
$('#example2').DataTable({
'paging' : true,
'lengthChange': false,
'searching' : false,
'ordering' : true,
'info' : true,
'autoWidth' : false
})
})
</script>
@endsection | ryanzzeng/laravelStarter | resources/views/promotion/index.blade.php | PHP | mit | 3,673 |
<?php
declare(strict_types = 1);
namespace Rx\Functional;
use Rx\Observable;
class FromArrayTest extends FunctionalTestCase
{
/**
* @test
*/
public function it_schedules_all_elements_from_the_array()
{
$xs = Observable::fromArray(['foo', 'bar', 'baz'], $this->scheduler);
$results = $this->scheduler->startWithCreate(function () use ($xs) {
return $xs;
});
$this->assertMessages([
onNext(201, 'foo'),
onNext(202, 'bar'),
onNext(203, 'baz'),
onCompleted(204),
], $results->getMessages());
}
/**
* @test
*/
public function it_calls_on_complete_when_the_array_is_empty()
{
$xs = Observable::fromArray([], $this->scheduler);
$results = $this->scheduler->startWithCreate(function () use ($xs) {
return $xs;
});
$this->assertMessages([
onCompleted(201),
], $results->getMessages());
}
/**
* @test
*/
public function fromArray_one()
{
$xs = Observable::fromArray([1], $this->scheduler);
$results = $this->scheduler->startWithCreate(function () use ($xs) {
return $xs;
});
$this->assertMessages([
onNext(201, 1),
onCompleted(202),
], $results->getMessages());
}
/**
* @test
*/
public function fromArray_dispose()
{
$xs = Observable::fromArray(['foo', 'bar', 'baz'], $this->scheduler);
$results = $this->scheduler->startWithDispose(function () use ($xs) {
return $xs;
}, 202);
$this->assertMessages([
onNext(201, 'foo')
], $results->getMessages());
}
}
| ReactiveX/RxPHP | test/Rx/Functional/Operator/FromArrayTest.php | PHP | mit | 1,767 |
package com.helospark.lightdi.it;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.isA;
import static org.junit.Assert.assertThat;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import com.helospark.lightdi.LightDi;
import com.helospark.lightdi.LightDiContext;
import com.helospark.lightdi.exception.BeanCreationException;
import com.helospark.lightdi.exception.ContextInitializationFailedException;
import com.helospark.lightdi.it.importingclassaware.DummyServiceConfiguration;
import com.helospark.lightdi.it.importingclassaware.ImportingClassAwareConfiguration;
public class ImportingClassAwareIT {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testSuccessfullyInjected() {
// GIVEN
// WHEN
LightDiContext context = LightDi.initContextByClass(ImportingClassAwareConfiguration.class);
// THEN
DummyServiceConfiguration dummyService = context.getBean(DummyServiceConfiguration.class);
assertThat(dummyService.getConfigurationValue(), is("testConfiguration"));
}
@Test
public void testOnDirectImportShouldThrow() {
// GIVEN
expectedException.expect(ContextInitializationFailedException.class);
expectedException.expectCause(isA(BeanCreationException.class));
// WHEN
LightDi.initContextByClass(DummyServiceConfiguration.class);
// THEN throws because empty is injected
}
}
| helospark/light-di | src/test/java/com/helospark/lightdi/it/ImportingClassAwareIT.java | Java | mit | 1,536 |
package bg;
import com.renren.api.RennException;
/** 定时刷新信息.
* @author ZCH
*/
public final class Driver {
/** magic number.
* set magic number 180000
*/
private static final int MN = 180000;
/** 调用dirive()函数.
* @param args String[]
*/
public static void main(final String[] args) {
drive();
}
/** Timer.
*/
private static void drive() {
long interval = MN;
while (true) {
InfoBG.getInfo();
try {
OrganBG.getOrgan();
} catch (RennException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("==============================");
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/** constructer.
*/
private Driver() {
}
}
| sibojia/ihomepage | infohub-yt/src/bg/Driver.java | Java | mit | 1,054 |
namespace NServiceBus.AcceptanceTests.Basic
{
using System;
using System.Threading.Tasks;
using AcceptanceTesting;
using EndpointTemplates;
using NUnit.Framework;
public class When_multiple_mappings_exists : NServiceBusAcceptanceTest
{
[Test]
public async Task First_registration_should_be_the_final_destination()
{
var context = await Scenario.Define<Context>()
.WithEndpoint<Sender>(b => b.When((session, c) => session.Send(new MyCommand1())))
.WithEndpoint<Receiver1>()
.WithEndpoint<Receiver2>()
.Done(c => c.WasCalled1 || c.WasCalled2)
.Run();
Assert.IsTrue(context.WasCalled1);
Assert.IsFalse(context.WasCalled2);
}
public class Context : ScenarioContext
{
public bool WasCalled1 { get; set; }
public bool WasCalled2 { get; set; }
}
public class Sender : EndpointConfigurationBuilder
{
public Sender()
{
EndpointSetup<DefaultServer>()
.AddMapping<MyCommand1>(typeof(Receiver1))
.AddMapping<MyCommand2>(typeof(Receiver2));
}
}
public class Receiver1 : EndpointConfigurationBuilder
{
public Receiver1()
{
EndpointSetup<DefaultServer>();
}
public class MyMessageHandler : IHandleMessages<MyBaseCommand>
{
public Context Context { get; set; }
public Task Handle(MyBaseCommand message, IMessageHandlerContext context)
{
Context.WasCalled1 = true;
return Task.Delay(2000); // Just to be sure the other receiver is finished
}
}
}
public class Receiver2 : EndpointConfigurationBuilder
{
public Receiver2()
{
EndpointSetup<DefaultServer>();
}
public class MyMessageHandler : IHandleMessages<MyBaseCommand>
{
public Context Context { get; set; }
public Task Handle(MyBaseCommand message, IMessageHandlerContext context)
{
Context.WasCalled2 = true;
return Task.Delay(2000); // Just to be sure the other receiver is finished
}
}
}
[Serializable]
public abstract class MyBaseCommand : ICommand
{
}
[Serializable]
public class MyCommand1 : MyBaseCommand
{
}
[Serializable]
public class MyCommand2 : MyBaseCommand
{
}
}
} | sbmako/NServiceBus.MongoDB | src/NServiceBus.MongoDB.Acceptance.Tests/App_Packages/NSB.AcceptanceTests.6.0.0/Basic/When_multiple_mappings_exists.cs | C# | mit | 2,894 |
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* 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 org.spongepowered.mod.mixin.core.event.entity.living;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraftforge.event.entity.EntityEvent;
import org.spongepowered.api.entity.living.Living;
import org.spongepowered.api.event.entity.living.LivingEvent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
@Mixin(value = net.minecraftforge.event.entity.living.LivingEvent.class, remap = false)
public abstract class MixinEventLiving extends EntityEvent implements LivingEvent {
@Shadow
public EntityLivingBase entityLiving;
public MixinEventLiving(Entity entity) {
super(entity);
}
@Override
public Living getLiving() {
return (Living) this.entityLiving;
}
@Override
public Living getEntity() {
return (Living) this.entityLiving;
}
}
| phase/Sponge | src/main/java/org/spongepowered/mod/mixin/core/event/entity/living/MixinEventLiving.java | Java | mit | 2,143 |
import test from 'ava';
import snapshot from '../../helpers/snapshot';
import Vue from 'vue/dist/vue.common.js';
import u from '../../../src/lib/components/u/index.vue';
import commonTest from '../../common/unit';
const testOptions = {
test,
Vue,
snapshot,
component : window.morning._origin.Form.extend(u),
name : 'u',
attrs : ``,
uiid : 2,
delVmEl : false,
_baseTestHookCustomMount : false
};
commonTest.componentBase(testOptions);
| Morning-UI/morning-ui | test/unit/components/u.js | JavaScript | mit | 586 |
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like
# NGINX, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
config.action_mailer.default_url_options = { :host => 'handelatnewberry.herokuapp.com' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "handelatnewberry.herokuapp.com",
authentication: "plain",
enable_starttls_auto: true,
user_name: ENV['EMAIL'],
password: ENV['PASSWORD']
}
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| reginafcompton/handelatnewberry | config/environments/production.rb | Ruby | mit | 3,853 |
/*Création des cookies*/
$(document).ready(function () {
CreateCookies();
$('input:not([type="submit"])').each(function () {
$(this).val('');
});
});
/*Ajout des vols dans la recherche*/
function addResultVols(toAppend, compagnie, code, provenance, destination, imgSrc, date, heure, ArrDep, imgArrDep,data_vols,typeAlert,statut) {
var dateTd = (date === null) ? '' : '<td>' + date + '</td>';
var trString = '<tr class="'+ArrDep+'" active="OK" data-codevol="'+code+'" data-typevols="result">'+
'<td class="imgArrDep"><img src="'+imgArrDep+'"/></td>'+
'<td class="logoCompagny"><img src="'+imgSrc+'"/></td>'+
'<td class="numVol">'+code+'</td>'+
'<td>'+provenance+'</td>'+
'<td>'+destination+'</td>'+
dateTd+
'<td>'+heure+'</td>'+
'<td>'+statut+'</td>'+
'<td class="ToggleTd"><input type="checkbox" name="Alert" class="Alert'+typeAlert+' toggleCheckBox" data-vols="'+data_vols+'"/></td>'+
'</tr>';
var tr = $.parseHTML(trString);
toAppend.append(tr);
}
/*Ajout message -> Aucun Vol*/
function addNoVol(toAppend) {
var trString = '<tr class="NoResultVol">' +
'<td colspan="9" style="text-align:center;">Aucun vol ne correspond à la provenance et à la destination soumise ou à la date soumise </td>' +
'</tr>';
var tr = $.parseHTML(trString);
toAppend.append(tr);
}
/*Création des cookies*/
function CreateCookies() {
Cookies.set('provenance', '');
Cookies.set('destination', '');
Cookies.set('dateVol', '');
}
/*Vérifier si les cookies existent*/
function CookiesExists() {
return Cookies.get('provenance') !== '' && Cookies.get('destination') !== '' && Cookies.get('dateVol') !== '';
}
/*Véfier si les cookies contiennent les données de la précédente recherche*/
function IsSetCookies(prov, dest, date) {
return Cookies.get('provenance') == prov && Cookies.get('destination') == dest && Cookies.get('dateVol') == date;
}
/*Set Cookie*/
function SetCookies(prov, dest, date) {
Cookies.set('provenance', prov);
Cookies.set('destination', dest);
Cookies.set('dateVol', date);
}
/*Nettoyage précédent résultat*/
function NettoyageResult(trs,envoiOk) {
trs.remove();
if(envoiOk.hasClass("displayButton"))
envoiOk.removeClass("displayButton");
if(!envoiOk.hasClass('noDisplayButton'))
envoiOk.addClass('noDisplayButton');
}
/*Select -> set à défaut*/
function DefaultSelect(heureVol, textArriveeDepart, selectName) {
var selected = $('select[name="'+selectName+'"] option:selected');
if(selected.attr('id') != "default"){
selected.removeAttr("selected");
$('select[name="' + selectName + '"]').selectpicker('val', $('select[name="' + selectName +'"] #default').text());
}
heureVol.text('Heure');
textArriveeDepart.text($('select[name="' + selectName +'"] #default').text());
}
/* Message Erreur Invalide */
function MessageErreurInvalide(message, checkValid, messageText) {
if (!checkValid) {
var messageErreur = message.find('span[itemprop="3"]');
messageErreur.find('mark').text(messageText);
AfficheMessageGenerique2(message.find('span[itemprop="1"]'), 'noDisplayGenerique2');
AfficheMessageGenerique2(message.find('span[itemprop="2"]'), 'noDisplayGenerique2');
AfficheMessageGenerique(message, "displayGenerique");
AfficheMessageGenerique2(messageErreur, "displayGenerique2");
}
}
/* Recherche des vols */
$("#zoneRecherche").submit(function (event) {
event.preventDefault();
var provenance = $('select[name="ProvSearch"] option:selected');
var destination = $('select[name="DestSearch"] option:selected');
var dateVol;
/*Récupération dateVol*/
$("#dateVolRecherche input").each(function () {
if ($(this).hasClass('displayGenerique2')) {
dateVol = $(this).val();
return;
}
})
var message = $('#MessageErreurProvDest');
var provSuccess = $('select[name="ProvSearch"]').siblings('button').hasClass('success');
var destSuccess = $('select[name="DestSearch"]').siblings('button').hasClass('success');
dateVol = dateVol.replace(/[/]/g, '-');
if (!MessageErreurRecherche(provenance.val(), message, 'provenance') || !MessageErreurRecherche(destination.val(), message, 'destination') || !MessageErreurRecherche(dateVol, message, 'jour du vol'))
return;
AfficheMessageGenerique2(message, 'noDisplayGenerique2');
if(!CompareProvDest(provenance.val(),destination.val()))
return;
AfficheMessageGenerique2(message, 'noDisplayGenerique2');
if (provSuccess && destSuccess) {
$("#ResultatVol").modal("show");
let urlRechercheVol = urlApi+"/RechercheVols/" + provenance.val() + "/" + destination.val() + "/" + dateVol;
/*Lancement de la recherche*/
if (!CookiesExists() || !IsSetCookies(provenance.val(), destination.val(), dateVol)) {
/*Enregistrement des valeurs de la recherche*/
SetCookies(provenance.val(), destination.val(),dateVol);
/*Nettoyage précédente recherche*/
NettoyageResult($("#RechercheVol tr"), $(".EnvoiOkRechercheVol"));
DefaultSelect($("#heureVol"), $("#ResultatSearchVol > thead > tr > .ResultArrivéeOuDépart"), "resultatVol");
/*Appel API*/
$.getJSON(urlRechercheVol, {})
.done(function (data) {
if (Object.keys(data).indexOf("message") == -1) {
DefaultSelect($("#heureVol"), $("#ResultatSearchVol > thead > tr > .ResultArrivéeOuDépart"), "resultatVol");
Object.keys(data).forEach(function (key) {
var ArrDep = (Object.keys(data[key]).indexOf("Arr") !== -1) ? "Arrivée" : "Départ";
addResultVols(
$("#RechercheVol"),
data[key].Compagnie,
data[key].CodeVol,
data[key].Provenance,
data[key].Destination,
data[key].Img,
data[key].Date,
(ArrDep == "Arrivée") ? data[key].Arr : data[key].Dep,
ArrDep,
data[key].imgArrDep,
"Search",
'RechercheVol',
data[key].Statut
);
});
/*Contrôle fenetre modal*/
$(".AlertRechercheVol").each(function () {
var EnvoiOk = $(".EnvoiOkRechercheVol");
$(this).change(function () {
CheckButtonCheckBox(EnvoiOk, $(this));
ControleCheckBox(EnvoiOk, 'RechercheVol');
});
});
/*Paramétrage Bootstrap Toggle Checkbox*/
$('.toggleCheckBox[data-vols="Search"]').bootstrapToggle({
on: 'Suivi',
off: 'Non Suivi',
onstyle: "success",
size: "small",
height: 60,
width: 85
});
}
else {
addNoVol($("#RechercheVol"));
return;
}
});
}
}
else {
MessageErreurInvalide(message, provSuccess, 'provenance invalide');
MessageErreurInvalide(message, destSuccess, 'destination invalide');
return;
}
});
| aimanwakidou/SiteAeroport | js/RechercheVol.js | JavaScript | mit | 7,968 |
using System;
using System.Collections.Generic;
using System.Text;
namespace CommandLineDeploymentTool
{
class Arguments
{
public string DeployType { get; private set; }
public string BackupFolder { get; private set; }
public string AppName { get; private set; }
public string AppFolder { get; private set; }
public string DeployFolder { get; private set; }
public string CategoryName { get; private set; }
public string FireDaemonPath { get; private set; }
public bool Restore { get; set; }
public string RestorePath { get; set; }
public string ApplicationPoolName { get; private set; }
public bool NoBackup { get; private set; }
public bool NoStop { get; private set; }
public bool NoStart { get; private set; }
public Arguments(string[] args, bool fineTuneArgs)
{
if (fineTuneArgs)
{
// handles quotations if necessary
args = this.FineTune(args);
}
this.AssignFields(args);
}
private string[] FineTune(string[] args)
{
List<string> argList = new List<string>();
foreach (string arg in args)
{
if (arg.Trim().StartsWith("/"))
{
argList.Add(arg);
}
else
{
string lastItem = argList[argList.Count - 1];
lastItem += " " + arg;
argList[argList.Count - 1] = lastItem;
}
}
return argList.ToArray();
}
private void AssignFields(string[] args)
{
foreach (string arg in args)
{
int indexOfColon = arg.Contains(":") ? arg.IndexOf(':') : arg.Length;
string argKey = arg.Substring(1, indexOfColon - 1);
string argVal = arg.Length > indexOfColon ? arg.Substring(indexOfColon + 1, arg.Length - indexOfColon - 1) : string.Empty;
switch (argKey)
{
case "deployType":
this.DeployType = argVal;
break;
case "backupFolder":
this.BackupFolder = argVal;
break;
case "appName":
this.AppName = argVal;
break;
case "appFolder":
this.AppFolder = argVal;
break;
case "deployFolder":
this.DeployFolder = argVal;
break;
case "categoryName":
this.CategoryName = argVal;
break;
case "fireDaemonPath":
this.FireDaemonPath = argVal;
break;
case "restore":
this.Restore = true;
break;
case "restorePath":
this.RestorePath = argVal;
break;
case "applicationPool":
this.ApplicationPoolName = argVal;
break;
case "noBackup":
this.NoBackup = true;
break;
case "noStop":
this.NoStop = true;
break;
case "noStart":
this.NoStart = true;
break;
}
}
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.Append(Environment.GetCommandLineArgs()[0]).Append(" ");
if (!string.IsNullOrEmpty(this.DeployType))
sb.Append("/deployType:" + this.DeployType).Append(" ");
if (!string.IsNullOrEmpty(this.BackupFolder))
sb.Append("/backupFolder:" + this.BackupFolder).Append(" ");
if (!string.IsNullOrEmpty(this.AppName))
sb.Append("/appName:" + this.AppName).Append(" ");
if (!string.IsNullOrEmpty(this.AppFolder))
sb.Append("/appFolder:" + this.AppFolder).Append(" ");
if (!string.IsNullOrEmpty(this.DeployFolder))
sb.Append("/deployFolder:" + this.DeployFolder).Append(" ");
if (!string.IsNullOrEmpty(this.CategoryName))
sb.Append("/categoryName:" + this.CategoryName).Append(" ");
if (!string.IsNullOrEmpty(this.FireDaemonPath))
sb.Append("/fireDaemonPath:" + this.FireDaemonPath).Append(" ");
if (this.Restore)
sb.Append("/restore:").Append(" ");
if (!string.IsNullOrEmpty(this.RestorePath))
sb.Append("/restorePath:" + this.RestorePath).Append(" ");
if (!string.IsNullOrEmpty(this.ApplicationPoolName))
sb.Append("/applicationPool:" + this.ApplicationPoolName).Append(" ");
if (this.NoBackup)
sb.Append("/noBackup:").Append(" ");
if (this.NoStop)
sb.Append("/noStop:").Append(" ");
if (this.NoStart)
sb.Append("/noStart:").Append(" ");
return sb.ToString();
}
public static string HelpString
{
get
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(@"Usage:");
sb.AppendLine();
sb.AppendLine(@"Format : /deployType:<deployType>");
sb.AppendLine(@"Desc. : Type of deployment");
sb.AppendLine(@"Sample : /deployType:COM");
sb.AppendLine(@"Sample : /deployType:EXE");
sb.AppendLine(@"Sample : /deployType:FIREDAEMONAPP");
sb.AppendLine(@"Sample : /deployType:IIS");
sb.AppendLine(@"Sample : /deployType:WINDOWSSERVICE");
sb.AppendLine();
sb.AppendLine(@"Format : /backupRootFolder:<backupRootFolder>");
sb.AppendLine(@"Desc. : Use this pat as a root to backups");
sb.AppendLine(@"Sample : /backupRootFolder:D:\Backups");
sb.AppendLine();
sb.AppendLine(@"Format : /appName:<appName>");
sb.AppendLine(@"Desc. : Name of the application (Generally dll or exe name)");
sb.AppendLine(@"Sample (COM) : /appName:MyApp (dll name)");
sb.AppendLine(@"Sample (EXE) : /appName:MyApp (exe name)");
sb.AppendLine(@"Sample (FIREDAEMONAPP) : /appName:MyApp (name seen in firedaemon)");
sb.AppendLine(@"Sample (IIS) : /appName:MyApp (not important in iis case, you may give anything)");
sb.AppendLine(@"Sample (WINDOWSSERVICE) : /appName:Myapp (exe name)");
sb.AppendLine();
sb.AppendLine(@"Format : /appFolder:<appFolder>");
sb.AppendLine(@"Desc. : Root folder of the application");
sb.AppendLine(@"Sample : /appFolder:D:\MyAppFolder");
sb.AppendLine();
sb.AppendLine(@"Format : /deployFolder:<deployFolder>");
sb.AppendLine(@"Desc. : Root folder of the deployed (new version) application");
sb.AppendLine(@"Sample : /deployFolder:D:\DeployFolder");
sb.AppendLine();
sb.AppendLine(@"Format : /categoryName:<categoryName>");
sb.AppendLine(@"Desc. : Name of the com category (Needed for category shutdown etc.). Only used in COM deployments");
sb.AppendLine(@"Sample : /categoryName:MyAppCategory");
sb.AppendLine();
sb.AppendLine(@"Format : /fireDaemonPath:<fireDaemonPath>");
sb.AppendLine(@"Desc. : Path for the FireDaemon.exe. Only used in FIREDAEMONAPP deployments");
sb.AppendLine(@"Sample : /fireDaemonPath:C:\Program Files\FireDaemon\FireDaemon.exe");
sb.AppendLine();
sb.AppendLine(@"Format : /restore");
sb.AppendLine(@"Desc. : Restore from backup, if the deployment fails. Or if you want to get back to previous version");
sb.AppendLine();
sb.AppendLine(@"Format : /restorePath:<restorePath>");
sb.AppendLine(@"Desc. : Path of the backup from which to restore");
sb.AppendLine(@"Sample : /restorePath:D:\Backups\MyApp\Backup_20150101_013030");
sb.AppendLine();
sb.AppendLine(@"Format : /applicationPool:<applicationPool>");
sb.AppendLine(@"Desc. : Name of the IIS ApplicationPool only used in IIS deployments");
sb.AppendLine(@"Sample : /applicationPool:DefaultAppPool");
sb.AppendLine();
sb.AppendLine(@"Format : /noBackup");
sb.AppendLine(@"Desc. : Bypasses backup step (Normal exection: Backup, Stop, Deploy, Start");
sb.AppendLine();
sb.AppendLine(@"Format : /noStop");
sb.AppendLine(@"Desc. : Bypasses stop step (Normal exection: Backup, Stop, Deploy, Start");
sb.AppendLine();
sb.AppendLine(@"Format : /noStart");
sb.AppendLine(@"Desc. : Bypasses start step (Normal exection: Backup, Stop, Deploy, Start");
return sb.ToString();
}
}
}
}
| erdalgokten/CommandLineDeploymentTool | CommandLineDeploymentTool/Arguments.cs | C# | mit | 9,801 |
/*
*
* ProjectList constants
*
*/
// export const DEFAULT_ACTION = 'app/ProjectList/DEFAULT_ACTION';
export const GET_PROJECTS_OWNED_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED';
export const GET_PROJECTS_OWNED_SUCCESS_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED_SUCCESS';
export const GET_PROJECTS_OWNED_ERROR_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED_ERROR';
export const GET_PROJECTS_ACCESS_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS';
export const GET_PROJECTS_ACCESS_SUCCESS_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS_SUCCESS';
export const GET_PROJECTS_ACCESS_ERROR_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS_ERROR';
| VeloCloud/website-ui | app/containers/ProjectList/constants.js | JavaScript | mit | 642 |
from django.core.management import setup_environ
import settings
setup_environ(settings)
from apps.modules.tasks import update_data
update_data.delay()
| udbhav/eurorack-planner | scripts/update_data.py | Python | mit | 167 |
//
//
// MIT License
//
// Copyright (c) 2017 Stellacore Corporation.
//
// 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.
//
//
/*! \file
\brief Definitions for dat::Jump
*/
#include "libdat/Jump.h"
#include "libdat/compare.h"
#include <iomanip>
#include <sstream>
namespace dat
{
//======================================================================
// explicit
Jump :: Jump
( size_t const & ndx
, double const & lo
, double const & hi
)
: theNdx(ndx)
, theLo(lo)
, theHi(hi)
{ }
// copy constructor -- compiler provided
// assignment operator -- compiler provided
// destructor -- compiler provided
bool
Jump :: nearlyEquals
( Jump const & other
) const
{
bool same(theNdx == other.theNdx);
if (same)
{
same &= dat::nearlyEquals(theLo, other.theLo);
same &= dat::nearlyEquals(theHi, other.theHi);
}
return same;
}
std::string
Jump :: infoString
( std::string const & title
) const
{
std::ostringstream oss;
oss << std::fixed << std::setprecision(3u);
oss
<< title
<< " " << std::setw(4u) << theNdx
<< " " << std::setw(9u) << theLo
<< " " << std::setw(9u) << theHi
;
return oss.str();
}
//======================================================================
}
| transpixel/tpqz | libdat/Jump.cpp | C++ | mit | 2,242 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("samplemvc")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("samplemvc")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d1809673-942c-4ad3-ae67-80be4e9db5bf")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.2.5.1")]
[assembly: AssemblyFileVersion("1.2.5.1")]
| dlmelendez/identitydocumentdb | sample/samplemvc/Properties/AssemblyInfo.cs | C# | mit | 1,349 |
<?php
namespace Oro\Bundle\MessageQueueBundle\Tests\Unit\DependencyInjection;
use Oro\Bundle\MessageQueueBundle\DependencyInjection\Configuration;
use Oro\Bundle\MessageQueueBundle\Tests\Unit\Mocks\FooTransportFactory;
use Oro\Component\MessageQueue\DependencyInjection\DbalTransportFactory;
use Oro\Component\MessageQueue\DependencyInjection\DefaultTransportFactory;
use Oro\Component\MessageQueue\DependencyInjection\NullTransportFactory;
use Oro\Component\Testing\ClassExtensionTrait;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Config\Definition\Processor;
class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
use ClassExtensionTrait;
public function testShouldImplementConfigurationInterface()
{
$this->assertClassImplements(ConfigurationInterface::class, Configuration::class);
}
public function testCouldBeConstructedWithFactoriesAsFirstArgument()
{
new Configuration([]);
}
public function testThrowIfTransportNotConfigured()
{
$this->setExpectedException(
InvalidConfigurationException::class,
'The child node "transport" at path "oro_message_queue" must be configured.'
);
$configuration = new Configuration([]);
$processor = new Processor();
$processor->processConfiguration($configuration, [[]]);
}
public function testShouldInjectFooTransportFactoryConfig()
{
$configuration = new Configuration([new FooTransportFactory()]);
$processor = new Processor();
$processor->processConfiguration($configuration, [[
'transport' => [
'foo' => [
'foo_param' => 'aParam'
],
]
]]);
}
public function testThrowExceptionIfFooTransportConfigInvalid()
{
$configuration = new Configuration([new FooTransportFactory()]);
$processor = new Processor();
$this->setExpectedException(
InvalidConfigurationException::class,
'The path "oro_message_queue.transport.foo.foo_param" cannot contain an empty value, but got null.'
);
$processor->processConfiguration($configuration, [[
'transport' => [
'foo' => [
'foo_param' => null
],
]
]]);
}
public function testShouldAllowConfigureDefaultTransport()
{
$configuration = new Configuration([new DefaultTransportFactory()]);
$processor = new Processor();
$processor->processConfiguration($configuration, [[
'transport' => [
'default' => ['alias' => 'foo'],
]
]]);
}
public function testShouldAllowConfigureNullTransport()
{
$configuration = new Configuration([new NullTransportFactory()]);
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
'transport' => [
'null' => true,
]
]]);
$this->assertEquals([
'transport' => [
'null' => [],
]
], $config);
}
public function testShouldAllowConfigureSeveralTransportsSameTime()
{
$configuration = new Configuration([
new NullTransportFactory(),
new DefaultTransportFactory(),
new FooTransportFactory(),
]);
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
'transport' => [
'default' => 'foo',
'null' => true,
'foo' => ['foo_param' => 'aParam'],
]
]]);
$this->assertEquals([
'transport' => [
'default' => ['alias' => 'foo'],
'null' => [],
'foo' => ['foo_param' => 'aParam'],
]
], $config);
}
public function testShouldAllowConfigureDBALTransport()
{
$configuration = new Configuration([
new DefaultTransportFactory(),
new DbalTransportFactory()
]);
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
'transport' => [
'default' => 'dbal',
'dbal' => true,
]
]]);
$this->assertEquals([
'transport' => [
'default' => [
'alias' => 'dbal',
],
'dbal' => [
'connection' => 'default',
'table' => 'oro_message_queue',
'orphan_time' => 300,
'polling_interval' => 1000,
],
]
], $config);
}
public function testShouldSetDefaultConfigurationForClient()
{
$configuration = new Configuration([new DefaultTransportFactory()]);
$processor = new Processor();
$config = $processor->processConfiguration($configuration, [[
'transport' => [
'default' => ['alias' => 'foo'],
],
'client' => null,
]]);
$this->assertEquals([
'transport' => [
'default' => ['alias' => 'foo'],
],
'client' => [
'prefix' => 'oro',
'router_processor' => 'oro_message_queue.client.route_message_processor',
'router_destination' => 'default',
'default_destination' => 'default',
'traceable_producer' => false,
'redelivered_delay_time' => 10
],
], $config);
}
public function testThrowExceptionIfRouterDestinationIsEmpty()
{
$this->setExpectedException(
InvalidConfigurationException::class,
'The path "oro_message_queue.client.router_destination" cannot contain an empty value, but got "".'
);
$configuration = new Configuration([new DefaultTransportFactory()]);
$processor = new Processor();
$processor->processConfiguration($configuration, [[
'transport' => [
'default' => ['alias' => 'foo'],
],
'client' => [
'router_destination' => '',
],
]]);
}
public function testShouldThrowExceptionIfDefaultDestinationIsEmpty()
{
$this->setExpectedException(
InvalidConfigurationException::class,
'The path "oro_message_queue.client.default_destination" cannot contain an empty value, but got "".'
);
$configuration = new Configuration([new DefaultTransportFactory()]);
$processor = new Processor();
$processor->processConfiguration($configuration, [[
'transport' => [
'default' => ['alias' => 'foo'],
],
'client' => [
'default_destination' => '',
],
]]);
}
}
| trustify/oroplatform | src/Oro/Bundle/MessageQueueBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php | PHP | mit | 7,174 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_snprintf_72a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.string.label.xml
Template File: sources-sink-72a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using malloc() and set data pointer to a small buffer
* GoodSource: Allocate using malloc() and set data pointer to a large buffer
* Sinks: snprintf
* BadSink : Copy string to data using snprintf
* Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <vector>
#include <wchar.h>
using namespace std;
namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_snprintf_72
{
#ifndef OMITBAD
/* bad function declaration */
void badSink(vector<char *> dataVector);
void bad()
{
char * data;
vector<char *> dataVector;
data = NULL;
/* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = (char *)malloc(50*sizeof(char));
data[0] = '\0'; /* null terminate */
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
badSink(dataVector);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(vector<char *> dataVector);
static void goodG2B()
{
char * data;
vector<char *> dataVector;
data = NULL;
/* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = (char *)malloc(100*sizeof(char));
data[0] = '\0'; /* null terminate */
/* Put data in a vector */
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
dataVector.insert(dataVector.end(), 1, data);
goodG2BSink(dataVector);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_snprintf_72; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| maurer/tiamat | samples/Juliet/testcases/CWE122_Heap_Based_Buffer_Overflow/s08/CWE122_Heap_Based_Buffer_Overflow__c_CWE805_char_snprintf_72a.cpp | C++ | mit | 3,040 |
import core from 'core-js';
var originStorage = new Map();
function ensureType(value){
if(value instanceof Origin){
return value;
}
return new Origin(value);
}
/**
* A metadata annotation that describes the origin module of the function to which it's attached.
*
* @class Origin
* @constructor
* @param {string} moduleId The origin module id.
* @param {string} moduleMember The name of the export in the origin module.
*/
export class Origin {
constructor(moduleId, moduleMember){
this.moduleId = moduleId;
this.moduleMember = moduleMember;
}
/**
* Get the Origin annotation for the specified function.
*
* @method get
* @static
* @param {Function} fn The function to inspect for Origin metadata.
* @return {Origin} Returns the Origin metadata.
*/
static get(fn){
var origin = originStorage.get(fn);
if(origin !== undefined){
return origin;
}
if(typeof fn.origin === 'function'){
originStorage.set(fn, origin = ensureType(fn.origin()));
} else if(fn.origin !== undefined){
originStorage.set(fn, origin = ensureType(fn.origin));
}
return origin;
}
/**
* Set the Origin annotation for the specified function.
*
* @method set
* @static
* @param {Function} fn The function to set the Origin metadata on.
* @param {origin} fn The Origin metadata to store on the function.
* @return {Origin} Returns the Origin metadata.
*/
static set(fn, origin){
if(Origin.get(fn) === undefined){
originStorage.set(fn, origin);
}
}
}
| behzad88/aurelia-ts-port | aurelia-latest/metadata/origin.js | JavaScript | mit | 1,546 |
import numpy as np
import cv2
import matplotlib.image as mpimg
import pickle
from line import Line
from warp_transformer import WarpTransformer
from moviepy.editor import VideoFileClip
calibration_mtx_dist_filename = 'dist_pickle.p'
# load mtx, dist
dist_pickle = pickle.load(open(calibration_mtx_dist_filename, "rb" ))
mtx = dist_pickle["mtx"]
dist = dist_pickle["dist"]
def binary_image_via_threshold(img, s_thresh=(170, 255), sx_thresh=(20, 100)):
'''
From Advanced Lane Finding lesson, section 30
'''
img = np.copy(img)
# Convert to HLS color space and separate the V channel
hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float)
l_channel = hls[:,:,1]
s_channel = hls[:,:,2]
# Sobel x
sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x
abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal
scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx))
# Threshold x gradient
sxbinary = np.zeros_like(scaled_sobel)
sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1
# Threshold color channel
s_binary = np.zeros_like(s_channel)
s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1
# combined them here.
combined = np.zeros_like(s_channel)
combined[(sxbinary == 1) | (s_binary == 1)] = 1
return combined
# Perspective transform
src = np.array([[262, 677], [580, 460], [703, 460], [1040, 677]]).astype(np.float32)
dst = np.array([[262, 720], [262, 0], [1040, 0], [1040, 720]]).astype(np.float32)
# Create transformer object
transformer = WarpTransformer(src, dst)
left_line = Line()
right_line = Line()
def non_sliding(binary_warped, line):
nonzero = binary_warped.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
margin = 100
left_fit = left_line.current_fit
right_fit = right_line.current_fit
left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] - margin))
& (nonzerox < (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] + margin)))
right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] - margin))
& (nonzerox < (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] + margin)))
# Extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
if line == 'left':
return leftx, lefty
elif line == 'right':
return rightx, righty
def sliding_window(binary_warped, line):
out_img = (np.dstack((binary_warped, binary_warped, binary_warped)) * 255).astype(np.uint8)
histogram = np.sum(binary_warped[int(binary_warped.shape[0]/2):,:], axis=0)
# Find the peak of the left and right halves of the histogram
# These will be the starting point for the left and right lines
midpoint = np.int(histogram.shape[0]/2)
leftx_base = np.argmax(histogram[:midpoint])
rightx_base = np.argmax(histogram[midpoint:]) + midpoint
# Choose the number of sliding windows
nwindows = 9
# Set height of windows
window_height = np.int(binary_warped.shape[0]/nwindows)
# Identify the x and y positions of all nonzero pixels in the image
nonzero = binary_warped.nonzero()
nonzeroy = np.array(nonzero[0])
nonzerox = np.array(nonzero[1])
# Current positions to be updated for each window
leftx_current = leftx_base
rightx_current = rightx_base
# Set the width of the windows +/- margin
margin = 100
# Set minimum number of pixels found to recenter window
minpix = 50
# Create empty lists to receive left and right lane pixel indices
left_lane_inds = []
right_lane_inds = []
# Step through the windows one by one
for window in range(nwindows):
# Identify window boundaries in x and y (and right and left)
win_y_low = binary_warped.shape[0] - (window+1)*window_height
win_y_high = binary_warped.shape[0] - window*window_height
win_xleft_low = leftx_current - margin
win_xleft_high = leftx_current + margin
win_xright_low = rightx_current - margin
win_xright_high = rightx_current + margin
# Draw the windows on the visualization image
cv2.rectangle(out_img, (win_xleft_low,win_y_low), (win_xleft_high,win_y_high), color=(0,255,0), thickness=2) # Green
cv2.rectangle(out_img, (win_xright_low,win_y_low), (win_xright_high,win_y_high), color=(0,255,0), thickness=2) # Green
# Identify the nonzero pixels in x and y within the window
good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0]
good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0]
# Append these indices to the lists
left_lane_inds.append(good_left_inds)
right_lane_inds.append(good_right_inds)
# If you found > minpix pixels, recenter next window on their mean position
if len(good_left_inds) > minpix:
leftx_current = np.int(np.mean(nonzerox[good_left_inds]))
if len(good_right_inds) > minpix:
rightx_current = np.int(np.mean(nonzerox[good_right_inds]))
# Concatenate the arrays of indices
left_lane_inds = np.concatenate(left_lane_inds)
right_lane_inds = np.concatenate(right_lane_inds)
# Extract left and right line pixel positions
leftx = nonzerox[left_lane_inds]
lefty = nonzeroy[left_lane_inds]
rightx = nonzerox[right_lane_inds]
righty = nonzeroy[right_lane_inds]
if line == 'left':
return leftx, lefty
elif line == 'right':
return rightx, righty
def pipeline(start_img):
'''
Incoming image must be RGB!!
'''
undist = cv2.undistort(start_img, mtx, dist, None, mtx)
combined = binary_image_via_threshold(undist)
binary_warped = transformer.to_birdview(combined)
# Check if line was detected in previous frame:
if left_line.detected == True:
leftx, lefty = non_sliding(binary_warped, 'left')
elif left_line.detected == False:
leftx, lefty = sliding_window(binary_warped, 'left')
left_line.detected = True
if right_line.detected == True:
rightx, righty = non_sliding(binary_warped, 'right')
elif right_line.detected == False:
rightx, righty = sliding_window(binary_warped, 'right')
right_line.detected = True
# Fit a second order polynomial to each
left_fit = np.polyfit(lefty, leftx, 2)
right_fit = np.polyfit(righty, rightx, 2)
# Stash away polynomials
left_line.current_fit = left_fit
right_line.current_fit = right_fit
# Generate x and y values for plotting
ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0])
left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2]
right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2]
# Define conversions in x and y from pixels space to meters
ym_per_pix = 30/720 # meters per pixel in y dimension
xm_per_pix = 3.7/700 # meters per pixel in x dimension
# Fit new polynomials to x,y in world space
left_fit_cr = np.polyfit(lefty*ym_per_pix, leftx*xm_per_pix, deg=2)
right_fit_cr = np.polyfit(righty*ym_per_pix, rightx*xm_per_pix, deg=2)
# Calculate radii of curvature in meters
y_eval = np.max(ploty) # Where radius of curvature is measured
left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0])
right_curverad = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0])
midpoint = np.int(start_img.shape[1]/2)
middle_of_lane = (right_fitx[-1] - left_fitx[-1]) / 2.0 + left_fitx[-1]
offset = (midpoint - middle_of_lane) * xm_per_pix
# Create an image to draw the lines on
warped_zero = np.zeros_like(binary_warped).astype(np.uint8)
color_warped = np.dstack((warped_zero, warped_zero, warped_zero))
# Recast the x and y points into usable format for cv2.fillPoly()
pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))])
pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))])
pts = np.hstack((pts_left, pts_right))
# Draw the lane onto the warped blank image
cv2.fillPoly(color_warped, np.int_([pts]), (0,255, 0))
# Warp the blank back to original image space using inverse perspective matrix (Minv)
unwarped = transformer.to_normal(color_warped)
# Combine the result with the original image
result = cv2.addWeighted(undist, 1, unwarped, 0.3, 0)
radius = np.mean([left_curverad, right_curverad])
# Add radius and offset calculations to top of video
cv2.putText(result,"Curvature Radius: " + "{:0.2f}".format(radius) + ' m', org=(50,50), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=2, color=(0,0,0), lineType = cv2.LINE_AA, thickness=2)
cv2.putText(result,"Lane center offset: " + "{:0.2f}".format(offset) + ' m', org=(50,100), fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=2, color=(0,0,0), lineType = cv2.LINE_AA, thickness=2)
return result
if __name__ == '__main__':
movie_output = 'final_output.mp4'
clip1 = VideoFileClip("project_video.mp4")
driving_clip = clip1.fl_image(pipeline)
driving_clip.write_videofile(movie_output, audio=False)
| mez/carnd | P4_advance_lane_finding/main.py | Python | mit | 9,709 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyFramework.ServiceModel
{
/// <summary>
/// 通用的服务返回结果.
/// </summary>
public class CommonServiceResult<T>
{
public CommonServiceResult()
{
}
public CommonServiceResult(Exception ex)
{
this.ResultCode = "SYSTEM_EXCEPTION";
this.ResultMessage = ex.Message;
}
/// <summary>
/// 结果码.
/// </summary>
public string ResultCode { set; get; }
/// <summary>
/// 结果消息.
/// </summary>
public string ResultMessage { set; get; }
/// <summary>
/// 结果数据.
/// </summary>
public T ResultData { set; get; }
/// <summary>
/// 是否执行成功.
/// </summary>
public bool IsSuccess
{
get
{
return this.ResultCode == ResultCodeIsSuccess;
}
}
public override string ToString()
{
StringBuilder buff = new StringBuilder();
buff.AppendLine(this.ResultCode.ToString());
buff.AppendLine(this.ResultMessage);
return buff.ToString();
}
/// <summary>
/// 处理成功.
/// </summary>
public const string ResultCodeIsSuccess = "0";
/// <summary>
/// 默认的,成功的执行结果.
/// </summary>
public static readonly CommonServiceResult<T> DefaultSuccessResult = new CommonServiceResult<T>()
{
ResultCode = ResultCodeIsSuccess,
ResultMessage = "success",
};
/// <summary>
/// 数据不存在.
/// </summary>
public const string ResultCodeIsDataNotFound = "COMMON_DATA_NOT_FOUND";
/// <summary>
/// 默认的,数据不存在的执行结果.
/// </summary>
public static readonly CommonServiceResult<T> DataNotFoundResult = new CommonServiceResult<T>()
{
ResultCode = ResultCodeIsDataNotFound,
ResultMessage = "数据不存在!",
};
/// <summary>
/// 数据已存在.
/// </summary>
public const string ResultCodeIsDataHadExists = "COMMON_DATA_HAD_EXISTS";
/// <summary>
/// 默认的,数据已存在的执行结果.
/// </summary>
public static readonly CommonServiceResult<T> DataHadExistsResult = new CommonServiceResult<T>()
{
ResultCode = ResultCodeIsDataHadExists,
ResultMessage = "数据已存在!",
};
/// <summary>
/// 创建默认的成功的结果.
/// </summary>
/// <param name="resultData"></param>
/// <returns></returns>
public static CommonServiceResult<T> CreateDefaultSuccessResult(T resultData)
{
CommonServiceResult<T> result = new CommonServiceResult<T>()
{
ResultCode = ResultCodeIsSuccess,
ResultMessage = "success",
ResultData = resultData
};
return result;
}
/// <summary>
/// 复制结果.
/// </summary>
/// <param name="commonServiceResult"></param>
/// <returns></returns>
public static CommonServiceResult<T> CopyFrom(CommonServiceResult commonServiceResult)
{
CommonServiceResult<T> result = new CommonServiceResult<T>()
{
ResultCode = commonServiceResult.ResultCode,
ResultMessage = commonServiceResult.ResultMessage
};
return result;
}
}
public class CommonServiceResult : CommonServiceResult<dynamic> {
public CommonServiceResult()
{
}
public CommonServiceResult(Exception ex)
{
this.ResultCode = "SYSTEM_EXCEPTION";
this.ResultMessage = ex.Message;
}
/// <summary>
/// 默认的,成功的执行结果.
/// </summary>
public new static readonly CommonServiceResult DefaultSuccessResult = new CommonServiceResult()
{
ResultCode = ResultCodeIsSuccess,
ResultMessage = "success",
};
/// <summary>
/// 默认的,数据不存在的执行结果.
/// </summary>
public new static readonly CommonServiceResult DataNotFoundResult = new CommonServiceResult()
{
ResultCode = ResultCodeIsDataNotFound,
ResultMessage = "数据不存在!",
};
/// <summary>
/// 默认的,数据已存在的执行结果.
/// </summary>
public new static readonly CommonServiceResult DataHadExistsResult = new CommonServiceResult()
{
ResultCode = ResultCodeIsDataHadExists,
ResultMessage = "数据已存在!",
};
/// <summary>
/// 创建默认的成功的结果.
/// </summary>
/// <param name="resultData"></param>
/// <returns></returns>
public new static CommonServiceResult CreateDefaultSuccessResult(dynamic resultData)
{
CommonServiceResult result = new CommonServiceResult()
{
ResultCode = ResultCodeIsSuccess,
ResultMessage = "success",
ResultData = resultData
};
return result;
}
}
}
| wangzhiqing999/my-csharp-project | MyFramework.Service/ServiceModel/CommonServiceResult.cs | C# | mit | 5,657 |
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {CommonModule, Location} from '@angular/common';
import {SpyLocation} from '@angular/common/testing';
import {ChangeDetectionStrategy, Component, Injectable, NgModule, NgModuleFactoryLoader, NgModuleRef, NgZone, OnDestroy, ɵConsole as Console, ɵNoopNgZone as NoopNgZone} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, inject, tick} from '@angular/core/testing';
import {By} from '@angular/platform-browser/src/dom/debug/by';
import {expect} from '@angular/platform-browser/testing/src/matchers';
import {ActivatedRoute, ActivatedRouteSnapshot, ActivationEnd, ActivationStart, CanActivate, CanDeactivate, ChildActivationEnd, ChildActivationStart, DefaultUrlSerializer, DetachedRouteHandle, Event, GuardsCheckEnd, GuardsCheckStart, Navigation, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, PRIMARY_OUTLET, ParamMap, Params, PreloadAllModules, PreloadingStrategy, Resolve, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouteReuseStrategy, Router, RouterEvent, RouterModule, RouterPreloader, RouterStateSnapshot, RoutesRecognized, RunGuardsAndResolvers, UrlHandlingStrategy, UrlSegmentGroup, UrlSerializer, UrlTree} from '@angular/router';
import {Observable, Observer, Subscription, of } from 'rxjs';
import {filter, first, map, tap} from 'rxjs/operators';
import {forEach} from '../src/utils/collection';
import {RouterTestingModule, SpyNgModuleFactoryLoader} from '../testing';
describe('Integration', () => {
const noopConsole: Console = {log() {}, warn() {}};
beforeEach(() => {
TestBed.configureTestingModule({
imports:
[RouterTestingModule.withRoutes([{path: 'simple', component: SimpleCmp}]), TestModule],
providers: [{provide: Console, useValue: noopConsole}]
});
});
it('should navigate with a provided config',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.navigateByUrl('/simple');
advance(fixture);
expect(location.path()).toEqual('/simple');
})));
it('should navigate from ngOnInit hook',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
router.resetConfig([
{path: '', component: SimpleCmp},
{path: 'one', component: RouteCmp},
]);
const fixture = createRoot(router, RootCmpWithOnInit);
expect(location.path()).toEqual('/one');
expect(fixture.nativeElement).toHaveText('route');
})));
describe('navigation', function() {
it('should navigate to the current URL', fakeAsync(inject([Router], (router: Router) => {
router.onSameUrlNavigation = 'reload';
router.resetConfig([
{path: '', component: SimpleCmp},
{path: 'simple', component: SimpleCmp},
]);
const fixture = createRoot(router, RootCmp);
const events: Event[] = [];
router.events.subscribe(e => onlyNavigationStartAndEnd(e) && events.push(e));
router.navigateByUrl('/simple');
tick();
router.navigateByUrl('/simple');
tick();
expectEvents(events, [
[NavigationStart, '/simple'], [NavigationEnd, '/simple'], [NavigationStart, '/simple'],
[NavigationEnd, '/simple']
]);
})));
describe('relativeLinkResolution', () => {
beforeEach(inject([Router], (router: Router) => {
router.resetConfig([{
path: 'foo',
children: [{path: 'bar', children: [{path: '', component: RelativeLinkCmp}]}]
}]);
}));
it('should not ignore empty paths in legacy mode',
fakeAsync(inject([Router], (router: Router) => {
router.relativeLinkResolution = 'legacy';
const fixture = createRoot(router, RootCmp);
router.navigateByUrl('/foo/bar');
advance(fixture);
const link = fixture.nativeElement.querySelector('a');
expect(link.getAttribute('href')).toEqual('/foo/bar/simple');
})));
it('should ignore empty paths in corrected mode',
fakeAsync(inject([Router], (router: Router) => {
router.relativeLinkResolution = 'corrected';
const fixture = createRoot(router, RootCmp);
router.navigateByUrl('/foo/bar');
advance(fixture);
const link = fixture.nativeElement.querySelector('a');
expect(link.getAttribute('href')).toEqual('/foo/simple');
})));
});
it('should set the restoredState to null when executing imperative navigations',
fakeAsync(inject([Router], (router: Router) => {
router.resetConfig([
{path: '', component: SimpleCmp},
{path: 'simple', component: SimpleCmp},
]);
const fixture = createRoot(router, RootCmp);
let event: NavigationStart;
router.events.subscribe(e => {
if (e instanceof NavigationStart) {
event = e;
}
});
router.navigateByUrl('/simple');
tick();
expect(event !.navigationTrigger).toEqual('imperative');
expect(event !.restoredState).toEqual(null);
})));
it('should set history.state if passed using imperative navigation',
fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => {
router.resetConfig([
{path: '', component: SimpleCmp},
{path: 'simple', component: SimpleCmp},
]);
const fixture = createRoot(router, RootCmp);
let navigation: Navigation = null !;
router.events.subscribe(e => {
if (e instanceof NavigationStart) {
navigation = router.getCurrentNavigation() !;
}
});
router.navigateByUrl('/simple', {state: {foo: 'bar'}});
tick();
const history = (location as any)._history;
expect(history[history.length - 1].state.foo).toBe('bar');
expect(history[history.length - 1].state)
.toEqual({foo: 'bar', navigationId: history.length});
expect(navigation.extras.state).toBeDefined();
expect(navigation.extras.state).toEqual({foo: 'bar'});
})));
it('should not pollute browser history when replaceUrl is set to true',
fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => {
router.resetConfig([
{path: '', component: SimpleCmp}, {path: 'a', component: SimpleCmp},
{path: 'b', component: SimpleCmp}
]);
const fixture = createRoot(router, RootCmp);
router.navigateByUrl('/a', {replaceUrl: true});
router.navigateByUrl('/b', {replaceUrl: true});
tick();
expect(location.urlChanges).toEqual(['replace: /', 'replace: /b']);
})));
it('should skip navigation if another navigation is already scheduled',
fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => {
router.resetConfig([
{path: '', component: SimpleCmp}, {path: 'a', component: SimpleCmp},
{path: 'b', component: SimpleCmp}
]);
const fixture = createRoot(router, RootCmp);
router.navigate(
['/a'], {queryParams: {a: true}, queryParamsHandling: 'merge', replaceUrl: true});
router.navigate(
['/b'], {queryParams: {b: true}, queryParamsHandling: 'merge', replaceUrl: true});
tick();
/**
* Why do we have '/b?b=true' and not '/b?a=true&b=true'?
*
* This is because the router has the right to stop a navigation mid-flight if another
* navigation has been already scheduled. This is why we can use a top-level guard
* to perform redirects. Calling `navigate` in such a guard will stop the navigation, and
* the components won't be instantiated.
*
* This is a fundamental property of the router: it only cares about its latest state.
*
* This means that components should only map params to something else, not reduce them.
* In other words, the following component is asking for trouble:
*
* ```
* class MyComponent {
* constructor(a: ActivatedRoute) {
* a.params.scan(...)
* }
* }
* ```
*
* This also means "queryParamsHandling: 'merge'" should only be used to merge with
* long-living query parameters (e.g., debug).
*/
expect(router.url).toEqual('/b?b=true');
})));
});
describe('navigation warning', () => {
let warnings: string[] = [];
class MockConsole {
warn(message: string) { warnings.push(message); }
}
beforeEach(() => {
warnings = [];
TestBed.overrideProvider(Console, {useValue: new MockConsole()});
});
describe('with NgZone enabled', () => {
it('should warn when triggered outside Angular zone',
fakeAsync(inject([Router, NgZone], (router: Router, ngZone: NgZone) => {
ngZone.runOutsideAngular(() => { router.navigateByUrl('/simple'); });
expect(warnings.length).toBe(1);
expect(warnings[0])
.toBe(
`Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?`);
})));
it('should not warn when triggered inside Angular zone',
fakeAsync(inject([Router, NgZone], (router: Router, ngZone: NgZone) => {
ngZone.run(() => { router.navigateByUrl('/simple'); });
expect(warnings.length).toBe(0);
})));
});
describe('with NgZone disabled', () => {
beforeEach(() => { TestBed.overrideProvider(NgZone, {useValue: new NoopNgZone()}); });
it('should not warn when triggered outside Angular zone',
fakeAsync(inject([Router, NgZone], (router: Router, ngZone: NgZone) => {
ngZone.runOutsideAngular(() => { router.navigateByUrl('/simple'); });
expect(warnings.length).toBe(0);
})));
});
});
describe('should execute navigations serially', () => {
let log: any[] = [];
beforeEach(() => {
log = [];
TestBed.configureTestingModule({
providers: [
{
provide: 'trueRightAway',
useValue: () => {
log.push('trueRightAway');
return true;
}
},
{
provide: 'trueIn2Seconds',
useValue: () => {
log.push('trueIn2Seconds-start');
let res: any = null;
const p = new Promise(r => res = r);
setTimeout(() => {
log.push('trueIn2Seconds-end');
res(true);
}, 2000);
return p;
}
}
]
});
});
describe('should advance the parent route after deactivating its children', () => {
@Component({template: '<router-outlet></router-outlet>'})
class Parent {
constructor(route: ActivatedRoute) {
route.params.subscribe((s: any) => { log.push(s); });
}
}
@Component({template: 'child1'})
class Child1 {
ngOnDestroy() { log.push('child1 destroy'); }
}
@Component({template: 'child2'})
class Child2 {
constructor() { log.push('child2 constructor'); }
}
@NgModule({
declarations: [Parent, Child1, Child2],
entryComponents: [Parent, Child1, Child2],
imports: [RouterModule]
})
class TestModule {
}
beforeEach(() => TestBed.configureTestingModule({imports: [TestModule]}));
it('should work',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'parent/:id',
component: Parent,
children: [
{path: 'child1', component: Child1},
{path: 'child2', component: Child2},
]
}]);
router.navigateByUrl('/parent/1/child1');
advance(fixture);
router.navigateByUrl('/parent/2/child2');
advance(fixture);
expect(location.path()).toEqual('/parent/2/child2');
expect(log).toEqual([
{id: '1'},
'child1 destroy',
{id: '2'},
'child2 constructor',
]);
})));
});
it('should not wait for prior navigations to start a new navigation',
fakeAsync(inject([Router, Location], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'a', component: SimpleCmp, canActivate: ['trueRightAway', 'trueIn2Seconds']},
{path: 'b', component: SimpleCmp, canActivate: ['trueRightAway', 'trueIn2Seconds']}
]);
router.navigateByUrl('/a');
tick(100);
fixture.detectChanges();
router.navigateByUrl('/b');
tick(100); // 200
fixture.detectChanges();
expect(log).toEqual(
['trueRightAway', 'trueIn2Seconds-start', 'trueRightAway', 'trueIn2Seconds-start']);
tick(2000); // 2200
fixture.detectChanges();
expect(log).toEqual([
'trueRightAway', 'trueIn2Seconds-start', 'trueRightAway', 'trueIn2Seconds-start',
'trueIn2Seconds-end', 'trueIn2Seconds-end'
]);
})));
});
it('Should work inside ChangeDetectionStrategy.OnPush components', fakeAsync(() => {
@Component({
selector: 'root-cmp',
template: `<router-outlet></router-outlet>`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
class OnPushOutlet {
}
@Component({selector: 'need-cd', template: `{{'it works!'}}`})
class NeedCdCmp {
}
@NgModule({
declarations: [OnPushOutlet, NeedCdCmp],
entryComponents: [OnPushOutlet, NeedCdCmp],
imports: [RouterModule],
})
class TestModule {
}
TestBed.configureTestingModule({imports: [TestModule]});
const router: Router = TestBed.get(Router);
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'on',
component: OnPushOutlet,
children: [{
path: 'push',
component: NeedCdCmp,
}],
}]);
advance(fixture);
router.navigateByUrl('on');
advance(fixture);
router.navigateByUrl('on/push');
advance(fixture);
expect(fixture.nativeElement).toHaveText('it works!');
}));
it('should not error when no url left and no children are matching',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [{path: 'simple', component: SimpleCmp}]
}]);
router.navigateByUrl('/team/33/simple');
advance(fixture);
expect(location.path()).toEqual('/team/33/simple');
expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]');
})));
it('should work when an outlet is in an ngIf',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'child',
component: OutletInNgIf,
children: [{path: 'simple', component: SimpleCmp}]
}]);
router.navigateByUrl('/child/simple');
advance(fixture);
expect(location.path()).toEqual('/child/simple');
})));
it('should work when an outlet is added/removed', fakeAsync(() => {
@Component({
selector: 'someRoot',
template: `[<div *ngIf="cond"><router-outlet></router-outlet></div>]`
})
class RootCmpWithLink {
cond: boolean = true;
}
TestBed.configureTestingModule({declarations: [RootCmpWithLink]});
const router: Router = TestBed.get(Router);
const fixture = createRoot(router, RootCmpWithLink);
router.resetConfig([
{path: 'simple', component: SimpleCmp},
{path: 'blank', component: BlankCmp},
]);
router.navigateByUrl('/simple');
advance(fixture);
expect(fixture.nativeElement).toHaveText('[simple]');
fixture.componentInstance.cond = false;
advance(fixture);
expect(fixture.nativeElement).toHaveText('[]');
fixture.componentInstance.cond = true;
advance(fixture);
expect(fixture.nativeElement).toHaveText('[simple]');
}));
it('should update location when navigating', fakeAsync(() => {
@Component({template: `record`})
class RecordLocationCmp {
private storedPath: string;
constructor(loc: Location) { this.storedPath = loc.path(); }
}
@NgModule({declarations: [RecordLocationCmp], entryComponents: [RecordLocationCmp]})
class TestModule {
}
TestBed.configureTestingModule({imports: [TestModule]});
const router = TestBed.get(Router);
const location = TestBed.get(Location);
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'record/:id', component: RecordLocationCmp}]);
router.navigateByUrl('/record/22');
advance(fixture);
const c = fixture.debugElement.children[1].componentInstance;
expect(location.path()).toEqual('/record/22');
expect(c.storedPath).toEqual('/record/22');
router.navigateByUrl('/record/33');
advance(fixture);
expect(location.path()).toEqual('/record/33');
}));
it('should skip location update when using NavigationExtras.skipLocationChange with navigateByUrl',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = TestBed.createComponent(RootCmp);
advance(fixture);
router.resetConfig([{path: 'team/:id', component: TeamCmp}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]');
router.navigateByUrl('/team/33', {skipLocationChange: true});
advance(fixture);
expect(location.path()).toEqual('/team/22');
expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]');
})));
it('should skip location update when using NavigationExtras.skipLocationChange with navigate',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = TestBed.createComponent(RootCmp);
advance(fixture);
router.resetConfig([{path: 'team/:id', component: TeamCmp}]);
router.navigate(['/team/22']);
advance(fixture);
expect(location.path()).toEqual('/team/22');
expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]');
router.navigate(['/team/33'], {skipLocationChange: true});
advance(fixture);
expect(location.path()).toEqual('/team/22');
expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]');
})));
it('should navigate after navigation with skipLocationChange',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = TestBed.createComponent(RootCmpWithNamedOutlet);
advance(fixture);
router.resetConfig([{path: 'show', outlet: 'main', component: SimpleCmp}]);
router.navigate([{outlets: {main: 'show'}}], {skipLocationChange: true});
advance(fixture);
expect(location.path()).toEqual('');
expect(fixture.nativeElement).toHaveText('main [simple]');
router.navigate([{outlets: {main: null}}], {skipLocationChange: true});
advance(fixture);
expect(location.path()).toEqual('');
expect(fixture.nativeElement).toHaveText('main []');
})));
describe('"eager" urlUpdateStrategy', () => {
beforeEach(() => {
const serializer = new DefaultUrlSerializer();
TestBed.configureTestingModule({
providers: [{
provide: 'authGuardFail',
useValue: (a: any, b: any) => {
return new Promise(res => { setTimeout(() => res(serializer.parse('/login')), 1); });
}
}]
});
});
it('should eagerly update the URL with urlUpdateStrategy="eagar"',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = TestBed.createComponent(RootCmp);
advance(fixture);
router.resetConfig([{path: 'team/:id', component: TeamCmp}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]');
router.urlUpdateStrategy = 'eager';
(router as any).hooks.beforePreactivation = () => {
expect(location.path()).toEqual('/team/33');
expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]');
return of (null);
};
router.navigateByUrl('/team/33');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]');
})));
it('should eagerly update the URL with urlUpdateStrategy="eagar"',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = TestBed.createComponent(RootCmp);
advance(fixture);
router.urlUpdateStrategy = 'eager';
router.resetConfig([
{path: 'team/:id', component: SimpleCmp, canActivate: ['authGuardFail']},
{path: 'login', component: AbsoluteSimpleLinkCmp}
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
// Redirects to /login
advance(fixture, 1);
expect(location.path()).toEqual('/login');
// Perform the same logic again, and it should produce the same result
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
// Redirects to /login
advance(fixture, 1);
expect(location.path()).toEqual('/login');
})));
it('should eagerly update URL after redirects are applied with urlUpdateStrategy="eagar"',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = TestBed.createComponent(RootCmp);
advance(fixture);
router.resetConfig([{path: 'team/:id', component: TeamCmp}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]');
router.urlUpdateStrategy = 'eager';
let urlAtNavStart = '';
let urlAtRoutesRecognized = '';
router.events.subscribe(e => {
if (e instanceof NavigationStart) {
urlAtNavStart = location.path();
}
if (e instanceof RoutesRecognized) {
urlAtRoutesRecognized = location.path();
}
});
router.navigateByUrl('/team/33');
advance(fixture);
expect(urlAtNavStart).toBe('/team/22');
expect(urlAtRoutesRecognized).toBe('/team/33');
expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]');
})));
});
it('should navigate back and forward',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children:
[{path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp}]
}]);
let event: NavigationStart;
router.events.subscribe(e => {
if (e instanceof NavigationStart) {
event = e;
}
});
router.navigateByUrl('/team/33/simple');
advance(fixture);
expect(location.path()).toEqual('/team/33/simple');
const simpleNavStart = event !;
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
const userVictorNavStart = event !;
location.back();
advance(fixture);
expect(location.path()).toEqual('/team/33/simple');
expect(event !.navigationTrigger).toEqual('hashchange');
expect(event !.restoredState !.navigationId).toEqual(simpleNavStart.id);
location.forward();
advance(fixture);
expect(location.path()).toEqual('/team/22/user/victor');
expect(event !.navigationTrigger).toEqual('hashchange');
expect(event !.restoredState !.navigationId).toEqual(userVictorNavStart.id);
})));
it('should navigate to the same url when config changes',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'a', component: SimpleCmp}]);
router.navigate(['/a']);
advance(fixture);
expect(location.path()).toEqual('/a');
expect(fixture.nativeElement).toHaveText('simple');
router.resetConfig([{path: 'a', component: RouteCmp}]);
router.navigate(['/a']);
advance(fixture);
expect(location.path()).toEqual('/a');
expect(fixture.nativeElement).toHaveText('route');
})));
it('should navigate when locations changes',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [{path: 'user/:name', component: UserCmp}]
}]);
const recordedEvents: any[] = [];
router.events.forEach(e => onlyNavigationStartAndEnd(e) && recordedEvents.push(e));
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
(<any>location).simulateHashChange('/team/22/user/fedor');
advance(fixture);
(<any>location).simulateUrlPop('/team/22/user/fedor');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user fedor, right: ]');
expectEvents(recordedEvents, [
[NavigationStart, '/team/22/user/victor'], [NavigationEnd, '/team/22/user/victor'],
[NavigationStart, '/team/22/user/fedor'], [NavigationEnd, '/team/22/user/fedor']
]);
})));
it('should update the location when the matched route does not change',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: '**', component: CollectParamsCmp}]);
router.navigateByUrl('/one/two');
advance(fixture);
const cmp = fixture.debugElement.children[1].componentInstance;
expect(location.path()).toEqual('/one/two');
expect(fixture.nativeElement).toHaveText('collect-params');
expect(cmp.recordedUrls()).toEqual(['one/two']);
router.navigateByUrl('/three/four');
advance(fixture);
expect(location.path()).toEqual('/three/four');
expect(fixture.nativeElement).toHaveText('collect-params');
expect(cmp.recordedUrls()).toEqual(['one/two', 'three/four']);
})));
describe('should reset location if a navigation by location is successful', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{
provide: 'in1Second',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
let res: any = null;
const p = new Promise(_ => res = _);
setTimeout(() => res(true), 1000);
return p;
}
}]
});
});
it('work', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'simple', component: SimpleCmp, canActivate: ['in1Second']}]);
// Trigger two location changes to the same URL.
// Because of the guard the order will look as follows:
// - location change 'simple'
// - start processing the change, start a guard
// - location change 'simple'
// - the first location change gets canceled, the URL gets reset to '/'
// - the second location change gets finished, the URL should be reset to '/simple'
(<any>location).simulateUrlPop('/simple');
(<any>location).simulateUrlPop('/simple');
tick(2000);
advance(fixture);
expect(location.path()).toEqual('/simple');
})));
});
it('should support secondary routes', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{path: 'simple', component: SimpleCmp, outlet: 'right'}
]
}]);
router.navigateByUrl('/team/22/(user/victor//right:simple)');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: simple ]');
})));
it('should support secondary routes in separate commands',
fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{path: 'simple', component: SimpleCmp, outlet: 'right'}
]
}]);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
router.navigate(['team/22', {outlets: {right: 'simple'}}]);
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: simple ]');
})));
it('should deactivate outlets', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{path: 'simple', component: SimpleCmp, outlet: 'right'}
]
}]);
router.navigateByUrl('/team/22/(user/victor//right:simple)');
advance(fixture);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: ]');
})));
it('should deactivate nested outlets', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{path: 'simple', component: SimpleCmp, outlet: 'right'}
]
},
{path: '', component: BlankCmp}
]);
router.navigateByUrl('/team/22/(user/victor//right:simple)');
advance(fixture);
router.navigateByUrl('/');
advance(fixture);
expect(fixture.nativeElement).toHaveText('');
})));
it('should set query params and fragment', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'query', component: QueryParamsAndFragmentCmp}]);
router.navigateByUrl('/query?name=1#fragment1');
advance(fixture);
expect(fixture.nativeElement).toHaveText('query: 1 fragment: fragment1');
router.navigateByUrl('/query?name=2#fragment2');
advance(fixture);
expect(fixture.nativeElement).toHaveText('query: 2 fragment: fragment2');
})));
it('should ignore null and undefined query params',
fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'query', component: EmptyQueryParamsCmp}]);
router.navigate(['query'], {queryParams: {name: 1, age: null, page: undefined}});
advance(fixture);
const cmp = fixture.debugElement.children[1].componentInstance;
expect(cmp.recordedParams).toEqual([{name: '1'}]);
})));
it('should throw an error when one of the commands is null/undefined',
fakeAsync(inject([Router], (router: Router) => {
createRoot(router, RootCmp);
router.resetConfig([{path: 'query', component: EmptyQueryParamsCmp}]);
expect(() => router.navigate([
undefined, 'query'
])).toThrowError(`The requested path contains undefined segment at index 0`);
})));
it('should push params only when they change', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [{path: 'user/:name', component: UserCmp}]
}]);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
const team = fixture.debugElement.children[1].componentInstance;
const user = fixture.debugElement.children[1].children[1].componentInstance;
expect(team.recordedParams).toEqual([{id: '22'}]);
expect(team.snapshotParams).toEqual([{id: '22'}]);
expect(user.recordedParams).toEqual([{name: 'victor'}]);
expect(user.snapshotParams).toEqual([{name: 'victor'}]);
router.navigateByUrl('/team/22/user/fedor');
advance(fixture);
expect(team.recordedParams).toEqual([{id: '22'}]);
expect(team.snapshotParams).toEqual([{id: '22'}]);
expect(user.recordedParams).toEqual([{name: 'victor'}, {name: 'fedor'}]);
expect(user.snapshotParams).toEqual([{name: 'victor'}, {name: 'fedor'}]);
})));
it('should work when navigating to /', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: '', pathMatch: 'full', component: SimpleCmp},
{path: 'user/:name', component: UserCmp}
]);
router.navigateByUrl('/user/victor');
advance(fixture);
expect(fixture.nativeElement).toHaveText('user victor');
router.navigateByUrl('/');
advance(fixture);
expect(fixture.nativeElement).toHaveText('simple');
})));
it('should cancel in-flight navigations', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'user/:name', component: UserCmp}]);
const recordedEvents: any[] = [];
router.events.forEach(e => recordedEvents.push(e));
router.navigateByUrl('/user/init');
advance(fixture);
const user = fixture.debugElement.children[1].componentInstance;
let r1: any, r2: any;
router.navigateByUrl('/user/victor') !.then(_ => r1 = _);
router.navigateByUrl('/user/fedor') !.then(_ => r2 = _);
advance(fixture);
expect(r1).toEqual(false); // returns false because it was canceled
expect(r2).toEqual(true); // returns true because it was successful
expect(fixture.nativeElement).toHaveText('user fedor');
expect(user.recordedParams).toEqual([{name: 'init'}, {name: 'fedor'}]);
expectEvents(recordedEvents, [
[NavigationStart, '/user/init'],
[RoutesRecognized, '/user/init'],
[GuardsCheckStart, '/user/init'],
[ChildActivationStart],
[ActivationStart],
[GuardsCheckEnd, '/user/init'],
[ResolveStart, '/user/init'],
[ResolveEnd, '/user/init'],
[ActivationEnd],
[ChildActivationEnd],
[NavigationEnd, '/user/init'],
[NavigationStart, '/user/victor'],
[NavigationCancel, '/user/victor'],
[NavigationStart, '/user/fedor'],
[RoutesRecognized, '/user/fedor'],
[GuardsCheckStart, '/user/fedor'],
[ChildActivationStart],
[ActivationStart],
[GuardsCheckEnd, '/user/fedor'],
[ResolveStart, '/user/fedor'],
[ResolveEnd, '/user/fedor'],
[ActivationEnd],
[ChildActivationEnd],
[NavigationEnd, '/user/fedor']
]);
})));
it('should handle failed navigations gracefully', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'user/:name', component: UserCmp}]);
const recordedEvents: any[] = [];
router.events.forEach(e => recordedEvents.push(e));
let e: any;
router.navigateByUrl('/invalid') !.catch(_ => e = _);
advance(fixture);
expect(e.message).toContain('Cannot match any routes');
router.navigateByUrl('/user/fedor');
advance(fixture);
expect(fixture.nativeElement).toHaveText('user fedor');
expectEvents(recordedEvents, [
[NavigationStart, '/invalid'], [NavigationError, '/invalid'],
[NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'],
[GuardsCheckStart, '/user/fedor'], [ChildActivationStart], [ActivationStart],
[GuardsCheckEnd, '/user/fedor'], [ResolveStart, '/user/fedor'],
[ResolveEnd, '/user/fedor'], [ActivationEnd], [ChildActivationEnd],
[NavigationEnd, '/user/fedor']
]);
})));
// Errors should behave the same for both deferred and eager URL update strategies
['deferred', 'eager'].forEach((strat: any) => {
it('should dispatch NavigationError after the url has been reset back', fakeAsync(() => {
const router: Router = TestBed.get(Router);
const location: SpyLocation = TestBed.get(Location);
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'simple', component: SimpleCmp}, {path: 'throwing', component: ThrowingCmp}]);
router.urlUpdateStrategy = strat;
router.navigateByUrl('/simple');
advance(fixture);
let routerUrlBeforeEmittingError = '';
let locationUrlBeforeEmittingError = '';
router.events.forEach(e => {
if (e instanceof NavigationError) {
routerUrlBeforeEmittingError = router.url;
locationUrlBeforeEmittingError = location.path();
}
});
router.navigateByUrl('/throwing').catch(() => null);
advance(fixture);
expect(routerUrlBeforeEmittingError).toEqual('/simple');
expect(locationUrlBeforeEmittingError).toEqual('/simple');
}));
it('should reset the url with the right state when navigation errors', fakeAsync(() => {
const router: Router = TestBed.get(Router);
const location: SpyLocation = TestBed.get(Location);
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'simple1', component: SimpleCmp}, {path: 'simple2', component: SimpleCmp},
{path: 'throwing', component: ThrowingCmp}
]);
router.urlUpdateStrategy = strat;
let event: NavigationStart;
router.events.subscribe(e => {
if (e instanceof NavigationStart) {
event = e;
}
});
router.navigateByUrl('/simple1');
advance(fixture);
const simple1NavStart = event !;
router.navigateByUrl('/throwing').catch(() => null);
advance(fixture);
router.navigateByUrl('/simple2');
advance(fixture);
location.back();
tick();
expect(event !.restoredState !.navigationId).toEqual(simple1NavStart.id);
}));
it('should not trigger another navigation when resetting the url back due to a NavigationError',
fakeAsync(() => {
const router = TestBed.get(Router);
router.onSameUrlNavigation = 'reload';
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'simple', component: SimpleCmp}, {path: 'throwing', component: ThrowingCmp}]);
router.urlUpdateStrategy = strat;
const events: any[] = [];
router.events.forEach((e: any) => {
if (e instanceof NavigationStart) {
events.push(e.url);
}
});
router.navigateByUrl('/simple');
advance(fixture);
router.navigateByUrl('/throwing').catch(() => null);
advance(fixture);
// we do not trigger another navigation to /simple
expect(events).toEqual(['/simple', '/throwing']);
}));
});
it('should dispatch NavigationCancel after the url has been reset back', fakeAsync(() => {
TestBed.configureTestingModule(
{providers: [{provide: 'returnsFalse', useValue: () => false}]});
const router: Router = TestBed.get(Router);
const location: SpyLocation = TestBed.get(Location);
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'simple', component: SimpleCmp},
{path: 'throwing', loadChildren: 'doesnotmatter', canLoad: ['returnsFalse']}
]);
router.navigateByUrl('/simple');
advance(fixture);
let routerUrlBeforeEmittingError = '';
let locationUrlBeforeEmittingError = '';
router.events.forEach(e => {
if (e instanceof NavigationCancel) {
routerUrlBeforeEmittingError = router.url;
locationUrlBeforeEmittingError = location.path();
}
});
location.simulateHashChange('/throwing');
advance(fixture);
expect(routerUrlBeforeEmittingError).toEqual('/simple');
expect(locationUrlBeforeEmittingError).toEqual('/simple');
}));
it('should support custom error handlers', fakeAsync(inject([Router], (router: Router) => {
router.errorHandler = (error) => 'resolvedValue';
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'user/:name', component: UserCmp}]);
const recordedEvents: any[] = [];
router.events.forEach(e => recordedEvents.push(e));
let e: any;
router.navigateByUrl('/invalid') !.then(_ => e = _);
advance(fixture);
expect(e).toEqual('resolvedValue');
expectEvents(recordedEvents, [[NavigationStart, '/invalid'], [NavigationError, '/invalid']]);
})));
it('should recover from malformed uri errors',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
router.resetConfig([{path: 'simple', component: SimpleCmp}]);
const fixture = createRoot(router, RootCmp);
router.navigateByUrl('/invalid/url%with%percent');
advance(fixture);
expect(location.path()).toEqual('/');
})));
it('should support custom malformed uri error handler',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const customMalformedUriErrorHandler =
(e: URIError, urlSerializer: UrlSerializer, url: string):
UrlTree => { return urlSerializer.parse('/?error=The-URL-you-went-to-is-invalid'); };
router.malformedUriErrorHandler = customMalformedUriErrorHandler;
router.resetConfig([{path: 'simple', component: SimpleCmp}]);
const fixture = createRoot(router, RootCmp);
router.navigateByUrl('/invalid/url%with%percent');
advance(fixture);
expect(location.path()).toEqual('/?error=The-URL-you-went-to-is-invalid');
})));
it('should not swallow errors', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'simple', component: SimpleCmp}]);
router.navigateByUrl('/invalid');
expect(() => advance(fixture)).toThrow();
router.navigateByUrl('/invalid2');
expect(() => advance(fixture)).toThrow();
})));
it('should replace state when path is equal to current path',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children:
[{path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp}]
}]);
router.navigateByUrl('/team/33/simple');
advance(fixture);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
location.back();
advance(fixture);
expect(location.path()).toEqual('/team/33/simple');
})));
it('should handle componentless paths',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmpWithTwoOutlets);
router.resetConfig([
{
path: 'parent/:id',
children: [
{path: 'simple', component: SimpleCmp},
{path: 'user/:name', component: UserCmp, outlet: 'right'}
]
},
{path: 'user/:name', component: UserCmp}
]);
// navigate to a componentless route
router.navigateByUrl('/parent/11/(simple//right:user/victor)');
advance(fixture);
expect(location.path()).toEqual('/parent/11/(simple//right:user/victor)');
expect(fixture.nativeElement).toHaveText('primary [simple] right [user victor]');
// navigate to the same route with different params (reuse)
router.navigateByUrl('/parent/22/(simple//right:user/fedor)');
advance(fixture);
expect(location.path()).toEqual('/parent/22/(simple//right:user/fedor)');
expect(fixture.nativeElement).toHaveText('primary [simple] right [user fedor]');
// navigate to a normal route (check deactivation)
router.navigateByUrl('/user/victor');
advance(fixture);
expect(location.path()).toEqual('/user/victor');
expect(fixture.nativeElement).toHaveText('primary [user victor] right []');
// navigate back to a componentless route
router.navigateByUrl('/parent/11/(simple//right:user/victor)');
advance(fixture);
expect(location.path()).toEqual('/parent/11/(simple//right:user/victor)');
expect(fixture.nativeElement).toHaveText('primary [simple] right [user victor]');
})));
it('should not deactivate aux routes when navigating from a componentless routes',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, TwoOutletsCmp);
router.resetConfig([
{path: 'simple', component: SimpleCmp},
{path: 'componentless', children: [{path: 'simple', component: SimpleCmp}]},
{path: 'user/:name', outlet: 'aux', component: UserCmp}
]);
router.navigateByUrl('/componentless/simple(aux:user/victor)');
advance(fixture);
expect(location.path()).toEqual('/componentless/simple(aux:user/victor)');
expect(fixture.nativeElement).toHaveText('[ simple, aux: user victor ]');
router.navigateByUrl('/simple(aux:user/victor)');
advance(fixture);
expect(location.path()).toEqual('/simple(aux:user/victor)');
expect(fixture.nativeElement).toHaveText('[ simple, aux: user victor ]');
})));
it('should emit an event when an outlet gets activated', fakeAsync(() => {
@Component({
selector: 'container',
template:
`<router-outlet (activate)="recordActivate($event)" (deactivate)="recordDeactivate($event)"></router-outlet>`
})
class Container {
activations: any[] = [];
deactivations: any[] = [];
recordActivate(component: any): void { this.activations.push(component); }
recordDeactivate(component: any): void { this.deactivations.push(component); }
}
TestBed.configureTestingModule({declarations: [Container]});
const router: Router = TestBed.get(Router);
const fixture = createRoot(router, Container);
const cmp = fixture.componentInstance;
router.resetConfig(
[{path: 'blank', component: BlankCmp}, {path: 'simple', component: SimpleCmp}]);
cmp.activations = [];
cmp.deactivations = [];
router.navigateByUrl('/blank');
advance(fixture);
expect(cmp.activations.length).toEqual(1);
expect(cmp.activations[0] instanceof BlankCmp).toBe(true);
router.navigateByUrl('/simple');
advance(fixture);
expect(cmp.activations.length).toEqual(2);
expect(cmp.activations[1] instanceof SimpleCmp).toBe(true);
expect(cmp.deactivations.length).toEqual(1);
expect(cmp.deactivations[0] instanceof BlankCmp).toBe(true);
}));
it('should update url and router state before activating components',
fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'cmp', component: ComponentRecordingRoutePathAndUrl}]);
router.navigateByUrl('/cmp');
advance(fixture);
const cmp = fixture.debugElement.children[1].componentInstance;
expect(cmp.url).toBe('/cmp');
expect(cmp.path.length).toEqual(2);
})));
describe('data', () => {
class ResolveSix implements Resolve<number> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): number { return 6; }
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: 'resolveTwo', useValue: (a: any, b: any) => 2},
{provide: 'resolveFour', useValue: (a: any, b: any) => 4},
{provide: 'resolveSix', useClass: ResolveSix},
{provide: 'resolveError', useValue: (a: any, b: any) => Promise.reject('error')},
{provide: 'resolveNullError', useValue: (a: any, b: any) => Promise.reject(null)},
{provide: 'numberOfUrlSegments', useValue: (a: any, b: any) => a.url.length},
]
});
});
it('should provide resolved data', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmpWithTwoOutlets);
router.resetConfig([{
path: 'parent/:id',
data: {one: 1},
resolve: {two: 'resolveTwo'},
children: [
{path: '', data: {three: 3}, resolve: {four: 'resolveFour'}, component: RouteCmp}, {
path: '',
data: {five: 5},
resolve: {six: 'resolveSix'},
component: RouteCmp,
outlet: 'right'
}
]
}]);
router.navigateByUrl('/parent/1');
advance(fixture);
const primaryCmp = fixture.debugElement.children[1].componentInstance;
const rightCmp = fixture.debugElement.children[3].componentInstance;
expect(primaryCmp.route.snapshot.data).toEqual({one: 1, two: 2, three: 3, four: 4});
expect(rightCmp.route.snapshot.data).toEqual({one: 1, two: 2, five: 5, six: 6});
const primaryRecorded: any[] = [];
primaryCmp.route.data.forEach((rec: any) => primaryRecorded.push(rec));
const rightRecorded: any[] = [];
rightCmp.route.data.forEach((rec: any) => rightRecorded.push(rec));
router.navigateByUrl('/parent/2');
advance(fixture);
expect(primaryRecorded).toEqual([{one: 1, three: 3, two: 2, four: 4}]);
expect(rightRecorded).toEqual([{one: 1, five: 5, two: 2, six: 6}]);
})));
it('should handle errors', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'simple', component: SimpleCmp, resolve: {error: 'resolveError'}}]);
const recordedEvents: any[] = [];
router.events.subscribe(e => e instanceof RouterEvent && recordedEvents.push(e));
let e: any = null;
router.navigateByUrl('/simple') !.catch(error => e = error);
advance(fixture);
expectEvents(recordedEvents, [
[NavigationStart, '/simple'], [RoutesRecognized, '/simple'],
[GuardsCheckStart, '/simple'], [GuardsCheckEnd, '/simple'], [ResolveStart, '/simple'],
[NavigationError, '/simple']
]);
expect(e).toEqual('error');
})));
it('should handle empty errors', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'simple', component: SimpleCmp, resolve: {error: 'resolveNullError'}}]);
const recordedEvents: any[] = [];
router.events.subscribe(e => e instanceof RouterEvent && recordedEvents.push(e));
let e: any = 'some value';
router.navigateByUrl('/simple').catch(error => e = error);
advance(fixture);
expect(e).toEqual(null);
})));
it('should preserve resolved data', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'parent',
resolve: {two: 'resolveTwo'},
children: [
{path: 'child1', component: CollectParamsCmp},
{path: 'child2', component: CollectParamsCmp}
]
}]);
const e: any = null;
router.navigateByUrl('/parent/child1');
advance(fixture);
router.navigateByUrl('/parent/child2');
advance(fixture);
const cmp = fixture.debugElement.children[1].componentInstance;
expect(cmp.route.snapshot.data).toEqual({two: 2});
})));
it('should rerun resolvers when the urls segments of a wildcard route change',
fakeAsync(inject([Router, Location], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: '**',
component: CollectParamsCmp,
resolve: {numberOfUrlSegments: 'numberOfUrlSegments'}
}]);
router.navigateByUrl('/one/two');
advance(fixture);
const cmp = fixture.debugElement.children[1].componentInstance;
expect(cmp.route.snapshot.data).toEqual({numberOfUrlSegments: 2});
router.navigateByUrl('/one/two/three');
advance(fixture);
expect(cmp.route.snapshot.data).toEqual({numberOfUrlSegments: 3});
})));
describe('should run resolvers for the same route concurrently', () => {
let log: string[];
let observer: Observer<any>;
beforeEach(() => {
log = [];
TestBed.configureTestingModule({
providers: [
{
provide: 'resolver1',
useValue: () => {
const obs$ = new Observable((obs: Observer<any>) => {
observer = obs;
return () => {};
});
return obs$.pipe(map(() => log.push('resolver1')));
}
},
{
provide: 'resolver2',
useValue: () => {
return of (null).pipe(map(() => {
log.push('resolver2');
observer.next(null);
observer.complete();
}));
}
},
]
});
});
it('works', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'a',
resolve: {
one: 'resolver1',
two: 'resolver2',
},
component: SimpleCmp
}]);
router.navigateByUrl('/a');
advance(fixture);
expect(log).toEqual(['resolver2', 'resolver1']);
})));
});
});
describe('router links', () => {
it('should support skipping location update for anchor router links',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = TestBed.createComponent(RootCmp);
advance(fixture);
router.resetConfig([{path: 'team/:id', component: TeamCmp}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]');
const teamCmp = fixture.debugElement.childNodes[1].componentInstance;
teamCmp.routerLink = ['/team/0'];
advance(fixture);
const anchor = fixture.debugElement.query(By.css('a')).nativeElement;
anchor.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 0 [ , right: ]');
expect(location.path()).toEqual('/team/22');
teamCmp.routerLink = ['/team/1'];
advance(fixture);
const button = fixture.debugElement.query(By.css('button')).nativeElement;
button.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 1 [ , right: ]');
expect(location.path()).toEqual('/team/22');
})));
it('should support string router links', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'link', component: StringLinkCmp}, {path: 'simple', component: SimpleCmp}
]
}]);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]');
const native = fixture.nativeElement.querySelector('a');
expect(native.getAttribute('href')).toEqual('/team/33/simple');
expect(native.getAttribute('target')).toEqual('_self');
native.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]');
})));
it('should not preserve query params and fragment by default', fakeAsync(() => {
@Component({
selector: 'someRoot',
template: `<router-outlet></router-outlet><a routerLink="/home">Link</a>`
})
class RootCmpWithLink {
}
TestBed.configureTestingModule({declarations: [RootCmpWithLink]});
const router: Router = TestBed.get(Router);
const fixture = createRoot(router, RootCmpWithLink);
router.resetConfig([{path: 'home', component: SimpleCmp}]);
const native = fixture.nativeElement.querySelector('a');
router.navigateByUrl('/home?q=123#fragment');
advance(fixture);
expect(native.getAttribute('href')).toEqual('/home');
}));
it('should not throw when commands is null', fakeAsync(() => {
@Component({
selector: 'someCmp',
template:
`<router-outlet></router-outlet><a [routerLink]="null">Link</a><button [routerLink]="null">Button</button>`
})
class CmpWithLink {
}
TestBed.configureTestingModule({declarations: [CmpWithLink]});
const router: Router = TestBed.get(Router);
let fixture: ComponentFixture<CmpWithLink> = createRoot(router, CmpWithLink);
router.resetConfig([{path: 'home', component: SimpleCmp}]);
const anchor = fixture.nativeElement.querySelector('a');
const button = fixture.nativeElement.querySelector('button');
expect(() => anchor.click()).not.toThrow();
expect(() => button.click()).not.toThrow();
}));
it('should update hrefs when query params or fragment change', fakeAsync(() => {
@Component({
selector: 'someRoot',
template:
`<router-outlet></router-outlet><a routerLink="/home" preserveQueryParams preserveFragment>Link</a>`
})
class RootCmpWithLink {
}
TestBed.configureTestingModule({declarations: [RootCmpWithLink]});
const router: Router = TestBed.get(Router);
const fixture = createRoot(router, RootCmpWithLink);
router.resetConfig([{path: 'home', component: SimpleCmp}]);
const native = fixture.nativeElement.querySelector('a');
router.navigateByUrl('/home?q=123');
advance(fixture);
expect(native.getAttribute('href')).toEqual('/home?q=123');
router.navigateByUrl('/home?q=456');
advance(fixture);
expect(native.getAttribute('href')).toEqual('/home?q=456');
router.navigateByUrl('/home?q=456#1');
advance(fixture);
expect(native.getAttribute('href')).toEqual('/home?q=456#1');
}));
it('should correctly use the preserve strategy', fakeAsync(() => {
@Component({
selector: 'someRoot',
template:
`<router-outlet></router-outlet><a routerLink="/home" [queryParams]="{q: 456}" queryParamsHandling="preserve">Link</a>`
})
class RootCmpWithLink {
}
TestBed.configureTestingModule({declarations: [RootCmpWithLink]});
const router: Router = TestBed.get(Router);
const fixture = createRoot(router, RootCmpWithLink);
router.resetConfig([{path: 'home', component: SimpleCmp}]);
const native = fixture.nativeElement.querySelector('a');
router.navigateByUrl('/home?a=123');
advance(fixture);
expect(native.getAttribute('href')).toEqual('/home?a=123');
}));
it('should correctly use the merge strategy', fakeAsync(() => {
@Component({
selector: 'someRoot',
template:
`<router-outlet></router-outlet><a routerLink="/home" [queryParams]="{removeMe: null, q: 456}" queryParamsHandling="merge">Link</a>`
})
class RootCmpWithLink {
}
TestBed.configureTestingModule({declarations: [RootCmpWithLink]});
const router: Router = TestBed.get(Router);
const fixture = createRoot(router, RootCmpWithLink);
router.resetConfig([{path: 'home', component: SimpleCmp}]);
const native = fixture.nativeElement.querySelector('a');
router.navigateByUrl('/home?a=123&removeMe=123');
advance(fixture);
expect(native.getAttribute('href')).toEqual('/home?a=123&q=456');
}));
it('should support using links on non-a tags', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'link', component: StringLinkButtonCmp},
{path: 'simple', component: SimpleCmp}
]
}]);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]');
const button = fixture.nativeElement.querySelector('button');
expect(button.getAttribute('tabindex')).toEqual('0');
button.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]');
})));
it('should support absolute router links', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'link', component: AbsoluteLinkCmp}, {path: 'simple', component: SimpleCmp}
]
}]);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]');
const native = fixture.nativeElement.querySelector('a');
expect(native.getAttribute('href')).toEqual('/team/33/simple');
native.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]');
})));
it('should support relative router links', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'link', component: RelativeLinkCmp}, {path: 'simple', component: SimpleCmp}
]
}]);
router.navigateByUrl('/team/22/link');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]');
const native = fixture.nativeElement.querySelector('a');
expect(native.getAttribute('href')).toEqual('/team/22/simple');
native.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]');
})));
it('should support top-level link', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RelativeLinkInIfCmp);
advance(fixture);
router.resetConfig(
[{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}]);
router.navigateByUrl('/');
advance(fixture);
expect(fixture.nativeElement).toHaveText('');
const cmp = fixture.componentInstance;
cmp.show = true;
advance(fixture);
expect(fixture.nativeElement).toHaveText('link');
const native = fixture.nativeElement.querySelector('a');
expect(native.getAttribute('href')).toEqual('/simple');
native.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('linksimple');
})));
it('should support query params and fragments',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'link', component: LinkWithQueryParamsAndFragment},
{path: 'simple', component: SimpleCmp}
]
}]);
router.navigateByUrl('/team/22/link');
advance(fixture);
const native = fixture.nativeElement.querySelector('a');
expect(native.getAttribute('href')).toEqual('/team/22/simple?q=1#f');
native.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]');
expect(location.path()).toEqual('/team/22/simple?q=1#f');
})));
it('should support history state',
fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'link', component: LinkWithState}, {path: 'simple', component: SimpleCmp}
]
}]);
router.navigateByUrl('/team/22/link');
advance(fixture);
const native = fixture.nativeElement.querySelector('a');
expect(native.getAttribute('href')).toEqual('/team/22/simple');
native.click();
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]');
// Check the history entry
const history = (location as any)._history;
expect(history[history.length - 1].state.foo).toBe('bar');
expect(history[history.length - 1].state)
.toEqual({foo: 'bar', navigationId: history.length});
})));
it('should set href on area elements', fakeAsync(() => {
@Component({
selector: 'someRoot',
template: `<router-outlet></router-outlet><map><area routerLink="/home" /></map>`
})
class RootCmpWithArea {
}
TestBed.configureTestingModule({declarations: [RootCmpWithArea]});
const router: Router = TestBed.get(Router);
const fixture = createRoot(router, RootCmpWithArea);
router.resetConfig([{path: 'home', component: SimpleCmp}]);
const native = fixture.nativeElement.querySelector('area');
expect(native.getAttribute('href')).toEqual('/home');
}));
});
describe('redirects', () => {
it('should work', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp}
]);
router.navigateByUrl('old/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
})));
it('should update Navigation object after redirects are applied',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
let initialUrl, afterRedirectUrl;
router.resetConfig([
{path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp}
]);
router.events.subscribe(e => {
if (e instanceof NavigationStart) {
const navigation = router.getCurrentNavigation();
initialUrl = navigation && navigation.finalUrl;
}
if (e instanceof RoutesRecognized) {
const navigation = router.getCurrentNavigation();
afterRedirectUrl = navigation && navigation.finalUrl;
}
});
router.navigateByUrl('old/team/22');
advance(fixture);
expect(initialUrl).toBeUndefined();
expect(router.serializeUrl(afterRedirectUrl as any)).toBe('/team/22');
})));
it('should not break the back button when trigger by location change',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = TestBed.createComponent(RootCmp);
advance(fixture);
router.resetConfig([
{path: 'initial', component: BlankCmp}, {path: 'old/team/:id', redirectTo: 'team/:id'},
{path: 'team/:id', component: TeamCmp}
]);
location.go('initial');
location.go('old/team/22');
// initial navigation
router.initialNavigation();
advance(fixture);
expect(location.path()).toEqual('/team/22');
location.back();
advance(fixture);
expect(location.path()).toEqual('/initial');
// location change
(<any>location).go('/old/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
location.back();
advance(fixture);
expect(location.path()).toEqual('/initial');
})));
});
describe('guards', () => {
describe('CanActivate', () => {
describe('should not activate a route when CanActivate returns false', () => {
beforeEach(() => {
TestBed.configureTestingModule(
{providers: [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}]});
});
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
const recordedEvents: any[] = [];
router.events.forEach(e => recordedEvents.push(e));
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canActivate: ['alwaysFalse']}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/');
expectEvents(recordedEvents, [
[NavigationStart, '/team/22'],
[RoutesRecognized, '/team/22'],
[GuardsCheckStart, '/team/22'],
[ChildActivationStart],
[ActivationStart],
[GuardsCheckEnd, '/team/22'],
[NavigationCancel, '/team/22'],
]);
expect((recordedEvents[5] as GuardsCheckEnd).shouldActivate).toBe(false);
})));
});
describe(
'should not activate a route when CanActivate returns false (componentless route)',
() => {
beforeEach(() => {
TestBed.configureTestingModule(
{providers: [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}]});
});
it('works',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'parent',
canActivate: ['alwaysFalse'],
children: [{path: 'team/:id', component: TeamCmp}]
}]);
router.navigateByUrl('parent/team/22');
advance(fixture);
expect(location.path()).toEqual('/');
})));
});
describe('should activate a route when CanActivate returns true', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{
provide: 'alwaysTrue',
useValue: (a: ActivatedRouteSnapshot, s: RouterStateSnapshot) => true
}]
});
});
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canActivate: ['alwaysTrue']}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
})));
});
describe('should work when given a class', () => {
class AlwaysTrue implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return true;
}
}
beforeEach(() => { TestBed.configureTestingModule({providers: [AlwaysTrue]}); });
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canActivate: [AlwaysTrue]}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
})));
});
describe('should work when returns an observable', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{
provide: 'CanActivate',
useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return Observable.create((observer: any) => { observer.next(false); });
}
}]
});
});
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/');
})));
});
describe('should work when returns a promise', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{
provide: 'CanActivate',
useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
if (a.params['id'] === '22') {
return Promise.resolve(true);
} else {
return Promise.resolve(false);
}
}
}]
});
});
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/22');
})));
});
describe('should reset the location when cancleling a navigation', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{
provide: 'alwaysFalse',
useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return false; }
}]
});
});
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'one', component: SimpleCmp},
{path: 'two', component: SimpleCmp, canActivate: ['alwaysFalse']}
]);
router.navigateByUrl('/one');
advance(fixture);
expect(location.path()).toEqual('/one');
location.go('/two');
advance(fixture);
expect(location.path()).toEqual('/one');
})));
});
describe('should redirect to / when guard returns false', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [{
provide: 'returnFalseAndNavigate',
useFactory: (router: Router) => () => {
router.navigate(['/']);
return false;
},
deps: [Router]
}]
}));
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
router.resetConfig([
{
path: '',
component: SimpleCmp,
},
{path: 'one', component: RouteCmp, canActivate: ['returnFalseAndNavigate']}
]);
const fixture = TestBed.createComponent(RootCmp);
router.navigateByUrl('/one');
advance(fixture);
expect(location.path()).toEqual('/');
expect(fixture.nativeElement).toHaveText('simple');
})));
});
describe('should redirect when guard returns UrlTree', () => {
beforeEach(() => TestBed.configureTestingModule({
providers: [
{
provide: 'returnUrlTree',
useFactory: (router: Router) => () => { return router.parseUrl('/redirected'); },
deps: [Router]
},
{
provide: 'returnRootUrlTree',
useFactory: (router: Router) => () => { return router.parseUrl('/'); },
deps: [Router]
}
]
}));
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const recordedEvents: any[] = [];
let cancelEvent: NavigationCancel = null !;
router.events.forEach((e: any) => {
recordedEvents.push(e);
if (e instanceof NavigationCancel) cancelEvent = e;
});
router.resetConfig([
{path: '', component: SimpleCmp},
{path: 'one', component: RouteCmp, canActivate: ['returnUrlTree']},
{path: 'redirected', component: SimpleCmp}
]);
const fixture = TestBed.createComponent(RootCmp);
router.navigateByUrl('/one');
advance(fixture);
expect(location.path()).toEqual('/redirected');
expect(fixture.nativeElement).toHaveText('simple');
expect(cancelEvent && cancelEvent.reason)
.toBe('NavigationCancelingError: Redirecting to "/redirected"');
expectEvents(recordedEvents, [
[NavigationStart, '/one'],
[RoutesRecognized, '/one'],
[GuardsCheckStart, '/one'],
[ChildActivationStart, undefined],
[ActivationStart, undefined],
[NavigationCancel, '/one'],
[NavigationStart, '/redirected'],
[RoutesRecognized, '/redirected'],
[GuardsCheckStart, '/redirected'],
[ChildActivationStart, undefined],
[ActivationStart, undefined],
[GuardsCheckEnd, '/redirected'],
[ResolveStart, '/redirected'],
[ResolveEnd, '/redirected'],
[ActivationEnd, undefined],
[ChildActivationEnd, undefined],
[NavigationEnd, '/redirected'],
]);
})));
it('works with root url',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const recordedEvents: any[] = [];
let cancelEvent: NavigationCancel = null !;
router.events.forEach((e: any) => {
recordedEvents.push(e);
if (e instanceof NavigationCancel) cancelEvent = e;
});
router.resetConfig([
{path: '', component: SimpleCmp},
{path: 'one', component: RouteCmp, canActivate: ['returnRootUrlTree']}
]);
const fixture = TestBed.createComponent(RootCmp);
router.navigateByUrl('/one');
advance(fixture);
expect(location.path()).toEqual('/');
expect(fixture.nativeElement).toHaveText('simple');
expect(cancelEvent && cancelEvent.reason)
.toBe('NavigationCancelingError: Redirecting to "/"');
expectEvents(recordedEvents, [
[NavigationStart, '/one'],
[RoutesRecognized, '/one'],
[GuardsCheckStart, '/one'],
[ChildActivationStart, undefined],
[ActivationStart, undefined],
[NavigationCancel, '/one'],
[NavigationStart, '/'],
[RoutesRecognized, '/'],
[GuardsCheckStart, '/'],
[ChildActivationStart, undefined],
[ActivationStart, undefined],
[GuardsCheckEnd, '/'],
[ResolveStart, '/'],
[ResolveEnd, '/'],
[ActivationEnd, undefined],
[ChildActivationEnd, undefined],
[NavigationEnd, '/'],
]);
})));
});
describe('runGuardsAndResolvers', () => {
let guardRunCount = 0;
let resolverRunCount = 0;
beforeEach(() => {
guardRunCount = 0;
resolverRunCount = 0;
TestBed.configureTestingModule({
providers: [
{
provide: 'guard',
useValue: () => {
guardRunCount++;
return true;
}
},
{provide: 'resolver', useValue: () => resolverRunCount++}
]
});
});
function configureRouter(router: Router, runGuardsAndResolvers: RunGuardsAndResolvers):
ComponentFixture<RootCmpWithTwoOutlets> {
const fixture = createRoot(router, RootCmpWithTwoOutlets);
router.resetConfig([
{
path: 'a',
runGuardsAndResolvers,
component: RouteCmp,
canActivate: ['guard'],
resolve: {data: 'resolver'}
},
{path: 'b', component: SimpleCmp, outlet: 'right'}, {
path: 'c/:param',
runGuardsAndResolvers,
component: RouteCmp,
canActivate: ['guard'],
resolve: {data: 'resolver'}
},
{
path: 'd/:param',
component: WrapperCmp, runGuardsAndResolvers,
children: [
{
path: 'e/:param',
component: SimpleCmp,
canActivate: ['guard'],
resolve: {data: 'resolver'},
},
]
}
]);
router.navigateByUrl('/a');
advance(fixture);
return fixture;
}
it('should rerun guards and resolvers when params change',
fakeAsync(inject([Router], (router: Router) => {
const fixture = configureRouter(router, 'paramsChange');
const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance;
const recordedData: any[] = [];
cmp.route.data.subscribe((data: any) => recordedData.push(data));
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
router.navigateByUrl('/a;p=1');
advance(fixture);
expect(guardRunCount).toEqual(2);
expect(recordedData).toEqual([{data: 0}, {data: 1}]);
router.navigateByUrl('/a;p=2');
advance(fixture);
expect(guardRunCount).toEqual(3);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]);
router.navigateByUrl('/a;p=2?q=1');
advance(fixture);
expect(guardRunCount).toEqual(3);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]);
})));
it('should rerun guards and resolvers when query params change',
fakeAsync(inject([Router], (router: Router) => {
const fixture = configureRouter(router, 'paramsOrQueryParamsChange');
const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance;
const recordedData: any[] = [];
cmp.route.data.subscribe((data: any) => recordedData.push(data));
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
router.navigateByUrl('/a;p=1');
advance(fixture);
expect(guardRunCount).toEqual(2);
expect(recordedData).toEqual([{data: 0}, {data: 1}]);
router.navigateByUrl('/a;p=2');
advance(fixture);
expect(guardRunCount).toEqual(3);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]);
router.navigateByUrl('/a;p=2?q=1');
advance(fixture);
expect(guardRunCount).toEqual(4);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]);
router.navigateByUrl('/a;p=2(right:b)?q=1');
advance(fixture);
expect(guardRunCount).toEqual(4);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]);
})));
it('should always rerun guards and resolvers',
fakeAsync(inject([Router], (router: Router) => {
const fixture = configureRouter(router, 'always');
const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance;
const recordedData: any[] = [];
cmp.route.data.subscribe((data: any) => recordedData.push(data));
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
router.navigateByUrl('/a;p=1');
advance(fixture);
expect(guardRunCount).toEqual(2);
expect(recordedData).toEqual([{data: 0}, {data: 1}]);
router.navigateByUrl('/a;p=2');
advance(fixture);
expect(guardRunCount).toEqual(3);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]);
router.navigateByUrl('/a;p=2?q=1');
advance(fixture);
expect(guardRunCount).toEqual(4);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]);
router.navigateByUrl('/a;p=2(right:b)?q=1');
advance(fixture);
expect(guardRunCount).toEqual(5);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}, {data: 4}]);
})));
it('should rerun rerun guards and resolvers when path params change',
fakeAsync(inject([Router], (router: Router) => {
const fixture = configureRouter(router, 'pathParamsChange');
const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance;
const recordedData: any[] = [];
cmp.route.data.subscribe((data: any) => recordedData.push(data));
// First navigation has already run
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
// Changing any optional params will not result in running guards or resolvers
router.navigateByUrl('/a;p=1');
advance(fixture);
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
router.navigateByUrl('/a;p=2');
advance(fixture);
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
router.navigateByUrl('/a;p=2?q=1');
advance(fixture);
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
router.navigateByUrl('/a;p=2(right:b)?q=1');
advance(fixture);
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
// Change to new route with path param should run guards and resolvers
router.navigateByUrl('/c/paramValue');
advance(fixture);
expect(guardRunCount).toEqual(2);
// Modifying a path param should run guards and resolvers
router.navigateByUrl('/c/paramValueChanged');
advance(fixture);
expect(guardRunCount).toEqual(3);
// Adding optional params should not cause guards/resolvers to run
router.navigateByUrl('/c/paramValueChanged;p=1?q=2');
advance(fixture);
expect(guardRunCount).toEqual(3);
})));
it('should rerun when a parent segment changes',
fakeAsync(inject([Router], (router: Router) => {
const fixture = configureRouter(router, 'pathParamsChange');
const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance;
// Land on an inital page
router.navigateByUrl('/d/1;dd=11/e/2;dd=22');
advance(fixture);
expect(guardRunCount).toEqual(2);
// Changes cause re-run on the config with the guard
router.navigateByUrl('/d/1;dd=11/e/3;ee=22');
advance(fixture);
expect(guardRunCount).toEqual(3);
// Changes to the parent also cause re-run
router.navigateByUrl('/d/2;dd=11/e/3;ee=22');
advance(fixture);
expect(guardRunCount).toEqual(4);
})));
it('should rerun rerun guards and resolvers when path or query params change',
fakeAsync(inject([Router], (router: Router) => {
const fixture = configureRouter(router, 'pathParamsOrQueryParamsChange');
const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance;
const recordedData: any[] = [];
cmp.route.data.subscribe((data: any) => recordedData.push(data));
// First navigation has already run
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
// Changing matrix params will not result in running guards or resolvers
router.navigateByUrl('/a;p=1');
advance(fixture);
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
router.navigateByUrl('/a;p=2');
advance(fixture);
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
// Adding query params will re-run guards/resolvers
router.navigateByUrl('/a;p=2?q=1');
advance(fixture);
expect(guardRunCount).toEqual(2);
expect(recordedData).toEqual([{data: 0}, {data: 1}]);
// Changing query params will re-run guards/resolvers
router.navigateByUrl('/a;p=2?q=2');
advance(fixture);
expect(guardRunCount).toEqual(3);
expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]);
})));
it('should allow a predicate function to determine when to run guards and resolvers',
fakeAsync(inject([Router], (router: Router) => {
const fixture = configureRouter(router, (from, to) => to.paramMap.get('p') === '2');
const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance;
const recordedData: any[] = [];
cmp.route.data.subscribe((data: any) => recordedData.push(data));
// First navigation has already run
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
// Adding `p` param shouldn't cause re-run
router.navigateByUrl('/a;p=1');
advance(fixture);
expect(guardRunCount).toEqual(1);
expect(recordedData).toEqual([{data: 0}]);
// Re-run should trigger on p=2
router.navigateByUrl('/a;p=2');
advance(fixture);
expect(guardRunCount).toEqual(2);
expect(recordedData).toEqual([{data: 0}, {data: 1}]);
// Any other changes don't pass the predicate
router.navigateByUrl('/a;p=3?q=1');
advance(fixture);
expect(guardRunCount).toEqual(2);
expect(recordedData).toEqual([{data: 0}, {data: 1}]);
// Changing query params will re-run guards/resolvers
router.navigateByUrl('/a;p=3?q=2');
advance(fixture);
expect(guardRunCount).toEqual(2);
expect(recordedData).toEqual([{data: 0}, {data: 1}]);
})));
});
describe('should wait for parent to complete', () => {
let log: string[];
beforeEach(() => {
log = [];
TestBed.configureTestingModule({
providers: [
{
provide: 'parentGuard',
useValue: () => {
return delayPromise(10).then(() => {
log.push('parent');
return true;
});
}
},
{
provide: 'childGuard',
useValue: () => {
return delayPromise(5).then(() => {
log.push('child');
return true;
});
}
}
]
});
});
function delayPromise(delay: number): Promise<boolean> {
let resolve: (val: boolean) => void;
const promise = new Promise<boolean>(res => resolve = res);
setTimeout(() => resolve(true), delay);
return promise;
}
it('works', fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'parent',
canActivate: ['parentGuard'],
children: [
{path: 'child', component: SimpleCmp, canActivate: ['childGuard']},
]
}]);
router.navigateByUrl('/parent/child');
advance(fixture);
tick(15);
expect(log).toEqual(['parent', 'child']);
})));
});
});
describe('CanDeactivate', () => {
let log: any;
beforeEach(() => {
log = [];
TestBed.configureTestingModule({
providers: [
{
provide: 'CanDeactivateParent',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return a.params['id'] === '22';
}
},
{
provide: 'CanDeactivateTeam',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return c.route.snapshot.params['id'] === '22';
}
},
{
provide: 'CanDeactivateUser',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return a.params['name'] === 'victor';
}
},
{
provide: 'RecordingDeactivate',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
log.push({path: a.routeConfig !.path, component: c});
return true;
}
},
{
provide: 'alwaysFalse',
useValue:
(c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return false; }
},
{
provide: 'alwaysFalseAndLogging',
useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
log.push('called');
return false;
}
},
{
provide: 'alwaysFalseWithDelayAndLogging',
useValue: () => {
log.push('called');
let resolve: (result: boolean) => void;
const promise = new Promise(res => resolve = res);
setTimeout(() => resolve(false), 0);
return promise;
}
},
{
provide: 'canActivate_alwaysTrueAndLogging',
useValue: () => {
log.push('canActivate called');
return true;
}
},
]
});
});
describe('should not deactivate a route when CanDeactivate returns false', () => {
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivateTeam']}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
let successStatus: boolean = false;
router.navigateByUrl('/team/33') !.then(res => successStatus = res);
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(successStatus).toEqual(true);
let canceledStatus: boolean = false;
router.navigateByUrl('/team/44') !.then(res => canceledStatus = res);
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(canceledStatus).toEqual(false);
})));
it('works with componentless routes',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{
path: 'grandparent',
canDeactivate: ['RecordingDeactivate'],
children: [{
path: 'parent',
canDeactivate: ['RecordingDeactivate'],
children: [{
path: 'child',
canDeactivate: ['RecordingDeactivate'],
children: [{
path: 'simple',
component: SimpleCmp,
canDeactivate: ['RecordingDeactivate']
}]
}]
}]
},
{path: 'simple', component: SimpleCmp}
]);
router.navigateByUrl('/grandparent/parent/child/simple');
advance(fixture);
expect(location.path()).toEqual('/grandparent/parent/child/simple');
router.navigateByUrl('/simple');
advance(fixture);
const child = fixture.debugElement.children[1].componentInstance;
expect(log.map((a: any) => a.path)).toEqual([
'simple', 'child', 'parent', 'grandparent'
]);
expect(log[0].component instanceof SimpleCmp).toBeTruthy();
[1, 2, 3].forEach(i => expect(log[i].component).toBeNull());
expect(child instanceof SimpleCmp).toBeTruthy();
expect(child).not.toBe(log[0].component);
})));
it('works with aux routes',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'two-outlets',
component: TwoOutletsCmp,
children: [
{path: 'a', component: BlankCmp}, {
path: 'b',
canDeactivate: ['RecordingDeactivate'],
component: SimpleCmp,
outlet: 'aux'
}
]
}]);
router.navigateByUrl('/two-outlets/(a//aux:b)');
advance(fixture);
expect(location.path()).toEqual('/two-outlets/(a//aux:b)');
router.navigate(['two-outlets', {outlets: {aux: null}}]);
advance(fixture);
expect(log.map((a: any) => a.path)).toEqual(['b']);
expect(location.path()).toEqual('/two-outlets/(a)');
})));
it('works with a nested route',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: '', pathMatch: 'full', component: SimpleCmp},
{path: 'user/:name', component: UserCmp, canDeactivate: ['CanDeactivateUser']}
]
}]);
router.navigateByUrl('/team/22/user/victor');
advance(fixture);
// this works because we can deactivate victor
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
router.navigateByUrl('/team/33/user/fedor');
advance(fixture);
// this doesn't work cause we cannot deactivate fedor
router.navigateByUrl('/team/44');
advance(fixture);
expect(location.path()).toEqual('/team/33/user/fedor');
})));
});
it('should not create a route state if navigation is canceled',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'main',
component: TeamCmp,
children: [
{path: 'component1', component: SimpleCmp, canDeactivate: ['alwaysFalse']},
{path: 'component2', component: SimpleCmp}
]
}]);
router.navigateByUrl('/main/component1');
advance(fixture);
router.navigateByUrl('/main/component2');
advance(fixture);
const teamCmp = fixture.debugElement.children[1].componentInstance;
expect(teamCmp.route.firstChild.url.value[0].path).toEqual('component1');
expect(location.path()).toEqual('/main/component1');
})));
it('should not run CanActivate when CanDeactivate returns false',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'main',
component: TeamCmp,
children: [
{
path: 'component1',
component: SimpleCmp,
canDeactivate: ['alwaysFalseWithDelayAndLogging']
},
{
path: 'component2',
component: SimpleCmp,
canActivate: ['canActivate_alwaysTrueAndLogging']
},
]
}]);
router.navigateByUrl('/main/component1');
advance(fixture);
expect(location.path()).toEqual('/main/component1');
router.navigateByUrl('/main/component2');
advance(fixture);
expect(location.path()).toEqual('/main/component1');
expect(log).toEqual(['called']);
})));
it('should call guards every time when navigating to the same url over and over again',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'simple', component: SimpleCmp, canDeactivate: ['alwaysFalseAndLogging']},
{path: 'blank', component: BlankCmp}
]);
router.navigateByUrl('/simple');
advance(fixture);
router.navigateByUrl('/blank');
advance(fixture);
expect(log).toEqual(['called']);
expect(location.path()).toEqual('/simple');
router.navigateByUrl('/blank');
advance(fixture);
expect(log).toEqual(['called', 'called']);
expect(location.path()).toEqual('/simple');
})));
describe('next state', () => {
let log: string[];
class ClassWithNextState implements CanDeactivate<TeamCmp> {
canDeactivate(
component: TeamCmp, currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot, nextState: RouterStateSnapshot): boolean {
log.push(currentState.url, nextState.url);
return true;
}
}
beforeEach(() => {
log = [];
TestBed.configureTestingModule({
providers: [
ClassWithNextState, {
provide: 'FunctionWithNextState',
useValue: (cmp: any, currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot, nextState: RouterStateSnapshot) => {
log.push(currentState.url, nextState.url);
return true;
}
}
]
});
});
it('should pass next state as the 4 argument when guard is a class',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canDeactivate: [ClassWithNextState]}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(log).toEqual(['/team/22', '/team/33']);
})));
it('should pass next state as the 4 argument when guard is a function',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'team/:id', component: TeamCmp, canDeactivate: ['FunctionWithNextState']}
]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
expect(log).toEqual(['/team/22', '/team/33']);
})));
});
describe('should work when given a class', () => {
class AlwaysTrue implements CanDeactivate<TeamCmp> {
canDeactivate(
component: TeamCmp, route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
return true;
}
}
beforeEach(() => { TestBed.configureTestingModule({providers: [AlwaysTrue]}); });
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canDeactivate: [AlwaysTrue]}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/33');
})));
});
describe('should work when returns an observable', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{
provide: 'CanDeactivate',
useValue: (c: TeamCmp, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => {
return Observable.create((observer: any) => { observer.next(false); });
}
}]
});
});
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivate']}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33');
advance(fixture);
expect(location.path()).toEqual('/team/22');
})));
});
});
describe('CanActivateChild', () => {
describe('should be invoked when activating a child', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [{
provide: 'alwaysFalse',
useValue: (a: any, b: any) => a.paramMap.get('id') === '22',
}]
});
});
it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: '',
canActivateChild: ['alwaysFalse'],
children: [{path: 'team/:id', component: TeamCmp}]
}]);
router.navigateByUrl('/team/22');
advance(fixture);
expect(location.path()).toEqual('/team/22');
router.navigateByUrl('/team/33') !.catch(() => {});
advance(fixture);
expect(location.path()).toEqual('/team/22');
})));
});
it('should find the guard provided in lazy loaded module',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'admin', template: '<router-outlet></router-outlet>'})
class AdminComponent {
}
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [AdminComponent, LazyLoadedComponent],
imports: [RouterModule.forChild([{
path: '',
component: AdminComponent,
children: [{
path: '',
canActivateChild: ['alwaysTrue'],
children: [{path: '', component: LazyLoadedComponent}]
}]
}])],
providers: [{provide: 'alwaysTrue', useValue: () => true}],
})
class LazyLoadedModule {
}
loader.stubbedModules = {lazy: LazyLoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'admin', loadChildren: 'lazy'}]);
router.navigateByUrl('/admin');
advance(fixture);
expect(location.path()).toEqual('/admin');
expect(fixture.nativeElement).toHaveText('lazy-loaded');
})));
});
describe('CanLoad', () => {
let canLoadRunCount = 0;
beforeEach(() => {
canLoadRunCount = 0;
TestBed.configureTestingModule({
providers: [
{provide: 'alwaysFalse', useValue: (a: any) => false},
{
provide: 'returnFalseAndNavigate',
useFactory: (router: any) => (a: any) => {
router.navigate(['blank']);
return false;
},
deps: [Router],
},
{
provide: 'alwaysTrue',
useValue: () => {
canLoadRunCount++;
return true;
}
},
]
});
});
it('should not load children when CanLoad returns false',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [LazyLoadedComponent],
imports:
[RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])]
})
class LoadedModule {
}
loader.stubbedModules = {lazyFalse: LoadedModule, lazyTrue: LoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'lazyFalse', canLoad: ['alwaysFalse'], loadChildren: 'lazyFalse'},
{path: 'lazyTrue', canLoad: ['alwaysTrue'], loadChildren: 'lazyTrue'}
]);
const recordedEvents: any[] = [];
router.events.forEach(e => recordedEvents.push(e));
// failed navigation
router.navigateByUrl('/lazyFalse/loaded');
advance(fixture);
expect(location.path()).toEqual('/');
expectEvents(recordedEvents, [
[NavigationStart, '/lazyFalse/loaded'],
// [GuardsCheckStart, '/lazyFalse/loaded'],
[NavigationCancel, '/lazyFalse/loaded'],
]);
recordedEvents.splice(0);
// successful navigation
router.navigateByUrl('/lazyTrue/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazyTrue/loaded');
expectEvents(recordedEvents, [
[NavigationStart, '/lazyTrue/loaded'],
[RouteConfigLoadStart],
[RouteConfigLoadEnd],
[RoutesRecognized, '/lazyTrue/loaded'],
[GuardsCheckStart, '/lazyTrue/loaded'],
[ChildActivationStart],
[ActivationStart],
[ChildActivationStart],
[ActivationStart],
[GuardsCheckEnd, '/lazyTrue/loaded'],
[ResolveStart, '/lazyTrue/loaded'],
[ResolveEnd, '/lazyTrue/loaded'],
[ActivationEnd],
[ChildActivationEnd],
[ActivationEnd],
[ChildActivationEnd],
[NavigationEnd, '/lazyTrue/loaded'],
]);
})));
it('should support navigating from within the guard',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'lazyFalse', canLoad: ['returnFalseAndNavigate'], loadChildren: 'lazyFalse'},
{path: 'blank', component: BlankCmp}
]);
const recordedEvents: any[] = [];
router.events.forEach(e => recordedEvents.push(e));
router.navigateByUrl('/lazyFalse/loaded');
advance(fixture);
expect(location.path()).toEqual('/blank');
expectEvents(recordedEvents, [
[NavigationStart, '/lazyFalse/loaded'],
// No GuardCheck events as `canLoad` is a special guard that's not actually part of the
// guard lifecycle.
[NavigationCancel, '/lazyFalse/loaded'],
[NavigationStart, '/blank'], [RoutesRecognized, '/blank'],
[GuardsCheckStart, '/blank'], [ChildActivationStart], [ActivationStart],
[GuardsCheckEnd, '/blank'], [ResolveStart, '/blank'], [ResolveEnd, '/blank'],
[ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/blank']
]);
})));
// Regression where navigateByUrl with false CanLoad no longer resolved `false` value on
// navigateByUrl promise: https://github.com/angular/angular/issues/26284
it('should resolve navigateByUrl promise after CanLoad executes',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [LazyLoadedComponent],
imports:
[RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])]
})
class LazyLoadedModule {
}
loader.stubbedModules = {lazy: LazyLoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'lazy-false', canLoad: ['alwaysFalse'], loadChildren: 'lazy'},
{path: 'lazy-true', canLoad: ['alwaysTrue'], loadChildren: 'lazy'},
]);
let navFalseResult: any;
let navTrueResult: any;
router.navigateByUrl('/lazy-false').then(v => { navFalseResult = v; });
advance(fixture);
router.navigateByUrl('/lazy-true').then(v => { navTrueResult = v; });
advance(fixture);
expect(navFalseResult).toBe(false);
expect(navTrueResult).toBe(true);
})));
it('should execute CanLoad only once',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [LazyLoadedComponent],
imports:
[RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])]
})
class LazyLoadedModule {
}
loader.stubbedModules = {lazy: LazyLoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', canLoad: ['alwaysTrue'], loadChildren: 'lazy'}]);
router.navigateByUrl('/lazy/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy/loaded');
expect(canLoadRunCount).toEqual(1);
router.navigateByUrl('/');
advance(fixture);
expect(location.path()).toEqual('/');
router.navigateByUrl('/lazy/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy/loaded');
expect(canLoadRunCount).toEqual(1);
})));
});
describe('order', () => {
class Logger {
logs: string[] = [];
add(thing: string) { this.logs.push(thing); }
}
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
Logger, {
provide: 'canActivateChild_parent',
useFactory: (logger: Logger) => () => (logger.add('canActivateChild_parent'), true),
deps: [Logger]
},
{
provide: 'canActivate_team',
useFactory: (logger: Logger) => () => (logger.add('canActivate_team'), true),
deps: [Logger]
},
{
provide: 'canDeactivate_team',
useFactory: (logger: Logger) => () => (logger.add('canDeactivate_team'), true),
deps: [Logger]
},
{
provide: 'canDeactivate_simple',
useFactory: (logger: Logger) => () => (logger.add('canDeactivate_simple'), true),
deps: [Logger]
}
]
});
});
it('should call guards in the right order',
fakeAsync(inject(
[Router, Location, Logger], (router: Router, location: Location, logger: Logger) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: '',
canActivateChild: ['canActivateChild_parent'],
children: [{
path: 'team/:id',
canActivate: ['canActivate_team'],
canDeactivate: ['canDeactivate_team'],
component: TeamCmp
}]
}]);
router.navigateByUrl('/team/22');
advance(fixture);
router.navigateByUrl('/team/33');
advance(fixture);
expect(logger.logs).toEqual([
'canActivateChild_parent', 'canActivate_team',
'canDeactivate_team', 'canActivateChild_parent', 'canActivate_team'
]);
})));
it('should call deactivate guards from bottom to top',
fakeAsync(inject(
[Router, Location, Logger], (router: Router, location: Location, logger: Logger) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: '',
children: [{
path: 'team/:id',
canDeactivate: ['canDeactivate_team'],
children:
[{path: '', component: SimpleCmp, canDeactivate: ['canDeactivate_simple']}],
component: TeamCmp
}]
}]);
router.navigateByUrl('/team/22');
advance(fixture);
router.navigateByUrl('/team/33');
advance(fixture);
expect(logger.logs).toEqual(['canDeactivate_simple', 'canDeactivate_team']);
})));
});
});
describe('route events', () => {
it('should fire matching (Child)ActivationStart/End events',
fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'user/:name', component: UserCmp}]);
const recordedEvents: any[] = [];
router.events.forEach(e => recordedEvents.push(e));
router.navigateByUrl('/user/fedor');
advance(fixture);
expect(fixture.nativeElement).toHaveText('user fedor');
expect(recordedEvents[3] instanceof ChildActivationStart).toBe(true);
expect(recordedEvents[3].snapshot).toBe(recordedEvents[9].snapshot.root);
expect(recordedEvents[9] instanceof ChildActivationEnd).toBe(true);
expect(recordedEvents[9].snapshot).toBe(recordedEvents[9].snapshot.root);
expect(recordedEvents[4] instanceof ActivationStart).toBe(true);
expect(recordedEvents[4].snapshot.routeConfig.path).toBe('user/:name');
expect(recordedEvents[8] instanceof ActivationEnd).toBe(true);
expect(recordedEvents[8].snapshot.routeConfig.path).toBe('user/:name');
expectEvents(recordedEvents, [
[NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'],
[GuardsCheckStart, '/user/fedor'], [ChildActivationStart], [ActivationStart],
[GuardsCheckEnd, '/user/fedor'], [ResolveStart, '/user/fedor'],
[ResolveEnd, '/user/fedor'], [ActivationEnd], [ChildActivationEnd],
[NavigationEnd, '/user/fedor']
]);
})));
it('should allow redirection in NavigationStart',
fakeAsync(inject([Router], (router: Router) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'blank', component: UserCmp},
{path: 'user/:name', component: BlankCmp},
]);
const navigateSpy = spyOn(router, 'navigate').and.callThrough();
const recordedEvents: any[] = [];
const navStart$ = router.events.pipe(
tap(e => recordedEvents.push(e)), filter(e => e instanceof NavigationStart), first());
navStart$.subscribe((e: NavigationStart | NavigationError) => {
router.navigate(
['/blank'], {queryParams: {state: 'redirected'}, queryParamsHandling: 'merge'});
advance(fixture);
});
router.navigate(['/user/:fedor']);
advance(fixture);
expect(navigateSpy.calls.mostRecent().args[1].queryParams);
})));
});
describe('routerActiveLink', () => {
it('should set the class when the link is active (a tag)',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [{
path: 'link',
component: DummyLinkCmp,
children:
[{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}]
}]
}]);
router.navigateByUrl('/team/22/link;exact=true');
advance(fixture);
advance(fixture);
expect(location.path()).toEqual('/team/22/link;exact=true');
const nativeLink = fixture.nativeElement.querySelector('a');
const nativeButton = fixture.nativeElement.querySelector('button');
expect(nativeLink.className).toEqual('active');
expect(nativeButton.className).toEqual('active');
router.navigateByUrl('/team/22/link/simple');
advance(fixture);
expect(location.path()).toEqual('/team/22/link/simple');
expect(nativeLink.className).toEqual('');
expect(nativeButton.className).toEqual('');
})));
it('should not set the class until the first navigation succeeds', fakeAsync(() => {
@Component({
template:
'<router-outlet></router-outlet><a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" ></a>'
})
class RootCmpWithLink {
}
TestBed.configureTestingModule({declarations: [RootCmpWithLink]});
const router: Router = TestBed.get(Router);
const f = TestBed.createComponent(RootCmpWithLink);
advance(f);
const link = f.nativeElement.querySelector('a');
expect(link.className).toEqual('');
router.initialNavigation();
advance(f);
expect(link.className).toEqual('active');
}));
it('should set the class on a parent element when the link is active',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [{
path: 'link',
component: DummyLinkWithParentCmp,
children:
[{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}]
}]
}]);
router.navigateByUrl('/team/22/link;exact=true');
advance(fixture);
advance(fixture);
expect(location.path()).toEqual('/team/22/link;exact=true');
const native = fixture.nativeElement.querySelector('#link-parent');
expect(native.className).toEqual('active');
router.navigateByUrl('/team/22/link/simple');
advance(fixture);
expect(location.path()).toEqual('/team/22/link/simple');
expect(native.className).toEqual('');
})));
it('should set the class when the link is active',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [{
path: 'link',
component: DummyLinkCmp,
children:
[{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}]
}]
}]);
router.navigateByUrl('/team/22/link');
advance(fixture);
advance(fixture);
expect(location.path()).toEqual('/team/22/link');
const native = fixture.nativeElement.querySelector('a');
expect(native.className).toEqual('active');
router.navigateByUrl('/team/22/link/simple');
advance(fixture);
expect(location.path()).toEqual('/team/22/link/simple');
expect(native.className).toEqual('active');
})));
it('should expose an isActive property', fakeAsync(() => {
@Component({
template: `<a routerLink="/team" routerLinkActive #rla="routerLinkActive"></a>
<p>{{rla.isActive}}</p>
<span *ngIf="rla.isActive"></span>
<span [ngClass]="{'highlight': rla.isActive}"></span>
<router-outlet></router-outlet>`
})
class ComponentWithRouterLink {
}
TestBed.configureTestingModule({declarations: [ComponentWithRouterLink]});
const router: Router = TestBed.get(Router);
router.resetConfig([
{
path: 'team',
component: TeamCmp,
},
{
path: 'otherteam',
component: TeamCmp,
}
]);
const fixture = TestBed.createComponent(ComponentWithRouterLink);
router.navigateByUrl('/team');
expect(() => advance(fixture)).not.toThrow();
advance(fixture);
const paragraph = fixture.nativeElement.querySelector('p');
expect(paragraph.textContent).toEqual('true');
router.navigateByUrl('/otherteam');
advance(fixture);
advance(fixture);
expect(paragraph.textContent).toEqual('false');
}));
});
describe('lazy loading', () => {
it('works',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded-parent [<router-outlet></router-outlet>]'
})
class ParentLazyLoadedComponent {
}
@Component({selector: 'lazy', template: 'lazy-loaded-child'})
class ChildLazyLoadedComponent {
}
@NgModule({
declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent],
imports: [RouterModule.forChild([{
path: 'loaded',
component: ParentLazyLoadedComponent,
children: [{path: 'child', component: ChildLazyLoadedComponent}]
}])]
})
class LoadedModule {
}
loader.stubbedModules = {expected: LoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]);
router.navigateByUrl('/lazy/loaded/child');
advance(fixture);
expect(location.path()).toEqual('/lazy/loaded/child');
expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]');
})));
it('should have 2 injector trees: module and element',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({
selector: 'lazy',
template: 'parent[<router-outlet></router-outlet>]',
viewProviders: [
{provide: 'shadow', useValue: 'from parent component'},
],
})
class Parent {
}
@Component({selector: 'lazy', template: 'child'})
class Child {
}
@NgModule({
declarations: [Parent],
imports: [RouterModule.forChild([{
path: 'parent',
component: Parent,
children: [
{path: 'child', loadChildren: 'child'},
]
}])],
providers: [
{provide: 'moduleName', useValue: 'parent'},
{provide: 'fromParent', useValue: 'from parent'},
],
})
class ParentModule {
}
@NgModule({
declarations: [Child],
imports: [RouterModule.forChild([{path: '', component: Child}])],
providers: [
{provide: 'moduleName', useValue: 'child'},
{provide: 'fromChild', useValue: 'from child'},
{provide: 'shadow', useValue: 'from child module'},
],
})
class ChildModule {
}
loader.stubbedModules = {
parent: ParentModule,
child: ChildModule,
};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'parent'}]);
router.navigateByUrl('/lazy/parent/child');
advance(fixture);
expect(location.path()).toEqual('/lazy/parent/child');
expect(fixture.nativeElement).toHaveText('parent[child]');
const pInj = fixture.debugElement.query(By.directive(Parent)).injector !;
const cInj = fixture.debugElement.query(By.directive(Child)).injector !;
expect(pInj.get('moduleName')).toEqual('parent');
expect(pInj.get('fromParent')).toEqual('from parent');
expect(pInj.get(Parent)).toBeAnInstanceOf(Parent);
expect(pInj.get('fromChild', null)).toEqual(null);
expect(pInj.get(Child, null)).toEqual(null);
expect(cInj.get('moduleName')).toEqual('child');
expect(cInj.get('fromParent')).toEqual('from parent');
expect(cInj.get('fromChild')).toEqual('from child');
expect(cInj.get(Parent)).toBeAnInstanceOf(Parent);
expect(cInj.get(Child)).toBeAnInstanceOf(Child);
// The child module can not shadow the parent component
expect(cInj.get('shadow')).toEqual('from parent component');
const pmInj = pInj.get(NgModuleRef).injector;
const cmInj = cInj.get(NgModuleRef).injector;
expect(pmInj.get('moduleName')).toEqual('parent');
expect(cmInj.get('moduleName')).toEqual('child');
expect(pmInj.get(Parent, '-')).toEqual('-');
expect(cmInj.get(Parent, '-')).toEqual('-');
expect(pmInj.get(Child, '-')).toEqual('-');
expect(cmInj.get(Child, '-')).toEqual('-');
})));
// https://github.com/angular/angular/issues/12889
it('should create a single instance of lazy-loaded modules',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded-parent [<router-outlet></router-outlet>]'
})
class ParentLazyLoadedComponent {
}
@Component({selector: 'lazy', template: 'lazy-loaded-child'})
class ChildLazyLoadedComponent {
}
@NgModule({
declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent],
imports: [RouterModule.forChild([{
path: 'loaded',
component: ParentLazyLoadedComponent,
children: [{path: 'child', component: ChildLazyLoadedComponent}]
}])]
})
class LoadedModule {
static instances = 0;
constructor() { LoadedModule.instances++; }
}
loader.stubbedModules = {expected: LoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]);
router.navigateByUrl('/lazy/loaded/child');
advance(fixture);
expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]');
expect(LoadedModule.instances).toEqual(1);
})));
// https://github.com/angular/angular/issues/13870
it('should create a single instance of guards for lazy-loaded modules',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Injectable()
class Service {
}
@Injectable()
class Resolver implements Resolve<Service> {
constructor(public service: Service) {}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.service;
}
}
@Component({selector: 'lazy', template: 'lazy'})
class LazyLoadedComponent {
resolvedService: Service;
constructor(public injectedService: Service, route: ActivatedRoute) {
this.resolvedService = route.snapshot.data['service'];
}
}
@NgModule({
declarations: [LazyLoadedComponent],
providers: [Service, Resolver],
imports: [
RouterModule.forChild([{
path: 'loaded',
component: LazyLoadedComponent,
resolve: {'service': Resolver},
}]),
]
})
class LoadedModule {
}
loader.stubbedModules = {expected: LoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]);
router.navigateByUrl('/lazy/loaded');
advance(fixture);
expect(fixture.nativeElement).toHaveText('lazy');
const lzc =
fixture.debugElement.query(By.directive(LazyLoadedComponent)).componentInstance;
expect(lzc.injectedService).toBe(lzc.resolvedService);
})));
it('should emit RouteConfigLoadStart and RouteConfigLoadEnd event when route is lazy loaded',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({
selector: 'lazy',
template: 'lazy-loaded-parent [<router-outlet></router-outlet>]',
})
class ParentLazyLoadedComponent {
}
@Component({selector: 'lazy', template: 'lazy-loaded-child'})
class ChildLazyLoadedComponent {
}
@NgModule({
declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent],
imports: [RouterModule.forChild([{
path: 'loaded',
component: ParentLazyLoadedComponent,
children: [{path: 'child', component: ChildLazyLoadedComponent}],
}])]
})
class LoadedModule {
}
const events: Array<RouteConfigLoadStart|RouteConfigLoadEnd> = [];
router.events.subscribe(e => {
if (e instanceof RouteConfigLoadStart || e instanceof RouteConfigLoadEnd) {
events.push(e);
}
});
loader.stubbedModules = {expected: LoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]);
router.navigateByUrl('/lazy/loaded/child');
advance(fixture);
expect(events.length).toEqual(2);
expect(events[0].toString()).toEqual('RouteConfigLoadStart(path: lazy)');
expect(events[1].toString()).toEqual('RouteConfigLoadEnd(path: lazy)');
})));
it('throws an error when forRoot() is used in a lazy context',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'should not show'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forRoot([{path: 'loaded', component: LazyLoadedComponent}])]
})
class LoadedModule {
}
loader.stubbedModules = {expected: LoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]);
let recordedError: any = null;
router.navigateByUrl('/lazy/loaded') !.catch(err => recordedError = err);
advance(fixture);
expect(recordedError.message)
.toEqual(
`RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`);
})));
it('should combine routes from multiple modules into a single configuration',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'lazy-loaded-2'})
class LazyComponent2 {
}
@NgModule({
declarations: [LazyComponent2],
imports: [RouterModule.forChild([{path: 'loaded', component: LazyComponent2}])]
})
class SiblingOfLoadedModule {
}
@Component({selector: 'lazy', template: 'lazy-loaded-1'})
class LazyComponent1 {
}
@NgModule({
declarations: [LazyComponent1],
imports: [
RouterModule.forChild([{path: 'loaded', component: LazyComponent1}]),
SiblingOfLoadedModule
]
})
class LoadedModule {
}
loader.stubbedModules = {expected1: LoadedModule, expected2: SiblingOfLoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'lazy1', loadChildren: 'expected1'},
{path: 'lazy2', loadChildren: 'expected2'}
]);
router.navigateByUrl('/lazy1/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy1/loaded');
router.navigateByUrl('/lazy2/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy2/loaded');
})));
it('should allow lazy loaded module in named outlet',
fakeAsync(inject(
[Router, NgModuleFactoryLoader], (router: Router, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyComponent {
}
@NgModule({
declarations: [LazyComponent],
imports: [RouterModule.forChild([{path: '', component: LazyComponent}])]
})
class LazyLoadedModule {
}
loader.stubbedModules = {lazyModule: LazyLoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{path: 'lazy', loadChildren: 'lazyModule', outlet: 'right'},
]
}]);
router.navigateByUrl('/team/22/user/john');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: ]');
router.navigateByUrl('/team/22/(user/john//right:lazy)');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: lazy-loaded ]');
})));
it('should allow componentless named outlet to render children',
fakeAsync(inject(
[Router, NgModuleFactoryLoader], (router: Router, loader: SpyNgModuleFactoryLoader) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'team/:id',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp},
{path: 'simple', outlet: 'right', children: [{path: '', component: SimpleCmp}]},
]
}]);
router.navigateByUrl('/team/22/user/john');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: ]');
router.navigateByUrl('/team/22/(user/john//right:simple)');
advance(fixture);
expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: simple ]');
})));
describe('should use the injector of the lazily-loaded configuration', () => {
class LazyLoadedServiceDefinedInModule {}
@Component({
selector: 'eager-parent',
template: 'eager-parent <router-outlet></router-outlet>',
})
class EagerParentComponent {
}
@Component({
selector: 'lazy-parent',
template: 'lazy-parent <router-outlet></router-outlet>',
})
class LazyParentComponent {
}
@Component({
selector: 'lazy-child',
template: 'lazy-child',
})
class LazyChildComponent {
constructor(
lazy: LazyParentComponent, // should be able to inject lazy/direct parent
lazyService: LazyLoadedServiceDefinedInModule, // should be able to inject lazy service
eager:
EagerParentComponent // should use the injector of the location to create a parent
) {}
}
@NgModule({
declarations: [LazyParentComponent, LazyChildComponent],
imports: [RouterModule.forChild([{
path: '',
children: [{
path: 'lazy-parent',
component: LazyParentComponent,
children: [{path: 'lazy-child', component: LazyChildComponent}]
}]
}])],
providers: [LazyLoadedServiceDefinedInModule]
})
class LoadedModule {
}
@NgModule({
declarations: [EagerParentComponent],
entryComponents: [EagerParentComponent],
imports: [RouterModule]
})
class TestModule {
}
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TestModule],
});
});
it('should use the injector of the lazily-loaded configuration',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
loader.stubbedModules = {expected: LoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'eager-parent',
component: EagerParentComponent,
children: [{path: 'lazy', loadChildren: 'expected'}]
}]);
router.navigateByUrl('/eager-parent/lazy/lazy-parent/lazy-child');
advance(fixture);
expect(location.path()).toEqual('/eager-parent/lazy/lazy-parent/lazy-child');
expect(fixture.nativeElement).toHaveText('eager-parent lazy-parent lazy-child');
})));
});
it('works when given a callback',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader], (router: Router, location: Location) => {
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])],
})
class LoadedModule {
}
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]);
router.navigateByUrl('/lazy/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy/loaded');
expect(fixture.nativeElement).toHaveText('lazy-loaded');
})));
it('error emit an error when cannot load a config',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
loader.stubbedModules = {};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'invalid'}]);
const recordedEvents: any[] = [];
router.events.forEach(e => recordedEvents.push(e));
router.navigateByUrl('/lazy/loaded') !.catch(s => {});
advance(fixture);
expect(location.path()).toEqual('/');
expectEvents(recordedEvents, [
[NavigationStart, '/lazy/loaded'],
[RouteConfigLoadStart],
[NavigationError, '/lazy/loaded'],
]);
})));
it('should work with complex redirect rules',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])],
})
class LoadedModule {
}
loader.stubbedModules = {lazy: LoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig(
[{path: 'lazy', loadChildren: 'lazy'}, {path: '**', redirectTo: 'lazy'}]);
router.navigateByUrl('/lazy/loaded');
advance(fixture);
expect(location.path()).toEqual('/lazy/loaded');
})));
it('should work with wildcard route',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forChild([{path: '', component: LazyLoadedComponent}])],
})
class LazyLoadedModule {
}
loader.stubbedModules = {lazy: LazyLoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: '**', loadChildren: 'lazy'}]);
router.navigateByUrl('/lazy');
advance(fixture);
expect(location.path()).toEqual('/lazy');
expect(fixture.nativeElement).toHaveText('lazy-loaded');
})));
describe('preloading', () => {
beforeEach(() => {
TestBed.configureTestingModule(
{providers: [{provide: PreloadingStrategy, useExisting: PreloadAllModules}]});
const preloader = TestBed.get(RouterPreloader);
preloader.setUpPreloading();
});
it('should work',
fakeAsync(inject(
[Router, Location, NgModuleFactoryLoader],
(router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => {
@Component({selector: 'lazy', template: 'should not show'})
class LazyLoadedComponent {
}
@NgModule({
declarations: [LazyLoadedComponent],
imports: [RouterModule.forChild(
[{path: 'LoadedModule2', component: LazyLoadedComponent}])]
})
class LoadedModule2 {
}
@NgModule({
imports:
[RouterModule.forChild([{path: 'LoadedModule1', loadChildren: 'expected2'}])]
})
class LoadedModule1 {
}
loader.stubbedModules = {expected: LoadedModule1, expected2: LoadedModule2};
const fixture = createRoot(router, RootCmp);
router.resetConfig([
{path: 'blank', component: BlankCmp}, {path: 'lazy', loadChildren: 'expected'}
]);
router.navigateByUrl('/blank');
advance(fixture);
const config = router.config as any;
const firstConfig = config[1]._loadedConfig !;
expect(firstConfig).toBeDefined();
expect(firstConfig.routes[0].path).toEqual('LoadedModule1');
const secondConfig = firstConfig.routes[0]._loadedConfig !;
expect(secondConfig).toBeDefined();
expect(secondConfig.routes[0].path).toEqual('LoadedModule2');
})));
});
describe('custom url handling strategies', () => {
class CustomUrlHandlingStrategy implements UrlHandlingStrategy {
shouldProcessUrl(url: UrlTree): boolean {
return url.toString().startsWith('/include') || url.toString() === '/';
}
extract(url: UrlTree): UrlTree {
const oldRoot = url.root;
const children: any = {};
if (oldRoot.children[PRIMARY_OUTLET]) {
children[PRIMARY_OUTLET] = oldRoot.children[PRIMARY_OUTLET];
}
const root = new UrlSegmentGroup(oldRoot.segments, children);
return new (UrlTree as any)(root, url.queryParams, url.fragment);
}
merge(newUrlPart: UrlTree, wholeUrl: UrlTree): UrlTree {
const oldRoot = newUrlPart.root;
const children: any = {};
if (oldRoot.children[PRIMARY_OUTLET]) {
children[PRIMARY_OUTLET] = oldRoot.children[PRIMARY_OUTLET];
}
forEach(wholeUrl.root.children, (v: any, k: any) => {
if (k !== PRIMARY_OUTLET) {
children[k] = v;
}
v.parent = this;
});
const root = new UrlSegmentGroup(oldRoot.segments, children);
return new (UrlTree as any)(root, newUrlPart.queryParams, newUrlPart.fragment);
}
}
beforeEach(() => {
TestBed.configureTestingModule(
{providers: [{provide: UrlHandlingStrategy, useClass: CustomUrlHandlingStrategy}]});
});
it('should work',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'include',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp}
]
}]);
const events: any[] = [];
router.events.subscribe(e => e instanceof RouterEvent && events.push(e));
// supported URL
router.navigateByUrl('/include/user/kate');
advance(fixture);
expect(location.path()).toEqual('/include/user/kate');
expectEvents(events, [
[NavigationStart, '/include/user/kate'], [RoutesRecognized, '/include/user/kate'],
[GuardsCheckStart, '/include/user/kate'], [GuardsCheckEnd, '/include/user/kate'],
[ResolveStart, '/include/user/kate'], [ResolveEnd, '/include/user/kate'],
[NavigationEnd, '/include/user/kate']
]);
expect(fixture.nativeElement).toHaveText('team [ user kate, right: ]');
events.splice(0);
// unsupported URL
router.navigateByUrl('/exclude/one');
advance(fixture);
expect(location.path()).toEqual('/exclude/one');
expect(Object.keys(router.routerState.root.children).length).toEqual(0);
expect(fixture.nativeElement).toHaveText('');
expectEvents(events, [
[NavigationStart, '/exclude/one'], [GuardsCheckStart, '/exclude/one'],
[GuardsCheckEnd, '/exclude/one'], [NavigationEnd, '/exclude/one']
]);
events.splice(0);
// another unsupported URL
location.go('/exclude/two');
advance(fixture);
expect(location.path()).toEqual('/exclude/two');
expectEvents(events, []);
// back to a supported URL
location.go('/include/simple');
advance(fixture);
expect(location.path()).toEqual('/include/simple');
expect(fixture.nativeElement).toHaveText('team [ simple, right: ]');
expectEvents(events, [
[NavigationStart, '/include/simple'], [RoutesRecognized, '/include/simple'],
[GuardsCheckStart, '/include/simple'], [GuardsCheckEnd, '/include/simple'],
[ResolveStart, '/include/simple'], [ResolveEnd, '/include/simple'],
[NavigationEnd, '/include/simple']
]);
})));
it('should handle the case when the router takes only the primary url',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.resetConfig([{
path: 'include',
component: TeamCmp,
children: [
{path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp}
]
}]);
const events: any[] = [];
router.events.subscribe(e => e instanceof RouterEvent && events.push(e));
location.go('/include/user/kate(aux:excluded)');
advance(fixture);
expect(location.path()).toEqual('/include/user/kate(aux:excluded)');
expectEvents(events, [
[NavigationStart, '/include/user/kate'], [RoutesRecognized, '/include/user/kate'],
[GuardsCheckStart, '/include/user/kate'], [GuardsCheckEnd, '/include/user/kate'],
[ResolveStart, '/include/user/kate'], [ResolveEnd, '/include/user/kate'],
[NavigationEnd, '/include/user/kate']
]);
events.splice(0);
location.go('/include/user/kate(aux:excluded2)');
advance(fixture);
expectEvents(events, []);
router.navigateByUrl('/include/simple');
advance(fixture);
expect(location.path()).toEqual('/include/simple(aux:excluded2)');
expectEvents(events, [
[NavigationStart, '/include/simple'], [RoutesRecognized, '/include/simple'],
[GuardsCheckStart, '/include/simple'], [GuardsCheckEnd, '/include/simple'],
[ResolveStart, '/include/simple'], [ResolveEnd, '/include/simple'],
[NavigationEnd, '/include/simple']
]);
})));
});
describe('relativeLinkResolution', () => {
@Component({selector: 'link-cmp', template: `<a [routerLink]="['../simple']">link</a>`})
class RelativeLinkCmp {
}
@NgModule({
declarations: [RelativeLinkCmp],
imports: [RouterModule.forChild([
{path: 'foo/bar', children: [{path: '', component: RelativeLinkCmp}]},
])]
})
class LazyLoadedModule {
}
it('should not ignore empty path when in legacy mode',
fakeAsync(inject(
[Router, NgModuleFactoryLoader],
(router: Router, loader: SpyNgModuleFactoryLoader) => {
router.relativeLinkResolution = 'legacy';
loader.stubbedModules = {expected: LazyLoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]);
router.navigateByUrl('/lazy/foo/bar');
advance(fixture);
const link = fixture.nativeElement.querySelector('a');
expect(link.getAttribute('href')).toEqual('/lazy/foo/bar/simple');
})));
it('should ignore empty path when in corrected mode',
fakeAsync(inject(
[Router, NgModuleFactoryLoader],
(router: Router, loader: SpyNgModuleFactoryLoader) => {
router.relativeLinkResolution = 'corrected';
loader.stubbedModules = {expected: LazyLoadedModule};
const fixture = createRoot(router, RootCmp);
router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]);
router.navigateByUrl('/lazy/foo/bar');
advance(fixture);
const link = fixture.nativeElement.querySelector('a');
expect(link.getAttribute('href')).toEqual('/lazy/foo/simple');
})));
});
});
describe('Custom Route Reuse Strategy', () => {
class AttachDetachReuseStrategy implements RouteReuseStrategy {
stored: {[k: string]: DetachedRouteHandle} = {};
shouldDetach(route: ActivatedRouteSnapshot): boolean {
return route.routeConfig !.path === 'a';
}
store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {
this.stored[route.routeConfig !.path !] = detachedTree;
}
shouldAttach(route: ActivatedRouteSnapshot): boolean {
return !!this.stored[route.routeConfig !.path !];
}
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
return this.stored[route.routeConfig !.path !];
}
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
return future.routeConfig === curr.routeConfig;
}
}
class ShortLifecycle implements RouteReuseStrategy {
shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; }
store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {}
shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; }
retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null { return null; }
shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
if (future.routeConfig !== curr.routeConfig) {
return false;
}
if (Object.keys(future.params).length !== Object.keys(curr.params).length) {
return false;
}
return Object.keys(future.params).every(k => future.params[k] === curr.params[k]);
}
}
it('should support attaching & detaching fragments',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.routeReuseStrategy = new AttachDetachReuseStrategy();
router.resetConfig([
{
path: 'a',
component: TeamCmp,
children: [{path: 'b', component: SimpleCmp}],
},
{path: 'c', component: UserCmp},
]);
router.navigateByUrl('/a/b');
advance(fixture);
const teamCmp = fixture.debugElement.children[1].componentInstance;
const simpleCmp = fixture.debugElement.children[1].children[1].componentInstance;
expect(location.path()).toEqual('/a/b');
expect(teamCmp).toBeDefined();
expect(simpleCmp).toBeDefined();
router.navigateByUrl('/c');
advance(fixture);
expect(location.path()).toEqual('/c');
expect(fixture.debugElement.children[1].componentInstance).toBeAnInstanceOf(UserCmp);
router.navigateByUrl('/a;p=1/b;p=2');
advance(fixture);
const teamCmp2 = fixture.debugElement.children[1].componentInstance;
const simpleCmp2 = fixture.debugElement.children[1].children[1].componentInstance;
expect(location.path()).toEqual('/a;p=1/b;p=2');
expect(teamCmp2).toBe(teamCmp);
expect(simpleCmp2).toBe(simpleCmp);
expect(teamCmp.route).toBe(router.routerState.root.firstChild);
expect(teamCmp.route.snapshot).toBe(router.routerState.snapshot.root.firstChild);
expect(teamCmp.route.snapshot.params).toEqual({p: '1'});
expect(teamCmp.route.firstChild.snapshot.params).toEqual({p: '2'});
})));
it('should support shorter lifecycles',
fakeAsync(inject([Router, Location], (router: Router, location: Location) => {
const fixture = createRoot(router, RootCmp);
router.routeReuseStrategy = new ShortLifecycle();
router.resetConfig([{path: 'a', component: SimpleCmp}]);
router.navigateByUrl('/a');
advance(fixture);
const simpleCmp1 = fixture.debugElement.children[1].componentInstance;
expect(location.path()).toEqual('/a');
router.navigateByUrl('/a;p=1');
advance(fixture);
expect(location.path()).toEqual('/a;p=1');
const simpleCmp2 = fixture.debugElement.children[1].componentInstance;
expect(simpleCmp1).not.toBe(simpleCmp2);
})));
it('should not mount the component of the previously reused route when the outlet was not instantiated at the time of route activation',
fakeAsync(() => {
@Component({
selector: 'root-cmp',
template:
'<div *ngIf="isToolpanelShowing"><router-outlet name="toolpanel"></router-outlet></div>'
})
class RootCmpWithCondOutlet implements OnDestroy {
private subscription: Subscription;
public isToolpanelShowing: boolean = false;
constructor(router: Router) {
this.subscription =
router.events.pipe(filter(event => event instanceof NavigationEnd))
.subscribe(
() => this.isToolpanelShowing =
!!router.parseUrl(router.url).root.children['toolpanel']);
}
public ngOnDestroy(): void { this.subscription.unsubscribe(); }
}
@Component({selector: 'tool-1-cmp', template: 'Tool 1 showing'})
class Tool1Component {
}
@Component({selector: 'tool-2-cmp', template: 'Tool 2 showing'})
class Tool2Component {
}
@NgModule({
declarations: [RootCmpWithCondOutlet, Tool1Component, Tool2Component],
imports: [
CommonModule,
RouterTestingModule.withRoutes([
{path: 'a', outlet: 'toolpanel', component: Tool1Component},
{path: 'b', outlet: 'toolpanel', component: Tool2Component},
]),
],
})
class TestModule {
}
TestBed.configureTestingModule({imports: [TestModule]});
const router: Router = TestBed.get(Router);
router.routeReuseStrategy = new AttachDetachReuseStrategy();
const fixture = createRoot(router, RootCmpWithCondOutlet);
// Activate 'tool-1'
router.navigate([{outlets: {toolpanel: 'a'}}]);
advance(fixture);
expect(fixture).toContainComponent(Tool1Component, '(a)');
// Deactivate 'tool-1'
router.navigate([{outlets: {toolpanel: null}}]);
advance(fixture);
expect(fixture).not.toContainComponent(Tool1Component, '(b)');
// Activate 'tool-1'
router.navigate([{outlets: {toolpanel: 'a'}}]);
advance(fixture);
expect(fixture).toContainComponent(Tool1Component, '(c)');
// Deactivate 'tool-1'
router.navigate([{outlets: {toolpanel: null}}]);
advance(fixture);
expect(fixture).not.toContainComponent(Tool1Component, '(d)');
// Activate 'tool-2'
router.navigate([{outlets: {toolpanel: 'b'}}]);
advance(fixture);
expect(fixture).toContainComponent(Tool2Component, '(e)');
}));
});
});
describe('Testing router options', () => {
describe('paramsInheritanceStrategy', () => {
beforeEach(() => {
TestBed.configureTestingModule(
{imports: [RouterTestingModule.withRoutes([], {paramsInheritanceStrategy: 'always'})]});
});
it('should configure the router', fakeAsync(inject([Router], (router: Router) => {
expect(router.paramsInheritanceStrategy).toEqual('always');
})));
});
describe('malformedUriErrorHandler', () => {
function malformedUriErrorHandler(e: URIError, urlSerializer: UrlSerializer, url: string) {
return urlSerializer.parse('/error');
}
beforeEach(() => {
TestBed.configureTestingModule(
{imports: [RouterTestingModule.withRoutes([], {malformedUriErrorHandler})]});
});
it('should configure the router', fakeAsync(inject([Router], (router: Router) => {
expect(router.malformedUriErrorHandler).toBe(malformedUriErrorHandler);
})));
});
});
function expectEvents(events: Event[], pairs: any[]) {
expect(events.length).toEqual(pairs.length);
for (let i = 0; i < events.length; ++i) {
expect((<any>events[i].constructor).name).toBe(pairs[i][0].name);
expect((<any>events[i]).url).toBe(pairs[i][1]);
}
}
function onlyNavigationStartAndEnd(e: Event): boolean {
return e instanceof NavigationStart || e instanceof NavigationEnd;
}
@Component(
{selector: 'link-cmp', template: `<a routerLink="/team/33/simple" [target]="'_self'">link</a>`})
class StringLinkCmp {
}
@Component({selector: 'link-cmp', template: `<button routerLink="/team/33/simple">link</button>`})
class StringLinkButtonCmp {
}
@Component({
selector: 'link-cmp',
template: `<router-outlet></router-outlet><a [routerLink]="['/team/33/simple']">link</a>`
})
class AbsoluteLinkCmp {
}
@Component({
selector: 'link-cmp',
template:
`<router-outlet></router-outlet><a routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">link</a>
<button routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">button</button>
`
})
class DummyLinkCmp {
private exact: boolean;
constructor(route: ActivatedRoute) {
this.exact = route.snapshot.paramMap.get('exact') === 'true';
}
}
@Component({selector: 'link-cmp', template: `<a [routerLink]="['/simple']">link</a>`})
class AbsoluteSimpleLinkCmp {
}
@Component({selector: 'link-cmp', template: `<a [routerLink]="['../simple']">link</a>`})
class RelativeLinkCmp {
}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['../simple']" [queryParams]="{q: '1'}" fragment="f">link</a>`
})
class LinkWithQueryParamsAndFragment {
}
@Component({
selector: 'link-cmp',
template: `<a [routerLink]="['../simple']" [state]="{foo: 'bar'}">link</a>`
})
class LinkWithState {
}
@Component({selector: 'simple-cmp', template: `simple`})
class SimpleCmp {
}
@Component({selector: 'collect-params-cmp', template: `collect-params`})
class CollectParamsCmp {
private params: any = [];
private urls: any = [];
constructor(private route: ActivatedRoute) {
route.params.forEach(p => this.params.push(p));
route.url.forEach(u => this.urls.push(u));
}
recordedUrls(): string[] {
return this.urls.map((a: any) => a.map((p: any) => p.path).join('/'));
}
}
@Component({selector: 'blank-cmp', template: ``})
class BlankCmp {
}
@Component({
selector: 'team-cmp',
template: `team {{id | async}} ` +
`[ <router-outlet></router-outlet>, right: <router-outlet name="right"></router-outlet> ]` +
`<a [routerLink]="routerLink" skipLocationChange></a>` +
`<button [routerLink]="routerLink" skipLocationChange></button>`
})
class TeamCmp {
id: Observable<string>;
recordedParams: Params[] = [];
snapshotParams: Params[] = [];
routerLink = ['.'];
constructor(public route: ActivatedRoute) {
this.id = route.params.pipe(map((p: any) => p['id']));
route.params.forEach(p => {
this.recordedParams.push(p);
this.snapshotParams.push(route.snapshot.params);
});
}
}
@Component({
selector: 'two-outlets-cmp',
template: `[ <router-outlet></router-outlet>, aux: <router-outlet name="aux"></router-outlet> ]`
})
class TwoOutletsCmp {
}
@Component({selector: 'user-cmp', template: `user {{name | async}}`})
class UserCmp {
name: Observable<string>;
recordedParams: Params[] = [];
snapshotParams: Params[] = [];
constructor(route: ActivatedRoute) {
this.name = route.params.pipe(map((p: any) => p['name']));
route.params.forEach(p => {
this.recordedParams.push(p);
this.snapshotParams.push(route.snapshot.params);
});
}
}
@Component({selector: 'wrapper', template: `<router-outlet></router-outlet>`})
class WrapperCmp {
}
@Component(
{selector: 'query-cmp', template: `query: {{name | async}} fragment: {{fragment | async}}`})
class QueryParamsAndFragmentCmp {
name: Observable<string|null>;
fragment: Observable<string>;
constructor(route: ActivatedRoute) {
this.name = route.queryParamMap.pipe(map((p: ParamMap) => p.get('name')));
this.fragment = route.fragment;
}
}
@Component({selector: 'empty-query-cmp', template: ``})
class EmptyQueryParamsCmp {
recordedParams: Params[] = [];
constructor(route: ActivatedRoute) {
route.queryParams.forEach(_ => this.recordedParams.push(_));
}
}
@Component({selector: 'route-cmp', template: `route`})
class RouteCmp {
constructor(public route: ActivatedRoute) {}
}
@Component({
selector: 'link-cmp',
template:
`<div *ngIf="show"><a [routerLink]="['./simple']">link</a></div> <router-outlet></router-outlet>`
})
class RelativeLinkInIfCmp {
show: boolean = false;
}
@Component(
{selector: 'child', template: '<div *ngIf="alwaysTrue"><router-outlet></router-outlet></div>'})
class OutletInNgIf {
alwaysTrue = true;
}
@Component({
selector: 'link-cmp',
template: `<router-outlet></router-outlet>
<div id="link-parent" routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}">
<div ngClass="{one: 'true'}"><a [routerLink]="['./']">link</a></div>
</div>`
})
class DummyLinkWithParentCmp {
private exact: boolean;
constructor(route: ActivatedRoute) { this.exact = (<any>route.snapshot.params).exact === 'true'; }
}
@Component({selector: 'cmp', template: ''})
class ComponentRecordingRoutePathAndUrl {
private path: any;
private url: any;
constructor(router: Router, route: ActivatedRoute) {
this.path = (router.routerState as any).pathFromRoot(route);
this.url = router.url.toString();
}
}
@Component({selector: 'root-cmp', template: `<router-outlet></router-outlet>`})
class RootCmp {
}
@Component({selector: 'root-cmp-on-init', template: `<router-outlet></router-outlet>`})
class RootCmpWithOnInit {
constructor(private router: Router) {}
ngOnInit(): void { this.router.navigate(['one']); }
}
@Component({
selector: 'root-cmp',
template:
`primary [<router-outlet></router-outlet>] right [<router-outlet name="right"></router-outlet>]`
})
class RootCmpWithTwoOutlets {
}
@Component({selector: 'root-cmp', template: `main [<router-outlet name="main"></router-outlet>]`})
class RootCmpWithNamedOutlet {
}
@Component({selector: 'throwing-cmp', template: ''})
class ThrowingCmp {
constructor() { throw new Error('Throwing Cmp'); }
}
function advance(fixture: ComponentFixture<any>, millis?: number): void {
tick(millis);
fixture.detectChanges();
}
function createRoot(router: Router, type: any): ComponentFixture<any> {
const f = TestBed.createComponent(type);
advance(f);
router.initialNavigation();
advance(f);
return f;
}
@Component({selector: 'lazy', template: 'lazy-loaded'})
class LazyComponent {
}
@NgModule({
imports: [RouterTestingModule, CommonModule],
entryComponents: [
BlankCmp,
SimpleCmp,
TwoOutletsCmp,
TeamCmp,
UserCmp,
StringLinkCmp,
DummyLinkCmp,
AbsoluteLinkCmp,
AbsoluteSimpleLinkCmp,
RelativeLinkCmp,
DummyLinkWithParentCmp,
LinkWithQueryParamsAndFragment,
LinkWithState,
CollectParamsCmp,
QueryParamsAndFragmentCmp,
StringLinkButtonCmp,
WrapperCmp,
OutletInNgIf,
ComponentRecordingRoutePathAndUrl,
RouteCmp,
RootCmp,
RelativeLinkInIfCmp,
RootCmpWithTwoOutlets,
RootCmpWithNamedOutlet,
EmptyQueryParamsCmp,
ThrowingCmp
],
exports: [
BlankCmp,
SimpleCmp,
TwoOutletsCmp,
TeamCmp,
UserCmp,
StringLinkCmp,
DummyLinkCmp,
AbsoluteLinkCmp,
AbsoluteSimpleLinkCmp,
RelativeLinkCmp,
DummyLinkWithParentCmp,
LinkWithQueryParamsAndFragment,
LinkWithState,
CollectParamsCmp,
QueryParamsAndFragmentCmp,
StringLinkButtonCmp,
WrapperCmp,
OutletInNgIf,
ComponentRecordingRoutePathAndUrl,
RouteCmp,
RootCmp,
RootCmpWithOnInit,
RelativeLinkInIfCmp,
RootCmpWithTwoOutlets,
RootCmpWithNamedOutlet,
EmptyQueryParamsCmp,
ThrowingCmp
],
declarations: [
BlankCmp,
SimpleCmp,
TeamCmp,
TwoOutletsCmp,
UserCmp,
StringLinkCmp,
DummyLinkCmp,
AbsoluteLinkCmp,
AbsoluteSimpleLinkCmp,
RelativeLinkCmp,
DummyLinkWithParentCmp,
LinkWithQueryParamsAndFragment,
LinkWithState,
CollectParamsCmp,
QueryParamsAndFragmentCmp,
StringLinkButtonCmp,
WrapperCmp,
OutletInNgIf,
ComponentRecordingRoutePathAndUrl,
RouteCmp,
RootCmp,
RootCmpWithOnInit,
RelativeLinkInIfCmp,
RootCmpWithTwoOutlets,
RootCmpWithNamedOutlet,
EmptyQueryParamsCmp,
ThrowingCmp
]
})
class TestModule {
}
| hansl/angular | packages/router/test/integration.spec.ts | TypeScript | mit | 182,197 |
/*global require module*/
var q = require('q');
var async = require('async');
var constants = require('./_constants');
var Logger = require('./logger');
var CompiledNode = require('./compiled-node');
var EvaluatedNode = require('./evaluated-node');
var _8a2a4f008c464f9b81b3b5f4e75772c5 = {
evaluateValue: function(mapper, logger, parent, name, instanceNode, requiredOnly) {
var evaluated = new EvaluatedNode(this);
evaluated.content = this.value;
return q().then(function () {
return evaluated;
});
},
evaluateObject: function(mapper, logger, parent, name, instanceNode, requiredOnly) {
var self = this;
var defer = q.defer();
var hasMissingNode = false;
var evaluated = new EvaluatedNode(this);
evaluated.children = (this.children instanceof Array) ? [] : {};
evaluated.content = (this.children instanceof Array) ? [] : {};
async.each(
Object.keys(self.children),
function (key, done) {
self.children[key].evaluate(mapper, logger, evaluated, key, instanceNode).then(function (child) {
evaluated.children[key] = child;
evaluated.content[key] = child.content;
hasMissingNode = hasMissingNode || child.isMissing;
})
.finally(function () {
done();
})
},
function (err) {
if (hasMissingNode) {
evaluated.content = null;
evaluated.isMissing = (self.isRequired);
}
defer.resolve(evaluated);
}
);
return defer.promise
}
};
module.exports = Module;
/*------------------------------------------------------------------------------
A module contains 0, 1 or more properties
A property contains 0 or 1 selector and 0 or 1 module
------------------------------------------------------------------------------*/
function Module(source) {
var helper = _8a2a4f008c464f9b81b3b5f4e75772c5;
function getSource(mapper, logger) {
function _getSource(source) {
if (source) {
if (typeof(source) === 'function') {
return _getSource(source(mapper, logger));
}
if (typeof(source.getSource) === 'function') {
return _getSource(source.getSource(mapper, logger));
}
}
return source;
}
return _getSource(source);
}
function validate(mapper, instanceNode, logger) {
return q().then(function () {
return getSourceModule(mapper, module);
})
.then(function (module) {
if (module === undefined) {
return true;
}
else if (module === null) {
return true;
}
else if (typeof(module.validate) === 'function') {
return module.validate(mapper, instanceNode);
}
else {
return true;
}
});
}
function __compile(parent, source, name) {
var compiled = new CompiledNode(null, null, parent, name);
if (source !== undefined && source !== null) {
var content = source.content;
if (content === undefined) {
compiled.value = content;
compiled.setIsRequired(false);
compiled._evaluate = helper.evaluateValue;
}
else if (content === null) {
compiled.value = content;
compiled.setIsRequired(false);
compiled._evaluate = helper.evaluateValue;
}
else if (content.$isModule) {
compiled = content._compile(parent, name);
}
else if (content[constants.interface.compile]) {
compiled = content[constants.interface.compile]._compile(parent, name);
}
else if (typeof(content) === 'object') {
compiled._evaluate = helper.evaluateObject;
compiled.children = (content instanceof Array) ? [] : {};
compiled.newContent();
var keys = Object.keys(content);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var child = __compile(compiled, {content: content[key]}, key);
compiled.children[key] = child;
compiled.content[key] = child.content;
}
}
else {
compiled.value = content;
compiled.setIsRequired(false);
compiled._evaluate = helper.evaluateValue;
}
}
return compiled;
}
function _compile(parent, name) {
var logger = parent.logger;
var containingModule = parent.mapper && parent.mapper.containingModule;
var mapper = parent.mapper && parent.mapper.newChild(logger, containingModule);
var source = getSource(mapper, module);
return __compile(parent, source, name);
}
function compile(mapper, logger) {
var compiled = new CompiledNode(mapper, logger);
return _compile(compiled, '');
}
return {
$isModule: true,
logger: null,
getSource: function (mapper, logger) {
return getSource(mapper, logger);
},
validate: function (mapper, instanceNode, logger) {
return validate.call(this, mapper, instanceNode, logger || this.logger);
},
_compile: function (parent, name) {
return _compile(parent, name);
},
compile: function (mapper, logger) {
return compile(mapper, logger || this.logger).content;
},
evaluate: function (mapper, instanceNode, logger) {
var api = this.compile(mapper, logger);
api._ = instanceNode;
return api._;
},
setLogger: function (val) {
this.logger = val;
return this;
}
};
}
| cellanda/flexapi-core-js | lib/module.js | JavaScript | mit | 6,246 |
from setuptools import setup, find_packages
setup(
name="Coinbox-mod-customer",
version="0.2",
packages=find_packages(),
zip_safe=True,
namespace_packages=['cbmod'],
include_package_data=True,
install_requires=[
'sqlalchemy>=0.7, <1.0',
'PyDispatcher>=2.0.3, <3.0',
'ProxyTypes>=0.9, <1.0',
'Babel>=1.3, <2.0',
'PySide>=1.0,<2.0'
],
author='Coinbox POS Team',
author_email='coinboxpos@googlegroups.com',
description='Coinbox POS customer module',
license='MIT',
url='http://coinboxpos.org/'
)
| coinbox/coinbox-mod-customer | setup.py | Python | mit | 654 |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__char_file_w32_spawnv_82_bad.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-82_bad.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: file Read input from a file
* GoodSource: Fixed string
* Sinks: w32_spawnv
* BadSink : execute command with spawnv
* Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE78_OS_Command_Injection__char_file_w32_spawnv_82.h"
#include <process.h>
namespace CWE78_OS_Command_Injection__char_file_w32_spawnv_82
{
void CWE78_OS_Command_Injection__char_file_w32_spawnv_82_bad::action(char * data)
{
{
char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL};
/* spawnv - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
_spawnv(_P_WAIT, COMMAND_INT_PATH, args);
}
}
}
#endif /* OMITBAD */
| maurer/tiamat | samples/Juliet/testcases/CWE78_OS_Command_Injection/s04/CWE78_OS_Command_Injection__char_file_w32_spawnv_82_bad.cpp | C++ | mit | 1,190 |
//= require jquery3
//= require popper
//= require bootstrap
//= require turbolinks
//= require_tree . | mrysav/familiar | app/assets/javascripts/application.js | JavaScript | mit | 102 |
module Quovo
module Models
class IframeToken < Base
fields %i(
user
token
)
def url
"https://embed.quovo.com/auth/#{token}"
end
end
end
end
| CanopyFA/quovo-ruby | lib/quovo/models/iframe_token.rb | Ruby | mit | 200 |
#include "sendmessagedialog.h"
#include "ui_sendmessagedialog.h"
#include "clientcommandmanager.h"
#include "clientcommand.h"
SendMessageDialog::SendMessageDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SendMessageDialog)
{
ui->setupUi(this);
errorPopup = new ErrorPopup();
attach(errorPopup);
}
SendMessageDialog::~SendMessageDialog()
{
delete errorPopup;
delete ui;
}
void SendMessageDialog::on_buttonBox_accepted()
{
QByteArray receiverByteArray = ui->friendname_lineedit->text().toUtf8();
const char* receiver = receiverByteArray.constData();
QByteArray messageByteArray = ui->message_textedit->toPlainText().toUtf8();
const char* message = messageByteArray.constData();
// call client command to send a message
int retVal = ClientCommandManager::clientCommand->SendCommand(receiver, message);
if (retVal == -1) {
// char message[] = "SendCommand error\0";
changeMessage( "SendCommand error\0");
}
if (retVal == 0) {
// char message[] = "message sent!\0";
changeMessage("message sent!\0");
}
}
void SendMessageDialog::on_unfriend_button_clicked()
{
if (ui->friendname_lineedit->text().isEmpty()) {
char message[] = "please enter your \"friend\"'s name first!\0";
changeMessage((std::string) message);
return;
}
QByteArray friendNameByteArray = ui->friendname_lineedit->text().toUtf8();
const char* friendName = friendNameByteArray.constData();
// CALL CLIENTCOMMAND TO UNFRIEND
int retVal = ClientCommandManager::clientCommand->UnCommand(friendName);
if (retVal == -1) {
char message[] = "unfriend error\0";
changeMessage((std::string) message);
}
if (retVal == 0) {
char message[] = "unfriend success\0";
changeMessage((std::string) message);
}
}
void SendMessageDialog::changeMessage(std::string _message) {
message = _message;
notify(message);
}
std::string SendMessageDialog::getMessage() {
return message;
}
void SendMessageDialog::setReceiver(std::string username) {
QString qstr = QString::fromStdString(username);
ui->friendname_lineedit->setText(qstr);
}
| taragu/sharefile | sharefileclient/sendmessagedialog.cpp | C++ | mit | 2,196 |
<?php
namespace Etk\Bundle\AdminBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* This is the class that validates and merges configuration from your app/config files
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
*/
class Configuration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('etk_admin');
// Here you should define the parameters that are allowed to
// configure your bundle. See the documentation linked above for
// more information on that topic.
return $treeBuilder;
}
}
| eibertek/etek10 | src/Etk/Bundle/AdminBundle/DependencyInjection/Configuration.php | PHP | mit | 909 |
<?php
namespace spec\GrumPHP\Runner;
use GrumPHP\Runner\TaskResult;
use GrumPHP\Task\Context\ContextInterface;
use GrumPHP\Task\TaskInterface;
use PhpSpec\ObjectBehavior;
class TaskResultSpec extends ObjectBehavior
{
const FAILED_TASK_MESSAGE = 'failed task message';
function it_creates_passed_task(TaskInterface $task, ContextInterface $context)
{
$this->beConstructedThrough('createPassed', array($task, $context));
$this->getTask()->shouldBe($task);
$this->getResultCode()->shouldBe(TaskResult::PASSED);
$this->isPassed()->shouldBe(true);
$this->getMessage()->shouldBeNull();
}
function it_creates_failed_task(TaskInterface $task, ContextInterface $context)
{
$this->beConstructedThrough('createFailed', array($task, $context, self::FAILED_TASK_MESSAGE));
$this->getTask()->shouldBe($task);
$this->getResultCode()->shouldBe(TaskResult::FAILED);
$this->isPassed()->shouldBe(false);
$this->getMessage()->shouldBe(self::FAILED_TASK_MESSAGE);
}
function it_creates_skipped_task(TaskInterface $task, ContextInterface $context)
{
$this->beConstructedThrough('createSkipped', array($task, $context));
$this->getTask()->shouldBe($task);
$this->getResultCode()->shouldBe(TaskResult::SKIPPED);
$this->isPassed()->shouldBe(false);
}
function it_should_be_a_blocking_task_if_it_is_a_failed_task(TaskInterface $task, ContextInterface $context)
{
$this->beConstructedThrough('createFailed', array($task, $context, self::FAILED_TASK_MESSAGE));
$this->isBlocking()->shouldBe(true);
}
function it_should_not_be_a_blocking_task_if_it_is_a_passed_task(TaskInterface $task, ContextInterface $context)
{
$this->beConstructedThrough('createPassed', array($task, $context, self::FAILED_TASK_MESSAGE));
$this->isBlocking()->shouldBe(false);
}
function it_should_not_be_a_blocking_task_if_it_is_a_non_blocking_failed_task(TaskInterface $task, ContextInterface $context)
{
$this->beConstructedThrough('createNonBlockingFailed', array($task, $context, self::FAILED_TASK_MESSAGE));
$this->isBlocking()->shouldBe(false);
}
}
| mikechernev/grumphp | spec/GrumPHP/Runner/TaskResultSpec.php | PHP | mit | 2,248 |
#!/usr/bin/env node
const
fs = require('mz/fs'),
path = require('path'),
Promise = require('bluebird'),
mongoose = require('mongoose'),
uuid = require('uuid4')
const config = require('../config/api_options.json')
const MongoUtil = require('../dist/server/lib/mongo-util').default
const Order = require('../dist/server/models/order').default
const Ticket = require('../dist/server/models/ticket').default
mongoose.Promise = Promise
mongoose.connect(config.mongodb.dburl, { useMongoClient: true })
mongoose.model('Order', Order)
mongoose.model('Ticket', Ticket)
fs.readFile(path.join(__dirname, '..', 'booth.csv')).then(async data => {
const entries = data.toString().split('\n').map(line => {
const parts = line.split(',')
return { firstname: parts[0], lastname: parts[1], email: parts[2] }
})
for (let entry of entries) {
const orderobj = {
uuid: uuid(),
email: entry.email.trim(),
firstname: entry.firstname || ' ',
lastname: entry.lastname || ' ',
ticket_category: 'booth'
}
const order = await MongoUtil.model('Order').create(orderobj)
const ticket = await MongoUtil.model('Ticket').create({
uuid: uuid(),
firstname: entry.firstname || ' ',
lastname: entry.lastname || ' ',
category: 'booth',
type: 'festival',
order_uuid: order.uuid,
issued: new Date(),
price: {
amount: 0.0,
currency: 'eur'
}
})
const od = await MongoUtil.model('Order').findOne({ uuid: order.uuid }).populate('tickets')
await od.authorizeTicket()
console.log(order.uuid, ticket.uuid)
}
}).then(() => {
process.exit(0)
}).catch(err => {
throw err
})
| dasantonym/nano-ticketron-xl | bin/import-booth.js | JavaScript | mit | 1,688 |
package admin
import (
"encoding/json"
"errors"
"fmt"
)
const (
// ErrUserExists - Attempt to create existing user
ErrUserExists errorReason = "UserAlreadyExists"
// ErrNoSuchUser - Attempt to create existing user
ErrNoSuchUser errorReason = "NoSuchUser"
// ErrInvalidAccessKey - Invalid access key specified
ErrInvalidAccessKey errorReason = "InvalidAccessKey"
// ErrInvalidSecretKey - Invalid secret key specified
ErrInvalidSecretKey errorReason = "InvalidSecretKey"
// ErrInvalidKeyType - Invalid key type specified
ErrInvalidKeyType errorReason = "InvalidKeyType"
// ErrKeyExists - Provided access key exists and belongs to another user
ErrKeyExists errorReason = "KeyExists"
// ErrEmailExists - Provided email address exists
ErrEmailExists errorReason = "EmailExists"
// ErrInvalidCapability - Attempt to remove an invalid admin capability
ErrInvalidCapability errorReason = "InvalidCapability"
// ErrSubuserExists - Specified subuser exists
ErrSubuserExists errorReason = "SubuserExists"
// ErrInvalidAccess - Invalid subuser access specified
ErrInvalidAccess errorReason = "InvalidAccess"
// ErrIndexRepairFailed - Bucket index repair failed
ErrIndexRepairFailed errorReason = "IndexRepairFailed"
// ErrBucketNotEmpty - Attempted to delete non-empty bucket
ErrBucketNotEmpty errorReason = "BucketNotEmpty"
// ErrObjectRemovalFailed - Unable to remove objects
ErrObjectRemovalFailed errorReason = "ObjectRemovalFailed"
// ErrBucketUnlinkFailed - Unable to unlink bucket from specified user
ErrBucketUnlinkFailed errorReason = "BucketUnlinkFailed"
// ErrBucketLinkFailed - Unable to link bucket to specified user
ErrBucketLinkFailed errorReason = "BucketLinkFailed"
// ErrNoSuchObject - Specified object does not exist
ErrNoSuchObject errorReason = "NoSuchObject"
// ErrIncompleteBody - Either bucket was not specified for a bucket policy request or bucket and object were not specified for an object policy request.
ErrIncompleteBody errorReason = "IncompleteBody"
// ErrNoSuchCap - User does not possess specified capability
ErrNoSuchCap errorReason = "NoSuchCap"
// ErrInternalError - Internal server error.
ErrInternalError errorReason = "InternalError"
// ErrAccessDenied - Access denied.
ErrAccessDenied errorReason = "AccessDenied"
// ErrNoSuchBucket - Bucket does not exist.
ErrNoSuchBucket errorReason = "NoSuchBucket"
// ErrNoSuchKey - No such access key.
ErrNoSuchKey errorReason = "NoSuchKey"
// ErrInvalidArgument - Invalid argument.
ErrInvalidArgument errorReason = "InvalidArgument"
// ErrUnknown - reports an unknown error
ErrUnknown errorReason = "Unknown"
// ErrSignatureDoesNotMatch - the query to the API has invalid parameters
ErrSignatureDoesNotMatch errorReason = "SignatureDoesNotMatch"
unmarshalError = "failed to unmarshal radosgw http response"
)
var (
errMissingUserID = errors.New("missing user ID")
errMissingUserAccessKey = errors.New("missing user access key")
errMissingUserDisplayName = errors.New("missing user display name")
errMissingUserCap = errors.New("missing user capabilities")
)
// errorReason is the reason of the error
type errorReason string
// statusError is the API response when an error occurs
type statusError struct {
Code string `json:"Code,omitempty"`
RequestID string `json:"RequestId,omitempty"`
HostID string `json:"HostId,omitempty"`
}
func handleStatusError(decodedResponse []byte) error {
statusError := statusError{}
err := json.Unmarshal(decodedResponse, &statusError)
if err != nil {
return fmt.Errorf("%s. %s. %w", unmarshalError, string(decodedResponse), err)
}
return statusError
}
func (e errorReason) Error() string { return string(e) }
// Is determines whether the error is known to be reported
func (e statusError) Is(target error) bool { return target == errorReason(e.Code) }
// Error returns non-empty string if there was an error.
func (e statusError) Error() string { return fmt.Sprintf("%s %s %s", e.Code, e.RequestID, e.HostID) }
| ceph/go-ceph | rgw/admin/errors.go | GO | mit | 4,043 |
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace Sylius\Behat\Context\Ui\Admin;
use Behat\Behat\Context\Context;
use Sylius\Behat\Element\Admin\TopBarElementInterface;
use Sylius\Behat\NotificationType;
use Sylius\Behat\Page\Admin\Administrator\CreatePageInterface;
use Sylius\Behat\Page\Admin\Administrator\UpdatePageInterface;
use Sylius\Behat\Page\Admin\Crud\IndexPageInterface;
use Sylius\Behat\Service\NotificationCheckerInterface;
use Sylius\Behat\Service\SharedStorageInterface;
use Sylius\Component\Core\Model\AdminUserInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Webmozart\Assert\Assert;
final class ManagingAdministratorsContext implements Context
{
/** @var CreatePageInterface */
private $createPage;
/** @var IndexPageInterface */
private $indexPage;
/** @var UpdatePageInterface */
private $updatePage;
/** @var TopBarElementInterface */
private $topBarElement;
/** @var NotificationCheckerInterface */
private $notificationChecker;
/** @var RepositoryInterface */
private $adminUserRepository;
/** @var SharedStorageInterface */
private $sharedStorage;
public function __construct(
CreatePageInterface $createPage,
IndexPageInterface $indexPage,
UpdatePageInterface $updatePage,
TopBarElementInterface $topBarElement,
NotificationCheckerInterface $notificationChecker,
RepositoryInterface $adminUserRepository,
SharedStorageInterface $sharedStorage
) {
$this->createPage = $createPage;
$this->indexPage = $indexPage;
$this->updatePage = $updatePage;
$this->topBarElement = $topBarElement;
$this->notificationChecker = $notificationChecker;
$this->adminUserRepository = $adminUserRepository;
$this->sharedStorage = $sharedStorage;
}
/**
* @Given I want to create a new administrator
*/
public function iWantToCreateANewAdministrator()
{
$this->createPage->open();
}
/**
* @Given /^I am editing (my) details$/
* @When /^I want to edit (this administrator)$/
*/
public function iWantToEditThisAdministrator(AdminUserInterface $adminUser)
{
$this->updatePage->open(['id' => $adminUser->getId()]);
}
/**
* @When I browse administrators
* @When I want to browse administrators
*/
public function iWantToBrowseAdministrators()
{
$this->indexPage->open();
}
/**
* @When I specify its name as :username
* @When I do not specify its name
*/
public function iSpecifyItsNameAs($username = null)
{
$this->createPage->specifyUsername($username ?? '');
}
/**
* @When I change its name to :username
*/
public function iChangeItsNameTo($username)
{
$this->updatePage->changeUsername($username);
}
/**
* @When I specify its email as :email
* @When I do not specify its email
*/
public function iSpecifyItsEmailAs($email = null)
{
$this->createPage->specifyEmail($email ?? '');
}
/**
* @When I change its email to :email
*/
public function iChangeItsEmailTo($email)
{
$this->updatePage->changeEmail($email);
}
/**
* @When I specify its locale as :localeCode
*/
public function iSpecifyItsLocaleAs($localeCode)
{
$this->createPage->specifyLocale($localeCode);
}
/**
* @When I set my locale to :localeCode
*/
public function iSetMyLocaleTo($localeCode)
{
$this->updatePage->changeLocale($localeCode);
$this->updatePage->saveChanges();
}
/**
* @When I specify its password as :password
* @When I do not specify its password
*/
public function iSpecifyItsPasswordAs($password = null)
{
$this->createPage->specifyPassword($password ?? '');
}
/**
* @When I change its password to :password
*/
public function iChangeItsPasswordTo($password)
{
$this->updatePage->changePassword($password);
}
/**
* @When I enable it
*/
public function iEnableIt()
{
$this->createPage->enable();
}
/**
* @When I add it
* @When I try to add it
*/
public function iAddIt()
{
$this->createPage->create();
}
/**
* @When I save my changes
*/
public function iSaveMyChanges()
{
$this->updatePage->saveChanges();
}
/**
* @When I delete administrator with email :email
*/
public function iDeleteAdministratorWithEmail($email)
{
$this->indexPage->deleteResourceOnPage(['email' => $email]);
}
/**
* @When I check (also) the :email administrator
*/
public function iCheckTheAdministrator(string $email): void
{
$this->indexPage->checkResourceOnPage(['email' => $email]);
}
/**
* @When I delete them
*/
public function iDeleteThem(): void
{
$this->indexPage->bulkDelete();
}
/**
* @When /^I (?:|upload|update) the "([^"]+)" image as (my) avatar$/
*/
public function iUploadTheImageAsMyAvatar(string $avatar, AdminUserInterface $administrator): void
{
$path = $this->updateAvatar($avatar, $administrator);
$this->sharedStorage->set($avatar, $path);
}
/**
* @Then the administrator :email should appear in the store
* @Then I should see the administrator :email in the list
* @Then there should still be only one administrator with an email :email
*/
public function theAdministratorShouldAppearInTheStore($email)
{
$this->indexPage->open();
Assert::true($this->indexPage->isSingleResourceOnPage(['email' => $email]));
}
/**
* @Then this administrator with name :username should appear in the store
* @Then there should still be only one administrator with name :username
*/
public function thisAdministratorWithNameShouldAppearInTheStore($username)
{
$this->indexPage->open();
Assert::true($this->indexPage->isSingleResourceOnPage(['username' => $username]));
}
/**
* @Then I should see a single administrator in the list
* @Then /^there should be (\d+) administrators in the list$/
*/
public function iShouldSeeAdministratorsInTheList(int $number = 1): void
{
Assert::same($this->indexPage->countItems(), (int) $number);
}
/**
* @Then I should be notified that email must be unique
*/
public function iShouldBeNotifiedThatEmailMustBeUnique()
{
Assert::same($this->createPage->getValidationMessage('email'), 'This email is already used.');
}
/**
* @Then I should be notified that name must be unique
*/
public function iShouldBeNotifiedThatNameMustBeUnique()
{
Assert::same($this->createPage->getValidationMessage('name'), 'This username is already used.');
}
/**
* @Then I should be notified that the :elementName is required
*/
public function iShouldBeNotifiedThatFirstNameIsRequired($elementName)
{
Assert::same($this->createPage->getValidationMessage($elementName), sprintf('Please enter your %s.', $elementName));
}
/**
* @Then I should be notified that this email is not valid
*/
public function iShouldBeNotifiedThatEmailIsNotValid()
{
Assert::same($this->createPage->getValidationMessage('email'), 'This email is invalid.');
}
/**
* @Then this administrator should not be added
*/
public function thisAdministratorShouldNotBeAdded()
{
$this->indexPage->open();
Assert::same($this->indexPage->countItems(), 1);
}
/**
* @Then there should not be :email administrator anymore
*/
public function thereShouldBeNoAnymore($email)
{
Assert::false($this->indexPage->isSingleResourceOnPage(['email' => $email]));
}
/**
* @Then I should be notified that it cannot be deleted
*/
public function iShouldBeNotifiedThatItCannotBeDeleted()
{
$this->notificationChecker->checkNotification(
'Cannot remove currently logged in user.',
NotificationType::failure()
);
}
/**
* @Then /^I should see the "([^"]*)" image as (my) avatar$/
*/
public function iShouldSeeTheImageAsMyAvatar(string $avatar, AdminUserInterface $administrator): void
{
/** @var AdminUserInterface $administrator */
$administrator = $this->adminUserRepository->findOneBy(['id' => $administrator->getId()]);
$this->updatePage->open(['id' => $administrator->getId()]);
Assert::same($this->sharedStorage->get($avatar), $administrator->getAvatar()->getPath());
}
/**
* @Then /^I should see the "([^"]*)" avatar image in the top bar next to my name$/
*/
public function iShouldSeeTheAvatarImageInTheTopBarNextToMyName(string $avatar): void
{
Assert::true($this->topBarElement->hasAvatarInMainBar($avatar));
}
private function getAdministrator(AdminUserInterface $administrator): AdminUserInterface
{
/** @var AdminUserInterface $administrator */
$administrator = $this->adminUserRepository->findOneBy(['id' => $administrator->getId()]);
return $administrator;
}
private function getPath(AdminUserInterface $administrator): string
{
$administrator = $this->getAdministrator($administrator);
$avatar = $administrator->getAvatar();
if (null === $avatar) {
return '';
}
return $avatar->getPath() ?? '';
}
private function updateAvatar(string $avatar, AdminUserInterface $administrator): string
{
$this->updatePage->attachAvatar($avatar);
$this->updatePage->saveChanges();
return $this->getPath($administrator);
}
}
| Brille24/Sylius | src/Sylius/Behat/Context/Ui/Admin/ManagingAdministratorsContext.php | PHP | mit | 10,196 |
<?php
/* @var $this RateToEurController */
/* @var $model CurrencyRateToEur */
?>
<div class="col-sm-3">
<?php $this->renderPartial('_menu', array('model' => $model, 'action' => 'view')); ?>
</div>
<div class="col-sm-9">
<br>
<h3 class="text-center"><?php echo Yii::t('CurrencyModule.view', 'Rate Data'); ?></h3>
<br>
<?php $this->widget('TbDetailView', array(
'data' => $model,
'attributes' => array(
'currency_from',
'checked',
'value',
),
)); ?>
</div>
| Anastaszor/yii1-currency | views/admin/rateToEur/view.php | PHP | mit | 474 |
<?xml version="1.0" ?><!DOCTYPE TS><TS language="tr" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About virtauniquecoin</source>
<translation>virtauniquecoin Hakkında</translation>
</message>
<message>
<location line="+39"/>
<source><b>virtauniquecoin</b> version</source>
<translation><b>virtauniquecoin</b> versiyonu</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2014 virtauniquecoin team
Copyright © 2014 The virtauniquecoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source>
<translation>
Bu, deneysel bir yazılımdır.
MIT/X11 yazılım lisansı kapsamında yayınlanmıştır, beraberindeki COPYING dosyasına ya da http://www.opensource.org/licenses/mit-license.php sayfasına bakınız.
Bu ürün, OpenSSL Araç Takımı'nda (http://www.openssl.org/) kullanılmak üzere OpenSSL projesi tarafından geliştirilen yazılımı, Eric Young (eay@cryptsoft.com) tarafından hazırlanmış kriptografik yazılımı ve Thomas Bernard tarafından yazılmış UPnP yazılımı içerir.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adres Defteri</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Adresi ya da etiketi düzenlemek için çift tıklayınız</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Yeni bir adres oluştur</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Seçili adresi sistem panosuna kopyala</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Yeni Adres</translation>
</message>
<message>
<location line="-46"/>
<source>These are your virtauniquecoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>Bunlar, ödeme almak için virtauniquecoin adreslerinizdir. Her bir göndericiye farklı birini verebilir, böylece size kimin ödeme yaptığını takip edebilirsiniz.</translation>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>Adresi &Kopyala</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>&QR Kodunu Göster</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a virtauniquecoin address</source>
<translation>Bir virtauniquecoin adresine sahip olduğunu ispatlamak için bir mesaj imzala</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Mesaj İmzala</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Seçili adresi listeden sil</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified virtauniquecoin address</source>
<translation>Mesajın, belirli bir virtauniquecoin adresiyle imzalandığından emin olmak için onu doğrula</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>Mesajı &Doğrula</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Sil</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>&Etiketi Kopyala</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Düzenle</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation>Adres Defteri Verisini Dışarı Aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Dışarı aktarım hatası</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Parola Diyaloğu</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Parolayı giriniz</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Yeni parola</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Yeni parolayı tekrarlayınız</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>OS hesabı tehlike girdiğinde önemsiz para gönderme özelliğini devre dışı bırakmayı sağlar. Gerçek anlamda bir güvenlik sağlamaz.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Sadece pay almak için</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<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>Cüzdanınız için yeni parolayı giriniz.<br/>Lütfen <b>10 ya da daha fazla rastgele karakter</b> veya <b>sekiz ya da daha fazla kelime</b> içeren bir parola seçiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Cüzdanı şifrele</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Bu işlem cüzdan kilidini açmak için cüzdan parolanızı gerektirir.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Cüzdan kilidini aç</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Bu işlem, cüzdan şifresini açmak için cüzdan parolasını gerektirir.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Cüzdan şifresini aç</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Parolayı değiştir</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Cüzdan için eski ve yeni parolaları giriniz.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Cüzdan şifrelenmesini teyit eder</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>Uyarı: Eğer cüzdanınızı şifreleyip parolanızı kaybederseniz, <b> TÜM COINLERİNİZİ KAYBEDECEKSİNİZ</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Cüzdanınızı şifrelemek istediğinizden emin misiniz?</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>ÖNEMLİ: Önceden yapmış olduğunuz cüzdan dosyası yedeklemelerinin yeni oluşturulan, şifrelenmiş cüzdan dosyası ile değiştirilmeleri gerekmektedir. Güvenlik nedenleriyle yeni, şifrelenmiş cüzdanı kullanmaya başladığınızda, şifrelenmemiş cüzdan dosyasının önceki yedekleri işe yaramaz hale gelecektir.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Uyarı: Caps Lock tuşu faal durumda!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Cüzdan şifrelendi</translation>
</message>
<message>
<location line="-58"/>
<source>virtauniquecoin 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>virtauniquecoin, şifreleme işlemini tamamlamak için şimdi kapatılacak. Cüzdanınızı şifrelemenin; coinlerinizin, bilgisayarınızı etkileyen zararlı yazılımlar tarafından çalınmasını bütünüyle engelleyemeyebileceğini unutmayınız.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Cüzdan şifrelemesi başarısız oldu</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dahili bir hata sebebiyle cüzdan şifrelemesi başarısız oldu. Cüzdanınız şifrelenmedi.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Girilen parolalar birbirleriyle eşleşmiyor.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Cüzdan kilidinin açılması başarısız oldu</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Cüzdan şifresinin açılması için girilen parola yanlıştı.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Cüzdan şifresinin açılması başarısız oldu</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Cüzdan parolası başarılı bir şekilde değiştirildi.</translation>
</message>
</context>
<context>
<name>virtauniquecoinGUI</name>
<message>
<location filename="../virtauniquecoingui.cpp" line="+282"/>
<source>Sign &message...</source>
<translation>&Mesaj imzala...</translation>
</message>
<message>
<location line="+251"/>
<source>Synchronizing with network...</source>
<translation>Ağ ile senkronizasyon...</translation>
</message>
<message>
<location line="-319"/>
<source>&Overview</source>
<translation>&Genel bakış</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Cüzdana genel bakışı göster</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&İşlemler</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>İşlem geçmişine göz at</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Adres Defteri</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Kayıtlı adresler ve etiketler listesini düzenle</translation>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation>Coin &al</translation>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Ödeme almak için kullanılan adres listesini göster</translation>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation>Coin &gönder</translation>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>&Çık</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Uygulamadan çık</translation>
</message>
<message>
<location line="+6"/>
<source>Show information about virtauniquecoin</source>
<translation>virtauniquecoin hakkındaki bilgiyi göster</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>&Qt hakkında</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Qt hakkındaki bilgiyi göster</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Seçenekler...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>Cüzdanı &Şifrele...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Cüzdanı &Yedekle...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Parolayı &Değiştir...</translation>
</message>
<message numerus="yes">
<location line="+259"/>
<source>~%n block(s) remaining</source>
<translation><numerusform>~%n blok kaldı</numerusform><numerusform>~%n blok kaldı</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation>İşlem geçmişindeki %2 bloğun %1'i indirildi (%3% tamamlandı).</translation>
</message>
<message>
<location line="-256"/>
<source>&Export...</source>
<translation>&Dışarı aktar...</translation>
</message>
<message>
<location line="-64"/>
<source>Send coins to a virtauniquecoin address</source>
<translation>Bir virtauniquecoin adresine coin gönder</translation>
</message>
<message>
<location line="+47"/>
<source>Modify configuration options for virtauniquecoin</source>
<translation>virtauniquecoin yapılandırma seçeneklerini değiştir</translation>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation>Mevcut sekmedeki veriyi bir dosyaya aktar</translation>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation>Cüzdanı şifrele veya cüzdanın şifresini aç</translation>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation>Cüzdanı başka bir konuma yedekle</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cüzdan şifrelemesi için kullanılan parolayı değiştir</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Hata ayıklama penceresi</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Hata ayıklama ve teşhis penceresini aç</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>Mesajı &doğrula...</translation>
</message>
<message>
<location line="-202"/>
<source>virtauniquecoin</source>
<translation>virtauniquecoin</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location line="+180"/>
<source>&About virtauniquecoin</source>
<translation>virtauniquecoin &Hakkında</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Göster / Gizle</translation>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation>Cüzdanın kilidini aç</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>Cüzdanı &Kilitle</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Cüzdanı kilitle</translation>
</message>
<message>
<location line="+35"/>
<source>&File</source>
<translation>&Dosya</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Ayarlar</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Yardım</translation>
</message>
<message>
<location line="+12"/>
<source>Tabs toolbar</source>
<translation>Sekme araç çubuğu</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation>Eylem araç çubuğu</translation>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>virtauniquecoin client</source>
<translation>virtauniquecoin istemcisi</translation>
</message>
<message numerus="yes">
<location line="+75"/>
<source>%n active connection(s) to virtauniquecoin network</source>
<translation><numerusform>virtauniquecoin ağına %n etkin bağlantı</numerusform><numerusform>virtauniquecoin ağına %n etkin bağlantı</numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation>İşlem geçmişinin %1 bloğu indirildi.</translation>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Pay alınıyor.<br>Sizin ağırlığınız %1<br>Ağın ağırlığı %2<br>Ödül almak için tahmini süre %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Pay alınmıyor çünkü cüzdan kilitlidir</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Pay alınmıyor çünkü cüzdan çevrimdışıdır</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Pay alınmıyor çünkü cüzdan senkronize ediliyor</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Pay alınmıyor çünkü olgunlaşmış coininiz yoktur</translation>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation><numerusform>%n saniye önce</numerusform><numerusform>%n saniye önce</numerusform></translation>
</message>
<message>
<location line="-312"/>
<source>About virtauniquecoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about virtauniquecoin card</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>&Unlock Wallet...</source>
<translation>Cüzdanı &Kilitle...</translation>
</message>
<message numerus="yes">
<location line="+297"/>
<source>%n minute(s) ago</source>
<translation><numerusform>%n dakika önce</numerusform><numerusform>%n dakika önce</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation><numerusform>%n saat önce</numerusform><numerusform>%n saat önce</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation><numerusform>%n gün önce</numerusform><numerusform>%n gün önce</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Güncel</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Aralık kapatılıyor...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</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>Bu işlem, büyüklük sınırının üzerindedir. İşleminizi gerçekleştirecek devrelere gidecek ve ağı desteklemeye yardımcı olacak %1 ücretle coin gönderebilirsiniz. Ücreti ödemek istiyor musunuz?</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation>İşlem ücretini onayla</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>İşlem gerçekleştirildi</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Gelen işlem</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Tarih: %1
Miktar: %2
Tür: %3
Adres: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>URI işleme</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid virtauniquecoin address or malformed URI parameters.</source>
<translation>URI ayrıştırılamadı! Bu, geçersiz bir virtauniquecoin adresi veya hatalı URI parametreleri nedeniyle olabilir.</translation>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilidi açıktır</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilitlidir</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation>Cüzdanı Yedekle</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Cüzdan Verisi (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Yedekleme Başarısız Oldu</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Cüzdan verisi, yeni bir konuma kaydedilmeye çalışılırken bir hata oluştu.</translation>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation><numerusform>%n saniye</numerusform><numerusform>%n saniye</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n dakika</numerusform><numerusform>%n dakika</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation><numerusform>%n saat</numerusform><numerusform>%n saat</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n gün</numerusform><numerusform>%n gün</numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation>Pay alınmıyor</translation>
</message>
<message>
<location filename="../virtauniquecoin.cpp" line="+109"/>
<source>A fatal error occurred. virtauniquecoin can no longer continue safely and will quit.</source>
<translation>Önemli bir hata oluştu. virtauniquecoin artık güvenli bir şekilde devam edemez ve şimdi kapatılacak.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation>Ağ Uyarısı</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Coin Kontrolü</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Adet:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bayt:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Öncelik:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Ücret:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Düşük Çıktı:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation>hayır</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Ücretten sonra:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Para üstü:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>tümünü seç(me)</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Ağaç kipi</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Liste kipi</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Onaylar</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Onaylandı</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Öncelik</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>İşlem Numarasını Kopyala</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Adedi kopyala</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Ücreti kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Ücretten sonrakini kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Baytları kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Önceliği kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Düşük çıktıyı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Para üstünü kopyala</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>en yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>orta-yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>orta</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>düşük-orta</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>düşük</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>en düşük</translation>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation>BOZUKLUK</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>evet</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>İşlem büyüklüğü 10000 bayttan büyükse, bu etiket kırmızıya dönüşür.
Bu, kb başına en az %1 ücret gerektiği anlamına gelir.
Girdi başına +/- 1 Byte değişkenlik gösterebilir.</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>Yüksek öncelikli işlemler, daha yüksek ihtimalle bir bloğa düşer.
Öncelik "orta" seviyeden düşükse, bu etiket kırmızıya döner.
Bu, kb başına en az %1 ücret gerektiği anlamına gelir.</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>Eğer herhangi bir alıcı, %1'den daha küçük bir miktar alırsa, bu etiket kırmızıya dönüşür.
Bu, en az %2 bir ücretin gerektiği anlamına gelir.
Minimum aktarım ücretinin 0.546 katından düşük miktarlar, BOZUKLUK olarak gösterilir.</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>Eğer para üstü %1'den küçükse, bu etiket kırmızıya dönüşür.
Bu, en az %2 bir ücretin gerektiği anlamına gelir.</translation>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>%1 unsurundan para üstü (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(para üstü)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Adresi düzenle</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Bu adres defteri kaydıyla ilişkili etiket</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adres</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>Bu adres defteri kaydıyla ilişkili etiket. Bu, sadece gönderi adresleri için değiştirilebilir.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Yeni alım adresi</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Yeni gönderi adresi</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Alım adresini düzenle</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Gönderi adresini düzenle</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Girilen "%1" adresi hâlihazırda adres defterinde mevcuttur.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid virtauniquecoin address.</source>
<translation>Girilen %1 adresi, geçerli bir virtauniquecoin adresi değildir.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Cüzdan kilidi açılamadı.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Yeni anahtar oluşturulması başarısız oldu.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>virtauniquecoin-Qt</source>
<translation>virtauniquecoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versiyon</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komut satırı seçenekleri</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>GA seçenekleri</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Dili ayarla, örneğin "de_DE" (varsayılan: sistem yerel ayarları)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Simge durumunda başlat</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Başlangıçta açılış ekranını göster (varsayılan: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Seçenekler</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Esas ayarlar</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>İşlemlerinizin hızlıca gerçekleştirilmesini sağlayan kB başına opsiyonel işlem ücreti. Birçok işlem 1 kB'tır. Tavsiye edilen ücret 0.01'dir.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Muamele ücreti &öde</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start virtauniquecoin after logging in to the system.</source>
<translation>Sisteme giriş yaptıktan sonra virtauniquecoin'i otomatik olarak başlat</translation>
</message>
<message>
<location line="+3"/>
<source>&Start virtauniquecoin on system login</source>
<translation>Sisteme girişte virtauniquecoin'i &başlat</translation>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation>Kapanışta blok ve adres veritabanlarını birbirinden ayır. Bu, onların başka bir veri klasörüne taşınabileceği anlamına gelir ancak bu işlem kapanışı yavaşlatır. Cüzdan ise her zaman ayrılmıştır.</translation>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation>Kapanışta veritabanlarını &ayır</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Şebeke</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the virtauniquecoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Yönelticide virtauniquecoin istemci portunu otomatik olarak aç. Bu, sadece yönelticiniz UPnP'i desteklediğinde ve etkin olduğunda çalışır.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portları &UPnP kullanarak haritala</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the virtauniquecoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>virtauniquecoin ağına bir SOCKS vekil sunucusu yoluyla bağlan (örn. Tor yoluyla bağlanıldığında)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>SOCKS vekil sunucusu yoluyla &bağlan:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Vekil &İP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Vekil sunucunun IP adresi (örn. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Vekil sunucunun portu (mesela 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &sürümü:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Vekil sunucunun SOCKS sürümü (mesela 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Pencere</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Küçültüldükten sonra sadece çekmece ikonu göster.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>İşlem çubuğu yerine sistem çekmecesine &küçült</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Pencere kapatıldığında uygulamadan çıkmak yerine uygulamayı küçültür. Bu seçenek etkinleştirildiğinde, uygulama sadece menüden çıkış seçildiğinde kapanacaktır.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Kapatma sırasında k&üçült</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Görünüm</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Kullanıcı arayüzü &lisanı:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting virtauniquecoin.</source>
<translation>Kullanıcı arabirimi dili buradan ayarlanabilir. Ayar, virtauniquecoin yeniden başlatıldığında etkin olacaktır.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Meblağları göstermek için &birim:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>virtauniquecoin gönderildiğinde arayüzde gösterilecek varsayılan alt birimi seçiniz.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show virtauniquecoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Muamele listesinde adresleri &göster</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation>Para kontrol özelliklerinin gösterilip gösterilmeyeceğini ayarlar.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Tamam</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&İptal</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation>varsayılan</translation>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting virtauniquecoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Girilen vekil sunucu adresi geçersizdir.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the virtauniquecoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Güncel harcanabilir bakiyeniz</translation>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation>Olgunlaşmamış:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Oluşturulan bakiye henüz olgunlaşmamıştır</translation>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation>Toplam:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Güncel toplam bakiyeniz</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Son muameleler</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>eşleşme dışı</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>İstemci ismi</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>Mevcut değil</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>İstemci sürümü</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Malumat</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Kullanılan OpenSSL sürümü</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Başlama zamanı</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Şebeke</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Bağlantı sayısı</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blok zinciri</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Güncel blok sayısı</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Tahmini toplam blok sayısı</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Son blok zamanı</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Aç</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the virtauniquecoin-Qt help message to get a list with possible virtauniquecoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Derleme tarihi</translation>
</message>
<message>
<location line="-104"/>
<source>virtauniquecoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>virtauniquecoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Hata ayıklama kütük dosyası</translation>
</message>
<message>
<location line="+7"/>
<source>Open the virtauniquecoin 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="+102"/>
<source>Clear console</source>
<translation>Konsolu temizle</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the virtauniquecoin 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>Tarihçede gezinmek için imleç tuşlarını kullanınız, <b>Ctrl-L</b> ile de ekranı temizleyebilirsiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Mevcut komutların listesi için <b>help</b> yazınız.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>virtauniquecoin yolla</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Para kontrolü özellikleri</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Girdiler...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>otomatik seçilmiş</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Yetersiz fon!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bayt:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Meblağ:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 VUC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation>Öncelik:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Ücret:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Düşük çıktı:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Ücretten sonra:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Birçok alıcıya aynı anda gönder</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Alıcı ekle</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 VUC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Yollama etkinliğini teyit ediniz</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>G&önder</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a virtauniquecoin address (e.g. virtauniquecoinNpBmRUEiP2Po1K8km2GXcFfwYh)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Meblağı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Ücreti kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Ücretten sonrakini kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Baytları kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Önceliği kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Düşük çıktıyı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Para üstünü kopyala</translation>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Gönderiyi teyit ediniz</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Alıcı adresi geçerli değildir, lütfen denetleyiniz.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Ödeyeceğiniz tutarın sıfırdan yüksek olması gerekir.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Tutar bakiyenizden yüksektir.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Toplam, %1 muamele ücreti ilâve edildiğinde bakiyenizi geçmektedir.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Çift adres bulundu, belli bir gönderi sırasında her adrese sadece tek bir gönderide bulunulabilir.</translation>
</message>
<message>
<location line="+5"/>
<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="+251"/>
<source>WARNING: Invalid virtauniquecoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Mebla&ğ:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Şu adrese öde:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Adres defterinize eklemek için bu adrese ilişik bir etiket giriniz</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. virtauniquecoinNpBmRUEiP2Po1K8km2GXcFfwYh)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a virtauniquecoin address (e.g. virtauniquecoinNpBmRUEiP2Po1K8km2GXcFfwYh)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>İmzalar - Mesaj İmzala / Kontrol et</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>Mesaj &imzala</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Bir adresin sizin olduğunu ispatlamak için adresinizle mesaj imzalayabilirsiniz. Oltalama saldırılarının kimliğinizi imzanızla elde etmeyi deneyebilecekleri için belirsiz hiçbir şey imzalamamaya dikkat ediniz. Sadece ayrıntılı açıklaması olan ve tümüne katıldığınız ifadeleri imzalayınız.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. virtauniquecoinNpBmRUEiP2Po1K8km2GXcFfwYh)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>İmzalamak istediğiniz mesajı burada giriniz</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Güncel imzayı sistem panosuna kopyala</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this virtauniquecoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Tüm mesaj alanlarını sıfırla</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>Mesaj &kontrol et</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>İmza için kullanılan adresi, mesajı (satır sonları, boşluklar, sekmeler vs. karakterleri tam olarak kopyaladığınızdan emin olunuz) ve imzayı aşağıda giriniz. Bir ortadaki adam saldırısı tarafından kandırılmaya mâni olmak için imzadan, imzalı mesajın içeriğini aşan bir anlam çıkarmamaya dikkat ediniz.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. virtauniquecoinNpBmRUEiP2Po1K8km2GXcFfwYh)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified virtauniquecoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Tüm mesaj kontrolü alanlarını sıfırla</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a virtauniquecoin address (e.g. virtauniquecoinNpBmRUEiP2Po1K8km2GXcFfwYh)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>İmzayı oluşturmak için "Mesaj İmzala" unsurunu tıklayın</translation>
</message>
<message>
<location line="+3"/>
<source>Enter virtauniquecoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Girilen adres geçersizdir.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Adresi kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Girilen adres herhangi bir anahtara işaret etmemektedir.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Cüzdan kilidinin açılması iptal edildi.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Girilen adres için özel anahtar mevcut değildir.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Mesajın imzalanması başarısız oldu.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mesaj imzalandı.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>İmzanın kodu çözülemedi.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>İmzayı kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>İmza mesajın hash değeri ile eşleşmedi.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Mesaj doğrulaması başarısız oldu.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mesaj doğrulandı.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation>çakışma</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/çevrim dışı</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/doğrulanmadı</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 teyit</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Durum</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kaynak</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Oluşturuldu</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Gönderen</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Alıcı</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>kendi adresiniz</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiket</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Gider</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>kabul edilmedi</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Gelir</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Muamele ücreti</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Net meblağ</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mesaj</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Yorum</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Muamele tanımlayıcı</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 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>Hata ayıklama verileri</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Muamele</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Girdiler</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>doğru</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>yanlış</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, henüz başarılı bir şekilde yayınlanmadı</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>bilinmiyor</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Muamele detayları</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Bu pano muamelenin ayrıntılı açıklamasını gösterir</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Doğrulandı (%1 teyit)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Çevrim dışı</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Teyit edilmemiş</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Teyit ediliyor (tavsiye edilen %2 teyit üzerinden %1 doğrulama)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Çakışma</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Olgunlaşmamış (%1 teyit, %2 teyit ardından kullanılabilir olacaktır)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Bu blok başka hiçbir düğüm tarafından alınmamıştır ve muhtemelen kabul edilmeyecektir!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Oluşturuldu ama kabul edilmedi</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Şununla alındı</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Alındığı kişi</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Kendinize ödeme</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Madenden çıkarılan</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(mevcut değil)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Muamele durumu. Doğrulama sayısını görüntülemek için imleci bu alanda tutunuz.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Muamelenin alındığı tarih ve zaman.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Muamele türü.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Muamelenin alıcı adresi.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bakiyeden alınan ya da bakiyeye eklenen meblağ.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Hepsi</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Bugün</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Bu hafta</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Bu ay</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Geçen ay</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Bu sene</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Aralık...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Şununla alınan</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Kendinize</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Oluşturulan</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Diğer</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Aranacak adres ya da etiket giriniz</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Asgari meblağ</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Meblağı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Muamele kimliğini kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Etiketi düzenle</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Muamele detaylarını göster</translation>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Doğrulandı</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>Tanımlayıcı</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Aralık:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>ilâ</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>virtauniquecoin-core</name>
<message>
<location filename="../virtauniquecoinstrings.cpp" line="+33"/>
<source>virtauniquecoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or virtauniquecoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Komutları listele</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Bir komut için yardım al</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Seçenekler:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: virtauniquecoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: virtauniquecoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Cüzdan dosyası belirtiniz (veri klasörünün içinde)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Veri dizinini belirt</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Veritabanı önbellek boyutunu megabayt olarak belirt (varsayılan: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 15714 or testnet: 25714)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Eşler ile en çok <n> adet bağlantı kur (varsayılan: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Eş adresleri elde etmek için bir düğüme bağlan ve ardından bağlantıyı kes</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Kendi genel adresinizi tanımlayın</translation>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Aksaklık gösteren eşlerle bağlantıyı kesme sınırı (varsayılan: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aksaklık gösteren eşlerle yeni bağlantıları engelleme süresi, saniye olarak (varsayılan: 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>IPv4 üzerinde dinlemek için %u numaralı RPC portunun kurulumu sırasında hata meydana geldi: %s</translation>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 15715 or testnet: 25715)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Konut satırı ve JSON-RPC komutlarını kabul et</translation>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Arka planda daemon (servis) olarak çalış ve komutları kabul et</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Deneme şebekesini kullan</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Dışarıdan gelen bağlantıları kabul et (varsayılan: -proxy veya -connect yoksa 1)</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>IPv6 üzerinde dinlemek için %u numaralı RPC portu kurulurken bir hata meydana geldi, IPv4'e dönülüyor: %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 type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</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>Uyarı: -paytxfee çok yüksek bir değere ayarlanmış! Bu, muamele gönderirseniz ödeyeceğiniz muamele ücretidir.</translation>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong virtauniquecoin will not work properly.</source>
<translation type="unfinished"/>
</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>Uyarı: wallet.dat dosyasının okunması sırasında bir hata meydana geldi! Tüm anahtarlar doğru bir şekilde okundu, ancak muamele verileri ya da adres defteri unsurları hatalı veya eksik olabilir.</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>Uyarı: wallet.dat bozuk, veriler geri kazanıldı! Özgün wallet.dat, wallet.{zamandamgası}.bak olarak %s klasörüne kaydedildi; bakiyeniz ya da muameleleriniz yanlışsa bir yedeklemeden tekrar yüklemeniz gerekir.</translation>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Bozuk bir wallet.dat dosyasından özel anahtarları geri kazanmayı dene</translation>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation>Blok oluşturma seçenekleri:</translation>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation>Sadece belirtilen düğüme veya düğümlere bağlan</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Kendi IP adresini keşfet (varsayılan: dinlenildiğinde ve -externalip yoksa 1)</translation>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Herhangi bir portun dinlenmesi başarısız oldu. Bunu istiyorsanız -listen=0 seçeneğini kullanınız.</translation>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Bağlantı başına azami alım tamponu, <n>*1000 bayt (varsayılan: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Bağlantı başına azami yollama tamponu, <n>*1000 bayt (varsayılan: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Sadece <net> şebekesindeki düğümlere bağlan (IPv4, IPv6 ya da Tor)</translation>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the virtauniquecoin Wiki for SSL setup instructions)</source>
<translation> SSL seçenekleri: (SSL kurulum bilgisi için virtauniquecoin vikisine bakınız)</translation>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Trace/hata ayıklama verilerini debug.log dosyası yerine konsola gönder</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Bayt olarak asgari blok boyutunu tanımla (varsayılan: 0)</translation>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>İstemci başlatıldığında debug.log dosyasını küçült (varsayılan: -debug bulunmadığında 1)</translation>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Bağlantı zaman aşım süresini milisaniye olarak belirt (varsayılan: 5000)</translation>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: dinlenildiğinde 1)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için kullanıcı ismi</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Uyarı: Bu sürüm çok eskidir, güncellemeniz gerekir!</translation>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat bozuk, geri kazanım başarısız oldu</translation>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için parola</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=virtauniquecoinrpc
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 "virtauniquecoin Alert" admin@foo.com
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Belirtilen İP adresinden JSON-RPC bağlantılarını kabul et</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Şu <ip> adresinde (varsayılan: 127.0.0.1) çalışan düğüme komut yolla</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>En iyi blok değiştiğinde komutu çalıştır (komut için %s parametresi blok hash değeri ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Bir cüzdan muamelesi değiştiğinde komutu çalıştır (komuttaki %s TxID ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Cüzdanı en yeni biçime güncelle</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Anahtar alan boyutunu <n> değerine ayarla (varsayılan: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blok zincirini eksik cüzdan muameleleri için tekrar tara</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için OpenSSL (https) kullan</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Sunucu sertifika dosyası (varsayılan: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Sunucu özel anahtarı (varsayılan: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Bu yardım mesajı</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. virtauniquecoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>virtauniquecoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. (bind şu hatayı iletti: %d, %s)</translation>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>-addnode, -seednode ve -connect için DNS aramalarına izin ver</translation>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Adresler yükleniyor...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: bozuk cüzdan</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of virtauniquecoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart virtauniquecoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Geçersiz -proxy adresi: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet için bilinmeyen bir şebeke belirtildi: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Bilinmeyen bir -socks vekil sürümü talep edildi: %i</translation>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>-bind adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>-externalip adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>-paytxfee=<meblağ> için geçersiz meblağ: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Geçersiz meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Yetersiz bakiye</translation>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Blok indeksi yükleniyor...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Bağlanılacak düğüm ekle ve bağlantıyı zinde tutmaya çalış</translation>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. virtauniquecoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Cüzdan yükleniyor...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Cüzdan eski biçime geri alınamaz</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Varsayılan adres yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Yeniden tarama...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Yükleme tamamlandı</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation>%s seçeneğini kullanmak için</translation>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Hata</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>rpcpassword=<parola> şu yapılandırma dosyasında belirtilmelidir:
%s
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.</translation>
</message>
</context>
</TS> | virtauniquecoin/virtauniquecoin-master | src/qt/locale/virtauniquecoin_tr.ts | TypeScript | mit | 124,772 |
#!/usr/bin/env python
'''
Retrospectively updates older FFV1/DV packages in order to meet our current
packaging requirements. This should allow accession.py and makepbcore.py to run as
expected. This script should work on files created by:
makeffv1.py
dvsip.py
loopline.py
'''
import argparse
import sys
import shutil
import os
import time
import ififuncs
def parse_args(args_):
'''
Parse command line arguments.
'''
parser = argparse.ArgumentParser(
description='Retrospectively updates older FFV1/DV packages in order to'
'meet our current packaging requirements. This should allow'
' accession.py and makepbcore.py to run as expected.'
' Written by Kieran O\'Leary.'
)
parser.add_argument(
'input', help='Input directory'
)
parser.add_argument(
'-start_number',
help='Enter the Object Entry number for the first package. The script will increment by one for each subsequent package.'
)
parser.add_argument(
'-technical',
help='Path to technical/PBCore CSV.'
)
parser.add_argument(
'-filmographic',
help='Path to Filmographic CSV. Must contain reference numbers.'
)
parsed_args = parser.parse_args(args_)
return parsed_args
def get_numbers(args):
'''
Figure out the first OE number and how to increment per package.
'''
if args.start_number:
if args.start_number[:2] != 'oe':
print 'First two characters must be \'oe\' and last four characters must be four digits'
object_entry = ififuncs.get_object_entry()
elif len(args.start_number[2:]) not in range(4, 6):
print 'First two characters must be \'oe\' and last four characters must be four digits'
object_entry = ififuncs.get_object_entry()
elif not args.start_number[2:].isdigit():
object_entry = ififuncs.get_object_entry()
print 'First two characters must be \'oe\' and last four characters must be four digits'
else:
object_entry = args.start_number
else:
object_entry = ififuncs.get_object_entry()
object_entry_digits = int(object_entry[2:])
new_object_entry = 'oe' + str(object_entry_digits)
return new_object_entry
def update_manifest(manifest, old_oe, uuid):
'''
Updates the existing checksum manifest by replacing OE numbers with
UUIDs where appropriate. Anything logfiles or metadata relating to the
original v210.mov will be left alone.
'''
updated_lines = []
with open(manifest, 'r') as file_object:
checksums = file_object.readlines()
for line in checksums:
if old_oe in line:
if 'source' in line:
# if source (v210) logs or metadata exist, leave filename
# alone, just change the path.
line = line[:40].replace(old_oe, uuid) + line[40:]
elif '.mov_log.log' in line:
line = line.replace(old_oe, uuid).replace('.mov_log', '_sip_log')
else:
line = line.replace(old_oe, uuid)
updated_lines.append(line)
return updated_lines
def rename_files(new_uuid_path, old_oe, uuid, manifest, logname):
'''
Renames files from OE numbers to UUID where appropriate.
'''
for root, _, filenames in os.walk(new_uuid_path):
for filename in filenames:
if old_oe in filename:
if 'source' not in filename:
if '.mov_log.log' in filename:
new_filename = os.path.join(root, filename).replace('.mov_log', '_sip_log').replace(old_oe, uuid)
os.rename(os.path.join(root, filename), new_filename)
logname = new_filename
ififuncs.generate_log(
logname,
'EVENT = eventType=Filename change,'
' eventOutcomeDetailNote=%s changed to %s'
% (os.path.join(root, filename), new_filename)
)
else:
new_filename = os.path.join(root, filename).replace(old_oe, uuid)
os.rename(os.path.join(root, filename), new_filename)
ififuncs.generate_log(
logname,
'EVENT = eventType=Filename change,'
' eventOutcomeDetailNote=%s changed to %s'
% (os.path.join(root, filename), new_filename)
)
return logname
def move_files(root, new_object_entry, old_oe_path, old_uuid_path, uuid):
'''
Moves files into their new folder paths.
'''
new_oe_path = os.path.join(
os.path.dirname(root),
new_object_entry
)
os.makedirs(new_oe_path)
os.rename(old_oe_path, old_uuid_path)
new_uuid_path = os.path.join(new_oe_path, uuid)
shutil.move(old_uuid_path, new_oe_path)
return new_oe_path, new_uuid_path
def make_register():
'''
This sends a placeholder accessions register to the desktop logs directory.
This should get rid of some of the more painful, repetitive identifier matching.
'''
desktop_logs_dir = ififuncs.make_desktop_logs_dir()
register = os.path.join(
desktop_logs_dir,
'oe_register_' + time.strftime("%Y-%m-%dT%H_%M_%S.csv")
)
ififuncs.create_csv(register, (
'OE No.',
'Date Received',
'Quantity',
'Format',
'Description',
'Contact Name',
'Type of Acquisition',
'Accession Number',
'Additional Information',
'Habitat',
'Vinegar No.'
))
return register
def get_date_modified(directory):
'''
Returns the date modified of a file in DD/MM/YYYY, which is
the format used for the Object Entry register. yes, we should be using
ISO8601 but we'll fix this later.
'''
file_list = ififuncs.recursive_file_list(directory)
# This will blindly use the first video file it encounters.
# This is fine for this project as all the objects folders contain single files.
extension = os.path.splitext(file_list[0])[1]
return time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file_list[0]))), extension
def main(args_):
'''
Retrospectively updates older FFV1/DV packages in order to meet our current
packaging requirements. This should allow accession.py and makepbcore.py to run as
expected. This script should work on files created by:
makeffv1.py
dvsip.py
loopline.py
'''
args = parse_args(args_)
user = ififuncs.get_user()
new_object_entry = get_numbers(args)
filmographic_csv = args.filmographic
technical_csv = args.technical
filmographic_oe_list = []
filmo_csv_extraction = ififuncs.extract_metadata(filmographic_csv)
tech_csv_extraction = ififuncs.extract_metadata(technical_csv)
register = make_register()
for line_item in filmo_csv_extraction[0]:
dictionary = {}
oe_number = line_item['Object Entry'].lower()
dictionary['title'] = line_item['Title']
if dictionary['title'] == '':
dictionary['title'] = '%s - %s' % (line_item['TitleSeries'], line_item['EpisodeNo'])
dictionary['uppercase_dashed_oe'] = oe_number.upper()
for tech_record in tech_csv_extraction[0]:
if tech_record['Reference Number'] == dictionary['uppercase_dashed_oe']:
dictionary['source_accession_number'] = tech_record['Accession Number']
dictionary['filmographic_reference_number'] = tech_record['new_ref']
# this transforms OE-#### to oe####
dictionary['old_oe'] = oe_number[:2] + oe_number[3:]
filmographic_oe_list.append(dictionary)
for oe_package in filmographic_oe_list:
for root, _, filenames in os.walk(args.input):
if os.path.basename(root) == oe_package['old_oe']:
old_oe_path = root
old_oe = os.path.basename(root)
log_dir = os.path.join(root, 'logs')
for files in os.listdir(log_dir):
if '.mov_log.log' in files:
log = os.path.join(log_dir, files)
manifest = os.path.join(
os.path.dirname(root),
old_oe + '_manifest.md5'
)
uuid = ififuncs.create_uuid()
uuid_event = (
'EVENT = eventType=Identifier assignement,'
' eventIdentifierType=UUID, value=%s, module=uuid.uuid4'
) % uuid
ififuncs.generate_log(
log,
'EVENT = loopline_repackage.py started'
)
ififuncs.generate_log(
log,
'eventDetail=loopline_repackage.py %s' % ififuncs.get_script_version('loopline_repackage.py')
)
ififuncs.generate_log(
log,
'Command line arguments: %s' % args
)
ififuncs.generate_log(
log,
'EVENT = agentName=%s' % user
)
ififuncs.generate_log(
log,
uuid_event
)
ififuncs.generate_log(
log,
'EVENT = eventType=Identifier assignement,'
' eventIdentifierType=object entry, value=%s'
% new_object_entry
)
ififuncs.generate_log(
log,
'EVENT = eventType=Identifier assignement,'
' eventIdentifierType=Filmographic reference number , value=%s'
% oe_package['filmographic_reference_number']
)
oe_package['new_object_entry'] = new_object_entry
print('Transforming %s into %s' % (oe_package['old_oe'], oe_package['new_object_entry']))
ififuncs.generate_log(
log,
'Relationship, derivation, has source=%s' % oe_package['source_accession_number']
)
old_uuid_path = os.path.join(os.path.dirname(root), uuid)
new_oe_path, new_uuid_path = move_files(
root, new_object_entry, old_oe_path, old_uuid_path, uuid
)
updated_lines = update_manifest(manifest, old_oe, uuid)
new_manifest = os.path.join(new_oe_path, uuid) + '_manifest.md5'
shutil.move(manifest, new_manifest)
with open(new_manifest, 'w') as fo:
for lines in updated_lines:
fo.write(lines)
new_logs_path = os.path.join(new_uuid_path, 'logs')
for files in os.listdir(new_logs_path):
if '.mov_log.log' in files:
log = os.path.join(new_logs_path, files)
logname = rename_files(new_uuid_path, old_oe, uuid, new_manifest, log)
date_modified, extension = get_date_modified(new_uuid_path)
# This normally would be bad practise, but this project only has two formats. MOV/DV and FFv1/MKV
if extension == '.mkv':
av_format = 'FFV1/PCM/Matroska'
elif extension == '.mov':
av_format = 'DV/PCM/QuickTime'
provenance_string = 'Reproduction of %s' % oe_package['source_accession_number']
ififuncs.append_csv(register, (oe_package['new_object_entry'].upper()[:2] + '-' + oe_package['new_object_entry'][2:],date_modified, '1',av_format,oe_package['title'],'contact_name','Reproduction','', provenance_string, '', ''))
ififuncs.generate_log(
logname,
'EVENT = loopline_repackage.py finished'
)
ififuncs.checksum_replace(new_manifest, logname, 'md5')
oe_digits = int(os.path.basename(new_oe_path)[2:]) + 1
new_object_entry = 'oe' + str(oe_digits)
if __name__ == '__main__':
main(sys.argv[1:])
| kieranjol/IFIscripts | loopline_repackage.py | Python | mit | 12,437 |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-04-05 14:04
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('story', '0037_auto_20170405_1401'),
]
operations = [
migrations.AlterField(
model_name='story',
name='language',
field=models.CharField(choices=[('English', 'English')], max_length=10, verbose_name='Language'),
),
]
| OrhanOdabasi/weirdbutreal | story/migrations/0038_auto_20170405_1404.py | Python | mit | 509 |
package datastructs
// Deque array implemented linked list
type Deque struct {
array []interface{}
left, right int
fixSize int
}
func NewDeque(capacity int) *Deque {
d := new(Deque)
if capacity <= 0 {
panic("deque must have capacity")
}
d.array = make([]interface{}, capacity)
d.fixSize = capacity
return d
}
func (q *Deque) EnqueueLeft(x interface{}) {
if q.left == q.right && q.left != 0 {
panic("overflow")
}
q.array[q.left] = x
q.left = q.left - 1
if q.left == -1 {
q.left = q.fixSize - 1
}
}
func (q *Deque) EnqueueRight(x interface{}) {
if q.right == q.fixSize {
panic("overflow")
}
q.array[q.right] = x
q.right = q.right + 1
}
func (q *Deque) DequeueLeft() interface{} {
if q.left == q.fixSize {
panic("overflow")
}
q.left = q.left + 1
if q.left == q.fixSize {
q.left = 0
}
x := q.array[q.left]
return x
}
func (q *Deque) DequeueRight() interface{} {
if q.right == q.left {
panic("underflow")
}
q.right = q.right - 1
if q.right == -1 {
q.right = q.fixSize - 1
}
x := q.array[q.right]
return x
}
| stoneflyop1/intro2algorithms | datastructs/deque.go | GO | mit | 1,068 |
// Currently unused, but don't want to delete it since
// it might be useful later.
//SmartRoutes.ComboBoxViewModel = function(data) {
// // Private:
// var comboboxChoices = ko.observableArray();
// var comboboxSelection = ko.observable();
// (function Init() {
// if (data && Array.isArray(data)) {
// $.each(data, function(key, value) {
// comboboxChoices.push(value);
// });
// }
// })();
// return {
// // Public:
// selectedItem: comboboxSelection,
// choices: comboboxChoices
// };
//}; | SmartRoutes/SmartRoutes | SmartRoutes/Scripts/ViewModels/ComboBoxViewModel.js | JavaScript | mit | 595 |
const TEXT_NODE = 3;
import { clearSelection } from 'content-kit-editor/utils/selection-utils';
import { walkDOMUntil } from 'content-kit-editor/utils/dom-utils';
import KEY_CODES from 'content-kit-editor/utils/keycodes';
import isPhantom from './is-phantom';
function selectRange(startNode, startOffset, endNode, endOffset) {
clearSelection();
const range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
const selection = window.getSelection();
selection.addRange(range);
}
function selectText(startText,
startContainingElement,
endText=startText,
endContainingElement=startContainingElement) {
const findTextNode = (text) => {
return (el) => el.nodeType === TEXT_NODE && el.textContent.indexOf(text) !== -1;
};
const startTextNode = walkDOMUntil(startContainingElement, findTextNode(startText));
const endTextNode = walkDOMUntil(endContainingElement, findTextNode(endText));
if (!startTextNode) {
throw new Error(`Could not find a starting textNode containing "${startText}"`);
}
if (!endTextNode) {
throw new Error(`Could not find an ending textNode containing "${endText}"`);
}
const startOffset = startTextNode.textContent.indexOf(startText),
endOffset = endTextNode.textContent.indexOf(endText) + endText.length;
selectRange(startTextNode, startOffset, endTextNode, endOffset);
}
function moveCursorTo(node, offset=0, endNode=node, endOffset=offset) {
selectRange(node, offset, endNode, endOffset);
}
function triggerEvent(node, eventType) {
if (!node) { throw new Error(`Attempted to trigger event "${eventType}" on undefined node`); }
let clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent(eventType, true, true);
return node.dispatchEvent(clickEvent);
}
function createKeyEvent(eventType, keyCode) {
let oEvent = document.createEvent('KeyboardEvent');
if (oEvent.initKeyboardEvent) {
oEvent.initKeyboardEvent(eventType, true, true, window, 0, 0, 0, 0, 0, keyCode);
} else if (oEvent.initKeyEvent) {
oEvent.initKeyEvent(eventType, true, true, window, 0, 0, 0, 0, 0, keyCode);
}
// Hack for Chrome to force keyCode/which value
try {
Object.defineProperty(oEvent, 'keyCode', {get: function() { return keyCode; }});
Object.defineProperty(oEvent, 'which', {get: function() { return keyCode; }});
} catch(e) {
// FIXME
// PhantomJS/webkit will throw an error "ERROR: Attempting to change access mechanism for an unconfigurable property"
// see https://bugs.webkit.org/show_bug.cgi?id=36423
}
if (oEvent.keyCode !== keyCode || oEvent.which !== keyCode) {
throw new Error(`Failed to create key event with keyCode ${keyCode}. \`keyCode\`: ${oEvent.keyCode}, \`which\`: ${oEvent.which}`);
}
return oEvent;
}
function triggerKeyEvent(node, eventType, keyCode=KEY_CODES.ENTER) {
let oEvent = createKeyEvent(eventType, keyCode);
return node.dispatchEvent(oEvent);
}
function _buildDOM(tagName, attributes={}, children=[]) {
const el = document.createElement(tagName);
Object.keys(attributes).forEach(k => el.setAttribute(k, attributes[k]));
children.forEach(child => el.appendChild(child));
return el;
}
_buildDOM.text = (string) => {
return document.createTextNode(string);
};
/**
* Usage:
* makeDOM(t =>
* t('div', attributes={}, children=[
* t('b', {}, [
* t.text('I am a bold text node')
* ])
* ])
* );
*/
function makeDOM(tree) {
return tree(_buildDOM);
}
function getSelectedText() {
const selection = window.getSelection();
if (selection.rangeCount === 0) {
return null;
} else if (selection.rangeCount > 1) {
// FIXME?
throw new Error('Unable to get selected text for multiple ranges');
} else {
const {
anchorNode, anchorOffset,
focusNode, focusOffset
} = selection;
if (anchorNode !== focusNode) {
// FIXME
throw new Error('Unable to get selected text when multiple nodes are selected');
} else {
return anchorNode.textContent.slice(anchorOffset, focusOffset);
}
}
}
// returns the node and the offset that the cursor is on
function getCursorPosition() {
const selection = window.getSelection();
return {
node: selection.anchorNode,
offset: selection.anchorOffset
};
}
function triggerDelete(editor) {
if (isPhantom()) {
// simulate deletion for phantomjs
let event = { preventDefault() {} };
editor.handleDeletion(event);
} else {
triggerKeyEvent(document, 'keydown', KEY_CODES.DELETE);
}
}
function triggerEnter(editor) {
if (isPhantom()) {
// simulate event when testing with phantom
let event = { preventDefault() {} };
editor.handleNewline(event);
} else {
triggerKeyEvent(document, 'keydown', KEY_CODES.ENTER);
}
}
function insertText(string) {
document.execCommand('insertText', false, string);
}
const DOMHelper = {
moveCursorTo,
selectText,
clearSelection,
triggerEvent,
triggerKeyEvent,
makeDOM,
KEY_CODES,
getCursorPosition,
getSelectedText,
triggerDelete,
triggerEnter,
insertText
};
export { triggerEvent };
export default DOMHelper;
| toddself/content-kit-editor | tests/helpers/dom.js | JavaScript | mit | 5,235 |
class Fhir::CodeSystem
attr_reader :symbolic, :display, :oid, :uris
DECLARED_SYSTEMS = [{
symbolic: :unii,
display: 'UNII',
oid: '2.16.840.1.113883.4.9'
}, {
symbolic: :snomed,
display: 'SNOMED',
oid: '2.16.840.1.113883.6.96',
uri: 'http://snomed.info/id'
}, {
symbolic: :loinc,
display: 'LOINC',
oid: '2.16.840.1.113883.6.1',
uri: 'http://loinc.org'
}, {
symbolic: :rxnorm,
display: 'RxNorm',
oid: '2.16.840.1.113883.6.88'
}, {
symbolic: :ucum,
display: 'The Unified Code for Units of Measure',
oid: '2.16.840.1.113883.6.8',
uri: 'http://unitsofmeasure.org'
}, {
symbolic: :ndc,
display: 'NDC',
oid: '2.16.840.1.113883.6.69'
}, {
symbolic: :ndfrt,
display: 'NDFRT',
oid: '2.16.840.1.113883.3.26.1.5'
}, {
symbolic: :fdb_hic,
display: 'HIC_SEQN',
oid: '2.16.840.1.113883.3.84'
}, {
symbolic: :fdb_med_name,
display: 'MED_NAME_ID',
oid: '2.16.840.1.113883.3.567.12.2'
}, {
symbolic: :fdb_allergen_group,
display: 'DAM_ALRGN_GRP',
oid: '2.16.840.1.113883.4.296'
}, {
symbolic: :fhir_administrative_gender,
display: 'Gender',
uri: 'http://hl7.org/fhir/v3/AdministrativeGender'
}, {
symbolic: :iso639_2,
display: 'ISO639-2 Language Names',
uri: 'http://www.loc.gov/standards/iso639-2'
}, {
symbolic: :race,
display: 'CDC Race code',
oid: '2.16.840.1.113883.6.238'
}, {
symbolic: :null_flavor,
display: 'HL7 v3 NULL Flavor',
oid: '2.16.840.1.113883.5.1008',
uri: 'http://hl7.org/fhir/v3/NullFlavor'
},
{
symbolic: :fhir_condition_category,
display: 'Fhir Condition Category',
uri: 'http://hl7.org/fhir/vs/condition-category'
},
{
symbolic: :cpt,
display: 'Current Procedural Terminology',
uri: 'http://ama-assn.org/go/cpt'
},
# for tests
{
symbolic: :rgb,
display: 'RGB',
oid: 'RGB'
}, {
symbolic: :rgba,
display: 'RGBA',
oid: 'RGBA'
}]
def initialize(attributes)
@symbolic = attributes.fetch(:symbolic)
@display = attributes.fetch(:display)
@oid = attributes[:oid]
@uris = [attributes[:uri]]
@uris << "urn:oid:#{@oid}" if @oid.present?
@uris = @uris.flatten.uniq.compact
end
def uri
uris.first
end
def self.all
@code_systems ||= DECLARED_SYSTEMS.map do |cs|
self.new(cs)
end
end
def self.find_by_uri(uri)
all.find {|cs| cs.uri == uri}
end
def self.[](symbolic)
all.find { |cs| cs.symbolic == symbolic }
end
def self.find(oid_or_symbolic_or_uri)
key = oid_or_symbolic_or_uri
all.find { |cs| cs.symbolic == key ||
cs.oid == key ||
cs.uris.include?(key) }
end
end
| niquola/fhir | lib/fhir/handmade/code_system.rb | Ruby | mit | 2,903 |
/*
* Copyright (c) 2015, enlo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package info.naiv.lab.java.jmt.infrastructure;
import org.junit.After;
import org.junit.Before;
/**
*
* @author enlo
*/
public class SimpleServiceContainerTest extends AbstractServiceContainerTest {
/**
*
*/
public SimpleServiceContainerTest() {
}
/**
*
*/
@Before
@Override
public void setUp() {
}
/**
*
*/
@After
@Override
public void tearDown() {
}
/**
*
* @return
*/
@Override
protected SimpleServiceContainer createContainer() {
return new SimpleServiceContainer();
}
}
| enlo/jmt-projects | jmt-core/src/test/java/info/naiv/lab/java/jmt/infrastructure/SimpleServiceContainerTest.java | Java | mit | 1,965 |
using System.Collections;
using ForumSystem.Data.Common.Repository;
using ForumSystem.Data.Models;
using ForumSystem.Web.Areas.Administration.ViewModels.Posts;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
using System;
using System.Linq;
using System.Web.Mvc;
using AutoMapper.QueryableExtensions;
namespace ForumSystem.Web.Areas.Administration.Controllers
{
public class PostsController : KendoGridAdministrationController
{
public PostsController(IDeletableEntityRepository<Post> posts) : base(posts)
{
}
protected override IEnumerable GetData()
{
return this.posts
.All()
.Project()
.To<PostAdminViewModel>();
}
protected override T GetById<T>(object id)
{
return this.posts.GetById(id) as T;
}
public ActionResult Index()
{
return View();
}
public ActionResult Posts_Read([DataSourceRequest] DataSourceRequest request)
{
var posts = this.GetData();
return Json(posts.ToDataSourceResult(request));
}
}
} | Dr4g0/TelerikForumSystem | Source/Web/ForumSystem.Web/Areas/Administration/Controllers/PostsController.cs | C# | mit | 1,157 |
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel
//
// 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.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using SharpDX.Serialization;
namespace SharpDX
{
/// <summary>
/// Defines a four component vector, using half precision floating point coordinates.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
#if !W8CORE
[Serializable]
[TypeConverter(typeof(SharpDX.Design.Half4Converter))]
#endif
[DynamicSerializer("TKH4")]
public struct Half4 : IEquatable<Half4>, IDataSerializable
{
/// <summary>
/// Gets or sets the X component of the vector.
/// </summary>
/// <value>The X component of the vector.</value>
public Half X;
/// <summary>
/// Gets or sets the Y component of the vector.
/// </summary>
/// <value>The Y component of the vector.</value>
public Half Y;
/// <summary>
/// Gets or sets the Z component of the vector.
/// </summary>
/// <value>The Z component of the vector.</value>
public Half Z;
/// <summary>
/// Gets or sets the W component of the vector.
/// </summary>
/// <value>The W component of the vector.</value>
public Half W;
/// <summary>
/// Initializes a new instance of the <see cref="T:SharpDX.Half4" /> structure.
/// </summary>
/// <param name="x">The X component.</param>
/// <param name="y">The Y component.</param>
/// <param name="z">The Z component.</param>
/// <param name="w">The W component.</param>
public Half4(Half x, Half y, Half z, Half w)
{
this.X = x;
this.Y = y;
this.Z = z;
this.W = w;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:SharpDX.Half4" /> structure.
/// </summary>
/// <param name="value">The value to set for the X, Y, Z, and W components.</param>
public Half4(Half value)
{
this.X = value;
this.Y = value;
this.Z = value;
this.W = value;
}
/// <summary>
/// Performs an implicit conversion from <see cref="SharpDX.Vector4"/> to <see cref="SharpDX.Half4"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Half4(Vector4 value)
{
return new Half4(value.X, value.Y, value.Z, value.W);
}
/// <summary>
/// Performs an implicit conversion from <see cref="SharpDX.Half4"/> to <see cref="SharpDX.Vector4"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static implicit operator Vector4(Half4 value)
{
return new Vector4(value.X, value.Y, value.Z, value.W);
}
/// <summary>
/// Performs an explicit conversion from <see cref="SharpDX.Vector3"/> to <see cref="SharpDX.Half4"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Half4(Vector3 value)
{
return new Half4(value.X, value.Y, value.Z, 0.0f);
}
/// <summary>
/// Performs an explicit conversion from <see cref="SharpDX.Half4"/> to <see cref="SharpDX.Vector3"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Vector3(Half4 value)
{
return new Vector3(value.X, value.Y, value.Z);
}
/// <summary>
/// Performs an explicit conversion from <see cref="SharpDX.Vector2"/> to <see cref="SharpDX.Half4"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Half4(Vector2 value)
{
return new Half4(value.X, value.Y, 0.0f, 0.0f);
}
/// <summary>
/// Performs an explicit conversion from <see cref="SharpDX.Half4"/> to <see cref="SharpDX.Vector2"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator Vector2(Half4 value)
{
return new Vector2(value.X, value.Y);
}
/// <summary>
/// Tests for equality between two objects.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns>
/// <c>true</c> if <paramref name="left" /> has the same value as <paramref name="right" />; otherwise, <c>false</c>.</returns>
public static bool operator ==(Half4 left, Half4 right)
{
return Equals(ref left, ref right);
}
/// <summary>
/// Tests for inequality between two objects.
/// </summary>
/// <param name="left">The first value to compare.</param>
/// <param name="right">The second value to compare.</param>
/// <returns>
/// <c>true</c> if <paramref name="left" /> has a different value than <paramref name="right" />; otherwise, <c>false</c>.</returns>
public static bool operator !=(Half4 left, Half4 right)
{
return !Equals(ref left, ref right);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
int num2 = this.W.GetHashCode() + this.Z.GetHashCode();
int num = this.Y.GetHashCode() + num2;
return (this.X.GetHashCode() + num);
}
/// <inheritdoc/>
void IDataSerializable.Serialize(BinarySerializer serializer)
{
// Write optimized version without using Serialize methods
if (serializer.Mode == SerializerMode.Write)
{
serializer.Writer.Write(X.RawValue);
serializer.Writer.Write(Y.RawValue);
serializer.Writer.Write(Z.RawValue);
serializer.Writer.Write(W.RawValue);
}
else
{
X.RawValue = serializer.Reader.ReadUInt16();
Y.RawValue = serializer.Reader.ReadUInt16();
Z.RawValue = serializer.Reader.ReadUInt16();
W.RawValue = serializer.Reader.ReadUInt16();
}
}
/// <summary>
/// Determines whether the specified object instances are considered equal.
/// </summary>
/// <param name="value1" />
/// <param name="value2" />
/// <returns>
/// <c>true</c> if <paramref name="value1" /> is the same instance as <paramref name="value2" /> or
/// if both are <c>null</c> references or if <c>value1.Equals(value2)</c> returns <c>true</c>; otherwise, <c>false</c>.</returns>
public static bool Equals(ref Half4 value1, ref Half4 value2)
{
return (((value1.X == value2.X) && (value1.Y == value2.Y)) && ((value1.Z == value2.Z) && (value1.W == value2.W)));
}
/// <summary>
/// Returns a value that indicates whether the current instance is equal to the specified object.
/// </summary>
/// <param name="other">Object to make the comparison with.</param>
/// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public bool Equals(Half4 other)
{
return (((this.X == other.X) && (this.Y == other.Y)) && ((this.Z == other.Z) && (this.W == other.W)));
}
/// <summary>
/// Returns a value that indicates whether the current instance is equal to a specified object.
/// </summary>
/// <param name="obj">Object to make the comparison with.</param>
/// <returns>
/// <c>true</c> if the current instance is equal to the specified object; <c>false</c> otherwise.</returns>
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
if (!ReferenceEquals(obj.GetType(), typeof(Half4)))
{
return false;
}
return this.Equals((Half4)obj);
}
}
}
| shoelzer/SharpDX | Source/SharpDX/Half4.cs | C# | mit | 10,134 |