text stringlengths 7 3.69M |
|---|
/**
* SearchStatsTable generates a table of stats given a list of countries.
*
*/
class SearchStatsTable
{
constructor(countries)
{
this.table = this.getSearchStatsAsTable(countries);
}
getTable()
{
return this.table;
}
getSearchStatsAsTable(countries)
{
var table = $("<table></table>");
table.append(this.getStatsTitleAsRow());
table.append(this.getTotalCountAsRow(countries));
table.append(this.getRegionsCountAsRow(countries));
table.append(this.getSubRegionsCountAsRow(countries));
return table;
}
getRegionsCountAsRow(countries)
{
var row = $("<tr></tr>");
row.append($("<td><i>" + "Regions in search:" + "</i></td>"));
var regions = this.getAttributeCount(countries, 'region');
var contentCell = $("<td></td>");
contentCell.append(this._getRegionsCountAsRow_getContentAsTable(regions));
row.append(contentCell);
return row;
}
getSubRegionsCountAsRow(countries)
{
var row = $("<tr></tr>");
row.append($("<td><i>" + "Subregions in search:" + "</i></td>"));
var regions = this.getAttributeCount(countries, 'subregion');
var contentCell = $("<td></td>");
contentCell.append(this._getRegionsCountAsRow_getContentAsTable(regions));
row.append(contentCell);
return row;
}
_getRegionsCountAsRow_getContentAsTable(regions)
{
var table = $("<table></table>");
for (var k in regions)
{
table.append(this.getRegionCountAsRown(k, regions[k]));
}
return table;
}
getRegionCountAsRown(name, count)
{
var row = $("<tr></tr>");
row.append($("<td><b>" + name + "</b></td>"));
row.append($("<td>(" + count + ")</td>"));
return row;
}
getAttributeCount(countries, attribute)
{
var regions = {};
countries.forEach(function(country)
{
if (regions[country[attribute]] === undefined)
{
regions[country[attribute]] = 0;
}
regions[country[attribute]]++;
});
return regions;
}
getStatsTitleAsRow()
{
var row = $("<tr></tr>");
row.append($("<td colspan='2'><u><h3>" + "Search results" + "</h3></u></td>"));
return row;
}
getTotalCountAsRow(countries)
{
var row = $("<tr></tr>");
row.append($("<td><i>" + "Total number of countries:" + "</i></td>"));
row.append($("<td>" + countries.length + "</td>"));
return row;
}
} |
import styled from "styled-components";
export default styled.nav`
position: fixed;
z-index: 1;
top: 0;
width: 100%;
border-bottom: 1px solid rgba(0, 0, 0, 0.0975);
background-color: #fff;
`;
|
'use strict';
const { saveNote,
editNote,
getNote,
deleteNote,
changeNoteState,
findNotes } = require('./controllers/note');
const { getList, clearList, editList } = require('./controllers/list');
module.exports = app => {
app.get('/find', findNotes);
app.route('/list')
.patch(editList)
.get(getList)
.delete(clearList);
app.route('/:name')
.post(saveNote)
.patch(editNote)
.get(getNote)
.delete(deleteNote);
app.patch('/:name/:state(visit|unvisit)', changeNoteState);
app.delete('/', clearList);
app.all('*', (req, res) => {
res.sendStatus(404);
});
};
|
const { EventEmitter } = require('events');
const Debug = require('debug');
// const { Asset } = require('parcel-bundler');
const JSAsset = require('parcel-bundler/src/assets/JSAsset');
const { compiler } = require('vueify-bolt');
const Vue = require('vue');
let ownDebugger = Debug('parcel-plugin-vue:MyAsset');
let event = new EventEmitter();
compiler.loadConfig();
function compilerPromise(fileContent, filePath) {
return new Promise((resolve, reject) => {
let style = '';
let dependencies = [];
function compilerStyle(e) {
style = e.style;
}
function addDependency(srcPath) {
if (dependencies.indexOf(srcPath) === -1) {
dependencies.push(srcPath);
}
}
compiler.on('style', compilerStyle);
compiler.on('dependency', addDependency)
compiler.compile(fileContent, filePath, function (err, result) {
compiler.removeListener('style', compilerStyle);
// result is a common js module string
if (err) {
reject(err);
} else {
resolve({
js: result,
css: style,
dependencies
});
}
});
});
}
ownDebugger('MyAsset');
class MyAsset extends JSAsset {
constructor(...args) {
super(...args);
if (compiler.options.extractCSS) {
this.type = 'css';
}
}
async parse(code) {
ownDebugger('parse');
// parse code to an AST
this.outputAll = await compilerPromise(this.contents, this.name);
this.outputCode = this.outputAll.js;
return await super.parse(this.outputCode);
}
collectDependencies() {
ownDebugger('collectDependencies');
for (let dep of this.outputAll.dependencies) {
this.addDependency(dep, {includedInParent: true});
}
// analyze dependencies
super.collectDependencies();
}
async generate() {
ownDebugger('generate');
let ret = await super.generate() || {};
ret.css = this.outputAll.css;
return ret;
}
}
module.exports = MyAsset;
|
import React from "react";
import axios from "axios";
import styled from "styled-components";
const CLOUDNAME = process.env.REACT_APP_CLOUDINARY_CLOUDNAME;
const PRESET = process.env.REACT_APP_CLOUDINARY_PRESET;
const StyledInput = styled.input`
width: 100%;
border-color: black;
padding: 5px;
`;
const StyledImage = styled.img`
display: flex;
margin-left: 2%;
margin-top: 2%;
margin-bottom: 10px;
width: 96%;
border-radius: 10px;
`;
const StyledLabel = styled.div`
margin-left: 5px;
font-size: 18px;
`;
export default function PicUploader({ image, onImageChange }) {
function upload(event) {
const url = `https://api.cloudinary.com/v1_1/${CLOUDNAME}/upload`;
const formData = new FormData();
formData.append("file", event.target.files[0]);
formData.append("upload_preset", PRESET);
axios
.post(url, formData, {
headers: {
"Content-type": "multipart/form-data"
}
})
.then(onImageSave)
.catch(err => console.error(err));
}
function onImageSave(response) {
onImageChange(response.data.url);
}
return (
<div>
{image && <StyledImage src={image} alt="" />}
<StyledLabel>
{image ? "Change picture" : "Add profile picture"}
</StyledLabel>
<StyledInput type="file" name="file" onChange={upload} />
</div>
);
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Fonction pour calculer la prime distance
* @param {integer} platFond
* @param {float} nbKilometres
* @returns {float}
*/
function calculPrimeDistance(platFond,nbKilometres)
{
return nbKilometres*0.01 <=platFond ? nbKilometres*0.01 :platFond;
}
/**
* Fonction pour calculer la prime anciennete
* @param {integer} nbanciennete
* @param {float} fixe
* @returns {float}
*/
function calculPrimeanciennete(nbanciennete,fixe)
{
return nbanciennete>=4 ? fixe+(nbanciennete>4?30*(nbanciennete-4):0):0;
}
/**
* Fonction pour calculer la prime annuel des employés
* @param {integer} platFond
* @param {float} nbKilometres
* @param {integer} nbanciennete
* @param {float} fixe
* @param {integer} nbAccidents
* @returns {float}
*/
function calculPrimeAnnuel(platFond,nbKilometres,nbanciennete,fixe,nbAccidents)
{
return nbAccidents<=3?(calculPrimeDistance(platFond,nbKilometres)+calculPrimeanciennete(nbanciennete,fixe))/ (nbAccidents+1):0;
} |
//會員群組Model
Ext.define("gigade.VipGroup", {
extend: 'Ext.data.Model',
fields: [
{ name: "group_id", type: "string" },
{ name: "group_name", type: "string" }]
});
//會員群組store
var VipGroupStore = Ext.create('Ext.data.Store', {
model: 'gigade.VipGroup',
autoLoad: true,
proxy: {
type: 'ajax',
url: "/Redirect/GetVipGroup",
actionMethods: 'post',
reader: {
type: 'json',
root: 'data'
}
}
});
function editRedirectFunction(row, store)
{
var editRedirectFrm = Ext.create('Ext.form.Panel', {
id: 'editRedirectFrm',
frame: true,
plain: true,
layout: 'anchor',
autoScroll: true,
labelWidth: 45,
url: '/Redirect/SaveRedirect',
defaults: { anchor: "95%", msgTarget: "side", labelWidth: 80 },
items: [
{
xtype: 'displayfield',
fieldLabel: '編號',
id: 'redirect_id',
name: 'redirect_id',
editable: false,
hidden: row == null ? true : false
},
{
xtype: 'textfield',
fieldLabel: "名稱",
allowBlank: false,
id: 'redirect_name',
name: 'redirect_name'
},
{
xtype: 'textfield',
fieldLabel: "目的連結",
name: 'redirect_url',
id: 'redirect_url',
labelWidth: 80,
submitValue: true,
vtype: 'url',
allowBlank: false
},
{
xtype: 'combobox', //會員群組
editable: false,
hidden: false,
fieldLabel: '會員綁定群組',
id: 'user_group_id',
name: 'user_group_id',
hiddenName: 'user_group_id',
store: VipGroupStore,
lastQuery: '',
displayField: 'group_name',
valueField: 'group_id',
typeAhead: true,
forceSelection: false,
value: "0",
hidden:true
},
{
xtype: 'radiogroup',
fieldLabel: "狀態",
id: 'redirect_status',
colName: 'redirect_status',
name: 'redirect_status',
defaults: {
name: 'redirect_status'
},
columns: 2,
vertical: true,
margin: '0 5',
items: [
{
id: 'normal',
boxLabel: "正常",
inputValue: '1',
width: 100
},
{
id: 'unnormal',
boxLabel: "停用" + "(<span style='color:red'>停用連結,一率導回首頁</span>)",
checked: true,
inputValue: '0'
}
]
},
{
xtype: 'displayfield',
fieldLabel: '群組',
id: 'group_name',
value:document.getElementById("group_name").value
},
{
xtype: 'textareafield',
fieldLabel: '備註',
id: 'redirect_note',
anchor: '100%'
},
{
xtype: 'displayfield',
fieldLabel: '建立日期',
id: 'sredirect_createdate',
hidden: row == null ? true : false
},
{
xtype: 'displayfield',
fieldLabel: '修改日期',
id: 'sredirect_updatedate',
hidden: row == null ? true : false
},
{
xtype: 'displayfield',
fieldLabel: '來源IP',
id: 'redirect_ipfrom',
hidden: row == null ? true : false
}
],
buttons: [{
text: '保存',
formBind: true,
disabled: true,
handler: function ()
{
var form = this.up('form').getForm();
if (form.isValid())
{
form.submit({
params: {
redirect_id: Ext.getCmp("redirect_id").getValue(),
redirect_name: Ext.getCmp("redirect_name").getValue(),
group_id: document.getElementById("group_id").value,
redirect_url: Ext.getCmp("redirect_url").getValue(),
user_group_id: Ext.getCmp("user_group_id").getValue(),
redirect_status: Ext.getCmp("redirect_status").getValue(),
redirect_note: Ext.getCmp("redirect_note").getValue()
},
success: function (form, action)
{
var result = Ext.decode(action.response.responseText);
if (result.success)
{
Ext.Msg.alert(INFORMATION, SUCCESS);
store.load();
editRedirectWin.close();
} else
{
Ext.Msg.alert(INFORMATION, FAILURE);
}
},
failure: function ()
{
Ext.Msg.alert(INFORMATION, FAILURE);
}
})
}
}
}]
});
var editRedirectWin = Ext.create('Ext.window.Window', {
title: row == null ? "連結新增" : "連結編輯",
id: 'editRedirectWin',
iconCls: row ? "icon-user-edit" : "icon-user-add",
layout: 'fit',
items: [editRedirectFrm],
constrain: true, //束縛窗口在框架內
closeAction: 'destroy',
modal: true,
resizable: true,
width: 600,
height: Ext.getCmp('editRedirectFrm').Height,
bodyStyle: 'padding:5px 5px 5px 5px',
closable: false,
tools: [
{
type: 'close',
qtip: CLOSE,
handler: function (event, toolEl, panel)
{
Ext.MessageBox.confirm(CONFIRM, IS_CLOSEFORM, function (btn)
{
if (btn == "yes")
{
Ext.getCmp('editRedirectWin').destroy();
}
else
{
return false;
}
});
}
}],
listeners: {
'show': function ()
{
if (row)
{
if (row)
{
editRedirectFrm.getForm().loadRecord(row);//為控件賦值
initForm(row);
}
else
{
editRedirectFrm.getForm().reset();
}
}
}
}
});
editRedirectWin.show();
function initForm(row)
{
switch (row.data.redirect_status)
{
case 1:
Ext.getCmp("normal").setValue(true);
break;
default:
Ext.getCmp("unnormal").setValue(true);
break;
}
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const DataAccess_1 = require("../DataAccess");
class ReportSchema {
static get schema() {
let schemaDefinition = {
name: {
type: String,
required: true,
trim: true,
min: 4,
max: 50
}
};
return DataAccess_1.DataAccess.initSchema(schemaDefinition);
}
}
exports.default = DataAccess_1.DataAccess.connection.model('Report', ReportSchema.schema);
|
import { createSelector } from 'reselect';
export const getSelectedVillage = (state) =>({ village: state.villageStore[state.selectedVillage] });
export const getVillages = ({ villages }) => ({ villages });
export const getUserProfile = ({ resources, username }) => ({ resources, username }); |
var fs = require("fs"),
path = require("path"),
async = require("async"),
expect = require("expect.js"),
wrench = require("wrench"),
Backup = require("../lib/Backup"),
src = path.join(__dirname, "src"),
dest = path.join(__dirname, "dest");
function initializeSourceFiles(backup, done) {
backup.clear(function (err) {
if (err) return done(err);
async.forEach([
[ "a.txt", "ABC" ],
[ "b.log", "123" ]
], function (file, done) {
fs.writeFile(path.join(backup.source, file[0]), file[1], done);
}, done);
});
}
describe("Backup", function () {
var backup = new Backup(src, dest);
before(function (done) {
async.forEach([ src, dest ], fs.mkdir, done);
});
after(function (done) {
async.forEach([ src, dest ], wrench.rmdirRecursive, done);
});
describe(".constructor", function () {
it("should initialize the source property", function () {
expect(backup).to.have.property("source", src);
});
it("should initialize the destination property", function () {
expect(backup).to.have.property("destination", dest);
});
});
describe("#list()", function () {
after(function (done) {
backup.clear(done);
});
it("should give an empty array when no restoration points available", function (done) {
backup.list(function (err, list) {
if (err) return done(err);
expect(list).to.be.an(Array);
done();
});
});
it("should return a list of date objects", function (done) {
backup.backup(function (err, date) {
if (err) return done(err);
backup.list(function (err, list) {
if (err) return done(err);
expect(list[0].getTime()).to.equal(date.getTime());
done();
});
});
});
it("should run callback in context of the backup object", function (done) {
backup.list(function (err) {
if (err) return done(err);
expect(this).to.equal(backup);
done();
});
});
});
describe("#backup()", function () {
before(function (done) {
initializeSourceFiles(backup, done);
});
after(function (done) {
backup.clear(done);
});
it("should create a new archive file", function (done) {
backup.backup(function (err, date) {
if (err) return done(err);
fs.exists(path.join(dest, date.getTime() + ".tar.gz"), function (exists) {
expect(exists).to.be.true;
done();
});
});
});
it("should run callback in context of the backup object", function (done) {
backup.backup(function (err) {
if (err) return done(err);
expect(this).to.equal(backup);
done();
});
});
});
describe("#restore()", function () {
beforeEach(function (done) {
initializeSourceFiles(backup, done);
});
after(function (done) {
backup.clear(done);
});
it("should restore the files as they were before the backup", function (done) {
async.waterfall([
function (done) {
fs.writeFile(path.join(src, "c.txt"), "Hello World", done);
},
function (done) {
fs.unlink(path.join(src, "a.txt"), done);
},
function (done) {
backup.backup(done);
},
function (date, done) {
backup.restore(date, done);
},
function (done) {
fs.exists(path.join(src, "a.txt"), function (exists) {
expect(exists).to.be.false;
done();
});
},
function (done) {
fs.readFile(path.join(src, "c.txt"), "utf8", function (err, contents) {
if (err) return done(err);
expect(contents).to.equal("Hello World");
done();
});
}
], done);
});
it("should accept a number instead of a date object", function (done) {
backup.backup(function (err, date) {
backup.restore(date.getTime(), done);
});
});
it("should accept a string instead of a date object", function (done) {
backup.backup(function (err, date) {
backup.restore(date.toString(), done);
});
});
it("should run callback in context of the backup object", function (done) {
async.waterfall([
function (done) {
backup.backup(done);
},
function (date, done) {
backup.restore(date, function (err) {
if (err) return done(err);
expect(this).to.equal(backup);
done();
});
}
], done);
});
});
describe("#remove()", function () {
beforeEach(function (done) {
var task = this;
backup.backup(function (err, date) {
if (err) return done(err);
task.date = date;
done();
});
});
it("should remove the target restore point", function (done) {
var date = this.date;
async.waterfall([
function (done) {
backup.remove(date, done);
},
function (done) {
backup.list(done);
},
function (list, done) {
expect(list).to.have.length(0);
done();
}
], done);
});
it("should run callback in context of the backup object", function (done) {
backup.remove(new Date(), function () {
expect(this).to.equal(backup);
done();
});
});
});
describe("#exists()", function () {
beforeEach(function (done) {
var task = this;
backup.backup(function (err, date) {
if (err) return done(err);
task.date = date;
done();
});
});
it("should check for a restore point with the given date object", function (done) {
backup.exists(this.date, function (exists) {
expect(exists).to.be.true;
done();
});
});
it("should run callback in context of the backup object", function (done) {
backup.exists(this.date, function () {
expect(this).to.equal(backup);
done();
});
});
});
describe("#clear()", function () {
before(function (done) {
backup.backup(done);
});
it("should clear out all the restore points", function (done) {
backup.clear(function (err) {
if (err) return done(err);
fs.readdir(dest, function (err, list) {
if (err) return done(err);
expect(list).to.be.empty();
done();
});
});
});
it("should run callback in context of the backup object", function (done) {
backup.clear(function () {
expect(this).to.equal(backup);
done();
});
});
});
});
|
function Vis(canvas) {
this._canvas = canvas;
this._ctx = canvas.getContext('2d');
this._colorFeed = undefined;
// Initialize the color grid.
this.grid = new Array(Vis.GRID_HEIGHT);
for (var r = 0; r < this.grid.length; r++) {
this.grid[r] = new Array(Vis.GRID_WIDTH);
for (var c = 0; c < this.grid[r].length; c++) {
this.grid[r][c] = Vis.DEFAULT_COLOR;
}
}
this.update = this.update.bind(this);
this.update();
return this;
}
Vis.GRID_WIDTH = 64;
Vis.GRID_HEIGHT = 24;
Vis.STEP_TIME = 500; // Milliseconds
Vis.CURRENT_COLOR_WEIGHT = 0.3;
Vis.OTHER_COLOR_WEIGHT = 0.7;
Vis.DEFAULT_COLOR = new Color(32, 0, 32);
Vis.prototype = {
/**
* Calculate the new color of a pixel.
* @param {Number} r - The row of the pixel
* @param {Number} c - The column of the pixel
*/
_calculateNewPixel(r, c) {
return new Color(this._calculateNewSubpixel(r, c, 'r'),
this._calculateNewSubpixel(r, c, 'g'),
this._calculateNewSubpixel(r, c, 'b'));
},
/**
* Calculate the new color of a subpixel.
* @param {Number} r - The row of the pixel containing the subpixel
* @param {Number} c - The column of the pixel containing the subpixel
* @param {String} sp - The subpixel: “r”, “g”, or “b”
*/
_calculateNewSubpixel(r, c, sp) {
var avgOtherColor = 0;
for (var row = r - 1; row <= r + 1; row++) {
for (var col = c - 1; col <= c + 1; col++) {
if (row === r && col === c) {
continue;
}
var wrappedRow = row,
wrappedCol = col;
if (wrappedRow < 0) {
wrappedRow = this.grid.length - 1;
} else if (wrappedRow >= this.grid.length) {
wrappedRow = 0;
}
if (wrappedCol < 0) {
wrappedCol = this.grid.length - 1;
} else if (wrappedCol >= this.grid.length) {
wrappedCol = 0;
}
avgOtherColor += this.grid[wrappedRow][wrappedCol][sp];
}
}
avgOtherColor /= 8;
return (this.grid[r][c][sp] * Vis.CURRENT_COLOR_WEIGHT) +
(avgOtherColor * Vis.OTHER_COLOR_WEIGHT);
},
_updateGrid: function () {
if (this._colorFeed) {
for (var r = this._colorFeed.row - 2; r <= this._colorFeed.row + 2; r++) {
for (var c = this._colorFeed.col - 2; c <= this._colorFeed.col + 2; c++) {
this.grid[r][c] = this._colorFeed.color;
}
}
}
var newGrid = new Array(Vis.GRID_HEIGHT);
for (var r = 0; r < this.grid.length; r++) {
newGrid[r] = new Array(Vis.GRID_WIDTH);
for (var c = 0; c < this.grid[r].length; c++) {
newGrid[r][c] = this._calculateNewPixel(r, c);
}
}
this.grid = newGrid;
},
_updateCanvas: function () {
var cellWidth = this._canvas.width / this.grid[0].length,
cellHeight = this._canvas.height / this.grid.length;
for (var r = 0; r < this.grid.length; r++) {
for (var c = 0; c < this.grid[r].length; c++) {
this._ctx.fillStyle = this.grid[r][c].rgb;
this._ctx.fillRect(c * cellWidth, r * cellHeight, cellWidth, cellHeight);
}
}
},
/**
* Add a splash of color in the center of the grid.
* @param {Number} polarity
* @param {Number} subjectivity
*/
setColorFeed: function (polarity, subjectivity) {
this._colorFeed = {
row: Math.round(Vis.GRID_HEIGHT / 2),
col: Math.max(2, Math.min(Vis.GRID_WIDTH - 3, Math.round(subjectivity * Vis.GRID_WIDTH))),
color: new Color(255 * (1 - polarity), 20 + 100 * polarity, 255 * polarity)
};
console.log(this._colorFeed);
},
/**
* Remove the color feed.
*/
clearColorFeed: function () {
this._colorFeed = undefined;
},
update: function () {
this._updateGrid();
this._updateCanvas();
setTimeout(this.update, Vis.STEP_TIME);
}
};
|
import './index.scss';
import React from 'react';
import {
TextField,
RaisedButton,
Divider
} from 'material-ui';
export default function RegistrationForm(props){
const {
fields: {email, password, passwordConfirmation},
handleSubmit,
submitting
} = props;
return <main>
<div className="app-container">
<section className="m-register">
<form onSubmit={handleSubmit}>
<div style={{backgroundColor: 'white'}}>
<TextField
hintText="Enter Email"
errorText={email.touched && email.error}
style={{display: 'block'}}
underlineStyle={{bottom: 0, borderBottom: 'none'}}
hintStyle={{left: 90}}
{...email}
/>
<Divider />
<TextField
hintText="Enter Password"
type="password"
errorText={password.touched && password.error}
style={{display: 'block'}}
underlineStyle={{bottom: 0, borderBottom: 'none'}}
hintStyle={{left: 70}}
{...password}
/>
<Divider />
<TextField
hintText="Confirm Password"
type="password"
errorText={passwordConfirmation.touched && passwordConfirmation.error}
style={{display: 'block'}}
underlineStyle={{bottom: 0, borderBottom: 'none'}}
hintStyle={{left: 63}}
{...passwordConfirmation}
/>
</div>
<div style={{marginTop: 50}}>
<RaisedButton
primary={true}
disabled={submitting}
label="Create Account"
onClick={handleSubmit}
/>
</div>
</form>
</section>
</div>
</main>
}
|
const mongoose = require("mongoose");
const course = mongoose.Schema({
courseNumber: {
type: String,
require: true
},
courseName: {
type: String,
require: true
},
year: {
type: Number,
require: true
},
semester:{
type: String,
require: true
},
registrationCode: {
type: String,
require: true
}
})
const attendaceSchema = mongoose.Schema({
date: {
type: Date,
require: true,
"default": new Date()
},
session: {
type: String,
require: true
},
course: {
type: course,
require: true
}
})
const student = mongoose.Schema({
studentId: {
type: String,
require: true,
unique: true
},
firstName: {
type: String,
require: true
},
lastName: {
type : String,
require: true
},
picture: {
data: Buffer,
contentType: String,
require: false
},
course: {
type: [course],
require: false
},
attendance: {
type: [attendaceSchema]
}
})
mongoose.model("Student", student); |
import React from 'react';
import { DatePicker, Form } from 'antd';
import moment from 'moment';
import styles from './index.less';
@Form.create()
class ConDate extends React.Component {
onChange = (date) => {
const {
onChange,
otherSelectData,
ruleDate = 'YYYY-MM-DD HH:mm:ss',
} = this.props; //otherData 用于解决表格行编辑带上其他参数
if (onChange) {
const data = date ? date.format(ruleDate) : '';
this.props.onChange(data, otherSelectData);
}
};
render() {
const {
formItemLayout = {
labelCol: { sm: { span: 6 } },
wrapperCol: { sm: { span: 18 } },
},
defValue,
disabled,
form,
required = false,
label = '',
id = 'date',
message = '请选择日期',
placeholder = '请选择日期',
validator,
disabledDate,
disabledTime,
formItemStyle,
formItemClass,
} = this.props;
let rules = [
{ required, message },
];
if (validator) {
rules.push({ validator });
}
const { getFieldDecorator } = form;
return (
<div>
<Form.Item
{...formItemLayout}
label={label}
style={formItemStyle}
className={formItemClass}
>
{getFieldDecorator(id, {
initialValue: defValue ? moment(defValue) : null,
rules,
onChange: this.onChange,
})(
<DatePicker
disabled={disabled}
style={{ width: '100%' }}
placeholder={placeholder}
disabledDate={disabledDate}
disabledTime={disabledTime}
/>,
)}
</Form.Item>
</div>
);
}
}
export default ConDate;
|
const { StringValue } = require('ddd-js')
class LocationName extends StringValue {
constructor (value) {
super(value, false)
}
}
module.exports = LocationName
|
// 'use strict';
// angular.module('beerMeApp')
// .controller('searchCtrl',function($scope,$http,searchResultsService,$location){
// $scope.submitSearch = function(beerName){
// $location.path('/searchResults/'+beerName);
// }
// }) |
/*
Class Tree: GameObject
COMPLETE: no
TODO: renderer
EXTRA: audio manager
*/
// dont forget (a ?? b)
class GameObject{ // with rudimentary physics & colliders
constructor(id = Math.round(1000000000 * Math.random()) ,type = "gameobject", quickIndex=0, transform=undefined,rigidbody=undefined,collider=undefined,renderer=undefined,audio=undefined,...connections){
this.transform=transform;
this.rigidbody=rigidbody;
this.collider=collider;
this.renderer=renderer;
this.audio=audio;
// joints
this.connections = connections; //OBJ <<?<< of ids or //objects// this to that connection (only one is neccessary)
this.tags; // multiple ex: enemy, spike, etc.
this.layer = 0;
this.id = id;
this.type = type; // "gameobject, nexttype, meteorite, player, rigidbody, etc." use indexof(n)==true?
// this.quickIndex = quickIndex; use if world uses a dictionary of keys for the obj.s
this.renderer = new Renderer();
return {
obj: this,
id:this.id // only use if id is secured
};
}
get physicsComponents(){
return [this.transform, this.rigidbody, this.collider];
}
// set setRenderer(r){ this.render = r; }
set col(v){ this.collider = v; }
get col(){ return this.collider; }
get connectionType(connector){
return connector.type;
}
get connectionInfo(connector){
return connector.info;
}
get connectionTypes(){
return this.connections.map(x => connectionType(x))
}
addConnection(connection){
this.connections.push(connection); // push id instead??
}
set joints(v){ this.connections = v; }
get joints(){ return this.connections; }
callibrateComponents(){
this.rigidbody.transform = this.transform;
this.collider.rigidbody = this.rigidbody;
for(c in this.connections){
c.base = this;
// pivot obj rigidbody
}
}
// updates are ordered by double value
// OR DO UPDATES BY: preupdate() returns delay amount relative to preupdate?
get updateChain(){
let chain = [];
let c = this.physicsComponents.map(x => x.updateChain);
for (i in c){ chain.push(...i); }
return chain;
}
render(display, renderer){
// maybe put the next line in f.js or display.js or main.js.diplay()?
// render based on vars in renderer & points on collider
// one or two rendered objs
// render connected gameobjects
// render connections: ie: a line, a bungy, a string, a parabola, etc.
}
};
/*
Gameobject
Position
Transforms
Rigidbody2d
Collider2d
Soft, Rigid, etc. body colliders
connectable joints
spring, rotational spring, rigid, wheel, etc. joints
*/ |
/**
* pfBrowser.js
*
* Este é o arquivo que contém as funções Java para
* controle do Browser
*
* @author Ubaldo H. Mattos
*/
//=======================================================================================================
// Tronks: Esta função fecha a aba do navegador onde está sendo executado o MIRA cine's viewer.
// Observação: Note que o comando window.close() é chamado duas vezes. Isto é devido ao navegador Firefox
// ser diferente dos outros navegadores e só permitir que se feche a janela após a execução do comando "netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');"
// Quaisquer dúvidas entre em contato com Tronks.
function popitup() {
newwindow=window.open('http://www.mira.med.br','name','height=564,width=1016');
if (window.focus) {newwindow.focus()}
return false;
}
//======================================================================================================= |
import Layout from './layout/Layout'
import QfUploadIcon from './common/qf-upload-icon'
export {
Layout,
QfUploadIcon
}
|
import { Component } from "./../component.component";
import { default as template } from "./pollution.component.html";
/**
* @type {Pollution}
*/
export class Pollution extends Component {
/**
* @constructor
* @param {City} city
* @param {Waqi} api
* @param {Hydrator} hydrator
*/
constructor(city, api, hydrator) {
super("pollution", template, [
city.get("pollution"),
api,
hydrator
]);
city.bind((city) => {
if (city.get("lat")) {
return this.byLatLng(city.get("lat"), city.get("lng"));
}
this.hydrator.deshydrate(this.model);
});
}
/**
* @param {Number} lat
* @param {Number} lng
*/
byLatLng(lat, lng) {
this.get(this.api.getGeolocationEndPoint(lat, lng), () => {
this.model.set("aqi", "-");
window.ui.dialog.alert(
"City", "<br>Can't get Pollution informations", "Retry", () => {
this.byLatLng(lat, lng);
}
).onconfirm();
this.render();
});
}
} |
import axios from 'axios';
//方法一
// export function request(config, success, fail) {
// //创建axios实例
// const instance1 = axios.create({
// baseURL: 'http://123.207.32.32:8000',
// timeout: 5000
// })
// instance1(config)
// .then(res => {
// success(res)
// })
// .catch(err => {
// fail(err)
// })
// }
//方法2
// export function request(config) {
// //创建axios实例
// const instance1 = axios.create({
// baseURL: 'http://123.207.32.32:8000',
// timeout: 5000
// })
// instance1(config.info)
// .then(res => {
// config.success(res)
// })
// .catch(err => {
// config.fail(err)
// })
// }
//方法3
export function request(config) {
const instance1 = axios.create({
baseURL: '/api',
timeout: 5000
})
//请求拦截器
instance1.interceptors.request.use(config => {
return config
}, err => {
console.log(err)
})
//响应拦截
instance1.interceptors.response.use(res => {
return res.data
}, err => {
console.log(err)
})
return instance1(config)
}
|
const request = require('request')
var getWeather = (lat, lng, callback) => {
request({
url: `https://api.darksky.net/forecast/1ba788b0f660699885450cbc6dba44e5/${lat},${lng}?exclude=hourly,daily&units=auto`,
json: true
}, (error, response, body) => {
if (!error && response.statusCode === 200) {
callback(undefined, {
temperature: body.currently.temperature,
apparentTemperature: body.currently.apparentTemperature
})
} else {
callback('Unable to fetch weather from the darksky.net server.')
}
})
}
// https://api.darksky.net/forecast/1ba788b0f660699885450cbc6dba44e5/42.6977082,23.3218675?exclude=hourly,daily&units=auto
module.exports.getWeather = getWeather |
'use strict'
const superagent = require('superagent')
const Discord = require('discord.js')
const bot = new Discord.Client()
const _TOKEN = INSERTYOURTOKEN
const _PREFIX = "+RS"
bot.on('ready', () => {
console.log('RuneStats Bot ready!')
})
bot.on('message', msg => {
//The bot ignores messages that don't start with the prefix or are from a bot
if (!msg.content.startsWith(_PREFIX) || msg.author.bot) {return}
let msgCommand = msg.content.split(" ")[1].toUpperCase()
let msgContent = msg.content.toUpperCase().replace('+RS '+msgCommand + " ", "")
if (msgCommand === 'HELP') {
console.log("Displaying help...")
let size = 23
let msgHelp = "```HELP"
+ '\n' + strStretch('StatsIron USERNAME', size) + '| ' + strStretch('Display IronMan Stats for USERNAME', size)
+ '\n' + strStretch('Stats USERNAME', size) + '| ' + strStretch('Display Stats for USERNAME', size)
+ '\n' + strStretch('StatsIronHard USERNAME', size) + '| ' + strStretch('Display IronMan Hardcore Stats for USERNAME', size)
+ "```"
msg.reply(msgHelp)
} else if (msgCommand ==='Hosts') {
} else if (msgCommand === 'OS') {
//TODO implement Old School
msg.reply("Old School functionality not implemented yet.")
} else {
if (msgCommand.startsWith('STATS')) {
if (!msgContent) {
msg.reply("Incorrect usage!")
return
} else {
msgContent.replace(" ", '_')
}
if (msgCommand === 'STATS') {
console.log("Ironman Stats Called...")
let statsLink = "http://services.runescape.com/m=hiscore/index_lite.ws?player=" + msgContent
displayStats(msg, statsLink, msgContent)
} else if (msgCommand === 'STATSIRON') {
console.log("Ironman Stats Called...")
let statsLink = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + msgContent
displayStats(msg, statsLink, msgContent)
} else if (msgCommand === 'STATSIRONHARD') {
console.log("Hardcore Ironman Stats Called...")
let statsLink = "http://services.runescape.com/m=hiscore_hardcore_ironman/index_lite.ws?player=" + msgContent
displayStats(msg, statsLink, msgContent)
}
}
}
})
function strMatch(str1, str2) {
if (str1.toUpperCase() === str2.toUpperCase()) {
return true
} else {
return false
}
}
function strStretch(str, size) {
while (str.length < size) {
str += " "
}
return str
}
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
function getSkillName(id) {
let skillNames = ['Overall','Attack','Defence','Strength','Constitution','Ranged','Prayer',
'Magic','Cooking','Woodcutting','Fletching','Fishing','Firemaking','Crafting','Smithing',
'Mining','Herblore','Agility','Thieving','Slayer','Farming','Runecrafting','Hunter',
'Construction','Summoning','Dungeoneering','Divination','Invention']
return skillNames[id];
}
function getSkillLvl(xp) {
let xpForLvl = [[100,14391160],[101,15889109],[102,17542976],[103,19368992],[104,21385073],
[105,23611006],[106,26068632],[107,28782069],[108,31777943],[109,35085654],[110,38737661],
[111,42769801],[112,47221641],[113,52136869],[114,57563718],[115,63555443],[116,70170840],
[117,77474828],[118,85539082],[119,94442737],[120,104273167]]
if (xp > 104273167) {
return '120'
}
for (let j=0; j<xpForLvl.length; j++) {
if (xp < xpForLvl[j][1]) {
return xpForLvl[j-1][0].toString()
}
}
}
function getSkillLvlInv(xp) {
let xpForLvl = [[121,83370445],[122,86186124],[123,89066630],[124,92012904],[125,95025896],
[126,98106559],[127,101255855],[128,104474750],[129,107764216],[130,111125230],[131,114558777],
[132,118065845],[133,121647430],[134,125304532],[135,129038159],[136,132849323],[137,136739041],
[138,140708338],[139,144758242],[140,148889790],[141,153104021],[142,157401983],[143,161784728],
[144,166253312],[145,170808801],[146,175452262],[147,180184770],[148,185007406],[149,189921255],[150,194927409]]
if (xp > 194927409) {
return '150'
}
for (let j=0; j<xpForLvl.length; j++) {
if (xp < xpForLvl[j][1]) {
return xpForLvl[j-1][0].toString()
}
}
}
function displayStats(msg, link, user) {
superagent.get(link)
.end((error, response) => {
if (error) {
msg.reply('There was an error while grabbing the stats for \'' + user + '\'. Please try again later.')
} else {
let statData = response.text.split('\n')
let row = []
let size = 15
let lvlSize = 6
let xpSize = 14
let rankSize = 6
let msgStats = "```" + '\n' + 'Displaying stats for: \'' + user + '\''
+ '\n' + strStretch('Skill', size) + '| ' + strStretch('Level', lvlSize) + '| ' + strStretch('Experience', xpSize) + '| ' + strStretch('Rank', rankSize)
for (let i = 0; i < 28; i++) {
row = statData[i].split(',')
if (row[2] >= 14391160 && i>0 && i<27) {
// Lvl is 100+
row[1] = getSkillLvl(row[2])
} else if (row[2] >= 83370445 && i == 27) {
row[1] = getSkillLvlInv(row[2])
}
row[2] = commaSeparateNumber(row[2])
msgStats += '\n' + strStretch(getSkillName(i), size) + '| ' + strStretch(row[1], lvlSize) + '| ' + strStretch(row[2], xpSize) + '| ' + strStretch(row[0], rankSize)
}
msgStats += '\n```'
msg.channel.sendMessage(msgStats)
}
});
}
bot.login(_TOKEN) |
import React, { useState, useEffect } from 'react'
import CardDatabase from './CardDatabase.js'
import DeckList from './DeckList.js'
const cardDB = [
{ id: 'd4k-001', name: 'Firat', type: 'seal',
pictureUrl: 'https://firebasestorage.googleapis.com/v0/b/smn-react.appspot.com/o/card_database%2Fs001%2F1.jpg?alt=media&token=fee399bc-13b9-412c-9c72-4a47c92db5b7' },
{ id: 'd4k-002', name: 'Golden Horn Unicorn', type: 'seal',
pictureUrl: 'https://firebasestorage.googleapis.com/v0/b/smn-react.appspot.com/o/card_database%2Fs001%2F2.jpg?alt=media&token=3ae7fc87-4680-40ed-9f9e-2e8325e42afb' },
{ id: 'd4k-003', name: 'Fairy Music Box', type: 'seal',
pictureUrl: 'https://firebasestorage.googleapis.com/v0/b/smn-react.appspot.com/o/card_database%2Fs001%2F3.jpg?alt=media&token=8541233e-fd96-4054-a4f1-75d8d25b77cf' },
{ id: 'exi-001', name: 'Thorny Lion', type: 'seal',
pictureUrl: 'https://firebasestorage.googleapis.com/v0/b/smn-react.appspot.com/o/card_database%2Fs002%2F1.jpg?alt=media&token=18244cfa-1802-4bb1-9601-681eb569a937' },
{ id: 'exi-002', name: 'Phoebus', type: 'seal', limit: 1,
pictureUrl: 'https://firebasestorage.googleapis.com/v0/b/smn-react.appspot.com/o/card_database%2Fs002%2F2.jpg?alt=media&token=7e3a340d-4a7c-4449-917d-a9db74f9e4d9' },
]
const BuildDeck = () => {
const [deckList, setDeckList] = useState([])
console.log(deckList)
return(
<div className="container">
<div className="row">
<div className="col-6 col-sm-4 col-md-3">
<DeckList cardDB={cardDB} deckList={deckList}/>
</div>
<div className="col-6 col-sm-8 col-md-9">
<CardDatabase cardDB={cardDB} deckList={deckList} setDeckList={setDeckList}/>
</div>
</div>
</div>
)
}
export default BuildDeck
|
import React from "react";
import fireApp from "../fire.js";
export function updateCharacter(characterObj) {
const ref = fireApp
.firestore()
.collection("games")
.doc(characterObj.gameId)
.collection("character");
let gameRef = ref
.doc(characterObj.characterId)
.update(characterObj)
.then(newRef => {
console.log("Updated character from gameid: ", newRef.id);
});
}
|
import {
ADD_MOVIE,
EDIT_MOVIE,
DELETE_MOVIE,
ADD_INIT_MOVIES
} from '../actionTypes'
const database = (state = {}, action) => {
switch (action.type) {
case ADD_MOVIE:
if (state.movies.some(movie => movie.imdbID === action.movie.imdbID)) {
return state
}
return { ...state, movies: [action.movie, ...state.movies] }
case EDIT_MOVIE:
return {
...state,
movies: state.movies.map(
movie => (movie.imdbID === action.imdbID ? action.newMovie : movie)
)
}
case DELETE_MOVIE:
return {
...state,
movies: state.movies.filter(movie => movie.imdbID !== action.imdbID)
}
case ADD_INIT_MOVIES:
return { ...state, movies: action.movies }
default:
return state
}
}
export default database
|
/********************************/
/**** template definitions ****/
/********************************/
Vue.component(
'pokedex-entry',
{
props: [
'entry'
],
template: `
<li class="list-group-item list-group-item-action">
<a :href="entry.detailsUrl"
class="pokedex-entry">
<img src="./images/pokeball.svg"
width="16px"
height="16px"/>
<span>
{{ entry.pokemonId }}
{{ entry.pokemonSpeciesName }}
</span>
<img src="./images/pokeball.svg"
width="16px"
height="16px"/>
</a>
</li>
`
}
);
/********************************/
/********************************/
/**** api access ****/
/********************************/
function parseResponseIntoPokedexEntries(
response
) {
let responseData = JSON.parse(
response
);
responseData.pokemon_entries.forEach(
( item ) => {
let pokedexEntry = {
pokemonId: item.entry_number,
pokemonSpeciesName: item.pokemon_species.name,
detailsUrl: detailsUrlForPokemon(
item.entry_number
)
};
pokedexEntries.push(
pokedexEntry
);
}
); // for each
// store the entries to avoid having
// to request them again
storeEntries(
pokedexEntries
);
} // parseResponseIntoPokedexEntries
function makeRequestForPokedex() {
let promise = makeRequestToApi(
apiPokedexUrl
);
return promise;
} // makeRequestForPokedex
/********************************/
/********************************/
/**** persistence ****/
/********************************/
function storeEntries(
pokedexEntries
) {
entryStringsByPokemonId = {};
pokedexEntries.forEach(
( entry ) => {
let entryString = JSON.stringify(
entry
);
// have to use object[ key ] notation
entryStringsByPokemonId[ entry.pokemonId ] = entryString;
}
); // for each
let storedEntries = JSON.stringify(
entryStringsByPokemonId
);
localStorage.setItem(
'pokedexEntries',
storedEntries
);
return;
} // storeEntries
// restores the entries and
// adds them to pokedex entries
function restoreEntries(
storedEntries
) {
// convert the stored entries
// from a string back to an object
// with the pokemonIds as keys and
// the stringified entries as values
let restoredEntries = JSON.parse(
storedEntries
);
// convert the entry strings back to
// objects and then add them to the
// pokedex entries
for (
let i = 1;
i <= 151;
i++
) {
// have to use object[ key ] notation
let entryString = restoredEntries[ i ];
let entry = JSON.parse(
entryString
);
pokedexEntries.push(
entry
);
} // loop
return;
} // restoreEntries
/********************************/
/********************************/
/**** domain ****/
/********************************/
function getPokedexEntries() {
let promise = new Promise(
function(
resolve,
reject
) {
let storedEntries = localStorage.getItem(
'pokedexEntries'
);
if (
storedEntries !== undefined
&& storedEntries !== null
) {
restoreEntries(
storedEntries
);
resolve();
return;
}
makeRequestToApi(
apiPokedexUrl
)
.then(
function( // accept callback
response
) {
parseResponseIntoPokedexEntries(
response
);
// could resolve entries and have
// another function display them...
resolve();
return;
} // accept callback
) // then
.catch(
function( // reject callback
reason
) {
console.error(
reason
);
reject(
reason
);
} // reject callback
); // catch
} // executor
); // promise
return promise;
} // getPokedexEntries
/********************************/
/********************************/
/**** execution ****/
/********************************/
var pokedexEntries = [];
// initialized to empty array
// avoid it being undefined
// when vue components access it
// root instance
new Vue(
{
el: '#app-container',
data: {
pages: pages,
currentPageId: 'pokedex',
entries: pokedexEntries
}
}
);
getPokedexEntries();
// asynchronously gets the pokedex entries
// either by restoring from local storage
// or by requesting from the api and then
// adds them to the pokedex entries
/********************************/
|
import Ember from 'ember';
export default Ember.Controller.extend({
projects: Ember.inject.service(),
actions: {
kubernetesReady() {
this.get('projects').updateOrchestrationState().then(() => {
this.transitionToRoute('k8s-tab.index');
});
},
}
});
|
Clients = new Mongo.Collection("clients");
Clients.attachSchema(new SimpleSchema({
cli_name : {
type: String,
optional : true,
},
cli_desc : {
type: String,
optional : true
},
cli_contact_name : {
type: String
},
cli_contact_phone : {
type: Number
},
cli_status: {
type: String,
autoform: {
type: "select",
options : function () {
return [
{label: "New", value: "N"},
{label: "Follow up", value: "F"},
{label: "Success", value: "S"}
];
}
}
},
cli_dt_status : {
type: Date,
optional: true
}
}));
Clients.allow({
insert: function(userId, doc){
return doc && doc.userId === userId;
},
update: function(userId, doc){
return doc && doc.userId === userId;
}
}) |
var searchData=
[
['zdepth_5fdecoder_2ecc',['zdepth_decoder.cc',['../zdepth__decoder_8cc.html',1,'']]],
['zdepth_5fdecoder_2eh',['zdepth_decoder.h',['../zdepth__decoder_8h.html',1,'']]],
['zdepth_5fencoder_2ecc',['zdepth_encoder.cc',['../zdepth__encoder_8cc.html',1,'']]],
['zdepth_5fencoder_2eh',['zdepth_encoder.h',['../zdepth__encoder_8h.html',1,'']]]
];
|
var x = (a, b) => {
return a + b;
}
console.log(x(7,78)); |
const { DEFAULT_DIR } = require('./constants')
const ARG_KEYS = [
/**
* the directory with env files
*/
'dir',
/**
* the file that be used as startup for the generator
*/
'target',
/**
* the path of the file that be generated.
*/
'output'
]
const REQUIRED_ARG_KEYS = ['target', 'output']
module.exports = function(commandArgs) {
let args = commandArgs.map(parseArg)
args = filterValidArgs(args)
let objArgs = {}
args.forEach(arg => {
objArgs[arg.key] = arg.value
})
validateArgs(objArgs)
hydrateArgs(objArgs)
return objArgs
}
function hydrateArgs(objArgs) {
objArgs.dir = objArgs.dir || DEFAULT_DIR
}
function validateArgs(objArgs) {
REQUIRED_ARG_KEYS.forEach(reqArg => {
if (!Object.keys(objArgs).includes(reqArg)) {
throw new Error(`ERROR: The argument '${reqArg}' is required.`)
}
})
}
function filterValidArgs(args) {
return args.filter(arg => {
return ARG_KEYS.includes(arg.key)
})
}
function parseArg(arg) {
const parts = arg.split('=')
return {
key: parts[0],
value: parts[1]
}
}
|
$(document).ready(function(){
$.ajax({
url:'/erp/rest/managermode/getaddmenu',
type:'get',
datatype:'json',
success:function(data){
console.log(data);
var str="";
for(var i in data.mList){
str+="<li><a id="+data.mList[i].f_functions+" onclick=menu('"+data.mList[i].f_functions+"')>"+data.mList[i].f_functions+"</a></li>";
if(data.mList[i].f_functions == "인사관리"){
if($("#myInfoMenu").length>0){
let menu = "";
menu += "<li><a href='/erp/myinfo/checkattendance'>출/퇴근 등록</a></li>";
menu += "<li><a href='/erp/myinfo/myPaycheck'>급여명세서 보기</li>";
menu += "<li><a href='/erp/myinfo/myattendance'>내 출결 보기</li>";
menu += "<li><a href='/erp/myinfo/myholiday'>내 휴가 보기</li>";
menu += "<li><a href='/erp/myinfo/applyholiday'>휴가신청</a></li>";
$("#myInfoMenu").html(menu);
console.log(menu);
}
}
}
str += "</ul>";
$("#mainmenu").html(str);
},
error:function(error){
console.log(error);
}
});
});
function menu(menu){
console.log(menu);
if(menu=="인사관리"){
$("#"+menu).attr("href","/erp/hr/hr");
}else if(menu=="영업관리"){
$("#"+menu).attr("href","/erp/sales/main");
}else if(menu=="구매관리"){
$("#"+menu).attr("href","/erp/Purchase/erpmain");
}else if(menu=="재고관리"){
$("#"+menu).attr("href","/erp/stock/basicstock");
}else if(menu=="회계관리"){
$("#"+menu).attr("href","/erp/Account/acerp");
}
}
function stockSideMenu(){
$.ajax({
url:"/erp/rest/home/getfunction",
type:"get",
dataType:"json",
success:function(result){
console.log(result)
$("#menuList").html(result);
},
error:function(err){
}
});
}
|
import Buttons from './Buttons'
import ButtonsSub from './ButtonsSub'
import React, { useState, useEffect } from 'react'
function SideBar() {
const [categorias, setCategorias] = useState([]);
const [open, setOpen] = useState(false)
const showSubMenu = () => setOpen(!open)
useEffect ( () => {
async function fetchData (){
const data = await fetch('http://www.pccomponents.com.ar/api/productos/cat')
const categoriasData = await data.json();
setCategorias(categoriasData)
}
;
fetchData();
}, [])
return (
<div className='sidebar'>
<Buttons name='Usuarios' path='/users'/>
<Buttons onClick={showSubMenu} name='Productos' path='/productos' />
<div className={open ? "open" : "close"}>
{categorias.map((cat) => {
return <ButtonsSub name={cat.nombre} path={`/productos/cat/${cat.id}`
} key={`${cat.nombre}${cat.id}`} />
})}
</div>
<Buttons name='Ventas' path='/ventas'/>
<Buttons name='Último Usuario' path='/ultimousuario'/>
<Buttons name='Último Producto' path='/ultimoproducto'/>
<Buttons name='Última Venta' path='/ultimaventa'/>
</div>
)
}
export default SideBar
|
import React from 'react';
import './Footer.css';
const Footer = () => {
return (
<div id="footer" className="navbar navbar-dark" style={{backgroundColor: 'rgba(220, 36, 36, 0.9)'}}>
<div>
<i className="fab fa-facebook fa-2x"></i>
<i className="fab fa-instagram fa-2x"></i>
<i className="fab fa-snapchat fa-2x"></i>
<i className="fab fa-medium fa-2x"></i>
<i className="fab fa-github fa-2x"></i>
</div>
</div>
);
}
export default Footer; |
$(document).ready(function(){
$("#btn1").click(function() {
navigator.notification.confirm(
'Please select one', // message
onConfirm, // callback to invoke with index of button pressed
'Hi', // title
['Beep','Vibrate'] // buttonLabels
);
});
$("#btn2").click(function() {
checkConnection();
});
});
function onConfirm(buttonIndex) {
if(buttonIndex == 1) {
// Beep twice!
navigator.notification.beep(2);
} else {
// Vibrate for 3 seconds
navigator.vibrate(3000);
}
}
function checkConnection() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.CELL] = 'Cell generic connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
} |
import React from "react";
import { Alert } from "reactstrap";
const NotFound = (props) => {
return (
<div>
<Alert color="danger">
<h5>Page Not Found 404 !</h5>
</Alert>
</div>
);
};
export { NotFound };
|
var group___avg_settings =
[
[ "HMC_AVG1", "group___avg_settings.html#ga0188f97ebf00a8af1cdaa587478d2a90", null ],
[ "HMC_AVG2", "group___avg_settings.html#ga2e2164befd111796e1a3bc17823600c5", null ],
[ "HMC_AVG4", "group___avg_settings.html#ga07c22d471bceae506c6fbef0d7400dbd", null ],
[ "HMC_AVG8", "group___avg_settings.html#gaa0195dbd0cfee3a554bb4464046ba781", null ]
]; |
const Session = require('./Session');
class SessionMananger {
constructor() {
this.sessions = {};
}
createSession(type) {
let session = new Session(type);
this.sessions[session.ID] = session;
return session;
}
joinSession(sessionID, wsClient) {
let session = this.getSession(sessionID);
session.clients.push(wsClient);
let clientID = sessionID+'.'+session.getNextClientID();
wsClient.ClientID = clientID;
wsClient.SessionID = sessionID;
return clientID;
}
removeClient(wsClient) {
let session = this.getSession(wsClient.SessionID);
let clientIndex = null;
let searchIndex = 0;
session.clients.forEach((client) => {
if (client.ClientID === wsClient.ClientID) {
clientIndex = searchIndex;
return false;
}
searchIndex++;
});
if (clientIndex === null) {
throw new Error('Client with ID '+wsClient.ClientID+' not found.');
}
session.clients.splice(clientIndex, 1);
if (session.clients.length === 0) {
console.log('All clients disconnected, ending session...');
this.endSession(wsClient.SessionID);
}
}
messageAllOtherClients(sessionID, messageBody, wsClient) {
let session = this.getSession(sessionID);
let senderClientID = wsClient.ClientID;
let sendCount = 0;
session.clients.forEach(function (client) {
if (client.ClientID !== senderClientID) {
client.send(messageBody);
sendCount++;
}
});
return sendCount;
}
getSession(sessionID) {
let session = this.sessions[sessionID];
if (!session) {
throw new Error('Session ID not found.');
}
return session;
}
endSession(sessionID) {
delete this.sessions[sessionID];
}
}
module.exports = SessionMananger;
|
import { connect } from 'react-redux';
import {Action} from '../../../../action-reducer/action';
import {getPathValue} from '../../../../action-reducer/helper';
import helper from '../../../../common/common';
import {fetchDictionary2, setDictionary2} from '../../../../common/dictionary';
import ChangeDialog from './ChangeDialog';
import showPopup from '../../../../standard-business/showPopup';
const STATE_PATH = ['temp'];
const action = new Action(STATE_PATH);
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH);
};
const cancelActionCreator = () => (dispatch) => {
dispatch(action.assign({visible: false}));
};
const okActionCreator = () => async (dispatch, getState) => {
const {value, controls} = getSelfState(getState());
if (!helper.validValue(controls, value)) {
dispatch(action.assign({valid: true}));
return;
}
dispatch(action.assign({confirmLoading: true}));
const body = {
...helper.convert(value),
newCarNumber: value.newCarInfoId.title,
newDriverName: value.newDriverId.title
};
const {returnCode, returnMsg} = await helper.fetchJson(`/api/dispatch/done/change`, helper.postOption(body));
if (returnCode !== 0) {
dispatch(action.assign({confirmLoading: false}));
helper.showError(returnMsg);
return;
}
dispatch(action.assign({visible: false, res: true}));
};
const searchActionCreator = (key, filter) => async (dispatch, getState) => {
const {value} = getSelfState(getState());
const ownerCarTag = Number(value.ownerCarTag);
let data, url, body, options=[];
switch (key) {
case 'newCarInfoId': {
url = '/api/dispatch/done/car_drop_list';
body = ownerCarTag === 1 ?
{maxNumber: 10, carNumber: filter, enabledType: 'enabled_type_enabled', isOwner: 1} :
{maxNumber: 10, carNumber: filter, enabledType: 'enabled_type_enabled', supplierId: value.supplierId.value};
data = await helper.fetchJson(url, helper.postOption(body));
break;
}
case 'newDriverId': {
url = '/api/dispatch/done/driver_drop_list';
body = ownerCarTag === 1 ?
{maxNumber: 10, diverName: filter, enabledType: 'enabled_type_enabled', isOwner: 1} :
{maxNumber: 10, diverName: filter, enabledType: 'enabled_type_enabled', supplierId: value.supplierId.value};
data = await helper.fetchJson(url, helper.postOption(body));
break;
}
default:
return;
}
if (data.returnCode === 0) {
options = data.result;
}
dispatch(action.update({options}, 'controls', {key:'key', value: key}));
};
const changeActionCreator = (key, value) => async (dispatch, getState) => {
const selfState = getSelfState(getState());
const ownerCarTag = Number(selfState.value.ownerCarTag);
let data, url, obj;
obj = {[key]: value};
switch (key) {
case 'newCarInfoId': {
obj.newDriverId = '';
obj.newDriverMobilePhone = '';
obj.newSupplierId = '';
if (value) {
url = `/api/dispatch/done/car_info/${value.value}`;
data = await helper.fetchJson(url);
if (data.returnCode === 0) {
obj.newDriverId = data.result.driverId;
if (ownerCarTag === 1) {
obj.newSupplierId = data.result.supplierId;
}else {
obj.newSupplierId = selfState.value.supplierId;
}
url = `/api/dispatch/done/driver_info/${obj.newDriverId.value}`;
data = await helper.fetchJson(url);
if (data.returnCode === 0) {
obj.newDriverMobilePhone = data.result.driverMobilePhone;
}
}
}
break;
}
case 'newDriverId': {
obj.newDriverMobilePhone = '';
if (value) {
url = `/api/dispatch/done/driver_info/${value.value}`;
data = await helper.fetchJson(url);
if (data.returnCode === 0) {
obj.newDriverMobilePhone = data.result.driverMobilePhone;
}
}
break;
}
}
dispatch(action.assign(obj, 'value'));
};
const exitValidActionCreator = () => (dispatch) => {
dispatch(action.assign({valid: false}));
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const actionCreators = {
onOk: okActionCreator,
onCancel: cancelActionCreator,
onChange: changeActionCreator,
onSearch: searchActionCreator,
onExitValid : exitValidActionCreator,
};
const buildDialogState = async (data) => {
const config = {
title: '变更车辆及司机',
ok: '确定',
cancel: '取消',
controls: [
{key: 'supplierId', title: '供应商', type: 'readonly'},
{key: 'newSupplierId', title: '新供应商', type: 'readonly'},
{key: 'ownerCarTag', title: '是否自有车', type: 'readonly', dictionary: 'zero_one_type'},
{key: 'carNumber', title: '车牌号码', type: 'readonly'},
{key: 'newCarInfoId', title: '新车牌', type: 'search', required: true},
{key: 'driverName', title: '司机', type: 'readonly'},
{key: 'newDriverId', title: '新司机', type: 'search', props:{searchWhenClick: true}, required: true},
{key: 'driverMobilePhone', title: '司机电话', type: 'readonly'},
{key: 'newDriverMobilePhone', title: '新司机电话', type: 'readonly'},
{key: 'trackingInformation', title: '变更原因', type: 'textArea', span: 2, required: true},
],
hideControls: Number(data.ownerCarTag) === 1 ? [] : ['newSupplierId']
};
const dic = await fetchDictionary2(config.controls);
setDictionary2(dic.result, config.controls);
global.store.dispatch(action.create({
...config,
value: data,
visible: true,
confirmLoading: false,
}));
};
/*
* 功能:变更车辆和司机对话框
* 参数:data: 【必需】待变更的记录信息
* 返回值:成功返回true,取消或关闭时返回空
*/
export default async (data) => {
await buildDialogState(data);
const Container = connect(mapStateToProps, actionCreators)(ChangeDialog);
return showPopup(Container, {}, true);
};
|
/**
* PurgeEditTally.js
* @file For whatever reason, the Oasis user page masthead edit count tally
* (try saying that quickly) does not update itself quickly the way the
* contribs page tally does. This script forces a purge upon navigating to
* a user page in Oasis.
* @author Eizen <dev.wikia.com/wiki/User_talk:Eizen>
* @external "jQuery"
* @external "wikia.ui.factory"
* @external "wikia.window"
* @external "mw"
*/
/*jslint browser, this:true */
/*global mw, jQuery, window, require, wk */
require(["mw", "wikia.window"], function (mw, wk) {
"use strict";
if (
!jQuery("#UserProfileMasthead").exists() ||
wk.wgNamespaceNumber !== 2
) {
return;
}
var PurgeEditTally = {
reload: function () {
jQuery(".contributions-details")
.load(
window.location.href + " .contributions-details > *",
function () {
mw.hook("refreshedMasthead").fire();
}
);
},
purgePage: function () {
var that = this;
jQuery.ajax({
type: "GET",
url: mw.util.wikiScript("api"),
data: {
action: "purge",
titles: wk.wgPageName
}
}).done(function () {
that.reload();
});
}
};
mw.loader.using("mediawiki.util").then(
jQuery.proxy(PurgeEditTally.purgePage, PurgeEditTally)
);
}); |
var express = require('express');
var bodyParser = require('body-parser');
var eventRouter = express.Router();
var SocialEventModel = require('../models/social-event');
var UserModel = require('../models/users');
eventRouter.use(bodyParser.json());
eventRouter.route('/events')
// Get all the Upcoming Eventsto populate informationt to client
.get(function(req,res,next){
SocialEventModel.find({},function(err,events){
if(err){
return console.log(err);
} else {
res.json(events);
}
});
});
eventRouter.route('/register/:id/:username')
.post(function(req,res,next){
UserModel.find({"username" : req.params.username}, function(err, user){
SocialEventModel.update( {_id: req.params.id},{$push: {"people_registered": {$each: user}}},
function(err, classroom) {
if(err){
console.log(err);
return res.status(500).send()
} else {
return res.json(classroom);
}
});
});
});
module.exports = eventRouter;
|
Ext.application({
extend: 'MyCVApp.Application',
name: 'MyCVApp'
}) |
import React, { Component } from 'react';
import Comment from './Comment.js';
export default class CommentsSection extends Component {
render() {
//map the comments into an array of elements to display
let{comments} = this.props;
let renderedComments = [];
console.log("comment-section");
if(comments){
renderedComments= comments.map(item=>{return <Comment key={item.id} comment={item}/>});
}
return (
<div className="comments-section">
{renderedComments}
</div>
)
}
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles, createStyleSheet } from 'material-ui/styles';
import Typography from 'material-ui/Typography';
import List, { ListItem } from 'material-ui/List';
const styleSheet = createStyleSheet('InstituteResults', theme => ({
bg: {
backgroundColor: theme.default.color,
textAlign: window.screen.width < 800 ? 'center' : 'left'
},
listItem: {
backgroundColor: theme.defaultDarken.color,
marginBottom: 10,
},
text: {
maxWidth: '100%',
flex: 5
},
icon: {
textAlign: window.screen.width < 800 ? 'center' : 'left',
fontWeight: 'bold',
backgroundColor: "#ED6D2C",
color: 'white',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 20,
fontSize: 20,
marginRight: 20,
flex: 1
},
title: {
textTransform: 'uppercase',
textAlign: window.screen.width < 900 ? 'center' : 'left',
fontWeight: 700,
marginTop: '2rem'
}
}));
class InstituteResults extends Component {
render() {
const { classes } = this.props;
return (
<div className="content-wrapper">
<div className="container padding">
<Typography type="headline" color="#ED6D2C" className={classes.title} gutterBottom>
Resultados
</Typography>
<List>
<ListItem className={classes.listItem}>
<Typography className={classes.icon}>+4 mil</Typography>
<Typography type="subheading" color="inherit" className={classes.text}>
horas de voluntariado
</Typography>
</ListItem>
<ListItem className={classes.listItem}>
<Typography className={classes.icon}>+450 mil</Typography>
<Typography type="subheading" color="inherit" className={classes.text}>
reais injetados nas economias locais
</Typography>
</ListItem>
<ListItem className={classes.listItem}>
<Typography className={classes.icon}>+500</Typography>
<Typography type="subheading" color="inherit" className={classes.text}>
voluntárixs
</Typography>
</ListItem>
<ListItem className={classes.listItem}>
<Typography className={classes.icon}>+150</Typography>
<Typography type="subheading" color="inherit" className={classes.text}>
micronegócios em nosso programa de capacitação profissional
</Typography>
</ListItem>
<ListItem className={classes.listItem}>
<Typography className={classes.icon}>+40</Typography>
<Typography type="subheading" color="inherit" className={classes.text}>
expedições pelo país
</Typography>
</ListItem>
<ListItem className={classes.listItem}>
<Typography className={classes.icon}>+6</Typography>
<Typography type="subheading" color="inherit" className={classes.text}>
comunidades brasileiras
</Typography>
</ListItem>
</List>
</div>
</div>
);
}
}
InstituteResults.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styleSheet)(InstituteResults);
|
import React from "react";
import { connect } from "react-redux";
/*
Loading component to show loading message to indicate user that images are currently loading and it will render
on loading set to true or false condition that is again coming from reducer as it receives the action the condition
will be set to true and as the saga will dispatch next action on that condition will be set to false as images are
loaded now.
*/
let Loading = ({ loading }) =>
loading ? (
<div style={{ textAlign: "center" }}>
<h1>LOADING...</h1>
</div>
) : null;
const mapStateToProps = (state) => ({ loading: state.ImageReducer.loading });
Loading = connect(mapStateToProps, null)(Loading);
export default Loading;
|
//jshint esversion:6
const express = require("express") ;
const app = express() ;
app.get("/",(request,response)=>{
response.header("plain/text");
response.send("Hello!") ;
});
app.get("/contact",(request,response)=>{
response.header("plain/text");
response.send("Contact me!") ;
});
app.get("/hobbies",(request,response)=>{
response.header("plain/text");
response.send("I drive!") ;
});
app.get("/aboutme",(request,response)=>{
response.header("plain/text");
response.send("I Am John") ;
});
app.listen(3000, () => {
console.log("listening!") ;
}) ;
|
function insert(item, user, request) {
request.execute();
switch (item.ClientType) {
case 0:
// apple push
push.apns.send(item.Identifier, {
alert: item.Message,
payload: {
inAppMessage: item.Message
}
});
break;
case 1:
// gcm (android push)
push.gcm.send(item.Identifier, item.Message, {
success: function(response) {
console.log('Push notification sent: ', response);
}, error: function(error) {
console.log('Error sending push notification: ', error);
}
});
break;
case 2:
// mpns (windows phone)
push.mpns.sendToast(item.Identifier, {
text1: "New Toast",
text2: item.Message
}, {
success: function (pushResponse) {
console.log("Sent push:", pushResponse);
}
});
break;
case 3:
// wns (windows 8)
push.wns.sendToastText04(item.Identifier, {
text1: item.Message
}, {
success: function(pushResponse) {
console.log("Sent push:", pushResponse);
}
});
break;
}
} |
let master_text = "";
let words = ["Smart", "Kind", "Amazing", "Bold", "Strong", "Confident",
"Ambitious", "Brave", "Cool", "Funny"];
let input, button, greeting;
let submit_remove = 0;
let canvas;
let gifLength = 5;
let started = 0;
function setup() {
var p5Canvas = createCanvas(windowWidth, windowHeight);
canvas = p5Canvas.canvas;
// frameRate(5);
input = createInput();
input.position(20, 230);
button = createButton('submit');
button.position(input.x + input.width, 230);
button.mousePressed(update_words);
fill(255);
greeting = createElement('h2', 'What is your name?');
greeting.style('color', '#ff0000');
greeting.position(20, 180);
//createCanvas(windowWidth, windowHeight);
frameRate(5);
//capturer.start();
}
function add_buttons_back(){
input = createInput();
input.position(20, 105);
button = createButton('submit');
button.position(input.x + input.width, 350);
button.mousePressed(update_words);
fill(255);
greeting = createElement('h2', 'What is your name?');
greeting.style('color', '#ff0000');
greeting.position(20, 100);
}
function save_photo(){
save('pix.jpg');
}
function save_video(){
if(started != 1){
capturer.start();
started = 1;
console.log("Starting to save");
greeting.remove();
input.remove();
button.remove();
submit_remove = 1;
}
draw() ;
}
function update_words(){
const name = input.value();
words.push(name);
greeting.remove();
input.remove();
button.remove();
submit_remove = 1;
}
let count = 0;
function draw() {
background(0);
console.log("sadfsad");
fill(random(255), random(255), 10);
textSize(30);
translate(width/2, height/2);
let ystep = 10;
let lastx = 20;
let lasty = 50;
let y = 50;
let border = 20;
for (var x=border; x<=width-border; x+=10) {
ystep = random(10)-15;
y += ystep;
line(x, y, lastx, lasty);
lastx = x;
lasty = y;
text(master_text, 0,0);
text(words[int(random(words.length-1))],x+50,y);
text(words[int(random(words.length-1))],x,y+50);
rotate(y);
}
if(started === 1 && count < 50){
//capturer.start();
capturer.capture(canvas);
count++;
console.log("started to capture");
}else if (started === 1) {
capturer.stop();
capturer.save();
started = 0;
count = 0;
console.log("done");
add_buttons_back();
}
console.log("sdf");
}
//add this function make the text be dynamic
function keyReleased() {
if (keyCode==8) {
if (master_text.length>0) {
master_text = master_text.substring(0, master_text.length-1);
}
}
else if (keyCode>=65 && keyCode<=90 || keyCode==32 || keyCode==54) {
master_text += str(key);
}else if(keyCode == ENTER || keyCode == RETURN){
console.log("hi");
master_text = master_text + " " + master_text;
}
}
|
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import {saveAs} from 'file-saver'
import XLSX from 'xlsx'
function s2ab (s) {
var buf = new ArrayBuffer(s.length)
var view = new Uint8Array(buf)
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
return buf
}
function datenum (v, date1904) {
if (date1904) v+=1462
var epoch = Date.parse(v)
return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000)
}
function sheet_from_array_of_arrays (data) {
var ws = {}
var range = {s: {c:10000000, r:10000000}, e: {c:0, r:0}}
for (var R = 0; R != data.length; ++R) {
for (var C = 0; C != data[R].length; ++C) {
if (range.s.r > R) range.s.r = R
if (range.s.c > C) range.s.c = C
if (range.e.r < R) range.e.r = R
if (range.e.c < C) range.e.c = C
var cell = {v: data[R][C]}
if (cell.v == null) continue
var cell_ref = XLSX.utils.encode_cell({c:C, r:R})
if (typeof cell.v === 'number') cell.t = 'n'
else if (typeof cell.v === 'boolean') cell.t = 'b'
else if (cell.v instanceof Date) {
cell.t = 'n'; cell.z = XLSX.SSF._table[14]
cell.v = datenum(cell.v)
} else cell.t = 's'
ws[cell_ref] = cell
const dataCopyList = JSON.parse(JSON.stringify(data));
dataCopyList.shift();
ws['!cols'] = dataCopyList.map(dataCopy => {
return {
wpx: dataCopy
.map(value => String(value))
.reduce((a, b) => a.length > b.length ? a : b)
.length * 6.5 + 20
}
});
}
}
if (range.s.c < 10000000) ws['!ref'] = XLSX.utils.encode_range(range)
return ws
}
export class Column extends Component { // eslint-disable-line react/require-render-return
static propTypes = {
label: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]).isRequired
}
render () {
throw new Error('<Column/> is not meant to be rendered.')
}
}
export class Sheet extends Component { // eslint-disable-line react/require-render-return
static propTypes = {
name: PropTypes.string.isRequired,
data: PropTypes.oneOfType([
PropTypes.array,
PropTypes.func
]).isRequired,
children: PropTypes.arrayOf((propValue, key) => {
const type = propValue[key].type
if (type !== Column) {
throw new Error('<Sheet> can only have <Column>\'s as children. ')
}
}).isRequired
}
render () {
throw new Error('<Sheet/> is not meant to be rendered.')
}
}
export class Workbook extends Component {
static propTypes = {
filename: PropTypes.string,
element: PropTypes.any,
beforeDownload: PropTypes.func,
children: function (props, propName, componentName) {
React.Children.forEach(props[propName], child => {
if (child.type !== Sheet) {
throw new Error('<Workbook> can only have <Sheet>\'s as children. ')
}
})
}
}
constructor (props) {
super(props)
this.download = this.download.bind(this)
this.createSheetData = this.createSheetData.bind(this)
}
createSheetData (sheet) {
const columns = sheet.props.children
const sheetData = [React.Children.map(columns, column => column.props.label)]
const data = typeof(sheet.props.data) === 'function' ? sheet.props.data() : sheet.props.data
data.forEach(row => {
const sheetRow = []
React.Children.forEach(columns, column => {
const getValue = typeof(column.props.value) === 'function' ? column.props.value : row => row[column.props.value]
sheetRow.push(getValue(row) || '')
})
sheetData.push(sheetRow)
})
return sheetData
}
download () {
if (this.props.beforeDownload !== undefined && this.props.beforeDownload !== null) {
this.props.beforeDownload()
}
const wb = {
SheetNames: React.Children.map(this.props.children, sheet => sheet.props.name),
Sheets: {}
}
React.Children.forEach(this.props.children, sheet => {
wb.Sheets[sheet.props.name] = sheet_from_array_of_arrays(this.createSheetData(sheet))
})
const wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'binary'})
saveAs(new Blob([s2ab(wbout)], {type:"application/octet-stream"}), this.props.filename || 'data.xlsx')
}
render () {
return (
<span onClick={this.download}>
{this.props.element ? this.props.element : "Download"}
</span>
)
}
}
Workbook.Column = Column
Workbook.Sheet = Sheet
export default Workbook
|
function runTest()
{
FBTest.progress("using baseLocalPath: " + baseLocalPath);
// Compute relative path and construct module loader.
var baseUrl = baseLocalPath + "loader/paths/";
var config = {
context: baseUrl + Math.random(), // to give each test its own loader,
baseUrl: baseUrl,
xhtml: true,
};
var require = FBTest.getRequire();
require(config, ["add", "subtract"], function(AddModule, SubtractModule)
{
FBTest.compare(3, AddModule.add(1, 2), "The add module must be properly loaded");
FBTest.compare(2, SubtractModule.subtract(3, 1), "The subtract module must be properly loaded");
FBTest.testDone();
});
}
|
import Apify from 'apify';
import { inspect } from 'util';
import { handleFailedRequest } from './lib/handleFailedRequest.js';
import { handlePage } from './lib/handlePage.js';
import { convertDetailedOutputToSimplified } from './lib/utils.js';
const { log } = Apify.utils;
const env = Apify.getEnv();
Apify.main(async () => {
/** @type {import('./types').PuppeteerActorInput} */
// @ts-expect-error It's not null
const input = await Apify.getInput();
// Log the input
// Log the input
log.info('Input provided:');
log.debug(inspect(input, false, 4));
log.info('Running a Puppeteer Checker.');
const {
maxConcurrentPagesCheckedPerDomain,
maxNumberOfPagesCheckedPerDomain,
proxyConfiguration,
urlsToCheck,
repeatChecksOnProvidedUrls,
retireBrowserInstanceAfterRequestCount,
'puppeteer.useChrome': useChrome,
'puppeteer.headfull': headfull,
} = input;
const proxy = await Apify.createProxyConfiguration({
groups: proxyConfiguration.apifyProxyGroups,
countryCode: proxyConfiguration.apifyProxyCountry,
});
const requestQueue = await Apify.openRequestQueue();
const [urlData] = urlsToCheck;
await requestQueue.addRequest({ ...urlData });
for (let _ = 0; _ < (repeatChecksOnProvidedUrls ?? 0); _++) {
await requestQueue.addRequest({
...urlData,
uniqueKey: Math.random().toString(),
});
}
/** @type {import('../../common/types').ActorCheckDetailedOutput} */
const state = {
url: urlData.url,
checkerType: 'puppeteer',
simplifiedOutput: `https://api.apify.com/v2/key-value-stores/${env.defaultKeyValueStoreId}/records/OUTPUT?disableRedirect=true`,
detailedOutput: `https://api.apify.com/v2/key-value-stores/${env.defaultKeyValueStoreId}/records/DETAILED-OUTPUT?disableRedirect=true`,
totalPages: [],
timedOut: [],
failedToLoadOther: [],
accessDenied: [],
success: [],
statusCodes: {},
recaptcha: [],
distilCaptcha: [],
hCaptcha: [],
};
const crawler = new Apify.PuppeteerCrawler({
maxRequestRetries: 0,
maxRequestsPerCrawl: maxNumberOfPagesCheckedPerDomain,
maxConcurrency: maxConcurrentPagesCheckedPerDomain,
requestQueue,
handlePageFunction: (pageInputs) => handlePage(input, requestQueue, state, pageInputs),
handleFailedRequestFunction: (requestInput) => handleFailedRequest(state, requestInput),
proxyConfiguration: proxy,
useSessionPool: false,
launchContext: {
stealth: true,
useChrome,
launchOptions: {
// @ts-expect-error Issue in the typings of apify
headless: headfull ? undefined : true,
},
},
// @ts-expect-error Might need to correct the typings for this somewhere (probably in apify)
browserPoolOptions: {
retireBrowserAfterPageCount: retireBrowserInstanceAfterRequestCount,
},
});
await crawler.run();
await Apify.setValue('OUTPUT', convertDetailedOutputToSimplified(state));
await Apify.setValue('DETAILED-OUTPUT', state);
log.info('Checker finished.');
log.info(
`Simplified output: https://api.apify.com/v2/key-value-stores/${env.defaultKeyValueStoreId}/records/OUTPUT?disableRedirect=true`,
);
log.info(
`Detailed output: https://api.apify.com/v2/key-value-stores/${env.defaultKeyValueStoreId}/records/DETAILED-OUTPUT?disableRedirect=true`,
);
log.info(`Preview dataset: https://api.apify.com/v2/datasets/${env.defaultDatasetId}/items?clean=true&format=html`);
});
|
export const FETCH_USER = 'fetch_user';
export const FETCH_USERSD = 'fetch_usersd';
export const FETCH_USERD = 'fetch_userd';
export const DELETE_USER = 'delete_user'
|
import TRAINING from "../mode/training.mode";
import VERSUS from "../mode/versus.mode";
import SELECTING_CHARACTER from "../sideState/selectingCharacter.state";
import SELECTING_COLOR from "../sideState/selectingColor.state";
import SELECTED from "../sideState/selected.state";
import TRAINING_SELECTING_CHARACTER_TWO from "../state/trainingSelectingCharacterTwo.state";
import VERSUS_SELECTING_STAGE from "../state/versusSelectingStage.state";
export default function selectCharacterOneColor(data, action) {
if (data.leftSideState !== SELECTING_COLOR) {
throw new Error(`Unable to select character one color in state: ${data.state}`);
}
const newData = {
...data,
characterOneColorIndex: action.colorIndex,
leftSideState: SELECTED
};
if (newData.mode === TRAINING) {
newData.state = TRAINING_SELECTING_CHARACTER_TWO;
newData.rightSideState = SELECTING_CHARACTER;
return newData;
}
if (newData.mode === VERSUS) {
if (newData.rightSideState === SELECTED) {
newData.state = VERSUS_SELECTING_STAGE;
}
return newData;
}
throw new Error(`Unable to select character one color in state: ${data.state}`);
}
|
import Crater from './crater';
export const batchActions = (...actions) => ({
type: 'BATCH_ACTIONS',
payload: actions,
});
export const subscribe = (name, params) => dispatch => new Promise((resolve, reject) => {
let subId = Crater.subscribe(name, params, (error) => {
error && reject(error);
!error && resolve(subId);
});
dispatch({
type: 'SET_STATUS',
payload: 'Loading',
});
});
export const unsubscribe = (subId) => (dispatch, getState) => {
Crater.unsubscribe(subId);
};
|
import React from 'react'
import "./contactDetail.css"
import {FaWhatsapp,FaMobile,FaMailBulk} from "react-icons/fa"
import Contact from './Contact'
const Card =(props)=>{
return (
<div className="contactDet_cardContainer">
<div className="contactDet_icon">
{props.icon}
</div>
<h3>{props.text}</h3>
</div>
)
}
const ContactDetail = () => {
return (
<div className="contacDetail">
<div className="contactDetail_container">
<Card icon={<FaMobile/>} text={"+91 7015500526"}/>
<Card icon={<FaWhatsapp/>} text="+91 7015500526"/>
<Card icon={<FaMailBulk/>} text="prakashkumartekari@gmail.com"/>
</div>
<Contact text={"Send Enquiry"}/>
</div>
)
}
export default ContactDetail
|
import '../styles/style.scss';
// getting all the specific ids and storing in variable
const mensOutwearElement = document.querySelectorAll(
'#mens-outwear-tab, #mens-outwear-btn'
);
const ladiesOutwearElement = document.querySelectorAll(
'#ladies-outwear-tab, #ladies-outwear-btn'
);
const mensTshirtElement = document.querySelectorAll(
'#mens-tshirt-tab, #mens-tshirt-btn'
);
const ladiesTshirtElement = document.querySelectorAll(
'#ladies-tshirt-tab, #ladies-tshirt-btn'
);
// iterating through above created variables and adding event listener
for (let ele of mensOutwearElement) {
ele.addEventListener('click', e => {
togglePage(e, 'mens-outwear-block');
});
}
for (let ele of ladiesOutwearElement) {
ele.addEventListener('click', e => {
togglePage(e, 'ladies-outwear-block');
});
}
for (let ele of mensTshirtElement) {
ele.addEventListener('click', e => {
togglePage(e, 'mens-tshirt-block');
});
}
for (let ele of ladiesTshirtElement) {
ele.addEventListener('click', e => {
togglePage(e, 'ladies-tshirt-block');
});
}
// toggle function to switch between tabs
function togglePage(e, page) {
// for smooth scrolling when click on button or links
window.scroll({
top: 0,
left: 0,
behavior: 'smooth'
});
// variabke for tabs
const tablinks = document.getElementsByClassName('tablinks');
// variable for blocks
const blockContent = document.getElementsByClassName('blocks');
// setting all blocks content to display to hide
for (let element of blockContent) {
element.style.display = 'none';
}
// iterating through each tablinks and removing class to reset sytles
for (let tab of tablinks) {
tab.className = tab.className.replace(' active', '');
tab.className = tab.className.replace(' aniAttribute', '');
tab.style.border = 'none';
tab.style.borderBottom = '1px transparent solid';
}
// adding classes based on element click
document.getElementById(page).style.display = 'block';
e.currentTarget.className += ' active';
e.currentTarget.className += ' aniAtribute';
}
// Snackbar Function
function snackbarFunction() {
console.log('triggered');
var snackbarElement = document.getElementById('snackbar');
snackbarElement.className = 'show';
setTimeout(function() {
snackbarElement.className = snackbarElement.className.replace('show', '');
}, 2000);
}
// document.querySelector('.hot-link');
for (let ele of document.querySelectorAll('.hot-link')) {
ele.addEventListener('click', () => {
snackbarFunction();
});
}
|
function redirect() {
if(document.getElementById('team').value === 'yes'){
window.location = '../../07week/Checkpoint2/index.html';
} else if(document.getElementById('team').value === 'no') {
window.location = 'https://www.niaaa.nih.gov/alcohol-health/special-populations-co-occurring-disorders/underage-drinking';
} else {
alert('Please say yes or no');
}
}
|
const fs = require('fs');
const path = require('path');
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const axios = require('axios');
const bodyParser = require('body-parser');
const app = express();
app.set('port', (process.env.PORT || 3001));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
function checkPalindromes(str) {
/*Assume str has no punctuation and assume letter case does not matter*/
str = str.toLowerCase().split(' ').join('');
return str === str.split('').reverse().join('');
}
function filterKeyPalindromes(data, file) {
if (Array.isArray(data)) {
return data.filter((x) => {
//return all objects with the "key" property
if (x.hasOwnProperty("key")) {
return x.key;
}
})
.map((x) => (x.key)) //returns all the values of the "key" property
.filter((x) => checkPalindromes(x)); //returns values that return true in checkPalindromes
}
else {
console.log("Error in "+ file.slice(5) + " : Please upload JSON array of objects.")
}
}
app.get('/palindromes', function(req, res) {
// Go to uploads directory
fs.readdir( './uploads', function( err, files ) {
let palindromeArray = [];
if( err ) {
console.error( "Could not list the directory.", err );
process.exit( 1 );
}
files.forEach(function( file, index ) { //Loop through all files in ./uploads
let filePath = path.join( './uploads', file );
let data = fs.readFileSync(filePath, "utf-8"); //read file
let filterKey = filterKeyPalindromes(JSON.parse(data), file); //find "key" and if it has palindromes
if (filterKey) {
palindromeArray = palindromeArray.concat({
"id": file,
"filename": file.slice(5),
"palindromes": filterKey,
"nameId": file.slice(0,6),
"countId": file.slice(1,6)
})
}
if (index === (files.length - 1)) {
res.json(palindromeArray)
}
})
});
})
app.get("/palindromes/count", function(req, res) {
let palindromeArrayCount = [];
axios.get("http://localhost:3001/palindromes")
.then((r) => palindromeArrayCount = palindromeArrayCount.concat(r.data.map((x) => ({
'id': x.id,
'palindromeCount': x.palindromes.length //calculate length of array
})
)
))
.then((s) => res.json(palindromeArrayCount))
.catch((error) => res.send(error.message));
})
app.post("/uploadJson", upload.single('file'), function(req, res, next) {
// get the temporary location of the file
var tempPath = req.file.path;
// set the unique identifier + original file name in the "./uploads" directory
var targetPath = './uploads/' + req.file.filename.slice(0,4) + '-' + req.file.originalname ;
// move the file from the temporary location to the intended location
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
// delete the temporary file, so that ./upload dir does not get filled with unwanted files
fs.unlink(tempPath, function() {
if (err) throw err;
console.log('File uploaded to: ' + targetPath);
res.send(targetPath)
});
});
});
app.listen(app.get('port'), () => {
console.log(`Find the server at: http://localhost:${app.get('port')}/`);
});
|
export default {
name: 'artwork',
type: 'document',
fields: [
{
name: 'visible',
type: 'boolean',
},
{
name: 'title',
type: 'string',
},
{
name: 'price',
type: 'number',
},
{
name: 'artist',
type: 'reference',
to: [{ type: 'artist' }],
},
{
name: 'image',
type: 'image',
},
],
preview: {
select: {
title: 'title',
visible: 'visible',
price: 'price',
artist: 'artist.name',
media: 'image',
},
prepare: (selection) => {
const { title, visible, price, artist, media } = selection
const priceFormatted = price
? Intl.NumberFormat('en-gb', {
style: 'currency',
currency: 'GBP',
}).format(price)
: ''
const subtitle = [priceFormatted, artist || '']
.filter((part) => part)
.join(' | ')
return {
title: visible ? `${title} 🟢` : `${title} ❌`,
subtitle,
media,
}
},
},
}
|
import React from 'react';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import CloseIcon from './';
Enzyme.configure({ adapter: new Adapter() });
function setup() {
const props = {
closeWidget: jest.fn(),
visible: true,
};
const wrapper = mount(<CloseIcon {...props} />)
return { props, wrapper };
}
describe('CloseIcon', () => {
const { wrapper, props } = setup();
it('should render correctly', () => {
expect(wrapper.find('aside').hasClass('close-icon')).toBe(true);
});
it('should call the closeWidget() action on click', () => {
const aside = wrapper.find('aside');
aside.simulate('click');
expect(props.closeWidget).toHaveBeenCalledTimes(1);
});
});
|
import React, { Component } from "react";
import { Modal, Alert, Button } from "react-bootstrap";
import { Link } from "react-router-dom";
import { base } from "config/base";
import FirestoreServices from 'services/FirestoreServices'
import Loading from "commons/Loading";
import styled from 'styled-components'
import ProductForm from "components/ProductForm";
const StyledProductForm = styled.div`
margin-top: 10px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
margin-left: auto;
margin-right: auto;
border-radius: 5px;
width: 90%;
padding: 25px;
color: #3C3C3C;
background: rgb(255,255,255);
animation-name: slideDown;
-webkit-animation-name: slideDown;
animation-duration: 1s;
-webkit-animation-duration: 1s;
animation-timing-function: ease;
-webkit-animation-timing-function: ease;
visibility: visible !important;
`;
const ErrorMessage = (props) =>
<div>
<Modal show={true} style={{ top: 300 }}>
<Modal.Header>حدث خطأ غير معروف</Modal.Header>
<Modal.Body>
<Alert bsStyle="danger">
{props.message}
</Alert>
<Link to="/">
<Button>العودة للصفحة الرئيسية</Button>
</Link>
</Modal.Body>
</Modal>
</div>
function getStateForNewProduct() {
return {
isNewProduct: true,
product: null,
loading: false,
errorHandling: {
showError: false,
errorMsg: "error"
},
}
}
function getStateForUpdateProduct() {
return {
product: {},
loading: true,
errorHandling: {
showError: false,
errorMsg: "error"
},
isNewProduct: false,
isUpdated: false
};
}
class ProductUpdater extends Component {
constructor(props) {
super(props);
//if we updating an existing product
if (this.props.match.params.id) {
this.productId = this.props.match.params.id;
this.state = getStateForUpdateProduct();
} else {
this.state = getStateForNewProduct();
}
this.handleSubmit = this.handleSubmit.bind(this);
this.updateProduct = this.updateProduct.bind(this);
// this.formPercentageViewer = this.formPercentageViewer.bind(this)
// this.formSuccessHandler = this.formSuccessHandler.bind(this)
}
componentWillMount() {
const { state: { currentUser } } = this.props;
if (!this.state.isNewProduct) {
this.productsRef = base.bindDoc(`${FirestoreServices.PRODUCTS_PATH}/${this.productId}`, {
context: this,
state: "product",
then(data) {
this.setState({ loading: false });
},
onFailure(error) {
this.setState({ errorHandling: { showError: true, errorMsg: error } });
}
});
}
//add owner to product
FirestoreServices.readDBRecord('profUser', currentUser.uid)
.then(val => {
this.name = val.name
})
}
componentWillUnmount() {
console.log(`${this.constructor.name}.componentWillUnmount`);
!this.state.isNewProduct && this.productsRef && base.removeBinding(this.productsRef);
}
componentDidMount() {
console.log(`${this.constructor.name}.componentDidMount`);
}
/**
* This should be called if user clicked on 'add new product' while viewing the form.
* Not sure if there is another case where this method will be called
*/
componentWillReceiveProps(nextProps) {
//if there is no id in the url (which means a new product)
if (!nextProps.match.params.id) {
//since updating current product was inturrupted,
!this.state.isNewProduct && this.productsRef && base.removeBinding(this.productsRef);
this.productId = undefined
this.setState(getStateForNewProduct());
}
}
//addImages(productId, newImages, selectedImg, formPercentageViewer){
addImages(productId, newImages, formPercentageViewer) {
return FirestoreServices.addProductImages(productId, newImages, formPercentageViewer, this.props.state.currentUser.uid)
}
addProduct(product) {
product = { ...product, owner: this.props.state.currentUser.uid, businessName: this.name };
product.price = parseInt(product.price, 10)
return FirestoreServices.insertProduct(product);//returns a promise resolved with product ID
}
updateProduct(newProductData) {
return FirestoreServices.updateProduct(newProductData, this.productId);//returns a promise resolved with product ID
}
// handleSubmit(product, newImages, selectedImg, formPercentageViewer) {
handleSubmit(product, newImages, formPercentageViewer) {
var self = this
if (this.state.isNewProduct) {
return this.addProduct(product)
.then((productId) => self.addImages(productId, newImages, formPercentageViewer))
.catch((error) => {
console.log('could not insert product or upload images');
console.log(`ERROR: code: ${error.code}, message:${error.message}`);
throw error
})
} else {
return this.updateProduct(product)
.then(() => {
this.setState({ isUpdated: true });
return self.addImages(this.productId, newImages, formPercentageViewer)
})
.catch((error) => {
console.log('could not update product or upload images');
console.log(`ERROR: code: ${error.code}, message:${error.message}`);
throw error
})
}
}
deleteImageFromDB(imageUrl) {
return FirestoreServices.deleteProductImage(imageUrl, this.productId)
}
render() {
const { currentUser } = this.props.state;
if (this.state.loading && !this.state.errorHandling.showError)
return <Loading />;
if (this.state.errorHandling.showError)
return (
<ErrorMessage message={this.state.errorHandling.errorMsg.message} />
);
if (!this.state.loading && !this.state.showError) {
return (
<StyledProductForm>
<ProductForm
isNewProduct={this.state.isNewProduct}
product={this.state.product}
onSubmit={this.handleSubmit.bind(this)}
currentUser={currentUser}
deleteImageFromDB={this.deleteImageFromDB.bind(this)}
isUpdated={this.state.isUpdated}
/>
</StyledProductForm>
);
}
}
}
export default ProductUpdater;
|
var express = require('express');
var router = express.Router();
var passport = require('passport');
var Users = require('../models/user');
var path = require('path');
router.post('/registerUser', function(req, res, next) {
Users.create(req.body, function(err, post) {
if(err) {
res.redirect('/#/registerFail');
} else {
res.redirect('/#/main');
} // end else
}); // end Users.create
console.log('New user registered');
}); // end /registerUser
module.exports = router;
|
import React, { useState, useEffect } from "react";
import {
StyleSheet,
Text,
View,
ScrollView,
Button,
Image,
Alert,
ActivityIndicator,
} from "react-native";
import { useDispatch } from "react-redux";
import * as ImagePicker from "expo-image-picker";
import * as Permissions from "expo-permissions";
import * as Location from "expo-location";
import NetInfo from "@react-native-community/netinfo";
import * as fotosActions from "../store/actions/fotosActions";
import Colors from "../constants/Colors";
const SalvarUnica = ({ navigation, route }) => {
const [foto, setFoto] = useState(null);
const [local, setLocal] = useState(null);
const [enviando, setEnviando] = useState(false);
const [rede, setRede] = useState(false);
const dispatch = useDispatch();
// Vai conferir a conexão quando abrir a tela de seleção
useEffect(() => {
const checarNet = setInterval(() => {
getConexao();
}, 30000);
return () => clearInterval(checarNet);
}, []);
useEffect(() => {
if (foto) {
salvarFoto();
} else {
return;
}
}, [rede]);
// Ao tentar enviar uma foto, vai conferir a localização
// do usuário para enviar as coordenadas junto da foto
useEffect(() => {
getLocalizacao();
}, [enviando]);
const verificarPermissoes = async () => {
const resultado = await Permissions.askAsync(
Permissions.CAMERA,
Permissions.CAMERA_ROLL,
Permissions.LOCATION
);
if (resultado.status !== "granted") {
Alert.alert(
"Para utilizar a aplicação é necessário permitir acesso a câmera e a localização.",
[{ text: "Entendido" }]
);
return false;
}
return true;
};
// Fazer um setTimeout para que essa função se repita à cada alguns minutos
const getConexao = () => {
NetInfo.fetch().then((conexao) => {
if (!conexao) {
console.log("Sem conexão.");
}
setRede(conexao.isConnected);
});
};
const toggleNet = () => {
rede ? setRede(false) : setRede(true);
};
const getLocalizacao = async () => {
const temPermissao = await verificarPermissoes();
if (!temPermissao) {
return;
} else {
try {
// Espera até 10 segundos em cada tentativa
const localizacao = await Location.getCurrentPositionAsync({
timeout: 10000,
});
setLocal(localizacao);
} catch (err) {
console.log(err);
}
}
};
const abrirCamera = async () => {
const temPermissao = await verificarPermissoes();
if (!temPermissao) {
return;
}
const imagem = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [16, 9],
quality: 1,
exif: true,
});
setFoto(imagem.uri);
getLocalizacao();
};
const finalizar = () => {
setEnviando(false);
navigation.navigate("Listagem");
};
const despachar = () => {
dispatch(fotosActions.addFoto(foto, local))
.then(() => {
setEnviando(true);
})
.catch((err) => {
console.log("Deu erro: " + err);
});
Alert.alert("Sucesso", "Sua foto foi enviada", [
{ text: "Ok", onPress: finalizar },
]);
};
const salvarFoto = async () => {
await getConexao();
if (!rede) {
Alert.alert("Celular sem internet", "Conecte-se para continuar", [
{ text: "Ok" },
]);
} else {
despachar();
}
};
const abrirBiblioteca = async () => {
const temPermissao = await verificarPermissoes();
if (!temPermissao) {
return;
}
navigation.navigate("Seletor");
};
return (
<ScrollView>
{enviando ? (
<View style={{ alignSelf: "center" }}>
<ActivityIndicator size="large" color={Colors.tirar} />
</View>
) : (
<View style={styles.form}>
<View
style={{
flexDirection: "row",
alignItems: "center",
justifyContent: "space-evenly",
}}
>
{rede ? (
<View style={styles.bolaVerde} />
) : (
<View style={styles.bolaVermelha} />
)}
<Text style={styles.titulo}>Envie aqui a foto dos documentos</Text>
</View>
<View style={styles.seletor}>
<View style={styles.visualizacao}>
{!foto ? (
<Text>As fotos aparecerão aqui</Text>
) : (
<Image style={styles.imagem} source={{ uri: foto }} />
)}
</View>
<View style={{ width: "100%" }}>
<View style={{ margin: 2 }}>
<Button
title="Tirar nova foto"
color={Colors.tirar}
onPress={abrirCamera}
/>
</View>
<View style={{ margin: 2 }}>
<Button
title="Escolher foto existente"
color={Colors.tirar}
onPress={abrirBiblioteca}
/>
</View>
<View style={{ margin: 2 }}>
<Button
title={rede ? "Desligar net" : "Ligar net"}
color={Colors.tirar}
onPress={toggleNet}
/>
</View>
</View>
</View>
{foto ? (
<Button
title="Salvar foto"
color={Colors.foto}
onPress={salvarFoto}
/>
) : (
<Button title="Salvar foto" disabled onPress={salvarFoto} />
)}
</View>
)}
</ScrollView>
);
};
export default SalvarUnica;
const styles = StyleSheet.create({
form: {
height: "100%",
margin: 30,
},
titulo: {
fontSize: 18,
textAlign: "center",
},
input: {
borderBottomColor: "#ccc",
borderBottomWidth: 1,
marginBottom: 15,
paddingVertical: 4,
paddingHorizontal: 2,
},
seletor: {
alignItems: "center",
marginTop: 20,
marginBottom: 50,
},
visualizacao: {
width: "100%",
height: 200,
marginBottom: 10,
justifyContent: "center",
alignItems: "center",
borderColor: "#ccc",
borderWidth: 1,
},
imagem: {
width: "100%",
height: "100%",
},
bolaVerde: {
width: 25,
height: 25,
borderRadius: 50,
backgroundColor: "green",
},
bolaVermelha: {
width: 25,
height: 25,
borderRadius: 50,
backgroundColor: "red",
},
});
|
var _ = require('lodash');
var dig = require('dig-it');
// very sophisticated: basically add an s on the end of a string if there
// isn't one already
function pluralize (str) {
return !!str.match(/s$/i) ? str : str + 's';
}
function sideload (data, path, opts) {
opts = opts || {};
data = _.cloneDeep(data);
var primaryKey = opts.primaryKey || 'id';
var docs = dig(data).get(path);
if (!docs) { return data; }
var topKey = opts.plural || pluralize(_.last(path.split('.')));
data[topKey] = _.isArray(docs) ? docs : [docs];
dig(data).set(path, function (doc) {
if (!doc) { return; }
return dig(doc).get(primaryKey);
});
return data;
}
module.exports = sideload;
|
import { storiesOf } from '@storybook/vue';
import Hero1 from './Hero1';
storiesOf('Design System|Molecules/Hero1', module)
.add('default', () => {
return {
components: { Hero1 },
template: `<Hero1 />`,
data: () => ({ }),
};
}); |
// Set the start URL
var startUrl = 'http://www.cowboytoyota.com';
// URL variables
var visitedUrls = [], pendingUrls = [];
// Create instances
var casper = require('casper').create({ /*verbose: true, logLevel: 'debug'*/ });
var utils = require('utils');
var helpers = require('./helpers');
// Spider from the given URL
function spider(url) {
// Add the URL to the visited stack
visitedUrls.push(url);
// Filter GA requests
casper.options.onResourceReceived = function(csp, res) {
if (res.stage === 'end' && res.url.indexOf('google-analytics') > -1){
console.log(res.status + ': ' + res.url);
}
};
// Open the URL
casper.open(url).then(function() {
var baseUrl = this.getGlobal('location').origin;
// Set the status style based on server status code
var status = this.status().currentHTTPStatus;
switch(status) {
case 200: var statusStyle = { fg: 'green', bold: true }; break;
case 404: var statusStyle = { fg: 'red', bold: true }; break;
default: var statusStyle = { fg: 'magenta', bold: true }; break;
}
// Display the spidered URL and status
this.echo(this.colorizer.format(status, statusStyle) + ' ' + url);
var links = this.evaluate(function() {
return Array.prototype.map.call(__utils__.findAll('a'), function(anchor) {
return anchor.getAttribute('href');
});
});
//Array.prototype.forEach.call(links, function(link) {console.log(link);});
Array.prototype.forEach.call(links, function(link) {
var newUrl = helpers.absoluteUri(baseUrl, link);
if (pendingUrls.indexOf(newUrl) === -1 && visitedUrls.indexOf(newUrl) === -1) {
pendingUrls.push(newUrl);
}
})
pendingUrls = pendingUrls.filter(function(url) { if (url.indexOf(baseUrl) > -1) { return url;}});
Array.prototype.forEach.call(pendingUrls, function(url) {console.log(url);});
});
}
// Start spidering
casper.start(startUrl, function() {
spider(startUrl);
});
// Start the run
casper.run();
|
var True = "*"; True = True.fontcolor ("#3df544"); //green
var halfTrue = "*"; halfTrue = halfTrue.fontcolor("#ffff00"); //orange
var False = "*"; False = False.fontcolor ("#ff3333");//red
var target = (Math.round(Math.random()*10000)).toString();
var lengthInputMax = target.length;
var attempt = 15;
var enteredWord;
var result = [0,0,0];
var k = attempt;
function reload (statute){
if (statute=="win") alert("Well played, the number is: "+target);
else alert("No luck, the number was "+target);
document.getElementById("demo").innerHTML = "";
target = (Math.floor(Math.random()*10000)).toString();
lengthInputMax = target.length;
k=attempt;
document.getElementById("btnValidate").innerHTML = "Submit (15)";
}
function mainScript()
{
k-=1;
document.getElementById("btnValidate").innerHTML = "Submit ("+k+")";
//ocument.getElementById("fBox").innerHTML = 15;
tmp = document.getElementById("enteredWord").value;
tmp = tmp.toString();
var spacingTmp = "_";
var spacingSize = 25 - tmp.length;
var i = 0;
while (i<spacingSize){
spacingTmp += "_";
i++;
}
spacingTmp = spacingTmp.fontcolor ("grey");
size = target.length;
var i=0
if (tmp.length>lengthInputMax) document.getElementById("demo").innerHTML += tmp+spacingTmp+"Too long<br>";
else
{
while (i<size)
{
if (tmp[i]==target[i])result[0] += 1;
else if (target.indexOf(tmp[i])>0) result[1] +=1;
else result[2] +=1;
i++;
}
var resultMoji=new Array;
var i=0;
while (i<3)
{
if (result [i]>0)
{
if (i==0)
{
resultMoji.push("<bold>"+True+"</bold>");
i--;
result[0]-=1;
}
else if (i==1)
{
resultMoji.push("<bold>"+halfTrue+"</bold>");
i--;
result[1]-=1;
}
else if (i==2)
{
resultMoji.push("<bold>"+False+"</bold>");
i--;
result[2]-=1;
}
}
i++;
}
wordEntered = document.getElementById("enteredWord").value+spacingTmp+" "+resultMoji.join(" ")+"<br>";
document.getElementById("demo").innerHTML += wordEntered;
if (tmp==target){
document.getElementById("demo").innerHTML += "Congratulation<br>";
reload("win");
}
else if (k<=0){
reload("loose");
}
result = [0,0,0];
}
document.getElementById("enteredWord").value="";
}
|
/*
* Copyright 2017 PhenixP2P Inc. Confidential and Proprietary. All Rights Reserved.
* Please see the LICENSE file included with this distribution for details.
*/
import React from 'react';
import PropTypes from 'prop-types';
const Gravatar = ({url}) => (
<img src={url} />
);
Gravatar.propTypes = {url: PropTypes.string.isRequired};
export default Gravatar; |
import React from 'react'
const ProductInfo = () => {
return (
<div className="m-20">
<input type="file" name="" id="" />
</div>
)
}
export default ProductInfo
|
var securitygroup_url = 'http://127.0.0.1:8181/controller/nb/v2/neutron/security-groups';
var securitygroup_post_json = {
"security_group": {
"tenant_id": "1dfe7dffa0624ae882cdbda397d1d276",
"description": "",
"id": "521e29d6-67b8-4b3c-8633-"+"#{INDEX}",
"security_group_rules": [
{
"remote_group_id": null,
"direction": "egress",
"remote_ip_prefix": null,
"protocol": null,
"ethertype": "IPv4",
"tenant_id": "1dfe7dffa0624ae882cdbda397d1d276",
"port_range_max": null,
"port_range_min": null,
"id": "823faaf7-175d-4f01-a271-0bf56fb1e7e6",
"security_group_id": "d3329053-bae5-4bf4-a2d1-7330f11ba5db"
},
{
"remote_group_id": null,
"direction": "egress",
"remote_ip_prefix": null,
"protocol": null,
"ethertype": "IPv6",
"tenant_id": "1dfe7dffa0624ae882cdbda397d1d276",
"port_range_max": null,
"port_range_min": null,
"id": "d3329053-bae5-4bf4-a2d1-7330f11ba5db",
"security_group_id": "d3329053-bae5-4bf4-a2d1-7330f11ba5db"
}
],
"name": "tempest-secgroup-1272206251"
}
}
var securitygroup_put_json = {
"security_group": {
"tenant_id": "00f340c7c3b34ab7be1fc690c05a0275",
"description": "tempest-security-description-897433715",
"id": "521e29d6-67b8-4b3c-8633-"+"#{INDEX}",
"security_group_rules": [
{
"remote_group_id": null,
"direction": "egress",
"remote_ip_prefix": null,
"protocol": null,
"ethertype": "IPv4",
"tenant_id": "00f340c7c3b34ab7be1fc690c05a0275",
"port_range_max": null,
"port_range_min": null,
"id": "808bcefb-9917-4640-be68-14157bf33288",
"security_group_id": "521e29d6-67b8-4b3c-8633-027d21195333"
},
{
"remote_group_id": null,
"direction": "egress",
"remote_ip_prefix": null,
"protocol": null,
"ethertype": "IPv6",
"tenant_id": "00f340c7c3b34ab7be1fc690c05a0275",
"port_range_max": null,
"port_range_min": null,
"id": "c376f7b5-a281-40e0-a703-5c832c03aeb3",
"security_group_id": "521e29d6-67b8-4b3c-8633-027d21195333"
}
],
"name": "tempest-security--1135434738"
}
}
exports.securitygroup_url = securitygroup_url
exports.securitygroup_post_json = securitygroup_post_json
exports.securitygroup_put_json = securitygroup_put_json |
import React, { Component, createRef } from 'react';
import FileButton from './components/FileButton';
import MessagesBox from './components/MessagesBox';
import './style.css';
class App extends Component {
state = {
buttonCounter: 1,
sizeSum: 0,
sizes: [], // For displaying total size of files
buttons: [],
files: [], // For http-requests
dragging: false,
messages: [],
isMessagesSent: false,
isMessageSending: false,
session: '',
isAuth: false,
toMail: '',
errors: {}, // For form validation
isInputsValid: false
};
// ---------------------------------- DRAG AND DROP -------------------------------------------
dropRef = createRef();
componentDidMount() {
const div = this.dropRef.current;
this.dragCounter = 0;
this.addButtonsIntoArr();
div.addEventListener('dragenter', this.handleDragIn);
div.addEventListener('dragleave', this.handleDragOut);
div.addEventListener('dragover', this.handleDrag);
div.addEventListener('drop', this.handleDrop);
}
componentWillUnmount() {
const div = this.dropRef.current;
div.removeEventListener('dragenter', this.handleDragIn);
div.removeEventListener('dragleave', this.handleDragOut);
div.removeEventListener('dragover', this.handleDrag);
div.removeEventListener('drop', this.handleDrop);
}
handleDrag = e => {
this.preventDefault(e);
e.stopPropagation();
};
handleDragIn = e => {
this.preventDefault(e);
e.stopPropagation();
const { items } = e.dataTransfer;
this.dragCounter++;
if (items && items.length > 0) {
this.setState({ dragging: true });
}
};
handleDragOut = e => {
this.preventDefault(e);
e.stopPropagation();
this.dragCounter--;
if (this.dragCounter === 0) {
this.setState({ dragging: false });
}
};
handleDrop = e => {
this.preventDefault(e);
e.stopPropagation();
const data = e.dataTransfer.files;
this.setState({
dragging: false
});
if (data && data.length > 0) {
for (let i = 0, len = data.length; i < len; i++) {
this.addFile(data[i]);
}
}
};
// --------------------------- ADDING FILES THROUGH THE BUTTON -------------------------------------
addFile = file => {
let content;
let { buttonCounter } = this.state;
const { sizes, files, sizeSum } = this.state;
const { size, name } = file;
const newFileSize = size / 1024 / 1024;
const newSizeSum = newFileSize + sizeSum;
const button = document.getElementById(`label-${buttonCounter}`);
const fileInput = document.getElementById(`file-${buttonCounter}`);
const reader = new FileReader();
if (newFileSize < 5 && newSizeSum < 20) {
fileInput.setAttribute('disabled', '');
reader.onload = ({ target: { result } }) => {
content = result;
files.push({
file: {
name,
content,
encoding: 'base64'
},
number: buttonCounter
});
};
reader.readAsDataURL(file);
button.innerHTML = name;
buttonCounter++;
sizes.push({
size: newFileSize,
number: buttonCounter
});
this.setState(
{
buttonCounter,
sizeSum: newSizeSum,
sizes
},
() => this.addButtonsIntoArr(buttonCounter)
);
} else if (newFileSize > 5) {
alert('Size of file too large!');
fileInput.value = '';
} else if (newSizeSum > 20) {
alert("Sum of file's sizes too large!");
fileInput.value = '';
}
};
// --------------------------------------- DELETING FILES -------------------------------------------
deleteFile = index => {
let { buttons, sizes, files } = this.state;
files = files.filter(({ number }) => number !== index + 1);
buttons = buttons.filter(({ number }) => number !== index);
sizes = sizes.filter(({ number }) => number !== index + 1);
const sizeSum = sizes.reduce((sum, { size }) => sum + size, 0);
this.setState({
files,
sizeSum,
sizes,
buttons
});
};
// ------------------------------ Filling buttons array ---------------------------------------
addButtonsIntoArr = (number = 1) => {
const { buttons } = this.state;
buttons.push({
component: '',
number
});
this.setState({
buttons
});
};
// --------------------------------------- Authorisation -------------------------------------
auth = e => {
this.preventDefault(e);
const params = {};
const request = `apiversion=100&json=1&request=${encodeURIComponent(JSON.stringify(params))}`;
fetch('https://api.sendsay.ru/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: request
})
.then(res => res.json())
.then(({ session }) => {
this.setState(
{
session
},
() => this.sendMail()
);
})
.catch(err => err);
};
// ---------------------------------------------- SEND MAIL ----------------------------------------------------------------
sendMail = e => {
const { files, messages, isAuth, session } = this.state;
if (isAuth) {
this.preventDefault(e);
}
const fromName = document.getElementById('fromName');
const fromMail = document.getElementById('fromMail');
const toName = document.getElementById('toName');
const toMail = document.getElementById('toMail');
const subject = document.getElementById('subject');
const text = document.getElementById('text');
const filesArr = [];
files.forEach(({ file }) => {
filesArr.push(file);
});
const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const date = new Date();
const mailDate = `${date.getDate()} ${monthNames[date.getMonth()]}`;
this.setState(({ isMessageSending }) => ({
isMessageSending: !isMessageSending,
toMail: toMail.value
}));
const params = {
action: 'issue.send.test',
letter: {
subject: subject.value,
'from.name': fromName.value,
'from.email': fromMail.value,
'to.name': toName.value,
message: { text: text.value },
attaches: filesArr
},
sendwhen: 'test',
mca: [toMail.value],
session
};
const request = `apiversion=100&json=1&request=${encodeURIComponent(JSON.stringify(params))}`;
fetch('https://api.sendsay.ru/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: request
})
.then(res => res.json())
.then(res => {
messages.push({
subject: subject.value,
fromName: fromName.value,
fromMail: fromMail.value,
toName: toName.value,
toMail: toMail.value,
text: text.value,
date: mailDate,
id: res['track.id']
});
// Cleaning the form
fromName.value = '';
fromMail.value = '';
toName.value = '';
toMail.value = '';
subject.value = '';
text.value = '';
setTimeout(() => this.stateClear(messages), 2000);
})
.catch(err => err);
};
// ---------------------------------------------- Cleaning state --------------------------------------------------------------
stateClear = messages => {
this.setState(
({ isMessageSending }) => ({
messages,
isMessagesSent: true,
isMessageSending: !isMessageSending,
isAuth: true,
sizeSum: 0,
buttonCounter: 1,
files: [],
sizes: [],
buttons: []
}),
() => this.addButtonsIntoArr()
);
};
// ----------------------------------------------- Validation -----------------------------------------------------------------------
checkInputValidity = () => {
const { messages } = this.state;
const fromName = document.getElementById('fromName').value;
const fromMail = document.getElementById('fromMail').value;
const toName = document.getElementById('toName').value;
const toMail = document.getElementById('toMail').value;
const subject = document.getElementById('subject').value;
const text = document.getElementById('text').value;
const errors = {};
let isInputsValid = true;
if (messages.length === 0) {
errors.fromName = '';
errors.fromMail = '';
errors.toName = '';
errors.toMail = '';
errors.subject = '';
errors.text = '';
}
if (fromName === '') {
errors.fromName = 'The name cannot be empty';
} else if (!fromName.match(/^[a-zA-Zа-яА-Я]*$/)) {
errors.fromName = 'Name contains invalid characters';
} else {
errors.fromName = '';
}
if (toName === '') {
errors.toName = 'The name cannot be empty';
} else if (!toName.match(/^[a-zA-Zа-яА-Я]*$/)) {
errors.toName = 'Name contains invalid characters';
} else {
errors.toName = '';
}
/* eslint-disable no-useless-escape */
if (fromMail === '') {
errors.fromMail = 'Email cannot be empty';
} else if (!fromMail.match(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/)) {
errors.fromMail = 'Please enter a valid Email';
} else {
errors.fromMail = '';
}
if (toMail === '') {
errors.toMail = 'Email cannot be empty';
} else if (!toMail.match(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/)) {
errors.toMail = 'Please enter a valid Email';
} else {
errors.toMail = '';
}
/* eslint-enable */
if (subject === '') {
errors.subject = 'Message subject cannot be empty';
} else if (subject.length < 4) {
errors.subject = 'Please enter at least 4 characters';
} else {
errors.subject = '';
}
if (text === '') {
errors.text = 'Message cannot be empty';
} else if (text.length < 10) {
errors.text = 'Please enter at least 10 characters';
} else {
errors.text = '';
}
/* eslint-disable no-unused-vars */
for (const i in errors) {
if (errors[i] !== '') {
isInputsValid = false;
}
}
/* eslint-enable */
this.setState({
errors,
isInputsValid
});
};
preventDefault = e => {
e.preventDefault();
};
// ---------------------------------------- RENDER ----------------------------------
render() {
const {
isAuth,
toMail,
buttonCounter,
dragging,
isMessagesSent,
messages,
buttons,
session,
isMessageSending,
errors: { fromName: errorFromName, fromMail: errorFromMail, toName: errorToName, subject: errorSubject, text: errorText, toMail: errorToMail },
isInputsValid
} = this.state;
return (
<div className="App">
{/* ------------------------------------------- Sending field -------------------------------------- */}
<div className={isMessageSending ? 'file-sending-zone' : 'disabled'}>
<h2 className="file-sending-zone__heading">Message queued for sending</h2>
<p className="file-sending-zone__text">
Soon the message flies out of the server, and will move towards the recipient's mail <b>{toMail}</b> with the speed of electrons
</p>
</div>
<form onSubmit={isInputsValid ? (isAuth ? this.sendMail : this.auth) : this.preventDefault} className={isMessageSending ? 'disabled' : 'form'} ref={this.dropRef}>
{/* ------------------- DROP ZONE ------------------------------- */}
<div className={dragging ? 'drop-zone' : 'disabled'}>
<div className="drop-zone--inner">
<p className="drop-zone__text">Throw files here, I catch</p>
<span className="drop-zone__sub-text">We accept pictures (jpg, png, gif), office files (doc, xls, pdf) and zip archives. File sizes up to 5 MB</span>
</div>
</div>
{/* ----------------------------------------- MAIN FORM ------------------------------ */}
<h1 className="form__heading">Posting Messages</h1>
<div className="form__inputs">
{/* ----------------------------------- FORM GROUP 1 -------------------------------------------- */}
<label className="label">
<span className="label--heading">From whom</span>
<div className="input-group">
<div className="input-wrapper">
<input className="input input--left" type="text" id="fromName" name="from-name" minLength="2" maxLength="30" placeholder="Name" required />
<span className={errorFromName === '' ? 'disabled' : 'input-error'}> {errorFromName} </span>
</div>
<div className="input-wrapper">
<input className="input input--right" type="email" id="fromMail" name="from-mail" placeholder="Email" required />
<span className={errorFromMail === '' ? 'disabled' : 'input-error'}> {errorFromMail} </span>
</div>
</div>
</label>
{/* ----------------------------------- FORM GROUP 2 -------------------------------------------- */}
<label className="label">
<span className="label--heading">To</span>
<div className="input-group">
<div className="input-wrapper">
<input className="input input--left" type="text" id="toName" name="to-name" minLength="2" maxLength="30" placeholder="Name" required />
<span className={errorToName === '' ? 'disabled' : 'input-error'}> {errorToName} </span>
</div>
<div className="input-wrapper">
<input className="input input--right" type="email" id="toMail" name="to-mail" placeholder="Email" required />
<span className={errorToMail === '' ? 'disabled' : 'input-error'}> {errorToMail} </span>
</div>
</div>
</label>
{/* ----------------------------------- FORM GROUP 3 -------------------------------------------- */}
<label className="label">
<span className="label--heading">Letter subject</span>
<div className="input-group">
<div className="input-wrapper input-wrapper--center">
<input className="input input--center" type="text" id="subject" name="subject" minLength="4" placeholder="Letter subject" required />
<span className={errorSubject === '' ? 'disabled' : 'input-error'}> {errorSubject} </span>
</div>
</div>
</label>
{/* ----------------------------------- FORM GROUP 4 -------------------------------------------- */}
<label className="label">
<span className="label--heading">Message</span>
<div className="input-wrapper input-wrapper--center">
<textarea className="textarea" id="text" placeholder="Enter your message!" minLength="10" required></textarea>
<span className={errorText === '' ? 'disabled' : 'input-error'}> {errorText} </span>
</div>
</label>
</div>
{/* ------------------------------------- FILES ----------------------------------- */}
<div className="files">
{buttons.map(({ number }) => (
<FileButton buttonCounter={buttonCounter} index={number} key={number} addFile={this.addFile} deleteFile={this.deleteFile} />
))}
</div>
<input type="submit" className="submit-btn" value="Submit" onClick={this.checkInputValidity} />
</form>
{/* ------------------------------------------- SENT MESSAGES ------------------------------------------------ */}
<MessagesBox isMessagesSent={isMessagesSent} messages={messages} session={session} />
</div>
);
}
}
export default App;
|
$(document).ready(testCaesarCipher );
function CaesarCipher(input, shiftNum ){
var alphabet = window.alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
var output = '';
for (var i=0; i<input.length; i++ ){
var foundIndex = alphabet.indexOf(input[i].toLowerCase());
if(foundIndex !== -1 ){
if( input[i] === input[i].toUpperCase() ){
output+=alphabet[foundIndex + shiftNum].toUpperCase();
} else output+=alphabet[foundIndex + shiftNum].toLowerCase();
} else output+=input[i]
}
console.log('output: ', output )
return output;
}
function testCaesarCipher(){
test('An input of Caesar Cipher should return Ecguct Ekrjgt ', function(){
return CaesarCipher('Caesar Cipher', 2) === 'Ecguct Ekrjgt';
});
}
|
import { StyleSheet } from 'react-native';
import * as colors from 'kitsu/constants/colors';
export const styles = StyleSheet.create({
wrapper: {
flex: 1,
backgroundColor: colors.listBackPurple,
paddingTop: 77,
},
webView: {
flex: 1,
},
errorText: {
fontSize: 16,
color: colors.white,
fontFamily: 'Open Sans',
},
});
|
total();
$(document).ready(function () {
$(".cart_quantity_up").click(function () {
var parent = $(this).parent();
var parentCha = $(this).closest("tr");
var thisTotal = parentCha.find("td")[4];
var thisPrice = $(parentCha.find("td")[2]).find("p").text().slice(1);
var thisCart = parent.find("input");
var thisSoLuong = $(thisCart[0]).val();
var thisID = $(thisCart[1]).val();
$.ajax({
type: "post",
url: "./ajaxCart.php",
data: { "thisSoLuong": thisSoLuong, "thisID": thisID, "mode": 'add' },
success: function (response) {
$(thisCart[0]).val(parseInt(thisSoLuong) + 1);
$(thisTotal).find("p").html((parseInt(thisSoLuong) + 1) * thisPrice);
total();
}
});
});
$(".cart_quantity_down").click(function () {
var parent = $(this).parent();
var parentCha = $(this).closest("tr");
var thisTotal = parentCha.find("td")[4];
var thisPrice = $(parentCha.find("td")[2]).find("p").text().slice(1);
var thisCart = parent.find("input");
var thisSoLuong = $(thisCart[0]).val();
var thisID = $(thisCart[1]).val();
if (thisSoLuong > 0) {
$.ajax({
type: "post",
url: "./ajaxCart.php",
data: { "thisSoLuong": thisSoLuong, "thisID": thisID, "mode": 'mod' },
success: function (response) {
$(thisCart[0]).val(parseInt(thisSoLuong) - 1);
$(thisTotal).find("p").html((parseInt(thisSoLuong) - 1) * thisPrice);
total();
}
});
}
});
});
function total() {
console.log("chay");
var tong = 0;
let countArrCart = document.getElementsByClassName('cart_total_price').length;
for (var i = 0; i < countArrCart; i++) {
tong += parseInt(document.getElementsByClassName('cart_total_price')[i].textContent);
}
$(".total").html("Total: " + tong);
}
//---Phần hiện account---------------------------------------
$(document).ready(function () {
$(".updateProductA").click(function (e) {
$(".userInfor").hide();
$(".updateProduct").show();
});
$(".userInforA").click(function (e) {
$(".updateProduct").hide();
$(".userInfor").show();
});
}); |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$("#registro").click(function(){
var dato = $("#genre").val();
var route = "/genero";
var toke = $("#token").val();
$.ajax({
url: route,
headers:
{
'X-CSRF-TOKEN': toke,
},
type: 'POST',
dataType: 'json',
data:
{
genre: dato,
},
success:function(){
$("#msj-success").fadeIn();
},
error:function(msj){
$('#msj').html(msj.responseJSON.errors.genre);
$('#msj-error').fadeIn();
},
});
});
|
app.factory('resourceSvc', function ($http, $q) {
return {
url: '/api/Resources/',
addResource: function (resource) {
var deferred = $q.defer();
$http({ method: 'post', url: this.url, data: resource })
.success(function (data) {
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
},
editResource: function (resource) {
var deferred = $q.defer();
$http({ method: 'put', url: this.url + resource.Id, data: resource })
.success(function (data) {
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
},
getResource: function (id) {
var deferred = $q.defer();
$http({ method: 'get', url: this.url + id })
.success(function (data) {
deferred.resolve(data);
})
.error(function (error) {
deferred.reject(error);
});
return deferred.promise;
}
};
}); |
import React from 'react';
import { mount } from 'enzyme';
import ReactRouterEnzymeContext from 'react-router-enzyme-context';
import Tags from '../Tags';
const options = new ReactRouterEnzymeContext();
const wrapper = mount(
<Tags
items={['name']}
/>,
options.get(),
);
describe('<Profiles />', () => {
it('should render articles search component without crashing', () => {
const node = wrapper.find('.search__dropdown_item');
expect(node.length).toBe(1);
});
});
|
// closures
function x() {
const a = 10;
const b = 50;
return function y() {
console.log(a);
};
}
const z = x();
z();
|
const axios = require('axios');
require('dotenv').config();
// Change to env var
const DARKSKY_KEY = process.env.DARKSKY_KEY;
const GOOGLE_KEY = process.env.GOOGLE_KEY;
exports.processAddress = async (addressInput) => {
// return await this.getWeather();
try {
const encodedAddress = encodeURIComponent(addressInput);
const geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}&key=${GOOGLE_KEY}`;
// http get request
const geocode = await axios.get(geocodeUrl);
if (geocode.data.status === 'ZERO_RESULTS') {
throw new Error('Unable to find that address');
} else if (geocode.data.status === 'OVER_QUERY_LIMIT') {
throw new Error("Whoops! Looks like I've exceeded request quota for Google Maps API");
} else if (geocode.data.status !== 'OK') {
throw new Error('Sorry! Some kind of error with Google Maps API');
}
const address = geocode.data.results[0].formatted_address;
const lat = geocode.data.results[0].geometry.location.lat;
const lng = geocode.data.results[0].geometry.location.lng;
return await this.getWeather(address, lat, lng);
} catch (e) {
let errorMessage = e.message;
if (e.code === 'ENOTFOUND') {
errorMessage = 'Unable to connect to API servers.';
} else {
errorMessage = e.message;
}
console.error(errorMessage);
}
};
exports.getWeather = async (address, lat, lng) => {
const weatherUrl = `https://api.darksky.net/forecast/${DARKSKY_KEY}/${lat},${lng}?units=si`;
// const weatherUrl = `https://api.darksky.net/forecast/5b05469397c05086e48a473a3c2bda80/37.8267,-122.4233?units=si`;
try {
const weather = await axios.get(weatherUrl);
// console.log('WEATHER!!', weather);
return {
weather,
address,
};
} catch (e) {
console.error(e.message);
}
};
|
const express = require("express");
const RateLimit = require("express-rate-limit");
const mysql = require("mysql");
require("dotenv").config();
const db = mysql.createConnection({
host: process.env.MYSQL_HOST,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
user: process.env.MYSQL_USER
})
db.connect((e) => {
if (e) {
throw e;
}
console.log("Napoejní na Mysql bylo úspěšné!");
setInterval(() => {
db.ping();
}, 10 * 60 * 1000);
})
const app = express();
app.set("view engine", "ejs");
app.use("/public", express.static("public"));
app.get("/", (req, res) => {
res.render("main");
})
app.get("/api/url/:url", (req, res) => {
db.query("SELECT * FROM `URLNapicu` WHERE `URL` LIKE '" + req.params.url + "' LIMIT 1", (e, result) => {
if (e || result.length < 1) {
//TODO: Nějaké design
res.send("Omlouváme se, ale nastala chyba. Nepodařilo se najít hlednaou URL ");
return;
}
res.redirect(result[0].REDIRECT_URL);
})
})
app.get("/api/regurl/:url", RateLimit({
windowMs: 24 * 60 * 60 * 100,
max: 1,
message: {err: 6969}
}),(req, res) => {
console.log(req.params);
const config = require("./config.json");
if (!req.params.url || !req.query.redirect){
res.json({err: 4});
return;
}
if (!req.query.redirect.startsWith("http")){
res.json({err: 5});
return;
}
if (config.rezerovaneSubDomeny.includes(req.params.url.toLocaleLowerCase())) {
res.json({err: 1});
return;
}
db.query("SELECT * FROM `URLNapicu` WHERE URL LIKE '" + req.params.url.toLocaleLowerCase() + "' LIMIT 1", (e, result) => {
if (result.length > 0) {
res.json({err: 2});
} else {
const ZnakyNapicu = /[!@#$%^&*ěščřžýáíéťď()_+\-=\[\]{};':"\\|,.<>\/?]+/;
if(ZnakyNapicu.test(req.params.url)){
res.json({err: 3});
} else {
db.query("INSERT INTO `URLNapicu`(`URL`, `REDIRECT_URL`) VALUES ('" + req.params.url + "', '" + req.query.redirect + "')", (e2, result2) => {
if (e2) {
res.json({err: 6});
return;
}
res.json({err: 69});
})
}
}
})
})
const port = process.env.WEB_PORT || 8080;
app.listen(port, () => console.log("WEb běží na portu " + port + "! Tak užívej a nezlob.")); |
import React, { PureComponent } from "react";
import "./style.css";
class Timer extends PureComponent {
state = {
count: 0,
};
intervalid = null;
starthandelet = () => {
if (this.state.count > 0 && !this.intervalid) {
this.intervalid = setInterval(() => {
this.setState({ count: this.state.count - 1 }, () => {
if (this.state.count === 0) {
alert("Timer Finish");
clearInterval(this.intervalid);
this.intervalid = null;
}
});
}, 1000);
}
};
stophandeler = () => {
if (this.intervalid) {
clearInterval(this.intervalid);
this.intervalid = null;
}
};
resethandeler = () => {
this.setState({ count: 0 });
clearInterval(this.intervalid);
this.intervalid = null;
};
incriment = () => {
this.setState({ count: this.state.count + 1 });
};
drecriment = () => {
if (this.state.count > 0) {
this.setState({ count: this.state.count - 1 });
}
};
render() {
return (
<div className="container">
<h2>Simple timer react</h2>
<div>
<button onClick={this.drecriment}>-</button>
<span> {this.state.count} </span>
<button onClick={this.incriment}>+</button>
</div>
<div>
<button onClick={this.starthandelet}>Start</button>
<button onClick={this.stophandeler}>stop</button>
<button onClick={this.resethandeler}>reset</button>
</div>
</div>
);
}
}
export default Timer;
|
/* fileselector.js - Menu to select tile for placing */
// currentTile = currently selected tile
export class TileSelector {
constructor(_game) {
this.game = _game
// Our tile picker menu
let tileSelector = this.game.add.group();
let tileSelectorBackground = this.game.make.graphics();
tileSelectorBackground.beginFill(0x000000, 0.5);
tileSelectorBackground.drawRect(0, 0, 800, 18);
tileSelectorBackground.endFill();
tileSelector.add(tileSelectorBackground);
var tileStrip = tileSelector.create(0, 0, 'grass');
tileStrip.inputEnabled = true;
// Tilestrip mouse events
tileStrip.events.onInputDown.add(this.pickTile, this);
tileStrip.events.onInputOver.add(() => {
this.cursorTile.alpha = 0
})
tileStrip.events.onInputOut.add(() => {
this.cursorTile.alpha = 0.6
})
tileSelector.fixedToCamera = true;
this.pickTile(null, {x: 0}) // Select the first tile by default
}
pickTile(sprite, pointer) {
this.currentTile = this.game.math.snapToFloor(pointer.x, 16) / 16;
/* Setup tile to be stuck to cursor */
if(this.cursorTile) {
// There's already a cursor sprite, delete it!
this.cursorTile.destroy()
}
this.cursorTile = this.game.add.sprite(pointer.worldX * 16, pointer.worldY * 16, `grass-sheet`, this.currentTile)
this.tileCount = 0 // Placeholder for rotating tile
this.cursorTile.alpha = 0.6 // Make sprite transparent so it doesn't totally cover other tiles
}
rotate(direction) {
/* Because tiles move when they are rotated, we need to constantly reset the anchor */
if(direction == 'right') {
this.tileCount++
} else {
this.tileCount--
}
// Check for overflow
if(this.tileCount == 4) {
this.tileCount = 0
} else if(this.tileCount == -1) {
this.tileCount = 3
}
switch(this.tileCount) {
case 0:
// First: 90 right
this.cursorTile.anchor.setTo(0, 0)
this.cursorTile.angle = 0
break;
case 1:
// First: 90 right
this.cursorTile.anchor.setTo(0, 1)
this.cursorTile.angle = 90
break;
case 2:
// First: 90 right
this.cursorTile.anchor.setTo(1, 1)
this.cursorTile.angle = 180
break;
case 3:
// First: 90 right
this.cursorTile.anchor.setTo(1, 0)
this.cursorTile.angle = 270
break;
}
}
}
|
var class_otter_1_1_component =
[
[ "Added", "class_otter_1_1_component.html#a896ba54fa65a3208621eaa06e23ac042", null ],
[ "Removed", "class_otter_1_1_component.html#a36bfe8aa7c9d8e9a71d0265ed3118e81", null ],
[ "RemoveSelf", "class_otter_1_1_component.html#ac0ab335d5603e5f09268e360a0710d09", null ],
[ "Render", "class_otter_1_1_component.html#a2cbb5cdad72e0ea64e2f7516e025bb11", null ],
[ "Update", "class_otter_1_1_component.html#ae777aef927019fdb858e31de6cf79909", null ],
[ "UpdateFirst", "class_otter_1_1_component.html#a44d89b80a8843ac6042dbfd4793a8df5", null ],
[ "UpdateLast", "class_otter_1_1_component.html#af7b18954fddd565ee9514cc2046b7cea", null ],
[ "Entity", "class_otter_1_1_component.html#a622eab27046de9233e421bf9e18824fe", null ],
[ "RenderAfterEntity", "class_otter_1_1_component.html#a3503c833d8f7da07162182b3af743adb", null ],
[ "Timer", "class_otter_1_1_component.html#aec8b7e96ceae938a19f99d6e38bd81a3", null ],
[ "Visible", "class_otter_1_1_component.html#a92cf7d2d7058c35ee879daf95728c390", null ]
]; |
"use strict";
var enzyme_1 = require('enzyme');
var React = require('react');
var index_1 = require('./index');
describe('Counter Component', function () {
var onIncrement = jasmine.createSpy('onIncrement');
var onDecrement = jasmine.createSpy('onDecrement');
it('should create a counter', function () {
var counter = enzyme_1.shallow(<index_1["default"] counter={5} increment={onIncrement} decrement={onDecrement}/>);
expect(counter.length).toBe(1);
});
it('should create a counter with the correct default class', function () {
var counter = enzyme_1.shallow(<index_1["default"] counter={5} increment={onIncrement} decrement={onDecrement}/>);
expect(counter.hasClass('flex')).toBe(true);
});
it('should create a counter with increment and decrement buttons', function () {
var counter = enzyme_1.render(<index_1["default"] counter={5} increment={onIncrement} decrement={onDecrement}/>);
var incrementButton = counter.find('#qa-increment-button');
var decrementButton = counter.find('#qa-decrement-button');
expect(incrementButton.length).toBe(1);
expect(decrementButton.length).toBe(1);
});
it('should create a counter with the given starting counter value', function () {
var counter = enzyme_1.render(<index_1["default"] counter={5} increment={onIncrement} decrement={onDecrement}/>);
var counterDiv = counter.find('#qa-counter-div');
expect(counterDiv.length).toBe(1);
expect(counterDiv.text()).toBe('5');
});
it('should have buttons that call the correct function on click', function () {
var counter = enzyme_1.shallow(<index_1["default"] counter={5} increment={onIncrement} decrement={onDecrement}/>);
var incrementButton = counter.find('#qa-increment-button');
var decrementButton = counter.find('#qa-decrement-button');
incrementButton.simulate('click');
expect(onIncrement).toHaveBeenCalled();
expect(onIncrement.calls.count()).toBe(1);
decrementButton.simulate('click');
expect(onDecrement).toHaveBeenCalled();
expect(onDecrement.calls.count()).toBe(1);
});
});
|
var searchData=
[
['open_5ffile',['open_file',['../util_8c.html#ae84bfdae0ec7b73cf580228efa76178e',1,'util.c']]],
['operator_20bool',['operator bool',['../class_sndfile_handle.html#a7f99c56f1af1f6d74c1312a05aaf1a12',1,'SndfileHandle']]],
['operator_3d',['operator=',['../class_sndfile_handle.html#af7f77c3dbd655daed9648b702329ca86',1,'SndfileHandle']]],
['operator_3d_3d',['operator==',['../class_sndfile_handle.html#a37b4778ae0a0e7125f68ea872cecc8e0',1,'SndfileHandle']]]
];
|
export default (namespace, fn) => (ev, update) => {
update(`${namespace}.loading`)
fn()(
(json) => update(`${namespace}.success`, json),
(r) => update(`${namespace}.failure`, r.statusText || r.message)
)
}
|
const shapes = [
{ type: 'rect' },
{ type: 'triangle', up: true, left: false },
{ type: 'triangle', up: false, left: true },
{ type: 'triangle', up: true, left: true },
{ type: 'triangle', up: false, left: false },
{ type: 'triangleBoundary', up: true, left: true },
{ type: 'empty' },
{ type: 'triangleBoundary', up: true, left: false },
{ type: 'triangleBoundary', up: false, left: true },
{ type: 'triangleBoundary', up: false, left: false },
]
const getBottomLeftSCorner = () => {
const random = Math.random()
if (random < 0.8) {
return [shapes[0]]
} else if (random < 0.9) {
return [shapes[1]]
} else {
return [shapes[1], shapes[5]]
}
}
const getCenterRightSCorner = () => {
const random = Math.random()
if (random < 0.8) {
return [shapes[0]]
} else {
return [shapes[3], shapes[7]]
}
}
const getCenterLeftSCorner = () => {
const random = Math.random()
if (random < 0.8) {
return [shapes[0]]
} else if (random < 0.9) {
return [shapes[4]]
} else {
return [shapes[4], shapes[8]]
}
}
const getTopRightSCorner = () => {
const random = Math.random()
if (random < 0.8) {
return [shapes[0]]
} else if (random < 0.9) {
return [shapes[2]]
} else {
return [shapes[2], shapes[9]]
}
}
const getTopLeftRCorner = () => {
const random = Math.random()
if (random > 0.8) {
return [shapes[1], shapes[5]]
} else {
return [shapes[0]]
}
}
const getTopRightCCorner = () => {
const random = Math.random()
if (random < 0.7) {
return [shapes[3], shapes[7]]
} else if (random < 0.8) {
return [shapes[2], shapes[9]]
} else if (random < 0.9) {
return [shapes[2]]
} else {
return [shapes[0]]
}
}
const getBottomRightCCorner = () => {
const random = Math.random()
if (random < 0.7) {
return [shapes[0]]
} else if (random < 0.8) {
return [shapes[3], shapes[7]]
} else if (random < 0.9) {
return [shapes[3]]
} else {
return [shapes[2], shapes[9]]
}
}
export default () => [
[shapes[0]],
[shapes[3], shapes[2]],
[shapes[0]],
[shapes[6]],
[shapes[0]],
[shapes[0]],
[shapes[0]],
[shapes[6]],
[shapes[0]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[0]],
[shapes[6]],
[shapes[0]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
getTopLeftRCorner(),
[shapes[0]],
[shapes[3]],
[shapes[6]],
[shapes[1]],
[shapes[0]],
[shapes[0]],
[shapes[0]],
[shapes[4]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[2]],
[shapes[0]],
getCenterRightSCorner(),
[shapes[6]],
getTopRightSCorner(),
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[0]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[0]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[0]],
[shapes[6]],
[shapes[0]],
[shapes[6]],
[shapes[0]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
getTopRightCCorner(),
[shapes[6]],
[shapes[6]],
[shapes[6]],
getBottomRightCCorner(),
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
[shapes[6]],
getBottomLeftSCorner(),
[shapes[6]],
getCenterLeftSCorner(),
[shapes[0]],
[shapes[1]],
] |
import React, {Component} from 'react';
import {Parser} from 'html-to-react';
class PreviewView extends Component {
render() {
var htmlToReactParser = new Parser();
var reactElement = htmlToReactParser.parse(this.props.value);
return (
<div className='previewView'>
{reactElement}
</div>
);
}
}
export default PreviewView; |
// JavaScript Document
jQuery(document).ready(function ($) {
"use strict";
$(function () {
$('.dropdown').hover(function () {
$(this).addClass('open');
}, function () {
$(this).removeClass('open');
});
});
// jPages paginated blocks
var $holder = $("body").find(".holder");
if (!$holder.length) {
$("body").append("<div class='holder'></div>");
}
$("div.holder").jPages({
containerID: "products",
previous: ".product-section a[data-role='prev']",
next: ".product-section a[data-role='next']",
animation: "fadeInRight",
perPage: 4
});
$("div.holder").jPages({
containerID: "products-bestseller",
previous: "#bestseller-control a[data-role='prev']",
next: "#bestseller-control a[data-role='next']",
animation: "fadeInRight",
perPage: 4
});
$("div.holder").jPages({
containerID: "products-featured",
previous: "#featured-control a[data-role='prev']",
next: "#featured-control a[data-role='next']",
animation: "fadeInRight",
perPage: 4
});
$("div.holder").jPages({
containerID: "products3",
previous: ".product-section a[data-role='prev']",
next: ".product-section a[data-role='next']",
animation: "fadeInRight",
perPage: 3
});
$("div.holder").jPages({
containerID: "products-related",
previous: ".block-products a[data-role='prev']",
next: ".block-products a[data-role='next']",
animation: "fadeInRight",
perPage: 3
});
$("div.holder").jPages({
containerID: "related-posts",
previous: ".block-related-posts a[data-role='prev']",
next: ".block-related-posts a[data-role='next']",
animation: "bounceInRight",
perPage: 3
});
$("div.holder").jPages({
containerID: "why-choose-us",
previous: ".block-why-choose-us a[data-role='prev']",
next: ".block-why-choose-us a[data-role='next']",
animation: "flipInY",
perPage: 4
});
$("div.holder").jPages({
containerID: "what-clients-say",
previous: ".block-what-clients-say a[data-role='prev']",
next: ".block-what-clients-say a[data-role='next']",
animation: "fadeInRight",
perPage: 1
});
jQuery('.tp-banner').show().revolution({
//delay:1000,
startwidth:1920,
startheight:390, //responsiveLevels seems to be a container
hideThumbs:10,
navigationType: "none",
//responsiveLevels: [2048,1024,778,480]
});
// Top login open functions
$("#header-login").click(function () {
var $obj = $(".header-top-login");
if ($obj.hasClass("expanded")) {
$obj.removeClass("expanded");
$obj.slideUp({
duration: 300,
easing: "easeInQuad"
});
}
else {
$obj.addClass("expanded");
$obj.slideDown({
duration: 300,
easing: "easeInQuad"
});
}
});
$("#header-login-close").click(function () {
var $obj = $(".header-top-login");
if ($obj.hasClass("expanded")) {
$obj.removeClass("expanded");
$obj.slideUp({
duration: 300,
easing: "easeInQuad"
});
}
else {
$obj.addClass("expanded");
$obj.slideDown({
duration: 300,
easing: "easeInQuad"
});
}
});
$(function () {
$("#top-slider").responsiveSlides({
timeout: 3000,
auto: true,
nav: true,
prevText: "",
nextText: ""
});
});
$(".flexisel").flexisel({
visibleItems: 5,
animationSpeed: 1000,
autoPlay: true,
autoPlaySpeed: 3000,
pauseOnHover: true,
enableResponsiveBreakpoints: true,
responsiveBreakpoints: {
portrait: {
changePoint: 480,
visibleItems: 1
},
landscape: {
changePoint: 640,
visibleItems: 2
},
tablet: {
changePoint: 768,
visibleItems: 3
}
}
});
// Color Filter
$(".colors li a").each(function () {
$(this).css("background-color", "#" + $(this).attr("rel")).attr("href", "#" + $(this).attr("rel"));
});
// Product zoom
$('#product-zoom').elevateZoom({
zoomType: "inner",
cursor: "crosshair",
zoomWindowFadeIn: 500,
zoomWindowFadeOut: 750
});
var gallery = $('#gal1');
gallery.find('a').hover(function () {
var smallImage = $(this).attr("data-image");
var largeImage = $(this).attr("data-zoom-image");
var ez = $('#product-zoom').data('elevateZoom');
ez.swaptheimage(smallImage, largeImage);
});
// Daily Deal CountDown Clock Settings
var date = new Date().getTime(); // This example is just to show how this function works.
var new_date = new Date(date + 86400000); // You can set your own time whenever you want.
// var n = new_date.toUTCString(); // 'date' value is given in milliseconds.
//alert(new_date)
$(".time").countdown({
date: new_date,
yearsAndMonths: true,
leadingZero: true
});
// Categories Menu Manipulations
$(".ul-side-category li a").click(function () {
var sm = $(this).next();
if (sm.hasClass("sub-category")) {
if (sm.css("display") === "none") {
$(this).next().slideDown();
}
else {
$(this).next().slideUp();
$(this).next().find(".sub-category").slideUp();
/*$(this).next().find(".categories-submenu").slideUp("normal", function() {
$(this).parent().find(".icon-angle-down").removeClass("icon-angle-down").addClass("icon-angle-right");
});*/
}
return false;
}
else {
return true;
}
});
});
|
var page = 1;
var backButton = document.getElementById("element1");
var forwardButton = document.getElementById("element2");
var mainPage = document.getElementById("mainPage");
var pages = ["PAGE 0","<p id='page1'>September 10, 1984,<br><br>I guess I could consider this another “stereotypical” diary that translates my fondest memories, thoughts, and feelings onto a piece of paper. It’s my first day and I know that everything written in here will be another saved memory for the future. for starters, I would like to discuss the moment I got this diary.<br><br>I started off by going down to my local pastry shop, I had ordered my usual dry biscuit and dark black coffee. I sat by the old swingset outside of the shop I’ve been going to for the past 9 years. There was a blue jay chirping away on a tree across the road. Even with all of the elderly people and sweet neighbors in our community, it seems like crime is a rising concern....<p>",
//page 2
"<p id='page1'>December 22, 1984<br><br>We were robbed today. They left our apartment a complete mess, there are books and broken glass shattered across the floor. He even took our frame from me and my husband’s wedding picture. Later today my husband had gone to the store and bought us a safe. It turns out it fits perfectly in our closets and still leaves lots of room for all of my clothes. I had made my password a fairly recent and memorable year. <p>",
//page 3
"<p id='page1'>July 4, 1985<br><br>I went out with one of my girlfriends last night… We were all supposed to go out and and watch the fireworks. My husband completely ruined it, he never went came with us and did not respond to any of my calls. It is almost like he tries hiding from all of my friends and family. <p>",
//page 4
"<p id='page1'>June 16, 1986<br><br>People have been asking me to visit a doctor about my “unsafe mental health”. People are talking about me and my husband’s relationship. They keep telling me its dangerous and unhealthy. I am right now confused and I don’t understand why they keep telling me that. <p>",
//page 5
"<p id='page1'>May 12, 1988<br><br>My husband, Noah, has died today. I don’t know what to do anymore. He was my life, it was almost like he was a part of me in a physical and mental manner. It has been really hard for me, I have quit my job and tried to organize his funeral.<p>",
//page 6
"<p id='page1'>June 15, 1988<br><br>None of my friends decided to come to the funeral. I was the only one there, but in spirit I know he is watching over me.<p>",
//page 7
"<p id='page1'>August 19, 1995<br><br>It’s been a long time since I have opened this diary, but I feel like it is important to let people know that I have cancer. I won’t be living for much longer and I feel like I have lived an unfilled life. I never had any good friends and for the past 7 years I have lived alone every day thinking about what is wrong with me and no one will help me. I dont live in my nice apartment, instead I sleep in the alley ways… It is not as bad as you might think. At least it wasn’t as bad as it was since my cancer came. <p>",
//page 8
"<p id='page1'>October 19, 1995<br><br>This will be the last time I open this diary. I have looked at all of my great memories and can see how my life has changed. Its an odd feeling, perhaps the last feeling I will ever feel. I don’t have much longer to live and I know I have done much wrong in my life but at the same time I am proud for living my entire regardless of all the hardships I have had.<p>"];
updateButtons();
backButton.addEventListener("click", function() {back();});
forwardButton.addEventListener("click", function() {forward();});
function back(){
if(page>1){
page--;
updateButtons();
}
}
function forward(){
page++;
updateButtons();
}
function updateButtons(){
backButton.innerHTML="page "+(page-1);
forwardButton.innerHTML="page "+(page+1);
mainPage.innerHTML=pages[page];
} |
$(document).ready(function(){
$(".conteudo").load("buscaros");
});
$("#clientes").click(function() {
$(".conteudo").load("clientes");
});
$("#buscarOS").click(function() {
$(".conteudo").load("buscaros");
});
$("#aberturaDeOs").click(function() {
$(".conteudo").load("aberturadeos");
});
$("#ordemDeServico").click(function() {
$(".conteudo").load("ordemdeservico");
});
$("#botaoSair").click(function(){
window.location = "../";
}); |
import './styles.css';
import '@pnotify/core/dist/BrightTheme.css';
import '@pnotify/mobile/dist/PNotifyMobile.css';
import { debounce } from 'lodash';
import {
alert,
defaultModules,
} from '../node_modules/@pnotify/core/dist/PNotify.js';
import * as PNotifyMobile from '../node_modules/@pnotify/mobile/dist/PNotifyMobile.js';
defaultModules.set(PNotifyMobile, {});
import countryHbs from './templates/country.hbs';
import fetchCountries from './js/fetchCountries';
const countryOptions = {};
const inputRef = document.querySelector('.input');
const countryDescpRef = document.querySelector('.countryDescp');
const countriesNames = [];
const alertOptions = {
text: 'Too many matches found. Please enter a more specific query.',
title: false,
closer: false,
sticker: false,
delay: 1500,
addClass: 'alert',
};
function createCountryMarkup(country) {
return [country].map(countryHbs).join('');
}
function renderCountry(country) {
const countryMarkup = createCountryMarkup(country);
countryDescpRef.insertAdjacentHTML('beforeend', countryMarkup);
}
const countriesListRef = document.querySelector('.countriesList');
inputRef.addEventListener('input', _.debounce(onInputChange, 500));
function onInputChange(e) {
if (countriesNames[0] !== undefined) {
clearList();
}
countriesNames.splice(0, countriesNames.length);
clearCountryMarkup();
fetchCountries(e)
.then(countries => {
countries.map(country => {
if (countries.length === 1) {
countryOptions.name = country.name;
countryOptions.capital = country.capital;
countryOptions.population = country.population;
countryOptions.languages = [];
for (let key in country.languages) {
countryOptions.languages.push(country.languages[key].name);
}
countryOptions.flag = country.flag;
renderCountry(countryOptions);
}
return countriesNames.push(country.name);
});
})
.then(() => {
renderList(countriesNames);
notificationCheck();
})
.catch(err => {
alert(alertOptions);
console.log(err);
});
}
function renderList(countriesArr) {
if (countriesArr.length <= 10 && countriesArr.length >= 2) {
const ulRef = document.createElement('ul');
countriesArr.forEach(element => {
const liRef = document.createElement('li');
liRef.textContent = element;
ulRef.append(liRef);
});
countriesListRef.append(ulRef);
}
}
function clearList() {
countriesListRef.innerHTML = '';
}
function notificationCheck() {
if (countriesNames.length > 10) {
alert(alertOptions);
}
}
function clearCountryMarkup() {
countryDescpRef.innerHTML = '';
}
|
const User = require('../models/User')
module.exports = {
created: async (req, res) =>{
const params = req.body
const user = await User.create(params)
res.status(200).json(user)
}
} |
/*
A non-empty array A consisting of N integers is given. Array A represents numbers on a tape.
Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].
The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|
In other words, it is the absolute difference between the sum of the first part and the sum of the second part.
For example, consider array A such that:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
We can split this tape in four places:
P = 1, difference = |3 − 10| = 7
P = 2, difference = |4 − 9| = 5
P = 3, difference = |6 − 7| = 1
P = 4, difference = |10 − 3| = 7
Write a function:
function solution(A);
that, given a non-empty array A of N integers, returns the minimal difference that can be achieved.
For example, given:
A[0] = 3
A[1] = 1
A[2] = 2
A[3] = 4
A[4] = 3
the function should return 1, as explained above.
Assume that:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [−1,000..1,000].
Complexity:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).
*/
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(A) {
let max = Number.MAX_VALUE;
const reducer = (accumulator, currentValue) => accumulator + currentValue
if(!A || A.length === 0){
return 0
}
if(A.length == 1){
return A[0]
}
for(let P=1; P< A.length -1; P++){
const left = A.slice(0, P).reduce(reducer );
const right = A.slice(P).reduce(reducer);
if(max > Math.abs(left - right)){
max = Math.abs(left - right)
}
}
return max;
} |
// Instructions:
// Write a function, persistence, that takes in a positive parameter num and returns
// its multiplicative persistence, which is the number of times you must multiply the
// digits in num until you reach a single digit.
// Solution:
function persistence(n) {
let count = -1;
doTheThing = ((n)=>{
count++;
num = (""+n).split('');
a = num.reduce((mult, number)=>{
return mult * Number(number);
}, 1)
if(num.length == 1) {
return count;
} else {
return doTheThing(a);
}
})
doTheThing(n);
return count;
} |
import { Component } from 'react';
import { Display } from '@react-demo/web-react-calculator-ui-display';
import { ButtonPanel } from '@react-demo/web-react-calculator-ui-button-panel'
import { calculate } from '@react-demo/web-react-calculator-util-logic'
import styles from './app.module.css';
export class App extends Component {
state = {
total: null,
next: null,
operation: null,
};
handleClick = buttonName => {
this.setState(calculate(this.state, buttonName));
};
render() {
return (
<div className="component-app">
<Display value={this.state.next || this.state.total || "0"} />
<ButtonPanel clickHandler={this.handleClick} />
</div>
);
}
}
export default App;
|
var app = require('../app/app'); //Here you get to require the app and put it in a variable. This app is the actual app object you created in app.js
var port = process.env.PORT || 3000;
var server = app.listen(port, function() {
console.log('Express server is running on port ' + port);
}); |
'use strict'
import {
StyleSheet,
View,
Text,
FlatList,
TouchableHighlight
} from 'react-native';
import React , {Component} from 'react';
import moment from 'moment-timezone'
import { connect } from 'react-redux';
import Modal from 'react-native-modal';
import {
RkText,
RkStyleSheet,
} from 'react-native-ui-kitten';
import { addMatch , homeTeamChanged , homeScoreChanged , awayScoreChanged , awayTeamChanged, setCurrentDate} from '../actions' ;
import MatchModal from './MatchModal';
import MatchPanel from './MatchPanel'
import {GradientButton} from '../../../components/gradientButton';
class MatchesList extends Component {
constructor (props) {
super(props);
this.state = {
date: this.getToday(),
isModalVisible: false ,
}
this.renderItem = this.renderItem.bind(this);
this.showNewMatchDialog = this.showNewMatchDialog.bind(this);
this.onSaveMatch = this.onSaveMatch.bind(this);
this.onSuccess = this.onSuccess.bind(this);
this.onError = this.onError.bind(this);
}
componentDidMount () {
}
renderItem ({item , index}) {
return (<MatchPanel index={index} />)
}
/* Get date format */
getToday () {
const dateString = moment.tz(Date.now(), 'Africa/khartoum').format()
const dateArray = dateString.replace('T', '-').split('-')
return dateArray.splice(0, 3)
}
_matchReset(){
//reset
this.props.homeTeamChanged(0);
this.props.awayTeamChanged(1);
this.props.homeScoreChanged('');
this.props.awayScoreChanged('');
this.props.setCurrentDate([]);
}
render () {
return (
<View style={styles.container}>
<FlatList
style={styles.listView}
ref='listRef'
data={this.props.matches}
renderItem={this.renderItem}
initialNumToRender={5}
keyExtractor={(item, index) => index.toString()}
/>
<TouchableHighlight
style={styles.addButton}
underlayColor='#ff7043' onPress={this.showNewMatchDialog}>
<Text style={{fontSize: 25, color: 'white'}}>+</Text>
</TouchableHighlight>
<Modal
isVisible={this.state.isModalVisible}
onBackdropPress={() => {
this.setState({ isModalVisible: false })
this._matchReset();
} }
animationInTiming={1000}
animationOutTiming={500}
backdropTransitionInTiming={1000}
backdropTransitionOutTiming={500}
>
{this.renderModalContent()}
</Modal>
</View>
);
}
/*
* <-----------------------------------------modal start------------------------------------------------>
*/
showNewMatchDialog(){
this.setState({
isModalVisible: true
});
}
renderFormError() {
return (<RkText rkType='danger'> {this.state.error} </RkText>);
}
renderModalContent = () =>{
return(
<View style = {rkstyles.matchPanel}>
<View>
{ this.renderFormError() }
</View>
<MatchModal/>
{this.renderButton()}
</View>
);
};
renderButton = () => (
<GradientButton
rkType='small'
colors = {['lightgrey', 'grey'] }
style={rkstyles.button}
text={'Save'}
onPress = {this.onSaveMatch.bind(this)}
/>
);
onSaveMatch(){
const {user , opponentId} = this.props; //opponentId is passed from Matches ^.^
const {homeTeam , awayTeam , homescore , awayscore , date} = this.props;
console.log('loggggg: '+date[0]+"-"+date[1]+"-"+date[2]);
//match object
const newMatch = {
homeTeam,
awayTeam ,
homescore ,
awayscore ,
date :this.getToday(),
oppId: opponentId ,
userId: user.uid,
};
//scores not empty
if(homeTeam!==undefined && awayTeam!==undefined && homescore!==undefined && awayscore!==undefined && date!==undefined&& homescore!='' &&awayscore!=''){
this.props.addMatch(newMatch, this.onSuccess, this.onError)
console.log('adding a new match');
}else{
if(homeTeam===undefined){
console.log('homeTEam is null');
}else if(awayTeam===undefined){
console.log('awayTeam is null');
}else if(homescore===undefined){
console.log('homescore is null');
}else if(awayscore===undefined){
console.log('awayscore is null');
}else if(date===undefined){
console.log('date is null');
}else{
console.log('please input the scores')
}
}
}
onSuccess(){
this.setState({
isModalVisible: false ,
});
this._matchReset();
}
onError(error){
this.setState({
error: error.message
});
// alert('error: '+ error.message);
}
}
/*
*<---------------------------------------modal end------------------------------------------------>
*/
function mapStateToProps (state , props){
return({
isLoading: state.matchesReducer.isLoading ,
matches: state.matchesReducer.matches ,
homeTeam: state.matchesReducer.homeTeam,
awayTeam: state.matchesReducer.awayTeam,
homescore: state.matchesReducer.homescore,
awayscore: state.matchesReducer.awayscore,
date: state.matchesReducer.date ,
user: state.authReducer.auth.user,
});
}
export default connect(mapStateToProps , { addMatch , homeTeamChanged , homeScoreChanged , awayScoreChanged , awayTeamChanged, setCurrentDate})(MatchesList);
let rkstyles = RkStyleSheet.create((theme) => ({
matchPanel: {
alignItems: 'center',
marginHorizontal: 20,
marginTop: 20
},
button: {
marginTop: 25,
marginHorizontal: 50,
marginBottom: 25
}
}));
const styles = StyleSheet.create({
container: {
flex: 1
},
// List View
listView: {
backgroundColor: '#fff',
flex: 6,
flexDirection: 'column',
paddingTop: 12
},
addButton:{
backgroundColor: '#ff5722',
borderColor: '#ff5722',
borderWidth: 1,
height: 50,
width: 50,
borderRadius: 50 / 2,
alignItems: 'center',
justifyContent: 'center',
position: 'absolute',
bottom: 20,
right: 20,
shadowColor: "#000000",
shadowOpacity: 0.8,
shadowRadius: 2,
shadowOffset: {
height: 1,
width: 0
}
} ,
})
|
import React from 'react';
const Prime = () => (
<div className="spacing-small" >
<i className="icon icon-prime primeUpsellIcon" />
|
<a>Try Fast, Free Shipping</a>
<i className="icon icon-popover" />
</div>
);
export default Prime;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.