text
stringlengths 2
6.14k
|
|---|
/**
* @method find
*
* @description
* This method will apply filters from the options object passed in to
* filter.
*/
const db = require('../../../lib/db');
const FilterParser = require('../../../lib/filter');
function find(options) {
// ensure epected options are parsed appropriately as binary
const filters = new FilterParser(options, { tableAlias : 'payroll' });
let statusIds = [];
let referenceEmployees = [];
if (options.status_id) {
statusIds = statusIds.concat(options.status_id);
}
if (options.reference) {
referenceEmployees = options.reference;
}
const sql = `
SELECT payroll.employee_uuid, payroll.reference, payroll.code, payroll.date_embauche, payroll.nb_enfant,
payroll.individual_salary, payroll.account_id, payroll.creditor_uuid, payroll.display_name, payroll.sex,
payroll.uuid, payroll.payroll_configuration_id, payroll.currency_id, payroll.paiement_date, payroll.base_taxable,
payroll.basic_salary, payroll.gross_salary, payroll.grade_salary, payroll.text, payroll.net_salary,
payroll.working_day, payroll.total_day, payroll.daily_salary, payroll.amount_paid,
payroll.status_id, payroll.status, (payroll.net_salary - payroll.amount_paid) AS balance
FROM(
SELECT BUID(employee.uuid) AS employee_uuid, employee.reference, employee.code, employee.date_embauche,
employee.nb_enfant,employee.individual_salary, creditor_group.account_id,
BUID(employee.creditor_uuid) AS creditor_uuid,
UPPER(patient.display_name) AS display_name, patient.sex, BUID(paiement.uuid) AS uuid,
paiement.payroll_configuration_id, paiement.currency_id, paiement.paiement_date, paiement.base_taxable,
paiement.basic_salary, paiement.gross_salary, grade.basic_salary AS grade_salary, grade.text,
paiement.net_salary, paiement.working_day, paiement.total_day, paiement.daily_salary, paiement.amount_paid,
paiement.status_id, paiement_status.text AS status
FROM employee
JOIN creditor ON creditor.uuid = employee.creditor_uuid
JOIN creditor_group ON creditor_group.uuid = creditor.group_uuid
JOIN patient ON patient.uuid = employee.patient_uuid
JOIN grade ON employee.grade_uuid = grade.uuid
JOIN paiement ON paiement.employee_uuid = employee.uuid
JOIN payroll_configuration ON payroll_configuration.id = paiement.payroll_configuration_id
JOIN config_employee ON config_employee.id = payroll_configuration.config_employee_id
JOIN config_employee_item ON config_employee_item.employee_uuid = employee.uuid
JOIN paiement_status ON paiement_status.id = paiement.status_id
WHERE paiement.payroll_configuration_id = '${options.payroll_configuration_id}'
UNION
SELECT BUID(employee.uuid) AS employee_uuid, employee.reference, employee.code, employee.date_embauche,
employee.nb_enfant, employee.individual_salary, creditor_group.account_id,
BUID(employee.creditor_uuid) AS creditor_uuid, UPPER(patient.display_name) AS display_name,
patient.sex, NULL AS 'paiement_uuid', '${options.payroll_configuration_id}' AS payroll_configuration_id,
'${options.currency_id}' AS currency_id, NULL AS paiement_date, 0 AS base_taxable, 0 AS basic_salary,
0 AS gross_salary, grade.basic_salary AS grade_salary, grade.text, 0 AS net_salary, 0 AS working_day,
0 AS total_day, 0 AS daily_salary, 0 AS amount_paid, 1 AS status_id,
'PAYROLL_STATUS.WAITING_FOR_CONFIGURATION' AS status
FROM employee
JOIN creditor ON creditor.uuid = employee.creditor_uuid
JOIN creditor_group ON creditor_group.uuid = creditor.group_uuid
JOIN patient ON patient.uuid = employee.patient_uuid
JOIN grade ON employee.grade_uuid = grade.uuid
JOIN config_employee_item ON config_employee_item.employee_uuid = employee.uuid
JOIN config_employee ON config_employee.id = config_employee_item.config_employee_id
JOIN payroll_configuration ON payroll_configuration.config_employee_id = config_employee.id
WHERE employee.uuid NOT IN (
SELECT paiement.employee_uuid
FROM paiement
WHERE paiement.payroll_configuration_id = '${options.payroll_configuration_id}')
AND payroll_configuration.id = '${options.payroll_configuration_id}'
) AS payroll`;
filters.fullText('display_name');
filters.fullText('code');
// Company currency filtering is optional only if you want to
// know the currency for which the employees have been configured for payment
if (options.filterCurrency) {
filters.equals('currency_id');
}
filters.custom('status_id', 'payroll.status_id IN (?)', [statusIds]);
filters.custom('reference', 'payroll.reference IN (?)', [referenceEmployees]);
filters.setOrder('ORDER BY payroll.display_name');
const query = filters.applyQuery(sql);
const parameters = filters.parameters();
return db.exec(query, parameters);
}
exports.find = find;
|
/***************************
* Modules Model
* Get module information
***************************/
var SensorsModel = function(){
// get module according device
this.getModulesSensors = function(deviceId, cb){
getConnection(function(mongoose){
// create member
var model = require('../database/sensorSchema').SensorSchema(mongoose);
model.find({device_id: deviceId}, function(err, result){
// close connection
closeConnection(mongoose);
if(err){
cb(err, null);
}
else{
cb(null, result);
}
});
});
}
// add new sensor
this.addSensor = function(data, cb){
getConnection(function(mongoose){
// create member
var model = require('../database/sensorSchema').SensorSchema(mongoose);
var schema = model({
device_id: data.deviceId,
deviceName: data.deviceName,
name: data.name,
image: data.file,
dateTime: data.date
});
// save new member information
schema.save(function(err, result){
// close connection
closeConnection(mongoose);
if(err){
cb(err, null);
}
else{
cb(null, result);
}
});
});
}
// get modules list
this.getSensorsList = function(cb){
getConnection(function(mongoose){
// create member
var model = require('../database/sensorSchema').SensorSchema(mongoose);
model.find({}, function(err, result){
// close connection
closeConnection(mongoose);
if(err){
cb(err, null);
}
else{
cb(null, result);
}
});
});
}
// update device status
this.changeSensorStatus = function(data, cb){
getConnection(function(mongoose){
// create member
var model = require('../database/sensorSchema').SensorSchema(mongoose);
model.update({ _id: data.id },{status: data.status}, function(err, result){
// close connection
closeConnection(mongoose);
if(err){
cb(err, null);
}
else{
cb(null, result);
}
});
});
}
// delete device
this.deleteSensor = function(data, cb){
var fs = require('fs');
getConnection(function(mongoose){
// create member
var model = require('../database/sensorSchema').SensorSchema(mongoose);
model.remove({ _id: data.id }, function(err, result){
// close connection
closeConnection(mongoose);
if(err){
cb(err, null);
}
else{
// remove image file of device
var filePath = './public/'+data.img;
fs.unlink(filePath);
cb(null, result);
}
});
});
}
// get sensor information
this.getSensorInfo = function(id, cb){
getConnection(function(mongoose){
// create member
var model = require('../database/sensorSchema').SensorSchema(mongoose);
model.findOne({ _id: id }, function(err, result){
// close connection
closeConnection(mongoose);
if(err){
cb(err, null);
}
else{
cb(null, result);
}
});
});
}
// update sensor information
this.updateSensor = function(data, cb){
getConnection(function(mongoose){
// create member
var model = require('../database/sensorSchema').SensorSchema(mongoose);
model.update({ _id: data.id },{
device_id: data.deviceId,
deviceName: data.deviceName,
name: data.name,
image: data.file,
dateTime: data.date
}, function(err, result){
// close connection
closeConnection(mongoose);
if(err){
cb(err, null);
}
else{
// remove image file of device
if(data.imgFlag == false){
var fs = require('fs');
var filePath = './public/'+data.image;
fs.unlink(filePath);
}
cb(null, result);
}
});
});
}
this.getSensorsInfo = function(sensors, cb){
getConnection(function(mongoose){
// create member
var model = require('../database/sensorSchema').SensorSchema(mongoose);
model.find({ _id: { $in: sensors } }, function(err, result){
// close connection
closeConnection(mongoose);
if(err){
cb(err, null);
}
else{
cb(null, result);
}
});
});
}
}
SensorsModel.__proto__ = new model;
module.exports = SensorsModel;
|
// first set the body to hide and show everyhthing when fully loaded ;)
document.write("<style>body{display:none;}</style>");
jQuery(document).ready(function(){
jQuery( 'input.search-field' ).addClass( 'form-control' );
// here for each comment reply link of wordpress
jQuery( '.comment-reply-link' ).addClass( 'btn btn-primary' );
// here for the submit button of the comment reply form
jQuery( '#commentsubmit' ).addClass( 'btn btn-primary' );
// The WordPress Default Widgets
// Now we'll add some classes for the wordpress default widgets - let's go
// the search widget
jQuery( 'input.search-field' ).addClass( 'form-control' );
jQuery( 'input.search-submit' ).addClass( 'btn btn-default' );
jQuery( '.widget_rss ul' ).addClass( 'media-list' );
jQuery( '.widget_meta ul, .widget_recent_entries ul, .widget_archive ul, .widget_categories ul, .widget_nav_menu ul, .widget_pages ul' ).addClass( 'nav' );
jQuery( '.widget_recent_comments ul#recentcomments' ).css( 'list-style', 'none').css( 'padding-left', '0' );
jQuery( '.widget_recent_comments ul#recentcomments li' ).css( 'padding', '5px 15px');
jQuery( 'table#wp-calendar' ).addClass( 'table table-striped');
jQuery(document.body).show();
});
|
// Category View
// =============
define([
"jquery",
"backbone"
], function( $, Backbone ) {
var View = Backbone.View.extend( {
//构造初始化
initialize: function() {
//this.assignme = "0";
},
//设置UI的动作
events: {
//"click #services_refresh": "refresh"
},
//UI加载触发的方法
onLoad:function(viewName,params){
/*
T.assertParamsLength(params,1);
$.mobile.changePage("#"+viewName, {
reverse: false,
changeHash: false
});
*/
},
onResume:function(viewName,params){
//this.render(null);
}
//渲染UI界面
render:function(collection){
/*
this.template = _.template( $( "script#services_list_template" ).html(), { "collection": collection } );
$("#services_list").html(this.template);
*/
return this;
}
} );
return View;
} );
|
define([],function(){
/**
* The WHGeometryFactory serves as a (abstract)base
* for all geometry factories
**/
var WHGeometryFactory = function ()
{
this.keywords = [];
this.name = "undefined";
}
WHGeometryFactory.prototype.supports = function(whGeometryPrimitive){
return false;
}
WHGeometryFactory.prototype.build = function(options, callback){
callback("");
}
return WHGeometryFactory;
});
|
// Copyright (c) 2015, Revant Nandgaonkar and contributors
// For license information, please see license.txt
cur_frm.add_fetch("worker", "employee_name", "worker_name");
cur_frm.add_fetch("worker", "workstation", "workstation");
cur_frm.add_fetch("worker", "outstanding_wages", "t_os_wage");
var os_wages_account = "";
frappe.ui.form.on("Wage Slip", {
onload: function(frm) {
frappe.call({
method: "civil_contracting.civil_contracting.doctype.worker_sheet_settings.worker_sheet_settings.get_account",
args: {
company: frm.doc.company
},
callback: function (data) {
os_wages_account = data.message[1].account;
if(!os_wages_account){
msgprint (__("Set Outstanding Wages account in Worker Sheet Settings"));
}
}
})
}
});
frappe.ui.form.on("Wage Slip", "get_outstanding_wages", function(frm) {
frm.set_value("payment_allocation", []);
return frappe.call({
method: 'civil_contracting.civil_contracting.doctype.wage_slip.wage_slip.get_os_wg',
args: {
"supplier": frm.doc.supplier,
"project": frm.doc.project
},
callback: function(r, rt) {
if(r.message) {
frm.clear_table("payment_allocation");
$.each(r.message, function(i, d) {
var c = frm.add_child("payment_allocation");
c.worker = d.name;
c.worker_name = d.employee_name;
c.workstation = d.workstation;
c.t_os_wage = d.outstanding_wages;
c.t_payment = d.outstanding_wages;
});
}
refresh_field("payment_allocation");
frm.layout.refresh_sections();
}
});
});
calculate_totals = function(doc) {
var allocation = doc.payment_allocation || [];
doc.total_os_wages = 0.0;
doc.total_payment = 0.0;
for(var i=0;i<allocation.length;i++) {
doc.total_os_wages += flt(allocation[i].t_os_wage);
doc.total_payment += flt(allocation[i].t_payment);
}
refresh_field('total_os_wages');
refresh_field('total_payment');
}
cur_frm.cscript.refresh = function(doc, dt, dn) {
if(!doc.__islocal) {
if(doc.docstatus==1 && frappe.model.can_create("Journal Entry")){
cur_frm.add_custom_button(__("Make Journal Entry"), make_journal_entry);
}
}
calculate_totals(doc);
}
make_journal_entry = function() {
var me = this;
if(cur_frm.doc.mode_of_payment === "Cash") {
voucher_type = "Cash Entry";
}
else if(cur_frm.doc.mode_of_payment === "Cheque") {
voucher_type = "Bank Entry";
}
return frappe.call({
method: "erpnext.accounts.doctype.journal_entry.journal_entry.get_default_bank_cash_account",
args: {
"company": cur_frm.doc.company,
"voucher_type": voucher_type
},
callback: function(r) {
var jv = frappe.model.make_new_doc_and_get_name('Journal Entry');
jv = locals['Journal Entry'][jv];
jv.voucher_type = voucher_type;
jv.company = cur_frm.doc.company;
jv.remark = 'Payment against Worker Sheet: ' + cur_frm.doc.name;
jv.fiscal_year = cur_frm.doc.fiscal_year;
var d1 = frappe.model.add_child(jv, 'Journal Entry Account', 'accounts');
d1.debit_in_account_currency = flt(cur_frm.doc.total_payment);
d1.account = os_wages_account;
// credit to cash_bank_account
var d2 = frappe.model.add_child(jv, 'Journal Entry Account', 'accounts');
d2.credit_in_account_currency = flt(cur_frm.doc.total_payment);
if(r.message) {
d2.account = r.message.account;
d2.balance = r.message.balance;
}
loaddoc('Journal Entry', jv.name);
}
});
}
|
featuredcontentslider.init({
id: "slider2", //id of main slider DIV
contentsource: ["inline", ""], //Valid values: ["inline", ""] or ["ajax", "path_to_file"]
toc: "markup", //Valid values: "#increment", "markup", ["label1", "label2", etc]
nextprev: ["Previous", "Next"], //labels for "prev" and "next" links. Set to "" to hide.
revealtype: "click", //Behavior of pagination links to reveal the slides: "click" or "mouseover"
enablefade: [true, 0.2], //[true/false, fadedegree]
autorotate: [true, 3000], //[true/false, pausetime]
onChange: function(previndex, curindex){ //event handler fired whenever script changes slide
//previndex holds index of last slide viewed b4 current (1=1st slide, 2nd=2nd etc)
//curindex holds index of currently shown slide (1=1st slide, 2nd=2nd etc)
}
})
|
/*
* @package AJAX_Chat
* @author Sebastian Tschan
* @contributors Ettelcar, Massimiliano Tiraboschi, Xytovl
* @copyright (c) Sebastian Tschan
* @license GNU Affero General Public License
* @link https://blueimp.net/ajax/
*/
// Ajax Chat language Object:
var ajaxChatLang = {
login: '%s se connecte au Chat.',
logout: '%s se déconnecte du Chat.',
logoutTimeout: '%s a été déconnecté (Temps écoulé).',
logoutIP: '%s a été déconnecté (Adresse IP invalide).',
logoutKicked: '%s a été déconnecté (Éjecté).',
channelEnter: '%s entre dans le salon.',
channelLeave: '%s sort du salon.',
privmsg: '(murmure)',
privmsgto: '(murmure à l’oreille de %s)',
invite: '%s vous invite à rejoindre %s.',
inviteto: 'Votre invation pour %s à rejoindre le salon %s a bien été envoyée.',
uninvite: '%s annule son invitation pour le salon %s.',
uninviteto: 'Votre annulaton d’invitation pour %s au salon %s a bien été envoyée.',
queryOpen: 'Salon privé ouvert sous le titre %s.',
queryClose: 'Le salon privé %s a été fermé.',
ignoreAdded: '%s a été ajouté à la liste des personnes ignorées.',
ignoreRemoved: '%s a été enlevé de la liste des personnes ignorées.',
ignoreList: 'Utilisateurs ignorés:',
ignoreListEmpty: 'Aucun utilisateur ignoré référencé.',
who: 'Utilisateurs en ligne:',
whoChannel: 'Utilisateurs en ligne dans le salon %s :',
whoEmpty: 'Aucun utilisateur en ligne dans le salon concerné.',
list: 'Salons disponibles :',
bans: 'Utilisateurs bannis :',
bansEmpty: 'Aucun utilisateur banni référencé.',
unban: 'Le ban de l’utilisateur %s a été levé.',
whois: 'Utilisateur %s - Adresse IP:',
whereis: 'L’utilisateur %s est dans le salon %s.',
roll: '%s jette %s et obtient %s.',
nick: '%s est maintenant %s.',
toggleUserMenu: 'Montrer/cacher menu pour %s',
userMenuLogout: 'Déconnexion',
userMenuWho: 'Liste membres en ligne',
userMenuList: 'Liste salons disponibles',
userMenuAction: 'Décrire une action',
userMenuRoll: 'Jeter un dé',
userMenuNick: 'Changer nom',
userMenuEnterPrivateRoom: 'Rejoindre un salon privé',
userMenuSendPrivateMessage: 'Envoyer un message privé',
userMenuDescribe: 'Envoyer une action privé',
userMenuOpenPrivateChannel: 'Ouvrir un salon privé',
userMenuClosePrivateChannel: 'Fermer un salon privé',
userMenuInvite: 'Inviter',
userMenuUninvite: 'Uninvite',
userMenuIgnore: 'Ignorer/Accepter',
userMenuIgnoreList: 'Liste utilisateurs ignorés',
userMenuWhereis: 'Montrer les salons',
userMenuKick: 'Éjecter/bannir',
userMenuBans: 'Liste utilisateurs bannis',
userMenuWhois: 'Display IP',
unbanUser: 'Revoke ban of user %s',
joinChannel: 'Rejoindre le salon %s',
cite: '%s a dit:',
urlDialog: 'Veuillez entrer l’addresse (URL) de la page web:',
deleteMessage: 'Effacer ce message',
deleteMessageConfirm: 'Effacer le message selectionné ?',
errorCookiesRequired: 'Ce Chat requiert l’acceptation des cookies.',
errorUserNameNotFound: 'Erreur : Utilisateur %s introuvable.',
errorMissingText: 'Erreur : Texte du message manquant.',
errorMissingUserName: 'Erreur : Nom d’utilisateur manquant.',
errorMissingChannelName: 'Erreur : Nom de salon manquant.',
errorInvalidChannelName: 'Erreur : Mauvais nom de salon: %s',
errorPrivateMessageNotAllowed: 'Erreur : Les messages privés sont interdits.',
errorInviteNotAllowed: 'Erreur : Vous n’êtes pas autorisé à inviter quelqu’un à ce salon.',
errorUninviteNotAllowed: 'Erreur : Vous n’êtes pas autorisé à annuler une invitation à ce salon.',
errorNoOpenQuery: 'Erreur : Aucun salon privé ouvert.',
errorKickNotAllowed: 'Erreur : Vous n’êtes pas autorisé à éjecter %s.',
errorCommandNotAllowed: 'Erreur : Commande interdite: %s',
errorUnknownCommand: 'Erreur : Commande inconnue: %s',
errorMaxMessageRate: 'Error : You exceeded the maximum number of messages per minute.',
errorConnectionTimeout: 'Erreur : Temps de connexion écoulé. Veuillez réessayer.',
errorConnectionStatus: 'Erreur : Statut de connexion: %s',
errorSoundIO: 'Erreur : Impossible de charger le fichier son (Erreur E/S Flash).',
errorSocketIO: 'Erreur : Connexion au serveur échouée (Erreur E/S Flash).',
errorSocketSecurity: 'Erreur : Connexion au serveur échouée (Erreur de sécurité Flash).',
errorDOMSyntax: 'Erreur : Syntaxe DOM invalide (ID DOM : %s).'
}
|
module.exports = (bot, db, config, winston, userDocument, serverDocument, channelDocument, memberDocument, msg, suffix, commandData) => {
if(suffix == "me") {
msg.channel.createMessage({
embed: {
author: {
name: bot.user.username,
icon_url: bot.user.avatarURL,
url: "https://github.com/GilbertGobbels/GAwesomeBot"
},
color: 0x00FF00,
description: `💬 You've sent ${memberDocument.messages} message${memberDocument.messages == 1 ? "" : "s"} this week`
}
});
} else if(suffix) {
const member = bot.memberSearch(suffix, msg.channel.guild);
if(member) {
if(member.user.bot) {
msg.channel.createMessage({
embed: {
author: {
name: bot.user.username,
icon_url: bot.user.avatarURL,
url: "https://github.com/GilbertGobbels/GAwesomeBot"
},
color: 0xFF0000,
description: "I don't keep tabs on my brethren 🤖😈"
}
});
} else {
let targetMemberDocument = serverDocument.members.id(member.id);
if(!targetMemberDocument) {
serverDocument.members.push({_id: member.id});
targetMemberDocument = serverDocument.members.id(member.id);
}
msg.channel.createMessage({
embed: {
author: {
name: bot.user.username,
icon_url: bot.user.avatarURL,
url: "https://github.com/GilbertGobbels/GAwesomeBot"
},
color: 0x00FF00,
description: `💬 **@${bot.getName(msg.channel.guild, serverDocument, member)}** has sent ${targetMemberDocument.messages} message${targetMemberDocument.messages == 1 ? "" : "s"} this week`
}
});
}
} else {
winston.warn(`Requested member does not exist so ${commandData.name} cannot be shown`, {svrid: msg.channel.guild.id, chid: msg.channel.id, usrid: msg.author.id});
msg.channel.createMessage({
embed: {
author: {
name: bot.user.username,
icon_url: bot.user.avatarURL,
url: "https://github.com/GilbertGobbels/GAwesomeBot"
},
color: 0xFF0000,
description: "Who's that? I'd like to meet them 🤝"
}
});
}
} else {
let embed_fields = [];
serverDocument.members.sort((a, b) => {
return b.messages - a.messages;
}).filter(a => {
return msg.channel.guild.members.has(a._id);
}).slice(0, 10).map(a => {
embed_fields.push({
name: `**@${bot.getName(msg.channel.guild, serverDocument, msg.channel.guild.members.get(a._id))}:**`,
value: `${a.messages} message${a.messages==1 ? "" : "s"} this week`,
inline: true
});
});
if(embed_fields.length > 0) {
msg.channel.createMessage({
embed: {
author: {
name: bot.user.username,
icon_url: bot.user.avatarURL,
url: "https://github.com/GilbertGobbels/GAwesomeBot"
},
color: 0x00FF00,
fields: embed_fields
}
});
} else {
msg.channel.createMessage({
embed: {
author: {
name: bot.user.username,
icon_url: bot.user.avatarURL,
url: "https://github.com/GilbertGobbels/GAwesomeBot"
},
color: 0xFF0000,
description: "*This server is literally dead (✖╭╮✖)"
}
});
}
}
};
|
public class MainMenuTouchControl extends BaseTouchScreenControl
{
/*------------------------------------------ PRIVATE MEMBERS ------------------------------------------*/
// position of a control
private var mcControlPosition: Vector2 = Vector2(0, 0);
private var mcSpaceSize: int = 30;
/*------------------------------------------ MONOBEHAVIOR IMPLEMENTATION ------------------------------------------*/
function Start ()
{
super.Start();
mcControlPosition.x = Screen.width / 2 - mcSpaceSize;
mcControlPosition.y = Screen.height - mcSpaceSize - mcControlSize.y;
guiTexture.pixelInset = Rect(mcControlPosition.x, mcControlPosition.y, mcControlSize.x, mcControlSize.y);
}
function Update ()
{
if ( !mcScreenControlEnabled || (mcGameState != GameState.Playing && mcGameState != GameState.Tutorial) )
{
//do nothing if screen controls are disabled or if we are not in a Playing game state
return;
}
super.Update();
}
/*------------------------------------------ PROTECTED METHODS ------------------------------------------*/
protected function handleOnMouseDown()
{
openMainMenu();
}
protected function handleTouchBegan(touch: Touch)
{
openMainMenu();
}
/*------------------------------------------ PRIVATE METHODS ------------------------------------------*/
private function openMainMenu()
{
if (mcGameDirectorComponent)
{
// requesting to show a main menu.
mcGameDirectorComponent.requestChangeMainMenuState(true);
}
}
/*------------------------------------------ APPLICATION SETTINGS LISTENER ------------------------------------------*/
function onTouchControlsEnabledChanged(enabled: boolean)
{}
}
@script AddComponentMenu ("UI/Touch Screen Main Menu UI")
|
QUnit.test( "RTL slider multiple value set.", function( assert ){
Q.innerHTML = '<div class="slider"></div>';
var slider = Q.getElementsByClassName('slider')[0];
noUiSlider.create(slider, {
range: { min: 0.201, max: 1 },
step: 0.01,
start: 0.401,
direction: "rtl",
orientation: "vertical",
format: {
to: function(x){
return x.toFixed(1);
},
from: Number
}
});
equal(slider.noUiSlider.get(), 0.4);
slider.noUiSlider.set(0.201);
equal(slider.noUiSlider.get(), 0.2);
slider.noUiSlider.set(0.201);
equal(slider.noUiSlider.get(), 0.2);
});
|
/** @format */
import { By } from 'selenium-webdriver';
import AsyncBaseContainer from '../../async-base-container';
import * as driverHelper from '../../driver-helper';
export default class InstallWooCommercePage extends AsyncBaseContainer {
constructor( driver ) {
super( driver, By.css( '.jetpack-onboarding' ) );
}
async selectSellOnline() {
return await driverHelper.clickWhenClickable(
this.driver,
By.css( '.steps__button-group a.button.is-primary' )
);
}
}
|
define(['components/paperdialoghelper', 'paper-dialog', 'paper-input'], function (paperDialogHelper) {
var lastPlaylistId = '';
function redirectToPlaylist(id) {
var context = getParameterByName('context');
ApiClient.getItem(Dashboard.getCurrentUserId(), id).then(function (item) {
Dashboard.navigate(LibraryBrowser.getHref(item, context));
});
}
function onAddToPlaylistFormSubmit() {
Dashboard.showLoadingMsg();
var panel = $(this).parents('paper-dialog')[0];
var playlistId = $('#selectPlaylistToAddTo', panel).val();
if (playlistId) {
lastPlaylistId = playlistId;
addToPlaylist(panel, playlistId);
} else {
createPlaylist(panel);
}
return false;
}
function createPlaylist(dlg) {
var url = ApiClient.getUrl("Playlists", {
Name: $('#txtNewPlaylistName', dlg).val(),
Ids: $('.fldSelectedItemIds', dlg).val() || '',
userId: Dashboard.getCurrentUserId()
});
ApiClient.ajax({
type: "POST",
url: url,
dataType: "json"
}).then(function (result) {
Dashboard.hideLoadingMsg();
var id = result.Id;
paperDialogHelper.close(dlg);
redirectToPlaylist(id);
});
}
function addToPlaylist(dlg, id) {
var url = ApiClient.getUrl("Playlists/" + id + "/Items", {
Ids: $('.fldSelectedItemIds', dlg).val() || '',
userId: Dashboard.getCurrentUserId()
});
ApiClient.ajax({
type: "POST",
url: url
}).then(function () {
Dashboard.hideLoadingMsg();
paperDialogHelper.close(dlg);
Dashboard.alert(Globalize.translate('MessageAddedToPlaylistSuccess'));
});
}
function onDialogClosed() {
$(this).remove();
Dashboard.hideLoadingMsg();
}
function populatePlaylists(panel) {
var select = $('#selectPlaylistToAddTo', panel);
if (!select.length) {
$('#txtNewPlaylistName', panel).val('').focus();
return;
}
Dashboard.showLoadingMsg();
$('.newPlaylistInfo', panel).hide();
var options = {
Recursive: true,
IncludeItemTypes: "Playlist",
SortBy: 'SortName'
};
ApiClient.getItems(Dashboard.getCurrentUserId(), options).then(function (result) {
var html = '';
html += '<option value="">' + Globalize.translate('OptionNewPlaylist') + '</option>';
html += result.Items.map(function (i) {
return '<option value="' + i.Id + '">' + i.Name + '</option>';
});
select.html(html).val(lastPlaylistId || '').trigger('change');
Dashboard.hideLoadingMsg();
});
}
function getEditorHtml() {
var html = '';
html += '<form style="margin:auto;">';
html += '<div class="fldSelectPlaylist">';
html += '<label for="selectPlaylistToAddTo">' + Globalize.translate('LabelSelectPlaylist') + '</label>';
html += '<select id="selectPlaylistToAddTo" data-mini="true"></select>';
html += '</div>';
html += '<div class="newPlaylistInfo">';
html += '<div>';
html += '<paper-input type="text" id="txtNewPlaylistName" required="required" label="' + Globalize.translate('LabelName') + '"></paper-input>';
html += '</div>';
html += '<br />';
// newPlaylistInfo
html += '</div>';
html += '<br />';
html += '<div>';
html += '<button type="submit" class="clearButton" data-role="none"><paper-button raised class="submit block">' + Globalize.translate('ButtonOk') + '</paper-button></button>';
html += '</div>';
html += '<input type="hidden" class="fldSelectedItemIds" />';
html += '</form>';
return html;
}
function initEditor(content, items) {
$('#selectPlaylistToAddTo', content).on('change', function () {
if (this.value) {
$('.newPlaylistInfo', content).hide();
$('input', content).removeAttr('required');
} else {
$('.newPlaylistInfo', content).show();
$('input', content).attr('required', 'required');
}
}).trigger('change');
populatePlaylists(content);
$('form', content).on('submit', onAddToPlaylistFormSubmit);
$('.fldSelectedItemIds', content).val(items.join(','));
if (items.length) {
$('.fldSelectPlaylist', content).show();
populatePlaylists(content);
} else {
$('.fldSelectPlaylist', content).hide();
$('#selectPlaylistToAddTo', content).html('').val('').trigger('change');
}
}
function playlisteditor() {
var self = this;
self.show = function (items) {
items = items || [];
var dlg = paperDialogHelper.createDialog({
size: 'small'
});
var html = '';
var title = Globalize.translate('HeaderAddToPlaylist');
html += '<div class="dialogHeader">';
html += '<paper-icon-button icon="close" class="btnCancel"></paper-icon-button>';
html += '<div class="dialogHeaderTitle">';
html += title;
html += '</div>';
html += '</div>';
html += getEditorHtml();
dlg.innerHTML = html;
document.body.appendChild(dlg);
initEditor(dlg, items);
$(dlg).on('iron-overlay-closed', onDialogClosed);
paperDialogHelper.open(dlg);
$('.btnCancel', dlg).on('click', function () {
paperDialogHelper.close(dlg);
});
};
}
return playlisteditor;
});
|
<<<<<<< HEAD
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2010 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKPlugins object that is responsible for loading the Plugins.
*/
var FCKPlugins = FCK.Plugins = new Object() ;
FCKPlugins.ItemsCount = 0 ;
FCKPlugins.Items = new Object() ;
FCKPlugins.Load = function()
{
var oItems = FCKPlugins.Items ;
// build the plugins collection.
for ( var i = 0 ; i < FCKConfig.Plugins.Items.length ; i++ )
{
var oItem = FCKConfig.Plugins.Items[i] ;
var oPlugin = oItems[ oItem[0] ] = new FCKPlugin( oItem[0], oItem[1], oItem[2] ) ;
FCKPlugins.ItemsCount++ ;
}
// Load all items in the plugins collection.
for ( var s in oItems )
oItems[s].Load() ;
// This is a self destroyable function (must be called once).
FCKPlugins.Load = null ;
}
=======
/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2010 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Defines the FCKPlugins object that is responsible for loading the Plugins.
*/
var FCKPlugins = FCK.Plugins = new Object() ;
FCKPlugins.ItemsCount = 0 ;
FCKPlugins.Items = new Object() ;
FCKPlugins.Load = function()
{
var oItems = FCKPlugins.Items ;
// build the plugins collection.
for ( var i = 0 ; i < FCKConfig.Plugins.Items.length ; i++ )
{
var oItem = FCKConfig.Plugins.Items[i] ;
var oPlugin = oItems[ oItem[0] ] = new FCKPlugin( oItem[0], oItem[1], oItem[2] ) ;
FCKPlugins.ItemsCount++ ;
}
// Load all items in the plugins collection.
for ( var s in oItems )
oItems[s].Load() ;
// This is a self destroyable function (must be called once).
FCKPlugins.Load = null ;
}
>>>>>>> origin/master
|
var EntityController = function () {
this.constructor();
this.Data = {
lastCollissionCheck: 0,
collisionCheckDelay: 0
};
return {
Elements: this.Elements,
Data: this.Data,
find: this.find,
add: this.add,
removeElement: this.removeElement,
killNonProtected: this.killNonProtected,
checkCollisions: this.checkCollisions,
renderAll: this.renderAll
}
}
EntityController.prototype = Object.create(Controller.prototype);
EntityController.prototype.constructor = Controller;
EntityController.prototype.renderAll = function (dt) {
this.Elements.forEach(function (e) {
//for (var i = 0; i < this.Elements.length; i++) {
// var e = this.Elements[i];
var Parent = Container.find(e.Data.Position.Parent);
if (Parent) {
var ParentCoords = Parent.getCoords();
if ((ParentCoords.Visible) && (Parent.withinFrustrum(ParentCoords))) {
e.checkCollisions(dt);
e.handleBehaviours(dt);
e.updatePosition(dt);
e.draw(dt);
}
}
//}
});
/*
this.checkCollisions(dt);
this.Elements.forEach(function (e) {
e.handleBehaviours(dt);
});
this.Elements.forEach(function (e) {
e.updatePosition(dt);
});
this.Elements.forEach(function (e) {
e.draw(dt);
});
*/
}
EntityController.prototype.checkCollisions = function (dt) {
/*
for (var i2 = 0; i2 < this.Elements.length; i2++) {
var e2 = this.Elements[i2];
if ((i1 !== i2) &&
(typeof e1 !== "undefined") &&
(typeof e2 !== "undefined") &&
(e1.Data.AI.Group !== e2.Data.AI.Group) &&
(e1.Data.AI.State === AI_State.Alive) &&
(e2.Data.AI.State === AI_State.Alive) &&
(e1.Data.Physics.Collision) &&
(e2.Data.Physics.Collision)) {
if (e1.doesCollideWith(e2)) {
e1.handleCollision(e2);
return;
}
}
}
*/
/*
var now = Date.now();
if (this.Data.lastCollissionCheck + this.Data.collisionCheckDelay < now) {
for (var i1 = 0; i1 < this.Elements.length; i1++) {
var e1 = this.Elements[i1];
for (var i2 = 0; i2 < this.Elements.length; i2++) {
var e2 = this.Elements[i2];
if ((i1 !== i2) &&
(typeof e1 !== "undefined") &&
(typeof e2 !== "undefined") &&
(e1.Data.AI.Group !== e2.Data.AI.Group) &&
(e1.Data.AI.State === AI_State.Alive) &&
(e2.Data.AI.State === AI_State.Alive) &&
(e1.Data.Physics.Collision) &&
(e2.Data.Physics.Collision)) {
if (e1.doesCollideWith(e2)) {
e1.handleCollision(e2);
return;
}
}
}
}
this.Data.lastCollissionCheck = now;
}
*/
}
var Entity = new EntityController;
|
/**
* Create a contact list
* Created by Kelsie on 10/1/2015.
*/
/* globals _ */
/* exported Contact, ContactList */
/**
* Contact constructor that accepts a list of string arguments (listed below)
* @param firstName String that accepts a first name
* @param lastName String that accepts a last name
* @param address String that accepts an address
* @param zipcode String that accepts a zipcode
* @param telNum String that accepts a telephone number
* @constructor Constructor of accessible arguments
*/
var Contact = function (firstName, lastName, address, zipcode, telNum) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.zipcode = zipcode;
this.telNum = telNum;
var callNum = 0;
/**
* Calls a contact and updates an internal counter
* @returns Returns whether the call was successful
*/
this.call = function () {
callNum++;
return true;
};
/**
* Counts the number of times that a contact has been called
* @returns Returns the number of times a contact has been called
*/
this.numCalls = function () {
return callNum;
};
};
/**
* Defines a number of functions
* @constructor Constructor that defines a number of functions
*/
var ContactList = function () {
var contactList = [];
/**
* Accepts a contact and adds it to an internal data structure
* @param contact Contact data
* @returns Returns added contact
*/
this.addContact = function (contact) {
contactList.push(contact);
return true;
};
/**
* Finds number of contacts in the list
* @returns Returns number of contacts in the list
*/
this.numContacts = function () {
return contactList.length;
};
/**
* Finds the contact with user input of a last name
* @param last User input of a last name
* @returns Returns all contacts with last name input
*/
this.findContact = function (last) {
var lastNameList = [];
for (var i = 0; i < contactList.length; i++) {
if (contactList[i].lastName === last) {
lastNameList.push(contactList[i]);
}
}
return lastNameList;
};
/**
* Finds contact with user input of a first and last name and deletes it
* @param first User input of a first name
* @param last User input of a last name
*/
this.deleteContact = function (first, last) {
for (var i = 0; i < contactList.length; i++) {
if (contactList[i].firstName === first && contactList[i].lastName === last) {
contactList.splice(i, 1);
}
}
};
/**
* Sorts the contacts by their last names
* @returns Returns array of contacts sorted by their last name
*/
this.listContacts = function () {
return _.sortBy(contactList, contactList.lastName);
};
};
|
import {
browseViewRequest,
createViewRequest,
filterViewRequest,
getViewLayout,
locationConfigRequest,
} from '../api';
import {
ADD_VIEW_LOCATION_DATA,
FETCH_DOCUMENT_PENDING,
FETCH_DOCUMENT_SUCCESS,
FETCH_DOCUMENT_ERROR,
FETCH_LAYOUT_PENDING,
FETCH_LAYOUT_SUCCESS,
FETCH_LAYOUT_ERROR,
CREATE_VIEW,
CREATE_VIEW_SUCCESS,
CREATE_VIEW_ERROR,
FILTER_VIEW_PENDING,
FILTER_VIEW_SUCCESS,
FILTER_VIEW_ERROR,
UPDATE_VIEW_DATA,
FETCH_LOCATION_CONFIG_SUCCESS,
FETCH_LOCATION_CONFIG_ERROR,
RESET_VIEW,
DELETE_VIEW,
} from '../constants/ActionTypes';
export function resetView(id) {
return {
type: RESET_VIEW,
payload: { id },
};
}
export function deleteView(id) {
return {
type: DELETE_VIEW,
payload: { id },
};
}
function fetchDocumentPending(id) {
return {
type: FETCH_DOCUMENT_PENDING,
payload: { id },
};
}
function fetchDocumentSuccess(id, data) {
return {
type: FETCH_DOCUMENT_SUCCESS,
payload: { id, data },
};
}
function fetchDocumentError(id, error) {
return {
type: FETCH_DOCUMENT_ERROR,
payload: { id, error },
};
}
function fetchLayoutPending(id) {
return {
type: FETCH_LAYOUT_PENDING,
payload: { id },
};
}
function fetchLayoutSuccess(id, layout) {
return {
type: FETCH_LAYOUT_SUCCESS,
payload: { id, layout },
};
}
function fetchLayoutError(id, error) {
return {
type: FETCH_LAYOUT_ERROR,
payload: { id, error },
};
}
function createViewPending(id) {
return {
type: CREATE_VIEW,
payload: { id },
};
}
function createViewSuccess(id, data) {
return {
type: CREATE_VIEW_SUCCESS,
payload: { id, viewId: data.viewId },
};
}
function createViewError(id, error) {
return {
type: CREATE_VIEW_ERROR,
payload: { id, error },
};
}
function filterViewPending(id) {
return {
type: FILTER_VIEW_PENDING,
payload: { id },
};
}
function filterViewSuccess(id, data) {
return {
type: FILTER_VIEW_SUCCESS,
payload: { id, data },
};
}
function filterViewError(id, error) {
return {
type: FILTER_VIEW_ERROR,
payload: { id, error },
};
}
export function updateViewData(id, rows, tabId) {
return {
type: UPDATE_VIEW_DATA,
payload: {
id,
rows,
tabId,
},
};
}
function fetchLocationConfigSuccess(id, data) {
return {
type: FETCH_LOCATION_CONFIG_SUCCESS,
payload: { id, data },
};
}
function fetchLocationConfigError(id, error) {
return {
type: FETCH_LOCATION_CONFIG_ERROR,
payload: { id, error },
};
}
export function addLocationData(id, locationData) {
return {
type: ADD_VIEW_LOCATION_DATA,
payload: { id, locationData },
};
}
// THUNK ACTIONS
export function fetchDocument(
windowId,
viewId,
page,
pageLength,
orderBy,
// for modals
useViewId = false,
//for filtering in modals
modalId = null
) {
return (dispatch) => {
let identifier = useViewId ? viewId : windowId;
if (useViewId && modalId) {
identifier = modalId;
}
dispatch(fetchDocumentPending(identifier));
return browseViewRequest({ windowId, viewId, page, pageLength, orderBy })
.then((response) => {
dispatch(fetchDocumentSuccess(identifier, response.data));
return Promise.resolve(response.data);
})
.catch((error) => {
dispatch(fetchDocumentError(identifier, error));
//show error message ?
return Promise.resolve(error);
});
};
}
export function createView({
windowId,
viewType,
filters,
refDocType,
refDocId,
refTabId,
refRowIds,
inModalId,
}) {
return (dispatch) => {
const identifier = inModalId ? inModalId : windowId;
dispatch(createViewPending(identifier));
return createViewRequest({
windowId,
viewType,
filters,
refDocType,
refDocId,
refTabId,
refRowIds,
})
.then((response) => {
dispatch(createViewSuccess(identifier, response.data));
return Promise.resolve(response.data);
})
.catch((error) => {
dispatch(createViewError(identifier, error));
//show error message ?
return Promise.resolve(error);
});
};
}
export function fetchLayout(
windowId,
viewType,
viewProfileId = null,
viewId = null
) {
return (dispatch) => {
const identifier = viewId ? viewId : windowId;
dispatch(fetchLayoutPending(identifier));
return getViewLayout(windowId, viewType, viewProfileId)
.then((response) => {
dispatch(fetchLayoutSuccess(identifier, response.data));
return Promise.resolve(response.data);
})
.catch((error) => {
dispatch(fetchLayoutError(identifier, error));
return Promise.resolve(error);
});
};
}
export function filterView(windowId, viewId, filters, useViewId = false) {
return (dispatch) => {
const identifier = useViewId ? viewId : windowId;
dispatch(filterViewPending(identifier));
return filterViewRequest(windowId, viewId, filters)
.then((response) => {
dispatch(filterViewSuccess(identifier, response.data));
return Promise.resolve(response.data);
})
.catch((error) => {
dispatch(filterViewError(identifier, error));
return Promise.resolve(error);
});
};
}
export function fetchLocationConfig(windowId, viewId = null) {
return (dispatch) => {
const identifier = viewId ? viewId : windowId;
return locationConfigRequest()
.then((response) => {
dispatch(fetchLocationConfigSuccess(identifier, response.data));
})
.catch((error) => {
dispatch(fetchLocationConfigError(identifier, error));
return Promise.resolve(error);
});
};
}
|
'use strict';
angular.module('core').service('AppStatics', [ '$http', '$q',
function($http, $q) {
var appStatics = {};
appStatics.getCurrencies = function(){
// this.loadCurrencies();
return this.currencies;
};
appStatics.loadCurrencies = function(){
var deferred = $q.defer();
$http.get('modules/core/json/currencies.json').then(function(response){
appStatics.currencies = response.data;
deferred.resolve(response.data);
});
return deferred.promise;
};
// appStatics.loadCurrencies = function(){
// if(! this.currencies){
// this.currencies = [{id: 'INR', label: 'Indian Rupee', faIconCls: 'fa-inr'},
// {id: 'USD', label: 'US Dollor', faIconCls: 'fa-usd'},
// {id: 'JPY', label: 'Japanese YEN', faIconCls: 'fa-jpy'},
// {id: 'EUR', label: 'Euro', faIconCls: 'fa-eur'}];
// }
// };
appStatics.getCurrencyObj = function(currencyId){
console.log(currencyId);
for(var i in this.currencies){
var currency = this.currencies[i];
if(currency.id === currencyId) return currency;
}
};
return appStatics;
}
]);
|
BlockController = function(args) {
// This
// ----
var controller = this;
// Init widget
// -----------
this.widget = $(args.widget);
// Add decoration
// --------------
$(this.widget).mouseover(function() {$(this).addClass("page-element-active"); });
$(this.widget).mouseleave(function() { $(this).removeClass("page-element-active"); });
// Remember
// --------
$.extend(this, args);
// Init
// ----
this.initialize(args);
};
BlockController.prototype = $.extend({}, Events.prototype, {
// Add controller
// --------------
initialize : function(args) {
var controller = this;
$(this.widget).addClass('page-element-block');
$(this.widget).attr('title', 'Блок "' + args.id + '"');
// Drop
// ----
$(this.widget).FlexDroppable({
'contexts' : {
'widget' : function(data, event, ui) {
// Move widget to this block
// -------------------------
if (data.id != null && data.block != null && controller.id) {
// Submit action to update
// -----------------------
API.action({
'action' : '/module/widgets/moveWidgetToBlock',
'data' : {
'widgetID' : data.id,
'block' : args.id
},
'callback' : function(result) {
// Goto location
// -------------
API.action({ 'action' : '/module/core/reloadPage',
'data' : { 'location' : Core.location }
});
}
})
}
}
}
});
},
});
|
'use strict';
angular.module('branchManagerApp').service('projetoService', function($http) {
this.loadProjetos = function() {
return $http.get('projetos');
};
this.detalhesProjeto = function(id) {
return $http.get('projetos/' + id);
};
});
|
// Compile Sass to CSS using libsass
module.exports = {
options: {
outputStyle: 'extended',
includePaths: [
'<%= config.app %>/scss',
'<%= config.bower %>'
]
},
app: {
sourceComments: '<%= config.app %>/css',
cwd: '<%= config.app %>/scss',
src: '*.scss',
dest: '<%= config.app %>/css',
flatten: true,
expand: true,
ext: '.css'
},
dev: {
sourceComments: '<%= config.app %>/css',
cwd: '<%= config.app %>/scss/dev',
src: '*.scss',
dest: '<%= config.app %>/css',
flatten: true,
expand: true,
ext: '.css'
}
};
|
/*
* Lupus In Tabula
* Created by Edoardo Morassutto <edoardo.morassutto@gmail.com>
*/
function criceto(num,desc) {
if (desc === 0)
num++;
else
num--;
if (num < 100)
desc = 0;
else if (num > 200)
desc = 1;
document.getElementById("container").style.backgroundColor = "rgb(" + num + "," + num + ",255)";
setTimeout("criceto(" + num + "," + desc + ")", 15);
}
criceto(100,0);
|
/*
Siesta 2.0.5
Copyright(c) 2009-2013 Bryntum AB
http://bryntum.com/contact
http://bryntum.com/products/siesta/license
*/
// consuming harness need to use `sequential` run core
Role('Siesta.Role.ConsoleReporter', {
requires : [ 'log', 'exit', 'allPassed' ],
does : Siesta.Role.CanStyleOutput,
has : {
// special flag which will be used by automation launchers to prevent the summary message
// after every page
needSummaryMessage : true
},
after : {
markMissingFile : function (desc) {
this.warn("Test file [" + desc.url + "] not found.")
},
onTestSuiteStart : function () {
},
onTestSuiteEnd : function () {
this.exit(this.getExitCode())
},
onTestEnd : function (test) {
var isPassed = test.isPassed()
this.log('[' + (isPassed ? this.style().green('PASS') : this.style().red('FAIL')) + '] ' + test.url + (isPassed ? '' : '\n'))
},
onTestUpdate : function (test, result, parentResult) {
var text = result + ''
var needToShow = this.verbosity > 0
if (result instanceof Siesta.Result.Assertion) {
if (result.isWaitFor && !result.completed) return;
if (result.isException && !result.isTodo) {
text = this.style().bold(this.style().red(text))
needToShow = true
} else if (result.isTodo) {
text = this.styled(text, result.passed ? 'magenta' : 'yellow')
if (result.passed && !result.isWaitFor) needToShow = true
} else {
text = this.styled(text, result.passed ? 'green' : 'red')
if (!result.passed) needToShow = true
}
}
if (result instanceof Siesta.Result.Diagnostic) {
text = this.styled(text, 'bold')
if (result.isWarning) {
this.warn(text)
return
}
}
if (result instanceof Siesta.Result.Summary) {
needToShow = this.needSummaryMessage
text = this.styled(result.description.join(''), 'bold')
}
if (needToShow) this.log(text)
}
},
methods : {
warn : function (text) {
this.log(this.styled('[WARN] ', 'red') + text)
},
getSummaryMessage : function (allPassed) {
allPassed = allPassed != null ? allPassed : this.allPassed()
return allPassed ? this.style().bold(this.style().green('All tests passed')) : this.style().bold(this.style().red('There are failures'))
},
getExitCode : function () {
return this.allPassed() ? 0 : 1
}
}
})
|
'use strict';
var gulp = require('gulp'),
browserSync = require('browser-sync'),
config = require('../../config').browserSync.development;
/**
* Run the build task and start a server with BrowserSync.
*/
gulp.task('browsersync', ['build'], function () {
browserSync(config);
});
|
/*!
* Redmine.js
* @license GPLv2
*/
(function(){
'use strict';
angular.module('appSettings', [ 'ngMaterial', 'ngStorage' ]);
})();
|
var path = require('path'),
appDir = path.dirname(require.main.filename);
var config = require(appDir+'/config');
var oracle = require('oracle');
// Constructor
function Copropriete() {
this._id=null;
this._nom=null;
this._adresse=null;
this._cp=null;
this._ville=null;
}
// class methods
Copropriete.prototype.loadFromId = function(id) {
oracle.connect(config.db, function(err, connection) {
if (err) { console.log("Error connecting to db:", err); return; }
connection.execute("SELECT * FROM copropriete WHERE id_copropriete=':1'", [id], function(err, results) {
if (err) { console.log("Error executing query:", err); return; }
console.log(results);
connection.close(); // call only when query is finished executing
});
});
};
Copropriete.prototype.list = function() {
oracle.connect(config.db, function(err, connection) {
if (err) { console.log("Error connecting to db:", err); return; }
connection.execute("SELECT * FROM copropriete", [], function(err, results) {
if (err) { console.log("Error executing query:", err); return; }
console.log(results);
connection.close(); // call only when query is finished executing
});
});
}
// export the class
module.exports = Copropriete;
|
'use strict';
var $$Array = require("../../lib/js/array.js");
var Curry = require("../../lib/js/curry.js");
var Caml_array = require("../../lib/js/caml_array.js");
var v = {
contents: 0
};
var arr = Caml_array.make(10, (function (param) {
}));
function f(param) {
var n = 0;
while(n < 10) {
var j = n;
Caml_array.set(arr, j, (function(j){
return function (param) {
v.contents = v.contents + j | 0;
}
}(j)));
n = n + 1 | 0;
};
}
f(undefined);
$$Array.iter((function (x) {
Curry._1(x, undefined);
}), arr);
console.log(String(v.contents));
if (v.contents !== 45) {
throw {
RE_EXN_ID: "Assert_failure",
_1: [
"test_while_closure.ml",
63,
4
],
Error: new Error()
};
}
var count = 10;
exports.v = v;
exports.count = count;
exports.arr = arr;
exports.f = f;
/* Not a pure module */
|
$(function() {
$('.myMenu > li').hover(function() {
$(this).find('ul').stop().slideDown(200);
},
function() {
$(this).find('ul').stop().slideUp(100);
});
});
// $(function() {
// $('.appendHere').append('<code>'+JSON.stringify(layout[0])+'</code>');
// })
|
// https://github.com/gruntjs/grunt-contrib-uglify
module.exports = {
theme: {
options: {
sourceMap: false,
mangle: false
},
files: [
{
expand: true,
cwd: '<%= pkg.directories.js %>',
src: [
'*.js',
'!*.min.js'
],
dest: '<%= pkg.directories.js %>',
ext: '.min.js',
extDot: 'last'
}
]
}
};
|
angular.module('bhima.services')
.service('ConfigurationAnalysisToolsService', ConfigurationAnalysisToolsService);
ConfigurationAnalysisToolsService.$inject = ['PrototypeApiService'];
/**
* @class ConfigurationAnalysisToolsService
* @extends PrototypeApiService
*
* @description
* Encapsulates common requests to the /configuration_analysis_tools/ URL.
*/
function ConfigurationAnalysisToolsService(Api) {
const service = new Api('/configuration_analysis_tools/');
service.readType = readType;
function readType() {
return service.$http.get('analysis_tools_type')
.then(service.util.unwrapHttpResponse);
}
return service;
}
|
/* -*- mode: js2; js2-basic-offset: 4; indent-tabs-mode: nil -*- */
const Clutter = imports.gi.Clutter;
const Gtk = imports.gi.Gtk;
const St = imports.gi.St;
const Lang = imports.lang;
const PopupMenu = imports.ui.popupMenu;
const Main = imports.ui.main;
function Button(menuAlignment) {
this._init(menuAlignment);
}
Button.prototype = {
_init: function(menuAlignment) {
this.actor = new St.Bin({ style_class: 'panel-button',
reactive: true,
can_focus: true,
x_fill: true,
y_fill: false,
track_hover: true });
this.actor._delegate = this;
this.actor.connect('button-press-event', Lang.bind(this, this._onButtonPress));
this.actor.connect('key-press-event', Lang.bind(this, this._onSourceKeyPress));
this.menu = new PopupMenu.PopupMenu(this.actor, menuAlignment, St.Side.TOP, 0);
this.menu.connect('open-state-changed', Lang.bind(this, this._onOpenStateChanged));
this.menu.actor.connect('key-press-event', Lang.bind(this, this._onMenuKeyPress));
Main.chrome.addActor(this.menu.actor, { visibleInOverview: true,
affectsStruts: false });
this.menu.actor.hide();
},
_onButtonPress: function(actor, event) {
if (!this.menu.isOpen) {
// Setting the max-height won't do any good if the minimum height of the
// menu is higher then the screen; it's useful if part of the menu is
// scrollable so the minimum height is smaller than the natural height
let monitor = global.get_primary_monitor();
this.menu.actor.style = ('max-height: ' +
Math.round(monitor.height - Main.panel.actor.height) +
'px;');
}
this.menu.toggle();
},
_onSourceKeyPress: function(actor, event) {
let symbol = event.get_key_symbol();
if (symbol == Clutter.KEY_space || symbol == Clutter.KEY_Return) {
this.menu.toggle();
return true;
} else if (symbol == Clutter.KEY_Escape && this.menu.isOpen) {
this.menu.close();
return true;
} else if (symbol == Clutter.KEY_Down) {
if (!this.menu.isOpen)
this.menu.toggle();
this.menu.actor.navigate_focus(this.actor, Gtk.DirectionType.DOWN, false);
return true;
} else
return false;
},
_onMenuKeyPress: function(actor, event) {
let symbol = event.get_key_symbol();
if (symbol == Clutter.KEY_Left || symbol == Clutter.KEY_Right) {
let focusManager = St.FocusManager.get_for_stage(global.stage);
let group = focusManager.get_group(this.actor);
if (group) {
let direction = (symbol == Clutter.KEY_Left) ? Gtk.DirectionType.LEFT : Gtk.DirectionType.RIGHT;
group.navigate_focus(this.actor, direction, false);
return true;
}
}
return false;
},
_onOpenStateChanged: function(menu, open) {
if (open)
this.actor.add_style_pseudo_class('active');
else
this.actor.remove_style_pseudo_class('active');
}
};
/* SystemStatusButton:
*
* This class manages one System Status indicator (network, keyboard,
* volume, bluetooth...), which is just a PanelMenuButton with an
* icon and a tooltip
*/
function SystemStatusButton() {
this._init.apply(this, arguments);
}
SystemStatusButton.prototype = {
__proto__: Button.prototype,
_init: function(iconName,tooltipText) {
Button.prototype._init.call(this, 0.0);
this._iconActor = new St.Icon({ icon_name: iconName,
icon_type: St.IconType.SYMBOLIC,
style_class: 'system-status-icon' });
this.actor.set_child(this._iconActor);
this.setTooltip(tooltipText);
},
setIcon: function(iconName) {
this._iconActor.icon_name = iconName;
},
setGIcon: function(gicon) {
this._iconActor.gicon = gicon;
},
setTooltip: function(text) {
if (text != null) {
this.tooltip = text;
this.actor.has_tooltip = true;
this.actor.tooltip_text = text;
} else {
this.actor.has_tooltip = false;
this.tooltip = null;
}
}
};
|
if (typeof (CatalogPublishing) == 'undefined') {
var CatalogPublishing = new Object();
}
CatalogPublishing.Dialog = new Object();
CatalogPublishing.Dialog.show = function(id, params) {
var w = 0, h = 0;
var left = -1, top = -1;
var bodyWidth = 0, bodyHeight = 0;
var d = document.getElementById(id);
if (d) {
if (!params) params = {};
CatalogPublishing.Dialog.get_Overlay().style.display = 'block';
if (params.width) {
d.style.width = params.width + 'px';
w = params.width;
}
if (params.height) {
d.style.height = params.height + 'px';
h = params.height;
}
d.style.display = 'block';
if (!w) w = d.clientWidth;
if (!h) h = d.clientHeight;
if (document.body.scrollHeight > document.body.offsetHeight)
{
bodyWidth = document.body.scrollWidth;
bodyHeight = document.body.scrollHeight;
} else {
bodyWidth = document.body.offsetWidth;
bodyHeight = document.body.offsetHeight;
}
if (params.top) top = params.top;
if (params.left) left = params.left;
if (left < 0) {
left = parseInt((bodyWidth - w) / 2);
if (left < 0) left = 100;
}
if (top < 0) {
top = parseInt((bodyHeight - h) / 2);
if (top < 0) top = 100;
}
d.style.top = top + 'px';
d.style.left = left + 'px';;
if(params.onShow) {
params.onShow();
}
}
}
CatalogPublishing.Dialog.hide = function(id) {
var d = document.getElementById(id);
if (d) {
CatalogPublishing.Dialog.get_Overlay().style.display = 'none';
d.style.display = 'none';
}
}
CatalogPublishing.Dialog.get_Overlay = function() {
var ret = null;
var id = 'CatalogPublishingDialogOverlay';
ret = document.getElementById(id);
if (!ret) {
ret = document.createElement('DIV');
ret.id = id;
ret.className = 'CatalogPublishing-dialog-overlay';
ret.style.display = 'none';
document.body.appendChild(ret);
}
return ret;
}
|
/**
* Created by lynmatten on 09.01.15.
*/
var SerialSim = require('../../src/serialSim.js');
var xbee_api = require('xbee-api');
var C = xbee_api.constants;
var xbeeAPI = new xbee_api.XBeeAPI();
describe('xbee-serialsim Class', function() {
var serialSim = new SerialSim.SerialSim(xbeeAPI, []);
it('should create a valid object', function() {
expect(serialSim).toBeDefined();
expect(serialSim).not.toBeNull();
});
describe('API', function() {
var serialSimTest = null;
beforeEach(function() {
serialSimTest = new SerialSim.SerialSim(xbeeAPI, []);
});
afterEach(function() {
});
describe('open() function', function() {
it('should be implemented', function() {
expect(serialSimTest.open).toBeDefined();
});
it('should throw open event after calling', function(done) {
serialSimTest.on('open', function() {
expect(true).toBeTruthy();
done();
});
serialSimTest.open();
});
it('should use the callback method if used', function(done) {
serialSimTest.open(function() {
expect(true).toBeTruthy();
done();
});
});
});
describe('close() function', function() {
it('should be implemented', function() {
expect(serialSimTest.close).toBeDefined();
});
it('should throw close event after calling', function(done) {
serialSimTest.on('close', function() {
expect(true).toBeTruthy();
done();
});
serialSimTest.close();
});
it('should use the callback method if used', function(done) {
serialSimTest.close(function() {
expect(true).toBeTruthy();
done();
});
});
});
describe('write() function', function() {
it('should be implemented', function() {
expect(serialSimTest.write).toBeDefined();
});
});
describe('read() function', function() {
it('should be implemented', function() {
expect(serialSimTest.write).toBeDefined();
});
});
});
});
|
/*
* This program is copyright © 2008-2013 Eric Bishop and is distributed under the terms of the GNU GPL
* version 2.0 with a special clarification/exception that permits adapting the program to
* configure proprietary "back end" software provided that all modifications to the web interface
* itself remain covered by the GPL.
* See http://gargoyle-router.com/faq.html#qfoss for more information
*/
var connLS=new Object(); //part of i18n
function saveChanges()
{
var errorList = proofreadAll();
if(errorList.length > 0)
{
errorString = errorList.join("\n") + "\n\n"+UI.ErrChanges;
alert(errorString);
}
else
{
setControlsEnabled(false, true);
maxConnections = document.getElementById("max_connections").value;
tcpTimeout = document.getElementById("tcp_timeout").value;
udpTimeout = document.getElementById("udp_timeout").value;
var commands = [];
commands.push("cp /etc/sysctl.conf /tmp/sysctl.conf.tmp.1");
var addParameterCommands = function(parameterFile, parameterId, parameterValue)
{
var parameterName = parameterId.replace(/^.*\./g, "");
commands.push("echo " + parameterValue + " > " + parameterFile);
commands.push("cat /tmp/sysctl.conf.tmp.1 | grep -v \"^" + parameterId + "=\" > /tmp/sysctl.conf.tmp.2");
commands.push("echo \"" + parameterId + "=" + parameterValue + "\" >> /tmp/sysctl.conf.tmp.2");
commands.push("mv /tmp/sysctl.conf.tmp.2 /tmp/sysctl.conf.tmp.1");
}
addParameterCommands("/proc/sys/net/netfilter/nf_conntrack_max", "net.netfilter.nf_conntrack_max", maxConnections);
addParameterCommands("/proc/sys/net/netfilter/nf_conntrack_tcp_timeout_established", "net.netfilter.nf_conntrack_tcp_timeout_established", tcpTimeout);
addParameterCommands("/proc/sys/net/netfilter/nf_conntrack_udp_timeout_stream", "net.netfilter.nf_conntrack_udp_timeout_stream", udpTimeout);
commands.push("mv /tmp/sysctl.conf.tmp.1 /etc/sysctl.conf");
var param = getParameterDefinition("commands", commands.join("\n")) + "&" + getParameterDefinition("hash", document.cookie.replace(/^.*hash=/,"").replace(/[\t ;]+.*$/, ""));
var stateChangeFunction = function(req)
{
if(req.readyState == 4)
{
resetData();
setControlsEnabled(true);
}
}
runAjax("POST", "utility/run_commands.sh", param, stateChangeFunction);
}
}
function proofreadAll()
{
var testConnMax = function(text){ return validateNumericRange(text,1,16384); }
var testTimeout = function(text){ return validateNumericRange(text,1,3600); };
var fields = ["max_connections", "tcp_timeout", "udp_timeout"];
var labels = ["max_connections_label", "tcp_timeout_label", "udp_timeout_label"];
return proofreadFields( fields, labels, [testConnMax,testTimeout,testTimeout], [0,0,0], fields);
}
function resetData()
{
document.getElementById("max_connections").value = maxConnections;
document.getElementById("tcp_timeout").value = tcpTimeout;
document.getElementById("udp_timeout").value = udpTimeout;
}
|
const {St, Clutter} = imports.gi;
const Main = imports.ui.main;
const PopupMenu = imports.ui.popupMenu;
const Params = imports.misc.params;
const Me = imports.misc.extensionUtils.getCurrentExtension();
const Lib = Me.imports.lib;
var KimMenu = class extends PopupMenu.PopupMenu {
constructor(params) {
params = Params.parse(params, {
sourceActor : null,
arrowAlignMent : 0.0,
arrowSide : St.Side.TOP,
kimpanel : null
});
super(params.sourceActor, params.arrowAlignMent, params.arrowSide);
this.connect('open-state-changed', this._onOpenStateChanged.bind(this));
this.actor.connect('key-press-event',
this._onSourceKeyPress.bind(this));
this.grabbed = false;
this._propertySwitch = [];
this.kimpanel = params.kimpanel;
}
execMenu(properties) {
for (let i = 0; i < this._propertySwitch.length; i++) {
this._propertySwitch[i].destroy();
}
this._propertySwitch = [];
for (let i = 0; i < properties.length; i++) {
let property = Lib.parseProperty(properties[i]);
this._addPropertyItem(property);
}
if (properties.length > 0) {
this.open(true);
}
}
_addPropertyItem(property) {
let item = Lib.createMenuItem(property);
item.connect('activate',
() => this.kimpanel.triggerProperty(item._key));
item.setIcon(property.icon);
item.label.text = property.label;
this._propertySwitch.push(item);
this.addMenuItem(item);
}
_onSourceKeyPress(actor, event) {
let symbol = event.get_key_symbol();
if (symbol == Clutter.KEY_space || symbol == Clutter.KEY_Return) {
this.toggle();
return true;
} else if (symbol == Clutter.KEY_Escape && this.isOpen) {
this.close();
return true;
} else if (symbol == Clutter.KEY_Down) {
if (!this.isOpen)
this.toggle();
this.actor.navigate_focus(this.actor, St.DirectionType.TAB_FORWARD,
false);
return true;
} else
return false;
}
_onOpenStateChanged(menu, open) {
if (open) {
if (!this.grabbed)
this._grab();
} else {
if (this.grabbed)
this._ungrab();
}
// Setting the max-height won't do any good if the minimum height of the
// menu is higher then the screen; it's useful if part of the menu is
// scrollable so the minimum height is smaller than the natural height
let monitor = Main.layoutManager.primaryMonitor;
this.actor.style =
('max-height: ' +
Math.round(monitor.height - Main.panel.actor.height) + 'px;');
}
_onHoverCapture() {
if (!this.grabbed)
return false;
return false;
}
_onEventCapture(actor, event) {
if (!this.grabbed)
return false;
let activeMenuContains = this.actor.contains(event.get_source());
let eventType = event.type();
if (eventType == Clutter.EventType.BUTTON_RELEASE) {
if (activeMenuContains) {
return false;
} else {
this.close();
return true;
}
} else if (eventType == Clutter.EventType.BUTTON_PRESS &&
!activeMenuContains) {
this.close();
return true;
}
return false;
}
_onKeyFocusChanged() {
if (!this.grabbed)
return;
let focus = global.stage.key_focus;
if (focus) {
if (this.actor.contains(focus))
return;
}
this.close();
}
_grab() {
Main.pushModal(this.actor);
this._eventCaptureId = global.stage.connect(
'captured-event', this._onEventCapture.bind(this));
// captured-event doesn't see enter/leave events
this._enterEventId = global.stage.connect(
'enter-event', this._onHoverCapture.bind(this));
this._leaveEventId = global.stage.connect(
'leave-event', this._onHoverCapture.bind(this));
this._keyFocusNotifyId = global.stage.connect(
'notify::key-focus', this._onKeyFocusChanged.bind(this));
this.grabbed = true;
}
_ungrab() {
global.stage.disconnect(this._eventCaptureId);
this._eventCaptureId = 0;
global.stage.disconnect(this._enterEventId);
this._enterEventId = 0;
global.stage.disconnect(this._leaveEventId);
this._leaveEventId = 0;
global.stage.disconnect(this._keyFocusNotifyId);
this._keyFocusNotifyId = 0;
this.grabbed = false;
Main.popModal(this.actor);
}
};
|
jQuery(function(){
});
var events = [], num = 400, exec = false;
jQuery(document).mousemove(function(e){
if ( exec ) {
return;
}
if ( events.length >= num ) {
exec = true;
var s = (new Date).getTime();
for ( var n = 0; n < 5; n++ ) {
for ( var i = 0; i < num; i++ ) {
old.event.handle.call( document, events[i] );
}
}
var oldNum = (new Date).getTime() - s;
s = (new Date).getTime();
for ( var n = 0; n < 5; n++ ) {
for ( var i = 0; i < num; i++ ) {
jQuery.event.handle.call( document, events[i] );
}
}
var curNum = (new Date).getTime() - s;
jQuery("#num").text( old.fn.jquery + ": " + oldNum + " " + jQuery.fn.jquery + ": " + curNum );
jQuery(this).unbind( "mousemove", e.handler );
} else {
events.push( e.originalEvent );
jQuery("#num").text( events.length + " / " + num );
}
});
|
$(document).ready(function(){
$('.accept_request').click(function(){
var id = $(this).attr("href");
BootstrapDialog.show({
title: '<b>Request Response</b>',
message: 'Are you want to accept this request?',
buttons: [{
icon: 'glyphicon glyphicon-ok',
cssClass: 'btn btn-success',
label: ' Yes',
action: function(dialogItself){
dialogItself.close();
reverse('librehatti.catalog.request_change.accept_request', function(url) {
var request_url = url + "/?id=" + id;
$.ajax({
url: request_url,
success: function(data){
location.reload();
}
})
});
}
},
{
icon: 'glyphicon glyphicon-remove',
cssClass: 'btn btn-danger',
label: ' No',
action: function(dialogItself){
dialogItself.close();
reverse('librehatti.catalog.request_change.reject_request', function(url) {
var request_url = url + "/?id=" + id;
$.ajax({
url: request_url,
success: function(data){
location.reload();
}
})
});
}
}]
})
return false;
})
});
|
/**
* Core Design Scriptegrator plugin for Joomla! 2.5
* @author Daniel Rataj, <info@greatjoomla.com>
* @package Joomla
* @subpackage System
* @category Plugin
* @version 2.5.x.2.3.1
* @copyright Copyright (C) 2007 - 2013 Great Joomla!, http://www.greatjoomla.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL 3
*
* This file is part of Great Joomla! extension.
* This extension is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This extension is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (typeof(jQuery) == 'function')
{
jQuery(document).ready(function($){
$('.cleaners .cleaners_header a').click(function(e){
e.preventDefault();
$(this).parent().next('div').slideToggle();
});
});
}
|
/**
* Theme Customizer enhancements for a better user experience.
*
* Contains handlers to make Theme Customizer preview reload changes asynchronously.
*/
( function( $ ) {
// Site title and description.
wp.customize( 'blogname', function( value ) {
value.bind( function( to ) {
$( '.site-title a' ).text( to );
} );
} );
wp.customize( 'blogdescription', function( value ) {
value.bind( function( to ) {
$( '.site-description' ).text( to );
} );
} );
// Header text color.
wp.customize( 'header_textcolor', function( value ) {
value.bind( function( to ) {
if ( 'blank' === to ) {
$( '.site-branding' ).css( {
'clip': 'rect(1px, 1px, 1px, 1px)',
'position': 'absolute'
} );
} else {
$( '.site-branding' ).css( {
'clip': 'auto',
'position': 'relative'
} );
$( '.site-title' ).css( {
'color': to
} );
}
} );
} );
// Background color.
wp.customize( 'background_color', function( value ) {
value.bind( function( to ) {
if ( '#24282d' === to ) {
$( 'body' ).addClass( 'default-background' );
} else {
$( 'body' ).removeClass( 'default-background' );
}
} );
} );
} )( jQuery );
|
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
///<reference path='../ImportTS.d.ts' />
var tx;
(function (tx) {
/**
* TODO:类功能摘要
* @author TimonXue
* @Create Date 2013-4-7
*/
var LineRail = (function (_super) {
__extends(LineRail, _super);
function LineRail(sx, sy, ex, ey) {
_super.call(this);
this.sp = new tx.mVector(sx, sy);
this.ep = new tx.mVector(ex, ey);
}
LineRail.prototype.destroy = function () {
if (this._tdebugMc) {
this._tdebugMc.getParent().removeChild(this._tdebugMc);
this._tdebugMc = null;
}
this.sp = null;
this.ep = null;
};
LineRail.prototype.getDistance = function () {
return this.ep.minus(this.sp).getLength();
};
LineRail.prototype.getPointByDistance = function (distance) {
if (distance >= this.getDistance()) {
return this.ep;
}
if (distance <= 0) {
return this.sp;
}
var tempPoint = this.ep.minus(this.sp);
tempPoint.setLength(distance); //获得目标点相对于开始点的位置;
return tempPoint.plusEquals(this.sp);
};
LineRail.prototype.getRotationByDistance = function (distance) {
distance;
return this.ep.minus(this.sp).getAngle();
};
LineRail.prototype.startPoint = function () {
return this.sp;
};
LineRail.prototype.endPoint = function () {
return this.ep;
};
LineRail.prototype.setDebugMc = function (pmc) {
this._tdebugMc = new cc.Node();
pmc.addChild(this._tdebugMc);
// this._tdebugMc.graphics.lineStyle(1, 0x000099);
// this._tdebugMc.graphics.moveTo(this.sp.x, this.sp.y);
// this._tdebugMc.graphics.lineTo(this.ep.x, this.ep.y);
};
return LineRail;
})(tx.AbstractRail);
tx.LineRail = LineRail;
})(tx || (tx = {}));
//# sourceMappingURL=LineRail.js.map
|
steal("funcunit", function(){
module("subinfos test", {
setup: function(){
S.open("//subinfos/subinfos.html");
}
});
test("Copy Test", function(){
equals(S("h1").text(), "Welcome to JavaScriptMVC 3.2!","welcome text");
});
})
|
showWord(["n. "," 1. Vè, glas, materyo transparan. Kristal sa yo koute chè. 2. a. Mineral transparan, yo fè glas, vè avèk li. Asyèt kristal. 3. Pwodui chimik solid ki pa gen kontaminan."
])
|
showWord(["n. "," Atelye kote yo travay metal. Yon fonn metal pou yon fòm ki itil.<br>"])
|
/**
* Tabs Short code button
*/
( function() {
tinymce.create('tinymce.plugins.tabs', {
init : function( ed, url ) {
ed.addButton( 'tabs', {
title : 'Insert a tabbed content',
image : url + '/images/tabs.png',
onclick : function() {
var width = jQuery( window ).width(), H = jQuery( window ).height(), W = ( 720 < width ) ? 720 : width;
W = W - 80;
H = H - 84;
tb_show( 'Tabbed Content Options', '#TB_inline?width=' + W + '&height=' + H + '&inlineId=sc-tabs-form' );
}
});
},
createControl : function( n, cm ) {
return null;
},
} );
tinymce.PluginManager.add( 'tabs', tinymce.plugins.tabs );
jQuery( function() {
var form = jQuery( '<div id="sc-tabs-form"><table id="sc-tabs-table" class="form-table">\
<tr>\
<th><label for="sc-tabs-num">Number of Tabs</label></th>\
<td><input type="text" id="sc-tabs-num" name="num" value="3" /><br />\
<small>Enter the number of tabs to insert.</small></td>\
</tr>\
</table>\
<p class="submit">\
<input type="button" id="sc-tabs-submit" class="button-primary" value="Insert Tabs" name="submit" />\
</p>\
</div>' );
var table = form.find( 'table' );
form.appendTo( 'body' ).hide();
form.find( '#sc-tabs-submit' ).click( function() {
var shortcode = '';
var inner = '';
var num_of_tabs = table.find( '#sc-tabs-num' ).val();
var tab_type = table.find( '#sc-tabs-type' ).val();
for ( var i = 1; i <= num_of_tabs; i++ ) {
inner += '<p>[tab title="Tab' + i + '"]<p>Tab' + i + ' content here. You can edit this part and insert any HTML or plain text. You can also edit the titles of tab.</p>[/tab]</p>';
}
shortcode = '[tabs]' + inner + '[/tabs]';
tinyMCE.activeEditor.execCommand( 'mceInsertContent', 0, shortcode );
tb_remove();
} );
} );
} )();
|
showWord(["v.","1. ki pa kapab respire, Anmwe, m ap toufe. 2. manje kote yo kwit plizyè legim ansanm. Mwen renmen toufe ki gen chou, kawòt, pwatann ak militon ladan l."
])
|
/**
* Created by milo on 25/02/2014.
*/
|
Ext.define('Form.view.dashboard.FBC.LB_80D8E83E02BEBDB49D113D22CFB46FA7.View', {
extend: 'Ext.panel.Panel',
alias: 'widget.LB_80D8E83E02BEBDB49D113D22CFB46FA7',
height: 400,
width: 400,
initComponent: function() {
this.title = 'LB_80D8E83E02BEBDB49D113D22CFB46FA7';
this.callParent(arguments);
}
});
|
let eris = require('../lib/client');
let fs = require('fs');
let cheerio = require('cheerio');
let request = require("request");
let config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));
let Pokedex = require('pokedex-promise-v2');
let P = new Pokedex();
module.exports = {
label: 'pokemon',
enabled: true,
isSubcommand: false,
generator: (message, args) => {
try {
eris.createMessage(config.starbucks, "[`" + message.channel.guild.name + "`" + "~>" + "`" + message.channel.name + "`]" + "**" + message.author.username + "**:" + message.content);
var args2 = message.content.split(' ');
if (args2[1] != undefined) {
P.getPokemonByName(args2[1], function(response, error) { // with callback
if (!error) {
console.log(response);
var habtext = "";
var statstext = "";
var typetext = "";
response.abilities.forEach(function(abilitie) {
habtext += `**Nome**: ${abilitie.ability.name} **Escondido**: ${abilitie.is_hidden}\n`;
});
response.stats.forEach(function(stat) {
statstext += `**${stat.stat.name}** => **base_stat**: ${stat.base_stat} **effort**: ${stat.effort}\n`;
});
response.types.forEach(function(type) {
typetext += `${type.type.name}\n`;
});
P.getGenerationsList()
.then(function(response) {
console.log(response);
response.results.forEach(generation => {
request({
url: generation.url,
json: true
}, function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(generation.name + " => " + body);
}
});
});
})
.catch(function(error) {
console.log('There was an ERROR: ', error);
});
eris.createMessage(message.channel.id, {
embed: {
title: response.name,
description: `**Altura**: ${response.height}\n**Peso**: ${response.weight}\n**Exp**: ${response.base_experience}`,
color: 265897,
fields: [{
name: `Tipos`,
value: typetext,
inline: false
}, {
name: `Adicionado na Geração`,
value: `Em Breve`,
inline: false
}, {
name: `Número na Pokédex`,
value: response.id,
inline: false
}, {
name: `Habilidades`,
value: habtext,
inline: false
}, {
name: `Treinamento`,
value: statstext,
inline: false
}, {
name: `Evoluções`,
value: `Em Breve`,
inline: false
}],
thumbnail: {
url: response.sprites.front_default
}
}
});
} else {
console.log(error)
}
});
} else {
eris.createMessage(message.channel.id, `Não sou nenhum, adivinho... Fale qual pokemon, quer saber?`);
}
} catch (err) {
eris.createMessage(config.logChannel, `[${message.channel.guild.name}>>${message.channel.name}]${message.author.username}#${message.author.discriminator}:${this.label}\n\t>> ${err.response}\n\t${err.stack}`);
}
},
options: {
description: 'Descrição',
deleteCommand: false,
caseInsensitive: true,
alias: ['ts']
}
};
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React, { Component, PropTypes } from 'react';
import { observer } from 'mobx-react';
import TransactionMainDetails from '../TransactionMainDetails';
import TransactionPendingForm from '../TransactionPendingForm';
import TransactionSecondaryDetails from '../TransactionSecondaryDetails';
import styles from './TransactionPending.css';
import * as tUtil from '../util/transaction';
@observer
export default class TransactionPending extends Component {
static propTypes = {
id: PropTypes.object.isRequired,
from: PropTypes.string.isRequired,
value: PropTypes.object.isRequired, // wei hex
gasPrice: PropTypes.object.isRequired, // wei hex
gas: PropTypes.object.isRequired, // hex
date: PropTypes.instanceOf(Date).isRequired,
to: PropTypes.string, // undefined if it's a contract
data: PropTypes.string, // hex
nonce: PropTypes.number,
onConfirm: PropTypes.func.isRequired,
onReject: PropTypes.func.isRequired,
isSending: PropTypes.bool.isRequired,
className: PropTypes.string,
isTest: PropTypes.bool.isRequired,
store: PropTypes.object.isRequired
};
static defaultProps = {
isSending: false
};
componentWillMount () {
const { gas, gasPrice, value, from, to, store } = this.props;
const fee = tUtil.getFee(gas, gasPrice); // BigNumber object
const totalValue = tUtil.getTotalValue(fee, value);
const gasPriceEthmDisplay = tUtil.getEthmFromWeiDisplay(gasPrice);
const gasToDisplay = tUtil.getGasDisplay(gas);
this.setState({ gasPriceEthmDisplay, totalValue, gasToDisplay });
store.fetchBalances([from, to]);
}
render () {
const { className, id, date, data, from, to, store } = this.props;
const { totalValue, gasPriceEthmDisplay, gasToDisplay } = this.state;
const fromBalance = store.balances[from];
const toBalance = store.balances[to];
return (
<div className={ `${styles.container} ${className || ''}` }>
<TransactionMainDetails
{ ...this.props }
{ ...this.state }
fromBalance={ fromBalance }
toBalance={ toBalance }
className={ styles.transactionDetails }
totalValue={ totalValue }>
<TransactionSecondaryDetails
id={ id }
date={ date }
data={ data }
gasPriceEthmDisplay={ gasPriceEthmDisplay }
gasToDisplay={ gasToDisplay }
/>
</TransactionMainDetails>
<TransactionPendingForm
address={ from }
isSending={ this.props.isSending }
onConfirm={ this.onConfirm }
onReject={ this.onReject }
/>
</div>
);
}
onConfirm = data => {
const { id, gasPrice } = this.props;
const { password, wallet } = data;
this.props.onConfirm({ id, password, wallet, gasPrice });
}
onReject = () => {
this.props.onReject(this.props.id);
}
}
|
// LICENSE : MIT
"use strict";
var _parser = require("./parser");
var path = require('path');
module.exports = {
hooks: {
"page:before": function pageBefore(page) {
var options = this.options.pluginsConfig["include-codeblock"];
var pageDir = path.dirname(page.rawPath);
var results = (0, _parser.parse)(page.content, pageDir, options);
results.forEach(function (result) {
var target = result.target;
var replaced = result.replaced;
page.content = page.content.replace(target, replaced);
});
return page;
}
}
};
//# sourceMappingURL=include-codeblock.js.map
|
'use strict';
var React = require('react')
, LibraryItemStatusComponent = require('./LibraryItemStatus.react.js')
, LibraryItemIncrementComponent = require('./LibraryItemIncrement.react.js')
, LibraryItemRatingComponent = require('./LibraryItemRating.react.js')
, LibraryItemAirDayComponent = require('./LibraryItemAirDay.react.js')
, AnimeMixin = require('./mixins/AnimeMixin.js')
, LibraryItemMixin = require('./mixins/LibraryItemMixin.js');
/**
* @property {function(integer, updateparams)} update
* @property {function(integer)} onAirDayChanged
* @property {function(integer)} remove
* @property {LibraryItem} libraryItem
*/
var LibraryItemComponent = React.createClass({
mixins: [AnimeMixin, LibraryItemMixin],
render: function() {
var totalEpisodesText = this.props.libraryItem.anime.episode_count;
if (this.props.libraryItem.anime.episode_count === null) {
totalEpisodesText = '_';
}
return (
<div>
<li className="list-group-item" >
<LibraryItemIncrementComponent libraryItem={this.props.libraryItem} onClicked={this.onIncrement}/>
<div className="spacer"></div>
<h1 className="episode">
<input type="text" size="2"
value={this.state.episodesText}
onChange={this.onChangeEpisodes}
onBlur={this.saveChangeEpisodes}
/>
/{totalEpisodesText}
</h1>
<h2 className="anime-title" ref="title" onMouseDown={this.toggleDescription.bind(this, this.props.libraryItem.anime)}>
{this.props.libraryItem.anime.title}
</h2>
<LibraryItemStatusComponent libraryItem={this.props.libraryItem}
onChangeStatus={this.onChangeStatus}
removeFromLibrary={this.removeFromLibrary}/>
<LibraryItemRatingComponent libraryItem={this.props.libraryItem} onChangeRating={this.onRatingChanged}/>
<LibraryItemAirDayComponent libraryItem={this.props.libraryItem} onChangeAirDay={this.onAirDayChanged}/>
</li>
</div>
);
}
});
module.exports = LibraryItemComponent;
|
var classutils_1_1Image =
[
[ "Image", "d8/d79/classutils_1_1Image.html#a143e2a3fa9c6dbb2f0e70169d7e99671", null ],
[ "height", "d8/d79/classutils_1_1Image.html#a369742a54a5723062d68a051c2e2ce8a", null ],
[ "scale", "d8/d79/classutils_1_1Image.html#adbaa219675b555ef8587a0701b4184e0", null ],
[ "width", "d8/d79/classutils_1_1Image.html#aa1d7f35b3fade6f28dc1ff5502985015", null ]
];
|
'use strict';
Ext.define('LogViewer.store.Filters', {
alias : 'store.filters',
extend : 'Ext.data.ArrayStore',
model : 'LogViewer.model.Filter'
});
|
MODX Evolution 1.0.2 = 74e5104b1936ced93cbf6c51ee6906e2
|
import React, { PropTypes } from 'react'
import { GoogleMapLoader, GoogleMap, Marker } from "react-google-maps";
const HopitauxMap = React.createClass({
render () {
let hopitaux = this.props.hopitaux;
return (
<section style={{height: "700px"}}>
<GoogleMapLoader
containerElement={
<div
{...this.props}
style={{
height: "100%"
}}
/>
}
googleMapElement={
<GoogleMap
defaultZoom={11}
defaultCenter={{lat: 48.856638, lng: 2.352241}}>
{hopitaux.map((hopital, index) => {
let coords = hopital.location.split(',');
let marker = {
position: {
lat: parseFloat(coords[0]),
lng: parseFloat(coords[1]),
},
key: hopital.uuid,
title: hopital.name
}
return (
<Marker {...marker} />
);
})}
</GoogleMap>
}
/>
</section>
)
}
})
export default HopitauxMap
|
require('./include/common')('splashscreen');
require('./include/ethereumProvider.js');
const mist = require('./include/mistAPI.js');
const { ipcRenderer, remote, webFrame } = require('electron');
require('./include/openExternal.js');
require('./include/setBasePath')('interface');
// get and set language
ipcRenderer.send('backendAction_setLanguage', navigator.language);
// disable pinch zoom
webFrame.setZoomLevelLimits(1, 1);
window.ipc = ipcRenderer;
window.mist = mist();
window.mistMode = remote.getGlobal('mode');
window.dirname = remote.getGlobal('dirname');
|
(function(angular, undefined) {
'use strict';
angular.module('LearningApp').controller('AboutCtrl', [function() {
}]);
})(angular);
|
import React from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import { fetchTournamentDate } from '../actions/index'
import Timer from './timer.js'
class Header extends React.Component {
componentWillMount () {
this.props.fetchTournamentDate()
}
render () {
const { date } = this.props
return (
<div className="header">
<ul className="menu nav nav-pills">
<li className="logo menu__item menu__item--left active">
<Link to="/">eliscore</Link>
</li>
<li className="menu__item">
<Link to="/leaderboard" className="menu__item__link">
Leaderboards
</Link>
</li>
<li className="menu__item">
<Link to="/#" className="menu__item__link">
Profile
</Link>
</li>
<li className="menu__item">
<Link to="/live" className="menu__item__link">
Live Game
</Link>
</li>
<li className="menu__item menu__item--left timer">
<Timer startDate={date}/>
</li>
</ul>
</div>
)
}
}
const mapStateToProps = (state) => {
return { date: state.tournamentDate }
}
const mapDispatchToProps = {
fetchTournamentDate
}
export default connect(mapStateToProps, mapDispatchToProps)(Header)
|
// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/koektrommel');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("we're connected!");
});
const Slide = require('./server/models/slide.model');
const Screen = require('./server/models/screen.model');
const app = express();
//use cors for css from localhost 4200 (angular default dev port)
app.use(cors({
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}));
// Parsers for POST data
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Get our API routes
const apiRoutes = require('./server/routes/api.routes')();
const slideRoutes = require('./server/routes/slide.routes')(Slide);
const screenRoutes = require('./server/routes/screen.routes')(Screen);
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set our api routes
app.use('/api',apiRoutes)
app.use('/api/slides', slideRoutes);
app.use('/api/screens', screenRoutes);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
const port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`API running on localhost:${port}`));
|
var searchData=
[
['antcar',['AntCar',['../classjustine_1_1robocar_1_1AntCar.html',1,'justine::robocar']]]
];
|
var mongoose = require('mongoose');
var timestamps = require('mongoose-timestamp');
var videoSchema = mongoose.Schema({
loc: {
type: [Number], // [<longitude>, <latitude>]
index: '2d'
},
type: { type: String },
description: { type: String },
title: { type: String, required: true },
filename: { type: String },
likes: { type: Number }
});
videoSchema.plugin(timestamps);
module.exports = mongoose.model('Video', videoSchema);
|
jQuery.noConflict();
jQuery(document).ready(function() {
jQuery('a.lookup').click(function(event) {
event.preventDefault();
jQuery('form#giftCardLookup').submit();
});
});
|
CShapeParticleSensor = function(object, type, name, x, y) {
CShapeBox.call(this, object, type, name, x, y, 1, 1);
}
CShapeParticleSensor.prototype = new CShapeBox();
|
/**
* product detail publication
* @param {String} productId - productId or handle
* @return {Object} return product cursor
*/
Meteor.publish("Product", function (productId) {
check(productId, Match.OptionalOrNull(String));
if (!productId) {
ReactionCore.Log.info("ignoring null request on Product subscription");
return this.ready();
}
let _id;
let shop = ReactionCore.getCurrentShop();
// verify that shop is ready
if (typeof shop !== "object") {
return this.ready();
}
let selector = {};
selector.isVisible = true;
if (Roles.userIsInRole(this.userId, ["owner", "admin", "createProduct"],
shop._id)) {
selector.isVisible = {
$in: [true, false]
};
}
// TODO review for REGEX / DOS vulnerabilities.
if (productId.match(/^[A-Za-z0-9]{17}$/)) {
selector._id = productId;
// TODO try/catch here because we can have product handle passed by such regex
_id = productId;
} else {
selector.handle = {
$regex: productId,
$options: "i"
};
const products = ReactionCore.Collections.Products.find(selector).fetch();
if (products.length > 0) {
_id = products[0]._id;
} else {
return this.ready();
}
}
// products are always visible to owners and admins
if (!Roles.userIsInRole(this.userId, ["admin"])) {
selector.isVisible = true;
// only products enabled by their owner
selector.isActive = true;
}
// check quantity
_.extend(selector, {
isSoldOut: false
});
selector = { $or: [{ _id: _id }, { ancestors: { $in: [_id] }}] };
return ReactionCore.Collections.Products.find(selector);
});
|
// DOMLib -- libmobdom.js
// Inspired from dom_library.js from www.MAH.se course in web programming.
// License: Public Domain.
// dom_library.js ingår i övningsmateriel från kursen Webbprogrammering, DA123A,
// HT08 vid Malmö högskola.
// Filerna hämtades från kursplatsen på It's learning (www.mah.se/lms) 2008-10-08.
function setText(element, string) {
removeAllChildren(element);
var textNode = document.createTextNode(string);
element.appendChild(textNode);
}
function removeAllChildren(element) {
while (element.firstChild != null)
element.removeChild(element.firstChild);
}
|
'use strict';
const argCharset = 'abcdeghijklmnopqrstuvwxyz';
// Generates comma seperated argument list
function generateArgString(count) {
let argString = '';
let prefix = '';
let charsetPos = 0;
while(count-- > 0) {
let suffix = ',';
if(!count)
suffix = '';
argString += prefix + argCharset[charsetPos] + suffix;
if(++charsetPos == argCharset.length) {
prefix += argCharset[0];
charsetPos = 0;
}
}
return argString;
}
/*
* Get full list of all inherited property names excluding constructors
* and ones from Object
*/
function getInheritedPropertyNames(proto) {
let propNames = [];
while(Object.getPrototypeOf(proto) && proto !== Object.prototype) {
propNames = propNames.concat(Object.getOwnPropertyNames(proto));
proto = Object.getPrototypeOf(proto);
}
return propNames.filter(key => key !== 'constructor');
}
module.exports = function(...args) {
// Generate list of arguments dynamically to get correct constructor.length
let nArgs = args.reduce(((count, clazz) => count + clazz.length), 0);
let argString = generateArgString(nArgs);
let mix = new Function('classes, getInheritedPropertyNames', `
return class {
constructor(${argString})
{
let cargs = [${argString}];
classes.forEach(clazz => {
// Clone and expand prototype
let obj = Object.create(clazz.prototype);
// Populate cloned prototype
getInheritedPropertyNames(this.__proto__)
.forEach(prop =>
obj.__proto__[prop] = this.__proto__[prop]);
let largs = cargs.splice(0, clazz.length);
largs.unshift(clazz);
// Create new object from constructor of populated prototype
let sub = new
(Function.prototype.bind
.apply(obj.__proto__.constructor, largs));
Object.getOwnPropertyNames(sub).forEach(key => {
this[key] = sub[key];
});
});
}
}`
)(args, getInheritedPropertyNames);
// Copy over functions
args.forEach(clazz => {
getInheritedPropertyNames(clazz.prototype).forEach(key =>
mix.prototype[key] = clazz.prototype[key]);
});
return mix;
};
|
import routes from './routes';
import home from './components/home';
import github from './components/subs/github';
import about from './components/subs/about';
import version from './components/subs/version';
import contribution from './components/subs/contribution';
export default {
type: 'feature',
name: 'home',
routes,
component: {
home,
github,
about,
version,
contribution
}
};
|
var searchData=
[
['hasnewfatalfailurehelper',['HasNewFatalFailureHelper',['../classtesting_1_1internal_1_1HasNewFatalFailureHelper.html',1,'testing::internal']]],
['hassubstrmatcher',['HasSubstrMatcher',['../classtesting_1_1internal_1_1HasSubstrMatcher.html',1,'testing::internal']]],
['httprpcserver',['HttpRpcServer',['../classupload_1_1HttpRpcServer.html',1,'upload']]]
];
|
var api = require('../../..');
debugger
api.registerPlugin(
{
handlers: {
'/~invalid': __dirname+'/invalid',
},
injections: []
}
);
|
#!/usr/bin/env nodejs
"use strict";
var exec = require("exec");
var request = require("request");
var sprintf = require("sprintf-js").sprintf;
// http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22my_city%22&format=xml
// http://weather.yahooapis.com/forecastrss?w=%s&u=%s
var city_code = 90717580;
var url = sprintf("http://query.yahooapis.com/v1/public/yql?q=select item from weather.forecast where woeid=\"%s\"&format=json", city_code);
function FtoC(temp) {return Math.round((temp - 32) / (9 / 5));}
request({
url: url,
method: "GET",
json: true,
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
}, function (error, response, body){
var value = FtoC(body.query.results.channel.item.condition.temp);
if(!value) {
console.log("Error\n");
process.exit(1);
} else {
console.log(value);
process.exit(0);
}
});
|
'use strict';
// Staging Settings
module.exports = {
logging: {
exitOnError: false,
use: {
console: true,
file: false
},
console: {
level: 'warn'
}
}
};
|
(function(window, document) {
var layout = document.getElementById('layout'),
menu = document.getElementById('menu'),
menuLink = document.getElementById('menuLink'),
content = document.getElementById('main');
function toggleClass(element, className) {
var classes = element.className.split(/\s+/),
length = classes.length,
i = 0;
for (; i < length; i++) {
if (classes[i] === className) {
classes.splice(i, 1);
break;
}
}
// The className is not found
if (length === classes.length) {
classes.push(className);
}
element.className = classes.join(' ');
}
function toggleAll(e) {
var active = 'active';
e.preventDefault();
toggleClass(layout, active);
toggleClass(menu, active);
toggleClass(menuLink, active);
}
menuLink.onclick = function(e) {
toggleAll(e);
};
content.onclick = function(e) {
if (menu.className.indexOf('active') !== -1) {
toggleAll(e);
}
};
}(this, this.document));
|
import moment from 'moment'
import {now, getApiFormat} from '#/main/app/intl/date'
import {makeInstanceAction} from '#/main/app/store/actions'
import {makeReducer, combineReducers} from '#/main/app/store/reducer'
import {TOOL_LOAD} from '#/main/core/tool/store/actions'
import {
AGENDA_CHANGE_TYPES,
AGENDA_CHANGE_VIEW,
AGENDA_SET_LOADED,
AGENDA_LOAD_EVENTS,
AGENDA_LOAD_EVENT
} from '#/plugin/agenda/tools/agenda/store/actions'
const reducer = combineReducers({
view: makeReducer('month', {
[AGENDA_CHANGE_VIEW]: (state, action) => action.view
}),
referenceDate: makeReducer(now(), {
[makeInstanceAction(TOOL_LOAD, 'agenda')]: () => now(),
[AGENDA_CHANGE_VIEW]: (state, action) => moment(action.referenceDate).format(getApiFormat()),
[AGENDA_LOAD_EVENT]: (state, action) => action.event && action.event.start ? moment(action.event.start).format(getApiFormat()) : state
}),
types: makeReducer(['event', 'task'], {
[AGENDA_CHANGE_TYPES]: (state, action) => action.types
}),
loaded: makeReducer(false, {
[makeInstanceAction(TOOL_LOAD, 'agenda')]: () => false,
[AGENDA_SET_LOADED]: (state, action) => action.loaded,
[AGENDA_CHANGE_TYPES]: () => false,
[AGENDA_CHANGE_VIEW]: () => false,
[AGENDA_LOAD_EVENTS]: () => true
}),
events: makeReducer([], {
[makeInstanceAction(TOOL_LOAD, 'agenda')]: () => [],
[AGENDA_LOAD_EVENTS]: (state, action) => action.events
}),
current: makeReducer(null, {
[AGENDA_LOAD_EVENT]: (state, action) => action.event
})
})
export {
reducer
}
|
var searchData=
[
['thdpost',['thdPost',['../group__kern__impl.html#gaae0a028e9f472994def9358f16cc40d3',1,'kernel.c']]],
['thdwait',['thdWait',['../group__kern__impl.html#ga59935809f83133fb909c513fb72576b7',1,'kernel.c']]]
];
|
"use strict";
class MergeConflictDocumentTracker {
}
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = MergeConflictDocumentTracker;
//# sourceMappingURL=document-merge-conflict-tracker.js.map
|
// ******* SITEMAP TOOLBAR VIEWER ACTIONS ******** //
$axure.internal(function($ax) {
var userTriggeredEventNames = ['onClick', 'onDoubleClick', 'onMouseOver', 'onMouseMove', 'onMouseOut', 'onMouseDown', 'onMouseUp', 'onKeyDown', 'onKeyUp', 'onFocus', 'onLostFocus', 'onTextChange', 'onSelectionChange', 'onCheckedChange', 'onSwipeLeft', 'onSwipeRight', 'onSwipeUp', 'onSwipeDown', 'onDragStart', 'onDrag', 'onDragDrop', 'onScroll', 'onContextMenu', 'onMouseHover', 'onLongClick'];
$ax.messageCenter.addMessageListener(function(message, data) {
//If annotation toggle message received from sitemap, toggle footnotes
if(message == 'annotationToggle') {
if(data == true) {
$('div.annotation').show();
$('div.annnotelabel').show();
$('div.annnoteimage').show();
} else {
$('div.annotation').hide();
$('div.annnotelabel').hide();
$('div.annnoteimage').hide();
}
}
});
var highlightEnabled = false;
$ax.messageCenter.addMessageListener(function(message, data) {
if(message == 'highlightInteractive') {
highlightEnabled = data == true;
_applyHighlight($ax('*'));
}
});
var _applyHighlight = $ax.applyHighlight = function(query, ignoreUnset) {
if(ignoreUnset && !highlightEnabled) return;
//Do condition to check if legacy browser (all IE, except 10) and select appropriate pulsate css class name
var userAgentString = navigator.userAgent.toLowerCase();
var isIEpre10 = userAgentString.indexOf('msie 9.') != -1 ||
userAgentString.indexOf('msie 8.') != -1 ||
userAgentString.indexOf('msie 7.') != -1 ||
userAgentString.indexOf('msie 6.') != -1;
var pulsateClassName = isIEpre10 ? 'legacyPulsateBorder' : 'pulsateBorder';
//Find all widgets with a defined userTriggeredEventName specified in the array above
var $matchingElements = query.filter(function(obj) {
if(obj.interactionMap) {
for(var index in userTriggeredEventNames) {
if(obj.interactionMap[userTriggeredEventNames[index]]) return true;
}
}
return false;
}).$();
var isHighlighted = $matchingElements.is('.' + pulsateClassName);
//Toggle the pulsate class on the matched elements
if(highlightEnabled && !isHighlighted) {
$matchingElements.addClass(pulsateClassName);
} else if(!highlightEnabled && isHighlighted) {
$matchingElements.removeClass(pulsateClassName);
}
};
});
|
var _m_s_vehicle_8cpp =
[
[ "BUS_STOP_OFFSET", "dd/d1d/_m_s_vehicle_8cpp.html#ad6e57ec62988057451224a702a658f9b", null ]
];
|
Ext.define('Onlineshopping.view.art.masterform.MasterTreePanelController', {
extend : 'Ext.app.ViewController',
alias : 'controller.masterTreePanelController',
renderData : function (data){
debugger;
var rootNode = this.getView().getRootNode();
rootNode.removeAll();
for (var int = 0; int < data.length; int++) {
var childNode = { text:data[int].primaryDisplay, bConfig:data[int], leaf : true ,icon:'images/table_icon.png'};
rootNode.appendChild(childNode);
}
debugger;
var masterTreePanelCombo = this.getView().down('#masterTreePanelSearchBox');
var store = Ext.create('Ext.data.Store',
{
storeId : 'masterTreePanelStore',
fields : ['primaryKey','primaryDisplay','bConfig'],
fields:[],
data : [],
sortOnLoad :true
});
Ext.each(data, function(ent)
{
this.store.add({primaryKey:ent.primaryKey,primaryDisplay:ent.primaryDisplay,bConfig:ent,leaf:true});
},{store:store});
store.sort('name', 'ASC');
masterTreePanelCombo.setStore(store);
},
onMasterTreePanelSearchBoxSelect:function(searchbox, records, eOpts)
{
debugger;
this.onMasterTreePanelSearchBoxSelect( searchbox, records, eOpts);
},
onMasterTreePanelSearchBoxSelect:function( searchbox, records, eOpts )
{
debugger;
this.setDataActiveTab();
this.searchEntity(this.getView().getRootNode(), records[0].data.primaryKey, true);
var treeObject = this.treePanel;
var records = records[0];
debugger;
this.setFormPanelData(records);
},
searchEntity : function (treeNode, entKey ,isExpand)
{
debugger;
var me = this;
treeNode.eachChild(function(child)
{
if(child.data.hasOwnProperty('bConfig')&&child.data.bConfig.primaryKey == entKey)
{
if(isExpand)
{
this.getView().selectPath(child.getPath());
this.getView().expandNode(child,true);
}
return false;
}
else if (child.hasChildNodes())
{
me.searchEntity(child,entKey,isExpand);
}
},me);
var masterTreePanelCombo = this.getView().down('#masterTreePanelSearchBox');
masterTreePanelCombo.reset();
},
setFormPanelData: function( record){
debugger;
var loadMask = new Ext.LoadMask({
msg : 'Loading data...',
target : this.getView().up().up().up()
}).show();
if(record.data.leaf){
var masterGridPanel = this.getView().up().up().items.items[2].down("#masterEditGridPanel");
masterGridPanel.getController().setMasterFormData(record.data.bConfig);
/*set grid selection...*/
masterGridPanel.getController().setSelection(record.data.bConfig);
}
loadMask.hide();
},
setDataActiveTab:function()
{
debugger;
var tab = this.getView().up().up().items.items[2];
if(tab.activeTab.panelId=="masterPanelAddTab")
{
if(tab.items.items[0].panelId=="masterPanelEditTab")
{
tab.setActiveTab(tab.tabBar.items.items[0].card);
}
}
},
searchTreeNode : function (treeNode, primaryKey ,isExpand){
var me = this;
treeNode.eachChild(function(child) {
debugger;
if(child.data.bConfig.primaryKey == primaryKey){
foundChild = child;
if(isExpand){
me.getView().selectPath(child.getPath());
me.getView().expandPath(child.getPath());
}
return false;
}
else if (child.hasChildNodes()){
me.searchTreeNode(child,itemId,isExpand); // handle the child recursively
}
},me);
}
});
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
gulp.task('partials', function () {
return gulp.src([
path.join(conf.paths.src, '/app/**/*.html'),
path.join(conf.paths.tmp, '/serve/app/**/*.html')
])
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe($.angularTemplatecache('templateCacheHtml.js', {
module: 'pteroWorkflowClient',
root: 'app'
}))
.pipe(gulp.dest(conf.paths.tmp + '/partials/'));
});
gulp.task('html', ['inject', 'partials'], function () {
var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), { read: false });
var partialsInjectOptions = {
starttag: '<!-- inject:partials -->',
ignorePath: path.join(conf.paths.tmp, '/partials'),
addRootSlash: false
};
var htmlFilter = $.filter('*.html', { restore: true });
var jsFilter = $.filter('**/*.js', { restore: true });
var cssFilter = $.filter('**/*.css', { restore: true });
var assets;
return gulp.src(path.join(conf.paths.tmp, '/serve/*.html'))
.pipe($.inject(partialsInjectFile, partialsInjectOptions))
.pipe(assets = $.useref.assets())
.pipe($.rev())
.pipe(jsFilter)
.pipe($.sourcemaps.init())
.pipe($.ngAnnotate())
.pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', conf.errorHandler('Uglify'))
.pipe($.sourcemaps.write('maps'))
.pipe(jsFilter.restore)
.pipe(cssFilter)
.pipe($.sourcemaps.init())
.pipe($.replace('../../bower_components/bootstrap/fonts/', '../fonts/'))
.pipe($.minifyCss({ processImport: false }))
.pipe($.sourcemaps.write('maps'))
.pipe(cssFilter.restore)
.pipe(assets.restore())
.pipe($.useref())
.pipe($.revReplace())
.pipe(htmlFilter)
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true,
conditionals: true
}))
.pipe(htmlFilter.restore)
.pipe(gulp.dest(path.join(conf.paths.dist, '/')))
.pipe($.size({ title: path.join(conf.paths.dist, '/'), showFiles: true }));
});
// Only applies for fonts from bower dependencies
// Custom fonts are handled by the "other" task
gulp.task('fonts', function () {
return gulp.src($.mainBowerFiles())
.pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}'))
.pipe($.flatten())
.pipe(gulp.dest(path.join(conf.paths.dist, '/fonts/')));
});
gulp.task('other', function () {
var fileFilter = $.filter(function (file) {
return file.stat.isFile();
});
return gulp.src([
path.join(conf.paths.src, '/**/*'),
path.join('!' + conf.paths.src, '/**/*.{html,css,js,less}')
])
.pipe(fileFilter)
.pipe(gulp.dest(path.join(conf.paths.dist, '/')));
});
gulp.task('clean', function (done) {
$.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')], done);
});
gulp.task('build', ['html', 'fonts', 'other']);
|
var searchData=
[
['math_2ejs',['Math.js',['../_math_8js.html',1,'']]]
];
|
var searchData=
[
['execute',['execute',['../class_drone.html#aa8219373d2c4ca9826e4e9464b2f9bcc',1,'Drone']]]
];
|
/*
Copyright (C) 2012 Andrew P. Sillers (apsillers@gmail.com)
This file is part of the HTML5 Netrek Client.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
var IND = 0x0, FED = 0x1, ROM = 0x2, KLI = 0x4, ORI = 0x8;
var teamLib = {
IND:0x0,
ROM:0x2,
KLI:0x4,
ORI:0x8,
FED:0x1,
getRaceColor: function(race, isLight) {
if(race == FED) return isLight?"#330":"#FF0";
if(race == KLI) return isLight?"#030":"#0F0";
if(race == ROM) return isLight?"#300":"#F00";
if(race == ORI) return isLight?"#003":"#00F";
return isLight?"#FFF":"#FFF";
},
raceDecode: function(n) {
if(n==0) return 'F';
if(n==1) return 'R';
if(n==2) return 'K';
if(n==3) return 'O';
return 'I';
},
teamDecode: function(mask) {
var x = []
if (mask & FED) x.push(FED);
if (mask & ROM) x.push(ROM);
if (mask & KLI) x.push(KLI);
if (mask & ORI) x.push(ORI);
return x;
},
teamNumber: function(team) {
if(team==FED) return 0;
if(team==ROM) return 1;
if(team==KLI) return 2;
if(team==ORI) return 3;
return -1;
}
}
|
const { v4: uuid } = require('node-uuid')
const PythonShell = require('python-shell')
const { APIError } = require('../../../helpers/error')
const { createError } = require('../../../helpers/response')
const { logger, modelDirectory, pythonPath } = require('../../../config')
const BIT_TO_BYTES = 1048576
const MAX_FILE_SIZE = 10 * BIT_TO_BYTES
const AUTHORIZED_FORMATS = ['jpg', 'jpeg']
module.exports = dependencies => {
const { fs, os, path } = dependencies
const getClassification = pathname => {
const options = {
pythonPath,
args: ['--model_dir', modelDirectory, '--image_file', pathname]
}
const classificationScript = new PythonShell('engine/classify.py', options)
return new Promise((resolve, reject) => {
classificationScript
.on('error', reject)
.on('message', data => resolve(JSON.parse(data)))
})
}
return {
* classify ({ request, response }) {
const { parts, contentLength } = request
const { answer, abort } = response
let filepath
try {
if (contentLength > MAX_FILE_SIZE) {
const code = 413
const message = `The file is too big (maximum size allowed is ${MAX_FILE_SIZE / BIT_TO_BYTES} MB).`
throw new APIError({ code, message })
}
const part = yield parts
if (!part) {
const code = 422
const message = 'The file is not specified.'
throw new APIError({ code, message })
}
const { mime } = part
const [, format] = mime.split('/')
if (!AUTHORIZED_FORMATS.includes(format)) {
const code = 415
const message = `The media type should be one of the following: ${AUTHORIZED_FORMATS.join(', ')}.`
throw new APIError({ code, message })
}
filepath = path.join(os.tmpdir(), uuid())
const stream = fs.createWriteStream(filepath)
part.pipe(stream)
if (!stream) {
const code = 422
const message = 'The file parameter is missing.'
throw new APIError({ code, message })
}
// Check if the model has already been downloaded
fs.stat(modelDirectory, err => {
if (err) {
logger.info('Downloading the model for the first time...')
}
})
try {
const data = yield getClassification(stream.path)
const result = {
meta: {
type: 'success',
code: 200
},
data
}
answer(result)
logger.info('Classified a picture.', data)
} catch (e) {
const code = 422
const message = 'Unable to process the classification (the file might be corrupted).'
logger.error(e)
throw new APIError({ code, message })
}
} catch (e) {
const code = e.code || 500
const message = e.message
abort(code, createError({ code, message }))
logger.info(message, { code, message })
}
// Delete the picture once processed
if (filepath) {
fs.unlink(filepath, err => {
if (err) {
logger.error(err)
}
})
}
}
}
}
|
Joomla 3.7.0 = c6ceb7876b22f9f141980a497b3901c6
|
"use strict";
var AbstractBag = require('zeujsChaos/bags/abstract.js');
var SchemaPrototype = require('../prototypes/schema.js');
var SchemasBag = function SchemasBag() {
AbstractBag.call(this);
};
SchemasBag.prototype = Object.create(AbstractBag.prototype);
SchemasBag.prototype.constructor = SchemasBag;
SchemasBag.prototype.find = function find(schemaId) {
var schema = this.findById(schemaId);
if (typeof schema === 'undefined') {
throw 'Schema want to be defined';
}
return schema.schema;
};
SchemasBag.prototype.push = function push(datum) {
this.normalize(datum);
this.data.push(
{
id: datum.id,
schema: new SchemaPrototype(this.services, datum)
}
);
};
module.exports = SchemasBag;
|
'use strict'
const pinGenerationDataService = require('./data-access/pin-generation.data.service')
const pupilIdentificationFlagService = require('../services/pupil-identification-flag.service')
/**
* Return a list of pupils who can have a pin generated
* @param {number} schoolId
* @return {Promise<*>}
*/
const serviceToExport = {
/**
* Return a list of pupils who can have a pin generated
* @param schoolId
* @return {Promise<*>}
*/
getPupilsEligibleForPinGeneration: async function getPupilsEligibleForPinGeneration (schoolId, isLiveCheck) {
const pupils = await pinGenerationDataService.sqlFindEligiblePupilsBySchool(schoolId, isLiveCheck)
return pupilIdentificationFlagService.sortAndAddIdentificationFlags(pupils)
},
/**
* Return a list of pupils who have an active pin - one that can be used to take a check
* @param {number} schoolId
* @param {boolean} isLiveCheck
* @return {Promise<Array<any>>}
*/
getPupilsWithActivePins: async function getPupilsWithActivePins (schoolId, isLiveCheck) {
const pupils = await pinGenerationDataService.sqlFindPupilsWithActivePins(schoolId, isLiveCheck)
if (pupils.length === 0) { return pupils }
// Pupil disambiguation for the user/gui
return pupilIdentificationFlagService.sortAndAddIdentificationFlags(pupils)
}
}
module.exports = serviceToExport
|
define(function(require, exports, module)
{
// Circular dependency.
var GREETINGS = require("../greetings");
exports.getWord = function()
{
return "Hello";
}
exports.getName = function()
{
return GREETINGS.getName();
}
});
|
function json2array(json) {
var result = [];
var keys = Object.keys(json);
keys.forEach(function(key) {
result.push(json[key]);
});
return result;
}
$(document).on("click", ".remove", function() {
var link = $(this);
var agree = confirm('Are you sure to remove this identy? You will not be able to read messages from this person!');
if (!agree) {
return false;
}
var public_key_md5 = link.data('public_key_md5');
server.certificates.remove(public_key_md5).done(function(key) {
//console.log(link.parent());
window.location = window.location;
});
return false;
});
var server;
$(document).ready(function() {
$('#add_identy').click(function() {
$('#identy_adder').slideDown();
return false;
});
$('#add_identy_do').click(function() {
var cert = $('#identy_cert').val();
var certinfo = CARRIER.get_certificate_info(cert);
if (certinfo) {
var agree = confirm("Are you sure to add:\n\n" + 'Carrier certificate with MD5 fingerprint ' + certinfo.public_key_md5 + ' of ' + certinfo.name + ' from ' + certinfo.city + ', ' + certinfo.state + ' (' + certinfo.country + ') Working at ' + certinfo.org + ' in ' + certinfo.department);
if (agree) {
server.certificates.add(certinfo).done(function(item) {
alert('Identy added successfully');
window.location = window.location;
}).fail(function() {
alert('Unable to add identy. Maybe you already know this user?');
});
}
} else {
alert('Invalid identy certificate, check your input');
}
return false;
});
db.open({
server: 'privateer-identy',
version: 1,
schema: {
certificates: {
key: {keyPath: 'public_key_md5'},
// Optionally add indexes
indexes: {
public_key_md5: {unique: true}
}
},
messages: {
key: {keyPath: 'md5'},
// Optionally add indexes
indexes: {
md5: {unique: true}
}
},
distribution_messages: {
key: {keyPath: 'origin_md5'},
// Optionally add indexes
indexes: {
origin_md5: {unique: true}
}
}
}
}).done(function(s) {
server = s;
server.certificates.query().filter( ).execute().done(function(identies) {
var to_table = [];
for (var i in identies) {
identies[i].pem = "<textarea>" + identies[i].pem + "</textarea>";
identies[i].public_key = "<textarea>" + identies[i].public_key + "</textarea>";
var table_row = json2array(identies[i]);
table_row.push('<a href="#" class="remove" data-public_key_md5="' + identies[i].public_key_md5 + '">Remove</a>');
to_table.push(table_row);
}
//console.log(JSON.stringify(to_table));
$('#identies').dataTable({"data": to_table});
});
$('#export').click(function() {
server.certificates.query().filter( ).execute().done(function(identies) {
alert('Identies archive created. Please save it as .json file');
//identies = forge.util.encode64(JSON.stringify(identies));
chrome.tabs.create({url: 'data:Application/octet-stream;base64,' +
forge.util.encode64(JSON.stringify(identies))});
});
});
$('#remove_all').click(function() {
var agree = confirm('Are you sure to remove ALL identies? You wont be able to chat with these people');
if (agree) {
server.certificates.clear();
window.location = window.location;
}
return false;
});
});
});
|
var
del = require('del'),
gulp = require('gulp'),
path = require('path'),
concat = require('gulp-concat'),
copy = require('gulp-copy'),
less = require('gulp-less'),
merge = require('gulp-merge'),
mincss = require('gulp-minify-css'),
minhtml = require('gulp-minify-html');
processhtml = require('gulp-processhtml'),
uglify = require('gulp-uglify');
webserver = require('gulp-webserver');
gulp.task('default', ["styles", "scripts", "files"], function() {
});
gulp.task("styles", [], function () {
return merge(
gulp
.src([
"./src/_components/bootstrap/dist/css/bootstrap.min.css",
"./src/_components/bootstrap/dist/css/bootstrap-theme.min.css",
]),
gulp
.src('./src/styles/**/*.css'),
gulp
.src('./src/styles/**/*.less')
.pipe(less({
paths: [ path.join(__dirname, 'less', 'includes') ]
}))
.pipe(mincss())
)
.pipe(concat('main.css'))
.pipe(gulp.dest('./dist/styles/'))
});
gulp.task("scripts", [], function () {
return merge(
gulp
.src([
"./src/_components/jquery/dist/jquery.min.js",
"./src/_components/bootstrap/dist/js/bootstrap.min.js"
]),
gulp
.src('./src/scripts/**/*.js')
.pipe(uglify())
)
.pipe(concat('main.js'))
.pipe(gulp.dest('./dist/scripts/'))
});
gulp.task("bootstrap-files", [], function () {
return gulp
.src("./src/_components/bootstrap/dist/fonts/**")
.pipe(copy("./dist/fonts/", {prefix: 5}));
});
gulp.task("assets", [], function () {
return gulp
.src("./src/assets/**")
.pipe(copy("./dist/assets/", {prefix: 2}));
});
gulp.task("app-files", [], function () {
return gulp
.src("./src/**/*.html")
.pipe(processhtml({}))
.pipe(minhtml())
.pipe(gulp.dest("./dist/"));
});
gulp.task("files", ["bootstrap-files", "assets", "app-files"], function () {
});
gulp.task('clean', [], function (cb) {
del('build/', cb);
});
gulp.task('serve', function() {
return gulp
.src('src')
.pipe(webserver({
livereload: true,
directoryListing: false,
open: false
}));
});
|
import firebase from 'firebase'
import {CONFIG} from '../private.config.js'
var fbApp = firebase.initializeApp(CONFIG.FIREBASE);
export function firebaseInit (func) {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
func(true, user)
} else {
func(false)
}
},(error) => {
console.log(error)
})
}
|
import { prime } from './nth-prime';
describe('nth-prime', () => {
test('first prime', () => {
expect(prime(1)).toEqual(2);
});
test('second prime', () => {
expect(prime(2)).toEqual(3);
});
test('sixth prime', () => {
expect(prime(6)).toEqual(13);
});
test('big prime', () => {
expect(prime(10001)).toEqual(104743);
});
test('there is no zeroth prime', () => {
expect(() => prime(0)).toThrow(new Error('there is no zeroth prime'));
});
});
|
// Keyboard events
document.onkeypress = function (e) {
e = e || window.event;
var key = e.key;
return keymap[key]();
};
|
// polyfills for Android 5.0
require('core-js/features/map');
require('core-js/features/set');
// Replace ./src/js with the directory of your application code and
// make sure the file name regexp matches your test files.
const context = require.context('../src/', true, /-test\.js$/);
context.keys().forEach(context);
|
/*
* This file is part of Corplms LMS
*
* Copyright (C) 2010 onwards Corplms Learning Solutions LTD
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @author Simon Coggins <simon.coggins@corplmslms.com>
* @author Eugene Venter <eugene@catalyst.net.nz>
* @package corplms
* @subpackage reportbuilder
*/
/**
* Javascript file containing JQuery bindings for show/hide popup dialog box
*/
M.corplms_reportbuilder_showhide = M.corplms_reportbuilder_showhide || {
Y: null,
/**
* module initialisation method called by php js_init_call()
*
* @param object YUI instance
* @param string args supplied in JSON format
*/
init: function(Y, args) {
// save a reference to the Y instance (all of its dependencies included)
this.Y = Y;
// check jQuery dependency is available
if (typeof $ === 'undefined') {
throw new Error('M.corplms_reportbuilder_showhide.init()-> jQuery dependency required for this module to function.');
}
///
/// first, hide columns that should be hidden!
///
if (args.length) {
for (col in args) {
$(args[col]).hide();
}
}
///
/// show/hide column dialog
///
// id not set when zero results
// http://verens.com/2005/07/25/isset-for-javascript/#comment-332
if (window.id === undefined) {return;}
$('#show-showhide-dialog').css('display','inline');
var path = M.cfg.wwwroot + '/corplms/reportbuilder/';
var handler = new corplmsDialog_handler();
var name = 'showhide';
var buttons = {};
buttons[M.util.get_string('ok', 'moodle')] = function() { handler._cancel() };
var querystring = window.location.search;
corplmsDialogs[name] = new corplmsDialog(
name,
'show-'+name+'-dialog',
{
buttons: buttons,
title: '<h2>' + M.util.get_string('showhidecolumns', 'corplms_reportbuilder') + '</h2>'
},
path + 'showhide.php?id=' + id.toString() + querystring.replace('?', '&'),
handler
);
}
}
|
import { Meteor } from 'meteor/meteor';
import { Projects } from './projects.js';
import { Tasks } from '../tasks/tasks.js';
import { check } from 'meteor/check';
Meteor.methods({
"projects.insert": (projectAttributes) => {
const project = Projects.simpleSchema().clean(projectAttributes);
const sameTitleProject = Projects.findOne({
title: projectAttributes.title,
owner: this.userId,
});
if (sameTitleProject) {
return {
_id: sameTitleProject._id,
exists: true
};
}
const _id = Projects.insert(project);
return {
_id
};
},
"projects.remove": (projectID) => {
check(projectID, String);
const project = Projects.findOne(projectID);
if (project.owner!==Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
Tasks.remove({ projectID });
Projects.remove({ _id: projectID });
},
});
|
/**
Set of constants focused on MRS.Core automated tests
**/
|
var TemplateLibraryTemplateView = require( 'qazana-templates/views/template/base' ),
TemplateLibraryTemplateThemeView;
TemplateLibraryTemplateThemeView = TemplateLibraryTemplateView.extend( {
template: '#tmpl-qazana-template-library-template-theme',
onPreviewButtonClick: function() {
qazana.templates.getLayout().showPreviewView( this.model );
}
} );
module.exports = TemplateLibraryTemplateThemeView;
|
'use strict';
var assert = require( 'assert' )
, fs = require( 'fs' )
, tmp = require( 'tmp' );
function Connector(options) {
var currentPath;
assert(options.hasOwnProperty('stdin'));
assert(options.hasOwnProperty('stdout'));
assert(options.hasOwnProperty('stderr'));
this.isActive = function() {
return typeof currentPath !== 'undefined';
};
this.pipeOut = function() {
assert( typeof currentPath !== 'undefined' );
return new Promise( (resolve, reject) => {
openReadFile( currentPath )
.then( fd => {
resolve({ stdin: fd, stdout: options.stdout, stderr: options.stderr });
} )
.catch( reject );
});
};
this.pipeIn = function() {
return new Promise( (resolve, reject) => {
openWriteFile()
.then( openFile => {
assert( openFile.hasOwnProperty('descriptor') );
if (typeof currentPath === 'undefined') {
resolve({ stdin: options.stdin, stdout: openFile.descriptor, stderr: options.stderr });
}
else {
openReadFile( currentPath )
.then( fd => {
resolve({ stdin: fd, stdout: openFile.descriptor, stderr: options.stderr });
} )
.catch( reject );
}
currentPath = openFile.path;
})
.catch( reject );
});
};
function openReadFile(path) {
return new Promise( (resolve, reject) => {
/*
//this should work
let stream = fs.createReadStream( path );
stream.on( 'open', resolve );
stream.on( 'error', reject );
// but it acts as if the file is closed
fs.open( path, 'r', (err, fd) => {
if (err)
{
reject(err);
}
else {
fs.closeSync(fd);
resolve(fd);
}
});
I was able to reproduce this by executing "ls | less".
// instead just use open :(
*/
fs.open( path, 'r', (err, fd) => {
if (err)
{
reject(err);
}
else {
resolve(fd);
}
});
});
}
function openWriteFile() {
return new Promise( (resolve, reject) => {
tmp.file( ( err, path ) => {
if (err) {
reject( err );
return;
}
let stream = fs.createWriteStream( path );
stream.on( 'open', (fd) => {
resolve( { descriptor: fd, path } );
});
stream.on( 'error', (err) => {
reject( err );
});
});
});
}
}
module.exports = Connector;
|
/* ==================================================================
Site
================================================================== */
$(document).ready(function() {
$(".js-background").background({ theme: "" });
$(".js-carousel").carousel({ theme: "" });
$(".js-navigation").navigation({ theme: "" });
$("body").find(".typography table").wrap('<div class="table_wrapper"><div class="table_wrapper_inner"></div></div>');
tableOverflow();
$(window).on("resize", onResize);
setInterval("demoTimer()", 1000);
});
function onResize() {
tableOverflow();
}
function tableOverflow() {
$(".table_wrapper").each(function() {
$(this).removeClass("table_wrapper_overflow");
if ($(this).prop("scrollWidth") > $(this).width() + 1) {
$(this).addClass("table_wrapper_overflow");
}
else {
$(this).removeClass("table_wrapper_overflow");
}
});
}
function demoTimer() {
var d = new Date();
minutes = 59 - d.getMinutes();
seconds = 59 - d.getSeconds();
$("#reset_minutes").html(minutes);
$("#reset_seconds").html((seconds < 10) ? "0" + seconds : seconds);
if (minutes == 0 && seconds == 1) {
setTimeout("window.reload();", 5000);
}
}
|
import {observable} from 'mobx';
import Post from './Post';
export default class PostStore {
@observable posts = [];
update(posts) {
this.posts = [];
posts.forEach(post => this.posts.push(new Post(post)));
}
all() {
return this.posts;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.