code stringlengths 2 1.05M |
|---|
class vss_vsscoordinator_1 {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = vss_vsscoordinator_1;
|
const StarOverlayNetwork = require('../../lib/star-overlay-network')
module.exports =
function buildStarNetwork (id, peerPool, {isHub, connectionTimeout}={}) {
const network = new StarOverlayNetwork({id, peerPool, isHub, connectionTimeout})
network.testJoinEvents = []
network.onMemberJoin(({peerId}) => network.testJoinEvents.push(peerId))
network.testLeaveEvents = []
network.onMemberLeave(({peerId, connectionLost}) => network.testLeaveEvents.push({peerId, connectionLost}))
network.testInbox = []
network.onReceive(({senderId, message}) => {
network.testInbox.push({
senderId,
message: message.toString()
})
})
return network
}
|
'use strict';
// Declare app level module which depends on filters, and services
angular.module('myApp', [
'ngRoute',
'ngCookies',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers',
'ui.bootstrap'
]).
config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/index', {templateUrl: 'partials/index.html', controller: 'IndexCtrl'});
$routeProvider.when('/form', {templateUrl: 'partials/searchForm.html', controller: 'SearchFormCtrl'});
$routeProvider.when('/search', {templateUrl: 'partials/search.html', controller: 'SearchCtrl'});
$routeProvider.when('/occurrence/dev', {templateUrl: 'partials/occurrence.html', controller: 'DevOccurrenceCtrl'});
$routeProvider.when('/occurrence/:id/:version', {templateUrl: 'partials/occurrence.html', controller: 'OccurrenceCtrl'});
$routeProvider.when('/occurrence/:id', {templateUrl: 'partials/occurrence.html', controller: 'OccurrenceCtrl'});
$routeProvider.otherwise({redirectTo: '/index'});
}]);
|
"use strict";
let entries = require("../mongodb/entries");
exports.createEntry = function(req,res,next) {
if (!req.session.userID) {
return next(new Error("user is not logged in"));
}
let entry = req.body;
if (entry.date) {
entry.date = new Date(entry.date);
}
entries.createEntry(req.db, req.session.userID, req.api.logID, entry).then(function (_id) {
res.json({
_id: _id
});
}).catch(function (err) {
next(err);
});
};
exports.readEntry = function (req,res,next) {
if (!req.session.userID) {
return next(new Error("user is not logged in"));
}
entries.readEntry(req.db, req.session.userID, req.api.logID, req.api.id).then(function (entry) {
res.json(entry);
});
};
exports.readEntryList = function (req,res,next) {
if (!req.session.userID) {
return next(new Error("user is not logged in"));
}
entries.readEntryList(req.db, req.session.userID, req.api.logID).then(function (list) {
let obj = {
list: list
};
res.json(obj);
});
};
exports.updateEntry = function (req,res,next) {
if (!req.session.userID) {
return next(new Error("user is not logged in"));
}
entries.updateEntry(req.db, req.session.userID, req.api.logID, req.api.id, req.body).then(function () {
res.end();
});
};
exports.deleteEntry = function (req,res,next) {
if (!req.session.userID) {
return next(new Error("user is not logged in"));
}
entries.deleteEntry(req.db, req.session.userID, req.api.logID, req.api.id).then(function () {
res.end();
});
};
exports.deleteEntryList = function (req,res,next) {
if (!req.session.userID) {
return next(new Error("user is not logged in"));
}
entries.deleteEntryList(req.db, req.session.userID, req.api.logID).then(function (deletedCount) {
let obj = {
deletedCount: deletedCount
};
res.json(obj);
});
};
|
import Vue from 'vue'
import Vuex from 'vuex'
import menus from './modules/menus.js'
import copyText from './modules/copyText.js'
import features from './modules/features.js'
import settings from './modules/settings.js'
import Persistance from '../api/vuex/persistance.js'
import createLogger from 'vuex/logger'
import truth from '../truth/truth.js'
Vue.use( Vuex )
var store = Persistance.get();
const state =
{
//store,
truth,
models:{
projects:{},
tasks:{},
conversations:{},
messages:{},
inventories:{},
},
pages:{
home:{
//menulayout:{},
},
},
};
export const mutations = {
SET_ROUTE (state, payload) {
state.currentRoute = payload
},
SET_MODEL (state, payload) {
state.models[payload[0]+''] = payload[1]
},
SET_PAGE (state, payload) {
state.pages[payload[0]+''] = payload[1]
},
// SET_COPY_TEXT (state, location, payload) {
// state.copyText[location['base']][location['name']][location['instance']] = location[1]
// },
SET_COMPANY_BRAND_DETAIL (state, payload) {
state.truth.company.branding[payload[0]+''] = payload[1]
},
}
const logger = createLogger({
collapsed: true, // auto-expand logged mutations
transformer (state) {
// transform the state before logging it.
// for example return only a specific sub-tree
return state
},
mutationTransformer (mutation) {
// mutations are logged in the format of { type, payload }
// we can format it anyway we want.
return mutation.type+' - '+mutation.payload
}
})
const persistToDatabase = {
snapshot: true,
onMutation (mutation, nextState, prevState, store) {
// console.log( mutation )
// console.log( prevState )
// console.log( nextState )
// console.log( store )
Persistance.save(nextState)
}
}
export default new Vuex.Store({
//remove these next two lines when in prodution cpu intence
middlewares: [createLogger(), persistToDatabase],
strict: true,
modules: {
menus,
copyText,
settings,
features,
},
state,
mutations
}) |
'use strict'
require('./app')
|
'use strict';
module.exports = {
db: 'mongodb://localhost/mecenate-web-test',
port: 3001,
app: {
title: 'mecenate-web - Test Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: '/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: '/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: '/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: '/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: '/auth/github/callback'
},
mailer: {
from: process.env.MAILER_FROM || 'MAILER_FROM',
options: {
service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER',
auth: {
user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID',
pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD'
}
}
}
};
|
define(["./inner"],function(inner){
var t
return inner
})
|
angular.module('team-task')
.controller('WorkforceController', ['$scope', '$rootScope', '$state', 'Atividade', 'Time',
'Pessoa', '$stateParams', 'Projeto', '$filter', '$uibModal',
function ($scope, $rootScope, $state, Atividade, Time, Pessoa, $stateParams, Projeto, $filter, $uibModal) {
$rootScope.showLoading = false;
function loadTable() {
$rootScope.showLoading = true;
Pessoa.getById($stateParams.id).then(function (pessoa) {
if (pessoa) {
var qTime = {
"recursos": $stateParams.id
};
Time.query(qTime, {"sort": {"nome": 1}}).then(function (times) {
if (times[0]) {
var listaTimes = [];
for (var i = 0; i < times.length; i++) {
listaTimes.push(times[i]._id.$oid);
}
$scope.cargaPessoa = pessoa;
$scope.ganttData = [];
var aQtdQuery = {
"time": {
"$in": listaTimes
},
"designado": pessoa._id.$oid
};
Atividade.query(aQtdQuery).then(function (atividades) {
for (var indexTimeAtividade = 0; indexTimeAtividade < atividades.length; indexTimeAtividade++) {
var time = $filter('filter')(times, {"_id" : {"$oid" : atividades[indexTimeAtividade].time}});
var nomeTime = "";
if(time && time.length > 0) {
nomeTime = time[0].nome + " / ";
}
var rowAt = {
"name": nomeTime + atividades[indexTimeAtividade].nome,
"time": time,
"status": atividades[indexTimeAtividade].status,
"atividade": atividades[indexTimeAtividade]
};
rowAt.tasks = [];
var listDep = [];
var statusColor =
atividades[indexTimeAtividade].status.toLowerCase() === 'aguardando' ? '#5bc0de' :
atividades[indexTimeAtividade].status.toLowerCase() === 'iniciada' ? '#f0ad4e' : '#5cb85c';
rowAt.tasks.push({
"id": nomeTime + atividades[indexTimeAtividade].nome,
"name": atividades[indexTimeAtividade].nome,
"from": moment(atividades[indexTimeAtividade].inicio.$date),
"to": moment(atividades[indexTimeAtividade].fim.$date),
"color": statusColor,
"status": atividades[indexTimeAtividade].status,
"dependencies": listDep,
"progress": {
"percent": atividades[indexTimeAtividade].progresso,
"color": "#606060"
}
});
$scope.ganttData.push(rowAt);
}
var pQtdQuery = {
"status": "Ativo",
"atividades.designado": pessoa._id.$oid
};
Projeto.query(pQtdQuery).then(function (projetos) {
for (var p = 0; p < projetos.length; p++) {
for (var at = 0; at < projetos[p].atividades.length; at++) {
if (projetos[p].atividades[at].designado === pessoa._id.$oid) {
var rowPr = {
"name": projetos[p].nome + " / " + projetos[p].atividades[at].nome,
"atividade": projetos[p].atividades[at],
"status": projetos[p].atividades[at].status,
"projeto": projetos[p],
"indiceAt": at
};
rowPr.tasks = [];
var listDep = [];
if(projetos[p].atividades[at].predecessora) {
listDep.push({"from": projetos[p].atividades[at].predecessora.id});
}
var statusColor =
projetos[p].atividades[at].status.toLowerCase() === 'aguardando' ? '#5bc0de' :
projetos[p].atividades[at].status.toLowerCase() === 'iniciada' ? '#f0ad4e' : '#5cb85c';
rowPr.tasks.push({
"id": projetos[p].atividades[at].id,
"name": projetos[p].atividades[at].nome,
"from": moment(projetos[p].atividades[at].inicio.$date),
"to": moment(projetos[p].atividades[at].fim.$date),
"color": statusColor,
"status": projetos[p].atividades[at].status,
"dependencies": listDep,
"progress": {
"percent": projetos[p].atividades[at].progresso,
"color": "#606060"
}
});
$scope.ganttData.push(rowPr);
}
}
}
});
});
}
});
}
});
$rootScope.showLoading = false;
}
$scope.editarAtividade = function (model) {
if(model.projeto) {
$uibModal
.open({
templateUrl: 'views/modal/edit-activity.html',
controller: 'ModalEditActivityController',
resolve: {
projetoSelecionado: function () {
return model.projeto;
},
indice: function () {
return model.indiceAt;
}
}
}).result.then(function () {
loadTable();
$rootScope.$emit("CallLoadMenus", {});
}, function () {
});
} else {
$uibModal
.open({
templateUrl: 'views/modal/edit-team-activity.html',
controller: 'ModalEditTeamActivityController',
resolve: {
timeSelecionado: function () {
return model.time[0];
},
atividadeSelecionada: function () {
return model.atividade;
}
}
}).result.then(function () {
loadTable();
$rootScope.$emit("CallLoadMenus", {});
}, function () {
});
}
};
$scope.mostrarDetalheAtividade = function (model) {
if(model.projeto) {
$uibModal
.open({
templateUrl: 'views/modal/view-activity.html',
controller: 'ModalViewActivityController',
resolve: {
projetoSelecionado: function () {
return model.projeto;
},
indice: function () {
return model.indiceAt;
}
}
}).result.then(function () {}, function () {});
} else {
$uibModal
.open({
templateUrl: 'views/modal/view-team-activity.html',
controller: 'ModalViewTeamActivityController',
resolve: {
atividadeSelecionada: function () {
return model.atividade;
}
}
}).result.then(function () {}, function () {});
}
};
$scope.filtro = [];
$scope.filterChange = function () {
if($scope.filtro) {
var listaFiltro = [];
if ($scope.filtro[0]) {
listaFiltro.push("aguardando");
}
if ($scope.filtro[1]) {
listaFiltro.push("iniciada");
}
if ($scope.filtro[2]) {
listaFiltro.push("concluída");
}
if(listaFiltro.length > 0) {
$scope.ganttOptions.filtertask = listaFiltro;
} else {
$scope.ganttOptions.filtertask = "";
}
} else {
$scope.ganttOptions.filtertask = "";
}
$scope.api.rows.refresh();
};
$scope.filterFunction = function (item) {
if(item && item.model) {
if($scope.ganttOptions.filtertask) {
return $scope.ganttOptions.filtertask.indexOf(item.model.status.toLowerCase()) > -1;
} else {
return false;
}
}
};
$scope.datasChange = function () {
if($scope.fromDate && moment($scope.fromDate).isValid() && moment($scope.fromDate).year() > 2010) {
$scope.ganttOptions.fromDate = $scope.fromDate;
} else {
$scope.ganttOptions.fromDate = undefined;
}
if($scope.toDate && moment($scope.toDate).isValid() && moment($scope.toDate).year() > 2010) {
$scope.ganttOptions.toDate = $scope.toDate;
} else {
$scope.ganttOptions.toDate = undefined;
}
};
$scope.initWorkforce = function () {
$scope.filtro = [true, true, false];
$scope.dateFormat = "dddd, DD/MM/YYYY";
$scope.usuarioLogado = $rootScope.usuarioLogado;
$scope.fromDate = null;
$scope.toDate = null;
$scope.ganttOptions = {
"zoom": 1,
"scale": "week",
"width": true,
"currentDate": 'line',
"tableHeaders": {'model.name': 'Atividade'},
"daily": true,
"sortMode": ["model.time.nome", "model.projeto.nome", "from"],
"taskContent": '<span></span>',
"timeFrames": {
closed: {
magnet: false, // This will disable magnet snapping
working: false // We don't work when it's closed
}
},
"dateFrames": {
weekend: {
evaluator: function(date) {
return date.isoWeekday() === 6 || date.isoWeekday() === 7;
},
targets: ['closed']
}
},
"fromDate": undefined,
"toDate": undefined,
"contents": {
'model.name': '<a ng-click="scope.mostrarDetalheAtividade(row.model)" class="pointer-action">{{getValue()}}</a>' +
' <span class="pointer-action fa fa-pencil-square-o" ' +
'ng-show="row.model.projeto.administrador === scope.usuarioLogado._id.$oid || row.model.time[0].lider === scope.usuarioLogado._id.$oid"' +
'ng-click="scope.editarAtividade(row.model)">'+
'</span>'
},
"filtertask": ["aguardando", "iniciada", "concluída"],
"tooltipcontent": '{{task.model.name}}<span ng-show="task.model.progress.percent"> - {{task.model.progress.percent}}%</span></br>' +
'<small>' +
'{{task.isMilestone() === true && getFromLabel() || getFromLabel() + \' - \' + getToLabel()}}' +
'</small>',
api: function(api) {
$scope.api = api;
api.core.on.rendered($scope, function() {
$scope.filterChange();
});
}
};
loadTable();
};
}]); |
var config = require('config');
var rest = require('restler');
var fs = require("fs");
var dateformat = require("dateformat");
var jsonfile = require("jsonfile");
var rssBaseURL = config.get('rssBaseURL');
var apps = config.get('apps');
var maxPage = config.get('maxPage');
var now = new Date()
var timestamp = dateformat(now, "yyyy-mm-dd");
console.log(timestamp);
for (var i = 0; i < apps.length; i++){
cleanFile("logs/"+apps[i].id+"-all-"+timestamp+".txt");
cleanFile("logs/"+apps[i].id+"-negative-"+timestamp+".txt");
cleanFile("logs/"+apps[i].id+"-positive-"+timestamp+".txt");
apps[i].page = 1;
ignoresReg = new RegExp(apps[i].ignores, "gi");
console.log(ignoresReg);
apps[i].ignoresReg = ignoresReg;
apps[i].stats = {"ratings":[0,0,0,0,0,0]};
getReviews(apps[i]);
}
function getReviews(app) {
var url = rssBaseURL + "page=" + app.page + "/id=" + app.id + "/sortBy=mostRecent/json";
console.log("%s(%d), page %d: %s", app.name, app.id, app.page, url);
rest.get(url).on('success', function(result) {
data = JSON.parse(result);
//console.dir(data, {depth:null});
entries = data.feed.entry;
if (undefined == entries) {
printStats(app);
return;
}
count = entries.length;
// skip the first one since it's just a display for this app
for(var j = 1; j < count; j++) {
entry = entries[j];
text = (entry.title.label + " " + entry.content.label).replace(app.ignoresReg, "").toUpperCase();
rating = entry['im:rating'].label;
printText(app, text, rating);
app.stats.ratings[rating]++;
if (app.page < maxPage) {
app.page++;
getReviews(app);
} else {
printStats(app);
}
}
});
}
function cleanFile(file) {
if (fs.existsSync(file)) {
fs.unlinkSync(file);
}
}
function printStats(app) {
jsonfile.writeFile("logs/"+app.id+"-"+timestamp+".stats", app.stats, {spaces: 2});
}
function printText(app, text, rating) {
allReviews = "logs/"+app.id+"-all-"+timestamp+".txt";
fs.appendFileSync(allReviews, text + "\n");
if (rating < 3) {
reviews = "logs/"+app.id+"-negative-"+timestamp+".txt";
} else {
reviews = "logs/"+app.id+"-positive-"+timestamp+".txt";
}
fs.appendFileSync(reviews, text + "\n");
}
|
'use strict';
describe('caesarCipher', function () {
var caesarCipher;
beforeEach(module('zsoltiii.angular-cipher-filters'));
beforeEach(inject(function ($filter) {
caesarCipher = $filter('caesarCipher');
}));
describe('default parameters', function() {
it('should return the letter n with default parameters', function() {
expect(caesarCipher('a')).toEqual('a');
});
it('should return encrypted sentence with default parameters', function(){
expect(caesarCipher('Why did the chicken cross the road?')).toEqual('Why did the chicken cross the road?');
});
});
describe('rotation parameter', function() {
it('should return the letter c with rotation of 2', function() {
expect(caesarCipher('a', 2)).toEqual('c');
});
it('should return the letter A with rotation of 1', function() {
expect(caesarCipher('Z', 1)).toEqual('A');
});
it('should return encrypted sentence with rotation of 13', function(){
expect(caesarCipher('Why did the chicken cross the road?', 13)).toEqual('Jul qvq gur puvpxra pebff gur ebnq?');
});
});
describe('alternative alphabets', function() {
var alphabetShort;
beforeEach(function(){
alphabetShort = 'abcdef';
});
it('should return the letter a with rotation of 2', function() {
expect(caesarCipher('e', 2, [alphabetShort])).toEqual('a');
});
it('should return encrypted sentence with rotation of 2', function() {
expect(caesarCipher('Why did the chicken cross the road?', 2, [alphabetShort])).toEqual('Why fif tha ehiekan eross tha rocf?');
});
});
describe('decoding', function() {
it('should return the letter v with rotation of -5', function() {
expect(caesarCipher('a', -5)).toEqual('v');
});
it('should return the letter A with rotation of -2', function() {
expect(caesarCipher('C', -2)).toEqual('A');
});
it('should return decrypted sentence with default parameters', function(){
expect(caesarCipher('Jul qvq gur puvpxra pebff gur ebnq?', -13)).toEqual('Why did the chicken cross the road?');
});
});
}); |
export default function canAccessProperty(key, value) {
let prop;
try {
prop = value[key];
} catch (error) {
console.error(error); // eslint-disable-line no-console
}
return !!prop;
}
|
//Modules
var async = require('async');
var tools = require('./tools.js');
var fs = require('fs');
var pathMod = require('path');
var Handlebars = require('handlebars');
var vCard = require('vcards-js');
var vcardparser = require('vcardparser');
var _ = require('lodash');
_.mixin( require('lodash-deep') );
//Global Variables
var templates = {};
//Private functions
(function loadTemplates(){
var files = fs.readdirSync(__dirname + '/templates');
files.forEach(function(templateDir){
templates[templateDir] = fs.readFileSync(__dirname + '/templates/' + templateDir, {encoding : 'utf8'});
templates[templateDir] = Handlebars.compile(templates[templateDir]);
});
})();
//Public functions
var Sync = function( config ){
this.config = config;
this.protocol
};
Sync.prototype.createAddressbook = function( path, info, callback ){
if(!path){
return callback({err : "Error: path required"});
}
var body = templates['newAddressbook'](info);
path = path + tools.uuid() + '/';
this.request('MKCOL', path, body, function (err, res) {
if (err || res.statusCode !== 201) {
callback({err : err, statusCode : res.statusCode});
return;
}
callback(null, path);
});
};
Sync.prototype.modifyAddressbook = function( path, info, callback ){
if(!path){
return callback({err : "Error: path required"});
}
var body = templates['modifyAddressbook'](info);
this.request('PROPPATCH', path, body, function (err, res) {
if (err) {
callback({err : err});
return;
}
callback(null, path);
});
};
Sync.prototype.createContact = function ( path, info, callback ) {
var body = tools.jsonToVCard( info );
path = pathMod.join( path, tools.uuid() + '.vcf' );
this.request( 'PUT', {
path : path,
headers : {
'If-None-Match' : '*',
'Content-Type': 'text/vcard; charset=utf-8'
}}, body, function (err, res) {
if (err || res.statusCode !== 201) {
callback({err : err, statusCode : res.statusCode});
return;
}
callback(null, path);
});
};
Sync.prototype.deleteAddressbook = function ( path, callback ) {
this.request('DELETE', path, '', function (err, res) {
callback(err);
});
};
Sync.prototype.deleteContact = function ( path, callback ) {
this.request('DELETE', path, '', function (err, res) {
callback(err);
});
};
Sync.prototype.getAddressbooks = function( calHome, callback ){
var body = templates['getAddressbooks']();
this.request( 'PROPFIND', { path : calHome, depth : 1 }, body, function( error, res ){
tools.parseXML( res.body, function ( err, data ){
if( err ){
return callback( err );
}
var addressbooks = _.map(data.response, function(internal){
var newObj = {};
newObj.href = internal.href;
newObj = _.extend(newObj, _.deepGet(internal, 'propstat[0].prop[0]'));
newObj = _.reduce(newObj, tools.normalizeAddressbookAttribute, {});
return newObj;
});
addressbooks = _.filter(addressbooks, function(item){
return item.resourcetype.indexOf('addressbook') !== -1;
});
callback(null, addressbooks);
});
});
};
Sync.prototype.getContact = function( path, callback ){
this.request( 'GET', path, '', function( error, res ){
if(error || res.statusCode !== 200){
return callback('UNABLE TO RETRIEVE CONTACT');
}
vcardparser.parseString( res.body, function(err, json) {
if(err) {
return callback(err);
}
//newObj['address-data'] = tools.VCardToJson( json );
callback( null, tools.VCardToJson( json ) );
});
});
};
Sync.prototype.login = function( callback ){
this.request( 'OPTIONS', '', '', function( error, res ){
if(error){
callback(true);
}
else {
callback(null, res.statusCode === 200);
}
});
};
Sync.prototype.getHome = function( callback ){
this.request( 'PROPFIND', '', templates['getHome'](), function( error, res ){
tools.parseXML( res.body, function( err, data ){
if( err ){
return callback( err );
}
callback(null, _.deepGet(data, 'response[0].propstat[0].prop[0].current-user-principal[0].href[0]'));
});
});
};
Sync.prototype.getAddressbookHome = function( home, callback ){
this.request( 'PROPFIND', home, templates['getAddressbookHome'](), function( err, res ){
tools.parseXML( res.body, function( err, data ){
if( err ){
return callback( err );
}
callback(null, _.deepGet(data, 'response[0].propstat[0].prop[0].addressbook-home-set[0].href[0]'));
});
});
};
Sync.prototype.getContacts = function ( filter, path, callback ) {
filter = filter || {};
var body = templates['getContacts'](filter);
body = body.replace(/^\s*$[\n\r]{1,}/gm, '');
this.request('REPORT', { path : path, depth : 1 }, body, function (err, res) {
if (err) {
callback(err);
return;
}
tools.parseXML( res.body, function ( err, data ) {
if (err) {
return callback(err);
}
if(!data || !data.response){
return callback(null, []);
}
async.map( data.response, function(internal, callback){
var newObj = {};
newObj.href = internal.href;
newObj = _.extend(newObj, _.deepGet(internal, 'propstat[0].prop[0]'));
newObj = _.reduce(newObj, tools.normalizeAddressbookAttribute, {});
vcardparser.parseString(newObj['address-data'], function(err, json) {
if(err) {
return callback(err);
}
newObj['address-data'] = tools.VCardToJson( json );
callback( null, newObj );
});
}, callback);
});
});
};
Sync.prototype.modifyContact = function ( path, info, callback ) {
var that = this;
that.request( 'GET', path, '', function( error, res ){
if(error || res.statusCode !== 200){
return callback('UNABLE TO RETRIEVE CONTACT');
}
var etag = res.headers.etag;
var body = tools.jsonToVCard( info );
that.request(
'PUT',
{
path : path,
headers : {
'If-Match' : etag,
'Content-Type': 'text/vcard; charset=utf-8'
}
},
body,
function (err, res) {
if (err || res.statusCode !== 204) {
return callback({err : err, statusCode : res.statusCode});
}
callback(null, path);
}
);
});
};
Sync.prototype.request = function( type, path, body, callback ){
var opts = {
host : this.config.host,
path : typeof path === 'string' ? path || '' : path.path || '',
method : type,
data : body,
port : this.config.port || 5232,
headers : {
'brief' : 't',
'accept-language' : 'es-es',
//'accept-encoding' : 'gzip, deflate',
'connection' : 'keep-alive',
'user-agent' : 'Inevio CalDAV Client',
'prefer' : 'return=minimal',
'Accept' : '*/*',
'Content-Type' : 'text/xml',
'Content-Length' : body.length,
'Depth' : path.depth || 0,
'Authorization' : 'Basic ' + new Buffer( this.config.credentials.user + ':' + this.config.credentials.password ).toString('base64')
}
};
if(path.headers){
opts.headers = _.extend(opts.headers, path.headers);
}
var self = this;
tools.request( opts, this.config.secure, function( err, res ){
if( err ){
return callback( err );
}else if( res.statusCode === 302 ){
self.request( type, res.headers.location, body, callback );
}else{
callback( null, res );
}
});
};
module.exports = Sync;
|
'use strict';
const basicAuth = require('basic-auth');
function unauthorized(res, realm) {
const _realm = realm || 'Authorization Required';
res.set('WWW-Authenticate', `Basic realm=${_realm}`);
return res.sendStatus(401);
};
function isPromiseLike(obj) {
return obj && typeof obj.then === 'function';
}
function isValidUser(user, username, password) {
return !(!user || user.name !== username || user.pass !== password);
}
function createMiddleware(username, password, realm) {
const _realm = typeof username === 'function'
? password
: realm;
return function basicAuthMiddleware(req, res, next) {
const user = basicAuth(req);
if (!user) {
return unauthorized(res, realm);
}
let authorized = null;
if (typeof username === 'function') {
const checkFn = username;
try {
authorized = checkFn(user.name, user.pass, function checkFnCallback(err, authentified) {
if (err) {
return next(err);
}
if (authentified) {
return next();
}
return unauthorized(res, _realm);
});
} catch(err) {
next(err);
}
} else if (Array.isArray(username)) {
authorized = username.some(([username, password]) => isValidUser(user, username, password));
} else {
authorized = isValidUser(user, username, password);
}
if (isPromiseLike(authorized)) {
return authorized
.then(function(authorized) {
if (authorized === true) {
return next();
}
return unauthorized(res, _realm);
})
.catch(next);
}
if (authorized === false) {
return unauthorized(res, _realm);
}
if (authorized === true) {
return next();
}
};
};
module.exports = createMiddleware;
|
const Hapi = require('hapi');
const routes = require('./routes');
const server = new Hapi.Server();
server.connection({ port: process.env.PORT || 8080});
server.route(routes);
server.start((err) => {
if (err) { throw err; }
console.log(`Server running at: ${server.info.uri}`);
});
|
describe('the RepoAssessor', function() {
beforeEach(module('sidewinder-app'));
var $httpBackend, RepoAssessor;
beforeEach(inject(function(_$httpBackend_, _RepoAssessor_, _GitHubRepo_) {
$httpBackend = _$httpBackend_;
RepoAssessor = _RepoAssessor_;
GitHubRepo = _GitHubRepo_;
$httpBackend.whenGET(/\.html$/).respond(200, '');
}));
it('gets the repository state from GitHub combined status API', function(done) {
$httpBackend.whenGET('https://api.github.com/repos/sidewinder-team/sidewinder-server/commits/master/status')
.respond(200, {
state: 'success'
});
var repo = new GitHubRepo('sidewinder-team', 'sidewinder-server');
RepoAssessor.assess(repo).then(function(result) {
expect(result.state).toBe('success');
}).catch(function(error) {
expect(error).toBeUndefined();
}).finally(done);
$httpBackend.flush();
});
it('returns repository state of unknown when connection fails', function(done) {
$httpBackend.whenGET('https://api.github.com/repos/angular/angular.js/commits/master/status')
.respond(500, {
boom: 'goes the dynamite'
});
var repo = new GitHubRepo('angular', 'angular.js');
RepoAssessor.assess(repo).then(function(result) {
expect(result.state).toBe('unknown');
}).catch(function(error) {
expect(error).toBeUndefined();
}).finally(done);
$httpBackend.flush();
});
it('treats a "pending" commit without any statuses as "unknown"', function(done) {
$httpBackend.whenGET('https://api.github.com/repos/sidewinder-team/sidewinder-server/commits/master/status')
.respond(200, {
state: 'pending',
statuses: []
});
var repo = new GitHubRepo('sidewinder-team', 'sidewinder-server');
RepoAssessor.assess(repo).then(function(result) {
expect(result.state).toBe('unknown');
}).catch(function(error) {
expect(error).toBeUndefined();
}).finally(done);
$httpBackend.flush();
});
it('includes state, description, url, and timestamp for each status', function(done) {
$httpBackend.whenGET('https://api.github.com/repos/sidewinder-team/sidewinder-app/commits/master/status')
.respond(200, {
state: 'success',
statuses: [{
"url": "https://api.github.com/repos/sidewinder-team/sidewinder-app/statuses/90a1afaaefb38642784b3a89eab2a7dc459c5d79",
"id": 241039215,
"state": "failure",
"description": "Your tests failed",
"target_url": "https://circleci.com/gh/sidewinder-team/sidewinder-app/2",
"context": "ci/circleci",
"updated_at": "2015-06-14T13:17:56Z"
}, {
"url": "https://api.github.com/repos/sidewinder-team/sidewinder-app/statuses/90a1afaaefb38642784b3a89eab2a7dc459c5d79",
"id": 241040339,
"state": "success",
"description": "The Travis CI build passed",
"target_url": "https://travis-ci.org/sidewinder-team/sidewinder-app/builds/66745547",
"context": "continuous-integration/travis-ci/push",
"updated_at": "2015-06-14T13:25:40Z"
}]
});
var repo = new GitHubRepo('sidewinder-team', 'sidewinder-app');
RepoAssessor.assess(repo).then(function(result) {
expect(result.statuses.length).toBe(2);
expect(result.statuses[0].state).toBe('failure');
expect(result.statuses[0].message).toBe('Your tests failed');
expect(result.statuses[0].href).toBe('https://circleci.com/gh/sidewinder-team/sidewinder-app/2');
expect(result.statuses[0].context).toBe('ci/circleci');
expect(result.statuses[0].timestamp).toBe('2015-06-14T13:17:56Z');
expect(result.statuses[1].state).toBe('success');
expect(result.statuses[1].message).toBe('The Travis CI build passed');
expect(result.statuses[1].href).toBe('https://travis-ci.org/sidewinder-team/sidewinder-app/builds/66745547');
expect(result.statuses[1].context).toBe('continuous-integration/travis-ci/push');
expect(result.statuses[1].timestamp).toBe('2015-06-14T13:25:40Z');
}).catch(function(error) {
expect(error).toBeUndefined();
}).finally(done);
$httpBackend.flush();
});
});
|
import {parse} from 'graphql/language/parser';
import {print} from 'graphql/language/printer';
import {teardownDocumentAST} from '../utils';
/**
* This is a stupid little function that sorts fields by alias & then by name
* That way, testing equality is easy
*/
export const parseSortPrint = graphQLString => {
const ast = parse(graphQLString, {noLocation: true, noSource: true});
return sortPrint(ast);
};
export const sortPrint = ast => {
const {operation} = teardownDocumentAST(ast.definitions);
recurse(operation.selectionSet.selections);
return print(ast);
};
export const sortAST = ast => {
const {operation} = teardownDocumentAST(ast.definitions);
recurse(operation.selectionSet.selections);
return ast;
};
const recurse = astSelections => {
for (let selection of astSelections) {
if (selection.selectionSet) {
recurse(selection.selectionSet.selections);
}
}
astSelections.sort(sortFields);
};
// if true, b moves forward
const sortFields = (a,b) => {
if (a.alias) {
if (b.alias) {
// if both have aliases, sort them alphabetically
return a.alias.value > b.alias.value
}
// if a has an alias, put it ahead of b
return false;
} else if (b.alias) {
// if b has an alias, put it ahead of a
return true;
}
if (a.name) {
if (b.name) {
// if both have names, sort them alphabetically
return a.name.value > b.name.value;
}
// if a has a name, put it ahead of b
return false;
} else if (b.name) {
// if b has a name, put it ahead of a
return true;
}
if (a.selectionSet) {
if (b.selectionSet) {
// if both are inline frags, sort by the length
return a.selectionSet.selections.length > b.selectionSet.selections.length
}
return false;
} else if (b.selectionSet) {
return true
}
};
// inline frags don't have names, so just stick em at the end
// const sortField = field => (field.alias && field.alias.value) ||
// (field.name && field.name.value) ||
// (field.selectionSet.selections[0].name && field.selectionSet.selections[0].name.value) ||
// Infinity;
|
var TEST_SECRET = sails.config.stripe.testSecretKey;
var stripe = require('stripe')(TEST_SECRET);
module.exports = {
charge: function (req, res) {
var userId = req.user.id;
var params = req.params.all();
var source = params.source;
var provider = params.providerId;
var amount = params.amount;
Provider.findOne(provider, function(err, provider) {
if (err) {
res.badRequest(err);
} else {
stripe_seller_id = provider.stripe_user_id;
stripe.charges.create({
amount: amount,
currency: "usd",
source: source, // obtained with Stripe.js
destination: stripe_seller_id,
application_fee: amount*0.1,
description: "Charge for test@example.com"
}, function(err, charge) {
if (err) {
res.badRequest(err);
} else {
Charge.create()
res.ok(charge);
}
});
}
});
}
};
|
const path = require('path');
const webpack = require('webpack');
const Visualizer = require('webpack-visualizer-plugin');
const Webiny = require('webiny-cli/lib/webiny');
const ModuleIdsPlugin = require('./plugins/ModuleIds');
module.exports = function (app) {
const sharedResolve = require('./resolve')(app);
const name = app.getName();
const bundleName = app.getPath();
const context = Webiny.projectRoot(app.getSourceDir());
const outputPath = path.resolve(Webiny.projectRoot(), 'public_html/build/' + process.env.NODE_ENV, app.getPath());
const plugins = [
new ModuleIdsPlugin(),
new webpack.DefinePlugin({
'DEVELOPMENT': process.env.NODE_ENV === 'development',
'PRODUCTION': process.env.NODE_ENV === 'production',
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
}),
new webpack.DllPlugin({
path: outputPath + '/[name].manifest.json',
name: 'Webiny_' + bundleName + '_Vendor'
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new Visualizer({filename: 'vendor.html'})
];
if (process.env.NODE_ENV === 'production') {
plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
comments: false,
mangle: true,
sourceMap: false
})
);
}
return {
name,
context,
entry: {},
output: {
path: outputPath,
filename: process.env.NODE_ENV === 'production' ? '[name]-[chunkhash].js' : '[name].js',
library: 'Webiny_' + bundleName + '_Vendor'
},
plugins,
externals: name === 'Webiny.Core' ? {} : require('./externals'),
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
require.resolve('babel-preset-es2015'),
require.resolve('babel-preset-react')
],
plugins: [
[require.resolve('babel-plugin-lodash')],
require.resolve('babel-plugin-transform-async-to-generator'),
[require.resolve('babel-plugin-transform-object-rest-spread'), {'useBuiltIns': true}],
[require.resolve('babel-plugin-syntax-dynamic-import')],
[require.resolve('babel-plugin-transform-builtin-extend'), {
globals: ['Error']
}]
]
}
}
]
}
]
},
resolve: sharedResolve
};
}; |
// const meshblu = require('./api/config/meshblu');
const config = require('./api/config/config');
const express = require('./api/config/express');
const mongoose = require('./api/config/mongoose');
const mqtt = require('./api/config/mqtt');
var port = process.env.PORT || config.port;
// Initializing the data base
var db = mongoose();
// Initializing the communication with the Knot Cloud
// var mesh = meshblu();
// Initializing the express app
var app = express();
app.listen(port);
console.log('server running at http://localhost:' + port);
var comm = mqtt();
// Initializing the mqtt communication
// var comm = mqtt();
// Adding a new student
// var controller = require('./api/controllers/student.controller');
// controller.addStudent('ACris', '43313', '134311');
|
'use strict';
angular.module('copayApp.services').factory('walletService', function($log, $timeout, lodash, trezor, ledger, storageService, configService, rateService, uxLanguage, $filter, gettextCatalog, bwcError, $ionicPopup, fingerprintService, ongoingProcess, gettext, $rootScope, txFormatService, $ionicModal, $state, bwcService, bitcore, popupService) {
// `wallet` is a decorated version of client.
var root = {};
root.WALLET_STATUS_MAX_TRIES = 7;
root.WALLET_STATUS_DELAY_BETWEEN_TRIES = 1.4 * 1000;
root.SOFT_CONFIRMATION_LIMIT = 12;
root.SAFE_CONFIRMATIONS = 6;
var errors = bwcService.getErrors();
var _signWithLedger = function(wallet, txp, cb) {
$log.info('Requesting Ledger Chrome app to sign the transaction');
ledger.signTx(txp, wallet.credentials.account, function(result) {
$log.debug('Ledger response', result);
if (!result.success)
return cb(result.message || result.error);
txp.signatures = lodash.map(result.signatures, function(s) {
return s.substring(0, s.length - 2);
});
return wallet.signTxProposal(txp, cb);
});
};
var _signWithTrezor = function(wallet, txp, cb) {
$log.info('Requesting Trezor to sign the transaction');
var xPubKeys = lodash.pluck(wallet.credentials.publicKeyRing, 'xPubKey');
trezor.signTx(xPubKeys, txp, wallet.credentials.account, function(err, result) {
if (err) return cb(err);
$log.debug('Trezor response', result);
txp.signatures = result.signatures;
return wallet.signTxProposal(txp, cb);
});
};
root.invalidateCache = function(wallet) {
if (wallet.cachedStatus)
wallet.cachedStatus.isValid = false;
if (wallet.completeHistory)
wallet.completeHistory.isValid = false;
if (wallet.cachedActivity)
wallet.cachedActivity.isValid = false;
if (wallet.cachedTxps)
wallet.cachedTxps.isValid = false;
};
root.getStatus = function(wallet, opts, cb) {
opts = opts || {};
function processPendingTxps(status) {
var txps = status.pendingTxps;
var now = Math.floor(Date.now() / 1000);
/* To test multiple outputs...
var txp = {
message: 'test multi-output',
fee: 1000,
createdOn: new Date() / 1000,
outputs: []
};
function addOutput(n) {
txp.outputs.push({
amount: 600,
toAddress: '2N8bhEwbKtMvR2jqMRcTCQqzHP6zXGToXcK',
message: 'output #' + (Number(n) + 1)
});
};
lodash.times(150, addOutput);
txps.push(txp);
*/
lodash.each(txps, function(tx) {
tx = txFormatService.processTx(tx);
// no future transactions...
if (tx.createdOn > now)
tx.createdOn = now;
tx.wallet = wallet;
if (!tx.wallet) {
$log.error("no wallet at txp?");
return;
}
var action = lodash.find(tx.actions, {
copayerId: tx.wallet.copayerId
});
if (!action && tx.status == 'pending') {
tx.pendingForUs = true;
}
if (action && action.type == 'accept') {
tx.statusForUs = 'accepted';
} else if (action && action.type == 'reject') {
tx.statusForUs = 'rejected';
} else {
tx.statusForUs = 'pending';
}
if (!tx.deleteLockTime)
tx.canBeRemoved = true;
});
wallet.pendingTxps = txps;
};
function get(cb) {
wallet.getStatus({
twoStep: true
}, function(err, ret) {
if (err) {
if (err instanceof errors.NOT_AUTHORIZED) {
return cb('WALLET_NOT_REGISTERED');
}
return cb(err);
}
return cb(null, ret);
});
};
function cacheBalance(wallet, balance) {
if (!balance) return;
var config = configService.getSync().wallet;
var cache = wallet.cachedStatus;
// Address with Balance
cache.balanceByAddress = balance.byAddress;
// Total wallet balance is same regardless of 'spend unconfirmed funds' setting.
cache.totalBalanceSat = balance.totalAmount;
// Spend unconfirmed funds
if (config.spendUnconfirmed) {
cache.lockedBalanceSat = balance.lockedAmount;
cache.availableBalanceSat = balance.availableAmount;
cache.totalBytesToSendMax = balance.totalBytesToSendMax;
cache.pendingAmount = 0;
cache.spendableAmount = balance.totalAmount - balance.lockedAmount;
} else {
cache.lockedBalanceSat = balance.lockedConfirmedAmount;
cache.availableBalanceSat = balance.availableConfirmedAmount;
cache.totalBytesToSendMax = balance.totalBytesToSendConfirmedMax;
cache.pendingAmount = balance.totalAmount - balance.totalConfirmedAmount;
cache.spendableAmount = balance.totalConfirmedAmount - balance.lockedAmount;
}
// Selected unit
cache.unitToSatoshi = config.settings.unitToSatoshi;
cache.satToUnit = 1 / cache.unitToSatoshi;
cache.unitName = config.settings.unitName;
//STR
cache.totalBalanceStr = txFormatService.formatAmount(cache.totalBalanceSat) + ' ' + cache.unitName;
cache.lockedBalanceStr = txFormatService.formatAmount(cache.lockedBalanceSat) + ' ' + cache.unitName;
cache.availableBalanceStr = txFormatService.formatAmount(cache.availableBalanceSat) + ' ' + cache.unitName;
cache.spendableBalanceStr = txFormatService.formatAmount(cache.spendableAmount) + ' ' + cache.unitName;
cache.pendingBalanceStr = txFormatService.formatAmount(cache.pendingAmount) + ' ' + cache.unitName;
cache.alternativeName = config.settings.alternativeName;
cache.alternativeIsoCode = config.settings.alternativeIsoCode;
// Check address
root.isAddressUsed(wallet, balance.byAddress, function(err, used) {
if (used) {
$log.debug('Address used. Creating new');
// Force new address
root.getAddress(wallet, true, function(err, addr) {
$log.debug('New address: ', addr);
});
}
});
rateService.whenAvailable(function() {
var totalBalanceAlternative = rateService.toFiat(cache.totalBalanceSat, cache.alternativeIsoCode);
var pendingBalanceAlternative = rateService.toFiat(cache.pendingAmount, cache.alternativeIsoCode);
var lockedBalanceAlternative = rateService.toFiat(cache.lockedBalanceSat, cache.alternativeIsoCode);
var spendableBalanceAlternative = rateService.toFiat(cache.spendableAmount, cache.alternativeIsoCode);
var alternativeConversionRate = rateService.toFiat(100000000, cache.alternativeIsoCode);
cache.totalBalanceAlternative = $filter('formatFiatAmount')(totalBalanceAlternative);
cache.pendingBalanceAlternative = $filter('formatFiatAmount')(pendingBalanceAlternative);
cache.lockedBalanceAlternative = $filter('formatFiatAmount')(lockedBalanceAlternative);
cache.spendableBalanceAlternative = $filter('formatFiatAmount')(spendableBalanceAlternative);
cache.alternativeConversionRate = $filter('formatFiatAmount')(alternativeConversionRate);
cache.alternativeBalanceAvailable = true;
cache.isRateAvailable = true;
});
};
function isStatusCached() {
return wallet.cachedStatus && wallet.cachedStatus.isValid;
};
function cacheStatus(status) {
wallet.cachedStatus = status || {};
var cache = wallet.cachedStatus;
cache.statusUpdatedOn = Date.now();
cache.isValid = true;
cache.email = status.preferences ? status.preferences.email : null;
cacheBalance(wallet, status.balance);
};
function walletStatusHash(status) {
return status ? status.balance.totalAmount : wallet.totalBalanceSat;
};
function _getStatus(initStatusHash, tries, cb) {
if (isStatusCached() && !opts.force) {
$log.debug('Wallet status cache hit:' + wallet.id);
cacheStatus(wallet.cachedStatus);
processPendingTxps(wallet.cachedStatus);
return cb(null, wallet.cachedStatus);
};
tries = tries || 0;
$log.debug('Updating Status:', wallet.credentials.walletName, tries);
get(function(err, status) {
if (err) return cb(err);
var currentStatusHash = walletStatusHash(status);
$log.debug('Status update. hash:' + currentStatusHash + ' Try:' + tries);
if (opts.untilItChanges &&
initStatusHash == currentStatusHash &&
tries < root.WALLET_STATUS_MAX_TRIES &&
walletId == wallet.credentials.walletId) {
return $timeout(function() {
$log.debug('Retrying update... ' + walletId + ' Try:' + tries)
return _getStatus(initStatusHash, ++tries, cb);
}, root.WALLET_STATUS_DELAY_BETWEEN_TRIES * tries);
}
processPendingTxps(status);
$log.debug('Got Wallet Status for:' + wallet.credentials.walletName);
cacheStatus(status);
return cb(null, status);
});
};
_getStatus(walletStatusHash(), 0, cb);
};
var getSavedTxs = function(walletId, cb) {
storageService.getTxHistory(walletId, function(err, txs) {
if (err) return cb(err);
var localTxs = [];
if (!txs) {
return cb(null, localTxs);
}
try {
localTxs = JSON.parse(txs);
} catch (ex) {
$log.warn(ex);
}
return cb(null, lodash.compact(localTxs));
});
};
var getTxsFromServer = function(wallet, skip, endingTxid, limit, cb) {
var res = [];
wallet.getTxHistory({
skip: skip,
limit: limit
}, function(err, txsFromServer) {
if (err) return cb(err);
if (!txsFromServer.length)
return cb();
var res = lodash.takeWhile(txsFromServer, function(tx) {
return tx.txid != endingTxid;
});
return cb(null, res, res.length >= limit);
});
};
var removeAndMarkSoftConfirmedTx = function(txs) {
return lodash.filter(txs, function(tx) {
if (tx.confirmations >= root.SOFT_CONFIRMATION_LIMIT)
return tx;
tx.recent = true;
});
}
var processNewTxs = function(wallet, txs) {
var config = configService.getSync().wallet.settings;
var now = Math.floor(Date.now() / 1000);
var txHistoryUnique = {};
var ret = [];
wallet.hasUnsafeConfirmed = false;
lodash.each(txs, function(tx) {
tx = txFormatService.processTx(tx);
// no future transactions...
if (tx.time > now)
tx.time = now;
if (tx.confirmations >= root.SAFE_CONFIRMATIONS) {
tx.safeConfirmed = root.SAFE_CONFIRMATIONS + '+';
} else {
tx.safeConfirmed = false;
wallet.hasUnsafeConfirmed = true;
}
if (tx.note) {
delete tx.note.encryptedEditedByName;
delete tx.note.encryptedBody;
}
if (!txHistoryUnique[tx.txid]) {
ret.push(tx);
txHistoryUnique[tx.txid] = true;
} else {
$log.debug('Ignoring duplicate TX in history: ' + tx.txid)
}
});
return ret;
};
var updateLocalTxHistory = function(wallet, progressFn, cb) {
var FIRST_LIMIT = 5;
var LIMIT = 50;
var requestLimit = FIRST_LIMIT;
var walletId = wallet.credentials.walletId;
var config = configService.getSync().wallet.settings;
progressFn = progressFn || function() {};
var fixTxsUnit = function(txs) {
if (!txs || !txs[0] || !txs[0].amountStr) return;
var cacheUnit = txs[0].amountStr.split(' ')[1];
if (cacheUnit == config.unitName)
return;
var name = ' ' + config.unitName;
$log.debug('Fixing Tx Cache Unit to:' + name)
lodash.each(txs, function(tx) {
tx.amountStr = txFormatService.formatAmount(tx.amount) + name;
tx.feeStr = txFormatService.formatAmount(tx.fees) + name;
});
};
getSavedTxs(walletId, function(err, txsFromLocal) {
if (err) return cb(err);
fixTxsUnit(txsFromLocal);
var confirmedTxs = removeAndMarkSoftConfirmedTx(txsFromLocal);
var endingTxid = confirmedTxs[0] ? confirmedTxs[0].txid : null;
var endingTs = confirmedTxs[0] ? confirmedTxs[0].time : null;
// First update
progressFn(txsFromLocal, 0);
wallet.completeHistory = txsFromLocal;
function getNewTxs(newTxs, skip, cb) {
getTxsFromServer(wallet, skip, endingTxid, requestLimit, function(err, res, shouldContinue) {
if (err) {
$log.warn(bwcError.msg(err, 'BWS Error')); //TODO
if (err instanceof errors.CONNECTION_ERROR || (err.message && err.message.match(/5../))) {
$log.info('Retrying history download in 5 secs...');
return $timeout(function() {
return getNewTxs(newTxs, skip, cb);
}, 5000);
};
return cb(err);
}
newTxs = newTxs.concat(processNewTxs(wallet, lodash.compact(res)));
progressFn(newTxs.concat(txsFromLocal), newTxs.length);
skip = skip + requestLimit;
$log.debug('Syncing TXs. Got:' + newTxs.length + ' Skip:' + skip, ' EndingTxid:', endingTxid, ' Continue:', shouldContinue);
if (!shouldContinue) {
$log.debug('Finished Sync: New / soft confirmed Txs: ' + newTxs.length);
return cb(null, newTxs);
}
requestLimit = LIMIT;
getNewTxs(newTxs, skip, cb);
});
};
getNewTxs([], 0, function(err, txs) {
if (err) return cb(err);
var newHistory = lodash.uniq(lodash.compact(txs.concat(confirmedTxs)), function(x) {
return x.txid;
});
function updateNotes(cb2) {
if (!endingTs) return cb2();
$log.debug('Syncing notes from: ' + endingTs);
wallet.getTxNotes({
minTs: endingTs
}, function(err, notes) {
if (err) {
$log.warn(err);
return cb2();
};
lodash.each(notes, function(note) {
$log.debug('Note for ' + note.txid);
lodash.each(newHistory, function(tx) {
if (tx.txid == note.txid) {
$log.debug('...updating note for ' + note.txid);
tx.note = note;
}
});
});
return cb2();
});
}
updateNotes(function() {
var historyToSave = JSON.stringify(newHistory);
lodash.each(txs, function(tx) {
tx.recent = true;
})
$log.debug('Tx History synced. Total Txs: ' + newHistory.length);
// Final update
if (walletId == wallet.credentials.walletId) {
wallet.completeHistory = newHistory;
}
return storageService.setTxHistory(historyToSave, walletId, function() {
$log.debug('Tx History saved.');
return cb();
});
});
});
});
};
root.getTxNote = function(wallet, txid, cb) {
wallet.getTxNote({
txid: txid
}, function(err, note) {
if (err) return cb(err);
return cb(null, note);
});
};
root.editTxNote = function(wallet, args, cb) {
wallet.editTxNote(args, function(err, res) {
return cb(err, res);
});
};
root.getTxp = function(wallet, txpid, cb) {
wallet.getTx(txpid, function(err, txp) {
if (err) return cb(err);
return cb(null, txp);
});
};
root.getTx = function(wallet, txid, cb) {
var tx;
if (wallet.completeHistory && wallet.completeHistory.isValid) {
tx = lodash.find(wallet.completeHistory, {
txid: txid
});
finish();
} else {
root.getTxHistory(wallet, {}, function(err, txHistory) {
if (err) return cb(err);
tx = lodash.find(txHistory, {
txid: txid
});
finish();
});
}
function finish() {
if (tx) return cb(null, tx);
else return cb();
};
};
root.getTxHistory = function(wallet, opts, cb) {
opts = opts || {};
var walletId = wallet.credentials.walletId;
if (!wallet.isComplete()) return cb();
function isHistoryCached() {
return wallet.completeHistory && wallet.completeHistory.isValid;
};
if (isHistoryCached() && !opts.force) return cb(null, wallet.completeHistory);
$log.debug('Updating Transaction History');
updateLocalTxHistory(wallet, opts.progressFn, function(err) {
if (err) return cb(err);
wallet.completeHistory.isValid = true;
return cb(err, wallet.completeHistory);
});
};
root.isEncrypted = function(wallet) {
if (lodash.isEmpty(wallet)) return;
var isEncrypted = wallet.isPrivKeyEncrypted();
if (isEncrypted) $log.debug('Wallet is encrypted');
return isEncrypted;
};
root.createTx = function(wallet, txp, cb) {
if (lodash.isEmpty(txp) || lodash.isEmpty(wallet))
return cb('MISSING_PARAMETER');
wallet.createTxProposal(txp, function(err, createdTxp) {
if (err) return cb(err);
else {
$log.debug('Transaction created');
return cb(null, createdTxp);
}
});
};
root.publishTx = function(wallet, txp, cb) {
if (lodash.isEmpty(txp) || lodash.isEmpty(wallet))
return cb('MISSING_PARAMETER');
wallet.publishTxProposal({
txp: txp
}, function(err, publishedTx) {
if (err) return cb(err);
else {
$log.debug('Transaction published');
return cb(null, publishedTx);
}
});
};
root.signTx = function(wallet, txp, password, cb) {
if (!wallet || !txp || !cb)
return cb('MISSING_PARAMETER');
if (wallet.isPrivKeyExternal()) {
switch (wallet.getPrivKeyExternalSourceName()) {
case 'ledger':
return _signWithLedger(wallet, txp, cb);
case 'trezor':
return _signWithTrezor(wallet, txp, cb);
default:
var msg = 'Unsupported External Key:' + wallet.getPrivKeyExternalSourceName();
$log.error(msg);
return cb(msg);
}
} else {
try {
wallet.signTxProposal(txp, password, function(err, signedTxp) {
$log.debug('Transaction signed err:' + err);
return cb(err, signedTxp);
});
} catch (e) {
$log.warn('Error at signTxProposal:', e);
return cb(e);
}
}
};
root.broadcastTx = function(wallet, txp, cb) {
if (lodash.isEmpty(txp) || lodash.isEmpty(wallet))
return cb('MISSING_PARAMETER');
if (txp.status != 'accepted')
return cb('TX_NOT_ACCEPTED');
wallet.broadcastTxProposal(txp, function(err, broadcastedTxp, memo) {
if (err)
return cb(err);
$log.debug('Transaction broadcasted');
if (memo) $log.info(memo);
return cb(null, broadcastedTxp);
});
};
root.rejectTx = function(wallet, txp, cb) {
if (lodash.isEmpty(txp) || lodash.isEmpty(wallet))
return cb('MISSING_PARAMETER');
wallet.rejectTxProposal(txp, null, function(err, rejectedTxp) {
$log.debug('Transaction rejected');
return cb(err, rejectedTxp);
});
};
root.removeTx = function(wallet, txp, cb) {
if (lodash.isEmpty(txp) || lodash.isEmpty(wallet))
return cb('MISSING_PARAMETER');
wallet.removeTxProposal(txp, function(err) {
$log.debug('Transaction removed');
root.invalidateCache(wallet);
$rootScope.$emit('Local/TxAction', wallet.id);
return cb(err);
});
};
root.updateRemotePreferences = function(clients, prefs, cb) {
prefs = prefs || {};
if (!lodash.isArray(clients))
clients = [clients];
function updateRemotePreferencesFor(clients, prefs, cb) {
var wallet = clients.shift();
if (!wallet) return cb();
$log.debug('Saving remote preferences', wallet.credentials.walletName, prefs);
wallet.savePreferences(prefs, function(err) {
// we ignore errors here
if (err) $log.warn(err);
updateRemotePreferencesFor(clients, prefs, cb);
});
};
// Update this JIC.
var config = configService.getSync().wallet.settings;
//prefs.email (may come from arguments)
prefs.language = uxLanguage.getCurrentLanguage();
prefs.unit = config.unitCode;
updateRemotePreferencesFor(clients, prefs, function(err) {
if (err) return cb(err);
lodash.each(clients, function(c) {
c.preferences = lodash.assign(prefs, c.preferences);
});
return cb();
});
};
root.recreate = function(wallet, cb) {
$log.debug('Recreating wallet:', wallet.id);
ongoingProcess.set('recreating', true);
wallet.recreateWallet(function(err) {
wallet.notAuthorized = false;
ongoingProcess.set('recreating', false);
return cb(err);
});
};
root.startScan = function(wallet, cb) {
cb = cb || function() {};
$log.debug('Scanning wallet ' + wallet.id);
if (!wallet.isComplete()) return;
wallet.updating = true;
ongoingProcess.set('scanning', true);
wallet.startScan({
includeCopayerBranches: true,
}, function(err) {
wallet.updating = false;
ongoingProcess.set('scanning', false);
return cb(err);
});
};
root.expireAddress = function(wallet, cb) {
$log.debug('Cleaning Address ' + wallet.id);
storageService.clearLastAddress(wallet.id, function(err) {
return cb(err);
});
};
// Check address
root.isAddressUsed = function(wallet, byAddress, cb) {
storageService.getLastAddress(wallet.id, function(err, addr) {
var used = lodash.find(byAddress, {
address: addr
});
return cb(err, used);
});
};
var createAddress = function(wallet, cb) {
$log.debug('Creating address for wallet:', wallet.id);
wallet.createAddress({}, function(err, addr) {
if (err) {
var prefix = gettextCatalog.getString('Could not create address');
if (err.error && err.error.match(/locked/gi)) {
$log.debug(err.error);
return $timeout(function() {
createAddress(wallet, cb);
}, 5000);
} else if (err.message && err.message == 'MAIN_ADDRESS_GAP_REACHED') {
$log.warn(err.message);
prefix = null;
wallet.getMainAddresses({
reverse: true,
limit: 1
}, function(err, addr) {
if (err) return cb(err);
return cb(null, addr[0].address);
});
}
return bwcError.cb(err, prefix, cb);
}
return cb(null, addr.address);
});
};
root.getMainAddresses = function(wallet, opts, cb) {
opts = opts || {};
opts.reverse = true;
wallet.getMainAddresses(opts, function(err, addresses) {
return cb(err, addresses);
});
};
root.getBalance = function(wallet, opts, cb) {
opts = opts || {};
wallet.getBalance(opts, function(err, resp) {
return cb(err, resp);
});
};
root.getAddress = function(wallet, forceNew, cb) {
storageService.getLastAddress(wallet.id, function(err, addr) {
if (err) return cb(err);
if (!forceNew && addr) return cb(null, addr);
if (!wallet.isComplete())
return cb('WALLET_NOT_COMPLETE');
createAddress(wallet, function(err, _addr) {
if (err) return cb(err, addr);
storageService.storeLastAddress(wallet.id, _addr, function() {
if (err) return cb(err);
return cb(null, _addr);
});
});
});
};
root.isReady = function(wallet, cb) {
if (!wallet.isComplete())
return cb('WALLET_NOT_COMPLETE');
if (wallet.needsBackup)
return cb('WALLET_NEEDS_BACKUP');
return cb();
};
// An alert dialog
var askPassword = function(name, title, cb) {
var opts = {
inputType: 'password',
forceHTMLPrompt: true,
class: 'text-warn'
};
popupService.showPrompt(title, name, opts, function(res) {
if (!res) return cb();
if (res) return cb(res)
});
};
root.encrypt = function(wallet, cb) {
var title = gettextCatalog.getString('Enter new spending password');
var warnMsg = gettextCatalog.getString('Your wallet key will be encrypted. The Spending Password cannot be recovered. Be sure to write it down.');
askPassword(warnMsg, title, function(password) {
if (!password) return cb('no password');
title = gettextCatalog.getString('Confirm you new spending password');
askPassword(warnMsg, gettextCatalog.getString('Confirm you new spending password'), function(password2) {
if (!password2 || password != password2)
return cb('password mismatch');
wallet.encryptPrivateKey(password);
return cb();
});
});
};
root.decrypt = function(wallet, cb) {
$log.debug('Disabling private key encryption for' + wallet.name);
askPassword(null, gettextCatalog.getString('Enter Spending Password'), function(password) {
if (!password) return cb('no password');
try {
wallet.decryptPrivateKey(password);
} catch (e) {
return cb(e);
}
return cb();
});
};
root.handleEncryptedWallet = function(wallet, cb) {
if (!root.isEncrypted(wallet)) return cb();
askPassword(wallet.name, gettextCatalog.getString('Enter Spending Password'), function(password) {
if (!password) return cb('No password');
if (!wallet.checkPassword(password)) return cb('Wrong password');
return cb(null, password);
});
};
root.reject = function(wallet, txp, cb) {
ongoingProcess.set('rejectTx', true);
root.rejectTx(wallet, txp, function(err, txpr) {
root.invalidateCache(wallet);
ongoingProcess.set('rejectTx', false);
if (err) return cb(err);
$rootScope.$emit('Local/TxAction', wallet.id);
return cb(null, txpr);
});
};
root.onlyPublish = function(wallet, txp, cb, customStatusHandler) {
ongoingProcess.set('sendingTx', true, customStatusHandler);
root.publishTx(wallet, txp, function(err, publishedTxp) {
root.invalidateCache(wallet);
ongoingProcess.set('sendingTx', false, customStatusHandler);
if (err) return cb(bwcError.msg(err));
$rootScope.$emit('Local/TxAction', wallet.id);
return cb();
});
};
root.prepare = function(wallet, cb) {
fingerprintService.check(wallet, function(err) {
if (err) return cb(err);
root.handleEncryptedWallet(wallet, function(err, password) {
if (err) return cb(err);
return cb(null, password);
});
});
};
root.publishAndSign = function(wallet, txp, cb, customStatusHandler) {
var publishFn = root.publishTx;
// Already published?
if (txp.status == 'pending') {
publishFn = function(wallet, txp, cb) {
return cb(null, txp);
};
}
root.prepare(wallet, function(err, password) {
if (err) return cb(bwcError.msg(err));
ongoingProcess.set('sendingTx', true, customStatusHandler);
publishFn(wallet, txp, function(err, publishedTxp) {
ongoingProcess.set('sendingTx', false, customStatusHandler);
if (err) return cb(bwcError.msg(err));
ongoingProcess.set('signingTx', true, customStatusHandler);
root.signTx(wallet, publishedTxp, password, function(err, signedTxp) {
ongoingProcess.set('signingTx', false, customStatusHandler);
root.invalidateCache(wallet);
if (err) {
$log.warn('sign error:' + err);
var msg = err && err.message ?
err.message :
gettextCatalog.getString('The payment was created but could not be completed. Please try again from home screen');
$rootScope.$emit('Local/TxAction', wallet.id);
return cb(msg);
}
if (signedTxp.status == 'accepted') {
ongoingProcess.set('broadcastingTx', true, customStatusHandler);
root.broadcastTx(wallet, signedTxp, function(err, broadcastedTxp) {
ongoingProcess.set('broadcastingTx', false, customStatusHandler);
if (err) return cb(bwcError.msg(err));
$rootScope.$emit('Local/TxAction', wallet.id);
return cb(null, broadcastedTxp);
});
} else {
$rootScope.$emit('Local/TxAction', wallet.id);
return cb(null, signedTxp);
}
});
});
});
};
root.getEncodedWalletInfo = function(wallet, password, cb) {
var derivationPath = wallet.credentials.getBaseAddressDerivationPath();
var encodingType = {
mnemonic: 1,
xpriv: 2,
xpub: 3
};
var info;
// not supported yet
if (wallet.credentials.derivationStrategy != 'BIP44' || !wallet.canSign())
return cb(gettextCatalog.getString('Exporting via QR not supported for this wallet'));
var keys = root.getKeysWithPassword(wallet, password);
if (keys.mnemonic) {
info = {
type: encodingType.mnemonic,
data: keys.mnemonic,
}
} else {
info = {
type: encodingType.xpriv,
data: keys.xPrivKey
}
}
return cb(null, info.type + '|' + info.data + '|' + wallet.credentials.network.toLowerCase() + '|' + derivationPath + '|' + (wallet.credentials.mnemonicHasPassphrase));
};
root.setTouchId = function(wallet, enabled, cb) {
var opts = {
touchIdFor: {}
};
opts.touchIdFor[wallet.id] = enabled;
fingerprintService.check(wallet, function(err) {
if (err) {
opts.touchIdFor[wallet.id] = !enabled;
$log.debug('Error with fingerprint:' + err);
return cb(err);
}
configService.set(opts, cb);
});
};
root.getKeys = function(wallet, cb) {
root.prepare(wallet, function(err, password) {
if (err) return cb(err);
var keys;
try {
keys = wallet.getKeys(password);
} catch (e) {
return cb(e);
}
return cb(null, keys);
});
};
root.getKeysWithPassword = function(wallet, password) {
try {
return wallet.getKeys(password);
} catch (e) {}
}
root.getSendMaxInfo = function(wallet, opts, cb) {
opts = opts || {};
wallet.getSendMaxInfo(opts, function(err, res) {
return cb(err, res);
});
};
return root;
});
|
define(['summernote/core/func'], function (func) {
/**
* list utils
*/
var list = (function () {
/**
* returns the first element of an array.
* @param {Array} array
*/
var head = function (array) {
return array[0];
};
/**
* returns the last element of an array.
* @param {Array} array
*/
var last = function (array) {
return array[array.length - 1];
};
/**
* returns everything but the last entry of the array.
* @param {Array} array
*/
var initial = function (array) {
return array.slice(0, array.length - 1);
};
/**
* returns the rest of the elements in an array.
* @param {Array} array
*/
var tail = function (array) {
return array.slice(1);
};
/**
* returns next item.
* @param {Array} array
*/
var next = function (array, item) {
var idx = array.indexOf(item);
if (idx === -1) { return null; }
return array[idx + 1];
};
/**
* returns prev item.
* @param {Array} array
*/
var prev = function (array, item) {
var idx = array.indexOf(item);
if (idx === -1) { return null; }
return array[idx - 1];
};
var all = function (array, pred) {
for (var idx = 0, len = array.length; idx < len; idx ++) {
if (!pred(array[idx])) {
return false;
}
}
return true;
};
var contains = function (array, item) {
return array.indexOf(item) !== -1;
};
/**
* get sum from a list
* @param {Array} array - array
* @param {Function} fn - iterator
*/
var sum = function (array, fn) {
fn = fn || func.self;
return array.reduce(function (memo, v) {
return memo + fn(v);
}, 0);
};
/**
* returns a copy of the collection with array type.
* @param {Collection} collection - collection eg) node.childNodes, ...
*/
var from = function (collection) {
var result = [], idx = -1, length = collection.length;
while (++idx < length) {
result[idx] = collection[idx];
}
return result;
};
/**
* cluster elements by predicate function.
* @param {Array} array - array
* @param {Function} fn - predicate function for cluster rule
* @param {Array[]}
*/
var clusterBy = function (array, fn) {
if (!array.length) { return []; }
var aTail = tail(array);
return aTail.reduce(function (memo, v) {
var aLast = last(memo);
if (fn(last(aLast), v)) {
aLast[aLast.length] = v;
} else {
memo[memo.length] = [v];
}
return memo;
}, [[head(array)]]);
};
/**
* returns a copy of the array with all falsy values removed
* @param {Array} array - array
* @param {Function} fn - predicate function for cluster rule
*/
var compact = function (array) {
var aResult = [];
for (var idx = 0, len = array.length; idx < len; idx ++) {
if (array[idx]) { aResult.push(array[idx]); }
}
return aResult;
};
var unique = function (array) {
var results = [];
for (var idx = 0, len = array.length; idx < len; idx ++) {
if (results.indexOf(array[idx]) === -1) {
results.push(array[idx]);
}
}
return results;
};
return { head: head, last: last, initial: initial, tail: tail,
prev: prev, next: next, contains: contains,
all: all, sum: sum, from: from,
clusterBy: clusterBy, compact: compact, unique: unique };
})();
return list;
});
|
function slugify(string) {
return string
.toString()
.trim()
.toLowerCase()
.replace(/\s+/g, "-")
.replace(/[^\w\-]+/g, "")
.replace(/\-\-+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "");
};
angular.module("exambazaar").controller("officialPapersController",
[ '$scope', '$rootScope', '$cookies', '$state', '$stateParams', 'coachingService', 'Notification', function($scope, $rootScope, $cookies, $state, $stateParams, coachingService, Notification){
$scope.currCity = null;
$scope.currCountry = null;
function latlngfromIP(){
if($cookies.getObject('ip')){
var thisIP = $cookies.getObject('ip');
//console.log("Using IP to geolocate user");
//console.log(thisIP);
$scope.currLocation = [thisIP.lat, thisIP.long];
$scope.currCity = thisIP.city;
$scope.currCountry = thisIP.country;
Notification.warning({message: "Exambazaar couldn't locate you with accuracy", positionY: 'top', positionX: 'right', delay: 1000});
}
};
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
alert("Geolocation is not supported by your browser");
latlngfromIP();
//use ip info
}
function displayPosition(position) {
$scope.currLocation = [position.coords.latitude, position.coords.longitude];
//console.log($scope.currLocation);
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
console.log("Error: " + errors[error.code]);
//use ip info
latlngfromIP();
}
$scope.goToN4 = function(){
if($scope.suggestedcoachings && $scope.suggestedcoachings.length > 0 && $scope.exam){
var examslug = $scope.exam.coaching_page_slug;
var cityslug = $scope.suggestedcoachings[0].city;
if(cityslug){
cityslug = slugify(cityslug);
}
console.log(examslug + " " + cityslug);
if(examslug && cityslug){
$state.go('findCoaching2', {examslug: examslug, cityslug: cityslug});
}else{
Notification.warning({message: "Exambazaar couldn't locate you with accuracy", positionY: 'top', positionX: 'right', delay: 1000});
}
}else{
Notification.warning({message: "Exambazaar couldn't locate you with accuracy", positionY: 'top', positionX: 'right', delay: 1000});
}
};
$scope.$watch('[currLocation,exam]', function (newValue, oldValue, scope){
if(newValue[0] && newValue[1]){
if(newValue[0] && newValue[0].length == 2){
$scope.currLatLng = {
lat: $scope.currLocation[0],
lng: $scope.currLocation[1],
}
var examUserinfo = {
exam: $scope.exam._id,
userinfo: {
user: null,
latlng: $scope.currLatLng,
city: $scope.currCity,
country: $scope.currCountry,
},
};
if($scope.user && $scope.user._id){
examUserinfo.userinfo.user = $scope.user._id;
}
coachingService.suggestedcoachingsPL2(examUserinfo).success(function (data, status, headers) {
$scope.suggestedcity = $scope.currCity;
$scope.suggestedcoachings = data;
})
.error(function (data, status, header, config) {
console.log("Error ");
});
}
}
}, true);
$scope.$watch("allExams", function (newValue, oldValue, rootScope){
if(newValue){
var allExams = $rootScope.allExams;
var allURLSlugs = allExams.map(function(a) {return a.question_papers_urlslug});
var thisExamSlug = $stateParams.question_papers_urlslug;
var eIndex = allURLSlugs.indexOf(thisExamSlug);
if(eIndex != -1){
$scope.exam = allExams[eIndex];
var streamId = $scope.exam.stream;
var allStreamIds = $rootScope.streamExams.map(function(a) {return a._id});
var sIndex = allStreamIds.indexOf(streamId);
if(sIndex != -1){
$scope.stream = $rootScope.streamExams[sIndex];
$rootScope.pageExam = $scope.exam;
$rootScope.pageStream = $scope.stream;
$rootScope.pageCourses = $rootScope.degreeBlogs[$scope.exam._id.toString()];
if(!$rootScope.pageCourses){
$rootScope.pageCourses = [];
}
$rootScope.examHubs = $rootScope.examBlogs[$scope.exam._id.toString()];
if(!$rootScope.examHubs){
$rootScope.examHubs = [];
}
if($rootScope.streamranks){
var streamNames = $rootScope.streamranks.map(function(a) {return a.stream});
var nIndex = streamNames.indexOf($scope.stream.stream);
if(nIndex != -1){
$scope.streamDegrees = $rootScope.streamranks[nIndex];
}
}
var qpURL = $scope.exam.question_papers_urlslug;
if(qpURL){
qpURL = "https://www.exambazaar.com/qp/" + qpURL;
$scope.canonicalFlip = true;
$rootScope.canonicalUrl = qpURL;
console.log("Canonical URL is: " + $rootScope.canonicalUrl);
}
$scope.defaultCoverPhoto = 'https://www.exambazaar.com/images/generic_question_papers.png';
if($scope.exam.officialpaperscoverphoto && $scope.exam.officialpaperscoverphoto != ''){
$scope.defaultCoverPhoto = $scope.exam.officialpaperscoverphoto;
};
$rootScope.pageImage = $scope.defaultCoverPhoto;
$rootScope.pageTitle = $scope.exam.exam_page_name + " Question Papers with Answer Keys: Attempt, Download and Analyse";
var keywordString = '';
var suffix = ["Question Papers", "Previous Papers", "Solved Papers", "Papers,2018 Question Paper", "2017 Question Paper", "2016 Question Paper", "last 10 years Papers", "Preparation", "Mock Tests", "Sample papers", "Test Series", "Question Papers with Answer Keys", "Question Papers with Solutions"];
suffix.forEach(function(thisSuffix, index){
var newKeyWord = $scope.exam.exam_page_name + ' ' + thisSuffix;
if(thisSuffix == "Preparation"){
newKeyWord = $scope.exam.top_coaching_name + ' ' + thisSuffix;
}
keywordString = keywordString + newKeyWord + ', ';
});
$rootScope.pageKeywords = keywordString;
}
if($scope.opStreams && $scope.stream){
var opStreamIds = $scope.opStreams.map(function(a) {return a._id.toString();});
var oIndex = opStreamIds.indexOf(streamId);
if(oIndex != -1){
$scope.otherPapers = $scope.opStreams[oIndex].exams;
}
}
}else{
//handle this
}
}
});
$scope.$watch("allOfficialPapers", function (newValue, oldValue, rootScope){
if(newValue && $scope.exam){
var examPapers = [];
$rootScope.allOfficialPapers.forEach(function(thisPaper, index){
if(thisPaper.exam && thisPaper.exam == $scope.exam._id){
examPapers.push(thisPaper);
}
});
$scope.examPapers = examPapers;
$scope.years = {
min: '',
max: '',
};
$scope.examSummary = {
papers: $scope.examPapers.length,
hours: 0,
questions: 0
};
$scope.examPapers.forEach(function(thisPaper, index){
$scope.examSummary.hours += Number(thisPaper.duration);
$scope.examSummary.questions += Number(thisPaper.nQuestions);
thisPaper.durationFormatted = '';
var hours = Math.floor( thisPaper.duration / 60);
var minutes = thisPaper.duration % 60;
if(hours > 0){
var hText = 'hours';
if(hours == 1){
hText = 'hour';
}
thisPaper.durationFormatted += hours + ' ' + hText;
}
if(minutes > 0){
thisPaper.durationFormatted += ' and ' + minutes + ' minutes';
}
var thisYear = thisPaper.year;
if($scope.years.min == ''){
$scope.years.min = thisYear;
}
if($scope.years.max == ''){
$scope.years.max = thisYear;
}
if($scope.years.min > thisYear){
$scope.years.min = thisYear;
}
if($scope.years.max < thisYear){
$scope.years.max = thisYear;
}
if($scope.years.min == '' || $scope.years.min == ''){
$scope.years = null;
}
var yearString = "years";
if($scope.years && $scope.years.min && $scope.years.max && $scope.years.min != $scope.years.max){
yearString = $scope.years.min + ' - ' + $scope.years.max;
}
$rootScope.pageDescription = "Attempt Official " + $scope.exam.exam_page_name + " Question Papers for " + yearString + " for Free in a Real, Exam-like Interface | " + $scope.exam.top_coaching_name + " Preparation";
if(thisPaper._actualdate){
thisPaper.fromnow = moment(thisPaper._actualdate).fromNow();
}
});
}
});
if($cookies.getObject('sessionuser')){
$scope.user = $cookies.getObject('sessionuser');
}else{
$scope.user = null;
}
$scope.userLogin = function(){
$rootScope.$emit("CallBlogLogin", {});
};
/*var unbind = $scope.$watch("allExams", function () {
unbind();
});*/
/*
var qpURL = $scope.exam.question_papers_urlslug;
if(qpURL){
qpURL = "https://www.exambazaar.com/qp/" + qpURL;
$scope.canonicalFlip = true;
$rootScope.canonicalUrl = qpURL;
console.log("Canonical URL is: " + $rootScope.canonicalUrl);
}
$scope.defaultCoverPhoto = 'https://www.exambazaar.com/images/generic_question_papers.png';
if($scope.exam.officialpaperscoverphoto && $scope.exam.officialpaperscoverphoto != ''){
$scope.defaultCoverPhoto = $scope.exam.officialpaperscoverphoto;
};
$scope.sideBarButtonClass = function(thisexam){
var classname = '';
if($scope.exam._id == thisexam._id){
classname = 'sideactive';
}
return classname;
};
$scope.officialPapers = officialPapers.data;
$scope.officialPapersStreamExam = officialPapersStreamExam.data;
var opStreamIds = $scope.officialPapersStreamExam.map(function(a) {return a._id.toString();});
var streamId = $scope.exam.stream._id.toString();
var sIndex = opStreamIds.indexOf(streamId);
$scope.thisStream = $scope.officialPapersStreamExam[sIndex];
$scope.years = {
min: '',
max: '',
};
$scope.examSummary = {
papers: $scope.officialPapers.length,
hours: 0,
questions: 0
};
$scope.officialPapers.forEach(function(thisPaper, index){
$scope.examSummary.hours += Number(thisPaper.duration);
$scope.examSummary.questions += Number(thisPaper.nQuestions);
thisPaper.durationFormatted = '';
var hours = Math.floor( thisPaper.duration / 60);
var minutes = thisPaper.duration % 60;
if(hours > 0){
var hText = 'hours';
if(hours == 1){
hText = 'hour';
}
thisPaper.durationFormatted += hours + ' ' + hText;
}
if(minutes > 0){
thisPaper.durationFormatted += ' and ' + minutes + ' minutes';
}
var thisYear = thisPaper.year;
if($scope.years.min == ''){
$scope.years.min = thisYear;
}
if($scope.years.max == ''){
$scope.years.max = thisYear;
}
if($scope.years.min > thisYear){
$scope.years.min = thisYear;
}
if($scope.years.max < thisYear){
$scope.years.max = thisYear;
}
if($scope.years.min == '' || $scope.years.min == ''){
$scope.years = null;
}
if(thisPaper._actualdate){
thisPaper.fromnow = moment(thisPaper._actualdate).fromNow();
}
});
$scope.examSummary.hours = Math.round($scope.examSummary.hours/60);
$rootScope.pageImage = $scope.defaultCoverPhoto;
//$rootScope.pageTitle = $scope.exam.displayname + " Question Papers | " + $scope.examSummary.papers + " Papers, " + $scope.examSummary.hours + " Hours, " + $scope.examSummary.questions + " Questions";
$rootScope.pageTitle = $scope.exam.exam_page_name + " Question Papers with Answer Keys: Attempt, Download and Analyse";
var yearString = "years";
if($scope.years.min && $scope.years.max && $scope.years.min != $scope.years.max){
yearString = $scope.years.min + ' - ' + $scope.years.max;
}
$rootScope.pageDescription = "Attempt Official " + $scope.exam.exam_page_name + " Question Papers for " + yearString + " for Free in a Real, Exam-like Interface | " + $scope.exam.top_coaching_name + " Preparation";
var keywordString = '';
//var suffix = [' Question Papers ', ' Question Papers PDF ', ' Question Papers & Answers PDF ' , ' Official Papers '];
var suffix = ["Question Papers", "Previous Papers", "Solved Papers", "Papers,2018 Question Paper", "2017 Question Paper", "2016 Question Paper", "last 10 years Papers", "Preparation", "Mock Tests", "Sample papers", "Test Series", "Question Papers with Answer Keys", "Question Papers with Solutions"];
suffix.forEach(function(thisSuffix, index){
var newKeyWord = $scope.exam.exam_page_name + ' ' + thisSuffix;
if(thisSuffix == "Preparation"){
newKeyWord = $scope.exam.top_coaching_name + ' ' + thisSuffix;
}
keywordString = keywordString + newKeyWord + ', ';
});
$rootScope.pageKeywords = keywordString;
if($cookies.getObject('sessionuser')){
$scope.user = $cookies.getObject('sessionuser');
}else{
//$scope.signupNeeded = true;
}
var viewForm = {
state: $state.current.name,
claim: false,
url: $location.url()
};
if($scope.user && $scope.user.userId){
viewForm.user = $scope.user.userId;
}
if($cookies.getObject('ip')){
var ip = $cookies.getObject('ip');
viewForm.ip = ip;
}
viewService.saveview(viewForm).success(function (data, status, headers) {
//console.log('View Marked');
})
.error(function (data, status, header, config) {
console.log('View not saved!');
});
*/
}]); |
(function (angular) {
'use strict';
/**
* @ngdoc directive
* @name esri.map.directive:esriInfoTemplate
* @restrict E
* @element
*
* @description
* This directive creates an
* {@link https://developers.arcgis.com/javascript/jsapi/infotemplate-amd.html InfoTemplate}
* and binds it to a layer to provide "popup" information functionality when clicking on the visible layer in the map.
* This directive **must** be placed within an esri-feature-layer directive or esri-dynamic-map-service-layer directive.
*
* ## Examples
* - {@link ../#/examples/dynamic-map-service-layers Multiple Dynamic Map Service Layers}
*
* <pre>
* <!-- The title is provided as an attribute parameter
* but the content is the entire inner HTML -->
*
* <esri-info-template title="Parks">
* <span>${PARK_NAME}</span>
* <span>This park had ${TOTAL_VISITS_2014} visitors in 2014</span>
* </esri-info-template>
* </pre>
*
* @param {String=} layer-id The layer id to which the InfoTemplate should be connected to.
* **Note:** This is only applicable when the parent directive is an esri-dynamic-map-service-layer.
* @param {String=} title The title of the template.
* @param {String | Node[]=} content **Note:** The content of the template is provided as inner HTML to this directive.
*
*/
angular.module('esri.map').directive('esriInfoTemplate', function () {
// this object will tell angular how our directive behaves
return {
// only allow esriInfoTemplate to be used as an element (<esri-feature-layer>)
restrict: 'E',
// require the esriInfoTemplate to have its own controller as well an esriMap controller
// you can access these controllers in the link function
require: ['?esriInfoTemplate', '?^esriDynamicMapServiceLayer', '?^esriFeatureLayer'],
// replace this element with our template.
// since we aren't declaring a template this essentially destroys the element
replace: true,
compile: function($element) {
// get info template content from element inner HTML
var content = $element.html();
// clear element inner HTML
$element.html('');
// since we are using compile we need to return our linker function
// the 'link' function handles how our directive responds to changes in $scope
return function (scope, element, attrs, controllers) {
// controllers is now an array of the controllers from the 'require' option
// var templateController = controllers[0];
var dynamicMapServiceLayerController = controllers[1];
var featureLayerController = controllers[2];
if (dynamicMapServiceLayerController) {
dynamicMapServiceLayerController.setInfoTemplate(attrs.layerId, {
title: attrs.title,
content: content
});
}
if (featureLayerController) {
featureLayerController.setInfoTemplate({
title: attrs.title,
content: content
});
}
};
}
};
});
})(angular);
|
/*
Created by Freshek on 07.10.2017
*/
class Box extends Movable {
constructor(x, y, hash, type) {
super(x, y);
this.hash = hash;
this.type = type;
}
toString() {
return JSON.parse(this);
}
isMaterial() {
var type = this.type.toLowerCase();
return (type == "mucosum" || type == "prismatium" || type == "scrapium" || type == "boltrum");
}
isCollectable() {
var type = this.type;
return (type == "BONUS_BOX" || type == "MINI_PUMPKIN" || type == "TURKISH_FLAG" || type == "GIFT_BOXES" || type == "ICY_BOX");
}
}
|
"use strict";
exports.__esModule = true;
exports["default"] = void 0;
var _react = require("react");
var _propTypes = _interopRequireDefault(require("prop-types"));
var _useSelect2 = _interopRequireDefault(require("./useSelect"));
var _types = require("./types");
var _Options = _interopRequireDefault(require("./Components/Options"));
var _useClassName = _interopRequireDefault(require("./useClassName"));
var _classes2 = _interopRequireDefault(require("./lib/classes"));
var _jsxRuntime = require("react/jsx-runtime");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var SelectSearch = /*#__PURE__*/(0, _react.forwardRef)(function (_ref, ref) {
var _classes;
var defaultValue = _ref.value,
disabled = _ref.disabled,
placeholder = _ref.placeholder,
multiple = _ref.multiple,
search = _ref.search,
autoFocus = _ref.autoFocus,
autoComplete = _ref.autoComplete,
defaultOptions = _ref.options,
id = _ref.id,
onChange = _ref.onChange,
onFocus = _ref.onFocus,
onBlur = _ref.onBlur,
printOptions = _ref.printOptions,
closeOnSelect = _ref.closeOnSelect,
className = _ref.className,
renderValue = _ref.renderValue,
renderOption = _ref.renderOption,
renderGroupHeader = _ref.renderGroupHeader,
getOptions = _ref.getOptions,
filterOptions = _ref.filterOptions,
debounce = _ref.debounce,
emptyMessage = _ref.emptyMessage;
var cls = (0, _useClassName["default"])(className);
var _useSelect = (0, _useSelect2["default"])({
options: defaultOptions,
value: defaultValue === null && (placeholder || multiple) ? '' : defaultValue,
multiple: multiple,
disabled: disabled,
search: search,
onChange: onChange,
onFocus: onFocus,
onBlur: onBlur,
closeOnSelect: closeOnSelect && (!multiple || ['on-focus', 'always'].includes(printOptions)),
getOptions: getOptions,
filterOptions: filterOptions,
debounce: debounce
}),
snapshot = _useSelect[0],
valueProps = _useSelect[1],
optionProps = _useSelect[2];
var wrapperClass = (0, _classes2["default"])((_classes = {}, _classes[cls('container')] = true, _classes[cls('is-disabled')] = disabled, _classes[cls('is-loading')] = snapshot.fetching, _classes[cls('has-focus')] = snapshot.focus, _classes));
var shouldRenderOptions;
switch (printOptions) {
case 'never':
shouldRenderOptions = false;
break;
case 'always':
shouldRenderOptions = true;
break;
case 'on-focus':
shouldRenderOptions = snapshot.focus;
break;
default:
shouldRenderOptions = !disabled && (snapshot.focus || multiple);
break;
}
var shouldRenderValue = !multiple || placeholder || search;
var props = _extends({}, valueProps, {
placeholder: placeholder,
autoFocus: autoFocus,
autoComplete: autoComplete,
value: snapshot.focus && search ? snapshot.search : snapshot.displayValue
});
return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
ref: ref,
className: wrapperClass,
id: id,
children: [shouldRenderValue && /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
className: cls('value'),
children: [renderValue && renderValue(props, snapshot, cls('input')), !renderValue && /*#__PURE__*/(0, _jsxRuntime.jsx)("input", _extends({}, props, {
className: cls('input')
}))]
}), shouldRenderOptions && /*#__PURE__*/(0, _jsxRuntime.jsx)(_Options["default"], {
options: snapshot.options,
optionProps: optionProps,
snapshot: snapshot,
cls: cls,
emptyMessage: emptyMessage,
renderOption: renderOption,
renderGroupHeader: renderGroupHeader
})]
});
});
SelectSearch.defaultProps = {
// Data
getOptions: null,
filterOptions: null,
value: null,
// Interaction
multiple: false,
search: false,
disabled: false,
printOptions: 'auto',
closeOnSelect: true,
debounce: 0,
// Attributes
placeholder: null,
id: null,
autoFocus: false,
autoComplete: 'on',
// Design
className: 'select-search',
// Renderers
renderOption: undefined,
renderGroupHeader: undefined,
renderValue: undefined,
emptyMessage: null,
// Events
onChange: function onChange() {},
onFocus: function onFocus() {},
onBlur: function onBlur() {}
};
SelectSearch.propTypes = process.env.NODE_ENV !== "production" ? {
// Data
options: _propTypes["default"].arrayOf(_types.optionType).isRequired,
getOptions: _propTypes["default"].func,
filterOptions: _propTypes["default"].func,
value: _types.valueType,
// Interaction
multiple: _propTypes["default"].bool,
search: _propTypes["default"].bool,
disabled: _propTypes["default"].bool,
printOptions: _propTypes["default"].oneOf(['auto', 'always', 'never', 'on-focus']),
closeOnSelect: _propTypes["default"].bool,
debounce: _propTypes["default"].number,
// Attributes
placeholder: _propTypes["default"].string,
id: _propTypes["default"].string,
autoComplete: _propTypes["default"].string,
autoFocus: _propTypes["default"].bool,
// Design
className: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].func]),
// Renderers
renderOption: _propTypes["default"].func,
renderGroupHeader: _propTypes["default"].func,
renderValue: _propTypes["default"].func,
emptyMessage: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].func]),
// Events
onChange: _propTypes["default"].func,
onFocus: _propTypes["default"].func,
onBlur: _propTypes["default"].func
} : {};
var _default = /*#__PURE__*/(0, _react.memo)(SelectSearch);
exports["default"] = _default; |
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, Text, TouchableOpacity } from 'react-native';
import Styles from './Styles';
import Checkbox from './Checkbox';
export default class CheckboxField extends Component {
static propTypes = {
// CheckboxField
label: PropTypes.string,
containerStyle: PropTypes.oneOfType([PropTypes.number, PropTypes.object, PropTypes.array]),
labelStyle: PropTypes.oneOfType([PropTypes.number, PropTypes.object, PropTypes.array]),
labelSide: PropTypes.oneOf(['left', 'right']),
// Checkbox
defaultColor: PropTypes.string,
selectedColor: PropTypes.string,
disabledColor: PropTypes.string,
selected: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
checkboxStyle: PropTypes.oneOfType([PropTypes.number, PropTypes.object, PropTypes.array]),
children: PropTypes.element.isRequired,
disabled: PropTypes.bool,
};
static defaultProps = {
containerStyle: {
flex: 1,
flexDirection: 'row',
padding: 20,
alignItems: 'center',
},
label: null,
labelStyle: {
flex: 1,
},
checkboxStyle: Styles.checkboxStyle,
defaultColor: Styles.defaultColor,
disabledColor: Styles.disabledColor,
selectedColor: Styles.selectedColor,
labelSide: 'left',
disabled: false,
selected: false,
};
render() {
const {
onSelect,
disabled,
containerStyle,
labelSide,
labelStyle,
label,
selected,
defaultColor,
selectedColor,
disabledColor,
checkboxStyle,
children,
} = this.props;
return (
<TouchableOpacity onPress={onSelect} disabled={disabled}>
<View style={containerStyle}>
{
labelSide === 'left' ? <Text style={labelStyle}>{label}</Text> : null
}
<Checkbox
selected={selected}
disabled={disabled}
onSelect={onSelect}
defaultColor={defaultColor}
selectedColor={selectedColor}
disabledColor={disabledColor}
checkboxStyle={checkboxStyle}
>
{children}
</Checkbox>
{
labelSide === 'right' ? <Text style={[labelStyle, { textAlign: 'right' }]}>{label}</Text> : null
}
</View>
</TouchableOpacity>
);
}
}
|
/**
* Internal dependencies.
*/
var Rule = require('../rule');
var MinLen = Rule.create({
error: 'The variable name is too short',
option: {
key: 'varmin',
type: 'number'
},
on: {
VariableDeclaration: 'check'
},
});
/**
* Perform the check.
*
* @param {Object} node
* @api public
*/
MinLen.prototype.check = function(node) {
var min = this.option();
node.declarations.forEach(function(node) {
if (node.id.name.length < min) {
this.badToken(node.id);
}
}, this);
};
/**
* Primary export.
*/
module.exports = MinLen;
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Contact from './Contact';
export default {
path: '/contact',
async action() {
const resp = await fetch('/graphql', {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
mdoe:'cors'
},
body: JSON.stringify({
query: '{news{name}}',
}),
credentials: 'include'
});
const { data } = await resp.json();
console.log(data)
if (!data || !data.news) throw new Error('Failed to load the news feed.');
return <Contact news={data.news} />;
},
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:8fcaa59f8f7d92d17f1967c30e716003bf2096aa6e162d68e3476991d70c5ad1
size 16572
|
version https://git-lfs.github.com/spec/v1
oid sha256:c2e49c9c3bf532498c29c64cbafec19f19fb11fddee2e36d8ea433291bbbc04f
size 5691
|
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const { webFrame, remote } = require("electron")
import Style from "./app/scss/app.scss"
// disable zoom in/out functionality in app
// webFrame.setVisualZoomLevelLimits(1, 1)
// webFrame.setLayoutZoomLevelLimits(0, 0)
console.log(remote.getGlobal("author"))
// detect OS type
$("html").addClass(process.platform)
// add Main window
require("./app/renderer-process/main-window/main-window")
|
/**
* @license Angular v4.2.5
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core')) :
typeof define === 'function' && define.amd ? define(['exports', '@angular/core'], factory) :
(factory((global.ng = global.ng || {}, global.ng.core = global.ng.core || {}, global.ng.core.testing = global.ng.core.testing || {}),global.ng.core));
}(this, (function (exports,_angular_core) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
/**
* @license Angular v4.2.5
* (c) 2010-2017 Google, Inc. https://angular.io/
* License: MIT
*/
/**
* @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
*/
var _global = (typeof window === 'undefined' ? global : window);
/**
* Wraps a test function in an asynchronous test zone. The test will automatically
* complete when all asynchronous calls within this zone are done. Can be used
* to wrap an {@link inject} call.
*
* Example:
*
* ```
* it('...', async(inject([AClass], (object) => {
* object.doSomething.then(() => {
* expect(...);
* })
* });
* ```
*
* @stable
*/
function async(fn) {
// If we're running using the Jasmine test framework, adapt to call the 'done'
// function when asynchronous activity is finished.
if (_global.jasmine) {
// Not using an arrow function to preserve context passed from call site
return function (done) {
if (!done) {
// if we run beforeEach in @angular/core/testing/testing_internal then we get no done
// fake it here and assume sync.
done = function () { };
done.fail = function (e) { throw e; };
}
runInTestZone(fn, this, done, function (err) {
if (typeof err === 'string') {
return done.fail(new Error(err));
}
else {
done.fail(err);
}
});
};
}
// Otherwise, return a promise which will resolve when asynchronous activity
// is finished. This will be correctly consumed by the Mocha framework with
// it('...', async(myFn)); or can be used in a custom framework.
// Not using an arrow function to preserve context passed from call site
return function () {
var _this = this;
return new Promise(function (finishCallback, failCallback) {
runInTestZone(fn, _this, finishCallback, failCallback);
});
};
}
function runInTestZone(fn, context, finishCallback, failCallback) {
var currentZone = Zone.current;
var AsyncTestZoneSpec = Zone['AsyncTestZoneSpec'];
if (AsyncTestZoneSpec === undefined) {
throw new Error('AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/dist/async-test.js');
}
var ProxyZoneSpec = Zone['ProxyZoneSpec'];
if (ProxyZoneSpec === undefined) {
throw new Error('ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
'Please make sure that your environment includes zone.js/dist/proxy.js');
}
var proxyZoneSpec = ProxyZoneSpec.get();
ProxyZoneSpec.assertPresent();
// We need to create the AsyncTestZoneSpec outside the ProxyZone.
// If we do it in ProxyZone then we will get to infinite recursion.
var proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
var previousDelegate = proxyZoneSpec.getDelegate();
proxyZone.parent.run(function () {
var testZoneSpec = new AsyncTestZoneSpec(function () {
// Need to restore the original zone.
currentZone.run(function () {
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
// Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
proxyZoneSpec.setDelegate(previousDelegate);
}
finishCallback();
});
}, function (error) {
// Need to restore the original zone.
currentZone.run(function () {
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
// Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
proxyZoneSpec.setDelegate(previousDelegate);
}
failCallback(error);
});
}, 'test');
proxyZoneSpec.setDelegate(testZoneSpec);
});
return Zone.current.runGuarded(fn, context);
}
/**
* @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
*/
/**
* Fixture for debugging and testing a component.
*
* @stable
*/
var ComponentFixture = (function () {
function ComponentFixture(componentRef, ngZone, _autoDetect) {
var _this = this;
this.componentRef = componentRef;
this.ngZone = ngZone;
this._autoDetect = _autoDetect;
this._isStable = true;
this._isDestroyed = false;
this._resolve = null;
this._promise = null;
this._onUnstableSubscription = null;
this._onStableSubscription = null;
this._onMicrotaskEmptySubscription = null;
this._onErrorSubscription = null;
this.changeDetectorRef = componentRef.changeDetectorRef;
this.elementRef = componentRef.location;
this.debugElement = _angular_core.getDebugNode(this.elementRef.nativeElement);
this.componentInstance = componentRef.instance;
this.nativeElement = this.elementRef.nativeElement;
this.componentRef = componentRef;
this.ngZone = ngZone;
if (ngZone) {
this._onUnstableSubscription =
ngZone.onUnstable.subscribe({ next: function () { _this._isStable = false; } });
this._onMicrotaskEmptySubscription = ngZone.onMicrotaskEmpty.subscribe({
next: function () {
if (_this._autoDetect) {
// Do a change detection run with checkNoChanges set to true to check
// there are no changes on the second run.
_this.detectChanges(true);
}
}
});
this._onStableSubscription = ngZone.onStable.subscribe({
next: function () {
_this._isStable = true;
// Check whether there is a pending whenStable() completer to resolve.
if (_this._promise !== null) {
// If so check whether there are no pending macrotasks before resolving.
// Do this check in the next tick so that ngZone gets a chance to update the state of
// pending macrotasks.
scheduleMicroTask(function () {
if (!ngZone.hasPendingMacrotasks) {
if (_this._promise !== null) {
_this._resolve(true);
_this._resolve = null;
_this._promise = null;
}
}
});
}
}
});
this._onErrorSubscription =
ngZone.onError.subscribe({ next: function (error) { throw error; } });
}
}
ComponentFixture.prototype._tick = function (checkNoChanges) {
this.changeDetectorRef.detectChanges();
if (checkNoChanges) {
this.checkNoChanges();
}
};
/**
* Trigger a change detection cycle for the component.
*/
ComponentFixture.prototype.detectChanges = function (checkNoChanges) {
var _this = this;
if (checkNoChanges === void 0) { checkNoChanges = true; }
if (this.ngZone != null) {
// Run the change detection inside the NgZone so that any async tasks as part of the change
// detection are captured by the zone and can be waited for in isStable.
this.ngZone.run(function () { _this._tick(checkNoChanges); });
}
else {
// Running without zone. Just do the change detection.
this._tick(checkNoChanges);
}
};
/**
* Do a change detection run to make sure there were no changes.
*/
ComponentFixture.prototype.checkNoChanges = function () { this.changeDetectorRef.checkNoChanges(); };
/**
* Set whether the fixture should autodetect changes.
*
* Also runs detectChanges once so that any existing change is detected.
*/
ComponentFixture.prototype.autoDetectChanges = function (autoDetect) {
if (autoDetect === void 0) { autoDetect = true; }
if (this.ngZone == null) {
throw new Error('Cannot call autoDetectChanges when ComponentFixtureNoNgZone is set');
}
this._autoDetect = autoDetect;
this.detectChanges();
};
/**
* Return whether the fixture is currently stable or has async tasks that have not been completed
* yet.
*/
ComponentFixture.prototype.isStable = function () { return this._isStable && !this.ngZone.hasPendingMacrotasks; };
/**
* Get a promise that resolves when the fixture is stable.
*
* This can be used to resume testing after events have triggered asynchronous activity or
* asynchronous change detection.
*/
ComponentFixture.prototype.whenStable = function () {
var _this = this;
if (this.isStable()) {
return Promise.resolve(false);
}
else if (this._promise !== null) {
return this._promise;
}
else {
this._promise = new Promise(function (res) { _this._resolve = res; });
return this._promise;
}
};
ComponentFixture.prototype._getRenderer = function () {
if (this._renderer === undefined) {
this._renderer = this.componentRef.injector.get(_angular_core.RendererFactory2, null);
}
return this._renderer;
};
/**
* Get a promise that resolves when the ui state is stable following animations.
*/
ComponentFixture.prototype.whenRenderingDone = function () {
var renderer = this._getRenderer();
if (renderer && renderer.whenRenderingDone) {
return renderer.whenRenderingDone();
}
return this.whenStable();
};
/**
* Trigger component destruction.
*/
ComponentFixture.prototype.destroy = function () {
if (!this._isDestroyed) {
this.componentRef.destroy();
if (this._onUnstableSubscription != null) {
this._onUnstableSubscription.unsubscribe();
this._onUnstableSubscription = null;
}
if (this._onStableSubscription != null) {
this._onStableSubscription.unsubscribe();
this._onStableSubscription = null;
}
if (this._onMicrotaskEmptySubscription != null) {
this._onMicrotaskEmptySubscription.unsubscribe();
this._onMicrotaskEmptySubscription = null;
}
if (this._onErrorSubscription != null) {
this._onErrorSubscription.unsubscribe();
this._onErrorSubscription = null;
}
this._isDestroyed = true;
}
};
return ComponentFixture;
}());
function scheduleMicroTask(fn) {
Zone.current.scheduleMicroTask('scheduleMicrotask', fn);
}
/**
* @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
*/
var FakeAsyncTestZoneSpec = Zone['FakeAsyncTestZoneSpec'];
var ProxyZoneSpec = Zone['ProxyZoneSpec'];
var _fakeAsyncTestZoneSpec = null;
/**
* Clears out the shared fake async zone for a test.
* To be called in a global `beforeEach`.
*
* @experimental
*/
function resetFakeAsyncZone() {
_fakeAsyncTestZoneSpec = null;
ProxyZoneSpec.assertPresent().resetDelegate();
}
var _inFakeAsyncCall = false;
/**
* Wraps a function to be executed in the fakeAsync zone:
* - microtasks are manually executed by calling `flushMicrotasks()`,
* - timers are synchronous, `tick()` simulates the asynchronous passage of time.
*
* If there are any pending timers at the end of the function, an exception will be thrown.
*
* Can be used to wrap inject() calls.
*
* ## Example
*
* {@example testing/ts/fake_async.ts region='basic'}
*
* @param fn
* @returns {Function} The function wrapped to be executed in the fakeAsync zone
*
* @experimental
*/
function fakeAsync(fn) {
// Not using an arrow function to preserve context passed from call site
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var proxyZoneSpec = ProxyZoneSpec.assertPresent();
if (_inFakeAsyncCall) {
throw new Error('fakeAsync() calls can not be nested');
}
_inFakeAsyncCall = true;
try {
if (!_fakeAsyncTestZoneSpec) {
if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
throw new Error('fakeAsync() calls can not be nested');
}
_fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
}
var res = void 0;
var lastProxyZoneSpec = proxyZoneSpec.getDelegate();
proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
try {
res = fn.apply(this, args);
flushMicrotasks();
}
finally {
proxyZoneSpec.setDelegate(lastProxyZoneSpec);
}
if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
throw new Error(_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length + " " +
"periodic timer(s) still in the queue.");
}
if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
throw new Error(_fakeAsyncTestZoneSpec.pendingTimers.length + " timer(s) still in the queue.");
}
return res;
}
finally {
_inFakeAsyncCall = false;
resetFakeAsyncZone();
}
};
}
function _getFakeAsyncZoneSpec() {
if (_fakeAsyncTestZoneSpec == null) {
throw new Error('The code should be running in the fakeAsync zone to call this function');
}
return _fakeAsyncTestZoneSpec;
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
*
* The microtasks queue is drained at the very start of this function and after any timer callback
* has been executed.
*
* ## Example
*
* {@example testing/ts/fake_async.ts region='basic'}
*
* @experimental
*/
function tick(millis) {
if (millis === void 0) { millis = 0; }
_getFakeAsyncZoneSpec().tick(millis);
}
/**
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
* draining the macrotask queue until it is empty. The returned value is the milliseconds
* of time that would have been elapsed.
*
* @param maxTurns
* @returns {number} The simulated time elapsed, in millis.
*
* @experimental
*/
function flush(maxTurns) {
return _getFakeAsyncZoneSpec().flush(maxTurns);
}
/**
* Discard all remaining periodic tasks.
*
* @experimental
*/
function discardPeriodicTasks() {
var zoneSpec = _getFakeAsyncZoneSpec();
var pendingTimers = zoneSpec.pendingPeriodicTimers;
zoneSpec.pendingPeriodicTimers.length = 0;
}
/**
* Flush any pending microtasks.
*
* @experimental
*/
function flushMicrotasks() {
_getFakeAsyncZoneSpec().flushMicrotasks();
}
/**
* @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
*/
/**
* Injectable completer that allows signaling completion of an asynchronous test. Used internally.
*/
/**
* @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
*/ var AsyncTestCompleter = (function () {
function AsyncTestCompleter() {
var _this = this;
this._promise = new Promise(function (res, rej) {
_this._resolve = res;
_this._reject = rej;
});
}
AsyncTestCompleter.prototype.done = function (value) { this._resolve(value); };
AsyncTestCompleter.prototype.fail = function (error, stackTrace) { this._reject(error); };
Object.defineProperty(AsyncTestCompleter.prototype, "promise", {
get: function () { return this._promise; },
enumerable: true,
configurable: true
});
return AsyncTestCompleter;
}());
/**
* @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
*/
function unimplemented() {
throw Error('unimplemented');
}
/**
* Special interface to the compiler only used by testing
*
* @experimental
*/
var TestingCompiler = (function (_super) {
__extends(TestingCompiler, _super);
function TestingCompiler() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(TestingCompiler.prototype, "injector", {
get: function () { throw unimplemented(); },
enumerable: true,
configurable: true
});
TestingCompiler.prototype.overrideModule = function (module, overrides) {
throw unimplemented();
};
TestingCompiler.prototype.overrideDirective = function (directive, overrides) {
throw unimplemented();
};
TestingCompiler.prototype.overrideComponent = function (component, overrides) {
throw unimplemented();
};
TestingCompiler.prototype.overridePipe = function (directive, overrides) {
throw unimplemented();
};
/**
* Allows to pass the compile summary from AOT compilation to the JIT compiler,
* so that it can use the code generated by AOT.
*/
TestingCompiler.prototype.loadAotSummaries = function (summaries) { throw unimplemented(); };
/**
* Gets the component factory for the given component.
* This assumes that the component has been compiled before calling this call using
* `compileModuleAndAllComponents*`.
*/
TestingCompiler.prototype.getComponentFactory = function (component) { throw unimplemented(); };
return TestingCompiler;
}(_angular_core.Compiler));
/**
* A factory for creating a Compiler
*
* @experimental
*/
var TestingCompilerFactory = (function () {
function TestingCompilerFactory() {
}
return TestingCompilerFactory;
}());
/**
* @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
*/
var UNDEFINED = new Object();
/**
* An abstract class for inserting the root test component element in a platform independent way.
*
* @experimental
*/
var TestComponentRenderer = (function () {
function TestComponentRenderer() {
}
TestComponentRenderer.prototype.insertRootElement = function (rootElementId) { };
return TestComponentRenderer;
}());
var _nextRootElementId = 0;
/**
* @experimental
*/
var ComponentFixtureAutoDetect = new _angular_core.InjectionToken('ComponentFixtureAutoDetect');
/**
* @experimental
*/
var ComponentFixtureNoNgZone = new _angular_core.InjectionToken('ComponentFixtureNoNgZone');
/**
* @whatItDoes Configures and initializes environment for unit testing and provides methods for
* creating components and services in unit tests.
* @description
*
* TestBed is the primary api for writing unit tests for Angular applications and libraries.
*
* @stable
*/
var TestBed = (function () {
function TestBed() {
this._instantiated = false;
this._compiler = null;
this._moduleRef = null;
this._moduleFactory = null;
this._compilerOptions = [];
this._moduleOverrides = [];
this._componentOverrides = [];
this._directiveOverrides = [];
this._pipeOverrides = [];
this._providers = [];
this._declarations = [];
this._imports = [];
this._schemas = [];
this._activeFixtures = [];
this._aotSummaries = function () { return []; };
this.platform = null;
this.ngModule = null;
}
/**
* Initialize the environment for testing with a compiler factory, a PlatformRef, and an
* angular module. These are common to every test in the suite.
*
* This may only be called once, to set up the common providers for the current test
* suite on the current platform. If you absolutely need to change the providers,
* first use `resetTestEnvironment`.
*
* Test modules and platforms for individual platforms are available from
* '@angular/<platform_name>/testing'.
*
* @experimental
*/
TestBed.initTestEnvironment = function (ngModule, platform, aotSummaries) {
var testBed = getTestBed();
testBed.initTestEnvironment(ngModule, platform, aotSummaries);
return testBed;
};
/**
* Reset the providers for the test injector.
*
* @experimental
*/
TestBed.resetTestEnvironment = function () { getTestBed().resetTestEnvironment(); };
TestBed.resetTestingModule = function () {
getTestBed().resetTestingModule();
return TestBed;
};
/**
* Allows overriding default compiler providers and settings
* which are defined in test_injector.js
*/
TestBed.configureCompiler = function (config) {
getTestBed().configureCompiler(config);
return TestBed;
};
/**
* Allows overriding default providers, directives, pipes, modules of the test injector,
* which are defined in test_injector.js
*/
TestBed.configureTestingModule = function (moduleDef) {
getTestBed().configureTestingModule(moduleDef);
return TestBed;
};
/**
* Compile components with a `templateUrl` for the test's NgModule.
* It is necessary to call this function
* as fetching urls is asynchronous.
*/
TestBed.compileComponents = function () { return getTestBed().compileComponents(); };
TestBed.overrideModule = function (ngModule, override) {
getTestBed().overrideModule(ngModule, override);
return TestBed;
};
TestBed.overrideComponent = function (component, override) {
getTestBed().overrideComponent(component, override);
return TestBed;
};
TestBed.overrideDirective = function (directive, override) {
getTestBed().overrideDirective(directive, override);
return TestBed;
};
TestBed.overridePipe = function (pipe, override) {
getTestBed().overridePipe(pipe, override);
return TestBed;
};
TestBed.overrideTemplate = function (component, template) {
getTestBed().overrideComponent(component, { set: { template: template, templateUrl: null } });
return TestBed;
};
TestBed.overrideProvider = function (token, provider) {
getTestBed().overrideProvider(token, provider);
return TestBed;
};
TestBed.get = function (token, notFoundValue) {
if (notFoundValue === void 0) { notFoundValue = _angular_core.Injector.THROW_IF_NOT_FOUND; }
return getTestBed().get(token, notFoundValue);
};
TestBed.createComponent = function (component) {
return getTestBed().createComponent(component);
};
/**
* Initialize the environment for testing with a compiler factory, a PlatformRef, and an
* angular module. These are common to every test in the suite.
*
* This may only be called once, to set up the common providers for the current test
* suite on the current platform. If you absolutely need to change the providers,
* first use `resetTestEnvironment`.
*
* Test modules and platforms for individual platforms are available from
* '@angular/<platform_name>/testing'.
*
* @experimental
*/
TestBed.prototype.initTestEnvironment = function (ngModule, platform, aotSummaries) {
if (this.platform || this.ngModule) {
throw new Error('Cannot set base providers because it has already been called');
}
this.platform = platform;
this.ngModule = ngModule;
if (aotSummaries) {
this._aotSummaries = aotSummaries;
}
};
/**
* Reset the providers for the test injector.
*
* @experimental
*/
TestBed.prototype.resetTestEnvironment = function () {
this.resetTestingModule();
this.platform = null;
this.ngModule = null;
this._aotSummaries = function () { return []; };
};
TestBed.prototype.resetTestingModule = function () {
_angular_core.ɵclearProviderOverrides();
this._compiler = null;
this._moduleOverrides = [];
this._componentOverrides = [];
this._directiveOverrides = [];
this._pipeOverrides = [];
this._moduleRef = null;
this._moduleFactory = null;
this._compilerOptions = [];
this._providers = [];
this._declarations = [];
this._imports = [];
this._schemas = [];
this._instantiated = false;
this._activeFixtures.forEach(function (fixture) {
try {
fixture.destroy();
}
catch (e) {
console.error('Error during cleanup of component', fixture.componentInstance);
}
});
this._activeFixtures = [];
};
TestBed.prototype.configureCompiler = function (config) {
this._assertNotInstantiated('TestBed.configureCompiler', 'configure the compiler');
this._compilerOptions.push(config);
};
TestBed.prototype.configureTestingModule = function (moduleDef) {
this._assertNotInstantiated('TestBed.configureTestingModule', 'configure the test module');
if (moduleDef.providers) {
(_a = this._providers).push.apply(_a, moduleDef.providers);
}
if (moduleDef.declarations) {
(_b = this._declarations).push.apply(_b, moduleDef.declarations);
}
if (moduleDef.imports) {
(_c = this._imports).push.apply(_c, moduleDef.imports);
}
if (moduleDef.schemas) {
(_d = this._schemas).push.apply(_d, moduleDef.schemas);
}
var _a, _b, _c, _d;
};
TestBed.prototype.compileComponents = function () {
var _this = this;
if (this._moduleFactory || this._instantiated) {
return Promise.resolve(null);
}
var moduleType = this._createCompilerAndModule();
return this._compiler.compileModuleAndAllComponentsAsync(moduleType)
.then(function (moduleAndComponentFactories) {
_this._moduleFactory = moduleAndComponentFactories.ngModuleFactory;
});
};
TestBed.prototype._initIfNeeded = function () {
if (this._instantiated) {
return;
}
if (!this._moduleFactory) {
try {
var moduleType = this._createCompilerAndModule();
this._moduleFactory =
this._compiler.compileModuleAndAllComponentsSync(moduleType).ngModuleFactory;
}
catch (e) {
if (getComponentType(e)) {
throw new Error("This test module uses the component " + _angular_core.ɵstringify(getComponentType(e)) + " which is using a \"templateUrl\" or \"styleUrls\", but they were never compiled. " +
"Please call \"TestBed.compileComponents\" before your test.");
}
else {
throw e;
}
}
}
var ngZone = new _angular_core.NgZone({ enableLongStackTrace: true });
var ngZoneInjector = _angular_core.ReflectiveInjector.resolveAndCreate([{ provide: _angular_core.NgZone, useValue: ngZone }], this.platform.injector);
this._moduleRef = this._moduleFactory.create(ngZoneInjector);
// ApplicationInitStatus.runInitializers() is marked @internal to core. So casting to any
// before accessing it.
this._moduleRef.injector.get(_angular_core.ApplicationInitStatus).runInitializers();
this._instantiated = true;
};
TestBed.prototype._createCompilerAndModule = function () {
var _this = this;
var providers = this._providers.concat([{ provide: TestBed, useValue: this }]);
var declarations = this._declarations;
var imports = [this.ngModule, this._imports];
var schemas = this._schemas;
var DynamicTestModule = (function () {
function DynamicTestModule() {
}
return DynamicTestModule;
}());
DynamicTestModule.decorators = [
{ type: _angular_core.NgModule, args: [{ providers: providers, declarations: declarations, imports: imports, schemas: schemas },] },
];
/** @nocollapse */
DynamicTestModule.ctorParameters = function () { return []; };
var compilerFactory = this.platform.injector.get(TestingCompilerFactory);
this._compiler =
compilerFactory.createTestingCompiler(this._compilerOptions.concat([{ useDebug: true }]));
this._compiler.loadAotSummaries(this._aotSummaries);
this._moduleOverrides.forEach(function (entry) { return _this._compiler.overrideModule(entry[0], entry[1]); });
this._componentOverrides.forEach(function (entry) { return _this._compiler.overrideComponent(entry[0], entry[1]); });
this._directiveOverrides.forEach(function (entry) { return _this._compiler.overrideDirective(entry[0], entry[1]); });
this._pipeOverrides.forEach(function (entry) { return _this._compiler.overridePipe(entry[0], entry[1]); });
return DynamicTestModule;
};
TestBed.prototype._assertNotInstantiated = function (methodName, methodDescription) {
if (this._instantiated) {
throw new Error("Cannot " + methodDescription + " when the test module has already been instantiated. " +
("Make sure you are not using `inject` before `" + methodName + "`."));
}
};
TestBed.prototype.get = function (token, notFoundValue) {
if (notFoundValue === void 0) { notFoundValue = _angular_core.Injector.THROW_IF_NOT_FOUND; }
this._initIfNeeded();
if (token === TestBed) {
return this;
}
// Tests can inject things from the ng module and from the compiler,
// but the ng module can't inject things from the compiler and vice versa.
var result = this._moduleRef.injector.get(token, UNDEFINED);
return result === UNDEFINED ? this._compiler.injector.get(token, notFoundValue) : result;
};
TestBed.prototype.execute = function (tokens, fn, context) {
var _this = this;
this._initIfNeeded();
var params = tokens.map(function (t) { return _this.get(t); });
return fn.apply(context, params);
};
TestBed.prototype.overrideModule = function (ngModule, override) {
this._assertNotInstantiated('overrideModule', 'override module metadata');
this._moduleOverrides.push([ngModule, override]);
};
TestBed.prototype.overrideComponent = function (component, override) {
this._assertNotInstantiated('overrideComponent', 'override component metadata');
this._componentOverrides.push([component, override]);
};
TestBed.prototype.overrideDirective = function (directive, override) {
this._assertNotInstantiated('overrideDirective', 'override directive metadata');
this._directiveOverrides.push([directive, override]);
};
TestBed.prototype.overridePipe = function (pipe, override) {
this._assertNotInstantiated('overridePipe', 'override pipe metadata');
this._pipeOverrides.push([pipe, override]);
};
TestBed.prototype.overrideProvider = function (token, provider) {
var flags = 0;
var value;
if (provider.useFactory) {
flags |= 1024 /* TypeFactoryProvider */;
value = provider.useFactory;
}
else {
flags |= 256 /* TypeValueProvider */;
value = provider.useValue;
}
var deps = (provider.deps || []).map(function (dep) {
var depFlags = 0;
var depToken;
if (Array.isArray(dep)) {
dep.forEach(function (entry) {
if (entry instanceof _angular_core.Optional) {
depFlags |= 2 /* Optional */;
}
else if (entry instanceof _angular_core.SkipSelf) {
depFlags |= 1 /* SkipSelf */;
}
else {
depToken = entry;
}
});
}
else {
depToken = dep;
}
return [depFlags, depToken];
});
_angular_core.ɵoverrideProvider({ token: token, flags: flags, deps: deps, value: value });
};
TestBed.prototype.createComponent = function (component) {
var _this = this;
this._initIfNeeded();
var componentFactory = this._compiler.getComponentFactory(component);
if (!componentFactory) {
throw new Error("Cannot create the component " + _angular_core.ɵstringify(component) + " as it was not imported into the testing module!");
}
var noNgZone = this.get(ComponentFixtureNoNgZone, false);
var autoDetect = this.get(ComponentFixtureAutoDetect, false);
var ngZone = noNgZone ? null : this.get(_angular_core.NgZone, null);
var testComponentRenderer = this.get(TestComponentRenderer);
var rootElId = "root" + _nextRootElementId++;
testComponentRenderer.insertRootElement(rootElId);
var initComponent = function () {
var componentRef = componentFactory.create(_angular_core.Injector.NULL, [], "#" + rootElId, _this._moduleRef);
return new ComponentFixture(componentRef, ngZone, autoDetect);
};
var fixture = !ngZone ? initComponent() : ngZone.run(initComponent);
this._activeFixtures.push(fixture);
return fixture;
};
return TestBed;
}());
var _testBed = null;
/**
* @experimental
*/
function getTestBed() {
return _testBed = _testBed || new TestBed();
}
/**
* Allows injecting dependencies in `beforeEach()` and `it()`.
*
* Example:
*
* ```
* beforeEach(inject([Dependency, AClass], (dep, object) => {
* // some code that uses `dep` and `object`
* // ...
* }));
*
* it('...', inject([AClass], (object) => {
* object.doSomething();
* expect(...);
* })
* ```
*
* Notes:
* - inject is currently a function because of some Traceur limitation the syntax should
* eventually
* becomes `it('...', @Inject (object: AClass, async: AsyncTestCompleter) => { ... });`
*
* @stable
*/
function inject(tokens, fn) {
var testBed = getTestBed();
if (tokens.indexOf(AsyncTestCompleter) >= 0) {
// Not using an arrow function to preserve context passed from call site
return function () {
var _this = this;
// Return an async test method that returns a Promise if AsyncTestCompleter is one of
// the injected tokens.
return testBed.compileComponents().then(function () {
var completer = testBed.get(AsyncTestCompleter);
testBed.execute(tokens, fn, _this);
return completer.promise;
});
};
}
else {
// Not using an arrow function to preserve context passed from call site
return function () { return testBed.execute(tokens, fn, this); };
}
}
/**
* @experimental
*/
var InjectSetupWrapper = (function () {
function InjectSetupWrapper(_moduleDef) {
this._moduleDef = _moduleDef;
}
InjectSetupWrapper.prototype._addModule = function () {
var moduleDef = this._moduleDef();
if (moduleDef) {
getTestBed().configureTestingModule(moduleDef);
}
};
InjectSetupWrapper.prototype.inject = function (tokens, fn) {
var self = this;
// Not using an arrow function to preserve context passed from call site
return function () {
self._addModule();
return inject(tokens, fn).call(this);
};
};
return InjectSetupWrapper;
}());
function withModule(moduleDef, fn) {
if (fn) {
// Not using an arrow function to preserve context passed from call site
return function () {
var testBed = getTestBed();
if (moduleDef) {
testBed.configureTestingModule(moduleDef);
}
return fn.apply(this);
};
}
return new InjectSetupWrapper(function () { return moduleDef; });
}
function getComponentType(error) {
return error[_angular_core.ɵERROR_COMPONENT_TYPE];
}
/**
* @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
*/
/**
* Public Test Library for unit testing Angular applications. Assumes that you are running
* with Jasmine, Mocha, or a similar framework which exports a beforeEach function and
* allows tests to be asynchronous by either returning a promise or using a 'done' parameter.
*/
var _global$1 = (typeof window === 'undefined' ? global : window);
// Reset the test providers and the fake async zone before each test.
if (_global$1.beforeEach) {
_global$1.beforeEach(function () {
TestBed.resetTestingModule();
resetFakeAsyncZone();
});
}
// TODO(juliemr): remove this, only used because we need to export something to have compilation
// work.
var __core_private_testing_placeholder__ = '';
exports.async = async;
exports.ComponentFixture = ComponentFixture;
exports.resetFakeAsyncZone = resetFakeAsyncZone;
exports.fakeAsync = fakeAsync;
exports.tick = tick;
exports.flush = flush;
exports.discardPeriodicTasks = discardPeriodicTasks;
exports.flushMicrotasks = flushMicrotasks;
exports.TestComponentRenderer = TestComponentRenderer;
exports.ComponentFixtureAutoDetect = ComponentFixtureAutoDetect;
exports.ComponentFixtureNoNgZone = ComponentFixtureNoNgZone;
exports.TestBed = TestBed;
exports.getTestBed = getTestBed;
exports.inject = inject;
exports.InjectSetupWrapper = InjectSetupWrapper;
exports.withModule = withModule;
exports.__core_private_testing_placeholder__ = __core_private_testing_placeholder__;
exports.ɵTestingCompiler = TestingCompiler;
exports.ɵTestingCompilerFactory = TestingCompilerFactory;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=core-testing.umd.js.map
|
define(function (require, exports, module) {
"use strict";
// External dependencies.
var Backbone = require('backbone');
var Marionette = require('marionette');
window.urls = require('urls');
window.util = require('util');
// The root path to run the application through.
exports.root = '/';
var app = new Backbone.Marionette.Application();
app.addInitializer(function (options) {
var MainView = require('modules/main/MainView');
app.mainView = new MainView();
app.mainRegion.show(app.mainView);
Backbone.history.start({ pushState: true, root: "/" });
});
app.addRegions({
mainRegion: '#mainWrapper'
});
return app;
});
|
module.exports = function(accounts) {
accounts = accounts != null ? accounts : {};
return function(req, res, next) {
var auth, buf, creds, found, i, password, tmp, userAuth, username;
auth = req.headers['authorization'];
if (!auth) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
return res.end();
} else {
tmp = auth.split(' ');
buf = new Buffer(tmp[1], 'base64');
userAuth = buf.toString();
creds = userAuth.split(':');
username = creds[0];
password = creds[1];
found = false;
for (i in accounts) {
if (username === i && password === accounts[i]) {
found = true;
}
}
if (found) {
res.statusCode = 200;
return next();
} else {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
return res.end();
}
}
};
};
|
/*!
* bespoke-hash v0.1.1
*
* Copyright 2013, Mark Dalgleish
* This content is released under the MIT license
* http://mit-license.org/markdalgleish
*/
(function(bespoke) {
bespoke.plugins.hash = function(deck) {
var activeIndex,
parseHash = function() {
var hash = window.location.hash.slice(1),
slideNumberOrName = parseInt(hash, 10);
if (hash) {
if (slideNumberOrName) {
activateSlide(slideNumberOrName - 1);
} else {
deck.slides.forEach(function(slide, i) {
slide.getAttribute('data-bespoke-hash') === hash && activateSlide(i);
});
}
}
},
activateSlide = function(index) {
if (index !== activeIndex) {
deck.slide(index);
}
};
setTimeout(function() {
parseHash();
deck.on('activate', function(e) {
var slideName = e.slide.getAttribute('data-bespoke-hash');
window.location.hash = slideName || e.index + 1;
activeIndex = e.index;
});
window.addEventListener('hashchange', parseHash);
}, 0);
};
}(bespoke)); |
version https://git-lfs.github.com/spec/v1
oid sha256:b7ace73d0372ab733e44a6e6e929f5d7f8f76aa936a63141ce71b444d15db719
size 59294
|
var common = require('../common.js');
var utils = common.load('utils');
module.exports = function handle_presenterRequest() {
var self = this;
var piccolo = this.piccolo;
var res = this.response;
var route = this.cache.route;
this.log('info', 'Require presenter module: ' + this.cache.filepath);
// Get change table resource
piccolo.require(this.cache.filepath, function (error, Resource) {
if (error) return self.emit('error', utils.httpError(500, error));
self.log('info', 'Got ' + self.cache.filepath + ' presenter, now checking presenter.' + route.method);
if (!Resource.prototype.hasOwnProperty(route.method)) {
var err = new Error('change table method ' + route.method + ' do not exist in ' + route.path);
return self.emit('error', utils.httpError(404, err));
}
self.log('info', 'Opening stream pipe to client from presenter (' + self.cache.filepath + ', ' + route.method + ') output');
if (res.statusCode < 400) res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
var stream = self.open();
if (stream) {
// Execute change table method with given arguments
var changeTable = new Resource(self.url, stream);
changeTable[route.method].apply(changeTable, route.args);
}
});
};
|
import * as SampleActions from './actions'
import {SampleReducer} from './reducer'
export {SampleActions, SampleReducer} |
'use strict';
angular.module('LDT.ui').directive('catchInput',function() {
return {
link: function(scope, element, iAttrs, ctrl) {
function stopit(e) {
e.stopPropagation();
}
//Don't allow clicks to change mode
element.click(stopit);
//Don't allow renaming keypresses to change mode
element.keypress(stopit);
}
};
});
|
/**
* Japanese translation
* @author Tomoaki Yoshida <info@yoshida-studio.jp>
* @version 2010-09-18
*/
(function($) {
elRTE.prototype.i18Messages.jp = {
'_translator' : 'Tomoaki Yoshida <info@yoshida-studio.jp>',
'_translation' : 'Japanese translation',
'Editor' : 'エディター',
'Source' : 'ソース',
// Panel Name
'Copy/Pase' : 'コピー/ペースト',
'Undo/Redo' : '元に戻す/やり直し',
'Text styles' : 'テキストスタイル',
'Colors' : '色',
'Alignment' : '行揃え',
'Indent/Outdent' : 'インデント/アウトデント',
'Text format' : 'テキストフォーマット',
'Lists' : 'リスト',
'Misc elements' : 'その他',
'Links' : 'リンク',
'Images' : '画像',
'Media' : 'メディア',
'Tables' : 'テーブル',
'File manager (elFinder)' : 'ファイルマネージャ(elFinder)',
// button names
'About this software' : 'このソフトウェアについて',
'Save' : '保存',
'Copy' : 'コピー',
'Cut' : '切り取り',
'Paste' : '貼り付け',
'Paste only text' : 'テキストのみ貼り付け',
'Paste formatted text' : 'フォーマットされたテキストの貼り付け',
'Clean format' : 'フォーマット消去',
'Undo last action' : '元に戻す',
'Redo previous action' : 'やり直し',
'Bold' : '太字',
'Italic' : '斜体',
'Underline' : '下線',
'Strikethrough' : '打ち消し線',
'Superscript' : '上付き文字',
'Subscript' : '添え字',
'Align left' : '左揃え',
'Ailgn right' : '右揃え',
'Align center' : '中央揃え',
'Align full' : '両端揃え',
'Font color' : 'テキスト色',
'Background color' : '背景色',
'Indent' : 'インデント',
'Outdent' : 'アウトデント',
'Format' : 'フォーマット',
'Font size' : 'サイズ',
'Font' : 'フォント',
'Ordered list' : '段落番号',
'Unordered list' : '箇条書き',
'Horizontal rule' : '横罫線',
'Blockquote' : 'ブロック引用',
'Block element (DIV)' : 'ブロック要素 (DIV)',
'Link' : 'リンク',
'Delete link' : 'リンク削除',
'Bookmark' : 'アンカー挿入/編集',
'Image' : 'イメージ',
'Table' : 'テーブル',
'Delete table' : 'テーブル削除',
'Insert row before' : '前に行を挿入',
'Insert row after' : '後ろに行を挿入',
'Delete row' : '行を削除',
'Insert column before' : '前に列を挿入',
'Insert column after' : '後ろに列を挿入',
'Delete column' : '列を削除',
'Merge table cells' : 'セルを結合する',
'Split table cell' : 'セルを分割する',
'Toggle display document structure' : '構成要素の表示',
'Table cell properties' : 'テーブルセルプロパティ',
'Table properties' : 'テーブルプロパティ',
'Toggle full screen mode' : '最大化',
'Open file manager' : 'ファイルマネージャを開く',
'Non breakable space' : '改行なしスペース',
'Stop element floating' : 'フロートの解除',
// dialogs
'Warning' : '警告',
'Properties' : 'プロパティ',
'Popup' : 'ポップアップ',
'Advanced' : 'アドバンス',
'Events' : 'イベント',
'Width' : '幅',
'Height' : '高さ',
'Left' : '左',
'Center' : '中央',
'Right' : '右',
'Border' : 'ボーダー',
'Background' : '背景',
'Css class' : 'CSS class',
'Css style' : 'CSS style',
'No' : 'No',
'Title' : 'タイトル',
'Script direction' : '文字表記方向',
'Language' : '言語',
'Charset' : 'Charset',
'Not set' : '設定しない',
'Left to right' : '左から右',
'Right to left' : '右から左',
'In this window' : '同じウィンドウ (_self)',
'In new window (_blank)' : '新しいウィンドウ (_blank)',
'In new parent window (_parent)' : '新しい親ウィンドウ (_parent)',
'In top frame (_top)' : 'トップフレーム (_top)',
'URL' : 'URL',
'Open in' : 'Open in',
// copy
'This operation is disabled in your browser on security reason. Use shortcut instead.' : 'この機能はお使いのブラウザではセキュリティの観点からご利用できません。ショートカットをご利用ください。',
// format
'Heading 1' : '見出し1',
'Heading 2' : '見出し2',
'Heading 3' : '見出し3',
'Heading 4' : '見出し4',
'Heading 5' : '見出し5',
'Heading 6' : '見出し6',
'Paragraph' : '段落',
'Address' : 'アドレス',
'Preformatted' : '',
// font size
'Small (8pt)' : '小(8pt)',
'Small (10px)' : '小(10pt)',
'Small (12pt)' : '小(12pt)',
'Normal (14pt)' : '中(14pt)',
'Large (18pt)' : '大(18pt)',
'Large (24pt)' : '大(24pt)',
'Large (36pt)' : '大(36pt)',
// bookmark
'Bookmark name' : 'アンカー名',
// link
'Link URL' : '(URL)',
'Target' : 'ターゲット',
'Open link in popup window' : 'リンク先をポップアップで開く',
'URL' : 'URL',
'Window name' : 'ウィンドウ名',
'Window size' : 'ウィンドウサイズ',
'Window position' : 'ウィンドウ位置',
'Location bar' : 'ロケーションバー',
'Menu bar' : 'メニューバー',
'Toolbar' : 'ツールバー',
'Scrollbars' : 'スクロールバー',
'Status bar' : 'ステータスバー',
'Resizable' : 'サイズ可変',
'Depedent' : 'ウィンドウ連動',
'Add return false' : 'return falseを加える',
'Target MIME type' : 'Target MIME type',
'Relationship page to target (rel)' : 'ページからターゲットの関係 (rel)',
'Relationship target to page (rev)' : 'ターゲットからページの関係 (rev)',
'Tab index' : 'タブインデックス',
'Access key' : 'アクセスキー',
// image
'Size' : 'サイズ',
'Preview' : 'プレビュー',
'Margins' : 'マージン',
'Alt text' : '代替テキスト',
'Image URL' : '画像URL',
// table
'Spacing' : 'セル間隔 (spacing)',
'Padding' : 'セル内余白 (padding)',
'Rows' : '行',
'Columns' : '列',
'Groups' : 'グループ',
'Cells' : 'セル',
'Caption' : 'キャプション',
'Inner borders' : '内部ボーダー',
// about
'About elRTE' : 'elRTEについて',
'Version' : 'バージョン',
'Licence' : 'ライセンス',
'elRTE is an open-source JavaScript based WYSIWYG HTML-editor.' : 'elRTEはJavascriptベースのオープンソースWYSIWYG HTMLエディタです。',
'Main goal of the editor - simplify work with text and formating (HTML) on sites, blogs, forums and other online services.' : 'このエディタの主な目的は、ウェブサイト、ブログ、フォーラムやその他のオンラインサービスのテキストとHTMLフォーマット入力作業をシンプルにすることです。',
'You can use it in any commercial or non-commercial projects.' : '商用・非商用に関わらずご利用いただけます。',
'Authors' : '著作者',
'Chief developer' : 'チーフデベロッパー',
'Developer, tech support' : 'デベロッパー・テクニカルサポート',
'Interface designer' : 'インターフェイスデザイナー',
'Spanish localization' : 'スペイン語化ローカライゼーション',
'Japanese localization' : '日本語化ローカライゼーション',
'Latvian localization' : 'ラトビア語化ローカライゼーション',
'German localization' : 'ドイツ語化ローカライゼーション',
'Ukranian localization' : 'ウクライナ語化ローカライゼーション',
'For more information about this software visit the' : '次のURLにてこのソフトウェアのより詳しい情報を公開しています。',
'elRTE website' : 'elRTE ウェブサイト'
}
})(jQuery);
|
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
import { CSS, rafFrames, transitionEnd, nativeTimeout } from '../util/dom';
import { assign, isDefined } from '../util/util';
/**
* @private
**/
export var Animation = function () {
function Animation(ele) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, Animation);
this._wChg = false;
this._rv = false;
this._lastUpd = 0;
this.isPlaying = false;
this.hasTween = false;
this.hasCompleted = false;
this._reset();
this.element(ele);
this._opts = assign({
renderDelay: 24
}, opts);
}
_createClass(Animation, [{
key: '_reset',
value: function _reset() {
this._el = [];
this._c = [];
this._fx = {};
this._bfSty = {};
this._bfAdd = [];
this._bfRmv = [];
this._afSty = {};
this._afAdd = [];
this._afRmv = [];
this._pFns = [];
this._fFns = [];
this._fOnceFns = [];
this._easing = this._dur = null;
}
}, {
key: 'element',
value: function element(ele) {
var i;
if (ele) {
if (Array.isArray(ele)) {
for (i = 0; i < ele.length; i++) {
this._addEle(ele[i]);
}
} else if (typeof ele === 'string') {
ele = document.querySelectorAll(ele);
for (i = 0; i < ele.length; i++) {
this._addEle(ele[i]);
}
} else {
this._addEle(ele);
}
}
return this;
}
}, {
key: '_addEle',
value: function _addEle(ele) {
if (ele.nativeElement) {
ele = ele.nativeElement;
}
if (ele.nodeType === 1) {
this._el.push(ele);
// does this element suport will-change property?
this._wChg = typeof ele.style.willChange !== 'undefined';
}
}
}, {
key: 'parent',
value: function parent(parentAnimation) {
this._parent = parentAnimation;
return this;
}
}, {
key: 'add',
value: function add(childAnimation) {
childAnimation.parent(this);
this._c.push(childAnimation);
return this;
}
}, {
key: 'getDuration',
value: function getDuration() {
return this._dur !== null ? this._dur : this._parent && this._parent.getDuration() || 0;
}
}, {
key: 'duration',
value: function duration(milliseconds) {
this._dur = milliseconds;
return this;
}
}, {
key: 'getEasing',
value: function getEasing() {
return this._easing !== null ? this._easing : this._parent && this._parent.getEasing() || null;
}
}, {
key: 'easing',
value: function easing(name) {
this._easing = name;
return this;
}
}, {
key: 'from',
value: function from(prop, val) {
this._addProp('from', prop, val);
return this;
}
}, {
key: 'to',
value: function to(prop, val, clearProperyAfterTransition) {
var fx = this._addProp('to', prop, val);
if (clearProperyAfterTransition) {
// if this effect is a transform then clear the transform effect
// otherwise just clear the actual property
this.after.clearStyles([fx.trans ? CSS.transform : prop]);
}
return this;
}
}, {
key: 'fromTo',
value: function fromTo(prop, fromVal, toVal, clearProperyAfterTransition) {
return this.from(prop, fromVal).to(prop, toVal, clearProperyAfterTransition);
}
}, {
key: '_addProp',
value: function _addProp(state, prop, val) {
var fxProp = this._fx[prop];
if (!fxProp) {
// first time we've see this EffectProperty
fxProp = this._fx[prop] = {
trans: typeof TRANSFORMS[prop] !== 'undefined',
wc: ''
};
// add the will-change property for transforms or opacity
if (fxProp.trans) {
fxProp.wc = CSS.transform;
} else if (prop === 'opacity') {
fxProp.wc = prop;
}
}
// add from/to EffectState to the EffectProperty
var fxState = fxProp[state] = {
val: val,
num: null,
unit: ''
};
if (typeof val === 'string' && val.indexOf(' ') < 0) {
var r = val.match(CSS_VALUE_REGEX);
var num = parseFloat(r[1]);
if (!isNaN(num)) {
fxState.num = num;
}
fxState.unit = r[0] !== r[2] ? r[2] : '';
} else if (typeof val === 'number') {
fxState.num = val;
}
return fxProp;
}
}, {
key: 'fadeIn',
value: function fadeIn() {
return this.fromTo('opacity', 0.001, 1, true);
}
}, {
key: 'fadeOut',
value: function fadeOut() {
return this.fromTo('opacity', 0.999, 0);
}
}, {
key: 'play',
value: function play() {
var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var self = this;
var i;
var duration = isDefined(opts.duration) ? opts.duration : self._dur;
console.debug('Animation, play, duration', duration, 'easing', self._easing);
// always default that an animation does not tween
// a tween requires that an Animation class has an element
// and that it has at least one FROM/TO effect
// and that the FROM/TO effect can tween numeric values
self.hasTween = false;
self.hasCompleted = false;
// fire off all the onPlays
for (i = 0; i < self._pFns.length; i++) {
self._pFns[i]();
}
self.isPlaying = true;
// this is the top level animation and is in full control
// of when the async play() should actually kick off
// if there is no duration then it'll set the TO property immediately
// if there is a duration, then it'll stage all animations at the
// FROM property and transition duration, wait a few frames, then
// kick off the animation by setting the TO property for each animation
// stage all of the before css classes and inline styles
// will recursively stage all child elements
self._before();
// ensure all past transition end events have been cleared
self._clearAsync();
if (duration > 30) {
// this animation has a duration, so it should animate
// place all the elements with their FROM properties
// set the FROM properties
self._progress(0);
// add the will-change or translateZ properties when applicable
self._willChg(true);
// set the async TRANSITION END event
// and run onFinishes when the transition ends
self._asyncEnd(duration, true);
// begin each animation when everything is rendered in their place
// and the transition duration/easing is ready to go
rafFrames(self._opts.renderDelay / 16, function () {
// there's been a moment and the elements are in place
// now set the TRANSITION duration/easing
self._setTrans(duration, false);
// wait a few moments again to wait for the transition
// info to take hold in the DOM
rafFrames(2, function () {
// browser had some time to render everything in place
// and the transition duration/easing is set
// now set the TO properties
// which will trigger the transition to begin
self._progress(1);
});
});
} else {
// this animation does not have a duration, so it should not animate
// just go straight to the TO properties and call it done
self._progress(1);
// since there was no animation, immediately run the after
self._after();
// since there was no animation, it's done
// fire off all the onFinishes
self._didFinish(true);
}
}
}, {
key: 'stop',
value: function stop() {
var opts = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var self = this;
var duration = isDefined(opts.duration) ? opts.duration : 0;
var stepValue = isDefined(opts.stepValue) ? opts.stepValue : 1;
// ensure all past transition end events have been cleared
this._clearAsync();
// set the TO properties
self._progress(stepValue);
if (duration > 30) {
// this animation has a duration, so it should animate
// place all the elements with their TO properties
// now set the TRANSITION duration
self._setTrans(duration, true);
// set the async TRANSITION END event
// and run onFinishes when the transition ends
self._asyncEnd(duration, false);
} else {
// this animation does not have a duration, so it should not animate
// just go straight to the TO properties and call it done
self._after();
// since there was no animation, it's done
// fire off all the onFinishes
self._didFinish(false);
}
}
}, {
key: '_asyncEnd',
value: function _asyncEnd(duration, shouldComplete) {
var self = this;
function onTransitionEnd(ev) {
console.debug('Animation onTransitionEnd', ev.target.nodeName, ev.propertyName);
// ensure transition end events and timeouts have been cleared
self._clearAsync();
// set the after styles
self._after();
// remove will change properties
self._willChg(false);
// transition finished
self._didFinish(shouldComplete);
}
function onTransitionFallback() {
console.debug('Animation onTransitionFallback');
// oh noz! the transition end event didn't fire in time!
// instead the fallback timer when first
// clear the other async end events from firing
self._tmr = 0;
self._clearAsync();
// too late to have a smooth animation, just finish it
self._setTrans(0, true);
// ensure the ending progress step gets rendered
self._progress(1);
// set the after styles
self._after();
// remove will change properties
self._willChg(false);
// transition finished
self._didFinish(shouldComplete);
}
// set the TRANSITION END event on one of the transition elements
self._unregTrans = transitionEnd(self._transEl(), onTransitionEnd);
// set a fallback timeout if the transition end event never fires, or is too slow
// transition end fallback: (animation duration + XXms)
self._tmr = nativeTimeout(onTransitionFallback, duration + 400);
}
}, {
key: '_clearAsync',
value: function _clearAsync() {
this._unregTrans && this._unregTrans();
if (this._tmr) {
clearTimeout(this._tmr);
this._tmr = 0;
}
}
}, {
key: '_progress',
value: function _progress(stepValue) {
// bread 'n butter
var i;
var prop;
var fx;
var val;
var transforms;
var tweenEffect;
for (i = 0; i < this._c.length; i++) {
this._c[i]._progress(stepValue);
}
if (this._el.length) {
// flip the number if we're going in reverse
if (this._rv) {
stepValue = stepValue * -1 + 1;
}
transforms = [];
for (prop in this._fx) {
fx = this._fx[prop];
if (fx.from && fx.to) {
tweenEffect = fx.from.num !== fx.to.num;
if (tweenEffect) {
this.hasTween = true;
}
if (stepValue === 0) {
// FROM
val = fx.from.val;
} else if (stepValue === 1) {
// TO
val = fx.to.val;
} else if (tweenEffect) {
// EVERYTHING IN BETWEEN
val = (fx.to.num - fx.from.num) * stepValue + fx.from.num + fx.to.unit;
} else {
val = null;
}
if (val !== null) {
if (fx.trans) {
transforms.push(prop + '(' + val + ')');
} else {
for (i = 0; i < this._el.length; i++) {
this._el[i].style[prop] = val;
}
}
}
}
}
// place all transforms on the same property
if (transforms.length) {
if (!this._wChg) {
// if the element doesn't support will-change
// then auto add translateZ for transform properties
transforms.push('translateZ(0px)');
}
for (i = 0; i < this._el.length; i++) {
this._el[i].style[CSS.transform] = transforms.join(' ');
}
}
}
}
}, {
key: '_setTrans',
value: function _setTrans(duration, forcedLinearEasing) {
var i;
var easing;
// set the TRANSITION properties inline on the element
for (i = 0; i < this._c.length; i++) {
this._c[i]._setTrans(duration, forcedLinearEasing);
}
if (Object.keys(this._fx).length) {
for (i = 0; i < this._el.length; i++) {
// all parent/child animations should have the same duration
this._el[i].style[CSS.transitionDuration] = duration + 'ms';
// each animation can have a different easing
easing = forcedLinearEasing ? 'linear' : this.getEasing();
if (easing) {
this._el[i].style[CSS.transitionTimingFn] = easing;
}
}
}
}
}, {
key: '_willChg',
value: function _willChg(addWillChange) {
var i;
var wc;
var prop;
for (i = 0; i < this._c.length; i++) {
this._c[i]._willChg(addWillChange);
}
if (this._wChg) {
wc = [];
if (addWillChange) {
for (prop in this._fx) {
if (this._fx[prop].wc !== '') {
wc.push(this._fx[prop].wc);
}
}
}
for (i = 0; i < this._el.length; i++) {
this._el[i].style['willChange'] = wc.join(',');
}
}
}
}, {
key: '_before',
value: function _before() {
// before the RENDER_DELAY
// before the animations have started
var i;
var j;
var prop;
var ele;
// stage all of the child animations
for (i = 0; i < this._c.length; i++) {
this._c[i]._before();
}
if (!this._rv) {
for (i = 0; i < this._el.length; i++) {
ele = this._el[i];
// css classes to add before the animation
for (j = 0; j < this._bfAdd.length; j++) {
ele.classList.add(this._bfAdd[j]);
}
// css classes to remove before the animation
for (j = 0; j < this._bfRmv.length; j++) {
ele.classList.remove(this._bfRmv[j]);
}
// inline styles to add before the animation
for (prop in this._bfSty) {
ele.style[prop] = this._bfSty[prop];
}
}
}
}
}, {
key: '_after',
value: function _after() {
// after the animations have finished
var i;
var j;
var prop;
var ele;
for (i = 0; i < this._c.length; i++) {
this._c[i]._after();
}
for (i = 0; i < this._el.length; i++) {
ele = this._el[i];
// remove the transition duration/easing
ele.style[CSS.transitionDuration] = '';
ele.style[CSS.transitionTimingFn] = '';
if (this._rv) {
// finished in reverse direction
// css classes that were added before the animation should be removed
for (j = 0; j < this._bfAdd.length; j++) {
ele.classList.remove(this._bfAdd[j]);
}
// css classes that were removed before the animation should be added
for (j = 0; j < this._bfRmv.length; j++) {
ele.classList.add(this._bfRmv[j]);
}
// inline styles that were added before the animation should be removed
for (prop in this._bfSty) {
ele.style[prop] = '';
}
} else {
// finished in forward direction
// css classes to add after the animation
for (j = 0; j < this._afAdd.length; j++) {
ele.classList.add(this._afAdd[j]);
}
// css classes to remove after the animation
for (j = 0; j < this._afRmv.length; j++) {
ele.classList.remove(this._afRmv[j]);
}
// inline styles to add after the animation
for (prop in this._afSty) {
ele.style[prop] = this._afSty[prop];
}
}
}
}
}, {
key: 'progressStart',
value: function progressStart() {
for (var i = 0; i < this._c.length; i++) {
this._c[i].progressStart();
}
this._before();
// force no duration, linear easing
this._setTrans(0, true);
}
}, {
key: 'progressStep',
value: function progressStep(stepValue) {
var now = Date.now();
// only update if the last update was more than 16ms ago
if (now - 16 > this._lastUpd) {
this._lastUpd = now;
stepValue = Math.min(1, Math.max(0, stepValue));
for (var i = 0; i < this._c.length; i++) {
this._c[i].progressStep(stepValue);
}
if (this._rv) {
// if the animation is going in reverse then
// flip the step value: 0 becomes 1, 1 becomes 0
stepValue = stepValue * -1 + 1;
}
this._progress(stepValue);
}
}
}, {
key: 'progressEnd',
value: function progressEnd(shouldComplete, currentStepValue) {
console.debug('Animation, progressEnd, shouldComplete', shouldComplete, 'currentStepValue', currentStepValue);
for (var i = 0; i < this._c.length; i++) {
this._c[i].progressEnd(shouldComplete, currentStepValue);
}
// set all the animations to their final position
this._progress(shouldComplete ? 1 : 0);
// if it's already at the final position, or close, then it's done
// otherwise we need to add a transition end event listener
if (currentStepValue < 0.05 || currentStepValue > 0.95) {
// the progress was already left off at the point that is finished
// for example, the left menu was dragged all the way open already
this._after();
this._willChg(false);
this._didFinish(shouldComplete);
} else {
// the stepValue was left off at a point when it needs to finish transition still
// for example, the left menu was opened 75% and needs to finish opening
this._asyncEnd(64, shouldComplete);
// force quick duration, linear easing
this._setTrans(64, true);
}
}
}, {
key: 'onPlay',
value: function onPlay(callback) {
this._pFns.push(callback);
return this;
}
}, {
key: 'onFinish',
value: function onFinish(callback) {
var onceTimeCallback = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
var clearOnFinishCallacks = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
if (clearOnFinishCallacks) {
this._fFns = [];
this._fOnceFns = [];
}
if (onceTimeCallback) {
this._fOnceFns.push(callback);
} else {
this._fFns.push(callback);
}
return this;
}
}, {
key: '_didFinish',
value: function _didFinish(hasCompleted) {
this.isPlaying = false;
this.hasCompleted = hasCompleted;
var i;
for (i = 0; i < this._fFns.length; i++) {
this._fFns[i](this);
}
for (i = 0; i < this._fOnceFns.length; i++) {
this._fOnceFns[i](this);
}
this._fOnceFns = [];
}
}, {
key: 'reverse',
value: function reverse() {
var shouldReverse = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
for (var i = 0; i < this._c.length; i++) {
this._c[i].reverse(shouldReverse);
}
this._rv = shouldReverse;
return this;
}
}, {
key: 'destroy',
value: function destroy(removeElement) {
var i;
var ele;
for (i = 0; i < this._c.length; i++) {
this._c[i].destroy(removeElement);
}
if (removeElement) {
for (i = 0; i < this._el.length; i++) {
ele = this._el[i];
ele.parentNode && ele.parentNode.removeChild(ele);
}
}
this._clearAsync();
this._reset();
}
}, {
key: '_transEl',
value: function _transEl() {
// get the lowest level element that has an Animation
var i;
var targetEl;
for (i = 0; i < this._c.length; i++) {
targetEl = this._c[i]._transEl();
if (targetEl) {
return targetEl;
}
}
return this.hasTween && this._el.length ? this._el[0] : null;
}
/*
STATIC CLASSES
*/
}, {
key: 'before',
get: function get() {
var _this = this;
return {
addClass: function addClass(className) {
_this._bfAdd.push(className);
return _this;
},
removeClass: function removeClass(className) {
_this._bfRmv.push(className);
return _this;
},
setStyles: function setStyles(styles) {
_this._bfSty = styles;
return _this;
},
clearStyles: function clearStyles(propertyNames) {
for (var i = 0; i < propertyNames.length; i++) {
_this._bfSty[propertyNames[i]] = '';
}
return _this;
}
};
}
}, {
key: 'after',
get: function get() {
var _this2 = this;
return {
addClass: function addClass(className) {
_this2._afAdd.push(className);
return _this2;
},
removeClass: function removeClass(className) {
_this2._afRmv.push(className);
return _this2;
},
setStyles: function setStyles(styles) {
_this2._afSty = styles;
return _this2;
},
clearStyles: function clearStyles(propertyNames) {
for (var i = 0; i < propertyNames.length; i++) {
_this2._afSty[propertyNames[i]] = '';
}
return _this2;
}
};
}
}], [{
key: 'create',
value: function create(name) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var AnimationClass = AnimationRegistry[name];
if (!AnimationClass) {
// couldn't find an animation by the given name
// fallback to just the base Animation class
AnimationClass = Animation;
}
return new AnimationClass(null, opts);
}
}, {
key: 'register',
value: function register(name, AnimationClass) {
AnimationRegistry[name] = AnimationClass;
}
}]);
return Animation;
}();
var TRANSFORMS = {
'translateX': 1, 'translateY': 1, 'translateZ': 1,
'scale': 1, 'scaleX': 1, 'scaleY': 1, 'scaleZ': 1,
'rotate': 1, 'rotateX': 1, 'rotateY': 1, 'rotateZ': 1,
'skewX': 1, 'skewY': 1, 'perspective': 1
};
var CSS_VALUE_REGEX = /(^-?\d*\.?\d*)(.*)/;
var AnimationRegistry = {}; |
(function (global) {
'use strict';
$ = global.jQuery;
let branding_style = $('.govuk-radios__item input[name="branding_style"]:checked');
if (!branding_style.length) { return; }
branding_style = branding_style.val();
const $paneWrapper = $('<div class="govuk-grid-column-full"></div>');
const $form = $('form');
const previewType = $form.data('previewType');
const $previewPane = $(`<iframe src="/_${previewType}?${buildQueryString(['branding_style', branding_style])}" class="branding-preview"></iframe>`);
function buildQueryString () {
return $.map(arguments, (val, idx) => encodeURI(val[0]) + '=' + encodeURI(val[1])).join('&');
}
function setPreviewPane (e) {
const $target = $(e.target);
if ($target.attr('name') == 'branding_style') {
branding_style = $target.val();
}
$previewPane.attr('src', `/_${previewType}?${buildQueryString(['branding_style', branding_style])}`);
}
$paneWrapper.append($previewPane);
$form.find('.govuk-grid-row').eq(0).prepend($paneWrapper);
$form.attr('action', location.pathname.replace(new RegExp(`set-${previewType}-branding$`), `preview-${previewType}-branding`));
$form.find('button[type="submit"]').text('Save');
$('fieldset').on('change', 'input[name="branding_style"]', setPreviewPane);
})(window);
|
"use strict"
//constructor
var FileManager = function(input,callback){
var that = this;
this.input = input;
}
FileManager.prototype.upload = function(callback){
this.input.addEventListener("change",function changeEvent (e){
try{
var reader = new FileReader();
reader.onloadend = function(evt){
callback(evt.target.result);
}
reader.readAsDataURL(this.files[0]);
}catch(error){
throw error
}
});
}
|
angular.module('deco').directive('decoEmail',
[function () {
return {
restrict: 'EA',
replace: false,
template: function (element, attrs) {
return attrs.before + '@' + attrs.after;
}
};
}]
); |
Router.configure({
layoutTemplate: 'layout',
//loadingTemplate: 'loading',
//waitOn: function() {return true;} // later we'll add more interesting things here ....
});
Router.route('/', {name: 'welcome'});
Router.route('/about', {name: 'about'});
Router.route('/sponsors', {name:'sponsors'})
Router.route('/graphics', {name:'graphics'})
Router.route('/iptable', {name: 'iptable'});
Router.route('/iptable/edit',{name:'ipform'});
Router.route('/people',{name:'people'});
Router.route('/profile/:_id',
{name:'profile',
data: function(){
return Meteor.users.findOne({_id:this.params._id})
}
});
Router.route('/profileEdit/:_id',
{name:'profileEdit',
data: function(){ return Meteor.users.findOne({_id:this.params._id})}
});
|
module.exports = require('./lib/shim')
|
// is this necessary? not sure
if (module.parents) {
throw new Error("node-dev-warnings won't work");
}
require('./json');
|
Fixtures.DefaultPluginConfig = {foo: 'foo', bar: 'bar'};
Fixtures.Plugin = function(config) {
var self = this;
this.config = config;
this.preUpdates = 0;
this.postUpdates = 0;
this.prefabsCreated = 0;
this.prefabsDestroyed = 0;
this.entitiesCreated = 0;
this.entitiesDestroyed = 0;
this.runs = 0;
this.stops = 0;
this.flushes = 0;
this.loads = false;
this.unloaded = false;
this.sceneLoads = false;
this.$onLoad = function() { self.loaded = true; };
this.$onUnload = function() { self.unloaded = true; };
this.$onSceneLoaded = function() { self.sceneLoaded = true; };
this.$onRun = function() { self.runs++; };
this.$onStop = function() { self.stops++; };
this.$onFlush = function() { self.flushes++; };
this.$onPreUpdate = function(deltaTime) { self.preUpdates++; };
this.$onPostUpdate = function(deltaTime) { self.postUpdates++; };
this.$onPrefabCreate = function() { self.prefabsCreated++; };
this.$onPrefabDestroy = function() { self.prefabsDestroyed++; };
this.$onEntityCreate = function() { self.entitiesCreated++; };
this.$onEntityDestroy = function() { self.entitiesDestroyed++; };
};
|
'use strict';
const jsonWebToken = require('jwt-simple');
const settings = require('../settings.js');
const passwords = require('../common/passwords.js');
/**
* @param userObject
* @returns {{access_token: String, expires: *, user: *}}
*/
function generateToken(userObject) {
const date = new Date();
const expires = date.setDate(date.getDate() + settings.expireDays);
const token = jsonWebToken.encode({ expires: expires, username: userObject.username, role: userObject.role }, settings.secret);
return {
access_token: token,
expires: expires,
user: userObject
};
}
/**
* @param req
* @param res
* @returns {*}
*/
module.exports.getToken = function(req, res) {
const username = req.body.username;
const password = req.body.password;
if (typeof username === 'undefined' || typeof password === 'undefined') {
return res.status(401).json({ status: 401, message: 'Unauthorized' });
}
req.app.get('db').db.get('SELECT * FROM users WHERE username = ?', [ username ], function(error, userObject) {
if (typeof userObject !== 'undefined' && passwords.comparePassword(password, userObject.password)) {
return res.json(generateToken(userObject));
}
return res.status(401).json({ status: 401, message: 'Unauthorized' });
});
};
|
/*global require */
require([
'jquery'
, 'lodash'
, 'backbone'
, 'src/js/main-view'
, 'livefyre-bootstrap'
, 'nls/i18n'
, 'src/js/polyfill'
, 'css!lib/livefyre-bootstrap/dist/all.css'
, 'css!dev/css/main.css'
], function(
$
, _
, Backbone
, MainView
, lfBootstrap
) {
var main = new MainView({
el: $('#content')
});
main.render();
}); |
(function() {
var width = 960,
height = 480;
var projection = d3.geo.equirectangular()
.scale(153)
.translate([width / 2, height / 2])
.precision(.1);
var path = d3.geo.path()
.projection(projection);
var graticule = d3.geo.graticule();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("path")
.datum(graticule)
.attr("class", "graticule")
.attr("d", path);
d3.json("world-50m.json", function(error, world) {
if (error) throw error;
svg.insert("path", ".graticule")
.datum(topojson.feature(world, world.objects.land))
.attr("class", "land")
.attr("d", path);
svg.insert("path", ".graticule")
.datum(topojson.mesh(world, world.objects.countries, function(a, b) { return a !== b; }))
.attr("class", "boundary")
.attr("d", path);
});
d3.select(self.frameElement).style("height", height + "px");
})();
|
{
"(member ex officio), Managing Director": "Diretor Administrativo",
"404_error_msg": "Desculpe, esta página não existe",
"About": "Sobre",
"About Participedia": "Sobre Participedia",
"about.cases.example": "Por exemplo, este caso em %s 2017 orçamento participativo de Paris%s é uma das mais de 160 entradas de casos documentando o uso de métodos participativos para dar aos cidadãos uma influência mais forte sobre a distribuição de recursos públicos.",
"about.cases.p1": "As inscrições sobre casos documentam exemplos específicos de como vários métodos de política participativa e governança são implementados. Os casos podem ser contemporâneos ou históricos, concluídos ou em andamento.",
"about.ckmc.description": "O Comitê de Comunicação e Mobilização do Conhecimento é responsável por assessorar o Comitê Executivo sobre como a comunicação com os parceiros de pesquisa pode ser planejada, realizada e aprimorada. O Comitê Comunicação e Mobilização do Conhecimento (CCMC) também aconselha a comunicação com a comunidade de usuários do Participedia, incluindo o suporte ao desenvolvimento de conteúdo para o site, newsletter e canais de mídia social.",
"about.ckmc.title": "Comitê de comunicação e mobilização de conhecimento",
"about.committees.communications_knowledge_mobilization.p1": "O comitê de comunicação e mobilização de conhecimento assessora o comitê executivo no planejamento, implementação e aprimoramento das comunicações entre os parceiros de pesquisa. O comitê também aconselha sobre a otimização das comunicações externas com e entre a comunidade da Participedia, apoiando o desenvolvimento de conteúdo para o site, boletim informativo e canais de mídia social.\n",
"about.committees.design_tech.p1": "A Equipe de Design e Tecnologia usa métodos de design participativos para pesquisar e responder às necessidades e objetivos da comunidade Participedia e é responsável pelo desenvolvimento e teste da plataforma Participedia.net de código aberto. A base de código aberto da plataforma está disponível no %sGithub%s. A equipe de Design & Tecnologia está comprometida com a equidade, diversidade, inclusão e orientação de alunos e opera com o %sStudio de estética extensiva%s na %sEmily Carr University of Art + Design%s. Seus membros, incluindo estudantes e designers profissionais e tecnólogos, contribuem para a forma e desenvolvimento da Participedia, sob a liderança da representante da Universidade Emily Carr, Amber Frid-Jimenez.\n",
"about.committees.executive_committee.p1": "O Comitê Executivo da Participedia compreende os presidentes de cada comitê permanente, e suas reuniões estão abertas a qualquer membro de nossa equipe estendida ou co - signatários do projeto de parceria do SSHRC (co-investigadores, colaboradores e representante das instituições parceiras).",
"about.committees.p1": "Os comitês da Participedia são compostos por co-investigadores e colaboradores do projeto e são chefiados por um presidente nomeado que faz parte do comitê executivo.",
"about.committees.reasearch_design.p1": "O Comitê de design de pesquisa define a direção estratégica da agenda de pesquisa da Participedia.",
"about.committees.teaching_training_mentoring.p1": "O comitê de ensino, capacitação e orientação são responsáveis pela integração dos materiais da Participedia na pedagogia, no ensino, no envolvimento dos alunos e na formação de profissionais e funcionários públicos.",
"about.community.p1": "O banco de dados pesquisável sobre democracia participativa da Participedia é indicado para utilização de qualquer pessoa. A plataforma foi projetada de forma colaborativa por uma parceria internacional de pesquisa para conectar e reforçar seu trabalho em democracia participativa com conhecimento público de recursos colaborativos (crowdsourcing).",
"about.community.p2": "Participedia foi fundado por Archon Fung (Escola de Governo Kennedy da Universidade de Harvard) e Mark E. Warren (Departamento de Ciências Políticas da Universidade British Columbia), e é guiado por um conjunto de comitês permanentes.",
"about.content.p1": "A Participedia oferece um banco de dados pesquisável de conteúdos relacionados à participação pública mundial. Por favor, leia nosso %sDiretrizes%s sobre como escrever entradas.",
"about.contribute.p1": "Ajude a expandir nosso banco de dados editando o conteúdo existente ou publicando o seu próprio. Por favor, leia nossa redação de entrada %sDiretrizes%s.",
"about.contribute.p2": "%s Guia de primeiros passos -> %s",
"about.design_and_tech.description": "O Comitê de Design e Tecnologia é responsável pelo projeto e manutenção do site da Participedia.",
"about.explore.p1": "Pesquise, leia, baixe e aprenda com nosso banco de dados de casos, métodos, organizações, pesquisas, recursos didáticos e conjuntos de dados externos.",
"about.explore.p2": "%s Leia mais sobre nossa pesquisa -> %s",
"about.funders.p1": "A Participedia é atualmente apoiada pelo %s Conselho de pesquisa em Ciências Sociais e Humanidades do Canadá%s (SSHRC) através de uma parceria de cinco anos, iniciada em abril de 2015. A equipe de Design e Tecnologia recebe suporte adicional do %s Programa de Cadeiras de Pesquisa do Canadá%s e da %s Fundação Canadá para a inovação%s. O financiamento inicial do projeto foi abrangido por uma subvenção de parceria SSHRC de dois anos, de abril de 2011-2013. A funcionalidade multilinguagem da plataforma foi desenvolvida com o generoso apoio da %s Fundação Bertelsmann%s em 2012.",
"about.get_involved.p1": "Qualquer pessoa pode participar da Comunidade Participedia e contribuir para disseminar fontes de informações, catalogar e comparar processos políticos participativos em todo o mundo. O conteúdo da Participedia é produzido de forma colaborativa e de código aberto, com uma licença gratuita da Creative Commons.",
"about.members.p1": "Participedia está aberta a qualquer um. Nossos membros incluem pessoas de todas as origens, nacionalidades e profissões. De analistas de políticas para professores, de ativistas para professores, Participedia é um lugar para qualquer pessoa interessada em participação democrática. Nossa comunidade está no cerne do nosso esforço: ao se associar, você também pode ajudar a criar esse recurso crescente editando entradas existentes ou publicando novo conteúdo sobre a participação pública.",
"about.methods.example": "Por exemplo, o %sReunião da cidade do século XXI%s método permite que um grande número de pessoas deliberem simultaneamente em pequenos grupos usando a tecnologia de resposta do público.\n\n",
"about.methods.example.2": "Por exemplo, %s Deliberative Polling® %s é um método que usa ferramentas e técnicas, como %s seleção aleatória %s , %s pesquisas %s e %s discussões facilitadas em pequenos grupos. %s",
"about.methods.p1": "As entradas sobre métodos fornecem informações sobre os processos abrangentes usados para orientar a participação do público, como júris dos cidadãos, votações deliberativas, orçamento participativo e muito mais.",
"about.methods.p2": "As entradas de métodos também podem fornecer informações sobre as técnicas, mecanismos e dispositivos usados para implementar, orientar ou melhorar os métodos participativos.",
"about.organizations.example": "Por exemplo,%s \"Apathy is Boring ( Apatia é Chato)\" é uma ONG canadense que usa metodologias participativas e educação democrática nas artes para engajar os jovens na política.",
"about.organizations.p1": "As organizações são perfis de grupos formais e informais que projetam,implementam e apoiam inovações participativas.",
"about.partners.p1": "A Participedia baseia-se em uma parceria global entre organizações, instituições e indivíduos que compartilham interesses sobre políticas participativas e governança. Nossos parceiros incluem co-candidatos e colaboradores subsidiados pela parceria com o Conselho de Pesquisa em Ciências Sociais e Humanas do Canadá (SSHRC). Entre em contato conosco se você gostaria de apoiar a missão global do Projeto Participedia para expandir o uso e o conhecimento da inovação democrática, tornando-se um parceiro.",
"about.phase1.p1": "A Fase 1 da Participedia, financiada por uma doação da parceria SSHRC de 2015-2021, abordou o desafio da pesquisa de curar e mobilizar conhecimento associado a milhares de tipos de inovações democráticas que estão em vigor em países de todo o mundo. Fizemos isso por meio do crowdsourcing digital de conhecimento em uma área de pesquisa marcada por rápido desenvolvimento e conhecimento altamente disperso, muito mais prático do que acadêmico.",
"about.phase1.p2": "Participedia.net é uma plataforma online de código aberto para co-produção colaborativa de conhecimento sobre inovações democráticas, com foco na governança participativa. Seu conteúdo inclui artigos contribuídos por usuários e dados disponíveis em vários idiomas. A Participedia é agora o maior repositório mundial de informações sobre governança participativa, e construímos uma rede global de acadêmicos e profissionais que a apoiam e usam.",
"about.phase1.p3": "Antes da Fase 1, o projeto Participedia foi fundado em 2009 por Archon Fung (Kennedy School of Government, Harvard University) e Mark E. Warren (Departamento de Ciência Política, University of British Columbia).",
"about.phase1.p4": "O que se segue é um arquivo dos membros da equipe da Fase 1 da Participedia e apoiadores.",
"about.phase2.committees.p": "A Fase 2 da Participedia é orientada e apoiada pelos seguintes comitês permanentes:",
"about.phase2.p1": "A Fase 2 da Participedia é financiada por uma bolsa de parceria do Conselho Canadense de Pesquisa em Ciências Sociais e Humanas (SSHRC) de 2021-2026. A Fase 2 visa promover o conhecimento intersetorial global que apóie a inovação democrática e a resiliência. Durante esta fase do projeto, os membros da equipe irão colaborar para produzir pesquisas e mobilizar conhecimento para enfrentar diretamente os desafios atuais à democracia e democratização. Esta nova fase de pesquisa da Participedia reúne 63 pesquisadores de 22 universidades e 21 organizações em 12 países. %s Leia mais sobre nossa última concessão. %s",
"about.phase2.partners": "Parceiros da Participedia Fase 2",
"about.phase2.research.p": "Os membros da equipe da Fase 2 da Participedia participam de grupos de pesquisa para explorar de forma colaborativa as seguintes áreas de pesquisa:",
"about.phase2.supporters.p1": "Atualmente, a Participedia é apoiada pelo %s Conselho de Pesquisa em Ciências Sociais e Humanas do Canadá %s (SSHRC) por meio de um Subsídio de Parceria de cinco anos com início em 2021.",
"about.phase2.supporters.p2": "Software de gestão de tradução para este site é fornecido por %sPhraseApp%s.",
"about.rdc.description": "O Comitê de design de pesquisa é responsável por definir a direção estratégica da agenda de pesquisa da Participedia.",
"about.rdc.title": "Comitê de design de pesquisa",
"about.staff.p1": "A equipe central da Participedia mantém as operações do dia-a-dia, apoiam a Comunidade e garantem que os objetivos do projeto sejam continuamente alcançados e refinados.",
"about.supporters.p1": "A Participedia é atualmente apoiada pelo %s Conselho de pesquisa em Ciências Sociais e Humanidades do Canadá%s (SSHRC) através de uma parceria de cinco anos, iniciada em abril de 2015.",
"about.supporters.p2": "A equipe de design e tecnologia opera fora do %sEstúdio para estética extensiva%s na Universidade de Art e Design Emily Carr, e é apoiado pelo %s Programa de cadeiras pesquisa do Canadá%s e pela %sFundação Canadá para a inovação%s.\n",
"about.supporters.p3": "Software de gestão de tradução para este site é fornecido por %sPhraseApp%s.",
"about.supporters.p4": "O projeto foi previamente financiado por um subsídio de parceria com Conselho de Pesquisa em Ciências Sociais e Humanas do Canadá (SSHRC)com duração de dois anos, a partir de abril de 2011-2013. E, uma versão anterior do site Participedia incluiu um protótipo para a funcionalidade da língua alemã, desenvolvido o generoso apoio do %s Fundação Bertelsmann %s em 2012.",
"about.teach.p1": "Use Participedia na sala de aula para envolver os alunos e mostrar suas pesquisas.",
"about.teach.p2": "%s Recursos de ensino -> %s",
"about.teaching_resources.example": "Esta seção está em construção e estará disponível em breve.",
"about.teaching_resources.p1": "O Centro de Recursos de Ensino e Aprendizagem fornecem recursos para as configurações da sala de aula de graduação e pós-graduação, bem como recursos de desenvolvimento profissional para profissionais, organizações da sociedade civil e ONGs. Os recursos variam de acordo com as ementas de curso e atribuições de classe, para manuais, simulações e material de treinamento multimídia.",
"about.tools_techniques.example": "Por exemplo, %s Votação deliberativa®%s é um método que utiliza ferramentas e técnicas como %s seleção aleatória%s, %s Pesquisas%s e %s facilitou as discussões em pequenos grupos%s.",
"about.tools_techniques.p1": "As entradas sobre ferramentas e técnicas fornecem informações sobre as técnicas, mecanismos e dispositivos usados para implementar, orientar ou aprimorar métodos participativos.",
"about.ttmc.decription": "O comitê de ensino, capacitação e orientação é responsável por integrar os materiais da Participedia sobre as temáticas pedagógicas, de ensino, envolvimento dos alunos e recursos de treinamento para profissionais e funcionários públicos.",
"about.ttmc.title": "Capacitação de ensino e Comitê de orientação",
"Add Bookmark": "Adicionar marcador",
"add_another_link": "Adicionar outro link",
"Admin Only": "Somente o administrador",
"Advanced search": "Busca Avançada",
"Afghanistan": "Afeganistão",
"Albania": "Albânia",
"Algeria": "Argélia",
"All": "Todos",
"All Collections": "Todas as coleções",
"American Samoa": "Samoa Americana",
"Andorra": "Andorra",
"Angola": "Angola",
"Anguilla": "Anguilla",
"Antarctica": "Antártida",
"Antigua and Barbuda": "Antígua e Barbuda",
"approaches_label": "Abordagem",
"Argentina": "Argentina",
"Armenia": "Armênia",
"Aruba": "Aruba",
"audio_link_instructional": "Adicione links para áudio, como podcasts.",
"audio_url_placeholder": "Adicionar link para áudio",
"Australia": "Austrália",
"Austria": "Áustria",
"Azerbaijan": "Azerbaijão",
"Bahamas": "Bahamas",
"Bahrain": "Barein",
"Bangladesh": "Bangladesh",
"Barbados": "Barbados",
"Belarus": "Belarus",
"Belgium": "Bélgica",
"Belize": "Belize",
"Benin": "Benin",
"Bermuda": "Bermudas",
"Bhutan": "Butão",
"body_placeholder": "<h3>Problemas e propósitos</h3><h3>Antecedentes</h3><h3>História e contexto</h3><h3>Organizando, apoiando e financiando entidades</h3><h3>Recrutamento e seleção de participantes</h3><h3>Métodos e ferramentas usadas</h3><h3>Deliberação, decisões e interação pública</h3><h3>Influência, resultados e efeitos</h3><h3>Análise e lições aprendidas</h3><h3>Ver também</h3><h3>Referências</h3><h3>Links externos</h3><h3>Anotações</h3>",
"Bolivia": "Bolívia",
"Bookmarks": "Favoritos",
"Bosnia and Herzegovina": "Bósnia e Herzegovina",
"Botswana": "Botswana",
"Bouvet Island": "Ilha Bouvet",
"Brazil": "Brasil",
"British Indian Ocean Territory": "Território Britânico do Oceano Índico\n",
"Browse all entries": "Navegue por todas as entradas",
"Browse our Data Repository": "Navegue pelo nosso repositório de dados",
"Brunei": "Brunei",
"Bulgaria": "Bulgária",
"Burkina Faso": "Burkina Faso",
"Burundi": "Burundi",
"Cambodia": "Camboja",
"Cameroon": "Camarões",
"Canada": "Canadá",
"Cape Verde": "Cabo verde",
"Case": "Caso",
"case": "Caso",
"Cases": "Casos",
"Cases & Organizations": "Casos e organizações",
"cases of": "casos de",
"case_edit_approaches_instructional": "Selecione e classifique até três abordagens, com \"1\" indicando o mais relevante.",
"case_edit_approaches_label": "Abordagem",
"case_edit_approaches_placeholder": "Selecione e classifique até 3 abordagens",
"case_edit_audio_attribution_instructional": "Quem é o proprietário original ou criador deste áudio?",
"case_edit_audio_attribution_placeholder": "Proprietário ou criador",
"case_edit_audio_link_instructional": "Adicione links para áudio, como podcasts.",
"case_edit_audio_link_label": "Áudio",
"case_edit_audio_title_instructional": "Forneça um título ou uma descrição deste áudio em até 10 palavras ou menos.",
"case_edit_audio_title_placeholder": "Título ou descrição",
"case_edit_audio_url_placeholder": "Adicionar link para áudio",
"case_edit_body_instructional": "A estrutura padrão a seguir facilita a comparação e a análise de entradas. Use os títulos abaixo e consulte nossas <a href=\"https://goo.gl/FZJgMm\" target=\"_blank\"> diretrizes </a> ao preparar sua inscrição do caso",
"case_edit_body_label": "Narrativa",
"case_edit_body_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"case_edit_body_placeholder": "<h2>Problemas e propósitos</h2><h2>Histórico e contexto do plano de fundo</h2><h2>Organizando, apoiando e financiando entidades</h2><h2>Recrutamento e seleção de participantes</h2><h2>Métodos e ferramentas usadas</h2><h2>O que passou: processo, interação e participação</h2><h2>Influência, resultados e efeitos</h2><h2>Análise e lições aprendidas</h2><h2>Ver também</h2><h2>Referências</h2><h2>Links externos</h2><h2>Notas</h2>",
"case_edit_change_types_info": "Forneça detalhes adicionais na seção \"influência, resultados e efeitos\" do caso descrito. ",
"case_edit_change_types_instructional": "Selecionar e classificar até cinco tipos de mudança a que este caso contribuiu, por ordem de relevância, com \"1\" sendo o tipo mais relevante de mudança.",
"case_edit_change_types_label": "Tipos de alteração",
"case_edit_change_types_placeholder": "Selecione e classifique até 5 tipos de mudança a que este caso contribuiu",
"case_edit_collections_info": "Pedimos que apenas representantes de projetos ou organizações identificados como tendo coleções usem esse campo. O filtro de pesquisa 'Coleções' na página inicial fornece uma maneira de compilar e exibir casos que compartilham características comuns, como associação a uma iniciativa em larga escala, uma instituição ou localização geográfica. Essas coleções de entradas conectadas podem ser exibidas como um único conjunto de resultados, com um URL personalizado que pode servir como uma página de destino na Participedia. Se você tem uma ideia para uma nova coleção ou se precisar de mais informações, entre em contato conosco.\n\n",
"case_edit_collections_instructional": "Se você é um representante de um projeto ou organização que foi identificado como tendo uma coleção na Participedia, selecione-o aqui. Se a sua entrada não faz parte de uma coleção, por favor, deixe este campo em branco.",
"case_edit_collections_label": "Coleções",
"case_edit_collections_placeholder": "Selecione uma coleção",
"case_edit_completeness_label": "Completude da entrada",
"case_edit_completeness_placeholder": "Selecione o nível de completude para esta entrada",
"case_edit_decision_methods_instructional": "Como os participantes neste caso tomaram decisões em grupo?",
"case_edit_decision_methods_label": "Métodos de decisão",
"case_edit_decision_methods_placeholder": "Como foram tomadas as decisões do grupo?",
"case_edit_description_instructional": "Digite a descrição desse caso em até (280 caracteres ou menos)",
"case_edit_description_label": "Descrição breve",
"case_edit_description_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"case_edit_description_placeholder": "Digite a descrição",
"case_edit_end_date_instructional": "Selecione uma data de término, se aplicável",
"case_edit_end_date_label": "Data de término",
"case_edit_end_date_placeholder": "Selecione uma data de término, se aplicável",
"case_edit_evaluation_links_attribution_instructional": "Quem é o proprietário ou criador original deste conteúdo vinculado?\n",
"case_edit_evaluation_links_attribution_placeholder": "Proprietário ou criador",
"case_edit_evaluation_links_link_instructional": "Adicione um link para o relatório de avaliação.",
"case_edit_evaluation_links_link_label": "Relatório de avaliação links",
"case_edit_evaluation_links_title_instructional": "Forneça um título ou uma descrição para esse conteúdo vinculado em até 10 palavras ou menos.",
"case_edit_evaluation_links_title_placeholder": "Título ou descrição",
"case_edit_evaluation_links_url_placeholder": "Adicionar link",
"case_edit_evaluation_reports_attribution_instructional": "Quem é o proprietário original ou criador deste arquivo?",
"case_edit_evaluation_reports_attribution_placeholder": "Proprietário ou criador",
"case_edit_evaluation_reports_instructional": "Carregue os documentos relevantes aqui. Os tipos de arquivo suportados incluem: RTF, txt, Doc, docx, xls, xlsx, PDF, ppt, pptx, PPS, ppsx, odt, ODS e odp. O tamanho máximo do arquivo é 5MB.",
"case_edit_evaluation_reports_label": "Documentos de relatório de avaliação",
"case_edit_evaluation_reports_placeholder": "Clique para selecionar/ arrastar/ soltar o arquivos aqui",
"case_edit_evaluation_reports_source_url_instructional": "Se aplicável, forneça um link para onde o arquivo original foi originado.",
"case_edit_evaluation_reports_source_url_placeholder": "Link para o original",
"case_edit_evaluation_reports_title_instructional": "Forneça um título ou uma descrição para esse arquivo em até 10 palavras ou menos.",
"case_edit_evaluation_reports_title_label": "N/A",
"case_edit_evaluation_reports_title_placeholder": "Título ou descrição",
"case_edit_facetoface_online_or_both_instructional": "Os participantes interagiram cara a cara, on-line ou ambos?",
"case_edit_facetoface_online_or_both_label": "Cara a cara , online ou ambos",
"case_edit_facetoface_online_or_both_placeholder": "A interação foi cara a cara ou online?",
"case_edit_facilitators_instructional": "Os facilitadores ajudaram a orientar parte ou o caso inteiro?",
"case_edit_facilitators_label": "Facilitadores",
"case_edit_facilitators_placeholder": "Os facilitadores ajudaram a orientar os participantes?",
"case_edit_facilitator_training_instructional": "Que nível de formação os facilitadores possuem?",
"case_edit_facilitator_training_label": "Treinamento de facilitadora",
"case_edit_facilitator_training_placeholder": "Selecione o tipo de facilitadores",
"case_edit_featured_instructional": "Os artigos em destaque são exibidos primeiro na página inicial",
"case_edit_featured_label": "Destaque",
"case_edit_files_attribution_instructional": "Quem é o proprietário original ou criador deste arquivo?",
"case_edit_files_attribution_placeholder": "Proprietário ou criador",
"case_edit_files_instructional": "Carregue os documentos relevantes aqui. Os tipos de arquivo suportados incluem: RTF, txt, Doc, docx, xls, xlsx, PDF, ppt, pptx, PPS, ppsx, odt, ODS e odp. O tamanho máximo do arquivo é 5MB.",
"case_edit_files_label": "Arquivos",
"case_edit_files_placeholder": "Clique para selecionar ou arrastar e soltar arquivos aqui",
"case_edit_files_source_url_instructional": "Se aplicável, forneça um link para onde o arquivo original foi originado.",
"case_edit_files_source_url_placeholder": "Link para o original",
"case_edit_files_title_instructional": "Forneça um título ou uma descrição deste arquivo em até 10 palavras ou menos.",
"case_edit_files_title_label": "N/A",
"case_edit_files_title_placeholder": "Título ou descrição",
"case_edit_formal_evaluation_instructional": "Foi realizada uma avaliação formal desta iniciativa?",
"case_edit_formal_evaluation_label": "Avaliação formal",
"case_edit_formal_evaluation_placeholder": "Houve uma avaliação formal deste caso?",
"case_edit_funder_info": "Forneça informações adicionais sobre os financiadores da iniciativa do caso descrito, na seção \"entidades de origem e financiamento\".",
"case_edit_funder_instructional": "Quem financiou este caso de participação pública? Forneça nomes das organizações, agências governamentais ou indivíduos que pagaram por esta iniciativa.",
"case_edit_funder_label": "Financiador",
"case_edit_funder_placeholder": "Quem financiou este caso?",
"case_edit_funder_types_label": "Tipo de Financiamento",
"case_edit_funder_types_placeholder": "Escolha um tipo de financiador",
"case_edit_general_issues_instructional": "Ordem de classificação até três das questões mais relevantes abordadas, com \"1\" indicando a questão mais relevante. Você será solicitado a fornecer informações mais detalhadas no campo tópicos específicos abaixo.",
"case_edit_general_issues_label": "Questões gerais",
"case_edit_general_issues_placeholder": "Selecione e classifique até 3 questões",
"case_edit_hidden_instructional": "Os artigos ocultos não serão exibidos nos resultados da pesquisa",
"case_edit_hidden_label": "Escondidos",
"case_edit_if_voting_instructional": "Que métodos de votação foram utilizados pelos participantes?",
"case_edit_if_voting_label": "Se votar",
"case_edit_if_voting_placeholder": "Que métodos de votação foram utilizados?",
"case_edit_impact_evidence_instructional": "Será que esta iniciativa contribui para a mudança social e/ou política?",
"case_edit_impact_evidence_label": "Evidência de impacto",
"case_edit_impact_evidence_placeholder": "Será que este trabalho contribuir para a mudança social ou política?",
"case_edit_implementers_of_change_instructional": "Selecione até três tipos de atores que desempenharam papéis na implementação de ideias que emergiram desta iniciativa.",
"case_edit_implementers_of_change_label": "Implementadores de mudança",
"case_edit_implementers_of_change_placeholder": "Selecione e classifique até 3 tipos de implementadores de mudança",
"case_edit_insights_outcomes_instructional": "Selecione até três maneiras pelas quais as idéias e os resultados desse caso foram comunicados aos públicos-alvo.\n\n",
"case_edit_insights_outcomes_label": "Comunicação de ideias e resultados",
"case_edit_insights_outcomes_placeholder": "Como as idéias e os resultados foram comunicados?",
"case_edit_is_component_of_info": "Se você não encontrar o caso que está procurando, primeiro publique esta entrada para salvar seu trabalho. Em seguida, use o envio rápido para publicar a entrada do caso \"principal\". Em seguida, retorne à entrada deste caso e identifique-o como um componente do novo caso \"principal\"",
"case_edit_is_component_of_instructional": "Um caso só pode ser um componente de um outro caso, e o outro caso já pode ter sido publicado no Participedia. Digite para procurar um caso existente na plataforma e rotulá-lo como um componente dele. Selecione um. ",
"case_edit_is_component_of_label": "Tornar este caso um componente de outro caso",
"case_edit_is_component_of_placeholder": "Pesquisar caso/Principal",
"case_edit_learning_resources_instructional": "Que tipos de informações básicas foram fornecidas aos participantes?",
"case_edit_learning_resources_label": "Informações e recursos de aprendizagem",
"case_edit_learning_resources_placeholder": "Identifique as informações (se houver) fornecidas",
"case_edit_legality_instructional": "O método geral utilizado neste caso é considerado legal pelas autoridades judiciais?",
"case_edit_legality_label": "Legalidade",
"case_edit_legality_placeholder": "Isso foi considerado legal?",
"case_edit_links_attribution_instructional": "Quem é o proprietário ou criador original deste conteúdo vinculado?",
"case_edit_links_attribution_placeholder": "Proprietário ou criador",
"case_edit_links_link_instructional": "Se houver um site principal para este caso, insira-o aqui. Adicione links para fontes adicionais para que os leitores e editores possam encontrar mais informações sobre este caso online. ",
"case_edit_links_link_label": "Links",
"case_edit_links_title_instructional": "Forneça um título ou uma descrição para esse conteúdo vinculado em até 10 palavras ou menos.",
"case_edit_links_title_placeholder": "Título ou descrição",
"case_edit_links_url_placeholder": "Adicionar link",
"case_edit_location_instructional": "Digite para selecionar um endereço, cidade ou país onde ocorreram as primeiras atividades de caso. Liste quaisquer locais adicionais na narrativa do caso em \"entidades de origem e financiamento\". Você também pode criar componentes de caso separados para os locais de outras atividades.",
"case_edit_location_label": "Localização primária",
"case_edit_location_placeholder": "Tipo de busca para um local conhecido",
"case_edit_method_types_info": "Há uma grande variedade de métodos participativos. Para ajudar na síntese, selecione e classifique até três dos seguintes tipos de métodos usados neste caso. Especificar os métodos utilizados facilita para os usuários da Participedia encontrar casos similares.",
"case_edit_method_types_instructional": "Selecione e classifique até três tipos que melhor descrevem os métodos usados neste caso, com \"1\" indicando o mais relevante.",
"case_edit_method_types_label": "Tipos gerais de métodos",
"case_edit_method_types_placeholder": "Selecione e classifique até 3 tipos",
"case_edit_number_of_participants_instructional": "Aproximadamente quantas pessoas participaram? ",
"case_edit_number_of_participants_label": "Número total de participantes",
"case_edit_number_of_participants_placeholder": "Quantas pessoas participaram?",
"case_edit_ongoing_instructional": "Este caso está em andamento",
"case_edit_ongoing_label": "Em andamento",
"case_edit_ongoing_placeholder": "Este caso está em curso?",
"case_edit_open_limited_instructional": "Isso foi aberto a todos ou limitado a uma parte da população?",
"case_edit_open_limited_label": "Aberto a todos ou limitado a alguns?",
"case_edit_open_limited_placeholder": "Isso foi aberto a todos ou limitados a alguns?",
"case_edit_organizer_types_instructional": "Selecione até três tipos de organizadores ou gerentes.",
"case_edit_organizer_types_label": "Tipo de organizador/gerente",
"case_edit_organizer_types_placeholder": "Selecione até 3 tipos de organizadores ou gerentes",
"case_edit_participants_interactions_instructional": "Selecione e classifique até três tipos de interações por ordem de relevância, com \"1\" indicando a forma mais usada de interação.",
"case_edit_participants_interactions_label": "Tipos de interação entre os participantes",
"case_edit_participants_interactions_placeholder": "Selecione e classifique até 3 tipos de interação",
"case_edit_photos_attribution_instructional": "Quem é o dono original ou criador desta imagem?",
"case_edit_photos_attribution_placeholder": "Proprietário ou criador",
"case_edit_photos_instructional": "Faça upload de imagens aqui. Os tipos de arquivo suportados incluem: jpg, jpeg e png. O tamanho máximo do arquivo é 5 MB. Para obter melhores resultados, carregue uma imagem recortada na proporção de 16:9, de preferência com pelo menos 640 pixels de largura por 360 pixels de altura.",
"case_edit_photos_label": "Imagens",
"case_edit_photos_placeholder": "Clique para selecionar ou arrastar e soltar imagens aqui",
"case_edit_photos_source_url_instructional": "Se aplicável, forneça um link para onde a imagem original foi originária.",
"case_edit_photos_source_url_placeholder": "Link para o original",
"case_edit_photos_title_instructional": "Forneça um título ou uma descrição desta imagem em até 10 palavras ou menos.",
"case_edit_photos_title_placeholder": "Título ou descrição",
"case_edit_primary_organizer_info": "Forneça informações sobre organizadores e patrocinadores adicionais da iniciativa na seção \"entidades de origem e financiamento\" da narrativa do caso.",
"case_edit_primary_organizer_instructional": "Quem foi o primeiro responsável pela organização/gestão da iniciativa? Digite para selecionar o nome de qualquer organização que já exista no Participedia. Para novas organizações, primeiro publique este caso para salvar seu trabalho e, em seguida, publique uma nova organização. Para adicionar sua nova organização, retorne para editar esse caso.\n\n",
"case_edit_primary_organizer_label": "Organizador Principal/Gerente",
"case_edit_primary_organizer_placeholder": "Digite para pesquisar e gerar possíveis correspondências de banco de dados",
"case_edit_public_spectrum_instructional": "Que tipo de objetivo do espectro IAP2 (Associação Internacional de Participação Pública) de participação pública este caso representa melhor?",
"case_edit_public_spectrum_label": "Espectro de participação pública",
"case_edit_public_spectrum_placeholder": "Selecione uma meta",
"case_edit_purposes_instructional": "Selecione e classifique até três finalidades, com \"1\" indicando a mais relevante.",
"case_edit_purposes_label": "Finalidade/objetivo",
"case_edit_purposes_placeholder": "Selecione e classifique até 3 finalidades/objetivos",
"case_edit_recruitment_method_instructional": "Se for relevante para este caso, selecione o método usado para recrutar um subconjunto limitado da população.",
"case_edit_recruitment_method_label": "Método de recrutamento para subconjunto limitado de população",
"case_edit_recruitment_method_placeholder": "Selecione o método de recrutamento",
"case_edit_scope_of_influence_instructional": "Qual é a área de abrangência geográfica ou jurisdicional deste caso?",
"case_edit_scope_of_influence_label": "Escopo de influência",
"case_edit_scope_of_influence_placeholder": "Selecione a área geográfico ou jurisdicional",
"case_edit_specific_methods_tools_techniques_info": "Se você não conseguir encontrar seu método, ferramenta ou técnica, primeiro publique essa entrada para salvar seu trabalho. Em seguida, adicione um novo método, ferramenta ou técnica de entrada. Em seguida, retorne a essa entrada de caso e adicione seu novo método, ferramenta ou técnica. ",
"case_edit_specific_methods_tools_techniques_instructional": "Que métodos específicos, ferramentas e técnicas foram utilizados neste caso? Digite para selecionar a partir de entradas já existentes no banco de dados Participedia.",
"case_edit_specific_methods_tools_techniques_label": "Métodos específicos, ferramentas e técnicas",
"case_edit_specific_methods_tools_techniques_placeholder": "Digite para pesquisar e gerar possíveis correspondências no banco de dados",
"case_edit_specific_topics_instructional": "Classifique a ordem dos três mais relevantes, tópicos específicos , utilizando o \"1\" para indicar o tópico mais relevante.",
"case_edit_specific_topics_label": "Tópicos específicos",
"case_edit_specific_topics_placeholder": "Selecione e classifique até 3 tópicos",
"case_edit_staff_instructional": "Algum funcionário ou consultores estiveram envolvidos neste caso?",
"case_edit_staff_label": "Pessoal",
"case_edit_staff_placeholder": "Foram pagos funcionários ou consultores envolvidos?",
"case_edit_start_date_instructional": "Selecione uma data de início ou data de um único evento.",
"case_edit_start_date_label": "Data de início",
"case_edit_start_date_placeholder": "Selecione uma data de início ou a data de um único evento",
"case_edit_tags_instructional": "Selecione as tags que melhor descrevem esse caso. ",
"case_edit_tags_label": "Tags",
"case_edit_tags_placeholder": "Insira uma ou mais Tags",
"case_edit_targeted_participants_instructional": "Selecione até três dos grupos mais fortemente recrutados.",
"case_edit_targeted_participants_label": "Segmentação Demográfica",
"case_edit_targeted_participants_placeholder": "Identifique em até 3, os grupos recrutados",
"case_edit_time_limited_instructional": "Este caso ocorreu durante um período único definido de dias, semanas ou meses? Ou todo o processo foi repetido ao longo do tempo? Selecione um.",
"case_edit_time_limited_label": "Tempo limitado ou repetido?",
"case_edit_time_limited_placeholder": "Este tempo foi limitado ou repetido?",
"case_edit_title_instructional": "Atribua a este projeto ou evento de participação pública um título descritivo em até 10 palavras ou menos. Por exemplo, \"Diálogo Brasileiro sobre Diversidade\" ou \"Fórum de Assuntos Públicos da Cidade de Nova York\".",
"case_edit_title_label": "Título do caso",
"case_edit_title_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"case_edit_title_placeholder": "Digite o título em até 10 palavras ou menos",
"case_edit_tools_techniques_types_info": "Existe uma variedade enorme de ferramentas / técnicas participativas. Para ajudar a reduzi-lo, selecione e classifique até três dos seguintes tipos que melhor descrevem as ferramentas / técnicas específicas usadas neste caso. A especificação de quais tipos de ferramentas / técnicas foram usadas facilita para os usuários da Participedia encontrar casos semelhantes.\n\n",
"case_edit_tools_techniques_types_instructional": "Selecione e classifique até três tipos que melhor descrevem as ferramentas/técnicas usadas neste caso, com \"1\" indicando o mais relevante.",
"case_edit_tools_techniques_types_label": "Tipos gerais de ferramentas/técnicas",
"case_edit_tools_techniques_types_placeholder": "Selecione e classifique até 3 tipos",
"case_edit_verified_instructional": "As entradas verificadas foram revisadas pelo conselho editorial da Participedia e só podem ser editadas por administradores.",
"case_edit_verified_label": "Verificado",
"case_edit_videos_attribution_instructional": "Quem é o dono original ou criador deste vídeo?",
"case_edit_videos_attribution_placeholder": "Proprietário ou criador",
"case_edit_videos_link_instructional": "Adicione um link de vídeo do Vimeo ou YouTube.",
"case_edit_videos_link_label": "Vídeos",
"case_edit_videos_title_instructional": "Forneça um título ou uma descrição deste vídeo em até 10 palavras ou menos.",
"case_edit_videos_title_placeholder": "Título ou descrição",
"case_edit_videos_url_placeholder": "Adicionar link de vídeo (Vimeo ou YouTube)",
"case_edit_volunteers_instructional": "Voluntários não remunerados ajudam a implementar este caso?",
"case_edit_volunteers_label": "Voluntários",
"case_edit_volunteers_placeholder": "Voluntários não remunerados estavam envolvidos?",
"case_view_approaches_label": "Abordagem",
"case_view_audio_label": "Áudio",
"case_view_body_label": "Narrativa",
"case_view_change_types_label": "Tipos de mudanças",
"case_view_collections_label": "Coleções",
"case_view_completeness_label": "Completude de entrada",
"case_view_country_label": "Países",
"case_view_decision_methods_label": "Métodos de decisão",
"case_view_description_label": "Descrição breve",
"case_view_end_date_label": "Data de término",
"case_view_evaluation_links_label": " Links do relatório de avaliação",
"case_view_evaluation_reports_label": "Documentos de relatório de avaliação",
"case_view_evaluation_reports_title_label": "N/A",
"case_view_facetoface_online_or_both_label": "Cara a cara, online ou ambos",
"case_view_facilitators_label": "Facilitadores",
"case_view_facilitator_training_label": "Treinamento de facilitadora",
"case_view_files_label": "Arquivos",
"case_view_files_title_label": "N/A",
"case_view_formal_evaluation_label": "Avaliação formal",
"case_view_funder_label": "Financiador",
"case_view_funder_types_label": "Tipo de Financiador",
"case_view_general_issues_label": "Questões gerais",
"case_view_has_components_label": "Componentes deste caso",
"case_view_if_voting_label": "Se votar",
"case_view_impact_evidence_label": "Evidência de impacto",
"case_view_implementers_of_change_label": "Implementadores de mudança",
"case_view_insights_outcomes_label": "Comunicação de percepção e resultados",
"case_view_is_component_of_label": "Responsável por esse caso",
"case_view_learning_resources_label": "Informações e recursos de aprendizado",
"case_view_legality_label": "Legalidade",
"case_view_links_label": "Links",
"case_view_location_label": "Localização primária",
"case_view_method_types_label": "Tipos gerais de métodos",
"case_view_number_of_participants_label": "Número total de participantes",
"case_view_ongoing_label": "Em andamento",
"case_view_open_limited_label": "Aberto a todos ou limitado a alguns?",
"case_view_organizer_types_label": "Tipo de organizador/gerente",
"case_view_participants_interactions_label": "Tipos de interação entre os participantes",
"case_view_photos_label": "Imagens",
"case_view_primary_organizer_label": "Organizador/gerente principal",
"case_view_public_spectrum_label": "Espectro de participação pública",
"case_view_purposes_label": "Finalidade/objetivo",
"case_view_recruitment_method_label": "Método de recrutamento para subconjunto limitado de população",
"case_view_scope_of_influence_label": "Área de Influência ",
"case_view_specific_methods_tools_techniques_label": "Métodos específicos, ferramentas e técnicas",
"case_view_specific_topics_label": "Tópicos específicos",
"case_view_staff_label": "Pessoal",
"case_view_start_date_label": "Data de início",
"case_view_tags_label": "Tags",
"case_view_targeted_participants_label": "Segmentação Demográfica",
"case_view_time_limited_label": "Tempo limitado ou repetido?",
"case_view_title_label": "Título do caso",
"case_view_tools_techniques_types_label": "Tipos gerais de ferramentas/técnicas",
"case_view_videos_label": "Vídeos",
"case_view_volunteers_label": "Voluntários",
"Cayman Islands": "Ilhas Cayman",
"Central African Republic": "República Centro-Africana",
"Chad": "Chade",
"Chair, Communication & Knowledge Mobilization Committee": "Presidente, Comitê de comunicação e mobilização do conhecimento",
"Chair, Research Design Committee": "Presidente, Comitê de design de pesquisa",
"change": "Mudar",
"Chile": "Chile",
"China": "China",
"Chinese": "Chinês",
"Christmas Island": "Ilha do Natal",
"citizens_voices_collection_is_now_live": "O \"%sCitizens Voices & Values on Covid-19%s\" coleção agora é ao vivo!",
"Clear All": "Apagar tudo",
"Clear Category": "Limpar categoria",
"Click anywhere to activate map": "Clique em qualquer lugar para ativar o mapa",
"click for more info": "clique para mais informações",
"Click to select": "Clique para selecionar",
"close banner": "fechar banner",
"Close Card": "Fechar cartão",
"close FAQ pop over": "fechar Perguntas Frequentes (FAQ)",
"close menu": "fechar o menu",
"Co-Chairs, Teaching, Training and Mentoring Committee": "Co- presidentes, Comitê de ensino, capacitação e orientação",
"Co-Founder": "Co-fundador",
"Co-investigator": "Co-investigador",
"Co-investigator & Committee Chair": "Co-investigador e Presidente da Comissão",
"Co-investigators": "Co-investigadores",
"coady_students": "Graduados no Instituto Coady",
"Cocos (Keeling) Islands": "Ilhas Cocos (Keeling)",
"Collaborator": "Colaborador",
"Collaborators": "Colaboradores",
"Collection": "Coleção",
"collection": "Coleção",
"collections": "Coleções",
"Collections": "Coleções",
"collections of": "coleções de",
"collection_edit_description_instructional": "Digite a descrição do comprimento do tweet (280 caracteres ou menos) desta coleção.",
"collection_edit_description_label": "Descrição breve",
"collection_edit_description_placeholder": "Digite a descrição ",
"collection_edit_featured_instructional": "Os artigos em destaque são exibidos primeiro na página inicial",
"collection_edit_featured_label": "Destaque",
"collection_edit_hidden_instructional": "Os artigos ocultos não serão exibidos nos resultados da pesquisa",
"collection_edit_hidden_label": "Escondidos",
"collection_edit_links_attribution_instructional": "Quem é o proprietário ou criador original deste conteúdo vinculado?",
"collection_edit_links_attribution_placeholder": "Proprietário ou criador",
"collection_edit_links_link_instructional": "Se houver um site principal para esta coleção, insira-o aqui.",
"collection_edit_links_link_label": "Links",
"collection_edit_links_title_instructional": "Forneça um título ou uma descrição deste conteúdo vinculado em até 10 palavras ou menos.",
"collection_edit_links_title_placeholder": "Título ou descrição",
"collection_edit_links_url_placeholder": "Adicionar link",
"collection_edit_photos_attribution_instructional": "Quem é o proprietário ou criador original desta imagem?",
"collection_edit_photos_attribution_placeholder": "Proprietário ou criador",
"collection_edit_photos_label": "Fotos",
"collection_edit_photos_source_url_instructional": "Se aplicável, forneça um link para onde a imagem original foi originária.",
"collection_edit_photos_source_url_placeholder": "Link para o original",
"collection_edit_photos_title_instructional": "Forneça um título ou uma descrição desta imagem em até 10 palavras ou menos.",
"collection_edit_photos_title_placeholder": "Título ou descrição",
"collection_edit_title_instructional": "Digite o nome desta coleção",
"collection_edit_title_label": "Título",
"collection_edit_title_placeholder": "Digite o título em até 10 palavras ou menos",
"collection_edit_verified_instructional": "As entradas verificadas foram revisadas pelo conselho editorial da Participedia e só podem ser editadas por administradores.",
"collection_edit_verified_label": "Verificado",
"collection_num_case": "%s Caso",
"collection_num_case_plural_or_zero": "%s Casos",
"collection_num_method": "%s Método",
"collection_num_method_plural_or_zero": "%s Métodos",
"collection_num_organization": "%s Organização",
"collection_num_organization_plural_or_zero": "%s Organizações",
"collection_summary_string": "O %s A coleção contém:",
"Colombia": "Colômbia",
"Committees": "Comitês",
"Communications & Knowledge Mobilization Committee": "Comitê de comunicação e mobilização de conhecimento",
"Communications Team": "Equipe de Comunicações",
"Community": "Comunidade",
"Comoros": "Comores",
"completeness.Citations/Footnotes Needed": "Citações/Notas de Rodapé Necessárias",
"completeness.general_modal_text_2": "O nível de completude de uma entrada é atribuído manualmente pela nossa equipe de edição. Entradas completas contêm a maioria dos dados solicitados no formulário de inscrição, incluem pelo menos três seções da narrativa escrita usando citações (notas de rodapé) e não exigem correções significativas em sua gramática ou ortografia. Se você concluir uma entrada, envie um e-mail %s para solicitar uma revisão para que ela possa ser rotulada corretamente.\n",
"completeness.general_modal_text_3": "Por favor, leia nosso %s Diretrizes%s sobre como escrever uma entrada ou entrar em contato conosco para obter mais informações.",
"completeness.Grammar/Spelling Edits Needed": "Gramática / Edições ortográficas necessárias",
"completeness.Partial": "Parcial",
"completeness.partial_citations_alert": "%s A entrada a seguir está faltando citações.%s Por favor, ajude-nos. %s verificar seu conteúdo%s.",
"completeness.partial_citation_modal_text_1": "Este tipo de entrada está faltando citações (notas de rodapé), mas de outra forma está completa. Entradas que necessitam de citações podem ser identificadas usando o filtro de pesquisa \"completude de entrada\" na página inicial.",
"completeness.partial_content_alert": "%s A entrada a seguir está incompleta.%s Você pode ajudar Participedia por %s adicionando a ele%s.",
"completeness.partial_content_modal_text_1": "Entradas parciais são quase pela metade completas e são bons pontos de partida para estudantes e qualquer pessoa interessada em contribuir com a Participedia. Mais entradas parciais podem ser encontradas usando o filtro de pesquisa \"completude de entrada\" na página inicial.",
"completeness.partial_editing_alert": "%s A entrada a seguir precisa de assistência com conteúdo e edição.%s Por favor, ajude-nos. %s a completá-lo%s.",
"completeness.partial_editing_modal_text_1": "Esse tipo de entrada precisa de melhorias significativas em sua gramática ou ortografia, e pode ser qualquer nível de completude (esboço, parcial ou completo). Entradas que precisam de gramática ou edições ortográficas podem ser identificadas usando o filtro de pesquisa \"completude de entrada\" na página inicial.",
"completeness.Stub": "Esboço",
"completeness.stub_alert": "%s A entrada a seguir é esboço.%s Por favor, ajude-nos. %scompletá-lo%s.",
"completeness.stub_modal_text_1": "As inscrições de stub contêm poucas informações além de um título, proporcionando vagas de início ideais para os alunos e qualquer pessoa interessada em contribuir para o Participedia. Mais entradas de stub podem ser encontradas usando o filtro de pesquisa de \"completude de entrada\" na página inicial.",
"components_sectionlabel": "Componentes",
"confirm_new_password_placeholder": "Confirmar nova senha",
"Congo": "Congo",
"Contact Us": "Contacte-nos",
"Content": "Conteúdo",
"content_types.case.description": "Os casos são eventos específicos e instâncias de política participativa e governança de todas as formas e tamanhos. Os casos podem ser contemporâneos ou históricos, concluídos ou em andamento.",
"content_types.collection.description": "As coleções fornecem uma maneira de compilar e exibir entradas (casos, métodos e organizações) que compartilham características comuns, como associação com uma iniciativa em larga escala, uma instituição ou localização geográfica.",
"content_types.header": "Selecione o tipo de conteúdo que você gostaria de publicar.",
"content_types.method.description": "Os métodos são os processos e procedimentos utilizados para orientar a política participativa e a governança.",
"content_types.organization.description": "As organizações são perfis de grupos formais e informais que projetam, implementam ou apoiam inovações em políticas e governança participativas.",
"Contribute": "Contribuir",
"Contributions": "Contribuições",
"contributors": "contribuidores",
"Cook Islands": "Ilhas Cook",
"Costa Rica": "Costa Rica",
"countries": "Países",
"Countries": "Países",
"country_label": "País",
"Croatia": "Croácia",
"Cuba": "Cuba",
"current_password_placeholder": "Senha atual",
"Cyprus": "Chipre",
"Czech Republic": "República Tcheca",
"Data": "Dados",
"Data Repository": "Repositório de dados",
"Date Submitted": "Data de submissão",
"date_sectionlabel": "Data e duração",
"Democracy Across Borders": "Democracy Across Borders",
"Democracy and digital communications": "Democracia e comunicações digitais",
"Democratic Accountability": "Responsabilidade Democrática",
"Democratic Representation": "Representação Democrática",
"Denmark": "Dinamarca",
"description_instructional": "Digite a descrição desse caso em até (280 caracteres ou menos)",
"description_label": "Descrição breve",
"description_narrative_sectionlabel": "Descrição e narrativa",
"Design & Technology Committee": "Comitê de Design e Tecnologia",
"Design & Technology Team Lead & Art Director": "Equipe de Design e Tecnologia e Diretor de Arte",
"Design Technology Team": "Equipe de Tecnologia de Design",
"Designer": "Designer",
"Designer & Developer": "Designer e desenvolvedor",
"Developer": "Desenvolvedor",
"disabled_language_selector_note": "Depois de inserir o texto em inglês, você pode adicionar outros idiomas.",
"Djibouti": "Djibouti",
"Do Full Version": "Fazer versão completa",
"Dominica": "Dominica",
"Dominican Republic": "República Dominicana",
"Dutch": "Holandês",
"East Timor": "Timor-Leste",
"Ecuador": "Equador",
"Edit": "Editar",
"Edit Submission Details": "Editar detalhes do envio",
"Editors": "Editores",
"edit_form.quick submit notice": "Esta é a forma rápida / curta e contém apenas um subconjunto dos campos disponíveis para edição.",
"edit_form.view the full form...": "Você pode ver o formulário completo %s aqui %s .",
"edit_media_not_supported_file_type_error": "Desculpe, o arquivo %s não pode ser carregado porque não é um tipo de arquivo suppported. Nós suportamos tipos de imagem .jpg e .png.",
"edit_profile": "Editar perfil",
"Egypt": "Egito",
"El Salvador": "El Salvador",
"Email Support Team": "E-mail da Equipe de Suporte",
"English": "Inglês",
"entries of": "entradas de",
"Entry Completeness": "Completude de entrada",
"Equatorial Guinea": "Guiné Equatorial",
"Eritrea": "Eritreia",
"Estonia": "Estônia",
"Ethiopia": "Etiópia",
"evaluation_links_link_label": "Links do relatório de avaliação",
"evaluation_links_title_instructional": "Forneça um título ou uma descrição deste conteúdo vinculado em até 10 palavras ou menos.",
"evaluation_links_url_placeholder": "Adicionar link",
"evaluation_reports_attribution_instructional": "Quem é o proprietário original ou criador deste arquivo?",
"evaluation_reports_attribution_placeholder": "Proprietário ou criador",
"evaluation_reports_label": "Documentos de relatório de avaliação",
"evaluation_reports_link_instructional": "Se aplicável, forneça um link para onde o arquivo original foi originado.",
"evaluation_reports_link_placeholder": "Link para o original",
"evaluation_reports_title_instructional": "Forneça um título ou uma descrição deste arquivo em até 10 palavras ou menos.",
"evaluation_reports_title_placeholder": "Título ou descrição",
"evidence_of_impact": "Evidência de impacto",
"evidence_sectionlabel": "Evidência de impacto",
"Executive Committee": "Comitê Executivo",
"Explore": "Explorar",
"Explore & Research": "Explorar e pesquisar",
"Explore Cases & Organizations by Location": "Explorar casos e organizações por local",
"facilitators_placeholder": "Os facilitadores ajudam a orientar os participantes?",
"Falkland Islands": "Ilhas Falkland (Malvinas)",
"false": "Falso",
"FAQ": "Perguntas Freqüentes",
"faq_a1": "Inscrições sobre casos documentam usos específicos de métodos de participação pública. Os casos podem ser contemporâneos ou históricos, concluídos ou contínuos. Por favor, leia nosso %sDiretrizes%s sobre como escrever um caso.",
"faq_a10_p1": "Navegue até a %s busca %s página no menu local, ou utilizar a barra de pesquisa no topo de qualquer página para realizar um site-wide palavra-chave de busca. Depois que os resultados da pesquisa são exibidos, você pode classificá-los por tipo de conteúdo, como casos, métodos ou organizações. Você pode filtrar ainda mais os resultados de casos, métodos ou organizações usando o botão de filtros.",
"faq_a10_p2": "Para realizar uma pesquisa avançada por palavra-chave, use a seguinte sintaxe na barra de pesquisa:",
"faq_a10_p4": "E: %s bicicleta e Rally%s (este é o padrão, então o mesmo que Rally de bicicleta) retornará itens que correspondem a ambas as palavras",
"faq_a10_p5": "Ou: %s bicicleta ou Rally%s irá corresponder itens com uma ou ambas as palavras",
"faq_a10_p6": "Não: %s bicicleta não Rally%s irá coincidir com os itens que contêm bicicleta, mas só se eles não contêm também Rally",
"faq_a10_p7": "Citações: %s\"direitos das mulheres\"%s devolverá itens que têm mulheres seguidas por direitos",
"faq_a10_p8": "Parênteses: %s(bicicleta ou Rally)%s e %s(direitos das mulheres e Reino Unido)%s agruparão operações lógicas dentro dos parênteses como um grupo antes de aplicar os operadores que se juntam aos grupos\n\n",
"faq_a11": "Para aceder a conta a partir de uma versão anterior do Participedia (antes de 2019), terá de repor a palavra-passe utilizando o mesmo endereço de e-mail que utilizou para iniciar sessão no antigo Website. Clique em \"login\" e digite seu endereço de e-mail. Em seguida, clique em \"esqueceu sua senha?\" e siga as instruções para acessar sua conta original e seu conteúdo. Por favor %sentre em contato conosco%s se precisar de ajuda.",
"faq_a12": "Quando estiver conectado, clique no seu avatar de perfil no canto superior direito da tela para visitar sua página de perfil. A partir daí você pode acessar seu conteúdo marcado debaixo da aba marcador de favoritos. Só você pode ver o seu conteúdo marcado. ",
"faq_a13": "As coleções consistem em entradas participantes que compartilham características comuns, como associação com uma iniciativa de grande escala, instituição ou tema específico. As entradas de caso, método e organização são adicionadas às coleções pelos membros da equipe da Participedia. Se você tiver uma sugestão para uma nova coleção, entre em contato conosco.",
"faq_a14_p1": "Em uma página de entrada, existem três campos preenchidos com texto em formato livre gerado pelo usuário, que chamamos de campos de texto aberto, e são o título, a descrição resumida e a narrativa. O restante dos campos são números, datas ou opções fixas e chamamos esses campos de dados fixos. Quando uma entrada é criada, nós a salvamos e depois convertemos automaticamente os campos de texto aberto em todos os outros idiomas suportados. A partir deste ponto, os campos de texto aberto existem como versões bifurcadas para cada idioma, enquanto os campos de dados fixos estão sincronizados entre todos os idiomas. Se você alterar um campo de dados fixo enquanto visualiza o site em qualquer idioma, essa alteração será vista na página de entrada de todos os idiomas. No entanto, se você alterar o título, a descrição resumida ou o texto narrativo, essas alterações serão salvas apenas nesse idioma.",
"faq_a14_p2": "Quando uma entrada é publicada pela primeira vez, traduzimos por máquina os campos Open Text em todos os outros idiomas suportados. A partir deste momento, os campos Open Text existem como versões totalmente separadas (ou seja, \"bifurcadas\") para cada idioma, enquanto os campos Fixed Data são sincronizados entre todos os idiomas. Se você alterar um campo Dados fixos enquanto visualiza o site em qualquer idioma, essa alteração será vista na página de entrada de todos os idiomas. No entanto, se você alterar o texto do Título, Descrição resumida ou Narrativa, essas alterações serão salvas apenas no Texto aberto do idioma em que você está escrevendo.",
"faq_a14_p3": "Clique no botão flutuante \"editar\" localizado no canto inferior direito da página para adicionar informações ou melhorar as traduções automáticas de qualquer entrada.",
"faq_a14_p4": "Para visualizar e editar uma entrada em outro idioma, use o seletor de idiomas suspenso encontrado na barra de menus superior e no rodapé do site para alterar seu idioma preferido.",
"faq_a2": "As inscrições sobre métodos fornecem informações sobre os processos gerais utilizados para orientar a participação pública, como os jurados do cidadão, a votação deliberativa e o orçamento participativo. Por favor, leia nosso %sDiretrizes%s sobre como escrever um método.",
"faq_a3": "As organizações são perfis de grupos formais e informais que projetam, implementam ou apoiam inovações na política participativa e na governança. Por favor, leia nosso %sDiretrizes%s sobre como escrever uma organização.",
"faq_a4": "Os inquéritos/pesquisas são complementares aos dados atuais da Participedia e descrições narrativas, e destinam-se a obter mais informações sobre os resultados e efeitos dos casos. As pesquisas concluídas estão vinculadas aos casos correspondentes. Consulte o %s Página de pesquisa %s para obter mais informações sobre pesquisas.",
"faq_a5": "Para criar uma nova conta, clique em \"login\" na barra de menu principal.",
"faq_a6": "Uma vez que você está conectado, você pode criar conteúdo clicando no botão \"enviar rápido\" no menu principal e escolhendo o tipo de artigo que você gostaria de criar. Por favor, reveja o nosso %sdiretrizes%s sobre como escrever participações no Participedia ou acesse %scontato%s do nosso editor de gerenciamento para mais informações.",
"faq_a7": "Clicar em \"envio rápido\" permite que você publique um caso, um método ou uma organização em minutos. Tudo o que você precisa fornecer é um título. Adicionar um link externo ou uma fonte também é útil.",
"faq_a8": "Ao visualizar uma entrada de caso, método ou organização, clique no ícone de caneta vermelha no canto inferior direito para adicionar ou alterar o conteúdo da entrada.",
"faq_a9_p1": "Para publicar, visualizar e editar uma entrada em outro idioma, use o seletor de idioma suspenso encontrado na barra de menus superior e no rodapé do site para alterar seu idioma preferido.",
"faq_a9_p2": "Se o idioma que você deseja inserir ainda não for suportado em nosso site, %s entre em contato com %s conosco para solicitá-lo. Enquanto isso, você pode usar a versão em inglês do site para enviar sua entrada. Nesse caso, indique o idioma entre colchetes no título da entrada, por exemplo, \"Seu título da entrada [Seu idioma]\".",
"faq_q1": "O que é um caso?",
"faq_q10": "Como faço para pesquisar conteúdo?",
"faq_q11": "Como faço para acessar uma conta de usuário antiga?",
"faq_q12": "Como acesso meu conteúdo marcado?",
"faq_q13": "O que é uma coleção?",
"faq_q14": "Como funciona a tradução?",
"faq_q2": "O que é um método?",
"faq_q3": "O que é uma organização?",
"faq_q4": "O que é uma pesquisa?",
"faq_q5": "Como faço para criar uma nova conta de usuário?",
"faq_q6": "Como faço para criar conteúdo?",
"faq_q7": "O que é envio rápido?",
"faq_q8": "Como faço para editar o conteúdo?",
"faq_q9": "Como faço para criar conteúdo em outro idioma?",
"Faroe Islands": "Ilhas Faroé",
"Featured Case": "Caso em Destaque",
"Featured Collections": "Coleções em destaque",
"Featured Entries": "Entradas em destaque",
"Featured Method": "Método Apresentado",
"Featured Organization": "Organização em Destaque",
"Featured [type]": "Destaque %s",
"Fiji Islands": "Ilhas Fiji",
"Filter": "Filtro",
"filter-for-case": "Filtros para Casos",
"filter-for-method": "Filtros para Métodos",
"filter-for-organizations": "Filtros para Organizações",
"filters": "Filtros",
"Finland": "Finlândia",
"first page": "Primeira página",
"First Submitted By": "Enviado pela primeira vez por",
"First Submitted Date": "Primeira data de submissão",
"first_submitted_label": "Enviado pela primeira vez por",
"focus_areas_sectionlabel": "Áreas de foco",
"for": "Para",
"France": "França",
"French": "Francês",
"French Guiana": "Guiana francesa",
"French Polynesia": "Polinésia francesa",
"French Southern territories": "Terras Austrais Francesas",
"Frequently Asked Questions": "Perguntas Mais Frequentes",
"Funders": "Financiadores",
"Gabon": "Gabão",
"Gambia": "Gâmbia",
"Georgia": "Geórgia",
"German": "Alemão",
"Germany": "Alemanha",
"Get Involved": "Envolva-se",
"Getting Started": "Começando",
"Getting Started as a Content Contributor": "Primeiros passos como contribuidor de conteúdo",
"Getting started guide": "Guia de Introdução",
"getting-started.editors.key_considerations": "Principais considerações para editores",
"getting-started.editors.key_considerations.p0": "Use o site em seu idioma preferido. Todas as alterações de dados fixos são aplicadas em todos os idiomas e as alterações de texto são aplicadas apenas no seu idioma. Leia mais sobre como as traduções funcionam em nosso %s faq %s .",
"getting-started.editors.key_considerations.p1": "Na página %s search %s , use o filtro de pesquisa chamado “completude da entrada” para encontrar entradas listadas como stubs, parcialmente completas ou conteúdo que precisa de citações. Por exemplo, aqui estão %s casos marcados como stubs %s .",
"getting-started.editors.key_considerations.p2": "Adicione informações ou imagens relacionadas a um evento participativo de que você compareceu",
"getting-started.editors.key_considerations.p3": "Use filtros de pesquisa para procurar casos que ocorreram perto de você. Depois de fazer pesquisas, adicione mais conteúdo a essas entradas. Por exemplo, uma entrada pode se beneficiar de links para documentos de suporte e sites externos.",
"getting-started.editors.key_considerations.p4": "Clique no ícone flutuante vermelho “editar” em qualquer entrada para começar.",
"getting-started.editors.p1": "Os editores da equipe do projeto revisam o conteúdo da Participedia, organizam coleções e sinalizam entradas com prompts de edição, como nível de completude e se o conteúdo requer citações. Além disso, todos os usuários são incentivados a ajudar a melhorar as entradas de Participedia feitas por outros contribuidores. Isso pode incluir, por exemplo, coisas tão básicas como melhorar a gramática e a legibilidade, revisar traduções de entradas que foram %s traduzidas por máquina %s para outros idiomas e adicionar imagens ou links para documentos de suporte e sites relevantes. Os usuários com experiência no assunto relevante são convidados a fazer alterações substanciais nas inscrições.",
"getting-started.Looking for more information?": "Procurando mais informações?",
"getting-started.p1": "Qualquer pessoa pode ajudar a documentar iniciativas participativas publicando e editando entradas de crowdsourcing em participedia.net.",
"getting-started.p2": "Participedia é uma plataforma de crowdsourcing e rede global para pesquisadores, educadores, profissionais, formuladores de políticas, ativistas e qualquer pessoa interessada na participação pública e inovações democráticas. O site abriga mais de 1600 casos de mais de 120 países e tem uma comunidade ativa de colaboradores que usam o site para estudar e projetar métodos eficazes de engajamento do cidadão. O site está atualmente disponível em sete idiomas e apresenta dois tipos principais de colaboradores: Editores e Editores.",
"getting-started.p3": "Estamos ansiosos para recebê-lo como editor ou editor do Participedia.net! Uma vez que você começar, você pode encontrar todas as suas contribuições em seu %s página perfil %s .",
"getting-started.p4": "Nosso %s Guia rápido do usuário %s detalha as principais considerações acima. Leia mais %s sobre a Participedia %s , aprenda mais sobre nossa %s pesquisa %s ou confira nossos %s recursos de ensino %s . As respostas para outras perguntas frequentes podem ser encontradas %s aqui %s . Se precisar de ajuda adicional, %s envie %s e-mail para nossa equipe de suporte %s .",
"getting-started.publishers.key_considerations": "Principais considerações para editores",
"getting-started.publishers.key_considerations.p1": "Participedia contém %s três tipos de entrada %s : casos, métodos e organizações. Leia mais sobre os tipos de entrada em nosso %s faq %s .",
"getting-started.publishers.key_considerations.p2": "Como a Wikipedia, a Participedia se concentra na documentação ao invés da persuasão ou opinião.",
"getting-started.publishers.key_considerations.p3": "Todo o conteúdo deve ser citado para que os leitores possam verificar as fontes originais.",
"getting-started.publishers.key_considerations.p4": "As contribuições devem ser provenientes de fontes confiáveis, sempre que estiverem disponíveis, como artigos acadêmicos, relatórios, avaliações oficiais, sites oficiais das organizações envolvidas ou meios de comunicação.",
"getting-started.publishers.key_considerations.p5": "Use o site em seu idioma preferido. As novas entradas são traduzidas automaticamente em todos os idiomas suportados, mas apenas na primeira vez em que são publicadas. Leia mais sobre como as traduções funcionam em nosso %s faq %s .",
"getting-started.publishers.key_considerations.p6": "Escreva na terceira pessoa, não na primeira pessoa.",
"getting-started.publishers.key_considerations.p7": "Clique no botão %s “Envio rápido” %s no desktop ou no “+” no celular para começar.",
"getting-started.publishers.p1": "Muitas pessoas que publicam novas entradas na Participedia são estudantes, praticantes ou organizadores de eventos participativos. Os alunos podem receber trabalhos de curso que envolvam pesquisa e documentação de iniciativas participativas, como %s esta coleção %s desenvolvida por graduados do Coady International Institute na St. Francis Xavier University. Praticantes e ativistas usam o site para documentar e divulgar métodos, casos e organizações.",
"getting-started.publishers.p2": "As pessoas que publicam entradas na Participedia se beneficiam do aumento da descoberta de seu trabalho, ao mesmo tempo que contribuem para um esforço colaborativo para documentar iniciativas participativas. O conteúdo com que os “participantes” contribuem torna possível que outros explorem um grande e diversificado banco de dados de exemplos de casos inspiradores e os métodos que os informam.",
"Ghana": "Gana",
"Gibraltar": "Gibraltar",
"Got it": "Consegui",
"gov_of_canada": "Governo do Canadá",
"Greece": "Grécia",
"Greenland": "Groenlândia",
"Grenada": "Granada",
"grid view": "Exibição de grade",
"Guadeloupe": "Guadalupe",
"Guam": "Guam",
"Guatemala": "Guatemala",
"guidelines_info_link": "Para obter mais informações sobre este formulário, consulte nossas %s diretrizes %s .",
"Guinea": "Guiné",
"Guinea-Bissau": "Guiné-Bissau",
"Guyana": "Guiana",
"Haiti": "Haiti",
"Heard Island and McDonald Islands": "Ilha Heard e Ilhas McDonald",
"Help & Contact": "Ajuda e Contato",
"Holy See (Vatican City State)": "Cidade do Vaticano",
"Home": "Principal",
"home.about.p1": "Nossa missão é fortalecer e mobilizar o conhecimento sobre as inovações democráticas participativas em todo o mundo.",
"home.about.p2": "Nós fornecemos um modelo de código aberto para crowdsourcing e organização de dados sobre a participação pública. Seu conteúdo é gerado e usado por diversas redes de pesquisadores, educadores, profissionais, legisladores e ativistas.",
"home.contribute.Help expand our database": "Ajude a expandir nosso banco de dados editando o conteúdo existente ou publicando o seu próprio. A publicação de entradas na Participedia fornece maior descoberta de seu trabalho, ao mesmo tempo em que contribui para um esforço colaborativo para documentar exemplos de participação pública e inovação democrática.",
"home.explore our database": "Explore nosso banco de dados de casos, métodos e organizações usando a barra de pesquisa acima, %s baixe os dados em arquivos csv %s ou %s explore entradas por localização %s .",
"home.newsletter.p1": "Inscreva-se no nosso boletim da comunidade! Compartilhamos as informações mais recentes sobre inovações democráticas participativas em todo o mundo, histórias de nossa grande comunidade de parceiros e colaboradores, convites para conferências e eventos futuros e muito mais.",
"home.supporters.p1": "A Participedia é apoiada pelo %s Conselho de Pesquisa em Ciências Sociais e Humanas do Canadá %s (SSHRC) por meio de uma Bolsa de Parceria.",
"home.supporters.p2": "A equipe de design e tecnologia da Participedia opera no %s Studio for Extensive Aesthetics %s na Emily Carr University of Art & Design e é apoiada pelo %s Canada Research Chairs Program %s e pela %s Canada Foundation for Innovation %s .",
"home.teach.Use Participedia in the classroom": "Use a Participedia em sala de aula para envolver os alunos e mostrar suas pesquisas.",
"home.verify_email.text": "Por favor verifique seu endereço de email. Se você não recebeu o e-mail, verifique sua caixa de spam ou tente %s reenviar o e-mail de verificação %s .",
"home.verify_email.title": "Verifique seu e-mail",
"home_hero.feature.5600": "Pesquisa Participativa sobre o Descomissionamento dos Serviços Sociais da África do Sul",
"home_hero.feature.5988": "Processo participativo de urbanização de favelas na cidade de Buenos Aires: o caso \"Villa 20\"",
"home_hero.feature.6590": "Protestos de George Floyd",
"home_hero_tagline": "Uma rede global e plataforma de crowdsourcing para pesquisadores, educadores, profissionais, formuladores de políticas, ativistas e qualquer pessoa interessada na participação pública e inovações democráticas",
"Honduras": "Honduras",
"Hong Kong": "Hong Kong",
"How does translation work?": "Como funciona a tradução?",
"how_does_translation_work_p1": "Em uma página de entrada, existem três campos preenchidos com texto de formulário livre gerado pelo usuário. Chamamos esses campos de \"Texto aberto\" e são Título, Descrição resumida e Narrativa. O restante dos campos são números, datas ou opções fixas - chamamos esses campos de \"Dados fixos\".",
"how_does_translation_work_p2": "Quando uma entrada é publicada pela primeira vez, traduzimos por máquina os campos Open Text em todos os outros idiomas suportados. A partir deste momento, os campos Open Text existem como versões totalmente separadas (ou seja, \"bifurcadas\") para cada idioma, enquanto os campos Fixed Data são sincronizados entre todos os idiomas. Se você alterar um campo Dados fixos enquanto visualiza o site em qualquer idioma, essa alteração será vista na página de entrada de todos os idiomas. No entanto, se você alterar o texto do Título, Descrição resumida ou Narrativa, essas alterações serão salvas apenas no Texto aberto do idioma em que você está escrevendo.",
"how_does_translation_work_p3": "Clique no botão flutuante \"editar\" localizado no canto inferior direito da página para adicionar informações ou melhorar as traduções automáticas de qualquer entrada.",
"how_does_translation_work_p4": "Para visualizar e editar uma entrada em outro idioma, use o seletor de idiomas suspenso encontrado na barra de menus superior e no rodapé do site para alterar seu idioma preferido.",
"Human & Political Rights": "Direitos Humanos e Políticos",
"Hungary": "Hungria",
"Iceland": "Islândia",
"Image credit": "Crédito da imagem",
"India": "Índia",
"Indonesia": "Indonésia",
"Iran": "Irã",
"Iraq": "Iraque",
"Ireland": "Irlanda",
"Israel": "Israel",
"issues": "Questões",
"Italian": "Itália",
"Italy": "Itália",
"Ivory Coast": "Costa do Marfim",
"Jamaica": "Jamaica",
"Japan": "Japão",
"Join Now": "Acesse agora",
"Jordan": "Jordânia",
"Kazakhstan": "Cazaquistão",
"Kenya": "Quênia",
"Kiribati": "Kiribati",
"know_other_lang": "%s Você conhece outro idioma? %s",
"Kuwait": "Kuwait",
"Kyrgyzstan": "Quirguistão",
"language_instructional": "Defina o idioma que você prefere ler e contribuir.",
"language_label": "Língua/ Idioma",
"language_placeholder": "Escolha um idioma",
"language_select_placeholder": "Selecione um idioma",
"Laos": "Laos",
"Last Edited": "Última edição",
"last page": "Última página",
"Latvia": "Letônia",
"Lead Designer & Communities Coordinator": " Designer Principal e Coordenador de Comunidades\n\n\n",
"Lead Developer": "Desenvolvedor líder",
"Lead Graphic Designer": "Designer gráfico principal",
"Lebanon": "Líbano",
"Lesotho": "Lesoto",
"level_complexity_instructional": "Selecione o nível de complexidade que esse método pode manipular.",
"level_complexity_label": "Nível de complexidade este método pode lidar",
"level_complexity_placeholder": "Selecione o nível de complexidade",
"level_polarization_instructional": "Selecione o nível de polarização política que este método pode suportar",
"level_polarization_label": "Nível de polarização que este método pode manipular",
"level_polarization_placeholder": "Selecione o nível de polarização",
"Liberia": "Libéria",
"Libyan Arab Jamahiriya": " Líbia",
"Liechtenstein": "Liechtenstein",
"links_link_instructional": "Se houver um site principal para este caso, insira-o aqui. Adicione links para fontes adicionais para que os leitores e editores possam encontrar mais informações sobre este caso online. ",
"links_url_placeholder": "Adicionar link",
"list view": "Exibição de lista",
"Lithuania": "Lituânia",
"location": "Localização",
"location_label": "Localização",
"location_sectionlabel": "Localização",
"Login": "Login",
"Luxembourg": "Luxemburgo",
"Macao": "Macau",
"Madagascar": "Madagascar",
"main_tagline": "Uma plataforma de crowdsourcing para pesquisadores, ativistas, profissionais e qualquer pessoa interessada em participação pública e inovações democráticas",
"Malawi": "Malawi",
"Malaysia": "Malásia",
"Maldives": "Maldivas",
"Mali": "Mali",
"Malta": "Malta",
"Managing Director": "Diretor",
"Managing Editor": "Editor Chefe",
"map information": "informações do mapa",
"Marshall Islands": "Ilhas Marshall",
"Martinique": "Martinica",
"Mauritania": "Mauritânia",
"Mauritius": "Maurício",
"Mayotte": "Mayotte",
"media_sectionlabel": "Mídia",
"Members": "Membros",
"member_since": "Membro desde",
"Method": "Método",
"method": "Método",
"Methodology": "Metodologia",
"Methods": "Métodos",
"methods of": "métodos de",
"method_edit_audio_attribution_instructional": "Quem é o proprietário original ou criador deste áudio?",
"method_edit_audio_attribution_placeholder": "Proprietário ou criador",
"method_edit_audio_link_instructional": "Adicione links para áudio, como podcasts.",
"method_edit_audio_link_label": "Áudio",
"method_edit_audio_title_instructional": "Forneça um título ou uma descrição deste áudio em até 10 palavras ou menos.",
"method_edit_audio_title_placeholder": "Título ou descrição",
"method_edit_audio_url_placeholder": "Adicionar link para áudio",
"method_edit_body_instructional": "A estrutura padrão a seguir facilita a comparação e a análise de entradas. Por favor, use os cabeçalhos abaixo e consulte nossas <a href=\"https://goo.gl/p6HYNk\" target=\"_blank\">diretrizes</a> ao preparar sua entrada.",
"method_edit_body_label": "Narrativa",
"method_edit_body_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"method_edit_body_placeholder": "<h2>Problemas e propósitos</h2><h2>Origens e desenvolvimento</h2><h2>Recrutamento e seleção de participantes</h2><h2>Como funciona: processo, interação e tomada de decisão</h2><h2>Influência, resultados e efeitos</h2><h2>Análise e lições aprendidas</h2><h2>Ver também</h2><h2>Referências</h2><h2>Links externos</h2><h2>Notas</h2>",
"method_edit_collections_instructional": "Se você é um representante de um projeto ou organização que foi identificado como tendo uma coleção na Participedia, selecione-o aqui. Se a sua entrada não faz parte de uma coleção, por favor, deixe este campo em branco.",
"method_edit_collections_label": "Coleções",
"method_edit_collections_placeholder": "Selecione uma coleção",
"method_edit_completeness_label": "Completude da entrada",
"method_edit_completeness_placeholder": "Selecione o nível de completude para esta entrada",
"method_edit_decision_methods_instructional": "Selecione até três tipos de tomada de decisão que são compatíveis com este método, com \"1\" indicando a forma mais típica de tomada de decisão.",
"method_edit_decision_methods_label": "Métodos de decisão",
"method_edit_decision_methods_placeholder": "Como são tomadas as decisões?",
"method_edit_description_instructional": "Digite a descrição desse método em até (280 caracteres ou menos)",
"method_edit_description_label": "Descrição breve",
"method_edit_description_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"method_edit_description_placeholder": "Digite a descrição ",
"method_edit_facetoface_online_or_both_instructional": "Os participantes podem usar esse método de interação cara a cara, on-line ou ambos?",
"method_edit_facetoface_online_or_both_label": "Cara a cara, online, ou ambos?",
"method_edit_facetoface_online_or_both_placeholder": "A interação é cara a cara ou on-line?",
"method_edit_facilitators_instructional": "Esse método requer um facilitador em algum momento durante o processo?",
"method_edit_facilitators_label": "Facilitação",
"method_edit_facilitators_placeholder": "São necessários facilitadores?",
"method_edit_featured_instructional": "Os artigos em destaque são exibidos primeiro na página inicial",
"method_edit_featured_label": "Destaque",
"method_edit_files_attribution_instructional": "Quem é o proprietário original ou criador deste arquivo?",
"method_edit_files_attribution_placeholder": "Proprietário ou criador",
"method_edit_files_instructional": "Carregue os documentos relevantes aqui. Os tipos de arquivo suportados incluem: RTF, txt, Doc, docx, xls, xlsx, PDF, ppt, pptx, PPS, ppsx, odt, ODS e odp. O tamanho máximo do arquivo é 5MB.",
"method_edit_files_label": "Arquivos",
"method_edit_files_placeholder": "Clique para selecionar ou arrastar e soltar arquivos aqui",
"method_edit_files_source_url_instructional": "Se aplicável, forneça um link para onde o arquivo original foi originado.",
"method_edit_files_source_url_placeholder": "Link para o original",
"method_edit_files_title_instructional": "Forneça um título ou uma descrição deste arquivo em até 10 palavras ou menos.",
"method_edit_files_title_placeholder": "Título ou descrição",
"method_edit_hidden_instructional": "Artigos ocultos não aparecerão nos resultados da pesquisa",
"method_edit_hidden_label": "Escondidos",
"method_edit_if_voting_instructional": "Selecione até três maneiras de como os votos são feitos com este método, com \"1\"\nindicando a forma mais típica de votação.",
"method_edit_if_voting_label": "Se votar",
"method_edit_if_voting_placeholder": "Que tipo de votação é usada?",
"method_edit_level_complexity_info": "Um exemplo da baixa complexidade seria uma decisão da vizinhança sobre o equipamento apropriado para área de lazer de um parque. Questões mais complexas envolvem altos níveis de complexidade técnica/científica, são altamente interdependentes com outras questões, e exigem soluções que são baseadas no balanceamento de trade-offs entre diferentes metas e valores. Alguns exemplos de questões altamente complexas incluem a reforma dos cuidados de saúde, as alterações climáticas ou a migração.",
"method_edit_level_complexity_instructional": "Selecione o nível de complexidade que esse método pode suportar.",
"method_edit_level_complexity_label": "Nível de complexidade este método pode suportar",
"method_edit_level_complexity_placeholder": "Selecione o nível de complexidade",
"method_edit_level_polarization_info": "Selecione o nível de polarização política em que este método pode lidar. Informações: existe baixa polarização quando uma iniciativa de participação pública pode assumir um acordo básico sobre metas, como o desejo das pessoas por serviços de incêndio de emergência. Existe alta polarização quando as atitudes públicas são fortemente divididas entre duas ou mais opções. Isso geralmente está associado ao partidarismo, animosidades de longa data e baixa confiança.",
"method_edit_level_polarization_instructional": "Selecione o nível de polarização política que este método pode suportar.",
"method_edit_level_polarization_label": "Nível de polarização este método pode suportar",
"method_edit_level_polarization_placeholder": "Selecione o nível de polarização",
"method_edit_links_attribution_instructional": "Quem é o proprietário ou criador original deste conteúdo vinculado?",
"method_edit_links_attribution_placeholder": "Proprietário ou criador",
"method_edit_links_link_instructional": "Se houver um site principal para este método, insira-o aqui. Adicione links para fontes adicionais para que os leitores e editores possam encontrar mais informações sobre esse método online.",
"method_edit_links_link_label": "Links",
"method_edit_links_title_instructional": "Forneça um título ou uma descrição deste conteúdo vinculado em até 10 palavras ou menos.",
"method_edit_links_title_placeholder": "Título ou descrição",
"method_edit_links_url_placeholder": "Adicionar link",
"method_edit_method_types_info": "Existe uma variedade enorme de métodos participativos. Para ajudar a reduzi-lo, selecione e classifique até três dos seguintes tipos de métodos que melhor descrevem o método específico que você está inserindo. A especificação de qual tipo de método é sua entrada facilita a localização dos usuários da Participedia.\n",
"method_edit_method_types_instructional": "Selecione e classifique até três tipos que melhor descrevem esse método, com \"1\" indicando o mais relevante.",
"method_edit_method_types_label": "Tipo geral de método",
"method_edit_method_types_placeholder": "Selecione e classifique até 3 tipos",
"method_edit_number_of_participants_instructional": "Selecione e classifique até três tamanhos de grupo que esse método pode utilizado, com \"1\" indicando o tamanho ideal.",
"method_edit_number_of_participants_label": "Número de participantes",
"method_edit_number_of_participants_placeholder": "Selecione e classifique até 3 tamanhos",
"method_edit_open_limited_instructional": "Esse método normalmente é aberto a todos, limitado a certas pessoas, ou ambos?",
"method_edit_open_limited_label": "Aberto a todos ou limitado a alguns?",
"method_edit_open_limited_placeholder": "Isso está aberto a todos ou limitados a alguns?",
"method_edit_participants_interactions_instructional": "Selecione e classifique até três tipos de interação que podem ser realizadas entre os participantes usando esse método, com \"1\" indicando a forma mais típica.",
"method_edit_participants_interactions_label": "Tipos de interação entre os participantes",
"method_edit_participants_interactions_placeholder": "Selecionar e classificar até 3 tipos de interação",
"method_edit_photos_attribution_instructional": "Quem é o dono original ou criador desta imagem?",
"method_edit_photos_attribution_placeholder": "Proprietário ou criador",
"method_edit_photos_instructional": "Faça upload de imagens aqui. Os tipos de arquivo suportados incluem: jpg, jpeg e png. O tamanho máximo do arquivo é 5 MB. Para obter melhores resultados, carregue uma imagem recortada na proporção de 16:9, de preferência com pelo menos 640 pixels de largura por 360 pixels de altura.",
"method_edit_photos_label": "Imagens",
"method_edit_photos_placeholder": "Clique para selecionar, arrastar e/ou soltar as imagens aqui",
"method_edit_photos_source_url_instructional": "Se aplicável, forneça um link para onde a imagem original foi proveniente.",
"method_edit_photos_source_url_placeholder": "Link para o original",
"method_edit_photos_title_instructional": "Forneça um título ou uma descrição desta imagem em até 10 palavras ou menos.",
"method_edit_photos_title_placeholder": "Título ou descrição",
"method_edit_public_spectrum_info": "O espectro IAP2 de participação pública é projetado para identificar o nível de participação pública dentro de qualquer processo de engajamento da Comunidade. Cada nível aumenta a quantidade de influência que o público pode ter sobre a tomada de decisão final, e o espectro pressupõe que a escolha de um nível mais alto engloba os níveis abaixo.",
"method_edit_public_spectrum_instructional": "Que parte do espectro IAP2 de participação pública este método melhor se encontra?",
"method_edit_public_spectrum_label": "Espectro de participação pública",
"method_edit_public_spectrum_placeholder": "Selecione 1 parte do espectro",
"method_edit_purpose_method_instructional": "Selecione e classifique até três finalidades que este método serve melhor, com \"1\" indicando o mais relevante. ",
"method_edit_purpose_method_label": "Finalidade típica",
"method_edit_purpose_method_placeholder": "Selecione e classifique até 3 finalidades",
"method_edit_recruitment_method_instructional": "Que técnica este método usa para recrutar um subconjunto limitado da população como participantes?",
"method_edit_recruitment_method_label": "Método de recrutamento para subconjunto limitado de população",
"method_edit_recruitment_method_placeholder": "Selecione o método de recrutamento",
"method_edit_scope_of_influence_instructional": "Selecione até três limites geográficos ou jurisdicionais dentro dos quais esse método pode ser implementado.",
"method_edit_scope_of_influence_label": "Escopo de implementação",
"method_edit_scope_of_influence_placeholder": "Selecione a área geográfica ou jurisdicional",
"method_edit_title_instructional": "Atribua a esse método um nome descritivo em até 10 palavras ou menos.",
"method_edit_title_label": "Título do método",
"method_edit_title_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"method_edit_title_placeholder": "Digite o título em até 10 palavras ou menos",
"method_edit_verified_instructional": "As entradas verificadas foram revisadas pelo conselho editorial da Participedia e só podem ser editadas por administradores.",
"method_edit_verified_label": "Verificado",
"method_edit_videos_attribution_instructional": "Quem é o dono original ou criador deste vídeo?",
"method_edit_videos_attribution_placeholder": "Proprietário ou criador",
"method_edit_videos_link_instructional": "Adicione um link de vídeo do Vimeo ou YouTube.",
"method_edit_videos_link_label": "Vídeos",
"method_edit_videos_title_instructional": "Forneça um título ou uma descrição deste vídeo em até 10 palavras ou menos.",
"method_edit_videos_title_placeholder": "Título ou descrição",
"method_edit_videos_url_placeholder": "Adicionar link de vídeo (Vimeo ou YouTube)",
"method_view_audio_label": "Áudio",
"method_view_body_label": "Narrativa",
"method_view_collections_label": "Coleções",
"method_view_completeness_label": "Completude de entrada",
"method_view_decision_methods_label": "Métodos de decisão",
"method_view_description_label": "Descrição breve",
"method_view_facetoface_online_or_both_label": "Cara a cara, online, ou ambos?",
"method_view_facilitators_label": "Facilitação",
"method_view_files_label": "Arquivos",
"method_view_if_voting_label": "Se votar",
"method_view_level_complexity_label": "Nível de complexidade este método pode suportar",
"method_view_level_polarization_label": "Nível de polarização este método pode lidar",
"method_view_links_label": "Links",
"method_view_method_types_label": "Tipo geral de método",
"method_view_number_of_participants_label": "Número de participantes",
"method_view_open_limited_label": "Aberto a todos ou limitado a alguns?",
"method_view_participants_interactions_label": "Tipos de interação entre os participantes",
"method_view_photos_label": "Imagens",
"method_view_public_spectrum_label": "Espectro de participação pública",
"method_view_purpose_method_label": "Finalidade típica",
"method_view_recruitment_method_label": "Método de recrutamento para subconjunto limitado de população",
"method_view_scope_of_influence_label": "Escopo de implementação",
"method_view_title_label": "Título do método",
"method_view_videos_label": "Vídeos",
"Mexico": "México",
"Micronesia, Federated States of": "Estados Federados da Micronésia",
"Mission": "Missão",
"mission.p1": "Participedia é uma rede global e plataforma de crowdsourcing para pesquisadores, educadores, profissionais, formuladores de políticas, ativistas e qualquer pessoa interessada em inovações democráticas. Por democrático, queremos dizer práticas ou instituições que potencialmente promovem ideais de autogoverno - individualmente, coletivamente e através do tempo, espaço e geografia. Por inovações, queremos dizer práticas ou instituições que são relativamente novas para um contexto ou lugar. Nossa missão é mobilizar o conhecimento sobre as práticas e instituições que melhoram a democracia que as pessoas estão inventando, remodelando, protegendo e transferindo de outros contextos.",
"mission.p2": "Embora comprometida com os ideais democráticos, a Participédia não promove nenhuma agenda ideológica, programática, institucional ou governamental. Acreditamos que existem muitas maneiras de fazer avançar a democracia e que variam de acordo com o local, a história, a cultura e os desafios baseados no contexto. Reconhecemos as desigualdades existentes na coleta, teorização e mobilização do conhecimento sobre as formas não ocidentais de inovações democráticas. A Participedia está empenhada em trabalhar para resolver esse desequilíbrio. Também reconhecemos que nem todos os casos e métodos documentados pela Participedia promoverão a democracia e que os impactos variam de acordo com o contexto. “Nossa missão é mobilizar conhecimento sobre as práticas e instituições que fomentam a democracia, que embasem as respostas à pergunta: Que tipo de inovação democrática funciona melhor, para quais propósitos e em que condições?",
"mission.p3": "A Fase 1 da Participedia enfatizou as inovações democráticas na governança participativa. A Fase 2 da Participedia, lançada em junho de 2021, está se expandindo para incluir uma gama mais ampla de práticas e instituições que potencialmente apóiam ideais democráticos, incluindo inovações em direitos humanos e políticos, responsabilidade democrática, representação democrática, democracia internacional e comunicações digitais. A Fase 2 reconhece que o projeto democrático se baseia em ecologias complexas de práticas e instituições e desenvolverá a infraestrutura conceitual necessária para capturar esses domínios mais amplos de inovações democráticas por meio de crowdsourcing.",
"Moldova": "Moldávia",
"Monaco": "Mônaco",
"Mongolia": "Mongólia",
"Montserrat": "Montserrat",
"More about this collection": "Mais sobre esta coleção",
"Morocco": "Marrocos",
"Most Recent Change": "Alteração mais recente",
"Most Recent Changes By": "Alterações mais recentes realizadas por",
"most_recent_label": "Alterações mais recentes por",
"Mozambique": "Moçambique",
"Myanmar": "Mianmar",
"name:approaches-key:advocacy": "Advocacy (defesa e argumentação em favor de uma causa)",
"name:approaches-key:advocacy-longValue": "Advocacy(por exemplo, lobby; petição)",
"name:approaches-key:citizenship": "Construção da cidadania",
"name:approaches-key:citizenship-longValue": "Construção de cidadania (por exemplo, oportunidades para as pessoas aprenderem sobre seus direitos e revindicar pelos mesmos)",
"name:approaches-key:civil": "Construção da sociedade civil",
"name:approaches-key:civil-longValue": "Construção da sociedade civil (por exemplo, construção de redes entre fronteiras governamentais e sociais)",
"name:approaches-key:cogovernance": "Co-governança",
"name:approaches-key:cogovernance-longValue": "Co-governança (por exemplo, colaboração na tomada de decisões com órgãos públicos e governamentais)",
"name:approaches-key:consultation": "Consulta (por exemplo, audiências públicas)",
"name:approaches-key:consultation-longValue": "Consulta (por exemplo, audiências públicas)",
"name:approaches-key:coproduction": "Coprodução em forma de parceria e/ou contrato com órgãos governamentais e/ou públicos\n\n",
"name:approaches-key:coproduction-longValue": "Co-produção em forma de parceria e / ou contrato com o governo e / ou órgãos públicos (por exemplo, colaboração com o governo para fornecer moradias acessíveis)",
"name:approaches-key:coproduction_form": "Co-produção em forma de parceria e / ou contrato com organizações privadas",
"name:approaches-key:coproduction_form-longValue": "Co-produção em forma de parceria e / ou contrato com organizações privadas (por exemplo, colaboração com empresas ou sociedade civil)",
"name:approaches-key:direct": "Tomada de decisão direta",
"name:approaches-key:direct-longValue": "Tomada de decisão direta (por exemplo, referendos)",
"name:approaches-key:evaluation": "Avaliação, fiscalização e auditoria social",
"name:approaches-key:evaluation-longValue": "Avaliação, supervisão e auditoria social (por exemplo, medir e relatar o desempenho organizacional)",
"name:approaches-key:independent": "Ação independente",
"name:approaches-key:independent-longValue": "Ação independente (sem a participação de órgãos governamentais ou privados)",
"name:approaches-key:informal": "Engajamento informal de intermediários com autoridades não governamentais",
"name:approaches-key:informal-longValue": "Engajamento informal de intermediários com autoridades não governamentais (por exemplo, barganha e negociações em nome de setores marginalizados)",
"name:approaches-key:informal_engagement": "Envolvimento informal dos intermediários com as autoridades políticas",
"name:approaches-key:informal_engagement-longValue": "Engajamento informal de intermediários com autoridades políticas (por exemplo, barganha e negociações em nome de setores marginalizados)",
"name:approaches-key:leadership": "Desenvolvimento de lideranças",
"name:approaches-key:leadership-longValue": "Desenvolvimento de liderança (por exemplo, capacidade individual e de grupo para envolvimento cívico)",
"name:approaches-key:protest": "Protesto (por exemplo: manifestações,marchas, greves ) ",
"name:approaches-key:protest-longValue": "Protesto (por exemplo, manifestações; marchas; piquetes) ",
"name:approaches-key:research": "Pesquisa",
"name:approaches-key:research-longValue": "Pesquisa (por exemplo, pesquisas de opinião pública; grupos focais; pesquisa-ação participativa)",
"name:approaches-key:social": "Mobilização social",
"name:approaches-key:social-longValue": "Mobilização social (por exemplo, organização comunitária; conscientização; consumismo político) ",
"name:change_types-key:changes": "Mudanças no conhecimento, atitudes e comportamento das pessoas",
"name:change_types-key:changes_civic": "Mudanças nas capacidades cívicas",
"name:change_types-key:changes_civic-longValue": "Mudanças nas capacidades cívicas (por exemplo, melhoria da resolução de problemas comunitários)",
"name:change_types-key:changes_how": "Mudanças na forma como as instituições operam",
"name:change_types-key:changes_how-longValue": "Alterações na forma como as instituições operam (por exemplo, melhoria da tomada de decisão)",
"name:change_types-key:changes_public": "Mudanças na política pública",
"name:change_types-key:changes_public-longValue": "Alterações na política pública (por exemplo, novas leis ou regulamentos)",
"name:change_types-key:conflict": "Transformação de conflitos",
"name:collections-key:coady_students": "Graduados no Instituto Coady",
"name:collections-key:covid_19_response": "Resposta do Covid-19",
"name:collections-key:gov_of_canada": "Governo do Canadá",
"name:collections-key:latinno": "LATINNO",
"name:collections-key:participedia_team": "Equipe participedia",
"name:collections-key:sciencewise": "Sciencewise (O programa Sciencewise é financiado pelo Departamento de Negócios, Energia e Estratégia Industrial e gerenciado pela Pesquisa e Inovação do Reino Unido . A iniciativa fornece assistência aos formuladores de políticas para realizar um diálogo público para informar suas tomadas de decisão sobre questões de ciência e tecnologia). ",
"name:collections-key:uarkansas_students": "Universidade de Arkansas, Clinton School of Public Service Students ( Escola Clinton de Serviços Públicos)",
"name:collections-key:usoton_students": "Estudantes da Universidade de Southampton",
"name:completeness-key:complete": "Completa",
"name:completeness-key:partial_citations": "Citações/Notas de Rodapé Necessárias",
"name:completeness-key:partial_content": "Parcial (cerca de metade completa)",
"name:completeness-key:partial_editing": "Gramática / Edições ortográficas necessárias",
"name:completeness-key:stub": "Esboço (menos da metade completa)",
"name:de": "Alemão",
"name:decision_methods-key:dont": "Não sei",
"name:decision_methods-key:general": "Acordo geral/consenso",
"name:decision_methods-key:general-longValue": "Acordo geral/consenso (ou seja, ampla aceitação de decisões; acordo unânime desejado, mas não necessário)",
"name:decision_methods-key:idea": "Geração de ideias",
"name:decision_methods-key:idea-longValue": "Geração de ideias (ou seja, soluções potenciais foram geradas, mas não foram decididas prioridades)",
"name:decision_methods-key:n/a": "Não aplicável",
"name:decision_methods-key:n/a-longValue": "Não aplicável (por exemplo, os votos não são obtidos em manifestações de protesto)",
"name:decision_methods-key:na": "Não aplicável",
"name:decision_methods-key:na-longValue": "Não aplicável (por exemplo, os votos geralmente não são obtidos em manifestações de protesto)\n",
"name:decision_methods-key:opinion": "Pesquisa de opinião",
"name:decision_methods-key:opinion-longValue": "Pesquisa de opinião (ou seja, realizada antes e / ou depois da convocação dos participantes)",
"name:decision_methods-key:voting": "Votação",
"name:decision_methods-key:voting-longValue": "Votação (ou seja, qualquer tipo de voto formal; por favor, forneça mais detalhes no próximo campo)\n\n",
"name:en": "Inglês",
"name:es": "Espanhol",
"name:facetoface_online_or_both-key:both": "Ambos",
"name:facetoface_online_or_both-key:facetoface": "Face a face",
"name:facetoface_online_or_both-key:online": "Online",
"name:facilitators-key:no": "Não",
"name:facilitators-key:not_applicable": "Não aplicável",
"name:facilitators-key:yes": "Sim",
"name:facilitator_training-key:professional": "Facilitadores profissionais",
"name:facilitator_training-key:trained": "Capacitado, facilitadores não - profissionais",
"name:facilitator_training-key:untrained": "Não capacitados, facilitadores não-profissionais",
"name:formal_evaluation-key:no": "Não",
"name:formal_evaluation-key:yes": "Sim",
"name:fr": "Francês",
"name:funder_types-key:academic": "Instituição acadêmica",
"name:funder_types-key:activist": "Rede ativista",
"name:funder_types-key:community": "Organização de base comunitária",
"name:funder_types-key:faithbased": "Organização de cunho religioso",
"name:funder_types-key:forprofit": "Negócios com fins lucrativos",
"name:funder_types-key:governmentowned": "Corporação de Propriedade do governo",
"name:funder_types-key:individual": "Individual",
"name:funder_types-key:international": "Organização internacional",
"name:funder_types-key:labortrade": "Trabalhista/sindical",
"name:funder_types-key:local": "Governo local",
"name:funder_types-key:local-longValue": "Governo local (por exemplo, vila e/ou cidade)",
"name:funder_types-key:n/a": "Não aplicável",
"name:funder_types-key:national": "Governo nacional",
"name:funder_types-key:nongovernmental": "Organização não governamental",
"name:funder_types-key:philanthropic": "Organização filantrópica",
"name:funder_types-key:regional": "Governo regional",
"name:funder_types-key:social": "Movimento social",
"name:general_issues-key:agriculture": "Agricultura, silvicultura, pesca e Indústrias de mineração",
"name:general_issues-key:arts": "Artes, cultura e recreação",
"name:general_issues-key:business": "Negócio",
"name:general_issues-key:economics": "Economia",
"name:general_issues-key:education": "Educação",
"name:general_issues-key:energy": "Energia",
"name:general_issues-key:environment": "Ambiente",
"name:general_issues-key:governance": "Governança e instituições políticas",
"name:general_issues-key:governance-longValue": "Governança e instituições políticas (por exemplo, Constituições, sistemas jurídicos, sistemas eleitorais)",
"name:general_issues-key:health": "Saúde",
"name:general_issues-key:housing": "Habitação",
"name:general_issues-key:human": "Direitos humanos e direitos civis",
"name:general_issues-key:identity": "Identidade e diversidade",
"name:general_issues-key:immigration": "Imigração e migração",
"name:general_issues-key:international": "Assuntos internacionais",
"name:general_issues-key:labor": "Trabalho",
"name:general_issues-key:law": "Aplicação da lei, justiça criminal e correções",
"name:general_issues-key:media": "Mídia, telecomunicações & informação",
"name:general_issues-key:national": "Segurança nacional",
"name:general_issues-key:planning": "Planejamento e desenvolvimento",
"name:general_issues-key:science": "Ciência e tecnologia",
"name:general_issues-key:social": "Previdência social",
"name:general_issues-key:transportation": "Transporte",
"name:if_voting-key:dont": "Não sei",
"name:if_voting-key:majoritarian": "Voto majoritário",
"name:if_voting-key:majoritarian-longValue": "Votação majoritária (Ou seja, 50% + 1)",
"name:if_voting-key:plurality": "Pluralidade",
"name:if_voting-key:plurality-longValue": "Pluralidade (ou seja, maior percentual vence, mesmo que a proposta receba menos de 50,1% de votos)",
"name:if_voting-key:preferential": "Votação preferencial",
"name:if_voting-key:preferential-longValue": "Votação preferencial (ou seja, preferências classificadas)",
"name:if_voting-key:supermajoritarian": "Super-Majoritário",
"name:if_voting-key:supermajoritarian-longValue": "Super-majoritário (ou seja, superior a 50% + 1)",
"name:if_voting-key:unanimous": "Decisão unânime",
"name:if_voting-key:unanimous-longValue": "Decisão unânime (ou seja, total concordância de todos os participantes)",
"name:impact_evidence-key:no": "Não",
"name:impact_evidence-key:yes": "Sim",
"name:implementers_of_change-key:appointed": "Funcionários públicos nomeados",
"name:implementers_of_change-key:appointed-longValue": "Funcionários públicos nomeados (por exemplo, burocratas)",
"name:implementers_of_change-key:corporations": "Corporações",
"name:implementers_of_change-key:dont": "Não sei",
"name:implementers_of_change-key:elected": "Funcionários públicos eleitos",
"name:implementers_of_change-key:experts": "Especialistas",
"name:implementers_of_change-key:experts-longValue": "Especialista técnico/perito (por exemplo, cientistas, engenheiros, criminologistas, médicos, advogados)",
"name:implementers_of_change-key:lay": "Público leigo",
"name:implementers_of_change-key:lay-longValue": "Público leigo (ou seja, pessoas sem participação profissional nas questões) ",
"name:implementers_of_change-key:stakeholder": "Organizações de partes interessadas (Stakeholders)",
"name:implementers_of_change-key:stakeholder-longValue": "Organizações de partes interessadas ( Stakeholders). Por exemplo, ONGs, interesses comerciais)",
"name:insights_outcomes-key:artistic": "Expressão artística",
"name:insights_outcomes-key:artistic-longValue": "Expressão artística (por exemplo, rap político, teatro de rua)",
"name:insights_outcomes-key:independent": "Mídia independente",
"name:insights_outcomes-key:independent-longValue": "Mídia independente (ou seja, livre de influência corporativa ou governamental)",
"name:insights_outcomes-key:minority": "Relatório Minoritário",
"name:insights_outcomes-key:minority-longValue": "Relatório minoritário (ou seja, um parecer discordante)",
"name:insights_outcomes-key:n/a": "Não aplicável",
"name:insights_outcomes-key:new": "Novas mídias",
"name:insights_outcomes-key:new-longValue": "Novas mídias (por exemplo, mídias sociais, Blogs, mensagens de texto)",
"name:insights_outcomes-key:petitions": "Petições",
"name:insights_outcomes-key:protestspublic": "Protestos/manifestações públicas",
"name:insights_outcomes-key:public": "Relatório público",
"name:insights_outcomes-key:public_hearingsmeetings": "Audiências públicas/reuniões",
"name:insights_outcomes-key:traditional": "Mídia tradicional",
"name:insights_outcomes-key:traditional-longValue": "Mídias tradicionais (isto é televisão, rádio, jornais)",
"name:insights_outcomes-key:word": "Boca a Boca",
"name:it": "Itália",
"name:learning_resources-key:expert": "Apresentações de especialistas",
"name:learning_resources-key:not": "Não é relevante para este tipo de iniciativa",
"name:learning_resources-key:no_info": "Nenhuma informação foi fornecida aos participantes",
"name:learning_resources-key:participant": "Apresentações dos participantes",
"name:learning_resources-key:site": "Visitas ao site",
"name:learning_resources-key:teachins": "Fórum educacional (Teach -in)",
"name:learning_resources-key:video": "Apresentações de vídeo",
"name:learning_resources-key:video-longValue": "Apresentações de vídeo (online ou presencial)",
"name:learning_resources-key:written": "Materiais de instruções escritas\n",
"name:learning_resources-key:written-longValue": "Materiais de apoio educacional (online ou como apostilas)",
"name:legality-key:no": "Não",
"name:legality-key:yes": "Sim",
"name:level_complexity-key:high": "Alta complexidade",
"name:level_complexity-key:low": "Baixa complexidade",
"name:level_complexity-key:moderate": "Complexidade moderada",
"name:level_complexity-key:very_high": "Muito alta complexidade",
"name:level_complexity-key:very_low": "Muito baixa complexidade",
"name:level_polarization-key:high": "Alta polarização",
"name:level_polarization-key:low": "Baixa polarização",
"name:level_polarization-key:moderate": "Polarização moderada",
"name:level_polarization-key:not": "Não polarizada",
"name:level_polarization-key:polarized": "Polarizada",
"name:method_types-key:collaborative": "Abordagens colaborativas",
"name:method_types-key:collaborative-longValue": "Abordagens colaborativas (ou seja, duas ou mais partes interessadas trabalham em conjunto para resolver um problema comum)",
"name:method_types-key:community": "Desenvolvimento, organização e mobilização da Comunidade",
"name:method_types-key:community-longValue": "Desenvolvimento comunitário, organização e mobilização (ou seja, capacitar comunidades para impulsionar, implementar e efetuar mudanças)",
"name:method_types-key:deliberative": "Processo deliberativo e dialógico",
"name:method_types-key:deliberative-longValue": "Processo deliberativo e dialógica (ou seja, processos estruturados que envolvem deliberação e/ou diálogo como aspecto central)\n\n",
"name:method_types-key:direct": "Democracia direta",
"name:method_types-key:direct-longValue": "Democracia direta (ou seja, processos formais pelos quais os cidadãos exercem autoridade direta sobre as decisões)\n\n",
"name:method_types-key:evaluation": "Avaliação, supervisão e auditoria social",
"name:method_types-key:evaluation-longValue": "Avaliação, supervisão e auditoria social (ou seja, monitoramento de órgãos e serviços públicos para responsabilizar funcionários e autoridades)",
"name:method_types-key:experiential": "Educação Experiencial e imersiva",
"name:method_types-key:experiential-longValue": "Educação Experiencial e imersiva (ou seja, abordagens alternativas ao ensino e à aprendizagem) ",
"name:method_types-key:informal": "Espaços de conversação informais",
"name:method_types-key:informal-longValue": "Espaços informais de conversa (ou seja, espaços onde deliberação e discussão podem ocorrer de maneira informal ou não estruturada)",
"name:method_types-key:informal_participation": "Participação informal",
"name:method_types-key:informal_participation-longValue": "Participação informal (ou seja, tentativas extra institucionais para garantir o acesso a recursos, direitos e representação política sem usar canais governamentais formais)",
"name:method_types-key:internal": "Gestão interna (ou seja, sistemas de comunicação interna, representação ou tomada de decisão da organização)",
"name:method_types-key:internal-longValue": "Gestão interna ou organização (ou seja, sistemas de comunicação interna, representação ou tomada de decisão)",
"name:method_types-key:longterm": "Órgãos cívicos de longo prazo",
"name:method_types-key:longterm-longValue": "Organismos cívicos a longo prazo (ou seja, esforços sustentados para proporcionar ao público oportunidades de entrada e tomada de decisões, tipicamente em nível local)",
"name:method_types-key:participantled": "Reuniões lideradas por participantes",
"name:method_types-key:participantled-longValue": "Reuniões lideradas pelos participantes (ou seja, os participantes moldam a agenda e o processo)",
"name:method_types-key:participatory": "Artes participativas",
"name:method_types-key:participatory-longValue": "Artes participativas (ou seja, processos que envolvem o público como participantes da produção ou empreendimento artístico)",
"name:method_types-key:planning": "Planejamento",
"name:method_types-key:planning-longValue": "Planejamento (ou seja, abordagens abrangentes para estabelecer metas, políticas e procedimentos para uma unidade social ou governamental)",
"name:method_types-key:protest": "Protesto",
"name:method_types-key:protest-longValue": "Protesto (ou seja, confronto direto com instituições públicas e/ou privadas)",
"name:method_types-key:public": "Orçamento público",
"name:method_types-key:public-longValue": "Orçamento público (ou seja, destinado a ajudar a decidir como devem ser gastos os fundos públicos)",
"name:method_types-key:public_meetings": "Reuniões públicas",
"name:method_types-key:public_meetings-longValue": "Reuniões públicas (ou seja, reuniões financiadas pelo governo, abertas ao público em geral, onde os funcionários públicos também podem estar presentes)",
"name:method_types-key:research": "Pesquisa ou método experimental",
"name:method_types-key:research-longValue": "Pesquisa ou método experimental (ou seja, formas de pesquisa acadêmica ou abordagens participativas testadas como parte de um projeto de pesquisa)",
"name:nl": "Holandês",
"name:number_of_participants-key:individuals": "Indivíduos",
"name:number_of_participants-key:large": "Grandes grupos",
"name:number_of_participants-key:large-longValue": "Grandes grupos (por exemplo, mais de 100 pessoas)",
"name:number_of_participants-key:medium": "Grupos de tamanho médio",
"name:number_of_participants-key:medium-longValue": "Grupos de tamanho médio (por exemplo, cerca de 50-100 pessoas)",
"name:number_of_participants-key:no_limit": "Não há limite para o número de pessoas que podem participar",
"name:number_of_participants-key:small": "Pequenos grupos",
"name:number_of_participants-key:small-longValue": "Pequenos grupos (por exemplo, menos de 20 pessoas)",
"name:ongoing-key:no": "Não",
"name:ongoing-key:yes": "Sim",
"name:open_limited-key:both": "Misto",
"name:open_limited-key:both-longValue": "Misto (ou seja, alguns aspectos estão abertos a todos e outros são limitados a alguns)",
"name:open_limited-key:limited": "Limitado a apenas alguns grupos ou indivíduos",
"name:open_limited-key:open": "Aberto a todos",
"name:open_limited-key:open_to": "Aberto a todos com esforço especial para recrutar alguns grupos",
"name:open_limited-key:open_to-longValue": "Aberto a todos com esforço especial para recrutar alguns grupos (por exemplo, organização comunitária para recrutar pessoas de baixa renda)",
"name:organizer_types-key:academic": "Instituição acadêmica",
"name:organizer_types-key:activist": "Rede de ativista",
"name:organizer_types-key:community": "Organização comunitária",
"name:organizer_types-key:faithbased": "Organização Religiosa",
"name:organizer_types-key:forprofit": "Negócios com fins lucrativos",
"name:organizer_types-key:governmentowned": "Corporação do governo",
"name:organizer_types-key:individual": "Individual",
"name:organizer_types-key:international": "Organização internacional",
"name:organizer_types-key:labortrade": "Trabalhista/sindical",
"name:organizer_types-key:local": "Governo local",
"name:organizer_types-key:local-longValue": "Governo local (por exemplo, vila, cidade)",
"name:organizer_types-key:n/a": "Não aplicável",
"name:organizer_types-key:national": "Governo nacional",
"name:organizer_types-key:nongovernmental": "Organização não governamental",
"name:organizer_types-key:nongovernmental-longValue": "Organização não governamental (sem fins lucrativos)",
"name:organizer_types-key:philanthropic": "Organização filantrópica",
"name:organizer_types-key:philanthropic-longValue": "Organização filantrópica (ou seja, dedicada a fazer doações ou doações monetárias)",
"name:organizer_types-key:regional": "Governo regional",
"name:organizer_types-key:regional-longValue": "Governo regional (por exemplo, estado, provincial, territorial)",
"name:organizer_types-key:social": "Movimento social",
"name:participants_interactions-key:acting": "Atuação, drama ou representação",
"name:participants_interactions-key:ask": "Perguntas e Respostas",
"name:participants_interactions-key:discussion": "Discussão, diálogo ou deliberação",
"name:participants_interactions-key:express": "Expressar opiniões/preferências apenas",
"name:participants_interactions-key:formal": "Testemunho formal",
"name:participants_interactions-key:informal": "Atividades sociais informais",
"name:participants_interactions-key:listenwatch": "Ouça/Assista como espectador",
"name:participants_interactions-key:negotiation": "Negociações",
"name:participants_interactions-key:no_interaction": "Nenhuma interação entre os participantes",
"name:participants_interactions-key:storytelling": "Narrativa",
"name:participants_interactions-key:teachinginstructing": "Ensinando/instruindo",
"name:pt": "Português",
"name:public_spectrum-key:collaborate": "Colaborar",
"name:public_spectrum-key:collaborate-longValue": "Colaborar (parceria com o público em cada aspecto da decisão, incluindo o desenvolvimento de alternativas e a identificação da solução preferida)",
"name:public_spectrum-key:consult": "Consultar",
"name:public_spectrum-key:consult-longValue": "Consultar (obter feedback sobre análises, alternativas e/ou decisões)",
"name:public_spectrum-key:empower": "Empoderamento",
"name:public_spectrum-key:empower-longValue": "Empoderamento (colocar a tomada de decisão final nas mãos do público)",
"name:public_spectrum-key:inform": "Informar (fornecer ao público informações equilibradas e objetivas para ajudar na compreensão do problema, alternativas, oportunidades e/ou soluções)",
"name:public_spectrum-key:inform-longValue": "Informar (fornecer ao público informações equilibradas e objetivas para ajudar na compreensão do problema, alternativas, oportunidades e/ou soluções)",
"name:public_spectrum-key:involve": "Envolver",
"name:public_spectrum-key:involve-longValue": "Envolva (trabalhe diretamente com o público durante todo o processo para garantir que as preocupações do público sejam entendidas e consideradas)",
"name:public_spectrum-key:not": "Não aplicável ou não relevante",
"name:purposes-key:academic": "Pesquisa",
"name:purposes-key:deliver": "Prestação de bens e serviços",
"name:purposes-key:deliver-longValue": "Entregar bens e serviços (por exemplo, co-produção de segurança pública pela polícia e pela Comunidade)\n\n",
"name:purposes-key:develop": "Desenvolver as capacidades cívicas de indivíduos, comunidades e/ou organizações da sociedade civil",
"name:purposes-key:develop-longValue": "Desenvolver as capacidades cívicas de indivíduos, comunidades e/ou organizações da sociedade civil (por exemplo, aumentar a compreensão das questões públicas; fortalecer o capital social)\n",
"name:purposes-key:make": "Tomar, influenciar ou contestar decisões de órgãos governamentais e públicos",
"name:purposes-key:make_influence": "Tomar, influenciar ou desafiar decisões de organizações privadas",
"name:purposes-key:make_influence-longValue": "Tomar, influenciar ou contestar decisões de organizações privadas (por exemplo, organizações da sociedade civil; corporações)",
"name:purpose_method-key:academic": "Pesquisa",
"name:purpose_method-key:deliver": "Entrega de bens e serviços (por exemplo, co-produção de segurança pública pela polícia e pela Comunidade)",
"name:purpose_method-key:deliver-longValue": "Prestação de bens e serviços (por exemplo, co-produção de segurança pública pela polícia e pela Comunidade)",
"name:purpose_method-key:develop": "Desenvolver as capacidades cívicas de indivíduos, comunidades e/ou organizações da sociedade civil\n\n",
"name:purpose_method-key:develop-longValue": "Desenvolver as capacidades cívicas de indivíduos, comunidades e/ou organizações da sociedade civil (por exemplo, aumentar a compreensão das questões públicas; fortalecer o capital social)",
"name:purpose_method-key:make": "Tomar, influenciar ou contestar decisões de órgãos governamentais e públicos",
"name:purpose_method-key:make_influence": "Tomar, influenciar ou contestar decisões de organizações privadas\n",
"name:purpose_method-key:make_influence-longValue": "Tomar, influenciar ou contestar decisões de organizações privadas (por exemplo, organizações da sociedade civil; corporações)\n",
"name:recruitment_method-key:appointment": "Nomeação",
"name:recruitment_method-key:captive": "Amostragem",
"name:recruitment_method-key:election": "Eleição",
"name:recruitment_method-key:not": "Não aplicável",
"name:recruitment_method-key:random": "Amostra aleatória",
"name:recruitment_method-key:stratified": "Amostra aleatória estratificada",
"name:scope_of_influence-key:city/town": "Cidade",
"name:scope_of_influence-key:metropolitan": "Área metropolitana",
"name:scope_of_influence-key:multinational": "Multinacional",
"name:scope_of_influence-key:national": "Nacional",
"name:scope_of_influence-key:neighbourhood": "Bairro",
"name:scope_of_influence-key:no_geo": "Sem limites geográficos",
"name:scope_of_influence-key:no_geo-longValue": "Sem limites geográficos (por exemplo, ambiente online onde qualquer pessoa de qualquer lugar pode participar)",
"name:scope_of_influence-key:organization": "Organização",
"name:scope_of_influence-key:organization-longValue": "Organização (por exemplo, uma empresa local ou cooperativa usando métodos participativos para gerenciar e governar a si mesmo)",
"name:scope_of_influence-key:regional": "Regional",
"name:scope_of_influence-key:regional-longValue": "Regional (por exemplo, estado, província, região autônoma)",
"name:sector-key:for_profit": "Lucro",
"name:sector-key:government": "Governo",
"name:sector-key:higher_ed": "Ensino superior ou pesquisa",
"name:sector-key:non_profit_non_gov": "Sem fins lucrativos ou não governamental",
"name:specific_topics-key:abilitydisability": "Problemas de capacidade/incapacidade",
"name:specific_topics-key:abortion": "Aborto",
"name:specific_topics-key:access": "Acesso a frequências de rádio e televisão",
"name:specific_topics-key:addiction": "Tratamento e Gerenciamento de Dependência Química",
"name:specific_topics-key:administration": "Administração de campanhas e eleições",
"name:specific_topics-key:affordable": "Habitação acessível",
"name:specific_topics-key:age": "Discriminação etária",
"name:specific_topics-key:aging": "Envelhecimento",
"name:specific_topics-key:aging_issues": "Problemas de envelhecimento",
"name:specific_topics-key:agricultural": "Biotecnologia agrícola",
"name:specific_topics-key:air": "Qualidade do ar",
"name:specific_topics-key:air_travel": "Viagens aéreas",
"name:specific_topics-key:alternative": "Energia alternativa e renovável ",
"name:specific_topics-key:alternative_education": "Educação alternativa",
"name:specific_topics-key:animal": "Bem-estar animal",
"name:specific_topics-key:arms": "Controle de armas",
"name:specific_topics-key:artificial": "Inteligência artificial",
"name:specific_topics-key:bankruptcy": "Falência",
"name:specific_topics-key:biomedical": "Pesquisa e Desenvolvimento Biomédica",
"name:specific_topics-key:birth": "Controle de natalidade",
"name:specific_topics-key:budget": "Orçamento-local",
"name:specific_topics-key:budget_national": "Orçamento-nacional",
"name:specific_topics-key:budget_provincial": "Orçamento público: municipal, regional, federal",
"name:specific_topics-key:bureaucracy": "Burocracia",
"name:specific_topics-key:carbon": "Captação e sequestro de carbono",
"name:specific_topics-key:censorship": "Censura",
"name:specific_topics-key:child": "Cuidados infantis",
"name:specific_topics-key:citizenship": "Cidadania e papel dos cidadãos",
"name:specific_topics-key:civil": "Direito civil",
"name:specific_topics-key:climate": "Mudanças climáticas",
"name:specific_topics-key:coal": "Carvão",
"name:specific_topics-key:cohousing": "Cohousing",
"name:specific_topics-key:community": "Comunidade e relações policiais",
"name:specific_topics-key:community_resettlement": "Reassentamento comunitário",
"name:specific_topics-key:concentration": "Concentração de propriedade de mídia",
"name:specific_topics-key:constitutional": "Reforma constitucional",
"name:specific_topics-key:consumer": "Defesa do consumidor",
"name:specific_topics-key:copyrights": "Direitos autorais e patentes",
"name:specific_topics-key:corporate": "Subsídios corporativos",
"name:specific_topics-key:court": "Sistemas jurídicos",
"name:specific_topics-key:criminal": "Direito penal",
"name:specific_topics-key:cultural": "Assimilação cultural ou integração",
"name:specific_topics-key:curriculum": "Currículo e normas",
"name:specific_topics-key:cyber": "Segurança cibernética",
"name:specific_topics-key:cycling": "Ciclismo",
"name:specific_topics-key:diplomacy": "Diplomacia",
"name:specific_topics-key:disability": "Estatuto da Pessoa com Deficiência",
"name:specific_topics-key:disabled": "Assistência para deficientes",
"name:specific_topics-key:disaster": "Gerenciamento de emergências: Desastres",
"name:specific_topics-key:disease": "Prevenção de doenças",
"name:specific_topics-key:drug": "Cobertura e custo de medicamentos",
"name:specific_topics-key:drug_testing": "Teste e regulamentação de drogas",
"name:specific_topics-key:early": "Educação na primeira infância",
"name:specific_topics-key:ecohousing": "Eco-habitação",
"name:specific_topics-key:economic": "Desenvolvimento econômico",
"name:specific_topics-key:economic_inequality": "Desigualdade econômica",
"name:specific_topics-key:elderly": "Assistência de idosos",
"name:specific_topics-key:elderly_housing": "Asilo",
"name:specific_topics-key:electricity": "Eletricidade",
"name:specific_topics-key:elementary": "Ensino fundamental e secundário",
"name:specific_topics-key:employee": "Benefícios do empregado",
"name:specific_topics-key:energy": "Conservação de energia",
"name:specific_topics-key:energy_efficiency": "Eficiência energética e armazenamento",
"name:specific_topics-key:energy_siting": "Geração e transmissão de energia",
"name:specific_topics-key:environmental": "Conservação ambiental",
"name:specific_topics-key:ethnicracial": "Igualdade étnica/racial e equidade",
"name:specific_topics-key:ethnicracial_relations": "Relações étnicas/raciais",
"name:specific_topics-key:fair": "Normas trabalhistas justas",
"name:specific_topics-key:financing": "Financiamento de campanhas políticas",
"name:specific_topics-key:fisheries": "Pesca",
"name:specific_topics-key:food": "Alimentação e nutrição",
"name:specific_topics-key:food_assistance": "Assistência alimentar",
"name:specific_topics-key:food_inspection": "Inspeção e segurança alimentar",
"name:specific_topics-key:foreign": "Ajuda estrangeira",
"name:specific_topics-key:freedom": "Liberdade de informação",
"name:specific_topics-key:freedom_of": "Liberdade de expressão",
"name:specific_topics-key:funding": "Financiamento",
"name:specific_topics-key:gender": "Igualdade de gênero e equidade",
"name:specific_topics-key:gender_identity": "Identidade de gênero",
"name:specific_topics-key:geopolitics": "Geopolítica",
"name:specific_topics-key:geotechnology": "Geotecnologias",
"name:specific_topics-key:government": "Corrupção do governo",
"name:specific_topics-key:government_funding": "Financiamento governamental da educação",
"name:specific_topics-key:government_spending": "Gastos do governo",
"name:specific_topics-key:government_subsidies": "Subsídios governamentais",
"name:specific_topics-key:government_transparency": "Transparência governamental",
"name:specific_topics-key:hazardous": "Resíduos perigosos",
"name:specific_topics-key:health": "Reforma dos cuidados de saúde",
"name:specific_topics-key:health_insurance": "Seguro de saúde",
"name:specific_topics-key:higher": "Ensino superior",
"name:specific_topics-key:highway": "Segurança viária",
"name:specific_topics-key:homelessness": "Sem-abrigo/ Sem -teto",
"name:specific_topics-key:housing": "Planejamento de habitação",
"name:specific_topics-key:human": "Direitos humanos",
"name:specific_topics-key:human_trafficking": "Tráfico de seres humanos",
"name:specific_topics-key:identity": "Política de identidade",
"name:specific_topics-key:immigration": "Imigração",
"name:specific_topics-key:indigenous": "Questões indígenas",
"name:specific_topics-key:indigenous_planning": "Planejamento indígena",
"name:specific_topics-key:industrial": "Política industrial",
"name:specific_topics-key:industrial_siting": "Diretrizes para localização industrial",
"name:specific_topics-key:information": " Tecnologias de Informação e Comunicação",
"name:specific_topics-key:infrastructure": "Infraestrutura",
"name:specific_topics-key:intellectual": "Direitos de propriedade intelectual",
"name:specific_topics-key:intelligence": "Coleta de informações",
"name:specific_topics-key:intergovernmental": "Relações intergovernamentais",
"name:specific_topics-key:international": "Direito internacional",
"name:specific_topics-key:internet": "Acesso à Internet",
"name:specific_topics-key:internet_governance": "Governança da Internet",
"name:specific_topics-key:jails": "Cadeias e prisões",
"name:specific_topics-key:judicial": "Reforma judicial",
"name:specific_topics-key:labor": "Sindicatos",
"name:specific_topics-key:land": "Uso da terra",
"name:specific_topics-key:lgbtq": "Questões LGBTQ",
"name:specific_topics-key:libraries": "Bibliotecas",
"name:specific_topics-key:longterm": "Cuidados a longo prazo",
"name:specific_topics-key:lowincome": "Assistência de baixa renda",
"name:specific_topics-key:maritime": "Marítimo",
"name:specific_topics-key:masspublic": "Transporte público",
"name:specific_topics-key:medical": "Responsabilidade médica",
"name:specific_topics-key:mental": "Saúde mental",
"name:specific_topics-key:migrant": "Trabalho migrante e sazonal",
"name:specific_topics-key:military": "Militar e defesa",
"name:specific_topics-key:monetary": "Política monetária",
"name:specific_topics-key:museums": "Museus",
"name:specific_topics-key:nanotechnology": "Nanotecnologia",
"name:specific_topics-key:natural": "Gás natural e petróleo",
"name:specific_topics-key:natural_resource": "Gestão de recursos naturais",
"name:specific_topics-key:nuclear": "Energia nuclear",
"name:specific_topics-key:open": "Dados Abertos",
"name:specific_topics-key:pensions": "Pensões e aposentadoria",
"name:specific_topics-key:police": "Polícia",
"name:specific_topics-key:political": "Partidos políticos",
"name:specific_topics-key:political_rights": "Direitos políticos",
"name:specific_topics-key:poverty": "Pobreza",
"name:specific_topics-key:public": "Serviços públicos",
"name:specific_topics-key:public_art": "Arte pública",
"name:specific_topics-key:public_participation": "Participação pública",
"name:specific_topics-key:public_safety": "Segurança pública",
"name:specific_topics-key:quality": "Qualidade dos cuidados de saúde",
"name:specific_topics-key:railroads": "Ferrovias",
"name:specific_topics-key:recycling": "Reciclagem",
"name:specific_topics-key:refugee": "Reassentamento de refugiados",
"name:specific_topics-key:refugee_rights": "Direitos dos refugiados",
"name:specific_topics-key:regional": "Governança regional e global",
"name:specific_topics-key:regionalism": "Regionalismo",
"name:specific_topics-key:regulation": "Regulamentação",
"name:specific_topics-key:regulatory": "Política regulatória",
"name:specific_topics-key:religious": "Direitos religiosos",
"name:specific_topics-key:research": "Pesquisa e desenvolvimento",
"name:specific_topics-key:resilience": "Planejamento e design de resiliência",
"name:specific_topics-key:right": "Direito à habitação adequada",
"name:specific_topics-key:right_to": "Direito à representação",
"name:specific_topics-key:roads": "Estradas e rodovias",
"name:specific_topics-key:rural": "Habitação rural",
"name:specific_topics-key:school": "Governança escolar",
"name:specific_topics-key:selfdriving": "Auto-condução de veículos",
"name:specific_topics-key:sentencing": "Diretrizes de sentença",
"name:specific_topics-key:social": "Determinantes sociais da saúde",
"name:specific_topics-key:space": "Exploração do espaço",
"name:specific_topics-key:special": "Educação especial",
"name:specific_topics-key:species": "Proteção de espécies",
"name:specific_topics-key:sports": "Esportes",
"name:specific_topics-key:substance": "Abuso de Drogas",
"name:specific_topics-key:sustainable": "Desenvolvimento sustentável",
"name:specific_topics-key:taxation": "Tributação",
"name:specific_topics-key:teacher": "Formação de professores e responsabilidade",
"name:specific_topics-key:telephone": "Acesso telefônico",
"name:specific_topics-key:terrorism": "Terrorismo",
"name:specific_topics-key:torture": "Tortura",
"name:specific_topics-key:tourism": "Turismo",
"name:specific_topics-key:trade": "Comércio e tarifas",
"name:specific_topics-key:transparency": "Transparência",
"name:specific_topics-key:transportation": "Planejamento de transporte",
"name:specific_topics-key:treaties": "Tratados",
"name:specific_topics-key:unemployment": "Desemprego",
"name:specific_topics-key:unofficial": "Diplomacia de faixa II",
"name:specific_topics-key:vocational": "Educação profissional e formação",
"name:specific_topics-key:wage": "Padrões salariais",
"name:specific_topics-key:walkingpedestrian": "Mobilidade para pedestres",
"name:specific_topics-key:waste": "Gestão de resíduos",
"name:specific_topics-key:water": "Qualidade da água",
"name:specific_topics-key:weather": "Previsão meteorológica",
"name:specific_topics-key:wilderness": "Proteção da região silvestre",
"name:specific_topics-key:worker": "Saúde e segurança do trabalhador",
"name:specific_topics-key:workforce": "Educação da força de trabalho",
"name:specific_topics-key:youth": "Emprego juvenil",
"name:specific_topics-key:youth_issues": "Questões da juventude",
"name:staff-key:no": "Não",
"name:staff-key:yes": "Sim",
"name:tags-key:accessibility": "Acessibilidade",
"name:tags-key:activism": "Ativismo",
"name:tags-key:agenda": "Formação da agenda",
"name:tags-key:animal": "Proteção e bem-estar Animal",
"name:tags-key:architecture": "Arquitetura e design",
"name:tags-key:capacity": "Capacitação",
"name:tags-key:civic_infra": "Infra-estrutura cívica",
"name:tags-key:civic_roles": "Funções e poderes cívicos",
"name:tags-key:civil": "Infraestrutura civil",
"name:tags-key:conflict": "Resolução de conflitos",
"name:tags-key:decision": "Tomada de decisão",
"name:tags-key:democratic": "Inovação democrática",
"name:tags-key:dialogue": "Diálogo e deliberação",
"name:tags-key:digital": "Digital/novas tecnologias",
"name:tags-key:direct": "Ação direta",
"name:tags-key:educational": "Recursos educacionais e oportunidades",
"name:tags-key:empowerment": "Empoderamento",
"name:tags-key:environment": "Ambiente",
"name:tags-key:formal": "Formal/ Estrutura da Participação",
"name:tags-key:gender": "Gênero",
"name:tags-key:global": "Assuntos globais",
"name:tags-key:human": "Direitos humanos",
"name:tags-key:inclusiveness": "Inclusão",
"name:tags-key:indigenous": "Questões indígenas",
"name:tags-key:informal": "Participação informal",
"name:tags-key:initiative": "Processo de iniciativa",
"name:tags-key:internal": "Gestão interna e auto-gestão",
"name:tags-key:mapping": "Mapeamento e análise",
"name:tags-key:online": "Online",
"name:tags-key:oversight": "Supervisão e monitoramento",
"name:tags-key:participatory": "Orçamento participativo",
"name:tags-key:planning": "Planejamento e desenvolvimento",
"name:tags-key:political": "Instituições políticas",
"name:tags-key:public_opinion": "Opinião pública",
"name:tags-key:public_services": "Serviços públicos",
"name:tags-key:race": "Corrida",
"name:tags-key:research": "Pesquisa e estudo",
"name:tags-key:rural": "Rural",
"name:tags-key:science": "Comunicação científica",
"name:tags-key:social_media": "Mídia social",
"name:tags-key:social_welfare": "Bem-estar social",
"name:tags-key:stateholder": "Engajamento das partes interessadas (stakeholders)",
"name:tags-key:storytelling": "Narrativa",
"name:tags-key:sustainability": "Sustentabilidade e hábitos ecológicos",
"name:tags-key:transparency": "Transparência e prestação de contas",
"name:tags-key:urban": "Urbana",
"name:tags-key:youth": "Engajamento de jovens e estudantes",
"name:targeted_participants-key:appointed": "Funcionários públicos nomeados",
"name:targeted_participants-key:appointed-longValue": "Funcionários públicos nomeados (por exemplo, burocratas)",
"name:targeted_participants-key:elderly": "Idosos",
"name:targeted_participants-key:elected": "Funcionários públicos eleitos",
"name:targeted_participants-key:experts": "Especialistas",
"name:targeted_participants-key:experts-longValue": "Peritos (por exemplo, cientistas)",
"name:targeted_participants-key:immigrants": "Imigrantes",
"name:targeted_participants-key:indigenous": "Povos indígenas",
"name:targeted_participants-key:lgbt": "Lésbicas, Gays, Bissexuais, Travestis, Transexuais e Transgêneros.",
"name:targeted_participants-key:lgbt-longValue": "Lésbicas, Gays, Bissexuais, Travestis, Transexuais e Transgêneros.",
"name:targeted_participants-key:lowincome": "Pessoas com baixa renda",
"name:targeted_participants-key:men": "Homens",
"name:targeted_participants-key:people": "Pessoas com deficiências",
"name:targeted_participants-key:racialethnic": "Grupos raciais/étnicos",
"name:targeted_participants-key:religious": "Grupos religiosos",
"name:targeted_participants-key:stakeholder": "Organizações de stakeholders ( partes interessadas)",
"name:targeted_participants-key:stakeholder-longValue": "Organizações de partes interessadas ( Stakeholders). Por exemplo, ONGs, interesses comerciais)",
"name:targeted_participants-key:students": "Estudantes",
"name:targeted_participants-key:women": "Mulheres",
"name:targeted_participants-key:youth": "Juventude",
"name:time_limited-key:a": "Um único período de tempo definido",
"name:time_limited-key:repeated": "Será que este caso se realiza em um único período definido de dias, semanas ou meses? Ou foi todo o processo repetido ao longo do tempo? Selecione um.",
"name:tools_techniques_types-key:collect": "Colete, analise e/ou solicite feedback",
"name:tools_techniques_types-key:collect-longValue": "Coletar, analisar e/ou solicitar feedback (por exemplo, questionário; pesquisa por teclado)",
"name:tools_techniques_types-key:facilitate": "Facilitar o diálogo, discussão e/ou a deliberação",
"name:tools_techniques_types-key:facilitate-longValue": "Facilitar o diálogo, a discussão e/ou a deliberação (por exemplo, a escuta ativa; gestão de conflitos)",
"name:tools_techniques_types-key:facilitate_decisionmaking": "Facilitar a tomada de decisões",
"name:tools_techniques_types-key:facilitate_decisionmaking-longValue": "Facilitar a tomada de decisões (por exemplo, classificação; multi-votação)",
"name:tools_techniques_types-key:inform": "Informar, educar e/ou sensibilizar",
"name:tools_techniques_types-key:inform-longValue": "Informar, educar e/ou sensibilizar (por exemplo, guia de discussão; Perguntas e Respostas com peritos)",
"name:tools_techniques_types-key:legislation": "Legislação, política ou estruturas (por exemplo, acordos que incorporam formalmente a participação do público)",
"name:tools_techniques_types-key:legislation-longValue": "Legislação, política ou estruturas (por exemplo, acordos que incorporam formalmente a participação do público)",
"name:tools_techniques_types-key:manage": "Gerenciar e/ou alocar dinheiro ou recursos",
"name:tools_techniques_types-key:manage-longValue": "Gerenciar e/ou alocar dinheiro ou recursos (por exemplo, aplicativos de orçamento para celular",
"name:tools_techniques_types-key:plan": "Planejar, mapear e/ou visualizar opções e propostas",
"name:tools_techniques_types-key:plan-longValue": "Planejar, mapear e/ou visualizar opções e propostas (por exemplo, mapeamento por Sistema de Informação Geográfico)",
"name:tools_techniques_types-key:propose": "Propor e/ou desenvolver políticas, ideias e recomendações",
"name:tools_techniques_types-key:propose-longValue": "Propor e/ou desenvolver políticas, ideias e recomendações (por exemplo, brainstorming; técnica de grupo)",
"name:tools_techniques_types-key:recruit": "Recrutar ou selecionar participantes",
"name:tools_techniques_types-key:recruit-longValue": "Recrutar ou selecionar participantes (Por exemplo, divulgação da Comunidade; seleção aleatória)",
"name:type_method-key:collaborative": "Abordagens colaborativas",
"name:type_method-key:collaborative-longValue": "Abordagens colaborativas (ou seja, duas ou mais partes interessadas trabalham em conjunto para resolver um problema comum)",
"name:type_method-key:community": "Desenvolvimento, organização e mobilização da Comunidade",
"name:type_method-key:community-longValue": "Desenvolvimento comunitário, organização e mobilização (ou seja, capacitar comunidades para impulsionar, implementar e efetuar mudanças)",
"name:type_method-key:deliberative": "Processo deliberativo e dialógico",
"name:type_method-key:deliberative-longValue": "Processo deliberativo e dialógico (ou seja, processos estruturados que envolvem deliberação e/ou diálogo como aspecto central)",
"name:type_method-key:direct": "Democracia direta",
"name:type_method-key:direct-longValue": "Democracia direta (ou seja, processos formais pelos quais os cidadãos exercem autoridade direta sobre as decisões)",
"name:type_method-key:evaluation": "Avaliação, supervisão e auditoria social",
"name:type_method-key:evaluation-longValue": "Avaliação, supervisão e auditoria social (ou seja, monitoramento de órgãos e serviços públicos para responsabilizar funcionários e autoridades)",
"name:type_method-key:experiential": "Educação experiencial e imersiva",
"name:type_method-key:experiential-longValue": "Educação Experiencial e imersiva (ou seja, abordagens alternativas ao ensino e à aprendizagem) ",
"name:type_method-key:informal": "Espaços de conversação informais",
"name:type_method-key:informal-longValue": "Espaços de conversação informais (ou seja, espaços onde a deliberação e discussão podem ocorrer de forma informal ou não estruturada)",
"name:type_method-key:informal_participation": "Participação informal",
"name:type_method-key:informal_participation-longValue": "Participação informal (ou seja, tentativas extra institucionais para garantir o acesso a recursos, direitos e representação política sem usar canais formais do governo)",
"name:type_method-key:internal": "Gestão interna (ou seja, sistemas de comunicação interna, representação ou tomada de decisão da organização)",
"name:type_method-key:internal-longValue": "Gerenciamento ou organização interna (ou seja, sistemas de comunicação interna, representação ou tomada de decisão)\n\n",
"name:type_method-key:longterm": "Órgãos cívicos a longo prazo (ou seja, esforços sustentados para proporcionar ao público oportunidades de entrada e tomada de decisões, tipicamente em nível local)",
"name:type_method-key:longterm-longValue": "Órgãos cívicos de longo prazo (ou seja, esforços contínuos para oferecer ao público oportunidades de contribuição e tomada de decisão, geralmente no nível local)",
"name:type_method-key:participantled": "Reuniões lideradas por participantes",
"name:type_method-key:participantled-longValue": "Reuniões lideradas pelos participantes (ou seja, os participantes moldam a agenda e o processo)",
"name:type_method-key:participatory": "Artes participativas",
"name:type_method-key:participatory-longValue": "Artes participativas (ou seja, processos que envolvem o público como participantes da produção ou empreendimento artístico)\n",
"name:type_method-key:planning": "Planejamento",
"name:type_method-key:planning-longValue": "Planejamento (ou seja, abordagens abrangentes para estabelecer metas, políticas e procedimentos para uma unidade social ou governamental)",
"name:type_method-key:protest": "Protesto",
"name:type_method-key:protest-longValue": "Protesto (ou seja, confronto direto com instituições públicas e/ou privadas)",
"name:type_method-key:public": "Orçamento público",
"name:type_method-key:public-longValue": "Orçamento público (ou seja, destinado a auxiliar a decidir como devem ser gastos os fundos públicos)",
"name:type_method-key:public_meetings": "Reuniões públicas",
"name:type_method-key:public_meetings-longValue": "Reuniões públicas (ou seja, reuniões financiadas pelo governo, abertas ao público em geral, onde os funcionários públicos também podem estar presentes)",
"name:type_method-key:research": "Pesquisa ou método experimental",
"name:type_method-key:research-longValue": "Pesquisa ou método experimental (ou seja, formas de pesquisa acadêmica ou abordagens participativas testadas como parte de um projeto de pesquisa)",
"name:type_tool-key:collect": "Colete, analise e/ou solicite feedback",
"name:type_tool-key:collect-longValue": "Coletar, analisar e/ou solicitar feedback (por exemplo, questionário; pesquisa por teclado)",
"name:type_tool-key:facilitate": "Facilitar o diálogo, a discussão e/ou a deliberação",
"name:type_tool-key:facilitate-longValue": "Facilitar o diálogo, a discussão e/ou a deliberação (por exemplo, a escuta ativa; gestão de conflitos)",
"name:type_tool-key:facilitate_decisionmaking": "Facilitar a tomada de decisões",
"name:type_tool-key:facilitate_decisionmaking-longValue": "Mediar a tomada de decisões (por exemplo, classificação; multi-votação)",
"name:type_tool-key:inform": "Informar, educar e/ou sensibilizar",
"name:type_tool-key:inform-longValue": "Informar, educar e/ou aumentar a conscientização (Por exemplo: guia de discussão; Perguntas e respostas com especialistas)",
"name:type_tool-key:legislation": "Legislação, política ou estruturas",
"name:type_tool-key:legislation-longValue": "Legislação, política ou estruturas (por exemplo, acordos que incorporam formalmente a participação do público)",
"name:type_tool-key:manage": "Gerencie e/ou distribua dinheiro ou recursos",
"name:type_tool-key:manage-longValue": "Gerenciar e/ou alocar dinheiro ou recursos (por exemplo, aplicativos de orçamento para celular)",
"name:type_tool-key:plan": "Planejar, mapear e/ou visualizar opções e propostas",
"name:type_tool-key:plan-longValue": "Planejar, mapear e/ou visualizar opções e propostas (por exemplo, mapeamento por Sistema de Informação Geográfico)",
"name:type_tool-key:propose": "Propor e/ou desenvolver políticas, ideias e recomendações",
"name:type_tool-key:propose-longValue": "Propor e/ou desenvolver políticas, ideias e recomendações (por exemplo, chuva de ideias; técnica de grupo)",
"name:type_tool-key:recruit": "Recrutar ou selecionar participantes",
"name:type_tool-key:recruit-longValue": "Recrutar ou selecionar participantes (por exemplo, divulgação da Comunidade; seleção aleatória)",
"name:volunteers-key:no": "Não",
"name:volunteers-key:yes": "Sim",
"name:zh": "Chinês",
"Namibia": "Namíbia",
"Nauru": "Nauru",
"Nepal": "Nepal",
"Netherlands": "Países Baixos",
"Netherlands Antilles": "Antilhas Holandesas",
"New Caledonia": "Nova Caledônia",
"New Zealand": "Nova Zelândia",
"new-entry-input-language-select-tooltip__text": "Você pode editar esta entrada nos seguintes idiomas. Para alterar o idioma de exibição do site, use o seletor de idioma localizado ao lado da barra de pesquisa acima.",
"new-entry-language-select-tooltip__text": "Para garantir uma tradução precisa, digite o texto em %s%s%s ou altere o idioma selecionado aqui.",
"News": "Notícias",
"Newsletter": "Boletim de Notícias",
"Newsletter Sign Up": "Newsletter/Inscreva-se",
"next": "Próxima",
"Nicaragua": "Nicarágua",
"Niger": "Níger",
"Nigeria": "Nigéria",
"Niue": "Niuê",
"no": "Não",
"Norfolk Island": "Ilha Norfolk",
"North Korea": "Coréia do Norte",
"North Macedonia": "Macedônia do Norte",
"Northern Ireland": "Irlanda do Norte",
"Northern Mariana Islands": "Ilhas Marianas do Norte",
"Norway": "Noruega",
"no_items": "Não há itens a serem exibidos.",
"Oman": "Omã",
"open menu": "abrir o menu",
"open_limited_label": "Aberto a todos ou limitado a alguns?",
"open_or_limited_label": "Aberto a todos ou limitado a alguns?",
"or drag and drop files here": "ou arrastar e soltar arquivos aqui",
"Organization": "Organização",
"organization": "Organização",
"Organizations": "Organizações",
"organizations of": "organizações de",
"organizations_edit_completeness_label": "Completude de entrada",
"organizations_view_collections_label": "Coleções",
"organizations_view_completeness_label": "Completude de entrada",
"organizations_view_country_label": "País",
"organizations_view_general_issues_label": "Questões gerais",
"organizations_view_scope_of_influence_label": "Escopo de operações",
"organizations_view_sector_label": "Setor",
"organizations_view_type_method_label": "Tipos gerais de métodos",
"organizations_view_type_tool_label": "Tipos gerais de ferramentas/técnicas",
"organization_edit_audio_attribution_instructional": "Quem é o proprietário ou criador original deste audio?",
"organization_edit_audio_attribution_placeholder": "Proprietário ou criador",
"organization_edit_audio_link_instructional": "Adicione links para áudio, como podcasts.",
"organization_edit_audio_link_label": "Áudio",
"organization_edit_audio_title_instructional": "Forneça um título ou uma descrição deste áudio em até 10 palavras ou menos.",
"organization_edit_audio_title_placeholder": "Título ou descrição",
"organization_edit_audio_url_placeholder": "Adicionar link para áudio",
"organization_edit_body_instructional": "A estrutura padrão a seguir facilita a comparação e a análise de entradas. Por favor, use os cabeçalhos abaixo e consulte nossas <a href=\"https://goo.gl/t2bDw4\" target=\"_blank\">diretrizes</a> ao preparar sua entrada.",
"organization_edit_body_label": "Narrativa",
"organization_edit_body_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"organization_edit_body_placeholder": "<h2>Missão e propósito</h2><h2>Origens e desenvolvimento</h2><h2>Estrutura organizacional, associação e financiamento</h2><h2>Especializações, métodos e ferramentas</h2><h2>Principais projetos e eventos</h2><h2>Análise e lições aprendidas</h2><h2>Publicações</h2><h2>Ver também</h2><h2>Referências</h2><h2>Links externos</h2><h2>Notas</h2>",
"organization_edit_collections_instructional": "Se você é um representante de um projeto ou organização que foi identificado como tendo uma coleção na Participedia, selecione-o aqui. Se a sua entrada não faz parte de uma coleção, por favor, deixe este campo em branco.",
"organization_edit_collections_label": "Coleções",
"organization_edit_collections_placeholder": "Selecione uma coleção",
"organization_edit_completeness_label": "Completude da entrada",
"organization_edit_completeness_placeholder": "Selecione o nível de completude para esta entrada",
"organization_edit_description_instructional": "Digite a descrição dessa organização em até (280 caracteres ou menos) ",
"organization_edit_description_label": "Descrição breve",
"organization_edit_description_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"organization_edit_description_placeholder": "Digite a descrição ",
"organization_edit_featured_instructional": "Os artigos em destaque são exibidos primeiro na página inicial",
"organization_edit_featured_label": "Destaque",
"organization_edit_files_attribution_instructional": "Quem é o proprietário original ou criador deste arquivo?",
"organization_edit_files_attribution_placeholder": "Proprietário ou criador",
"organization_edit_files_instructional": "Carregue os documentos relevantes aqui. Os tipos de arquivo suportados incluem: RTF, txt, Doc, docx, xls, xlsx, PDF, ppt, pptx, PPS, ppsx, odt, ODS e odp. O tamanho máximo do arquivo é 5MB.",
"organization_edit_files_label": "Arquivos",
"organization_edit_files_placeholder": "Clique para selecionar ou arrastar e soltar arquivos aqui",
"organization_edit_files_source_url_instructional": "Se aplicável, forneça um link para onde o arquivo original foi originado.",
"organization_edit_files_source_url_placeholder": "Link para o original",
"organization_edit_files_title_instructional": "Forneça um título ou uma descrição para esse arquivo em até 10 palavras ou menos.",
"organization_edit_files_title_placeholder": "Título ou descrição",
"organization_edit_general_issues_instructional": "Classifique os três mais relevantes assuntos abordados pela organização, com \"1\" indicando o assunto mais relevante. Abaixo, você será solicitado a fornecer informações mais detalhadas no campo tópicos específicos.",
"organization_edit_general_issues_label": "Questões gerais",
"organization_edit_general_issues_placeholder": "Selecione e classifique até 3 questões",
"organization_edit_hidden_instructional": "Artigos ocultos não aparecerão nos resultados da pesquisa",
"organization_edit_hidden_label": "Escondidos",
"organization_edit_links_attribution_instructional": "Quem é o proprietário ou criador original deste conteúdo vinculado?",
"organization_edit_links_attribution_placeholder": "Proprietário ou criador",
"organization_edit_links_link_instructional": "Se houver um site principal para esta organização, insira-o aqui. Adicione links para fontes adicionais para que os leitores e editores possam encontrar mais informações sobre essa organização online.",
"organization_edit_links_link_label": "Links",
"organization_edit_links_title_instructional": "Forneça um título ou uma descrição deste conteúdo vinculado em até 10 palavras ou menos.",
"organization_edit_links_title_placeholder": "Título ou descrição",
"organization_edit_links_url_placeholder": "Adicionar link",
"organization_edit_location_instructional": "Digite para procurar um lugar conhecido",
"organization_edit_location_label": "Localização",
"organization_edit_location_placeholder": "Tipo de busca para um local conhecido",
"organization_edit_methods_tools_techniques_info": "Se você não encontrar seu método, ferramenta ou técnica, primeiro publique esta entrada para salvar seu trabalho. Em seguida, adicione um novo método, ferramenta ou entrada de técnica. Em seguida, retorne a esta entrada de caso e adicione seu novo método, ferramenta ou técnica.",
"organization_edit_photos_attribution_instructional": "Quem é o proprietário ou criador original desta imagem?",
"organization_edit_photos_attribution_placeholder": "Proprietário ou criador",
"organization_edit_photos_instructional": "Faça upload de imagens aqui. Os tipos de arquivo suportados incluem: jpg, jpeg e png. O tamanho máximo do arquivo é 5 MB. Para obter melhores resultados, carregue uma imagem recortada na proporção de 16:9, de preferência com pelo menos 640 pixels de largura por 360 pixels de altura.",
"organization_edit_photos_label": "Imagens",
"organization_edit_photos_placeholder": "Clique para selecionar, arrastar e soltar imagens aqui",
"organization_edit_photos_source_url_instructional": "Se aplicável, forneça um link para onde a imagem original foi originária.",
"organization_edit_photos_source_url_placeholder": "Link para o original",
"organization_edit_photos_title_instructional": "Forneça um título ou uma descrição desta imagem em até 10 palavras ou menos.",
"organization_edit_photos_title_placeholder": "Título ou descrição",
"organization_edit_scope_of_influence_instructional": "Selecione até três limites geográficos ou jurisdicionais dentro dos quais esta organização está ativa",
"organization_edit_scope_of_influence_label": "Escopo de operações e atividades",
"organization_edit_scope_of_influence_placeholder": "Selecione a área geográfica ou jurisdicional",
"organization_edit_sector_instructional": "Em que setor esta organização opera?",
"organization_edit_sector_label": "Setor",
"organization_edit_sector_placeholder": "Selecione um setor",
"organization_edit_specific_methods_tools_techniques_instructional": "Especifique quais métodos, ferramentas e técnicas são usadas por esta organização? Digite para selecionar a partir de entradas já existentes no banco de dados Participedia.",
"organization_edit_specific_methods_tools_techniques_label": "Métodos específicos, ferramentas e técnicas",
"organization_edit_specific_methods_tools_techniques_placeholder": "Digite para pesquisar e gerar possíveis correspondências de banco de dados",
"organization_edit_specific_topics_instructional": "Classifique até três dos tópicos mais relevantes e específicos, com \"1\" indicando o tópico mais relevante.\n",
"organization_edit_specific_topics_label": "Tópicos específicos",
"organization_edit_specific_topics_placeholder": "Selecione e classifique até 3 tópicos",
"organization_edit_title_instructional": "Digite o nome desta organização",
"organization_edit_title_label": "Nome da organização",
"organization_edit_title_locale": "Qualquer idioma que não for inserido será traduzido automaticamente do inglês.",
"organization_edit_title_placeholder": "Digite o título em até 10 palavras ou menos",
"organization_edit_type_method_info": "Existe uma enorme variedade de métodos participativos. Para ajudar a reduzi-lo, selecione e classifique até três dos seguintes tipos de métodos usados por esta organização. Especificar quais tipos de métodos usados facilita para os usuários do Participedia encontrar organizações semelhantes. ",
"organization_edit_type_method_instructional": "Selecione e classifique até três tipos de métodos usados por esta organização, com \"1\" indicando o mais relevante.",
"organization_edit_type_method_label": "Tipos gerais de métodos",
"organization_edit_type_method_placeholder": "Selecione e classifique até 3 tipos",
"organization_edit_type_tool_info": "Existe uma grande variedade de métodos participativos. Para ajudar a reduzir, selecione e classifique até três dos seguintes tipos de ferramentas/técnicas utilizadas por essa organização. A especificação dos tipos de ferramentas/técnicas utilizados facilita, na pesquisa realizada pelos usuários da Participedia a encontrar organizações similares.\n",
"organization_edit_type_tool_instructional": "Selecione e classifique até três tipos de ferramentas/técnicas usadas por esta organização, com \"1\" indicando o mais relevante.",
"organization_edit_type_tool_label": "Tipos gerais de ferramentas/técnicas",
"organization_edit_type_tool_placeholder": "Selecione e classifique até 3 tipos",
"organization_edit_verified_instructional": "As entradas verificadas foram revisadas pelo conselho editorial da Participedia e só podem ser editadas por administradores.",
"organization_edit_verified_label": "Verificado",
"organization_edit_videos_attribution_instructional": "Quem é o dono original ou criador deste vídeo?",
"organization_edit_videos_attribution_placeholder": "Proprietário ou criador",
"organization_edit_videos_link_instructional": "Adicione um link de vídeo do Vimeo ou YouTube.",
"organization_edit_videos_link_label": "Vídeos",
"organization_edit_videos_title_instructional": "Forneça um título ou uma descrição deste vídeo em ate 10 palavras ou menos.",
"organization_edit_videos_title_placeholder": "Título ou descrição",
"organization_edit_videos_url_placeholder": "Adicionar link de vídeo (Vimeo ou YouTube)",
"organization_view_audio_label": "Áudio",
"organization_view_body_label": "Narrativa",
"organization_view_collections_label": "Coleções",
"organization_view_description_label": "Descrição breve",
"organization_view_files_label": "Arquivos",
"organization_view_general_issues_label": "Questões gerais",
"organization_view_links_label": "Links",
"organization_view_links_link_label": "Links",
"organization_view_location_label": "Localização",
"organization_view_photos_label": "Imagens",
"organization_view_scope_of_influence_label": "Escopo de operações e atividades",
"organization_view_sector_label": "Setor",
"organization_view_specific_methods_tools_techniques_label": "Métodos específicos, ferramentas e técnicas",
"organization_view_specific_topics_label": "Tópicos específicos",
"organization_view_title_label": "Nome da organização",
"organization_view_type_method_label": "Tipos gerais de métodos",
"organization_view_type_tool_label": "Tipos gerais de ferramentas/técnicas",
"organization_view_videos_label": "Vídeos",
"organizers_sectionlabel": "Organizadores",
"organizers_supporters": "Organizadores e apoiadores",
"overview": "Visão geral",
"overview_sectionlabel": "Visão geral",
"page": "Página",
"Pakistan": "Paquistão",
"Palau": "Palau",
"Palestine": "Palestina",
"Panama": "Panamá",
"Papua New Guinea": "Papua-Nova Guiné",
"Paraguay": "Paraguai",
"participants": "Participantes",
"participants_sectionlabel": "Participantes",
"Participatory & Deliberative Governance": "Governança Participativa e Deliberativa",
"Participedia Co-founder": "Participedia co-fundador",
"Participedia Design Lead and Chair, Design & Technology Committee": "Designer líder do Participedia e Presidente, Comitê de designer e tecnologia",
"Participedia Help": "Participedia Help (Ajuda)",
"Participedia on LinkedIn": "Participedia no LinkedIn",
"Participedia on Twitter": "Participedia no Twitter",
"Participedia Phase 1": "Participedia Fase 1",
"Participedia Phase 2": "Participedia Fase 2",
"Participedia Project Director and Co-Founder": "Diretor de Projetos e Co-Fundador da Participedia",
"Participedia Project Director and Co-founder": "Diretor de Projetos e Co-fundador da Participedia\n",
"participedia_team": "Equipe Participedia",
"Particpedia on Facebook": "Participedia no Facebook",
"Particpedia on GitHub": "Participedia no GitHub",
"Partners": "Parceiros",
"Peru": "Peru",
"Philippines": "Filipinas",
"photos_instructional": "Faça upload de imagens aqui. Os tipos de arquivo suportados incluem: jpg, jpeg e png. O tamanho máximo do arquivo é 5 MB. Para obter melhores resultados, carregue uma imagem recortada na proporção de 16:9, de preferência com pelo menos 640 pixels de largura por 360 pixels de altura.",
"photos_label": "Fotos",
"Pitcairn": "Ilhas Pitcairn",
"Poland": "Polônia",
"Portugal": "Portugal",
"Portuguese": "Português",
"previous": "Anterior",
"Principal Investigator": "Investigador principal",
"private_settings": "Configurações particulares",
"process": "Processo",
"process_sectionlabel": "Processo",
"Profile": "Perfil",
"profile_picture": "Imagem do perfil",
"Project Director, Co-Founder and Principal Investigator": "Diretor de projetos, co-fundador e investigador principal",
"Project Manager": "Gerente de projetos",
"public_profile": "Perfil público",
"Publish": "Publicar",
"Publishers": "Publishers",
"Puerto Rico": "Porto Rico",
"purpose_and_approach": "Propósito e abordagem",
"purpose_sectionlabel": "Propósito e abordagem",
"Qatar": "Catar",
"Quick Submit": "Envio rápido",
"quick_submit_sectionlabel": "Envio rápido",
"Read more": "Leia mais",
"Read more about our research": "Leia mais sobre nossa pesquisa",
"recaptcha_error": "Preencha o captcha para confirmar que você não é um robô",
"recaptcha_issues": "Por favor, corrija os seguintes problemas",
"Remove Bookmark": "Remover marcador",
"Research": "Pesquisa",
"Research Assistant": "Assistente de pesquisa",
"Research Associate": "Pesquisador associado",
"Research Committee": "Comitê de Pesquisa",
"Research Design Committee": "Comitê de design de pesquisa",
"research.data_downloads.cases_codebook": "Livro de códigos para casos",
"research.data_downloads.cases_csv": "Baixar casos CSV",
"research.data_downloads.If you do any analysis...": "Se você fizer qualquer análise, visualização de dados ou outros tipos de projetos com esses dados, gostaríamos de vê-lo. %s Envie-nos %s ou compartilhe seu projeto conosco no %s Twitter %s .",
"research.data_downloads.methods_codebook": "(Livro de códigos em breve)",
"research.data_downloads.methods_csv": "Métodos de download CSV",
"research.data_downloads.organizations_codebook": "(Livro de códigos em breve)",
"research.data_downloads.organizations_csv": "Baixar CSV de organizações",
"research.data_downloads.p1": "Os dados do Participedia em tempo real estão disponíveis para download como arquivos csv nos seguintes links:",
"research.data_downloads.p2": "Melhorar a qualidade do conjunto de dados da Participedia é um processo contínuo e agradecemos feedback sobre qualquer aspecto de nossos dados e como permitimos seu uso. Os dados da Participédia em tempo real estão disponíveis nos seguintes links:",
"research.data_downloads_header": "Downloads de dados em tempo real",
"research.data_repository.dataverse": "Repositório do Dataverse",
"research.data_repository.feature.1": "métricas sobre o número de downloads de cada conjunto de dados;",
"research.data_repository.feature.2": "a capacidade de baixar conjuntos de dados em vários formatos que são gerados automaticamente;",
"research.data_repository.feature.3": "a capacidade de realizar a análise de dados diretamente através da interface do usuário sem baixar dados, já que %sR%s é incorporado à interface do usuário;\n\n\n",
"research.data_repository.feature.4": "preservação de dados a longo prazo;",
"research.data_repository.feature.5": "atribuição automática de identificadores de objeto digital (DOIs) e outros metadados compatíveis com os padrões para permitir a citação de conjuntos de dados;",
"research.data_repository.feature.6": "indexação de conjuntos de dados nos principais mecanismos de busca para ajudar os usuários a encontrarem os mesmos;",
"research.data_repository.feature.7": "criação de impressões digitais para permitir a autenticação de conjuntos de dados; E",
"research.data_repository.feature.8": "Utiliza um sistema de gerenciamento de API aberta que permite que dados e metadados sejam usados por outros serviços da Web.",
"research.data_repository.p1": "A maioria das pesquisas sobre inovações democráticas e processos participativos que ocorrem em todo o mundo não está disponível ao público. Esses materiais incluem conjuntos de dados, livros de códigos, scripts ou sintaxe do software estatístico, dissertações, documentos de conferências e avaliações e relatórios dos profissionais. O%sParticipedia Dataverse%s fornece um local para esses materiais em um repositório de dados acessível e organizado, arquiva os materiais para preservação a longo prazo e gera descrições e identificadores padronizados para facilitar a descoberta e citação dos materiais.",
"research.data_repository.p2": "Pesquisadores e demais profissionais podem contribuir para o Participedia Dataverse, depositando seus materiais de pesquisa gratuitamente. As características do repositório de dados Participedia incluem:",
"research.data_repository.questions": "Por favor, dirija quaisquer perguntas sobre como contribuir para Participedia para %sdata@participedia.net%s",
"research.methodology.p1": "A estratégia é simples: recursos colaborativos de informações sobre as inovações democráticas de todo o mundo e agregá-lo em um banco de dados públicos que continuamente se atualiza com novas contribuições. Todo o conteúdo e dados do Participedia são de código aberto.",
"research.methodology.p2": "Para obter uma explicação detalhada da história, aspirações, teoria e abordagem analítica da Participedia, consulte '%sO Projeto Participedia: Uma Introdução%s', pelos fundadores do projeto, Archon Fung e Mark E. Warren. Para obter informações sobre como você pode contribuir para o projeto, consulte nossa entrada %sguidelines%s.\n",
"research.surveys.p1": "As pesquisas/ inquéritos são complementares aos dados actuais, as descrições e narrativas da Participedia destinam-se a obter mais informações sobre os resultados e efeitos dos casos.\n\n",
"research.surveys.p2": "A pesquisa participante capturará a experiência daqueles diretamente envolvidos em um processo participativo. A mesma, poderá ser entregue pelos organizadores no local de um processo específico ou concluído pelos participantes após o evento.",
"research.surveys.p3": "A pesquisa de observadores capturará visões relativas ao impacto mais amplo de um caso específico. Os «observadores» incluem profissionais, participantes ou investigadores com particular conhecimento desse caso.",
"research.surveys.p4": "As pesquisas da Participedia estão sendo submetidas a testes e estarão disponíveis para download em breve.",
"research.tagline": "Participedia é orientada pela pergunta da pesquisa: Que tipos de processos participativos funcionam melhor, com que finalidades e sob quais condições?",
"resources_sectionlabel": "Recursos",
"Results CSV": "Resultados CSV",
"results of": "resultados de",
"Reunion": "Reunião",
"reviewed_entries_label": "Revisado pelo Conselho Editorial da Participedia",
"reviewed_entries_title": "Entradas revisadas",
"reviewed_popup_message": "Esta entrada foi revisada pelo nosso Conselho Editorial e não pode mais ser editada. Se você quiser sugerir alterações a esta entrada, por favor, %s entre em contato conosco. %s",
"reviwed_popup_message": "Esta entrada foi revisada pelo nosso Conselho Editorial e não pode mais ser editada. Se você gostaria de sugerir alterações a esta entrada, por favor %s entre em contato conosco",
"Romania": "Romênia",
"Russian Federation": "Rússia",
"Rwanda": "Ruanda",
"Saint Helena": "Santa Helena",
"Saint Kitts and Nevis": "São Cristóvão e Névis",
"Saint Lucia": "Santa Lúcia",
"Saint Pierre and Miquelon": "São Pedro e Miquelão",
"Saint Vincent and the Grenadines": "São Vicente e Granadinas",
"Samoa": "Samoa",
"San Marino": "San Marino",
"Sao Tome and Principe": "São Tomé e Príncipe",
"Saudi Arabia": "Arábia Saudita",
"sciencewise": "Sciencewise ",
"scope_of_influence_instructional": "Qual é a área geográfica ou jurisdicional deste caso?",
"scope_of_influence_label": "Escopo de influência",
"scope_of_influence_placeholder": "Selecione o escopo geográfico ou jurisdicional",
"Search": "Pesquisa",
"search-error-not-available": "Lamentamos o transtorno, a pesquisa por palavra-chave ainda não está disponível em seu idioma.",
"search-error-switch-to-en": "Você também pode usar o seletor de idioma no rodapé ou no cabeçalho para alterar seu idioma para inglês se desejar usar a pesquisa por palavra-chave em inglês.",
"search-error-working-on-solution": "Estamos trabalhando em uma solução, mas enquanto isso, use os filtros de pesquisa para %s casos %s , %s métodos %s%s organizações %s .",
"Select a country": "Selecione um pais",
"Select Language": "Selecionar idioma",
"Select one or more countries": "Selecione um ou mais países",
"Senegal": "Senegal",
"Seychelles": "Seychelles",
"Show All": "Mostrar Tudo",
"Show Less": "Mostre menos",
"Show Results": "Mostrar resultados",
"Sierra Leone": "Serra Leoa",
"Sign out": "Sair",
"Sign up": "inscrever-se",
"Singapore": "Cingapura",
"Slovakia": "Eslováquia",
"Slovenia": "Eslovênia",
"Solomon Islands": "Ilhas Salomão",
"Somalia": "Somália",
"Something Missing?": "Faltando algo?",
"Sorry, this page cannot be found": "Desculpe, esta página não pode ser encontrada",
"Sort By": "Ordenar por",
"Source": "Fonte",
"South Africa": "África do Sul",
"South Georgia and the South Sandwich Islands": " Ilhas Geórgia do Sul e Sandwich do Sul",
"South Korea": "Coreia do Sul",
"South Sudan": "Sudão do Sul",
"Spain": "Espanha",
"Spanish": "Espanhol",
"Sri Lanka": "Sri Lanka",
"Staff": "Pessoal",
"Submitted": "Enviada",
"Sudan": "Sudão",
"Suggest edits...": "Sugerir edições deste formulário por e-mail para",
"suitable_for_sectionlabel": "Apropriado para",
"Supporters": "Apoiadores",
"Suriname": "Suriname",
"Surveys": "Pesquisas",
"Svalbard and Jan Mayen": "Svalbard e Jan Mayen",
"Swaziland": "Suazilândia",
"Sweden": "Suécia",
"Switzerland": "Suíça",
"Syria": "Síria",
"Tajikistan": "Tajiquistão",
"Tanzania": "Tanzânia",
"Teach": "Ensino",
"Teaching": "Ensino",
"Teaching Resources": "Recursos didáticos",
"Teaching resources": "Recursos didáticos",
"Teaching Training & Mentoring Committee": "Capacitação de ensino e Comitê de orientação",
"teaching.Assignments": "Atribuições",
"teaching.Bibliographies": "Bibliografias",
"teaching.Browse our Teaching & Learning Resource Centre": "Consulte o nosso Centro de Recursos de Ensino e Aprendizagem",
"teaching.Discussion.p1": "Criamos um bate-papo em grupo onde todos podem discutir sobre recursos de ensino/aprendizagem e pedagogia democrática. Participe do Grupo do Facebook do Participedia para contribuir nas discussões e fazer perguntas para comunidade acadêmica.",
"teaching.Discussions & Questions About Our Resources": "Discussões e perguntas sobre nossos recursos",
"teaching.Grading Rubrics": "Classificação de rubricas",
"teaching.How to Write a Participedia Entry": "Como escrever uma entrada Participedia",
"teaching.in_course": "Participedia em atribuições do curso",
"teaching.in_the_classroom": "Participedia na sala de aula",
"teaching.in_the_classroom.p1": "Escrever ou editar artigos para Participedia pode ser uma grande tarefa para cursos que lidam com a participação política, a inovação democrática ou a deliberação.",
"teaching.in_the_classroom.p2": "No decorrer da seleção, pesquisa e redação de um caso, método ou organização, os alunos aprenderão sobre a substância de participação em contextos variados. Os alunos também podem achar gratificante ter seu trabalho apresentado na Participedia.",
"teaching.in_the_classroom.p3": "Os recursos a seguir oferecem ideias sobre como aprimorar as ofertas de cursos sobre a participação pública:\n\n\n",
"teaching.Join Group Chat About Teaching Resources": "Participe do chat de grupo sobre recursos didáticos",
"teaching.learning_webinar": "Série de webinars sobre ensino e aprendizagem democrática",
"teaching.learning_webinar.p1": "Esta série de webinars foi projetada para conectar pesquisadores e colaboradores da Participedia com interesses comuns e para trocar conhecimentos sobre desafios e sucessos no campo de métodos de ensino, teorias e casos que apoiam a participação democrática. A série foi desenvolvida e lançada em 2018 pelos Co-Presidentes do Comitê de Ensino, Treinamento e Mentoria de %s Participedia.net %s , Drs. Joanna Ashworth e Bettina von Lieres.",
"teaching.Lesson Plans": "Planos de aula",
"teaching.Participedia provides open access to": "Participedia fornece acesso aberto a recursos colaborativo que são úteis para as salas de aula de graduação e pós-graduação, bem como recursos de desenvolvimento profissional para profissionais, organizações da sociedade civil e ONGs. Os recursos variam de conteúdos programáticos e trabalhos de aula a manuais, simulações e material de treinamento multimídia.\n\n",
"teaching.Please use this form": "Por favor, use %seste formulário%s ou envie um e-mail para %sinfo@participedia.net%s se você tiver recursos para compartilhar.",
"teaching.Quizzes/Tests": "Quizzes/testes",
"teaching.resource.p1": "Aumentar o conhecimento dos alunos sobre inovações na democracia participativa;",
"teaching.resource.p2": "Melhore as habilidades de pesquisa e escrita dos alunos publicando casos, métodos e organizações na Participedia;",
"teaching.resource.p3": "Aprimorar a capacidade dos alunos de fazer conexões entre a teoria e a prática da participação pública;",
"teaching.resource.p4": "Preparar os alunos para serem organizadores e pesquisadores de inovações democráticas, e;",
"teaching.resource.p5": "Adaptar a pedagogia e a cultura da sala de aula para serem mais participativas",
"teaching.Sample Assignment": "Atribuição de amostra e avaliação de rubrica",
"teaching.Share Your Resources with the Community": "Compartilhe seus recursos com a Comunidade",
"teaching.Submit a Teaching Resource": "Submeter um recurso de ensino",
"teaching.Syllabi": "Ementa",
"teaching.These resources can be used to:": "Esses recursos podem ser usados para:",
"teaching.tlrc.header": "Centro de recursos de ensino e aprendizagem",
"teaching.What are Teaching & Learning Resources?": "O que são os recursos de ensino e aprendizagem?",
"Team Members": "Membros do time",
"Tech Lead": "Líder de tecnologia",
"teching.Here are a few types of Teaching & Learning Resources": "Aqui estão alguns tipos de recursos de ensino e aprendizagem que esperamos coletar e compartilhar com a Comunidade Participedia:",
"Tell me more...": "Me diga mais...",
"Terms of Use": "Termos de uso ",
"Thailand": "Tailândia",
"The Democratic Republic of Congo": "República Democrática do Congo",
"This entry was originally added in %s.": "Esta entrada foi originalmente adicionada em %s.",
"Togo": "Togo",
"Tokelau": "Toquelau ",
"Tonga": "Tonga",
"Tools/Techniques": "Ferramentas/técnicas",
"tools_techniques_sectionlabel": "Métodos, ferramentas e técnicas usadas",
"Trinidad and Tobago": "Trinidade e Tobago",
"true": "Verdade",
"Tunisia": "Tunísia",
"Turkey": "Turquia",
"Turkmenistan": "Turquemenistão",
"Turks and Caicos Islands": "Ilhas Turcas e Caicos",
"Tuvalu": "Tuvalu",
"type_purpose_sectionlabel": "Tipo e propósito",
"uarkansas_students": "Universidade de Arkansas, Clinton School of Public Service Students ( Escola Clinton de Serviços Públicos)",
"Uganda": "Uganda",
"Ukraine": "Ucrânia",
"United Arab Emirates": "Emirados Árabes Unidos",
"United Kingdom": "Reino Unido",
"United States": "Estados Unidos",
"United States Minor Outlying Islands": "Ilhas menores distantes dos Estados Unidos",
"Updated": "Atualizado",
"Uruguay": "Uruguai",
"user_edit_bio_instructional": "Conte-nos sobre você",
"user_edit_bio_label": "Biografia",
"user_edit_name_instructional": "Seu nome será exibido em todas as contribuições, incluindo conteúdo editado e publicado.",
"user_edit_name_label": "Nome",
"user_edit_name_placeholder": "Digite seu nome",
"usoton_students": "Estudantes da Universidade de Southampton",
"Uzbekistan": "Uzbequistão",
"Vanuatu": "Vanuatu",
"Venezuela": "Venezuela",
"videos_url_placeholder": "Adicionar link para vídeo",
"Vietnam": "Vietnã",
"View all": "Ver tudo",
"View all collections": "Ver todas as coleções",
"View case": "Ver Caso",
"View collection": "Ver coleção",
"View method": "Método de visualização",
"View organization": "Ver Organização",
"View this entry in its original language": "Veja esta entrada em seu idioma original",
"Virgin Islands, British": "Ilhas Virgens Britânicas",
"Virgin Islands, U.S.": "Ilhas Virgens americanas",
"Wallis and Futuna": "Ilhas Wallis e Futuna",
"Welcome to Participedia": "Bem-vindo à Participedia",
"Western Sahara": "Saara Ocidental",
"Wiki Contributor History": "Histórico de contribuidores da Wiki",
"Yemen": "Iêmen",
"yes": "Sim",
"Yugoslavia": "Iugoslávia",
"Zambia": "Zâmbia",
"Zimbabwe": "Zimbábue",
"Zoom Map In": "Ampliar o mapa",
"Zoom Map Out": "Diminuir o mapa"
} |
/**
* The Header view.
*/
define([
'jquery',
'backbone',
'underscore',
'mps',
'views/ShareView'
], function($,Backbone, _,mps, ShareView) {
'use strict';
var HeaderView = Backbone.View.extend({
el: '#headerView',
events: {
'click #btn-menu' : 'toggleMenu',
'click .share-link' : 'shareOpen',
'click .menu-section-link' : 'menuOpen'
},
initialize: function() {
//CACHE
this.$htmlbody = $('html,body');
this.$window = $(window);
this.$document = $(document);
this.$navMobile = $('#nav-mobile');
this.$footer = $('#footerMenu');
this.$siteMap = $('#siteMap');
this.$mobileMenu = $('#mobileMenu');
this.$translate = $('#google_translate_element');
this.createMenu();
this.$window.on('resize',_.bind(this.createMenu,this));
this.welcome();
},
toggleMenu: function(e){
$(e.currentTarget).toggleClass('active');
if ($(e.currentTarget).hasClass('active')) {
this.scrollTop = this.$document.scrollTop();
this.$htmlbody.addClass('active');
this.$el.addClass('active');
this.$navMobile.addClass('active');
}else{
this.$htmlbody.removeClass('active').animate({ scrollTop: this.scrollTop }, 0);
this.$el.removeClass('active');
this.$navMobile.removeClass('active');
}
},
createMenu: function(){
if (this.$window.width() > 850) {
this.$footer.appendTo(this.$siteMap);
this.$translate.appendTo($('#google_translate_element_box1'));
}else{
this.$footer.appendTo(this.$mobileMenu);
this.$translate.appendTo($('#google_translate_element_box2'));
}
},
shareOpen: function(event){
var shareView = new ShareView().share(event);
this.$el.append(shareView.el);
},
menuOpen: function(e){
$(e.currentTarget).toggleClass('active');
$('#menu-section-dropdown').toggleClass('active');
},
welcome: function() {
if (window.location.hostname === 'localhost') { return; }
console.info('%c .', "background-image: url('http://www.globalforestwatch.org/assets/logo-new.png'); width: 85px; height: 90px; float:left;font-size:82px; color: transparent;");
console.info('%cWelcome to GFW ', "background: rgba(151, 189, 61, 0.1); color: #666; padding: 3px 6px;font-size: 15px;");
console.info('%cIn case you\'re interested in the code of this website ', "background: rgba(151, 189, 61, 0.1); color: #666; padding: 3px 6px;");
console.info('%cplease, feel free to check our apps: ', "background: rgba(151, 189, 61, 0.1); color: #666; padding: 3px 6px;");
console.info('%chttp://www.globalforestwatch.org/explore/applications ', "background: rgba(151, 189, 61, 0.1); font-weight: bold; padding: 3px 6px;");
console.info('%cor go and fork this project on GitHub: ', "background: rgba(151, 189, 61, 0.1); color: #666; padding: 3px 6px;");
console.info('%chttps://github.com/Vizzuality/gfw ', "background: rgba(151, 189, 61, 0.1); font-weight: bold; padding: 3px 6px;");
console.info('%cand the API: ', "background: rgba(151, 189, 61, 0.1); color: #666; padding: 3px 6px;");
console.info('%chttps://github.com/wri/gfw-api ', "background: rgba(151, 189, 61, 0.1); font-weight: bold; padding: 3px 6px;");
console.info('%cThank you! ', "background: rgba(151, 189, 61, 0.1); color: #666; padding: 3px 6px;");
}
});
return HeaderView;
});
|
import React, { PropTypes } from 'react'
import { Modal } from 'antd'
import wechatCodeImg from '../../static/img/me/wechat_code.jpg'
import classes from './ImageModal.scss'
class ImageModal extends React.Component {
static propTypes = {
visible: PropTypes.bool.isRequired
};
componentDidUpdate() {
const { visible } = this.props
if(visible) {
$('body').addClass('noScroll')
} else {
$('body').removeClass('noScroll')
}
}
render() {
const { visible, width, title, onCancel } = this.props
return (
<Modal visible={visible}
width={width}
footer={false}
closable={true}
wrapClassName={classes.container}
onCancel={onCancel}
style={{maxWidth: width, margin: '1rem auto'}}
zIndex={1010}
>
<div className={classes.modalBody}>
<h4 className={classes.title}>{title}</h4>
<img src={wechatCodeImg} className={classes.wechatCode}/>
</div>
</Modal>
)
}
}
export default ImageModal
|
version https://git-lfs.github.com/spec/v1
oid sha256:2a87ff5b4bbc72c52d9a82be37ffa8e7f1f7d41c49ecd9c9868fcf511a1a03ad
size 28192
|
SyncedCron.config({
// Log job run details to console
log: true,
// Use a custom logger function (defaults to Meteor's logging package)
//logger: null,
// Name of collection to use for synchronisation and logging
collectionName: DRM.collectionNamePrefix + 'cronHistory',
// Default to using localTime
utc: false,
/*
TTL in seconds for history records in collection to expire
NOTE: Unset to remove expiry but ensure you remove the index from
mongo by hand
ALSO: SyncedCron can't use the `_ensureIndex` command to modify
the TTL index. The best way to modify the default value of
`collectionTTL` is to remove the index by hand (in the mongo shell
run `db.cronHistory.dropIndex({startedAt: 1})`) and re-run your
project. SyncedCron will recreate the index with the updated TTL.
*/
collectionTTL: 172800
});
SyncedCron.start();
|
// Fixture for has function
// Object literals with attributes to test against
var has_attribute_with_backslash_fixture = {
"hello": {
"world": {
"foo\\bar": {
"baz": true
},
"\\foo bar": {
"baz": true
},
"foo bar\\": {
"baz": true
}
}
}
};
if (typeof module !== "undefined") {
module.exports = has_attribute_with_backslash_fixture;
}
// End of file
|
var gmaps = require('google-maps-api')('AIzaSyC2Xp07hffemgAHYenBMKxeAeJ017nIbbk');
var mapOptions = {
zoom: 13,
center: {lat: -34.397, lng: 150.644},
mapTypeControl: false,
streetViewControl: false,
zoomControl: false
};
var map = {};
var Map = React.createClass({
componentDidMount: function() {
gmaps().then( function(mp) {
map = new google.maps.Map(document.getElementById('mapp'), mapOptions);
});
},
componentDidUpdate: function(prevProps, prevState){
if(typeof google != 'object' || typeof google.maps != 'object'){
return;
}
if(this.props.location != undefined && map.setCenter != undefined){
map.setCenter(new google.maps.LatLng(this.props.location.latitude, this.props.location.longitude));
}
var flightPath = new google.maps.Polyline({
path: this.props.route,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 4
});
flightPath.setMap(map);
},
getInitialState: function() {
return {
map: {}
};
},
render: function () {
return (
<div id="mapp" style={{height: '600px'}} ref={(x) => this.mapDiv = x}>
x
</div>
)
}
});
module.exports = Map; |
import Login from '../components/Login.jsx';
import {useDeps, composeWithTracker, composeAll} from 'mantra-core';
import { connect } from 'react-redux'
import { push } from 'react-router-redux';
export const composer = ({context, clearErrors}, onData) => {
onData(null, {});
// clearErrors when unmounting the component
return clearErrors;
};
export const depsMapper = (context, actions) => ({
submitLoginAction: actions.account.login,
clearErrors: actions.account.loginErrorClear,
loginWithFacebook: actions.account.loginWithFacebook,
loginWithTwitter: actions.account.loginWithTwitter,
loginWithGoogle: actions.account.loginWithGoogle,
loginWithGithub: actions.account.loginWithGithub,
context: () => context,
});
const mapStateToProps = (state) => {
return {
i18n: state.i18n,
loginError: state.error.loginError,
}
};
export default composeAll(
connect(mapStateToProps),
composeWithTracker(composer),
useDeps(depsMapper)
)(Login);
|
"use strict";
var debug = require('debug')('loopback:CustomerAccountUserMapping');
var vasync = require('vasync');
module.exports = function customerAccountUserMapping(CustomerAccountUserMapping) {
CustomerAccountUserMapping.findAccount = function findAccount(token, next) {
var Account = CustomerAccountUserMapping.app.models.CustomerAccount;
vasync.waterfall([
function getMapping(cb) {
CustomerAccountUserMapping.find({"where": {"userModelId": token.userId}}, cb);
},
function getAccounts(result, cb) {
//@todo get all accounts
if (result.length === 1) {
Account.find({"where": {"id": result[0].customerAccountId}}, cb);
} else {
cb(null, []);
}
}
], function end(err, result){
if (err) {
return next(err);
}
debug('> findAccount processed successfully');
if (result.length === 1) {
return next(err, [result]);
}
return next(err, result);
});
};
};
|
import Hero from './Hero';
import MiniHero from './MiniHero';
export default Hero;
export { MiniHero }
|
'use strict';
var BrowserifyCache = require('browserify-cache-api');
module.exports = function incrementalWatchPlugin(b) {
var hasReadCache = false;
b.on('bundle', function() {
var cache = BrowserifyCache.getCache(b);
if (!hasReadCache && cache) {
Object.keys(cache.dependentFiles).forEach(function(file) {
b.emit('file', file);
});
Object.keys(cache.modules).forEach(function(file) {
b.emit('file', file);
});
}
hasReadCache = true;
});
};
|
/**@license
The MIT License (MIT)
Copyright (c) 2015 Daniel Furtlehner
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.
*/
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.CommandJS=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
/// <reference path="../../typings/commandjs/command-definitions.d.ts"/>
var CommandJS;
(function (CommandJS) {
"use strict";
var states = _dereq_('./states');
var commandParser = _dereq_('./command-parser');
var CommandExecutorImpl = (function () {
function CommandExecutorImpl(commands) {
if (commands && !(commands instanceof Array)) {
throw 'An array of commands is required';
}
this.commands = this.prepareCommands(commands);
}
CommandExecutorImpl.prototype.getCommands = function () {
return this.commands;
};
CommandExecutorImpl.prototype.execute = function (commandString) {
var parsed = this.parse(commandString);
var commandParts = this.getCommandParts(parsed);
if (!commandParts) {
return {
state: states.ExecutorResponseState.ERROR,
errorType: states.ExecutorErrorType.PARSER_ERROR,
commandString: commandString
};
}
var commandResponse = this.findCommand(commandParts, true);
if (commandResponse.state === states.ExecutorResponseState.ERROR) {
commandResponse.commandString = commandString;
return commandResponse;
}
try {
return commandResponse.response;
}
catch (e) {
return {
state: states.ExecutorResponseState.ERROR,
errorType: states.ExecutorErrorType.COMMAND_EXECUTION_ERROR,
commandString: commandString,
response: e
};
}
};
CommandExecutorImpl.prototype.getCommand = function (commandString) {
var commandParts = this.getCommandParts(this.parse(commandString));
if (!commandParts) {
return {
state: states.ExecutorResponseState.ERROR,
errorType: states.ExecutorErrorType.PARSER_ERROR,
commandString: commandString
};
}
var commandResponse = this.findCommand(commandParts, false);
commandResponse.commandString = commandString;
return commandResponse;
};
CommandExecutorImpl.prototype.findCommand = function (commandParts, paramsAllowed) {
if (!commandParts) {
return null;
}
var actualCommand;
var current = this.commands;
var i;
var part;
for (i in commandParts) {
part = commandParts[i];
if (current[part]) {
actualCommand = current[part];
if (actualCommand.subCommands) {
current = actualCommand.subCommands;
}
else if (!paramsAllowed && i < commandParts.length - 1) {
return {
state: states.ExecutorResponseState.ERROR,
errorType: states.ExecutorErrorType.COMMAND_NOT_FOUND
};
}
}
else {
return {
state: states.ExecutorResponseState.ERROR,
errorType: states.ExecutorErrorType.COMMAND_NOT_FOUND,
response: Object.keys(actualCommand.subCommands)
};
}
}
return {
state: states.ExecutorResponseState.SUCCESS,
response: actualCommand.command
};
};
CommandExecutorImpl.prototype.parse = function (commandString) {
if (!commandString) {
return [];
}
return commandParser.parse(commandString.trim());
};
CommandExecutorImpl.prototype.getCommandParts = function (parseResults) {
if (!parseResults || parseResults.length === 0) {
return null;
}
for (var _i = 0; _i < parseResults.length; _i++) {
var result = parseResults[_i];
if (result.type === 'COMMAND_PARAM') {
return result.values;
}
}
return null;
};
CommandExecutorImpl.prototype.prepareCommands = function (commands) {
if (!commands) {
return;
}
var self = this;
var commandMap = {};
commands.forEach(function (command) {
commandMap[command.name] = {
command: command
};
if (command.subCommands) {
commandMap[command.name].subCommands = self.prepareCommands(command.subCommands);
}
});
return commandMap;
};
return CommandExecutorImpl;
})();
CommandJS.CommandExecutorImpl = CommandExecutorImpl;
module.exports = CommandExecutorImpl;
})(CommandJS || (CommandJS = {}));
},{"./command-parser":2,"./states":4}],2:[function(_dereq_,module,exports){
module.exports = (function() {
/*
* Generated by PEG.js 0.8.0.
*
* http://pegjs.majda.cz/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function SyntaxError(message, expected, found, offset, line, column) {
this.message = message;
this.expected = expected;
this.found = found;
this.offset = offset;
this.line = line;
this.column = column;
this.name = "SyntaxError";
}
peg$subclass(SyntaxError, Error);
function parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
peg$FAILED = {},
peg$startRuleFunctions = { start: peg$parsestart },
peg$startRuleFunction = peg$parsestart,
peg$c0 = [],
peg$c1 = peg$FAILED,
peg$c2 = " ",
peg$c3 = { type: "literal", value: " ", description: "\" \"" },
peg$c4 = function(c) {return c;},
peg$c5 = function(c, c1) {
if(c1) {
return toCommand([c].concat(c1))
}
else {
return toCommand([c])
}
},
peg$c6 = /^[^" "]/,
peg$c7 = { type: "class", value: "[^\" \"]", description: "[^\" \"]" },
peg$c8 = function(c) {return c.join("")},
peg$currPos = 0,
peg$reportedPos = 0,
peg$cachedPos = 0,
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false },
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$reportedPos, peg$currPos);
}
function offset() {
return peg$reportedPos;
}
function line() {
return peg$computePosDetails(peg$reportedPos).line;
}
function column() {
return peg$computePosDetails(peg$reportedPos).column;
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
peg$reportedPos
);
}
function error(message) {
throw peg$buildException(message, null, peg$reportedPos);
}
function peg$computePosDetails(pos) {
function advance(details, startPos, endPos) {
var p, ch;
for (p = startPos; p < endPos; p++) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
}
}
if (peg$cachedPos !== pos) {
if (peg$cachedPos > pos) {
peg$cachedPos = 0;
peg$cachedPosDetails = { line: 1, column: 1, seenCR: false };
}
advance(peg$cachedPosDetails, peg$cachedPos, pos);
peg$cachedPos = pos;
}
return peg$cachedPosDetails;
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, pos) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
var posDetails = peg$computePosDetails(pos),
found = pos < input.length ? input.charAt(pos) : null;
if (expected !== null) {
cleanupExpected(expected);
}
return new SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
pos,
posDetails.line,
posDetails.column
);
}
function peg$parsestart() {
var s0, s1;
s0 = [];
s1 = peg$parsecommandsOrParams();
if (s1 !== peg$FAILED) {
while (s1 !== peg$FAILED) {
s0.push(s1);
s1 = peg$parsecommandsOrParams();
}
} else {
s0 = peg$c1;
}
return s0;
}
function peg$parsecommandsOrParams() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parsecommandOrParam();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = [];
if (input.charCodeAt(peg$currPos) === 32) {
s5 = peg$c2;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c3); }
}
if (s5 !== peg$FAILED) {
while (s5 !== peg$FAILED) {
s4.push(s5);
if (input.charCodeAt(peg$currPos) === 32) {
s5 = peg$c2;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c3); }
}
}
} else {
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
s5 = peg$parsecommandOrParam();
if (s5 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c4(s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = [];
if (input.charCodeAt(peg$currPos) === 32) {
s5 = peg$c2;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c3); }
}
if (s5 !== peg$FAILED) {
while (s5 !== peg$FAILED) {
s4.push(s5);
if (input.charCodeAt(peg$currPos) === 32) {
s5 = peg$c2;
peg$currPos++;
} else {
s5 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c3); }
}
}
} else {
s4 = peg$c1;
}
if (s4 !== peg$FAILED) {
s5 = peg$parsecommandOrParam();
if (s5 !== peg$FAILED) {
peg$reportedPos = s3;
s4 = peg$c4(s5);
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$c1;
}
} else {
peg$currPos = s3;
s3 = peg$c1;
}
}
if (s2 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c5(s1, s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$c1;
}
} else {
peg$currPos = s0;
s0 = peg$c1;
}
return s0;
}
function peg$parsecommandOrParam() {
var s0;
s0 = peg$parsecharacters();
return s0;
}
function peg$parsecharacters() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c6.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c7); }
}
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c6.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c7); }
}
}
} else {
s1 = peg$c1;
}
if (s1 !== peg$FAILED) {
peg$reportedPos = s0;
s1 = peg$c8(s1);
}
s0 = s1;
return s0;
}
function toCommand(c) {
return {
type: "COMMAND_PARAM",
values: c
};
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(null, peg$maxFailExpected, peg$maxFailPos);
}
}
return {
SyntaxError: SyntaxError,
parse: parse
};
})();
},{}],3:[function(_dereq_,module,exports){
var CommandJS;
(function (CommandJS) {
"use strict";
var CommandExecutor = _dereq_('./command-executor');
var states = _dereq_('./states');
module.exports = {
ExecutorResponseState: states.ExecutorResponseState,
ExecutorErrorType: states.ExecutorErrorType,
executor: function (commands) {
return new CommandExecutor(commands);
}
};
})(CommandJS || (CommandJS = {}));
},{"./command-executor":1,"./states":4}],4:[function(_dereq_,module,exports){
var CommandJS;
(function (CommandJS) {
(function (ExecutorResponseState) {
ExecutorResponseState[ExecutorResponseState["SUCCESS"] = 0] = "SUCCESS";
ExecutorResponseState[ExecutorResponseState["ERROR"] = 1] = "ERROR";
})(CommandJS.ExecutorResponseState || (CommandJS.ExecutorResponseState = {}));
var ExecutorResponseState = CommandJS.ExecutorResponseState;
(function (ExecutorErrorType) {
ExecutorErrorType[ExecutorErrorType["COMMAND_NOT_FOUND"] = 0] = "COMMAND_NOT_FOUND";
ExecutorErrorType[ExecutorErrorType["PARSER_ERROR"] = 1] = "PARSER_ERROR";
ExecutorErrorType[ExecutorErrorType["COMMAND_EXECUTION_ERROR"] = 2] = "COMMAND_EXECUTION_ERROR";
})(CommandJS.ExecutorErrorType || (CommandJS.ExecutorErrorType = {}));
var ExecutorErrorType = CommandJS.ExecutorErrorType;
module.exports = {
ExecutorResponseState: ExecutorResponseState,
ExecutorErrorType: ExecutorErrorType
};
})(CommandJS || (CommandJS = {}));
},{}]},{},[3])
(3)
}); |
import React, { Component } from 'react';
import * as PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as R from 'ramda';
import Button from '@material-ui/core/Button';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import Dialog from '@material-ui/core/Dialog';
import DialogContent from '@material-ui/core/DialogContent';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogActions from '@material-ui/core/DialogActions';
import { withStyles } from '@material-ui/core/styles';
import {
CenterFocusStrongOutlined,
CenterFocusWeakOutlined,
} from '@material-ui/icons';
import Collapse from '@material-ui/core/Collapse';
import Typography from '@material-ui/core/Typography';
import { T } from '../../../../components/I18n';
import { i18nRegister } from '../../../../utils/Messages';
import { fetchObjectives } from '../../../../actions/Objective';
import { fetchSubobjectives } from '../../../../actions/Subobjective';
import { fetchGroups } from '../../../../actions/Group';
import ObjectivePopover from './ObjectivePopover';
import SubobjectivePopover from './SubobjectivePopover';
import CreateObjective from './CreateObjective';
import ObjectiveView from './ObjectiveView';
import SubobjectiveView from './SubobjectiveView';
i18nRegister({
fr: {
Objectives: 'Objectifs',
'You do not have any objectives in this exercise.':
"Vous n'avez aucun objectif dans cet exercice.",
'Objective view': "Vue de l'objectif",
'Subobjective view': 'Vue du sous-objectif',
},
});
const styles = (theme) => ({
container: {
paddingBottom: '50px',
},
empty: {
marginTop: 30,
fontSize: '18px',
fontWeight: 500,
textAlign: 'center',
},
priority: {
fontSize: 18,
fontWeight: 500,
marginRight: '50px',
},
nested: {
paddingLeft: theme.spacing(4),
},
});
class IndexObjective extends Component {
constructor(props) {
super(props);
this.state = {
openObjective: false,
currentObjective: {},
openSubobjective: false,
currentSubobjective: {},
};
}
componentDidMount() {
this.props.fetchObjectives(this.props.exerciseId);
this.props.fetchSubobjectives(this.props.exerciseId);
this.props.fetchGroups();
}
handleOpenObjective(objective) {
this.setState({ currentObjective: objective, openObjective: true });
}
handleCloseObjective() {
this.setState({ openObjective: false });
}
handleOpenSubobjective(subobjective) {
this.setState({
currentSubobjective: subobjective,
openSubobjective: true,
});
}
handleCloseSubobjective() {
this.setState({ openSubobjective: false });
}
render() {
const { classes } = this.props;
const { exerciseId, objectives } = this.props;
return (
<div className={classes.container}>
<Typography variant="h5" style={{ float: 'left' }}>
<T>Objectives</T>
</Typography>
<div className="clearfix" />
{objectives.length === 0 && (
<div className={classes.empty}>
<T>You do not have any objectives in this exercise.</T>
</div>
)}
<List>
{objectives.map((objective) => {
const nestedItems = objective.objective_subobjectives.map(
(data) => {
const subobjective = R.propOr(
{},
data.subobjective_id,
this.props.subobjectives,
);
const subobjectiveId = R.propOr(
data.subobjective_id,
'subobjective_id',
subobjective,
);
const subobjectiveTitle = R.propOr(
'-',
'subobjective_title',
subobjective,
);
const subobjectiveDescription = R.propOr(
'-',
'subobjective_description',
subobjective,
);
const subobjectivePriority = R.propOr(
'-',
'subobjective_priority',
subobjective,
);
return (
<ListItem
key={subobjectiveId}
onClick={this.handleOpenSubobjective.bind(
this,
subobjective,
)}
button={true}
divider={true}
className={classes.nested}
>
<ListItemIcon>
<CenterFocusWeakOutlined />
</ListItemIcon>
<ListItemText
primary={subobjectiveTitle}
secondary={subobjectiveDescription}
/>
<div className={classes.priority}>
{objective.objective_priority}.{subobjectivePriority}
</div>
{this.props.userCanUpdate && (
<ListItemSecondaryAction>
<SubobjectivePopover
exerciseId={exerciseId}
objectiveId={objective.objective_id}
subobjective={subobjective}
/>
</ListItemSecondaryAction>
)}
</ListItem>
);
},
);
return (
<div key={objective.objective_id}>
<ListItem
onClick={this.handleOpenObjective.bind(this, objective)}
button={true}
divider={true}
>
<ListItemIcon>
<CenterFocusStrongOutlined />
</ListItemIcon>
<ListItemText
primary={objective.objective_title}
secondary={objective.objective_description}
/>
<div className={classes.priority}>
{objective.objective_priority}
</div>
{this.props.userCanUpdate && (
<ListItemSecondaryAction>
<ObjectivePopover
exerciseId={exerciseId}
objective={objective}
/>
</ListItemSecondaryAction>
)}
</ListItem>
<Collapse in={true}>
<List>{nestedItems}</List>
</Collapse>
</div>
);
})}
</List>
<Dialog
open={this.state.openObjective}
onClose={this.handleCloseObjective.bind(this)}
fullWidth={true}
maxWidth="xs"
>
<DialogTitle>
{R.propOr('-', 'objective_title', this.state.currentObjective)}
</DialogTitle>
<DialogContent>
<ObjectiveView objective={this.state.currentObjective} />
</DialogContent>
<DialogActions>
<Button
variant="outlined"
onClick={this.handleCloseObjective.bind(this)}
>
<T>Close</T>
</Button>
</DialogActions>
</Dialog>
<Dialog
open={this.state.openSubobjective}
onClose={this.handleCloseSubobjective.bind(this)}
fullWidth={true}
maxWidth="xs"
>
<DialogTitle>
{R.propOr(
'-',
'subobjective_title',
this.state.currentSubobjective,
)}
</DialogTitle>
<DialogContent>
<SubobjectiveView subobjective={this.state.currentSubobjective} />
</DialogContent>
<DialogActions>
<Button
variant="outlined"
onClick={this.handleCloseSubobjective.bind(this)}
>
<T>Close</T>
</Button>
</DialogActions>
</Dialog>
{this.props.userCanUpdate && (
<CreateObjective exerciseId={exerciseId} />
)}
</div>
);
}
}
IndexObjective.propTypes = {
exerciseId: PropTypes.string,
objectives: PropTypes.array,
subobjectives: PropTypes.object,
fetchObjectives: PropTypes.func.isRequired,
fetchSubobjectives: PropTypes.func.isRequired,
userCanUpdate: PropTypes.bool,
};
const filterObjectives = (objectives, exerciseId) => {
const objectivesFilterAndSorting = R.pipe(
R.values,
R.filter((n) => n.objective_exercise.exercise_id === exerciseId),
R.sortWith([R.ascend(R.prop('objective_priority'))]),
);
return objectivesFilterAndSorting(objectives);
};
const filterSubobjectives = (subobjectives) => {
const subobjectivesSorting = R.pipe(
R.values,
R.sortWith([R.ascend(R.prop('subobjective_priority'))]),
R.indexBy(R.prop('subobjective_id')),
);
return subobjectivesSorting(subobjectives);
};
const checkUserCanUpdate = (state, ownProps) => {
const { id: exerciseId } = ownProps;
const userId = R.path(['logged', 'user'], state.app);
let userCanUpdate = R.path(
[userId, 'user_admin'],
state.referential.entities.users,
);
if (!userCanUpdate) {
const groupValues = R.values(state.referential.entities.groups);
groupValues.forEach((group) => {
group.group_grants.forEach((grant) => {
if (
grant
&& grant.grant_exercise
&& grant.grant_exercise.exercise_id === exerciseId
&& grant.grant_name === 'PLANNER'
) {
group.group_users.forEach((user) => {
if (user && user.user_id === userId) {
userCanUpdate = true;
}
});
}
});
});
}
return userCanUpdate;
};
const select = (state, ownProps) => {
const { id: exerciseId } = ownProps;
const objectives = filterObjectives(
state.referential.entities.objectives,
exerciseId,
);
const subobjectives = filterSubobjectives(
state.referential.entities.subobjectives,
);
const userCanUpdate = checkUserCanUpdate(state, ownProps);
return {
exerciseId,
objectives,
subobjectives,
userCanUpdate,
};
};
export default R.compose(
connect(select, {
fetchObjectives,
fetchSubobjectives,
fetchGroups,
}),
withStyles(styles),
)(IndexObjective);
|
import Action from './Action'
import tryCall from './tryCall'
export default function then (f, r, p, promise) {
p._when(new Then(f, r, promise))
return promise
}
class Then extends Action {
constructor (f, r, promise) {
super(promise)
this.f = f
this.r = r
}
fulfilled (p) {
this.runThen(this.f, p)
}
rejected (p) {
return this.runThen(this.r, p)
}
runThen (f, p) {
if (typeof f !== 'function') {
this.promise._become(p)
return false
}
tryCall(f, p.value, handleThen, this.promise)
return true
}
}
function handleThen (promise, result) {
promise._resolve(result)
}
|
var execSync = require('child_process').execSync,
eslint = require('gulp-eslint'),
gulp = require('gulp'),
mocha = require('gulp-mocha'),
path = require('path'),
spawn = require('child_process').spawn
gulp.task('lint', function () {
return gulp.src([
'src/**/*.js',
'test/**/*.js'
])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError())
})
gulp.task('mocha', function(done) {
gulp
.src([
'./test/setup.js',
'./test/integration/routes.js'
], {read: false})
.pipe(mocha({reporter: 'spec'}))
.on('end', function () {
process.exit()
})
.on('error', function (e) {
console.error(e)
})
})
gulp.task('stop-reqlite', function(done) {
try {
execSync('node_modules/forever/bin/forever stop node_modules/reqlite/lib/node.js --port-offset 1 -s')
}
catch(e) {}
process.exit()
})
gulp.task('test', ['mocha'])
gulp.task('t', ['test'])
|
{
var regexp = /EQUIVALENCE.*$/gm;
var aSpecs = (a.match(regexp) || []).sort().join("\n");
var bSpecs = (b.match(regexp) || []).sort().join("\n");
if (aSpecs.length === 0 && bSpecs.length === 0) {
throw new Error("No spec results found in the output");
}
expect(aSpecs).toEqual(bSpecs);
}
|
module.exports = {
apps: [{
name: 'URL-ShortenerAPI',
script: './source/server.js',
env: {
watch: 'source',
ignore_watch : 'source/gui',
NODE_ENV: 'development',
MONGO_PORT: 28017,
API_PORT: 8000
},
env_production: {
watch: false,
NODE_ENV: 'production',
HOOK_PORT: 8813,
MONGO_PORT: 27017,
API_PORT: 8080
}
}],
deploy: {
production: {
'user': 'adminus',
'host': '138.68.183.160',
'ref': 'origin/master',
'repo': 'git@github.com:taxnuke/url-shortener.git',
'path': '/var/www/short.taxnuke.ru',
'post-deploy':
'npm i && npm run build && pm2 startOrReload ecosystem.config.js \
--update-env --env production'
}
}
}
|
'use strict'
module.exports = {
// Format a string for terminal ouptut
formatString: require('./methods/format-string'),
// JSON pretty print
json: require('./methods/json'),
// Send notification via pushover
notify: require('./methods/notify'),
// Gets a random array item
getRandom: require('./methods/get-random'),
// List available class methods
getMethods: require('./methods/get-methods')
}
|
var results;
function viewData()
{
var resultsTable = $('<table></table>').attr('id', 'results');
var tableHead = $("<thead></thead>");
var tableBody = $("<tbody></tbody>");
var temp;
$.post("/api/Data/Query/",
{
name: $('#name').val(),
query: $('#query').val(),
server: $('#server').val(),
description: $('#description').val()
},
function(data, status){})
.done(function(data)
{
data = JSON.parse(data);
//Take care of the headers
var columnSet = [];
var tableHeadRow = $("<tr></tr>");
for (var key in data[0])
{
if ($.inArray(key, columnSet) == -1)
{
columnSet.push(key);
tableHeadRow.append($('<th/>').html(key));
}
}
tableHead.append(tableHeadRow);
//Take care of the data
for(i = 0; i < 10 || i == data.length; i++)
{
row = data[i];
var tableBodyRow = $("<tr></tr>");
$.each(row, function(j, field)
{
tableBodyRow.append($('<td/>').html(field));
});
tableBody.append(tableBodyRow);
}
buildSelect("Dependent",columnSet,"Dependent");
buildSelect("Independent",columnSet,"Independent");
$('#main').append('<button class="btn grey" type="button" onclick="buildChart()">Build Chart</button>');
$('#main').append('<br>');
$('#main').append('<br>');
$('#main').append('<br>');
results = data;
});
//Append Everything
resultsTable.append(tableHead);
resultsTable.append(tableBody);
resultsTable.addClass("centered");
resultsTable.addClass("highlight");
$('#main').append(resultsTable);
}
function buildChart()
{
$('#myChart').remove();
$('#main').append('<canvas id="myChart" width="500" height="500"></canvas>');
var depend = $('#Dependent').find(":selected").text();
var independ = $('#Independent').find(":selected").text();
var labels = [];
var data = [];
var color = [];
$.each(results, function(j, row)
{
labels.push(row[independ]);
data.push(row[depend]);
color.push(colorGenerator());
});
var data = {
labels: labels,
datasets: [{
data: data,
backgroundColor: color,
hoverBackgroundColor: color}]
};
var ctx = document.getElementById("myChart");
var chart = new Chart(ctx,{
type: 'pie',
data: data,
options: {responsive: false, maintainAspectRatio: false}
});
$('#saveBtn').remove();
$('#main').append('<button class="btn grey" id="saveBtn" type="button" onclick="persistChart()">Save Chart</button>');
$('#main').append('<br>');
}
//
//
//
function buildSelect(ID, options, name)
{
var division = $('<div class="input-field col s12" id="'+ID+'"></div>');
var selectBox = $("<select id='"+name+"'></select>");
for(var x in options)
{
var option = $("<option value="+options[x]+">"+options[x]+"</option>");
selectBox.append(option);
}
var option = $('<option value="0" disabled selected>Choose your option</option>');
selectBox.append(option);
var labelBox = $("<label>"+name+"</label>");
division.append(selectBox);
division.append(labelBox);
$('#main').append(division);
$('select').material_select();
}
//
//
//
function persistChart()
{
$.post("/api/Charts/Create/",
{
name: $('#name').val(),
query: $('#query').val(),
server: $('#server').val(),
description: $('#description').val(),
dependent: $('#Dependent').find(":selected").text(),
independent: $('#Independent').find(":selected").text()
},
function(data, status){})
.done(function(data)
{
alert("Chart Saved");
});
}
|
/*
* remotejs
* Controls iTunes from your browser
*
* Copyright (c) 2013 Jeffrey Muller
* Licensed under the MIT license.
*/
app.music = {
songMetadata: function(song) {
return {
'song': song,
'artist': (song.artist !== null) ? app.library.artists[song.artist] : null,
'album': (song.album !== null) ? app.library.albums[song.album] : null
};
},
artistMetadata: function(artist) {
var songs = [];
var albums = [];
for (var i = 0; i < artist.songs.length; i++) {
songs.push(app.library.songs[artist.songs[i]]);
}
for (var i = 0; i < artist.albums.length; i++) {
albums.push(app.library.albums[artist.albums[i]]);
}
return {
'artist': artist,
'songs': songs,
'albums': albums
};
},
onVolumeSliderChanged: function(event) {
var sliderValue = $(event.currentTarget).val();
app.socket.emit('change volume', { value: sliderValue });
},
renderPlayerData: function(data) {
if (data.playing === true)
$('.play-pause').removeClass('fa-play').addClass('fa-pause');
else
$('.play-pause').removeClass('fa-pause').addClass('fa-play');
$('.song-data h1').text(data.current_song);
$('.song-data h3').text(data.current_artist);
$('input[type=range].volume').val(data.volume);
},
togglePlay: function() {
if ($('.play-pause').hasClass('fa-play'))
app.socket.emit('play');
else
app.socket.emit('pause');
}
};
setTimeout(function() {
app.socket.on('paused', function () {
$('.play-pause').removeClass('fa-pause').addClass('fa-play');
});
app.socket.on('played', function () {
$('.play-pause').removeClass('fa-play').addClass('fa-pause');
});
app.socket.on('volume', function(packet) {
$('input[type=range].volume').val(packet.value);
});
app.socket.on('player data', function (packet) {
app.music.renderPlayerData(packet);
});
$('.play-pause').click(app.music.togglePlay);
$('input[type=range].volume').on('click touchend', app.music.onVolumeSliderChanged);
}, 100); |
/**
* Relies on Googoose for the basic exportation to Winword.
* This javascript file is loaded by marknotes **only when Pandoc isn't
* correctly installed.**
*
* When Pandoc is installed, this script isn't included by marknotes since
* the action behind the "Download as .docx file" will be immedialty a
* link to the note.docx file.
*
* The fnPluginHTMLDOCX will be called by the "Docx" button of the content's
* toolbar
/ @link https://github.com/aadel112/googoose
*/
function fnPluginHTMLDOCX() {
/*<!-- build:debug -->*/
if (marknotes.settings.debug) {
console.log(' Plugin Page html - DOCX');
}
/*<!-- endbuild -->*/
// When the user has clicked on a note from the treeview, the jstree_init()
// function (from jstree.js) has initialized the marknotes.note.file
// variable to 'objNode.data.file' i.e. the data-file info of that
// node and that info is set by the PHP listFiles task to the relative
// filename of the note without any extension (so, f.i.
// folder/documentation/marknotes and not the full file like
// http://localhost/docs/folder/documentation/marknotes.html)
if (marknotes.note.file == '') {
// The user click on the Reveal button but should first select
// a note in the treeview
Noty({
message: $.i18n('error_select_first'),
type: 'error'
});
} else {
// The extension for Googoose should be .DOC and not .DOCX
var fname = marknotes.note.basename + '.doc';
/*<!-- build:debug -->*/
if (marknotes.settings.debug) {
console.log(' Generate ' + fname);
}
/*<!-- endbuild -->*/
// Load clipboard.min.js
// @link @https://github.com/zenorocha/clipboard.js
// Then handle the click on the button
$.ajax({
"type": "GET",
"url": "marknotes/plugins/page/html/docx/libs/googoose/jquery.googoose.js",
"dataType": "script",
"cache": true,
"async": false,
"success": function (data) {
// See https://github.com/aadel112/googoose#options for
// explanation of the options
var o = {
area: 'article', // The content is inside the article tag
lang: marknotes.settings.locale, // language of the content
filename: fname // name of the file, will be the one of the downloaded file
};
try {
// Googoose will not export the note's title if
// that title is hidden so, check if we need to show
// it => show it, export and hide it back
var $bVisible = $('#CONTENT h1').is(':visible');
if (!$bVisible) $('#CONTENT h1').show();
$(document).googoose(o);
if (!$bVisible) $('#CONTENT h1').hide();
} catch (e) {
console.warn('Error when trying to convert with Googoose : [' + e.message + ']');
}
}
});
}
return true;
}
|
"use strict";
var express = require('express');
var app = express(); // define our app using express
var path = require('path');
var fs = require('fs')
var handlebars = require('express-handlebars'), hbs;
var bodyParser = require('body-parser');
// handlebars template engine
hbs = handlebars.create({ defaultLayout: '_default.hview' });
app.engine('hview', hbs.engine); // hview is a custom extension (hence any extension name can be used)
app.set('port', 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hview');
//app.use(express.favicon());
app.use(express.static(path.join(__dirname, 'assets')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// dynamically include routes (from Controllers)
fs.readdirSync('./controllers').forEach(function (file) {
if(file.substr(-3) == '.js') {
// var route = require('./controllers/' + file); // these 2 lines result the same as uncommented one
// route.controller(app);
require('./controllers/' + file).controller(app);
/* passes the app instance to controller
(means controllers are imported, but don't have to be binded to a variable
since they're using app instance already)
*/
}
});
// custom 404 page (middleware) - MUST be placed after controllers because they have already defined valid routes
app.use(function(req,res,next){ res.status(404); res.render("layouts/_404.hview"); }); //error page
app.listen(app.get('port'));
console.log("Server listening on localhost:" + app.get('port'));
|
let dice1; let dice2; let dice3; let dice4; let dice5; let dice6;
let dice;
function preload(){
dice1 = loadImage("images/dice-1.png");
dice2 = loadImage("images/dice-2.png");
dice3 = loadImage("images/dice-3.png");
dice4 = loadImage("images/dice-4.png");
dice5 = loadImage("images/dice-5.png");
dice6 = loadImage("images/dice-6.png");
}
function switchDice(number){
switch(number){
case 1: dice = dice1; break;
case 2: dice = dice2; break;
case 3: dice = dice3; break;
case 4: dice = dice4; break;
case 5: dice = dice5; break;
case 6: dice = dice6; break;
}
}
function GameScreen(name1,name2){
let player1;
let player2;
let turn = 1;
let rolling;
let rollBtn; let holdBtn; let homeBtn; let newBtn;
let gameOver = false;
this.player1Name = name1;
this.player2Name = name2;
this.setup = ()=>{
homeBtn = createButton("Home").size(150,50).position(windowWidth/2-100,60).addClass("red");
homeBtn.mousePressed(this.goHome);
newBtn = createButton("New Game").size(150,50).position(windowWidth/2+100,60).addClass("red");
newBtn.mousePressed(this.newGame);
rollBtn = createButton("Roll Dice").position(windowWidth/2,windowHeight-120-80);
rollBtn.mousePressed(this.startRoll);
holdBtn = createButton("Hold Roll").position(windowWidth/2,windowHeight-120).addClass("red");
holdBtn.mousePressed(this.hold);
player1 = new Player(this.player1Name,0,0,width/2,height);
player2 = new Player(this.player2Name,width/2,0,width/2,height);
switchDice(Math.floor(random(1,6)));
}
this.draw = ()=>{
if(turn === 1){
player1.active = true;
player2.active = false;
}else{
player1.active = false;
player2.active = true;
}
player1.show();
player2.show();
if(!gameOver){
this.showDice();
}
}
this.showDice = ()=>{
fill(0);
rectMode(CENTER);
rect(width/2,height/2,150,150,5);
imageMode(CENTER);
image(dice,width/2,height/2,135,135);
}
this.startRoll = ()=>{
rollBtn.attribute("disabled","");
switchDice(1);
rolling = setInterval(function(){
let suffle = Math.floor(random(2,6));
switchDice(suffle);
},100);
setTimeout(this.diceRolled,1000);
}
this.diceRolled = ()=>{
clearInterval(rolling);
let rolled = Math.floor(random(1,6));
switchDice(rolled);
rollBtn.removeAttribute("disabled");
if(rolled == 1){
this.dead();
return;
}
if(turn == 1){
player1.addScore(rolled);
}else{
player2.addScore(rolled);
}
}
this.dead = ()=>{
if(turn == 1){
player1.score = 0;
this.hold();
}else{
player2.score = 0;
this.hold();
}
}
this.hold = ()=>{
if(turn == 1){
if(!player1.hold()){
turn = 2;
}
}else{
if(!player2.hold()){
turn = 1;
}
}
}
this.newGame = ()=>{
if(!gameOver){
let reset = confirm("Do you want to reset?");
if(!reset){
return;
}
homeBtn.remove(); newBtn.remove(); rollBtn.remove(); holdBtn.remove();
}else{
homeBtn.remove();
newBtn.remove();
}
player1.score = 0;
player1.total = 0;
player2.score = 0;
player2.total = 0;
turn = 1;
gameOver = false;
this.setup();
}
this.goHome = ()=>{
if(!gameOver){
let goHome = confirm("Do you want to exit?");
if(!goHome){
return;
}
}
this.hide();
home();
}
this.hide = ()=>{
rollBtn.remove();
holdBtn.remove();
homeBtn.remove();
newBtn.remove();
}
this.gameOver = ()=>{
rollBtn.remove();
holdBtn.remove();
gameOver = true;
}
} |
function result() {
this.insert_id = 0
this.affected_rows = 0
this.rows = []
}
module.exports = result |
import { toBeDeepCloseTo } from 'jest-matcher-deep-close-to';
import {
highResolution4,
highResolution,
simple,
} from '../../../testFiles/examples';
expect.extend({ toBeDeepCloseTo });
describe('merge: Low resolution', () => {
it('no options', () => {
let result = simple.merge();
result.x = Array.from(result.x);
result.y = Array.from(result.y);
expect(result).toStrictEqual({
x: [100, 101, 200, 201, 300, 301],
y: [10, 11, 20, 21, 30, 31],
from: { index: 0, time: 1 },
to: { index: 1, time: 2 },
});
});
it('time range', () => {
let result = simple.merge({ range: { from: 1, to: 1 } });
result.x = Array.from(result.x);
result.y = Array.from(result.y);
expect(result).toStrictEqual({
x: [100, 200, 300],
y: [10, 20, 30],
from: { index: 0, time: 1 },
to: { index: 0, time: 1 },
});
});
it('time range to high', () => {
let result = simple.merge({ range: { from: 2, to: 100 } });
result.x = Array.from(result.x);
result.y = Array.from(result.y);
expect(result).toStrictEqual({
x: [101, 201, 301],
y: [11, 21, 31],
from: { index: 1, time: 2 },
to: { index: 1, time: 2 },
});
});
it('outside time range', () => {
let result = simple.merge({ range: { from: 10, to: 11 } });
expect(result).toStrictEqual({
x: [],
y: [],
});
});
});
describe('merge: High resolution', () => {
it('no options', () => {
let result = highResolution.merge();
expect(result).toBeDeepCloseTo({
x: [100.00147619047618, 200.0148780487805, 300.00014918032787],
y: [21, 41, 61],
from: { index: 0, time: 1 },
to: { index: 1, time: 2 },
});
});
it('no options and 4 spectra', () => {
let result = highResolution4.merge();
expect(result).toBeDeepCloseTo({
x: [100.05858333333335, 200.00119999999998, 300],
y: [60, 25, 32],
from: { index: 0, time: 1 },
to: { index: 3, time: 4 },
});
});
it('small threhold', () => {
let result = highResolution.merge({ mergeThreshold: 0.00001 });
result.x = Array.from(result.x);
result.y = Array.from(result.y);
expect(result).toBeDeepCloseTo({
x: [100.001, 100.002, 200.01, 200.02, 300.0001, 300.0002],
y: [11, 10, 21, 20, 31, 30],
from: { index: 0, time: 1 },
to: { index: 1, time: 2 },
});
});
it('wrong seriesName', () => {
expect(() => highResolution.merge({ seriesName: 'abc' })).toThrow(
'The series "abc"',
);
});
});
|
var clv = require("../../../../index.js");
var assert = require("assert");
describe("Generated test - rm/ins/undo/undo/rm/ins/ins/rm/ins/ins - 10-ops-3cb06c80-722e-4eaa-a5f7-7068c46db475", function() {
var doc1 = new clv.string.Document("163cfd90-537e-11e7-a087-55438491864c", 0, null);
var doc2 = new clv.string.Document("163ef960-537e-11e7-a087-55438491864c", 0, null);
var doc3 = new clv.string.Document("16408000-537e-11e7-a087-55438491864c", 0, null);
var data1 = "Hello World";
var data2 = "Hello World";
var data3 = "Hello World";
var serverData = {"id":"bee1c52d-25cd-4f08-ae1f-fb646628cdb9","data":"Hello World","ops":[],"execOrder":0,"context":null};
it("Site 163cfd90-537e-11e7-a087-55438491864c operations should be executed without errors", function() {
var commit1 = [{"type":1,"at":5,"value":" Wo"}];
var commitTuple1 = doc1.commit(commit1);
data1 = clv.string.exec(data1, commitTuple1.toExec);
var update1 = [{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":5,"value":" Wo"},"execOrder":1}];
var updateTuple1 = doc1.update(update1);
data1 = clv.string.exec(data1, updateTuple1.toExec);
var update2 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":5,"value":"r"},"execOrder":2}];
var updateTuple2 = doc1.update(update2);
data1 = clv.string.exec(data1, updateTuple2.toExec);
var commit2 = [{"type":0,"at":6,"value":"t"}];
var commitTuple2 = doc1.commit(commit2);
data1 = clv.string.exec(data1, commitTuple2.toExec);
var update3 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":6,"value":"ld"},"execOrder":3},{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0},"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"t"},"execOrder":4}];
var updateTuple3 = doc1.update(update3);
data1 = clv.string.exec(data1, updateTuple3.toExec);
var update4 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":3,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"wq"},"execOrder":5}];
var updateTuple4 = doc1.update(update4);
data1 = clv.string.exec(data1, updateTuple4.toExec);
var commitTuple3 = doc1.undo();
data1 = clv.string.exec(data1, commitTuple3.toExec);
var update5 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":4,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":3,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"q"},"execOrder":6},{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0},"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":1,"at":6,"value":"t"},"execOrder":7}];
var updateTuple5 = doc1.update(update5);
data1 = clv.string.exec(data1, updateTuple5.toExec);
var commitTuple4 = doc1.undo();
data1 = clv.string.exec(data1, commitTuple4.toExec);
var update6 = [{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":5,"value":" Wo"},"execOrder":8}];
var updateTuple6 = doc1.update(update6);
data1 = clv.string.exec(data1, updateTuple6.toExec);
var update7 = [{"siteId":"163ef960-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{"1":1,"2":1},"invClusterSize":2},"16408000-537e-11e7-a087-55438491864c":{"seqId":4,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":1,"value":"e"},"execOrder":9},{"siteId":"163ef960-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{"1":1,"2":1},"invClusterSize":2},"16408000-537e-11e7-a087-55438491864c":{"seqId":4,"invCluster":{},"invClusterSize":0},"163ef960-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":3},"invCount":0,"load":{"type":0,"at":6,"value":"t"},"execOrder":10}];
var updateTuple7 = doc1.update(update7);
data1 = clv.string.exec(data1, updateTuple7.toExec);
});
it("Site 163ef960-537e-11e7-a087-55438491864c operations should be executed without errors", function() {
var update1 = [{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":5,"value":" Wo"},"execOrder":1}];
var updateTuple1 = doc2.update(update1);
data2 = clv.string.exec(data2, updateTuple1.toExec);
var update2 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":5,"value":"r"},"execOrder":2}];
var updateTuple2 = doc2.update(update2);
data2 = clv.string.exec(data2, updateTuple2.toExec);
var update3 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":6,"value":"ld"},"execOrder":3},{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0},"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"t"},"execOrder":4}];
var updateTuple3 = doc2.update(update3);
data2 = clv.string.exec(data2, updateTuple3.toExec);
var update4 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":3,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"wq"},"execOrder":5}];
var updateTuple4 = doc2.update(update4);
data2 = clv.string.exec(data2, updateTuple4.toExec);
var update5 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":4,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":3,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"q"},"execOrder":6}];
var updateTuple5 = doc2.update(update5);
data2 = clv.string.exec(data2, updateTuple5.toExec);
var update6 = [{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0},"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":1,"at":6,"value":"t"},"execOrder":7},{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":5,"value":" Wo"},"execOrder":8}];
var updateTuple6 = doc2.update(update6);
data2 = clv.string.exec(data2, updateTuple6.toExec);
var commit1 = [{"type":1,"at":1,"value":"e"}];
var commitTuple1 = doc2.commit(commit1);
data2 = clv.string.exec(data2, commitTuple1.toExec);
var update7 = [{"siteId":"163ef960-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{"1":1,"2":1},"invClusterSize":2},"16408000-537e-11e7-a087-55438491864c":{"seqId":4,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":1,"value":"e"},"execOrder":9}];
var updateTuple7 = doc2.update(update7);
data2 = clv.string.exec(data2, updateTuple7.toExec);
var commit2 = [{"type":0,"at":6,"value":"t"}];
var commitTuple2 = doc2.commit(commit2);
data2 = clv.string.exec(data2, commitTuple2.toExec);
var update8 = [{"siteId":"163ef960-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{"1":1,"2":1},"invClusterSize":2},"16408000-537e-11e7-a087-55438491864c":{"seqId":4,"invCluster":{},"invClusterSize":0},"163ef960-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":3},"invCount":0,"load":{"type":0,"at":6,"value":"t"},"execOrder":10}];
var updateTuple8 = doc2.update(update8);
data2 = clv.string.exec(data2, updateTuple8.toExec);
});
it("Site 16408000-537e-11e7-a087-55438491864c operations should be executed without errors", function() {
var commit1 = [{"type":0,"at":5,"value":"r"}];
var commitTuple1 = doc3.commit(commit1);
data3 = clv.string.exec(data3, commitTuple1.toExec);
var update1 = [{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":5,"value":" Wo"},"execOrder":1}];
var updateTuple1 = doc3.update(update1);
data3 = clv.string.exec(data3, updateTuple1.toExec);
var commit2 = [{"type":1,"at":6,"value":"ld"}];
var commitTuple2 = doc3.commit(commit2);
data3 = clv.string.exec(data3, commitTuple2.toExec);
var update2 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":5,"value":"r"},"execOrder":2}];
var updateTuple2 = doc3.update(update2);
data3 = clv.string.exec(data3, updateTuple2.toExec);
var update3 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":6,"value":"ld"},"execOrder":3}];
var updateTuple3 = doc3.update(update3);
data3 = clv.string.exec(data3, updateTuple3.toExec);
var commit3 = [{"type":0,"at":6,"value":"wq"}];
var commitTuple3 = doc3.commit(commit3);
data3 = clv.string.exec(data3, commitTuple3.toExec);
var update4 = [{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0},"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"t"},"execOrder":4}];
var updateTuple4 = doc3.update(update4);
data3 = clv.string.exec(data3, updateTuple4.toExec);
var commit4 = [{"type":0,"at":2,"value":"q"}];
var commitTuple4 = doc3.commit(commit4);
data3 = clv.string.exec(data3, commitTuple4.toExec);
var update5 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":3,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"wq"},"execOrder":5}];
var updateTuple5 = doc3.update(update5);
data3 = clv.string.exec(data3, updateTuple5.toExec);
var update6 = [{"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":4,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":3,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"q"},"execOrder":6}];
var updateTuple6 = doc3.update(update6);
data3 = clv.string.exec(data3, updateTuple6.toExec);
var update7 = [{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0},"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":1,"at":6,"value":"t"},"execOrder":7}];
var updateTuple7 = doc3.update(update7);
data3 = clv.string.exec(data3, updateTuple7.toExec);
var update8 = [{"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":5,"value":" Wo"},"execOrder":8}];
var updateTuple8 = doc3.update(update8);
data3 = clv.string.exec(data3, updateTuple8.toExec);
var update9 = [{"siteId":"163ef960-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{"1":1,"2":1},"invClusterSize":2},"16408000-537e-11e7-a087-55438491864c":{"seqId":4,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":1,"value":"e"},"execOrder":9}];
var updateTuple9 = doc3.update(update9);
data3 = clv.string.exec(data3, updateTuple9.toExec);
var update10 = [{"siteId":"163ef960-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{"1":1,"2":1},"invClusterSize":2},"16408000-537e-11e7-a087-55438491864c":{"seqId":4,"invCluster":{},"invClusterSize":0},"163ef960-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":3},"invCount":0,"load":{"type":0,"at":6,"value":"t"},"execOrder":10}];
var updateTuple10 = doc3.update(update10);
data3 = clv.string.exec(data3, updateTuple10.toExec);
});
it("Server operations should be executed without errors", function() {
function updateServer(op) {
var server = new clv.string.Document(null, serverData.execOrder, serverData.context);
server.update(serverData.ops);
var serverTuple = server.update(op);
serverData.data = clv.string.exec(serverData.data, serverTuple.toExec);
serverData.context = server.getContext();
serverData.ops.push(op);
serverData.execOrder = server.getExecOrder();
}
var serverUpdate0 = {"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":1,"at":5,"value":" Wo"},"execOrder":1};
updateServer(serverUpdate0);
var serverUpdate1 = {"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{},"size":0},"invCount":0,"load":{"type":0,"at":5,"value":"r"},"execOrder":2};
updateServer(serverUpdate1);
var serverUpdate2 = {"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":6,"value":"ld"},"execOrder":3};
updateServer(serverUpdate2);
var serverUpdate3 = {"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0},"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"t"},"execOrder":4};
updateServer(serverUpdate3);
var serverUpdate4 = {"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":3,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":6,"value":"wq"},"execOrder":5};
updateServer(serverUpdate4);
var serverUpdate5 = {"siteId":"16408000-537e-11e7-a087-55438491864c","seqId":4,"context":{"vector":{"16408000-537e-11e7-a087-55438491864c":{"seqId":3,"invCluster":{},"invClusterSize":0},"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":0,"at":2,"value":"q"},"execOrder":6};
updateServer(serverUpdate5);
var serverUpdate6 = {"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{},"invClusterSize":0},"16408000-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":1,"load":{"type":1,"at":6,"value":"t"},"execOrder":7};
updateServer(serverUpdate6);
var serverUpdate7 = {"siteId":"163cfd90-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":1},"invCount":1,"load":{"type":0,"at":5,"value":" Wo"},"execOrder":8};
updateServer(serverUpdate7);
var serverUpdate8 = {"siteId":"163ef960-537e-11e7-a087-55438491864c","seqId":1,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{"1":1,"2":1},"invClusterSize":2},"16408000-537e-11e7-a087-55438491864c":{"seqId":4,"invCluster":{},"invClusterSize":0}},"size":2},"invCount":0,"load":{"type":1,"at":1,"value":"e"},"execOrder":9};
updateServer(serverUpdate8);
var serverUpdate9 = {"siteId":"163ef960-537e-11e7-a087-55438491864c","seqId":2,"context":{"vector":{"163cfd90-537e-11e7-a087-55438491864c":{"seqId":2,"invCluster":{"1":1,"2":1},"invClusterSize":2},"16408000-537e-11e7-a087-55438491864c":{"seqId":4,"invCluster":{},"invClusterSize":0},"163ef960-537e-11e7-a087-55438491864c":{"seqId":1,"invCluster":{},"invClusterSize":0}},"size":3},"invCount":0,"load":{"type":0,"at":6,"value":"t"},"execOrder":10};
updateServer(serverUpdate9);
});
it("All sites should have same data with the server", function() {
assert.equal(data1, serverData.data, "Site 1 data should be equal to server");
assert.equal(data2, serverData.data, "Site 2 data should be equal to server");
assert.equal(data3, serverData.data, "Site 3 data should be equal to server");
});
});
|
_.mixin({
on : function(obj, event, callback) {
// Define a global Observer
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
if(this.isUndefined(obj._events)) obj._events = {};
if (!(event in obj._events)) obj._events[event] = [];
obj._events[event].push(callback);
return this;
},
once : function(obj, event, callback) {
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
var removeEvent = function() { _.removeEvent(obj, event); };
callback = _.compose(removeEvent, callback);
this.on(obj, event, callback);
},
emit : function(obj, event, args){
if(this.isString(obj)) {
callback = event;
event = obj;
obj = this;
}
if(this.isUndefined(obj._events)) return;
if (event in obj._events) {
var events = obj._events[event].concat();
for (var i = 0, ii = events.length; i < ii; i++)
events[i].apply(obj, args === undefined ? [] : args);
}
return this;
},
removeEvent : function(obj, event) {
if(this.isString(obj)) { event = obj; obj = this; }
if(this.isUndefined(obj._events)) return;
console.log("remove");
delete obj._events[event];
}
});
_.mixin({
deepClone:function(obj, deep)
{
if (!_.isObject(obj) || this.isFunction(obj)) return obj;
if (this.isDate(obj)) return new Date(obj.getTime());
if (this.isRegExp(obj)) return new RegExp(obj.source, obj.toString().replace(/.*\//, ""));
var isArr = (this.isArray(obj) || this.isArguments(obj));
if (deep) {
var func = function (memo, value, key) {
if (isArr)
memo.push(_.clone(value, true));
else
memo[key] = _.clone(value, true);
return memo;
};
return this.reduce(obj, func, isArr ? [] : {});
} else {
return isArr ? slice.call(obj) : this.extend({}, obj);
}
}
});
|
/*Made by *** for learning perpouses
Feel free to use it as you see fit.
*/
var JSConsol;
function CreateConsol() {
JSConsol = function Consol() {
/*create stack of functions w8 for input*/
var awaitInputStack = new Array();
/*create execution list*/
var execList = new Array();
/*create body*/
var consol = document.createElement('div');
;
(function () {
consol.setAttribute('id', 'consol')
consol.style.backgroundColor = "black";
consol.style.height = '100%';
consol.style.margin = '0';
}());
//append the consol to body upon loading
window.addEventListener("DOMContentLoaded",
function () {
document.getElementsByTagName('body')[0].appendChild(consol);
document.getElementsByTagName('body')[0].style.backgroundColor = 'black';
//load the scripts that need to be executed
for (var i = 0; i < execList.length; i++) {
var newSctipt = document.createElement('script');
newSctipt.setAttribute("type", "text/javascript")
newSctipt.setAttribute("src", execList[i]);
document.getElementsByTagName('body')[0].appendChild(newSctipt);
}
input.focus();
}, true);
//creating the output
var output = document.createElement("label");
var outputText = document.createElement("pre");
(function (){
outputText.style.margin = '0';
output.appendChild(outputText);
output.style.border = '0';
output.style.color = "white";
output.style.backgroundColor = 'transparent';
output.style.width = "100%";
outputText.style.fontFamily = "Consolas";
output.disabled = true;
consol.appendChild(output);
outputText.innerHTML = "Console JS.\nDeveloped for Telerik Academy by ***\n";
}());
//creating the input
var input = document.createElement('input');
(function (){
input.setAttribute('type', 'text');
input.setAttribute('id', 'console-input');
input.style.border = '0';
input.style.color = "white";
input.style.backgroundColor = 'transparent';
input.style.width = "100%";
input.style.fontFamily = "Consolas";
input.style.outlineWidth = '0';
input.style.margin = 0;
input.style.padding = 0;
input.style.fontFamily = "consolas";
input.style.fontSize = '1em';
consol.appendChild(input);
}());
//Global error handling
(function () {
window.onerror = function (errorMsg, url, lineNumber) {
writeLine("ERROR!!!\nOff file: " + url + "\nFrom :" + Number);
writeLine(errorMsg);
}
}());
/*initialize code input*/
(function (){
input.onkeyup=function(event){
if (event.keyCode == 13) {
if (awaitInputStack.length == 0) {
/*Read and execute command */
var toBeEvaluated = input.value;
input.value = "";
writeLine(toBeEvaluated);
writeLine(eval(toBeEvaluated));
} else {
var parameter = input.value;
input.value = "";
writeLine(parameter);
awaitInputStack.pop()(parameter);
}
}
}
}());
/*private function*/
function readLine(message) {
var result = window.prompt(message ? message : "PLease enter your data:","");
outputText.innerHTML += (message ? message : "PLease enter your data:") + result + '\n';
return result;
}
function writeLine(string) {
outputText.innerHTML += string + '\n';
input.scrollIntoView();
input.focus();
}
function write(string) {
outputText.innerHTML += string;
input.scrollIntoView();
input.focus();
}
/*after an input fromt the user instead of evaluating the string
it passes it as a parameter to the given function. Prints nothing.
!!! ATENTION-After the first executino of the function every next input will
be evaluated (unles the function itself calls readLineFN*/
function readLineFN(func) {
awaitInputStack.push(func);
input.focus();
};
/*Use this function to load your script*/
function loadSrcipt(src) {
execList.unshift(src);
}
return {
'readLine': readLine,
'readLineFN': readLineFN,
'writeLine': writeLine,
'write': write,
'loadSrcipt': loadSrcipt
}
}();
};
CreateConsol(); |
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, triggerEvent } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import $ from 'jquery';
module('Integration | Component | fm-widget:radio', function(hooks) {
setupRenderingTest(hooks);
test('action onUserAction is sent on focus out event', async function(assert) {
assert.expect(1);
this.set('externalAction', () => assert.ok(true));
await render(hbs`{{fm-widgets/radio onUserInteraction=(action this.externalAction)}}`);
$('input').trigger('focusout');
});
test('action onUserAction is sent on change event', async function(assert) {
assert.expect(1);
this.set('externalAction', () => assert.ok(true));
await render(hbs`{{fm-widgets/radio onUserInteraction=(action this.externalAction)}}`);
await triggerEvent('input', 'change');
});
});
|
/*globals define*/
/*eslint-env node, browser*/
/**
* Plugin illustrating how to merge branches/commits.
*
* @author lattmann / https://github.com/lattmann
* @module CorePlugins:MergeExample
*/
define([
'plugin/PluginConfig',
'plugin/PluginBase',
'text!./metadata.json',
'common/core/users/merge',
'q',
'common/regexp'
], function (PluginConfig, PluginBase, pluginMetadata, merge, Q, REGEXP) {
'use strict';
pluginMetadata = JSON.parse(pluginMetadata);
/**
* Initializes a new instance of MergeExample.
* @class
* @augments {PluginBase}
* @classdesc This class represents the plugin MergeExample.
* @constructor
*/
function MergeExample() {
// Call base class' constructor.
PluginBase.call(this);
this.pluginMetadata = pluginMetadata;
}
MergeExample.metadata = pluginMetadata;
// Prototypal inheritance from PluginBase.
MergeExample.prototype = Object.create(PluginBase.prototype);
MergeExample.prototype.constructor = MergeExample;
/**
* Main function for the plugin to execute. This will perform the execution.
* Notes:
* - Always log with the provided logger.[error,warning,info,debug].
* - Do NOT put any user interaction logic UI, etc. inside this method.
* - callback always has to be called even if error happened.
*
* @param {function(string, plugin.PluginResult)} callback - the result callback
*/
MergeExample.prototype.main = function (callback) {
// Use self to access core, project, result, logger etc from PluginBase.
// These are all instantiated at this point.
var self = this,
newBranchName;
// Obtain the current user configuration.
var currentConfig = self.getCurrentConfig();
self.logger.info('Current configuration ' + JSON.stringify(currentConfig, null, 4));
newBranchName = currentConfig.createNewBranch ? currentConfig.newBranchName : null;
function resolutionStrategy(result) {
// set the resolution as needed, then return with the object.
return result;
}
self.merge(currentConfig.mergeFrom, currentConfig.mergeTo, newBranchName, resolutionStrategy)
.then(function (result) {
// if merged without any conflicts the result structure is
// result.baseCommitHash
// result.conflict
// result.diff
// result.myCommitHash
// result.projectId
// result.targetBranchName
// result.theirCommitHash
// result.finalCommitHash
// if resolved and a branch got updatedthe result structure as follows
// result.updatedBranch
// result.hash
// if resolved and only commit is created the result structure as follows
// result is a commit hash itself
var resultHash = result.finalCommitHash || result.hash || result,
resultBranch = result.targetBranchName || result.updatedBranch;
if (resultBranch) {
self.createMessage(null, 'Successfully updated branch.', 'info');
} else {
self.createMessage(null, 'Failed to update branch, but merge commit got created ' +
resultHash, 'warn');
}
self.logger.info(result);
self.result.setSuccess(true);
callback(null, self.result);
})
.catch(function (err) {
self.result.setSuccess(false);
self.result.setError(err.message);
callback(err, self.result);
});
};
/**
* Creates a new branch from an existing branch or commit hash if new branch name is given and it is not the same
* as the branchNameOrCommitHash.
*
* @param branchNameOrCommitHash
* @param newBranchName
* @returns {*}
*/
MergeExample.prototype.ensureBranch = function (branchNameOrCommitHash, newBranchName) {
var self = this,
deferred = Q.defer(),
getCommitHash = function (commitOrBranch) {
var commitDeferred = Q.defer();
if (REGEXP.HASH.test(commitOrBranch)) {
commitDeferred.resolve(commitOrBranch);
} else {
self.project.getBranches()
.then(function (branches) {
commitDeferred.resolve(branches[commitOrBranch]);
})
.catch(commitDeferred.reject);
}
return commitDeferred.promise;
};
if (newBranchName && branchNameOrCommitHash !== newBranchName) {
getCommitHash(branchNameOrCommitHash)
.then(function (commitHash) {
return self.project.createBranch(newBranchName, commitHash);
})
.then(function () {
deferred.resolve(newBranchName);
})
.catch(deferred.reject);
} else {
deferred.resolve(branchNameOrCommitHash);
}
return deferred.promise;
};
/**
* Merges two branches or commits. If the newBranchName is given it creates a new branch for the result.
*
* @param mergeFrom {string}
* @param mergeTo {string}
* @param newBranchName [string|null]
* @param resolutionStrategy [Function|null] - defines how the conflicts should be resolved, by default 'mine'
* is chosen for all conflicts.
* @returns {*}
*/
MergeExample.prototype.merge = function (mergeFrom, mergeTo, newBranchName, resolutionStrategy) {
var self = this;
// default values
mergeTo = mergeTo || 'master';
newBranchName = newBranchName || null;
if (typeof resolutionStrategy !== 'function') {
resolutionStrategy = function (result) {
return result;
};
}
return self.ensureBranch(mergeTo, newBranchName)
.then(function (mergeTo__) {
mergeTo = mergeTo__;
return merge.merge({
project: self.project,
logger: self.logger,
gmeConfig: self.gmeConfig,
myBranchOrCommit: mergeFrom,
theirBranchOrCommit: mergeTo,
auto: true
});
})
.then(function (result) {
// result.baseCommitHash
// [result.conflict] - not there if fast-forward
// [result.diff]- not there if fast-forward
// result.myCommitHash
// result.projectId
// result.targetBranchName
// result.theirCommitHash
self.logger.info(result);
if (!result.conflict || result.conflict.items.length === 0) {
// FIXME: what if it could not update the branch or got a commit hash
return result;
} else {
// there was a conflict
// resolve
return merge.resolve({
partial: resolutionStrategy(result),
project: self.project,
logger: self.logger,
gmeConfig: self.gmeConfig,
myBranchOrCommit: mergeFrom,
theirBranchOrCommit: mergeTo,
auto: true
});
}
});
};
return MergeExample;
}); |
// Generated by CoffeeScript 1.6.3
var Message, should, vows;
Message = require("../");
vows = require("vows");
should = require("chai").should();
vows.describe("Utility methods").addBatch({
"#prefixIsHostmask()": {
"when prefix is valid hostname": {
topic: Message(":test!test@something.com PRIVMSG #Test :Testing!"),
"should return `true`": function(topic) {
return topic.prefixIsHostmask().should.be["true"];
}
},
"when prefix is invalid hostname": {
topic: Message(":127.0.0.1 PRIVMSG #Test :Testing!"),
"should return `false`": function(topic) {
return topic.prefixIsHostmask().should.be["false"];
}
}
},
"#prefixIsServer()": {
"when prefix is valid server hostname": {
topic: Message(":127.0.0.1 NOTICE * :Looking up your hostname..."),
"should return `true`": function(topic) {
return topic.prefixIsServer().should.be["true"];
}
},
"when prefix is invalid server hostname": {
topic: Message(":test!test@something.com NOTICE * :Looking up your hostname..."),
"should return `false`": function(topic) {
return topic.prefixIsServer().should.be["false"];
}
}
},
"#parseHostmaskFromPrefix()": {
"when prefix is 'james!james@my.awesome-rdns.co'": {
topic: (Message(":james!baz@my.awesome-rdns.co PRIVMSG #test :Hello!")).parseHostmaskFromPrefix(),
"should have property 'nickname' of 'james'": function(topic) {
return topic.nickname.should.equal("james");
},
"should have property 'username' of 'baz'": function(topic) {
return topic.username.should.equal("baz");
},
"should have property 'hostname' of 'my.awesome-rdns.co'": function(topic) {
return topic.hostname.should.equal("my.awesome-rdns.co");
}
},
"when prefix is '127.0.0.1'": {
topic: (Message(":127.0.0.1 NOTICE * :Looking up your hostname...")).parseHostmaskFromPrefix(),
"should return `null`": function(topic) {
return (topic === null).should.be["true"];
}
}
}
})["export"](module);
|
/*
Plotr.PieChart
==============
Plotr.PieChart is part of the Plotr Charting Framework.
For license/info/documentation: http://www.solutoire.com/plotr/
Credits
-------
Plotr is partially based on PlotKit (BSD license) by
Alastair Tse <http://www.liquidx.net/plotkit>.
Copyright
---------
Copyright 2007 (c) Bas Wenneker <sabmann[a]gmail[d]com>
For use under the BSD license. <http://www.solutoire.com/plotr>
*/
if (typeof(Plotr.Base) == 'undefined' ||
typeof(Plotr.Chart) == 'undefined'){
throw 'Plotr.PieChart depends on Plotr.{Base, Chart}.';
}
Plotr.PieChart = Class.create();
Object.extend(Plotr.PieChart.prototype, Plotr.Chart);
Object.extend(Plotr.PieChart.prototype,{
type: 'pie',
/*
Function: render
Renders the chart with the specified options. The optional parameters can be used to render a piechart in a different canvas element with new options.
Parameters:
element - (Optional) canvas element to render a chart in.
options - (Optional) options for this chart.
*/
render: function(/*String*/element, /*Object*/options) {
if(this.isIE && this._ieWaitForVML(element,options)){
return;
}
this._evaluate(options);
this._render(element);
this._renderPieChart();
this._renderPieAxis();
if(this.isIE){
for(var el in this.renderStack){
if(typeof(this.renderStack[el]) != 'function'){
this.render(el,this.renderStack[el]);
break;
}
}
}
},
/*
Function: _evaluate
(Private) Evaluates all the data needed to plot the pie chart.
Parameters:
options - options for this chart.
*/
_evaluate: function(/*Object*/options) {
this._eval(options);
this._evalPieChart();
this._evalPieTicks();
},
/*
Function: _evalPieChart
(Private) Evaluates measures for pie charts.
*/
_evalPieChart: function(){
var slices = this.dataSets.collect(function(hash, index){
return {
name: hash[0], // TODO Real labels
value: [index, hash[1][0][1]]
};
});
var sum = slices.pluck('value').pluck(1).inject(0, function(acc, n) { return acc + n; });
var fraction = angle = 0.0;
this.slices = slices.collect(function(slice){
angle += fraction;
if(slice.value[1] > 0){
fraction = slice.value[1]/sum;
return {
name: slice.name,
fraction: fraction,
xval: slice.value[0],
yval: slice.value[1],
startAngle: 2 * angle * Math.PI,
endAngle: 2 * (angle + fraction) * Math.PI
};
}
});
},
/*
Function: _renderPieChart
(Private) Renders a pie chart.
*/
_renderPieChart: function(){
var cx = this.canvasNode.getContext('2d');
var centerx = this.area.x + this.area.w * 0.5;
var centery = this.area.y + this.area.h * 0.5;
var radius = Math.min(this.area.w * this.options.pieRadius, this.area.h * this.options.pieRadius);
if(this.isIE){
centerx = parseInt(centerx,10);
centery = parseInt(centery,10);
radius = parseInt(radius,10);
}
var drawPie = function(slice){
cx.beginPath();
cx.moveTo(centerx, centery);
cx.arc(centerx, centery, radius,
slice.startAngle - Math.PI/2,
slice.endAngle - Math.PI/2,
false);
cx.lineTo(centerx, centery);
cx.closePath();
};
if(this.options.stroke.shadow){
cx.save();
cx.fillStyle = "rgba(0,0,0,0.15)";
cx.beginPath();
cx.moveTo(centerx, centery);
cx.arc(centerx+1, centery+2, radius+1, 0, Math.PI*2, false);
cx.lineTo(centerx, centery);
cx.closePath();
cx.fill();
cx.restore();
}
cx.save();
this.slices.each(function(slice,i){
if(Math.abs(slice.startAngle - slice.endAngle) > 0.001){
cx.fillStyle = new Plotr.Color(this.options.colorScheme[slice.name]).toRgbaString(parseFloat(this.options.fillOpacity));;
if(this.options.shouldFill){
drawPie(slice);
cx.fill();
}
if(!this.options.stroke.hide){
drawPie(slice);
cx.lineWidth = this.options.stroke.width;
cx.strokeStyle = this.options.stroke.color;
cx.stroke();
}
}
}.bind(this));
cx.restore();
},
/*
Function: _evalPieTicks
(Private) Evaluates ticks for x and y axis.
*/
_evalPieTicks: function(){
this.xticks = [];
if(this.options.axis.x.ticks){
var lookup = [];
this.slices.each(function(slice){
lookup[slice.xval] = slice;
});
this.options.axis.x.ticks.each(function(tick){
var slice = lookup[tick.v];
var label = tick.label || tick.v.toString();
if(!!(slice)){
label += ' (' + (slice.fraction * 100).toFixed(1) + '%)';
this.xticks.push([tick.v, label]);
}
}.bind(this));
}else{
this.slices.each(function(slice){
var label = slice.xval + ' (' + (slice.fraction * 100).toFixed(1) + '%)';
this.xticks.push([slice.xval, label]);
}.bind(this));
}
},
/*
Function: _renderPieAxis
(Private) Renders the axis for pie charts.
*/
_renderPieAxis: function(){
if(this.options.axis.x.hide || !this.xticks){
return;
}
this.xlabels = lookup = [];
this.slices.each(function(slice){
lookup[slice.xval] = slice;
});
var centerx = this.area.x + this.area.w * 0.5;
var centery = this.area.y + this.area.h * 0.5;
var radius = Math.min(this.area.w * this.options.pieRadius, this.area.h * this.options.pieRadius);
var labelWidth = this.options.axis.labelWidth;
var labelStyle = {
position: 'absolute',
zIndex: 11,
width: labelWidth + 'px',
fontFamily: this.options.axis.labelFont,
fontSize: this.options.axis.labelFontSize + 'px',
overflow: 'hidden',
color: this.options.axis.labelColor
};
this.xticks.each(function(tick){
var slice = lookup[tick[0]];
// normalize the angle
var normalisedAngle = (slice.startAngle + slice.endAngle)/2;
if(normalisedAngle > Math.PI * 2){
normalisedAngle = normalisedAngle - Math.PI * 2;
}else if(normalisedAngle < 0){
normalisedAngle = normalisedAngle + Math.PI * 2;
}
var labelx = centerx + Math.sin(normalisedAngle) * (radius + 10);
var labely = centery - Math.cos(normalisedAngle) * (radius + 10);
if(normalisedAngle <= Math.PI * 0.5){
// text on top and align left
Object.extend(labelStyle, {
textAlign: 'left',
verticalAlign: 'top',
left: labelx + 'px',
top: (labely - this.options.axis.labelFontSize) + 'px'
});
}else if((normalisedAngle > Math.PI * 0.5) && (normalisedAngle <= Math.PI)){
// text on bottom and align left
Object.extend(labelStyle, {
textAlign: 'left',
verticalAlign: 'bottom',
left: labelx + 'px',
top: labely + 'px'
});
}else if((normalisedAngle > Math.PI) && (normalisedAngle <= Math.PI*1.5)){
// text on bottom and align right
Object.extend(labelStyle, {
textAlign: 'right',
verticalAlign: 'bottom',
left: (labelx - labelWidth) + 'px',
top: labely + 'px'
});
}else {
// text on top and align right
Object.extend(labelStyle, {
textAlign: 'right',
verticalAlign: 'bottom',
left: (labelx - labelWidth) + 'px',
top: (labely - this.options.axis.labelFontSize) + 'px'
});
}
var label = Element.setStyle(document.createElement('div'), labelStyle);
label.appendChild(document.createTextNode(tick[1]));
this.htmlWrapper.appendChild(label);
this.xlabels.push(label);
}.bind(this));
}
}); |
// # Display shape mixin
// This mixin defines additional attributes and functions for Stack and Canvas artefacts, in particular adding hooks for functions that will be automatically invoked when the artefact's dimensions update.
// #### Demos:
// + [Canvas-034](../../demo/canvas-034.html) - Determine the displayed shape of the visible canvas; react to changes in the displayed shape
// + [DOM-016](../../demo/dom-016.html) - Determine the displayed shape of the visible stack; react to changes in the displayed shape
// #### Imports
import { mergeOver, pushUnique, λnull, isa_obj, isa_number, isa_fn, Ωempty } from '../core/utilities.js';
// #### Export function
export default function (P = Ωempty) {
// #### Shared attributes
let defaultAttributes = {
// Scrawl-canvas recognises five shapes, separated by four breakpoints:
// + `banner`
// + `landscape`
// + `rectangle`
// + `portrait`
// + `skyscraper`
//
// The values assigned to the breakpoints are Float numbers for the displayed Canvas element's width/height ratio - the value `3` represents the case where the width value is three times __more__ than the height value, while `0.35` represents a width (roughly) 3 times __less__ than the height.
//
// We can set a Canvas artefact's breakpoints in one go using the dedicated `setDisplayShapeBreakpoints()` function, as below. Alternatively we can use the regular `set()` function, supplying the attributes `breakToBanner`, `breakToLandscape`, `breakToPortrait` and `breakToSkyscraper` as required. The values given here are the default values for Canvas artefacts.
breakToBanner: 3,
breakToLandscape: 1.5,
breakToPortrait: 0.65,
breakToSkyscraper: 0.35,
actionBannerShape: null,
actionLandscapeShape: null,
actionRectangleShape: null,
actionPortraitShape: null,
actionSkyscraperShape: null,
// Scrawl-canvas also recognises five areas, again separated by four breakpoints:
// + `smallest`
// + `smaller`
// + `regular`
// + `larger`
// + `largest`
//
// The values assigned to the breakpoints are Float numbers for the displayed Canvas element's pixel area (`width * height`).
// + Useful for dynamic Cells - for example Canvas base Cells, where the canvas `baseMatchesCanvasDimensions` flag has been set to `true`; in these situations we can use the area breakpoints to adjust entity dimensions and scales, and text font sizes, to better match the changed environment.
// + The other option - to set the base Cell's dimensions to known, static values and set the canvas's `fit` attribute - suffers from image degredation when the canvas and its base cell's dimensions are excessively different.
breakToSmallest: 20000,
breakToSmaller: 80000,
breakToLarger: 180000,
breakToLargest: 320000,
actionSmallestArea: null,
actionSmallerArea: null,
actionRegularArea: null,
actionLargerArea: null,
actionLargestArea: null,
};
P.defs = mergeOver(P.defs, defaultAttributes);
mergeOver(P, defaultAttributes);
// #### Packet management
P.packetFunctions = pushUnique(P.packetFunctions, ['actionBannerShape', 'actionLandscapeShape', 'actionRectangleShape', 'actionPortraitShape', 'actionSkyscraperShape']);
// #### Clone management
// No additional clone functionality defined here
// #### Kill management
// No additional kill functionality defined here
// #### Get, Set, deltaSet
let G = P.getters,
S = P.setters;
// Get __displayShape__ - returns the current display shape for the Canvas or Stack artefact. Returns a string whose value can be one of `banner`, `landscape`, `rectangle`, `portrait`, or `skyscraper`.
G.displayShape = function () {
return this.currentDisplayShape;
};
// Get __displayShapeBreakpoints__ - returns an object with the current Number values for each of the breakpoint attributes.
G.displayShapeBreakpoints = function () {
return {
breakToBanner: this.breakToBanner,
breakToLandscape: this.breakToLandscape,
breakToPortrait: this.breakToPortrait,
breakToSkyscraper: this.breakToSkyscraper,
breakToSmallest: this.breakToSmallest,
breakToSmaller: this.breakToSmaller,
breakToLarger: this.breakToLarger,
breakToLargest: this.breakToLargest,
};
};
// Set __displayShapeBreakpoints__ - breakpoints can be set individually, or alternatively they can be supplied in an object keyed to this attribute
S.displayShapeBreakpoints = function (items = Ωempty) {
for (let [key, val] of Object.entries(items)) {
if (isa_number(val)) {
switch (key) {
case 'breakToBanner' :
this.breakToBanner = val;
break;
case 'breakToLandscape' :
this.breakToLandscape = val;
break;
case 'breakToPortrait' :
this.breakToPortrait = val;
break;
case 'breakToSkyscraper' :
this.breakToSkyscraper = val;
break;
case 'breakToSmallest' :
this.breakToSmallest = val;
break;
case 'breakToSmaller' :
this.breakToSmaller = val;
break;
case 'breakToLarger' :
this.breakToLarger = val;
break;
case 'breakToLargest' :
this.breakToLargest = val;
break;
}
}
}
this.dirtyDisplayShape = true;
this.dirtyDisplayArea = true;
};
// `setDisplayShapeBreakpoints` - an alternative mechanism to set breakpoints beyond the normal `set` function
P.setDisplayShapeBreakpoints = S.displayShapeBreakpoints;
// Set __breakToBanner__ - the breakpoint between `landscape` and `banner` display shapes; value will generally be a number greater than `1`
S.breakToBanner = function (item) {
if (isa_number(item)) this.breakToBanner = item;
this.dirtyDisplayShape = true;
};
// Set __breakToLandscape__ - the breakpoint between `landscape` and `rectangle` display shapes; value will generally be a number greater than `1`
S.breakToLandscape = function (item) {
if (isa_number(item)) this.breakToLandscape = item;
this.dirtyDisplayShape = true;
};
// Set __breakToPortrait__ - the breakpoint between `portrait` and `rectangle` display shapes; value will generally be a number greater than `0` and less than `1`
S.breakToPortrait = function (item) {
if (isa_number(item)) this.breakToPortrait = item;
this.dirtyDisplayShape = true;
};
// Set __breakToSkyscraper__ - the breakpoint between `portrait` and `skyscraper` display shapes; value will generally be a number greater than `0` and less than `1`
S.breakToSkyscraper = function (item) {
if (isa_number(item)) this.breakToSkyscraper = item;
this.dirtyDisplayShape = true;
};
// Set __breakToSmallest__ - the breakpoint between `smaller` and `smallest` display shapes
S.breakToSmallest = function (item) {
if (isa_number(item)) this.breakToSmallest = item;
this.dirtyDisplayArea = true;
};
// Set __breakToSmaller__ - the breakpoint between `regular` and `smaller` display shapes
S.breakToSmaller = function (item) {
if (isa_number(item)) this.breakToSmaller = item;
this.dirtyDisplayArea = true;
};
// Set __breakToLarger__ - the breakpoint between `regular` and `larger` display shapes
S.breakToLarger = function (item) {
if (isa_number(item)) this.breakToLarger = item;
this.dirtyDisplayArea = true;
};
// Set __breakToLargest__ - the breakpoint between `larger` and `largest` display shapes
S.breakToLargest = function (item) {
if (isa_number(item)) this.breakToLargest = item;
this.dirtyDisplayArea = true;
};
// Each display shape has an associated hook function (by default a function that does nothing) which Scrawl-canvas will run each time it detects that the Canvas display shape has changed to that shape. We can replace these null-functions with our own; this allows us to configure the scene/animation to accommodate different display shapes, thus making the code reusable in a range of different web page environments.
//
// We can set/update these functions at any time using the normal `set()` function. We can also set/update the functions using dedicated `setAction???Shape()` functions:
// Set __actionBannerShape__ - must be a Function
S.actionBannerShape = function (item) {
if (isa_fn(item)) this.actionBannerShape = item;
this.dirtyDisplayShape = true;
};
// `setActionBannerShape` - an alternative mechanism to set the __actionBannerShape__ function, beyond the normal `set` functionality
P.setActionBannerShape = S.actionBannerShape;
// Set __actionLandscapeShape__ - must be a Function
S.actionLandscapeShape = function (item) {
if (isa_fn(item)) this.actionLandscapeShape = item;
this.dirtyDisplayShape = true;
};
// `setActionLandscapeShape` - an alternative mechanism to set the __actionLandscapeShape__ function, beyond the normal `set` functionality
P.setActionLandscapeShape = S.actionLandscapeShape;
// Set __actionRectangleShape__ - must be a Function
S.actionRectangleShape = function (item) {
if (isa_fn(item)) this.actionRectangleShape = item;
this.dirtyDisplayShape = true;
};
// `setActionRectangleShape` - an alternative mechanism to set the __actionRectangleShape__ function, beyond the normal `set` functionality
P.setActionRectangleShape = S.actionRectangleShape;
// Set __actionPortraitShape__ - must be a Function
S.actionPortraitShape = function (item) {
if (isa_fn(item)) this.actionPortraitShape = item;
this.dirtyDisplayShape = true;
};
// `setActionPortraitShape` - an alternative mechanism to set the __actionPortraitShape__ function, beyond the normal `set` functionality
P.setActionPortraitShape = S.actionPortraitShape;
// Set __actionSkyscraperShape__ - must be a Function
S.actionSkyscraperShape = function (item) {
if (isa_fn(item)) this.actionSkyscraperShape = item;
this.dirtyDisplayShape = true;
};
// `setActionSkyscraperShape` - an alternative mechanism to set the __actionSkyscraperShape__ function, beyond the normal `set` functionality
P.setActionSkyscraperShape = S.actionSkyscraperShape;
// Set __actionSmallestArea__ - must be a Function
S.actionSmallestArea = function (item) {
if (isa_fn(item)) this.actionSmallestArea = item;
this.dirtyDisplayArea = true;
};
// `setActionSmallestArea` - an alternative mechanism to set the __actionSmallestArea__ function, beyond the normal `set` functionality
P.setActionSmallestArea = S.actionSmallestArea;
// Set __actionSmallerArea__ - must be a Function
S.actionSmallerArea = function (item) {
if (isa_fn(item)) this.actionSmallerArea = item;
this.dirtyDisplayArea = true;
};
// `setActionSmallerArea` - an alternative mechanism to set the __actionSmallerArea__ function, beyond the normal `set` functionality
P.setActionSmallerArea = S.actionSmallerArea;
// Set __actionRegularArea__ - must be a Function
S.actionRegularArea = function (item) {
if (isa_fn(item)) this.actionRegularArea = item;
this.dirtyDisplayArea = true;
};
// `setActionRegularArea` - an alternative mechanism to set the __actionRegularArea__ function, beyond the normal `set` functionality
P.setActionRegularArea = S.actionRegularArea;
// Set __actionLargerArea__ - must be a Function
S.actionLargerArea = function (item) {
if (isa_fn(item)) this.actionLargerArea = item;
this.dirtyDisplayArea = true;
};
// `setActionLargerArea` - an alternative mechanism to set the __actionLargerArea__ function, beyond the normal `set` functionality
P.setActionLargerArea = S.actionLargerArea;
// Set __actionLargestArea__ - must be a Function
S.actionLargestArea = function (item) {
if (isa_fn(item)) this.actionLargestArea = item;
this.dirtyDisplayArea = true;
};
// `setActionLargestArea` - an alternative mechanism to set the __actionLargestArea__ function, beyond the normal `set` functionality
P.setActionLargestArea = S.actionLargestArea;
// #### Prototype functions
// `initializeDisplayShapeActions` - internal function; called by the Canvas and Stack artefact constructors
P.initializeDisplayShapeActions = function () {
this.actionBannerShape = λnull;
this.actionLandscapeShape = λnull;
this.actionRectangleShape = λnull;
this.actionPortraitShape = λnull;
this.actionSkyscraperShape = λnull;
this.currentDisplayShape = '';
this.dirtyDisplayShape = true;
this.actionSmallestArea = λnull;
this.actionSmallerArea = λnull;
this.actionRegularArea = λnull;
this.actionLargerArea = λnull;
this.actionLargestArea = λnull;
this.currentDisplayArea = '';
this.dirtyDisplayArea = true;
};
// `cleanDisplayShape` - internal function; replaces the function defined in the dom.js mixin, invoked when required as part of the DOM artefact `prestamp` functionality
P.cleanDisplayShape = function () {
this.dirtyDisplayShape = false;
let [width, height] = this.currentDimensions;
if (width > 0 && height > 0) {
let ratio = width / height,
current = this.currentDisplayShape,
banner = this.breakToBanner,
landscape = this.breakToLandscape,
portrait = this.breakToPortrait,
skyscraper = this.breakToSkyscraper;
if (ratio > banner) {
if (current !== 'banner') {
this.currentDisplayShape = 'banner';
this.actionBannerShape();
return true;
}
return false;
}
else if (ratio > landscape) {
if (current !== 'landscape') {
this.currentDisplayShape = 'landscape';
this.actionLandscapeShape();
return true;
}
return false;
}
else if (ratio < skyscraper) {
if (current !== 'skyscraper') {
this.currentDisplayShape = 'skyscraper';
this.actionSkyscraperShape();
return true;
}
return false;
}
else if (ratio < portrait) {
if (current !== 'portrait') {
this.currentDisplayShape = 'portrait';
this.actionPortraitShape();
return true;
}
return false;
}
else {
if (current !== 'rectangle') {
this.currentDisplayShape = 'rectangle';
this.actionRectangleShape();
return true;
}
return false;
}
}
else {
this.dirtyDisplayShape = true;
return false;
}
};
// `cleanDisplayArea` - internal function; replaces the function defined in the dom.js mixin, invoked when required as part of the DOM artefact `prestamp` functionality
// + Note that `cleanDisplayArea` fires before `cleanDisplayShape`!
P.cleanDisplayArea = function () {
this.dirtyDisplayArea = false;
let [width, height] = this.currentDimensions;
if (width > 0 && height > 0) {
let area = width * height,
current = this.currentDisplayArea,
largest = this.breakToLargest,
larger = this.breakToLarger,
smaller = this.breakToSmaller,
smallest = this.breakToSmallest;
if (area > largest) {
if (current !== 'largest') {
this.currentDisplayArea = 'largest';
this.actionLargestArea();
return true;
}
return false;
}
else if (area > larger) {
if (current !== 'larger') {
this.currentDisplayArea = 'larger';
this.actionLargerArea();
return true;
}
return false;
}
else if (area < smallest) {
if (current !== 'smallest') {
this.currentDisplayArea = 'smallest';
this.actionSmallestArea();
return true;
}
return false;
}
else if (area < smaller) {
if (current !== 'smaller') {
this.currentDisplayArea = 'smaller';
this.actionSmallerArea();
return true;
}
return false;
}
else {
if (current !== 'regular') {
this.currentDisplayArea = 'regular';
this.actionRegularArea();
return true;
}
return false;
}
}
else {
this.dirtyDisplayArea = true;
return false;
}
};
// `updateDisplayShape` - use this function to force the Canvas or Stack artefact to re-evaluate its current display shape, and invoke the action hook function associated with that shape.
P.updateDisplayShape = function () {
this.currentDisplayShape = '';
this.dirtyDisplayShape = true;
};
// `updateDisplayArea` - use this function to force the Canvas or Stack artefact to re-evaluate its current display area, and invoke the action hook function associated with that area.
P.updateDisplayArea = function () {
this.currentDisplayArea = '';
this.dirtyDisplayArea = true;
};
// `updateDisplay` - perform update for both display shape and area.
P.updateDisplay = function () {
this.updateDisplayShape();
this.updateDisplayArea();
};
// Return the prototype
return P;
};
|
import { REQUEST_CONTACT_DATA } from '../Contacts/ContactCard/constants';
export function requestContactData(userId) {
return {
type: REQUEST_CONTACT_DATA,
userId,
};
}
|
/** @jsx h */
import h from '../../helpers/h'
export const flags = {}
export const schema = {
blocks: {
paragraph: {},
item: {
parent: { types: ['list'] },
nodes: [{ objects: ['text'] }],
},
list: {},
},
}
export const customChange = change => {
// see if we can break the expected validation sequence by toggling
// the normalization option
const target = change.value.document.nodes.get(0)
change.wrapBlockByKey(target.key, 'item', { normalize: true })
}
export const input = (
<value>
<document>
<paragraph />
</document>
</value>
)
export const output = (
<value>
<document />
</value>
)
|
(function($){
$(function(){
var window_width = $(window).width();
// convert rgb to hex value string
function rgb2hex(rgb) {
if (/^#[0-9A-F]{6}$/i.test(rgb)) { return rgb; }
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) { return "N/A"; }
function hex(x) {
return ("0" + parseInt(x).toString(16)).slice(-2);
}
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}
$('.dynamic-color .col').each(function () {
$(this).children().each(function () {
var color = $(this).css('background-color'),
classes = $(this).attr('class');
$(this).html(rgb2hex(color) + " " + classes);
if (classes.indexOf("darken") >= 0 || $(this).hasClass('black')) {
$(this).css('color', 'rgba(255,255,255,.9');
}
});
});
// Floating-Fixed table of contents
setTimeout(function() {
var tocWrapperHeight = 260; // Max height of ads.
var tocHeight = $('.toc-wrapper .table-of-contents').length ? $('.toc-wrapper .table-of-contents').height() : 0;
var socialHeight = 95; // Height of unloaded social media in footer.
var footerOffset = $('body > footer').first().length ? $('body > footer').first().offset().top : 0;
var bottomOffset = footerOffset - socialHeight - tocHeight - tocWrapperHeight;
var pushpinObj = {
bottom: bottomOffset
};
if ($('nav').length) {
pushpinObj.top = $('nav').height();
} else if ($('#index-banner').length) {
pushpinObj.top = $('#index-banner').height();
} else {
pushpinObj.top = 0;
}
if ($('.fixed-announcement').length) {
pushpinObj.top += 48;
}
$('.toc-wrapper').pushpin(pushpinObj);
}, 100);
// BuySellAds Detection
var $bsa = $(".buysellads"),
$timesToCheck = 3;
function checkForChanges() {
if (!$bsa.find('#carbonads').length) {
$timesToCheck -= 1;
if ($timesToCheck >= 0) {
setTimeout(checkForChanges, 500);
}
else {
var donateAd = $('<div id="carbonads"><span><a class="carbon-text" href="#!" onclick="document.getElementById(\'paypal-donate\').submit();"><img src="app/images/donate.png" /> Help support us by turning off adblock. If you still prefer to keep adblock on for this page but still want to support us, feel free to donate. Any little bit helps.</a></form></span></div>');
$bsa.append(donateAd);
}
}
}
checkForChanges();
// BuySellAds Demos close button.
$('.buysellads.buysellads-demo .close').on('click', function() {
$(this).parent().remove();
});
// Github Latest Commit
if ($('.github-commit').length) { // Checks if widget div exists (Index only)
$.ajax({
url: "https://api.github.com/repos/dogfalo/materialize/commits/master",
dataType: "json",
success: function (data) {
var sha = data.sha,
date = jQuery.timeago(data.commit.author.date);
if (window_width < 1120) {
sha = sha.substring(0,7);
}
$('.github-commit').find('.date').html(date);
$('.github-commit').find('.sha').html(sha).attr('href', data.html_url);
}
});
}
// Toggle Flow Text
var toggleFlowTextButton = $('#flow-toggle');
toggleFlowTextButton.click( function(){
$('#flow-text-demo').children('p').each(function(){
$(this).toggleClass('flow-text');
});
});
// Toggle Containers on page
var toggleContainersButton = $('#container-toggle-button');
toggleContainersButton.click(function(){
$('body .browser-window .container, .had-container').each(function(){
$(this).toggleClass('had-container');
$(this).toggleClass('container');
if ($(this).hasClass('container')) {
toggleContainersButton.text("Turn off Containers");
}
else {
toggleContainersButton.text("Turn on Containers");
}
});
});
// Detect touch screen and enable scrollbar if necessary
function is_touch_device() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}
if (is_touch_device()) {
$('#nav-mobile').css({ overflow: 'auto'});
}
// Set checkbox on forms.html to indeterminate
var indeterminateCheckbox = document.getElementById('indeterminate-checkbox');
if (indeterminateCheckbox !== null)
indeterminateCheckbox.indeterminate = true;
// Pushpin Demo Init
if ($('.pushpin-demo-nav').length) {
$('.pushpin-demo-nav').each(function() {
var $this = $(this);
var $target = $('#' + $(this).attr('data-target'));
$this.pushpin({
top: $target.offset().top,
bottom: $target.offset().top + $target.outerHeight() - $this.height()
});
});
}
// CSS Transitions Demo Init
if ($('#scale-demo').length &&
$('#scale-demo-trigger').length) {
$('#scale-demo-trigger').click(function() {
$('#scale-demo').toggleClass('scale-out');
});
}
// Plugin initialization
$('.carousel.carousel-slider').carousel({fullWidth: true});
$('.carousel').carousel();
$('.slider').slider();
$('.parallax').parallax();
$('.modal').modal();
$('.scrollspy').scrollSpy();
$('.button-collapse').sideNav({'edge': 'left'});
$('.datepicker').pickadate({selectYears: 20});
$('.timepicker').pickatime();
$('select').not('.disabled').material_select();
$('input.autocomplete').autocomplete({
data: {"Apple": null, "Microsoft": null, "Google": 'http://placehold.it/250x250'},
});
}); // end of document ready
})(jQuery); // end of jQuery name space
|
'use strict';
angular.module('skillz').directive('xebianSkillCard', function () {
return {
restrict: 'E',
scope: {
xebian: '=xebian',
showRating: '=showRating',
onClick: '&onClick'
},
templateUrl: 'modules/skillz/views/xebian-skill-card.template.html'
};
});
angular.module('skillz').directive('help', ['$http', function ($http) {
return {
restrict: 'E',
templateUrl: 'modules/skillz/views/help.template.html'
};
}]);
angular.module('skillz').controller('SkillzController', ['$rootScope', '$scope', '$http', '$location', '_', 'd3', '$analytics', 'Authentication',
function ($rootScope, $scope, $http, $location, _, d3, $analytics, Authentication) {
$scope.expertLevel = 3;
$scope.confirmedLevel = 2;
$scope.rookieLevel = 1;
$scope.enthusiastLevel = 0;
$scope.domains = ['Agile', 'Back', 'Cloud', 'Craft', 'Data', 'Devops', 'Front', 'Mobile', 'Loisirs'];
$scope.domain = 'Agile';
$scope.levels = ['3', '2', '1', '0'];
$scope.level = '3';
$scope.newSkill = '';
$scope.years = _.range(new Date().getFullYear(), 1990, -1);
$scope.help = function () {
$scope.displayHelp = !$scope.displayHelp;
};
$scope.cloud = function (id, api) {
function domainColor(domain, count) {
var alpha = count / 10;
var color;
if (!domain) {
return 'rgba(255,255,255,1)';
}
switch (domain.toLowerCase()) {
case 'back':
color = 'rgba(170, 38, 21, ' + alpha + ')';
break;
case 'cloud':
color = 'rgba(170, 38, 21, ' + alpha + ')';
break;
case 'craft' :
color = 'rgba(175, 205, 55, ' + alpha + ')';
break;
case 'agile':
color = 'rgba(215, 213, 208, ' + alpha + ')';
break;
case 'data' :
color = 'rgba(223, 0, 117, ' + alpha + ')';
break;
case 'devops':
color = 'rgba(249, 155, 29, ' + alpha + ')';
break;
case 'front' :
color = 'rgba(0, 160, 212, ' + alpha + ')';
break;
case 'mobile' :
color = 'rgba(20, 71, 211, ' + alpha + ')';
break;
default:
color = 'rgba(100, 100, 100, ' + alpha + ')';
break;
}
return color;
}
var diameter = 960, format = d3.format(',d'), color = d3.scale.category20c();
var bubble = d3.layout.pack()
.sort(null)
.size([diameter, diameter])
.padding(15);
var svg = d3.select(id).append('svg')
.attr('width', diameter)
.attr('height', diameter)
.attr('class', 'bubble');
d3.json(api, function (error, root) {
if (!root.length) {
return;
}
var node = svg.selectAll('.node')
.data(bubble.nodes(setClasses(root))
.filter(function (d) {
return !d.children;
}))
.enter().append('g')
.attr('class', 'node')
.attr('transform', function (d) {
return 'translate(' + d.x + ',' + d.y + ')';
});
node.append('title')
.text(function (d) {
return d.name + ': ' + format(d.value);
});
node.append('circle')
.attr('r', function (d) {
return d.r;
})
.style('fill', function (d) {
if (d.domains) {
var domain = d.domains[0];
return domainColor(domain, d.value);
}
return '#FFFFFF';
});
node.append('a')
.attr({'xlink:href': '#'})
.on('mouseover', function (d, i) {
d3.select(this)
.attr({'xlink:href': '#!/skillz/search?query=' + d.name});
})
.append('text')
.attr('dy', '.3em')
.style('text-anchor', 'middle')
.text(function (d) {
if (d.name) {
return d.name.substring(0, d.r / 4);
}
return '';
});
});
function setClasses(root) {
var classes = [];
root.forEach(function (node) {
classes.push({name: node.name, value: node.count, domains: node.domains});
});
return {children: classes};
}
d3.select(id).style('height', diameter + 'px');
};
$scope.cloudify = function () {
angular.element('#cloud').empty();
$scope.cloud('#cloud', '/skills?level=' + $scope.level + '&domain=' + $scope.domain);
};
$scope.cloudify();
$scope.getSkills = function () {
$http.get('/skills').then(function (response) {
$scope.skillz = response.data;
});
};
$scope.getXebians = function () {
$http.get('/users?q=.').then(function (response) {
$scope.xebians = response.data;
});
};
$scope.getManagers = function () {
$http.get('/managers').then(function (response) {
$scope.managers = response.data;
});
};
$scope.getSkills();
$scope.getXebians();
$scope.getManagers();
$scope.getOrphanSkillz = function () {
$http.get('/skills/orphans').then(function (response) {
$scope.orphanSkillz = response.data;
});
};
$scope.getOrphanSkillz();
$scope.merge = function () {
$http.post('/skills/merge', {
'source': $scope.source,
'destination': $scope.destination
}).then(function (response) {
$scope.skillz = response.data;
$scope.getOrphanSkillz();
$scope.source = {};
$scope.destination = {};
});
};
$scope.domainize = function () {
$http.post('/skills/domains', {'skill': $scope.skill, 'domain': $scope.domain}).then(function (response) {
$scope.skillz = response.data;
$scope.skill = {};
$scope.domain = {};
});
};
$scope.associateManager = function () {
$http.post('/user/manager', {
'xebianWithoutManager': $scope.xebianWithoutManager,
'manager': $scope.manager
}).then(function () {
$scope.getXebians();
$scope.xebianWithoutManager = {};
});
};
$scope.diplomize = function () {
$http.post('/user/diploma', {'email': $scope.xebian, 'diploma': $scope.year}).then(function (response) {
$scope.getXebians();
$scope.year = {};
$scope.xebian = {};
});
};
$scope.deleteSkill = function (nodeToDelete) {
$http.post('/skills/delete', {'source': nodeToDelete}).then(function (response) {
$scope.orphanSkillz = response.data;
$scope.getSkills();
});
};
var transformResultToXebians = function (response) {
var values = _.map(response.data, function (node) {
return {
'skillName': node.skillName,
'nameForSort': node.skillName.toLowerCase(),
'email': node.email,
'gravatar': node.gravatar,
'displayName': node.xebianName,
'level': node.level,
'like': node.like,
'experience': node.experience
};
});
return _.sortBy(values, 'level').reverse();
};
$scope.searchSkillz = function () {
$analytics.eventTrack(Authentication.user.email.split('@')[0], {
category: 'Skill Search',
label: $scope.query
});
$http.get('/users/skillz/' + encodeURIComponent($scope.query))
.then(function (response) {
$scope.results = transformResultToXebians(response);
$analytics.eventTrack($scope.query, {category: 'Skill Results', label: $scope.results.length});
});
};
$scope.proposeSkillz = function (query) {
return $http.get('/skills', {'params': {'skill': query}}).then(function (response) {
return response.data;
});
};
$scope.findSkillByName = function (skill) {
$scope.query = skill;
if (skill.length > 2) {
$scope.searchSkillz();
}
};
$scope.changingSearchSkillz = _.debounce(function () {
$scope.results = [];
if ($scope.query.length > 2) {
$scope.searchSkillz();
}
}, 500);
$scope.isLiked = function (like) {
if (like) {
return 'glyphicon-heart';
} else {
return 'glyphicon-heart-empty';
}
};
// initialize
if ($location.search().query) {
$scope.query = $location.search().query;
$scope.searchSkillz();
}
}
]); |
'use strict';
var express = require('express');
var app = express();
var mongojs = require('mongojs');
var db = mongojs('questions', ['questions']);
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var UserSchema = new Schema({
username: {
type: String,
trim: true
},
password: {
type: String,
trim: true
}
});
mongoose.model('User', UserSchema);
var User = mongoose.model('User');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
mongoose.connect('mongodb://localhost/users');
app.use(express.static(__dirname+"/public"));
app.use(bodyParser.json());
app.use(session(
{store: new MongoStore({
url: 'mongodb://localhost/test'
}),
secret:'mySecretKey',
resave: true,
saveUninitialized: true
}));
//LOG IN AND SIGN UP ROUTES
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
function(username, password, done){
User.findOne({'username': username}, function(err, user){
if(err){
throw err;
}
if(!user){
console.log('whats up');
return done(null, false, {alert:'Incorrect username.'});
}
if(user.password != password){
console.log('que paso');
return done(null, false, {alert: 'Incorrect password.'});
}
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
//CHECK IF AUTHENTICATED
function isAuthenticated(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.send(401);
}
//LOG IN AND SIGN UP ROUTES
app.post('/login', passport.authenticate('local'), function(req, res){
console.log(req.user);
res.json(req.user);
});
app.get('/currentuser',isAuthenticated,function(req,res){
res.json(req.user);
});
app.post('/signup',function(req,res){
var u = new User();
u.username = req.body.username;
u.password = req.body.password;
u.save(function(err){
if (err) {
res.json({'alert':'Registration error'});
}else{
res.json({'alert':'Registration success'});
}
});
});
app.get('/logout', function(req, res){
console.log('logout');
req.logout();
res.send(200);
});
//QUESTIONS PART OF SERVER
app.get('/questions', function(req, res){
console.log('I recieved a GET request');
db.questions.find(function(err, docs){
if(err) throw err;
console.log(docs);
res.json(docs);
});
});
app.post('/questions', isAuthenticated, function(req, res){
console.log(req.body);
db.questions.insert(req.body, function(err,doc){
if(err) throw err;
res.json(doc);
});
});
app.delete('/questions/:id', isAuthenticated, function(req,res){
var id = req.params.id;
//console.log(id);
db.questions.remove({_id: mongojs.ObjectId(id)}, function(err,doc){
if(err) throw err;
res.json(doc);
});
});
app.put('/questions/:id', function(req,res){
var id=req.params.id;
if(req.body.newChoice && req.body.count){
db.questions.findAndModify({query:{_id: mongojs.ObjectId(id)},
update:{$addToSet:{options: req.body.newChoice}, $set:{count: req.body.count}},
new: true}, function(err,doc){
if(err) throw err;
res.json(doc);
}
);
}
else{
console.log('count being saved');
db.questions.findAndModify({query:{_id: mongojs.ObjectId(id)},
update:{$set:{count: req.body}},
new: true}, function(err,doc){
if(err) throw err;
res.json(doc);
});
}
});
app.listen(8080, function () {
console.log('Listening on port 8080...');
}); |
export const find = (array, element) => {
let start = 0;
let end = array.length - 1;
let middle;
while (start <= end) {
middle = Math.floor((start + end) / 2);
if (element === array[middle]) {
return middle;
} else if (element < array[middle]) {
end = middle - 1;
} else if (element > array[middle]) {
start = middle + 1;
}
}
throw new Error('Value not in array');
};
|
import Joi from 'joi'
export default class EventsEntity {
constructor(deps = {}) {
this.Adapter = deps.Adapter || require('./Adapter').default
}
createValidation(input){
return new Promise((resolve, reject) => {
let schema = Joi.object().keys({
game: Joi.string().required(),
time: Joi.number().required(),
participants: Joi.array().min(1).items(
Joi.number()
).required()
})
let result = Joi.validate(input, schema)
if(!result.error){
resolve(result.value)
} else {
let outputMessage = {
name: 'ValidationError',
messages: result.error.details.map(e => e.message)
}
reject(outputMessage)
}
})
}
create(body){
let adapter = new this.Adapter
return adapter.save(body)
}
updateValidation(input){
return new Promise((resolve, reject) => {
let schema = Joi.object().keys({
id: Joi.string().required(),
game: Joi.string().optional(),
time: Joi.number().optional(),
participants: Joi.array().min(1).items(
Joi.number()
).optional()
})
let result = Joi.validate(input, schema)
if(!result.error){
resolve(result.value)
} else {
let outputMessage = {
name: 'ValidationError',
messages: result.error.details.map(e => e.message)
}
reject(outputMessage)
}
})
}
update(body){
let adapter = new this.Adapter
return adapter.update(body)
}
read(ids){
let adapter = new this.Adapter
if(!ids || ids.length === 0){
return adapter.read()
}
switch(ids.length){
case 1:
return adapter.readOne(ids[0])
}
}
delete(id){
let adapter = new this.Adapter
return adapter.delete(id)
}
}
|
module.exports.DB = require('./lib/database');
module.exports.Layer = require('./lib/layer');
|
const initStart = process.hrtime();
const DeviceDetector = require('device-detector-js');
const detector = new DeviceDetector({ skipBotDetection: true, cache: false });
// Trigger a parse to force cache loading
detector.parse('Test String');
const initTime = process.hrtime(initStart)[1] / 1000000000;
const package = require(require('path').dirname(
require.resolve('device-detector-js')
) + '/../package.json');
const version = package.version;
let benchmark = false;
const benchmarkPos = process.argv.indexOf('--benchmark');
if (benchmarkPos >= 0) {
process.argv.splice(benchmarkPos, 1);
benchmark = true;
}
const lineReader = require('readline').createInterface({
input: require('fs').createReadStream(process.argv[2])
});
const output = {
results: [],
parse_time: 0,
init_time: initTime,
memory_used: 0,
version: version
};
lineReader.on('line', function(line) {
if (line === '') {
return;
}
const start = process.hrtime();
let error = null,
result = {},
r;
try {
r = detector.parse(line);
} catch (err) {
error = err;
result = {
useragent: line,
parsed: {
browser: {
name: null,
version: null
},
platform: {
name: null,
version: null
},
device: {
name: null,
brand: null,
type: null,
ismobile: null
}
}
};
}
const end = process.hrtime(start)[1] / 1000000000;
output.parse_time += end;
if (benchmark) {
return;
}
if (typeof r !== 'undefined') {
result = {
useragent: line,
parsed: {
browser: {
name: r.client && r.client.name ? r.client.name : null,
version:
r.client && r.client.version ? r.client.version : null
},
platform: {
name: r.os && r.os.name ? r.os.name : null,
version: r.os && r.os.version ? r.os.version : null
},
device: {
name: r.device && r.device.model ? r.device.model : null,
brand: r.device && r.device.brand ? r.device.brand : null,
type: r.device && r.device.type ? r.device.type : null,
ismobile:
r.device &&
(r.device.type === 'mobile' ||
r.device.type === 'mobilephone' ||
r.device.type === 'tablet' ||
r.device.type === 'wearable')
? true
: false
}
},
time: end,
error: error
};
} else {
result.error = error;
result.time = end;
}
output.results.push(result);
});
lineReader.on('close', function() {
output.memory_used = process.memoryUsage().heapUsed;
console.log(JSON.stringify(output));
});
|
// Allow a form to post without navigating to another page:
postForm = function(oFormElement) {
if (!oFormElement.action) { return; }
var oReq = new XMLHttpRequest();
if (oFormElement.method.toLowerCase() === "post") {
oReq.open("post", oFormElement.action);
oReq.send(new FormData(oFormElement));
} else {
console.error("Can only use post with this!");
}
}
// Make it so ctrl-Enter can send a message:
onKeyDown = function(e) {
var keynum;
var keychar;
var numcheck;
keynum = e.keyCode;
if (e.ctrlKey && (keynum == 13 || // ctrl-Enter
keynum == 77)) // ctrl-M (ctrl-Enter on mac firefox does
// this)
{
postForm(document.forms["messageForm"]);
document.getElementById('content').value='';
return false;
}
return true;
}
// Called every time a new message shows up from the server:
onMessage = function(messages) {
var posted_at_bottom = false;
var height_before = $(document).height();
for (var i = 0; i < messages.length; i++) {
var message = messages[i];
var html = "<div class=\"message\" data-messageid=\"" + message.id +
"\"><b title=\"" + message.email + "\">" + message.nickname + " (" +
message.topic + ") [" + message.date + "]</b><blockquote>" +
message.content + "</blockquote></div>";
// Now we need to figure out where to add this message. Optimize for
// the common cases of it being inserted first or last:
if ($(".message").length == 0 ||
$(".message").last().attr("data-messageid") < message.id) {
$(".bottom").last().before(html);
posted_at_bottom = true;
} else {
var iter = $(".message").first();
while (iter != null) {
if (iter.attr("data-messageid") == message.id) {
// Discard duplicate message:
iter = null;
} else if (iter.attr("data-messageid") > message.id) {
iter.before(html);
iter = null;
} else {
iter = iter.next();
}
}
}
}
var height_after = $(document).height();
// Lame attempt at making the window not scroll as we insert new messages at
// the top. This doesn't always work very well, feel free to improve this
// if you are reading this. :-)
var new_scroll_position = height_after - height_before;
if (new_scroll_position > 0 && !posted_at_bottom) {
$(window).scrollTop(new_scroll_position);
}
}
onOpened = function() {
console.log("Channel to server opened.");
if($(".message").length == 0) {
fetchMoreMessages();
}
}
// Initialization, called once upon page load:
openChannel = function() {
// [START auth_login]
// sign into Firebase with the token passed from the server
firebase.auth().signInWithCustomToken(token).catch(function(error) {
console.log('Login Failed!', error.code);
console.log('Error message: ', error.message);
console.log('Token: ', token);
});
// [END auth_login]
// [START add_listener]
// setup a database reference at path /channels/channelId
channel = firebase.database().ref('channels/' + channelId);
// add a listener to the path that fires any time the value of the data
// changes
channel.on('value', function(data) {
onMessage(data.val());
});
// [END add_listener]
onOpened();
// let the server know that the channel is open
}
fetchMoreMessages = function() {
// Send a "get" request back to the server so it provides us with messages
// older than last_id:
var last_id = $(".message").first().attr("data-messageid")
if($(".message").length == 0) {
last_id = "2099-01-01T01:00:00.000000";
}
$.post("get", {older_than: last_id});
}
onScroll = function() {
// If the user scrolls up to the top of the window, load some older
// messages to display for them and insert them into the top.
if ($(window).scrollTop() == 0){
fetchMoreMessages();
}
}
// Invoked by jQuery once the DOM is constructed:
$(function () {
// Set callback to invoke when window scrolls:
$(window).on("scroll", onScroll);
// Scroll to bottom of document
$(window).scrollTop($(document).height() - $(window).height());
// Open channel back to server to get new messages:
openChannel();
});
|
/**
*
* @fileoverview fileoverview comment before import. transformer_util.ts has
* special logic to handle comments before import/require() calls. This file
* tests the regular import case.
*
* @suppress {checkTypes} checked by tsc
*/
goog.module('test_files.file_comment.before_import');var module = module || {id: 'test_files/file_comment/before_import.js'};
var comment_before_var_1 = goog.require('test_files.file_comment.comment_before_var');
const tsickle_forward_declare_1 = goog.forwardDeclare("test_files.file_comment.comment_before_var");
console.log(comment_before_var_1.y);
|
export const ic_looks_two_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M19 5H5v14h14V5zm-4 6c0 1.11-.9 2-2 2h-2v2h4v2H9v-4c0-1.11.9-2 2-2h2V9H9V7h4c1.1 0 2 .89 2 2v2z","opacity":".3"},"children":[]},{"name":"path","attribs":{"d":"M5 21h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2zM5 5h14v14H5V5zm8 2H9v2h4v2h-2c-1.1 0-2 .89-2 2v4h6v-2h-4v-2h2c1.1 0 2-.89 2-2V9c0-1.11-.9-2-2-2z"},"children":[]}]}; |
;(function() {
"use strict";
owid.namespace("App.Views.Form.MapColorSchemeView");
var ColorPicker = App.Views.UI.ColorPicker;
App.Views.Form.MapColorSchemeView = Backbone.View.extend({
el: "#form-view #map-tab .map-color-scheme-preview",
events: {},
initialize: function( options ) {
this.dispatcher = options.dispatcher;
this.$colorAutomaticClassification = $("[name='map-color-automatic-classification']");
this.$colorAutomaticClassification.on( "change", this.onAutomaticClassification.bind(this) );
this.$colorInvert = $("[name='map-color-invert']");
this.$colorInvert.on("change", this.onColorInvert.bind(this));
App.ChartModel.on( "change", this.onChartModelChange, this );
this.render();
},
onChartModelChange: function() {
this.mapConfig = App.ChartModel.get("map-config");
this.render();
},
render: function() {
var that = this,
mapConfig = App.ChartModel.get("map-config"),
colorScheme = owdColorbrewer.getColors(mapConfig);
this.$el.empty();
var html = "",
//get values stored in the database
colorSchemeKeys = _.map( colorScheme, function( d, i ) { return i; } ),
colorSchemeInterval = mapConfig.colorSchemeInterval,
colorSchemeValues = mapConfig.colorSchemeValues,
colorSchemeLabels = mapConfig.colorSchemeLabels,
minimalColorSchemeValue = ( mapConfig.colorSchemeMinValue )? mapConfig.colorSchemeMinValue: "";
//minimal value option
html += "<li class='clearfix min-color-wrapper'><span>Minimal value:</span><input class='map-color-scheme-value form-control' name='min-color-scheme-value' type='text' placeholder='Minimal value' value='" + minimalColorSchemeValue + "' /></li>";
for( var i = 0; i < colorSchemeInterval; i++ ) {
var key = colorSchemeKeys[ i ],
color = ( colorScheme[ key ] )? colorScheme[ key ]: "#fff",
value = ( colorSchemeValues && colorSchemeValues[ i ] )? colorSchemeValues[ i ]: "",
label = ( colorSchemeLabels && colorSchemeLabels[ i ] )? colorSchemeLabels[ i ]: "";
html += "<li class='clearfix'><span class='map-color-scheme-icon' style='background-color:" + color + ";' data-color='" + color + "'></span><input class='map-color-scheme-value form-control' name='map-scheme[]' type='text' placeholder='Maximum value' value='" + value + "' /><input class='map-color-scheme-label form-control' name='map-label[]' type='text' placeholder='Category label' value='" + label + "' /></li>";
}
this.$el.append( $( html ) );
this.$lis = this.$el.find( ".map-color-scheme-icon" );
this.$lis.on( "click", function( evt ) {
evt.preventDefault();
var $country = $(evt.currentTarget);
if (that.colorPicker)
that.colorPicker.onClose();
that.colorPicker = new ColorPicker({ target: $country, currentColor: $country.attr("data-color") });
that.colorPicker.onSelected = function( value ) {
$country.css( "background-color", value );
$country.attr( "data-color", value );
that.updateColorScheme();
//App.ChartModel.updateSelectedCountry( $countryLabel.attr( "data-id" ), value );
};
} );
var colorSchemeValuesAutomatic = ( mapConfig.colorSchemeValuesAutomatic !== undefined )? mapConfig.colorSchemeValuesAutomatic: true;
this.$el.toggleClass( "automatic-values", colorSchemeValuesAutomatic );
this.$colorAutomaticClassification.prop( "checked", colorSchemeValuesAutomatic );
this.$colorInvert.prop("checked", mapConfig.colorSchemeInvert);
//react to user entering custom values
this.$inputs = this.$el.find(".map-color-scheme-value");
this.$inputs.on( "change", function( evt ) {
that.updateSchemeValues( evt );
} );
this.$labelInputs = this.$el.find(".map-color-scheme-label");
this.$labelInputs.on( "change", function( evt ) {
that.updateSchemeLabels( evt );
} );
},
updateColorScheme: function() {
var colors = _.map(this.$lis, function(el) {
return $(el).attr("data-color");
});
if (this.mapConfig.colorSchemeInvert)
colors.reverse();
App.ChartModel.updateMapConfig("customColorScheme", colors, true);
App.ChartModel.updateMapConfig("colorSchemeName", "custom");
},
updateSchemeValues: function( evt ) {
//updating minimal value?
var $minValueInput = this.$inputs.eq( 0 );
if( $minValueInput.get( 0 ) == evt.currentTarget ) {
App.ChartModel.updateMapConfig( "colorSchemeMinValue", $minValueInput.val() );
} else {
//update values
var values = [];
$.each( this.$inputs, function( i, d ) {
//first input is minimal value
if( i > 0 ) {
var inputValue = $( d ).val();
//if( inputValue ) {
values.push( inputValue );
//}
}
} );
App.ChartModel.updateMapConfig( "colorSchemeValues", values );
}
},
updateSchemeLabels: function() {
//update values
var values = [];
$.each(this.$labelInputs, function( i, d ) {
var inputValue = $( d ).val();
values.push( inputValue );
});
App.ChartModel.updateMapConfig("colorSchemeLabels", values);
},
onAutomaticClassification: function(evt) {
var checked = this.$colorAutomaticClassification.prop("checked");
this.$el.toggleClass("automatic-values", checked);
App.ChartModel.updateMapConfig("colorSchemeValuesAutomatic", checked);
},
onColorInvert: function(evt) {
var checked = this.$colorInvert.prop("checked");
App.ChartModel.updateMapConfig("colorSchemeInvert", checked);
}
});
})(); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
exports.extractStyle = extractStyle;
exports.setActiveAndFocusProps = setActiveAndFocusProps;
exports.joinClasses = joinClasses;
var _constants = require('./constants');
// extract and return the style object and className string for the state given
function extractStyle(props, state) {
// if no hoverActive prop, then use hover prop for style and classes
var stateProp = state === 'hoverActive' && !props.hoverActive ? 'hover' : state;
// loop until the state prop to use is found (i.e. it's not a string)
var times = 0;
while (typeof stateProp === 'string' && times < 10) {
stateProp = props[stateProp];
times++;
}
// if the state prop to use wasn't found, then return a blank style and className object
if ((typeof stateProp === 'undefined' ? 'undefined' : _typeof(stateProp)) !== 'object') return { style: null, className: '' };
var extract = {};
// check if the stateProp is an options object, and extract style and className from the stateProp
if (_constants.statePropOptionKeys.some(function (key) {
return stateProp[key];
})) {
extract.style = stateProp.style || null;
extract.className = stateProp.className || '';
} else {
// if the stateProp is not an options object, then it's a style object
extract.style = stateProp;
extract.className = '';
}
return extract;
}
function setActiveAndFocusProps(props) {
// use the `active` prop for `[type]Active` if no `[type]Active` prop
if (props.active) {
if (!props.hoverActive) props.hoverActive = props.active;
if (!props.touchActive) props.touchActive = props.active;
if (!props.keyActive) props.keyActive = props.active;
}
// use the `focus` prop for `focusFrom[type]` if no `focusFrom[type]` prop
if (props.focus) {
if (!props.focusFromTab) props.focusFromTab = props.focus;
if (!props.focusFromMouse) props.focusFromMouse = props.focus;
if (!props.focusFromTouch) props.focusFromTouch = props.focus;
}
}
function joinClasses(className, iStateClass, focusClass) {
var joined = className;
joined += joined && iStateClass ? ' ' + iStateClass : '' + iStateClass;
joined += joined && focusClass ? ' ' + focusClass : '' + focusClass;
return joined;
} |
import Ember from 'ember';
import SelectPicker from './select-picker';
import ItemCursorMixin from 'ember-cli-select-picker/mixins/item-cursor';
const KEY_ENTER = 13;
const KEY_ESC = 27;
const KEY_UP = 38;
const KEY_DOWN = 40;
export default SelectPicker.extend(ItemCursorMixin, {
layoutName: 'components/select-picker',
classNames: ['select-picker', 'keyboard-select-picker'],
didInsertElement() {
this.$().on(`keydown.${this.get('elementId')}`,
Ember.run.bind(this, 'handleKeyPress'));
},
willDestroyElement() {
this.$().off(`keydown.${this.get('elementId')}`);
},
focusActiveItem() {
this.$(`[data-itemid=${this.get('activeItem.itemId')}]`).focus();
},
handleKeyPress(e) {
var actionName = (() => {
switch (e.which) {
case KEY_DOWN: return 'activeNext';
case KEY_UP: return 'activePrev';
case KEY_ESC: return 'closeDropdown';
case KEY_ENTER:
return this.get('showDropdown') ?
'selectActiveItem' :
'openDropdown';
default: return null;
}
})();
if (actionName) {
e.preventDefault();
Ember.run(() => { this.send(actionName); });
this.focusActiveItem();
return false;
}
return true;
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.