text
stringlengths
7
3.69M
(function() { 'use strict'; angular.module('app.admin.directivas', [ ]).directive('administrador', administrador); function administrador() { return { scope: {}, templateUrl: 'app/admin/admin.html', controller: 'adminCtrl', controllerAs: 'vm' }; } })();
import React from 'react'; import { prefix } from '../variable'; import { YearProps } from '../Props'; class Year extends React.PureComponent<YearProps> { render() { const { children, onClick } = this.props; return ( <td className={`${prefix}-cell`}> <div className={`${prefix}-year`} onClick={!children ? () => null : onClick}> {children} </div> </td> ); } } export default Year;
import test from 'tape' import stop from '../../../signals/processes/stop' import { spy } from 'sinon' test('stop', (assert) => { const signal = spy() const next = spy() stop()(signal)(next) assert.ok(!signal.getCall(0)) assert.end() })
import React from 'react'; import { Home } from './components/Home' import './App.css'; import Carrinho from './components/Carrinho.component'; import Filtro from './components/Filtro.component'; import styled from 'styled-components'; import BotaoCarrinho from './icones/add_shopping_cart-black-18dp.svg' class App extends React.Component { constructor(){ super(); this.state = { } } render(){ return ( <Home /> ); } } export default App;
var http = require('http'); var fs = require('fs'); var server = http.createServer(function(req, res) { if(req.url === '/' || req.url === '/home') { res.writeHead(200, {'Content-Type' : 'text/html'}); var myReadStream = fs.createReadStream(__dirname + '/index.html'); myReadStream.pipe(res); } else if(req.url === '/contact') { res.writeHead(200, {'Content-Type' : 'text/html'}); var myReadStream = fs.createReadStream(__dirname + '/contact.html'); myReadStream.pipe(res); } else if(req.url === '/api/family') { var family = [{name : 'amit', age:23}, {name: 'tanishka', age:18}]; res.writeHead(200, {'Content-Type' : 'application/json'}); res.end(JSON.stringify(family)); } else { res.writeHead(404, {'Content-Type' : 'text/html'}); var myReadStream = fs.createReadStream(__dirname + '/404.html'); myReadStream.pipe(res); } }); server.listen(9876, function() { console.log("listening at 9876"); });
import appDispatcher from "../dispatcher/dispatcher"; import { EventEmitter } from "events"; var assign = require("object-assign"); var energyCalculator = require("../libs/energyCalculator"); import nutritionCalculator from "../libs/nutritionCalculator"; var foodBuilder = require("../libs/foodBuilder"); var isLoading = false; function getEmptyExercise() { return { energy: "", time: "", duration: "" }; } function getEmptyMeasurements() { return { chest: "", stomach: "", thigh: "" }; } function clone() { return { exercises: [ getEmptyExercise(), getEmptyExercise() ], foods: [], measurements: getEmptyMeasurements() }; } var entry = clone(); var CHANGE_EVENT = "change"; function applyFavourites(favourites) { for (var i = 0; i < favourites.length; i++) { entry.foods.push(foodBuilder.build(favourites[i])); } } var dailyEntryStore = assign({}, EventEmitter.prototype, { emitChange: function() { this.emit(CHANGE_EVENT); }, addChangeListener: function(callback) { this.on(CHANGE_EVENT, callback); }, removeChangeListener: function(callback) { this.removeListener(CHANGE_EVENT, callback); }, getCurrent: function() { return { isLoading: isLoading, morningExercise: entry.exercises[0], eveningExercise: entry.exercises[1], entry: entry, foods: entry.foods, id: entry.id, energy: energyCalculator.calculate(entry), nutrition: nutritionCalculator.getNutritionTotals(entry), measurements: entry.measurements }; } }); function getExercise(exercise) { return { energy: exercise.energy || "", time: exercise.time || "", duration: exercise.duration || "" }; } function normalise(exercises) { if(exercises.length === 0) { return [ getEmptyExercise(), getEmptyExercise() ] } return [ getExercise(exercises[0]), getExercise(exercises[1]) ]; } function build(entryFromApi) { return { id: entryFromApi.id, exercises: normalise(entryFromApi.exercises), foods: entryFromApi.foods, measurements: entryFromApi.measurements } } appDispatcher.register(function(action) { switch(action.actionType) { case "dailyEntry_save_started": isLoading = true; dailyEntryStore.emitChange(); break; case "dailyEntry_get_started": isLoading = true; dailyEntryStore.emitChange(); break; case "dailyEntry_get_notfound": isLoading = false; entry = clone(); dailyEntryStore.emitChange(); break; case "dailyEntry_get_completed": isLoading = false; entry = build(action.entry); dailyEntryStore.emitChange(); break; case "dailyEntry_save_completed": isLoading = false; entry = build(action.entry); dailyEntryStore.emitChange(); break; case "favourites_get_completed": applyFavourites(action.favourites); dailyEntryStore.emitChange(); break; default: // no op } }); module.exports = dailyEntryStore;
function take_val(val) { var last_sym = document.getElementById('field').value.slice(-1); var oper = ['+','-','*','/']; if(oper.indexOf(val)!=-1 && oper.indexOf(last_sym)!=-1){ //замена последнего оператора back() } if(!( ((last_sym=='' || last_sym=='.') && (oper.indexOf(val)!=-1 ||val=='.' ))|| //оператор или точка после точки или в начале выражения (val=='.' && (oper.indexOf(last_sym)!=-1 || last_sym=='.')) || //точка после . или {+,-,*,/} ((val=='.' && last_num_contain_point()) //точка есть в последнем числе ))) { document.getElementById('field').value = document.getElementById('field').value + val; } } function equal() { var v = document.getElementById('field').value; document.getElementById('field').value = eval(v).toFixed(5); } function clean() { document.getElementById('field').value = ""; } function back() { var v = document.getElementById('field').value; document.getElementById('field').value = v.substring(0,v.length-1); } function last_num_contain_point() { var str = document.getElementById('field').value; var last_sym = str.slice(-1); if(['+','-','*','/','.',''].indexOf(last_sym)==-1) { while(['+','-','*','/',''].indexOf(last_sym)==-1) { str=str.substring(0,str.length-1); last_sym = str.slice(-1); console.log(str); if(last_sym=='.') { return true; } } } return false; }
import { ClassAttributor, Scope } from 'parchment'; const config = { scope: Scope.INLINE, whitelist: ['normal'], }; const DottedClass = new ClassAttributor('dotted', 'tkspec-dotted', config); export default DottedClass;
/** * Если роутов станет много -- их можно разбить по иерархии файлов */ // var checkAuth = require('middleware/checkAuth'); module.exports = function (app) { app.get('/users', require('./users').get); app.post('/users', require('./users').post); app.get('/', require('./root').get); }; //var express = require('express'); //var router = express.Router(); ///* GET home page. */ //router.get('/', function (req, res) { // res.render('index', { title: 'Express' }); //}); //module.exports = router;
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. $(function () { $("#playerListTable").tablesorter( {sortList: [[23,1]]} ); $("#playerNameFilter").select().focus(); }); $("#playerListTable").ready(function() { $("a[data-remote]").on("ajax:success", function(e, data) { if (data.bats) { $("#hitter" + data.id).fadeOut("slow"); } else { $("#pitcher" + data.id).fadeOut("slow"); } $("#playerNameFilter").select().focus(); }).on("ajax:error", function(e, xhr, status, errors) { alert('Could not draft: ' + JSON.stringify(errors)); $("#playerNameFilter").select().focus(); }); });
import { memoize , cloneDeep } from 'lodash'; import Session from './Session'; import metaProcessor from './metaProcessor'; function promiseResolveReduce(initialArgument, functions) { return functions.reduce((promise, func) => { return promise.then(func); }, Promise.resolve(initialArgument)); } function safeTransfer(value) { if(value instanceof Error){ //@TODO ERROR要有协议的传输 否则ERROR存在被其他更改风险 return value; } return cloneDeep(value); } export default class ResourceAgent { _requestInterceptors = []; _responseInterceptors = []; _session = null; resource = {}; constructor (resourceConfigs, processor) { this._session = new Session(); resourceConfigs.forEach(resourceConfig => { this.resource[resourceConfig.name] = this.createResource(resourceConfig, processor); }); } addRequestInterceptors(interceptors) { if (interceptors) { this._requestInterceptors.push(...([].concat(interceptors))); } } addResponseInterceptors(interceptors) { if (interceptors) { this._responseInterceptors.push(...([].concat(interceptors))); } } createResource(resourceConfig, processor) { let requestInterceptors = this._requestInterceptors; let responseInterceptors = this._responseInterceptors; let session = this._session; let { name, path, methods } = resourceConfig; return memoize(function(params) { return new Proxy({}, { // Proxy handler.get get: function(target, method, receiver) { if (methods.indexOf(method) == -1) { throw new Error(`[ResourceProxy] Can't use "${method}" , #${name}# must allow ${methods}`); } return function(payload) { let _metaProcessor = data => data; if (payload && payload.$meta) { let { $meta } = payload; delete payload.$meta; _metaProcessor = metaProcessor.bind(null, $meta); } let options = { name, path, method, session, params: params || null, payload: payload || null }; if (processor === null) { throw new Error(`Can't find processor.`); } let queue = [].concat(requestInterceptors, processor, safeTransfer, _metaProcessor, responseInterceptors); return promiseResolveReduce(options, queue); }; } }); }); } } var log = ()=>{ var args = Array.prototype.slice.apply(Array,arguments); args.unshift('app-'); console.log.apply(console, args); }
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "1dc4affed79d1593f2e65db95973e02e", "url": "/a-c/index.html" }, { "revision": "932a14d84b645c60c73f", "url": "/a-c/static/css/2.1f172402.chunk.css" }, { "revision": "932a14d84b645c60c73f", "url": "/a-c/static/js/2.7e011817.chunk.js" }, { "revision": "cb4293a028d0175415ddb31dc1aaaefb", "url": "/a-c/static/js/2.7e011817.chunk.js.LICENSE.txt" }, { "revision": "15b58ab9d947e3ff471f", "url": "/a-c/static/js/main.642343ec.chunk.js" }, { "revision": "e0aadfedacbb6837d297", "url": "/a-c/static/js/runtime-main.d62b4ef5.js" } ]);
var parseArgs = require('minimist'), log = require('./log'), pkg = require('../package.json'), version = pkg.version; var helpText = [ 'Release It! v' + version, '', 'Usage: release-it <increment> [options]', '', 'Use e.g. "release-it minor" directly as shorthand for "release-it --increment=minor".', '', '-c --config Path to local configuration options [default: ".release.json"]', '-d --dry-run Do not touch or write anything, but show the commands and interactivity', '-e --debug Output exceptions', '-f --force Allow empty Git commit, force tag.', '-g --github.release Release to GitHub', '-h --help Print this help', '-i --increment Increment the "major", "minor", or "patch" version; or specify version [default: "patch"]', '-m --message Commit message [default: "Release %s"]', '-n --non-interactive No interaction (assume default answers to questions)', '-p --npm.publish Auto-publish to npm (only relevant in --non-interactive mode)', '-v --version Print version number', '-V --verbose Verbose output' ].join('\n'); var aliases = { c: 'config', d: 'dry-run', e: 'debug', f: 'force', g: 'github.release', h: 'help', i: 'increment', m: 'message', n: 'non-interactive', p: 'npm.publish', v: 'version', V: 'verbose' }; module.exports = { version: function() { log.log('v' + version); }, help: function() { log.log(helpText); }, parse: function(argv) { var options = parseArgs(argv, { boolean: true, alias: aliases }); options.increment = options.i = (options._[0] || options.i); options.commitMessage = options.message; return options; } };
import React, { useState } from 'react'; const CouponArea = () => { const [checkoutLogin, setCheckoutLogin] = useState(false); const [checkoutCoupon, setCheckoutCoupon] = useState(false); return ( <> <section className="coupon-area pt-100 pb-30"> <div className="container"> <div className="row"> <div className="col-md-6"> <div className="coupon-accordion"> <h3>Returning customer? <span onClick={()=> setCheckoutLogin(!checkoutLogin)} id="showlogin">Click here to login</span></h3> {checkoutLogin && <div id="checkout-login" className="coupon-content"> <div className="coupon-info"> <p className="coupon-text">Quisque gravida turpis sit amet nulla posuere lacinia. Cras sed est sit amet ipsum luctus.</p> <form onSubmit={e => e.preventDefault()}> <p className="form-row-first"> <label>Username or email <span className="required">*</span></label> <input type="text" /> </p> <p className="form-row-last"> <label>Password <span className="required">*</span></label> <input type="text" /> </p> <p className="form-row"> <button className="tp-btn" type="submit">Login</button> <label> <input type="checkbox" /> Remember me </label> </p> <p className="lost-password"> <a href="#">Lost your password?</a> </p> </form> </div> </div>} </div> </div> <div className="col-md-6"> <div className="coupon-accordion"> <h3>Have a coupon? <span onClick={()=> setCheckoutCoupon(!checkoutCoupon)} id="showcoupon">Click here to enter your code</span></h3> {checkoutCoupon && <div id="checkout_coupon" className="coupon-checkout-content"> <div className="coupon-info"> <form onSubmit={e => e.preventDefault()}> <p className="checkout-coupon"> <input type="text" placeholder="Coupon Code" /> <button className="tp-btn" type="submit">Apply Coupon</button> </p> </form> </div> </div>} </div> </div> </div> </div> </section> </> ); }; export default CouponArea;
describe('P.views.ReportsWeeklyLayout', function() { var View = P.views.ReportsWeeklyLayout; var Model = P.models.workouts.Report; var noop = function() {}; describe('date change', function() { beforeEach(function() { spyOn(Model.prototype, 'pFetch').and.returnValue(new Promise(noop)); this.model = new Model(); this.view = new View({ model: this.model, userID: 'foo' }); }); it('must link to the next and previous years', function() { this.view.date = moment('2015-05-01', 'YYYY-MM-DD'); this.view.dispAttr = 'reps'; this.view.render(); expect(this.view.$('.js-period-after').attr('href')) .toBe('/a/reports/weekly/foo/2016?m=reps'); expect(this.view.$('.js-period-before').attr('href')) .toBe('/a/reports/weekly/foo/2014?m=reps'); }); }); });
import React from 'react'; import {createStackNavigator, createAppContainer,} from 'react-navigation'; import HomeScreen from './src/screens/HomeScreen'; import StudentScreen from './src/screens/StudentScreen'; import LoginScreen from './src/screens/LoginScreen'; import LoginStudentScreen from './src/screens/LoginStudentScreen'; import SettingsScreen from './src/screens/SettingsScreen'; import SignUpScreen from './src/screens/SignUpScreen'; import SignUpAdmin from './src/screens/SignUpAdmin'; import Adminscreen from './src/screens/Adminscreen'; import AssignDriver from './src/screens/AssignDriver'; import ListItem from './src/screens/ListItem'; import ItemComponent from './src/components/ItemComponent'; //import CurrentLocationButton from './src/screens/CurrentLocationButton'; import * as firebase from 'firebase'; // // Config Firebase // const firebaseConfig = { // apiKey: "AIzaSyDb-MHYH3z8wtKf-oMqevKUAZRFQ2cg6xg", // authDomain: "polybus-gps.firebaseapp.com", // databaseURL: "https://polybus-gps.firebaseio.com", // projectId: "polybus-gps", // storageBucket: "", // messagingSenderId: "942603006584", // appId: "1:942603006584:web:0dbbdafa56c59063" // } // // Initialize Firebase // firebase.initializeApp(firebaseConfig); // console.log('firebase', firebase); // firebase.database().ref('trackers').on('value', (data) => { // console.log('Data', data.toJSON()); // }) const Rootstack = createStackNavigator( { Home: HomeScreen, Student: StudentScreen, login: LoginScreen, login1:LoginStudentScreen, Settings:SettingsScreen, SignUp:SignUpScreen, SignUp1:SignUpAdmin, // CurrentLocationButton:CurrentLocationButton , Admin:Adminscreen, AssignDriver:AssignDriver, ListItem:ListItem, ItemComponent:ItemComponent }, { initialRouteName: "Home" } ); const AppContainer = createAppContainer(Rootstack); export default function App() { return ( <AppContainer /> ); }
"use strict"; const jeopardyGrid = new JeopardyGrid({ rows: 6, columns: 6, parentElement: document.querySelector("main"), cell: { width: "90px", height: "60px", border: "3px solid black", color: "blue", classList: ["cell", "hidden"], } });
const numWordsEl = document.querySelector('#numWords'); const resetEl = document.querySelector('#reset'); const puzzleEl = document.querySelector('#puzzle'); const guessesEl = document.querySelector('#guesses'); let game; // Check numWords const checkNumberWords = () => { // debugger let numWords = Number.parseFloat(numWordsEl.value); if (typeof numWords === 'number' && !isNaN(numWords)) { if (numWords < 0 || numWords > 9) { numWords = 1; alert('Number of words must be more than 0 and less than 10!'); } } else { numWords = 1; } return numWords; }; // render Html const renderHtml = () => { if (game._status === 'playing') { puzzleEl.textContent = game.puzzle(); guessesEl.textContent = `You have ${game.remainingGuesses} chances`; } if (game._status === 'isWin') { puzzleEl.textContent = `Congretulations! You are winner! You guessed word - "${game.puzzle().toUpperCase()}".`; guessesEl.textContent = `You won by ${(Math.round(game.word.length / 3))} steps`;; } if (game._status === 'isLose') { puzzleEl.textContent = `Good try! Try again. Your guess word is - "${game.word.join('').toUpperCase()}".`; guessesEl.textContent = `You lost all your chances "${game.remainingGuesses}"`; } }; // Start Game const startGame = async () => { const numWords = checkNumberWords(); await fetchWord(numWords).then((response) => { game = new Puzzle(response); }).catch((err) => console.log(err)); renderHtml(); }; startGame(); // Reset click resetEl.addEventListener('click', async () => { await startGame(); renderHtml(); console.log(game); console.log(game.puzzle()); }); // Keypress window.addEventListener('keypress', (e) => { const guess = String.fromCharCode(e.charCode).toLowerCase(); game.makeGuess(guess); renderHtml(); console.log(game); });
var searchData= [ ['current_5falgorithm_91',['current_algorithm',['../_main_8c.html#a930f72cb04917dc2aa6101def122572a',1,'current_algorithm():&#160;Main.c'],['../values_8h.html#a930f72cb04917dc2aa6101def122572a',1,'current_algorithm():&#160;Main.c']]], ['current_5fimage_92',['current_image',['../_main_8c.html#a53b606c00e8fe1eb14232a47d723f71a',1,'current_image():&#160;Main.c'],['../values_8h.html#a53b606c00e8fe1eb14232a47d723f71a',1,'current_image():&#160;Main.c']]] ];
var express = require('express'); var router = express.Router(); const userMap = require('../models/model') const jsORM = require('js-hibernate'); const dbconfig = require('../config/config'); // console.log(dbconfig); const session = jsORM.session(dbconfig); const userController = require('../controllers/user/signup') /* GET users listing. */ router.get('/list_user/:id', function(req, res, next) { res.send('respond with a resource'); }); router.post('/sign_up', userController.signUp(session, userMap)) module.exports = router;
import * as auth from './auth' import * as firebase from './firebase' import * as googleprovider from './google-auth' import * as database from './database' // Layer that protect the user to access direct the firebase file export { auth, firebase, googleprovider, database }
ig.module( 'game.entities.stall' ) .requires( 'plusplus.core.entity' ) .defines(function () { EntityStall = ig.EntityExtended.extend({ size: { x: 128, y: 60 }, offset: { x: 0, y: 20 }, animSheet: new ig.AnimationSheet('media/buildings/stall.png', 128, 80), animSettings: { idle: { sequence: [0], frameTime: 1 } }, collides: ig.Entity.COLLIDES.FIXED, // The associated trader entity. It gets set manually in Weltmeister, and can be null // (a stall doesn't have to "own" a trader) trader: null, initProperties: function () { // Call the parent constructor first so all of the entities are drawn and positioned this.parent(); // Store the associated trader entity var trader = ig.game.getEntityByName(this.trader); this.trader = trader || null; } }); });
const A; // 错误,不能只声明不赋值 A = 123;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FindExercise = void 0; class FindExercise { constructor(exerciseRepo) { this.exerciseRepo = exerciseRepo; } async execute(id) { var exercise = null; var exercises = null; if (id) { exercise = await this.exerciseRepo.findById(id); } else { exercises = await this.exerciseRepo.findAll(); } return exercise || exercises; } } exports.FindExercise = FindExercise;
import React from "react"; class EventCreate extends React.Component { state = {}; constructor(p) { super(); this.state = { form: p.event }; } bindInput = key => { return { value: this.state.form[key], onChange: e => this.setState({ form: { ...this.state.form, [key]: e.target.value } }) }; }; render() { const { event, onClose, onSave } = this.props; const { summary, start, end } = {}; console.log(this.props); return ( <div> <div className="card-content"> <form className="col s12"> <div className="row" style={{ minWidth: 400 }}> <div className="input-field"> <i className="material-icons prefix">event_note</i> <input id="icon_prefix" type="text" {...this.bindInput("summary")} defaultValue={summary} placeholder="Event name" /> </div> <div className="input-field"> <i className="material-icons prefix">access_time</i> <input id="icon_prefix" type="text" {...this.bindInput("startTime")} placeholder="Time" /> </div> <div className="input-field"> <i className="material-icons prefix">people</i> <input placeholder="Add people to invite" value={''} defaultValue={"qwer"} /> </div> <div className="input-field"> <i className="material-icons prefix">place</i> <input placeholder="Location" defaultValue={"qwer"} {...this.bindInput("location")} /> </div> </div> </form> </div> <div className="card-actions"> <a className="waves-effect waves-teal btn-flat" onClick={() => onSave(this.state.form)} > Save </a> <a className="waves-effect waves-teal btn-flat" onClick={onClose}> Cancel </a> </div> </div> ); } } export default EventCreate;
import React from 'react'; import './App.css'; import settings from './config.js' class App extends React.Component { constructor(props) { super(props); this.state = { yo_responses: [] }; } onYoClickHandler = () => { fetch(`${settings.API_URL}/api/v1/yo`) .then(res => res.json()) .then( (result) => { this.setState( { yo_responses: this.state.yo_responses.concat(result.message) } ); } ); } render() { return ( <div className="App"> <h1>Yo Frontend</h1> <p> Connected to { settings.API_URL }</p> <div> <button onClick={this.onYoClickHandler}>Say "Yo"</button> { this.state.yo_responses.map(response => ( <p>{ response }</p> ))} </div> </div> ); } } export default App;
var db = require('../../../config/db.config'); db.bookmarks.belongsTo(db.jobpostcollection,{foreignKey: 'job_id'}); db.jobpostcollection.belongsTo(db.registration,{foreignKey: 'user_id'}); db.jobpostcollection.belongsTo(db.companybio,{foreignKey: 'user_id'}); db.bookmarks.belongsTo(db.registration,{foreignKey: 'save_id'}); db.bookmarks.belongsTo(db.candidate_bio,{foreignKey: 'user_id'}); db.bookmarks.belongsTo(db.work,{foreignKey: 'user_id'}); exports.create = (req, res) =>{ if(!req.body.role_type){ return res.json({ success: false, message: "role type can not be empty" }) } if(!req.body.user_id){ return res.json({ success: false, message: "user_id can not be empty" }) } if(!req.body.save_id){ return res.json({ success: false, message: "save_id can not be empty" }) } if(!req.body.job_id){ return res.json({ success: false, message: "job_id can not be empty" }) } db.bookmarks.findOne({where:{save_id: req.body.save_id}}).then(data =>{ if(data){ db.bookmarks.update({ user_id: req.body.user_id, job_id: req.body.job_id, role_type: req.body.role_type, },{ where:{save_id: data.save_id} }).then(()=>{ return res.json({ success: true, message: "Update successfully" }) }).catch(err=>{ return res.json({ success: false, message: "Something went to wrong! "+err }) }) } if(!data){ const newbookmark = new db.bookmarks({ user_id: req.body.user_id, save_id: req.body.save_id, job_id: req.body.job_id, role_type: req.body.role_type, }); newbookmark.save().then(data=>{ return res.json({ success: true, data: data }) }).catch(err=>{ return res.json({ success:false, message: "something went to wrong! "+err }) }) } }) } // get saved jobs exports.getsavedjobs = (req,res) =>{ if(!req.body.role_type){ return res.json({ success: false, message: "role type can not be empty" }) } if(!req.body.user_id){ return res.json({ success: false, message: "user id can not be empty" }) } if(req.body.role_type == 2){ db.bookmarks.findAll({ attributes:['id','save_id','role_type'], where:{user_id: req.body.user_id}, include: [ { attributes:[['id','jobPostId'],'user_id','job_title','company_industry_location','company_lat','company_lng','last_date_to_apply'], model: db.jobpostcollection, include: [ { attributes:[['id','companyId'],'company_name'], model: db.registration, include: [ { attributes:['profile_pic'], model: db.companybio } ] } ] } ] }).then(data=>{ return res.json({ success:true, data:data }) }).catch(err=>{ res.json({ success: false, message: "Something wentto wrong! "+err }) }) } if(req.body.role_type == 1){ db.bookmarks.findAll({ attributes:[['id','bookmarkId'],'save_id','role_type'], where:{user_id: req.body.user_id}, include: [ { attributes:['id','fullName'], model: db.registration, include: [ { attributes:[['id','candidateBioId'],'user_id','profile_pic'], model: db.candidate_bio }, { attributes: [['id','workId'],'name_of_company','designation', 'to_date'], order: [ ['to_date', 'DESC'], ], limit:1, model: db.work } ] } ] }).then(data=>{ return res.json({ success:true, data:data }) }).catch(err=>{ res.json({ success: false, message: "Something wentto wrong! "+err }) }) } }
(function(shoptet) { function getSelectValue(select) { return select.value; } function getCheckedInputValue(containingElement) { var inputs = containingElement.querySelectorAll('input[type="radio"]'); for (var i = 0; i < inputs.length; i++) { if (inputs[i].checked) { return inputs[i].value; } } return false; } function createDocumentFromString(string) { return new DOMParser().parseFromString(string, "text/html"); } function serializeData(data) { if (typeof data === "object") { try { var params = []; for (key in data) { params.push(key + '=' + data[key]); } return params.join('&'); } catch(e) { console.error(e); return data; } } return data; } /** * Create object from form through FormData object * Ready for request consume FormData Directly */ function serializeForm(form) { var fallBack = form; if (typeof form === 'undefined' || form === null) { return form; } if (form instanceof jQuery) { form = form.get(0); } if (form instanceof HTMLFormElement) { form = new FormData(form); } if (form instanceof FormData) { var object = {}; try { var formDataEntries = form.entries(), formDataEntry = formDataEntries.next(), pair; while (!formDataEntry.done) { pair = formDataEntry.value; object[pair[0]] = encodeURIComponent(pair[1]); formDataEntry = formDataEntries.next(); } return serializeData(object); } catch (e) { console.error(e); // Polyfill doesn't work or something wrong => jQuery fallBack form = $(fallBack).serialize(); return form; } } else { return form; } } /** * Create name for custom event depending on form action * * @param {String} action * action = action attribute of submitted form */ function createEventNameFromFormAction(action) { var actionName = action.replace(shoptet.config.cartActionUrl, ''); actionName = actionName.replace(/\//gi, ''); actionName = 'ShoptetCart' + actionName.charAt(0).toUpperCase() + actionName.slice(1); return actionName; } /** * Check if element width fits into its closest positioned ancestor element (offset parent) * * @param {Element} el * el = element * @param {Number} paddingRight * paddingRight = optional - width reserved on offset parent right side in pixels */ function fitsToParentWidth(el, paddingRight) { var reserved = typeof paddingRight === 'undefined' ? 0 : paddingRight; var parent = el.offsetParent; if (!parent) { return true; } if (el.offsetLeft + el.offsetWidth > parent.offsetWidth - reserved) { return false; } return true; } function addClassToElements(elements, className) { for (var i = 0; i < elements.length; i++) { elements[i].classList.add(className); } } function removeClassFromElements(elements, className) { for (var i = 0; i < elements.length; i++) { elements[i].classList.remove(className); } } /** * Move cursor to the end of input or textarea */ function moveCursorToEnd(el) { if (typeof el.selectionStart == "number") { el.selectionStart = el.selectionEnd = el.value.length; } else if (typeof el.createTextRange != "undefined") { el.focus(); var range = el.createTextRange(); range.collapse(false); range.select(); } } /** * See https://github.com/jashkenas/underscore/blob/master/modules/throttle.js * Returns a function, that, when invoked, will only be triggered at most once * during a given window of time. Normally, the throttled function will run * as much as it can, without ever going more than once per `wait` duration; * but if you'd like to disable the execution on the leading edge, pass * `{leading: false}`. To disable execution on the trailing edge, ditto. */ function throttle(func, wait, options) { var now = Date.now || function () { return new Date().getTime(); }; var timeout, context, args, result; var previous = 0; if (!options) options = {}; var later = function () { previous = options.leading === false ? 0 : now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; var throttled = function () { var _now = now(); if (!previous && options.leading === false) previous = _now; var remaining = wait - (_now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = _now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; throttled.cancel = function () { clearTimeout(timeout); previous = 0; timeout = context = args = null; }; return throttled; } shoptet.common = shoptet.common || {}; shoptet.scripts.libs.common.forEach(function(fnName) { var fn = eval(fnName); shoptet.scripts.registerFunction(fn, 'common'); }); shoptet.common.keyCodes = { backspace: 8, enter: 13, escape: 27 }; })(shoptet);
import React, { Component } from 'react'; import { lottery } from './lottery'; import { web3 } from './web3'; import './App.css'; class App extends Component { state = { manager: '', players: [], balance: '', value: '', message: '' }; async componentDidMount() { const [ manager, players, balance ] = await Promise.all([ lottery.methods.manager().call(), lottery.methods.getPlayers().call(), web3.eth.getBalance(lottery.options.address) ]); this.setState({ manager, players, balance }); } onSubmit = async ( event ) => { event.preventDefault(); const accounts = await web3.eth.getAccounts(); this.setState({ message: 'Waiting on transaction success...' }); await lottery.methods.enter().send({ from: accounts[ 0 ], value: web3.utils.toWei(this.state.value, 'ether') }); this.setState({ message: 'You have benn entered!' }); }; onClick = async () => { const accounts = await web3.eth.getAccounts(); this.setState({ message: 'Waiting on transaction success...' }); await lottery.methods.pickWinner().send({ from: accounts[ 0 ] }); this.setState({ message: 'A winner has been picker!' }); }; render() { return ( <div> <h2>Lottery Contract</h2> <p>This contract is managed by {this.state.manager}</p> <p>There are currenty {this.state.players.length} people entered competing to win {web3.utils.fromWei(this.state.balance, 'ether')} ether</p> <hr/> <form onSubmit={this.onSubmit}> <h4>Want to try your luck?</h4> <div> <label>Amount of ether to enter</label> <input onChange={event => this.setState({ value: event.target.value })} type="text" value={this.state.value}/> </div> <button type="submit">Enter</button> </form> <hr/> <h4>Ready to pick a winner?</h4> <button onClick={this.onClick}>Pick a winner!</button> <hr/> <h2>{this.state.message}</h2> </div> ); } } export default App;
import DS from 'ember-data'; const { Model, attr } = DS; export default class PostalAddressModel extends Model { @attr() country; @attr() locality; @attr() postalCode; @attr() streetAddress; }
import { createRouter, createWebHashHistory } from 'vue-router' import { reAuthentication } from '@/main' import { routes } from '@/router/routes' import store from '@/store/vuexStore' const router = createRouter({ history: createWebHashHistory(), routes, }) // Wait for store router.beforeEach(async (to, from, next) => { await reAuthentication // Set the title according to the meta if (store.getters['user/user'].username && to.matched.some(r => r.name == "profile")) { document.title = store.getters['user/user'].username + ' - ' + to.meta.title || process.env.VUE_APP_NAME } else { document.title = to.meta.title || process.env.VUE_APP_NAME } next() }) export { router }
//财务账户-确认提取保证金 import React, { Component, PureComponent } from 'react'; import { StyleSheet, Dimensions, View, Text, Button, Image, ScrollView, TouchableOpacity, Keyboard } from 'react-native'; import { connect } from 'rn-dva'; import Header from '../../components/Header'; import CommonStyles from '../../common/Styles'; import ImageView from '../../components/ImageView'; import TextInputView from '../../components/TextInputView'; import * as nativeApi from '../../config/nativeApi'; import Line from '../../components/Line'; import Content from '../../components/ContentItem'; import * as requestApi from '../../config/requestApi'; const { width, height } = Dimensions.get('window'); import CheckButton from '../../components/CheckButton'; import CommonButton from '../../components/CommonButton'; import * as regular from '../../config/regular'; class AccountConfirmDeposit extends PureComponent { static navigationOptions = { header: null, } constructor(props) { super(props) const params = props.navigation.state.params || {} this.state = { topParams:params, code: '', phone: global.loginInfo && global.loginInfo.phone || '', payPassword: "", callback: params && params.callback || (() => { }) } } componentDidMount() { } componentWillUnmount() { } goSetPassword=()=>{ CustomAlert.onShow( "confirm", "您未设置过支付密码,是否立即设置?", "提示", () => { }, () => { this.props.navigation.navigate('MerchantSetPswValidate',{goBackRouter:'AccountConfirmDeposit',}) }, botton1Text = "去设置", botton2Text = "取消", ); } // 是否设置过支付密码 getPayPwdStatus = (callback) => { let textPwdIsSet = this.props.setPayPwdStatus.result if(!textPwdIsSet){ //undefind || 0 if(textPwdIsSet=== 0){ this.goSetPassword(callback) }else{ Loading.show() console.log('获取设置支付密码状态1') requestApi.merchantPayPasswordIsSet().then(res => { console.log('获取设置支付密码状态', res) this.props.userSave({setPayPwdStatus:res}) if (res.result === 0) { // 没有设置支付密码 this.goSetPassword(callback) } else { callback() } }).catch(err => { console.log(err) }); } }else{ callback() } }; confirm = () => { // console.log(this.state.callback) // this.state.callback() // this.props.navigation.navigate('AccountDepositSuccess',topParams) // return const { code, phone, password,topParams } = this.state const { navigation } = this.props const params = { code, phone, password, merchantType:topParams.merchantType } if (!regular.phone(params.phone)) { Toast.show('请输入正确格式的手机号'); } else if (!regular.checkcode(params.code)) { Toast.show('请输入正确格式的验证码'); } else if (!password) { Toast.show('请输入支付密码') } else { this.getPayPwdStatus(()=>{ Loading.show() let func = requestApi.merchantCashDepositRefund func(params).then(data => { this.state.callback() navigation.navigate('AccountDepositSuccess',topParams) }).catch(err => { console.log(err) }); }) } } //获取验证码 _checkBtn = () => { Keyboard.dismiss(); if (this.refs.getCode.state.disabled) { return; } const { phone } = this.state; if (phone.trim() === '') { Toast.show('请输入手机号'); return } if (!regular.phone(phone)) { Toast.show('请输入正确格式的手机号') } else { Loading.show(); requestApi.sendAuthMessage({ phone, bizType: 'WITHDRAWAL_CASH_DEPOSIT', }).then(() => this.refs.getCode.sendVerCode()) .catch((err)=>{ }); } } render() { const { navigation } = this.props; let items = [ { title: '联盟商手机号', type: 'input', key: 'phone', editable:false}, { title: '验证码', type: 'input', key: 'code',editable:true }, { title: '支付密码',type: 'input', key: 'password',editable:true }, ] return ( <View style={styles.container}> <Header title='确认提取' navigation={navigation} goBack={true} /> <ScrollView alwaysBounceVertical={false} style={{ flex: 1 }}> <View style={styles.content}> <View style={{ alignItems: 'center' }}> { items.map((item, index) => { return ( <Content key={index} style={{ height: 50, justifyContent: 'center' }}> <TextInputView editable={item.editable} placeholder={item.title} inputView={{ flex: 1, paddingHorizontal: 15 }} style={{ lineHeight: 20, height: 20, color: '#777' }} placeholderTextColor={'#ccc'} onChangeText={(data) => {this.setState({ [item.key]: data })}} maxLength={item.key == 'phone' ? 11 : null} secureTextEntry={item.key == 'password' ? true : false} value={this.state[item.key]} /> { item.key == 'code' ? <CheckButton ref="getCode" onClick={this._checkBtn} delay={60} name='发送验证码' styleBtn={[styles.code, { borderWidth: 0, borderLeftWidth: 1, borderRadius: 0, borderColor: '#F1F1F1' }]} title={{ color: '#4A90FA', fontSize: 12 }} /> : null } </Content> ) }) } </View> <CommonButton title='确认提取' onPress={() => this.confirm()} style={{marginBottom:0}}/> <CommonButton title='暂不提取' style={{backgroundColor:'#fff'}} textStyle={{color:CommonStyles.globalHeaderColor}} onPress={()=>navigation.navigate('FinancialAccount')} /> </View> </ScrollView> </View> ); } }; const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, backgroundColor: CommonStyles.globalBgColor }, content: { alignItems: 'center', paddingBottom: 10 }, code: { backgroundColor: '#fff', position: 'absolute', right: 15, top: 15, height: 22, alignItems: 'center', justifyContent: 'center', borderWidth: 1, borderColor: '#4A90FA', borderRadius: 10 }, shopName: { fontSize: 14, color: '#999999', width: width - 20, textAlign: 'left', marginTop: 8, marginBottom: 20, marginLeft: 10, paddingHorizontal:10 } }); export default connect( (state) => ({ setPayPwdStatus:state.user.setPayPwdStatus || {} }), { userSave:(payload={})=>({type:'user/save',payload}) } )(AccountConfirmDeposit);
var mysql = require("mysql"); var inquirer = require("inquirer"); // create the connection information for the sql database var connection = mysql.createConnection({ host: "localhost", // Your port; if not 3306 port: 3306, // Your username user: "root", // Your password password: "password", database: "fantasy_bamazon" }); // connect to the mysql server and sql database connection.connect(function(err) { if (err) throw err; // run the start function after the connection is made to prompt the user start(); }); // function which prompts the user for what action they should take function start() { connection.query("SELECT * FROM products", function(err, response){ if (err) throw err; console.table(response); inquirer .prompt({ name: "welcome", type: "list", message: "What would you like to do?", choices: ["BUY SOMETHING", "EXIT"] }) .then(function(answer) { // based on their answer, either call the bid or the post functions if (answer.welcome === "BUY SOMETHING") { buyItem(); } else{ connection.end(); } }); }) } function buyItem() { // query the database connection.query("SELECT * FROM products", function(err, results) { if (err) throw err; // inquirer .prompt([ { name: "choice", type: "rawlist", choices: function() { var choiceArray = []; for (var i = 0; i < results.length; i++) { choiceArray.push(results[i].product_name); } return choiceArray; }, message: "What item do you want to buy? (enter the ID# or when selected, press enter)" }, { name: "stock", type: "number", message: "How many would you like to buy?" } ]) .then(function(answer) { // get the information of the chosen item var chosenItem; for (var i = 0; i < results.length; i++) { if (results[i].product_name === answer.choice) { chosenItem = results[i]; } } // determine if stock is enough if (chosenItem.stock_quantity > parseInt(answer.stock)) { // bid was high enough, so update db, let the user know, and start over connection.query( "UPDATE products SET stock_quantity = stock_quantity - ? WHERE ?", [ answer.stock, { id: chosenItem.id } ], function(error) { if (error) throw err; console.log("We have enough in stock!"); console.log("Thank you for your business! Your total is " + "$" + parseInt(answer.stock) * chosenItem.price); start(); } ); } else { // not enough stock console.log("Not enough in stock"); start(); } }); }); }
const backslashSoup = pattern => new RegExp(pattern.replace(/\\/g, '\\\\')); module.exports = (plugins = []) => ({ extensions: ['js'], include: dirPath => plugins.some(plugin => backslashSoup(`(\\|/)(katulong-plugin-${plugin})+(\\|/)src(\\|/)index.js$`).test(dirPath)), recurse: true });
// function invoiceTotal(amount1, amount2, amount3, amount4) { // return amount1 + amount2 + amount3 + amount4; // } function invoiceTotal(...args) { return args.reduce((a, b) => a + b, 0); } console.log(invoiceTotal(20, 30, 40, 50)); // works as expected console.log(invoiceTotal(20, 30, 40, 50, 40, 40)); // does not work; how can you make it work?
import axios from 'axios'; import { OFFER_LOADING, EDIT_OFFER, ADD_OFFER, DELETE_OFFER, GET_OFFERS, GET_OFFER, GET_ERRORS, } from '../constants/action-types'; export const getOffer = offerId => dispatch => { dispatch(setOfferLoading()); axios .get('/api/career/' + offerId) .then(res => dispatch({ type: GET_OFFER, payload: res.data, }) ) .catch(err => dispatch({ type: GET_OFFER, payload: err.response.data, }) ); }; export const getOffers = () => dispatch => { dispatch(setOfferLoading()); axios .get('/api/career') .then(res => dispatch({ type: GET_OFFERS, payload: res.data, }) ) .catch(err => dispatch({ type: GET_OFFERS, payload: [], }) ); }; export const addOffer = (offerData, history) => dispatch => { axios .post('/api/career/', offerData) .then(res => { dispatch({ type: ADD_OFFER, payload: res.data, }); history.push('/offer/' + res.data._id); }) .catch(err => dispatch({ type: GET_ERRORS, payload: err.response.data, }) ); }; export const editOffer = (offerData, history) => dispatch => { axios .put('/api/career/', offerData) .then(res => { dispatch({ type: EDIT_OFFER, payload: res.data, }); history.push('/offer/' + res.data._id); }) .catch(err => dispatch({ type: GET_ERRORS, payload: err.response.data, }) ); }; export const deleteOffer = (offerId, history) => dispatch => { axios .delete('/api/career/' + offerId) .then(() => { history.push('/offers'); dispatch({ type: DELETE_OFFER, payload: offerId, }); }) .catch(err => dispatch({ type: GET_ERRORS, payload: err.response.data, }) ); }; export const sendApplication = ({ offerId, ...data }, history) => dispatch => { axios .post(`/api/career/${offerId}/apply`, data) .then(() => { history.push({ pathname: '/success', state: { message: 'Application send!', }, }); }) .catch(err => dispatch({ type: GET_ERRORS, payload: err.response.data, }) ); }; export const setOfferLoading = () => { return { type: OFFER_LOADING, }; };
//primitve Datatypes - stack memory number String Boolean null undefined Symbol //non primitive datatypes/ reference datatypes (Heap memory) function object
/*! * Wpier * Copyright(c) 2006-2011 Sencha Inc. * * */ Ext.define('Gvsu.modules.tender.controller.BidPos', { extend: 'Core.controller.Controller' ,id:'tender-bidpos-win' ,launcher: { text: D.t('Заявки участников'), iconCls:'tender' } ,getPermissions: function() { this.Permissions = { read: true, add: false, modify: false, del: false } } });
module.exports = function(employee, EmployeesSvc) { this.departments = EmployeesSvc.departments this.employee = employee }
//接口地址设置 var baseUrl = "http://192.168.5.138:8080/lansoft/"; var imgBasePath = "http://192.168.5.138:8080/lansoft-images/";
//Filename: models/user define([ 'underscore', 'backbone' ], function(_, Backbone){ var InstagramBlock = Backbone.Model.extend({ defaults: { name: 'undefined', imageUrl: 'undefined', width: '612', height: '612' } }); return InstagramBlock; });
var w = window.innerWidth, h = window.innerHeight, color = d3.scale.category20(), fontSize = 13; // 碰撞检测 function collide(node) { var r = node.radius, nx1 = node.x - r, nx2 = node.x + r, ny1 = node.y - r, ny2 = node.y + r; return function (quad, x1, y1, x2, y2) { if (quad.point && (quad.point !== node)) { var x = node.x - quad.point.x, y = node.y - quad.point.y, l = Math.sqrt(x * x + y * y), r = node.radius + quad.point.radius + 10; if (l < r) { l = (l - r) / l * 0.05; node.x -= x *= l; node.y -= y *= l; quad.point.x += x; quad.point.y += y; } } return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1; }; } d3.json('data.json', function (err, data) { if (err) throw err; document.getElementById('loading').className = 'done'; var nodes = data.map(function (item) { var textPerLine = Math.ceil(Math.sqrt(item.todo.length)); var lineCount = Math.ceil(item.todo.length / textPerLine); return { todo: item.todo, finished: item.finished, lineCount: lineCount, textPerLine: textPerLine, radius: Math.sqrt(textPerLine * textPerLine + lineCount * lineCount) * fontSize / 2 + 10, }; }); var deltaPoint = { x: null, y: null }; var dragStartPoint = { x: null, y: null }; var tranStartPoint = { x: 0, y: 0 }; // 使用原生拖动 var drag = d3.behavior.drag() .origin(function (d) { return d; }) .on('drag', function () { var pageX, pageY; if (d3.event.sourceEvent.touches) { pageX = d3.event.sourceEvent.touches[0].pageX; pageY = d3.event.sourceEvent.touches[0].pageY; } else { pageX = d3.event.sourceEvent.pageX; pageY = d3.event.sourceEvent.pageY; } if (dragStartPoint.x === null) { dragStartPoint = { x: pageX, y: pageY }; } else { svg.attr('style', function () { deltaPoint.x = pageX - dragStartPoint.x; deltaPoint.y = pageY - dragStartPoint.y; var newX = tranStartPoint.x + deltaPoint.x; var newY = tranStartPoint.y + deltaPoint.y; return 'transform:translate3d(' + newX + 'px,' + newY + 'px,0)'; }); } d3.event.sourceEvent.preventDefault(); }) .on('dragend', function () { var newX = tranStartPoint.x + deltaPoint.x; var newY = tranStartPoint.y + deltaPoint.y; tranStartPoint = { x: newX, y: newY }; dragStartPoint = { x: null, y: null }; }); var force = d3.layout.force() .gravity(0.02) .size([w, h]); var dragArray = [{ x: 0, y: 0 }]; var svg = d3.select('.todos').append('svg') .attr('width', w) .attr('height', h) .selectAll('g') .data(dragArray) .enter() .append('g') .attr('style', function (d) { return 'transform:translate3d(' + d.x + 'px,' + d.y + 'px,0)'; }); var dragRect = svg.selectAll('rect') .data(dragArray) .enter() .append('rect') .attr('width', w * 20) .attr('height', h * 20) .attr('x', -w * 10) .attr('y', -h * 10) .attr('fill', 'transparent'); var g = svg.selectAll('g') .data(nodes) .enter() .append('g') .attr('class', function (d) { return d.finished ? 'finished' : ''; }); g.append('circle') .attr('r', function (d) { return d.radius; }) .style('fill', function (d, i) { return color(i); }); var text = g.append('text') .attr('class', 'text') .attr('font-size', fontSize) .attr('y', function (d) { return -d.lineCount * (fontSize + 2) / 2; }); text.selectAll('tspan') .data(function (d) { var strs = []; for (var i = 0; i < d.todo.length; i++) { var index = parseInt(i / d.textPerLine); if (!strs[index]) strs[index] = ''; strs[index] += d.todo[i]; } return strs; }) .enter() .append('tspan') .attr('x', function (d) { return -(d.length - text.attr('width')) * fontSize / 2; }) .attr('width', text.attr('width')) .attr('dy', (fontSize + 1) + 'px') .text(function (d) { return d; }); dragRect.call(drag); g.call(force.drag); force .nodes(nodes) .on('tick', function (e) { var q = d3.geom.quadtree(nodes); for (var i = 0; i < nodes.length; i++) { q.visit(collide(nodes[i])); } g.attr('style', function (d) { return 'transform:translate3d(' + d.x + 'px,' + d.y + 'px,0)'; }); }) .start(); });
// const { fetchMyIP } = require('./iss-prom'); const { nextISSTimesForMyLocation } = require('./iss-cb'); const {obj} = require('./constants'); // fetchMyIP((error, ip) => { // if (error) { // console.log("It didn't work!" , error); // return; // } // console.log('It worked! Returned IP:' , ip); // }); // fetchCoordsByIP(obj.IP, (error, data) => { // // console.log(err, data) // if (error) { // console.log("It didn't work!" , error); // return; // } // console.log(data); // }); // fetchISSFlyOverTimes({ latitude: '49.27670', longitude: '-123.13000' }, (error, data) => { // // console.log(err, data) // if (error) { // console.log("It didn't work!" , error); // return; // } // console.log(data); // }); nextISSTimesForMyLocation((error, time) => { if (error) { console.log("It didn't work!" , error); return; } print(time); }); const print = passes => { for(let pass of passes) { const date = new Date(0); date.setUTCSeconds(pass.risetime); console.log(`Next pass at ${date} for ${pass.duration} seconds!`); } }
import { ref, computed, onMounted, onBeforeUnmount } from '@nuxtjs/composition-api' import mobileInnerHeight from '@/plugins/functions/mobileInnerHeight' let innerHeight export default (context) => { const { root } = context const mobileHeight = ref(0) const globalStyle = computed(() => { const style = { '--vh': '1vh', '--loading-duration': '0.5s', } if (process.browser) { style['--vh'] = `${window.innerHeight / mobileHeight.value}vh` } return style }) onMounted(() => { innerHeight = mobileInnerHeight() mobileHeight.value = innerHeight() window.addEventListener('resize', resize) }) onBeforeUnmount(() => { window.removeEventListener('resize', resize) }) const resize = () => { mobileHeight.value = innerHeight(true) } return { globalStyle, } }
function displayYelpReviews(resultString) { var rowContents = []; // convert half-star numeric ratings to string-type ratings with dashes // instead of periods; e.g. 3.5 --> 3.5 // for use in applying class to overall business rating for styling purposes. var ratingClass = resultString[1].rating.toString().replace(/\./, '-'); yelpInformation = '<ul><span class="rating r' + ratingClass + ' stars">' + resultString[1].rating + ' of 5</span>' + 'based on ' + resultString[1].review_count + ' reviews on <a href="https://www.yelp.com/biz/' + resultString[1].id + '" target="_blank"><img' + ' src="static/img/yelp-2c-outline.png" class="yelp-logo"></a>'; rowContents.push(yelpInformation); for (var i in resultString[0].reviews) { var reviewString = '<li>' + resultString[0].reviews[i].rating + ' out of 5, on ' + resultString[0].reviews[i].time_created + '<br>"' + resultString[0].reviews[i].text + '"</li>'; rowContents.push(reviewString); } rowContents.push('</ul>'); rowContents = rowContents.join(''); $("#" + resultString[1].id).html(rowContents); }
$(document).ready(function () { $('[data-toggle="popover"]').popover(); }); function request(codigo, parametro, succes) { var resultado = ""; switch (codigo) { case "USER": resultado += "220 " + parametro + "Service ready for new user." + "\n"; if (succes) { resultado += "331 " + parametro + " OK, password required" + "\n"; } else { resultado += "332 " + parametro + " Need account for login." + "\n"; } break; case "PASS": if (!succes) { resultado += "430 " + parametro + " Invalid username or password" + "\n"; } else { resultado += "230 " + parametro + " User logged in, proceed. Logged out if appropriate." + "\n"; } break; case "PORT": resultado += "200 " + parametro + "The requested action has been successfully completed." + "\n"; break; case "LIST": if (succes) { resultado += "200 " + parametro + "File status okay; about to open data connection.." + "\n"; resultado += "150 " + parametro + "File status okay; about to open data connection." + "\n"; resultado += "226 " + parametro + "Closing data connection. Requested file action successful (for example, file transfer or file abort)." + "\n"; } break; case "RETR": if (succes) { resultado += "150 " + parametro + "File status okay; about to open data connection." + "\n"; resultado += "226 " + parametro + "Closing data connection. Requested file action successful (for example, file transfer or file abort)." + "\n"; } else { resultado += "426 " + parametro + "Connection closed; transfer aborted." + "\n"; } break; case "STOR": if (succes) { resultado += "150 " + parametro + "File status okay; about to open data connection." + "\n"; resultado += "226 " + parametro + "Closing data connection. Requested file action successful (for example, file transfer or file abort)." + "\n"; } else { resultado += "426 " + parametro + "Connection closed; transfer aborted." + "\n"; } break; default: resultado = "502 " + parametro + " Command not implemented." + "\n"; break; } document.getElementById("commands").value += codigo + " " + parametro + "\n"; document.getElementById("responses").value += resultado; } function desconectar() { cliente.logado = false; document.getElementById("remotos").value = ""; } function conectar() { if (document.getElementById("host").value === servidor.ip) { if (servidor.online) { document.getElementById("commands").value += "Connected to 172.16.62.36" + "\n"; request("USER", document.getElementById("user").value); if (document.getElementById("pwd").value === "admin") { request("PASS", document.getElementById("pwd").value, true); cliente.logado = true; request("PORT", document.getElementById("host").value); } } else { document.getElementById("responses").value += "10060 Cannot connect to remote server." + "\n"; } } else { document.getElementById("responses").value += "434 Requested host unavailable" + "\n"; } } var servidor = {online: false , arq: ["arquivo remoto 1"], ip: "172.16.62.36" }; function atdesServ() { if (servidor.online) { servidor.online = false; cliente.logado = false; document.getElementById("remotos").value = ""; $('#estadoServidor').html("Servidor Offline"); } else { servidor.online = true; $('#estadoServidor').html("Servidor Online"); } } var cliente = { logado: false, arquivos: [] }; function enviarArquivo() { if (servidor.online && cliente.logado) { if (cliente.logado) { var n = document.getElementById("send").value; document.getElementById("send").value = ""; var achou = false; var x; for (x in cliente.arquivos) { if (cliente.arquivos[x] === (n)) { achou = true; } } if (achou) { $("#progressTimer").progressTimer({ timeLimit: 5, warningThreshold: 0, baseStyle: 'progress-bar-info', warningStyle: 'progress-bar-info', completeStyle: 'progress-bar-success', onFinish: function () { if (servidor.online) { servidor.arq.push(n); listServidor(); listCliente(); request("STOR", n, true); console.log("I'm done"); } else { request("STOR", n, false); } } }); } else { alert(n + " does not exist"); } } } else { request(); } } function criarArquivo() { var nome = document.getElementById("new").value; document.getElementById("new").value = ""; cliente.arquivos.push(nome); listCliente(); } function receberArquivo() { if (servidor.online) { if (cliente.logado) { var n = document.getElementById("receive").value; document.getElementById("receive").value = ""; var achou = false; var x; for (x in servidor.arq) { if (servidor.arq[x].localeCompare(n)) { achou = true; } } if (achou) { $("#progressTimer").progressTimer({ timeLimit: 5, warningThreshold: 0, baseStyle: 'progress-bar-info', warningStyle: 'progress-bar-info', completeStyle: 'progress-bar-success', onFinish: function () { if (servidor.online) { cliente.arquivos.push(n); listCliente(); request("RETR", n, true); console.log("I'm done"); } else { request("RETR", n, false); } } }); } else { alert(n + " does not exist"); } } } else { request(); } } function listServidor() { request("LIST", "", true); var s = ""; var x; for (x in servidor.arq) { s += servidor.arq[x] + "\n"; } document.getElementById("remotos").value = s; } function listCliente() { var x; var soma = ""; for (x in cliente.arquivos) { soma += cliente.arquivos[x] + "\n"; } document.getElementById("locais").value = soma; } var transfer = { started: false, finished: false, start: function () { this.started = true; } };
import React, { Component } from 'react'; import Crossword from './components/Crossword' import Clues from './components/Clues' import Dashboard from './components/Dashboard' import {getWords} from './apiAdapter' import { Grid } from 'semantic-ui-react' import './App.css'; class App extends Component { constructor(){ super() this.state = { currentCrossword: [], nextCrossword: [], acrossClues: [], downClues: [], clickedGen: false } } componentDidMount(){ getWords().then((json) => this.setState({nextCrossword: json})) } handleGenerate = () => { let currentCrossword = this.state.nextCrossword this.setState({ currentCrossword, clickedGen: true }, this.structureClues) getWords() .then((json) => this.setState({ nextCrossword: json })) } resetGen = () => { this.setState({ clickedGen: false }) } structureClues = () => { let clues = this.state.currentCrossword.map((data) => data.clue) let across = clues.filter((clue, i) => i % 2 === 0) let down = clues.filter((clue, i) => i % 2 === 1) let acrossNumbers = [{num: '1'}, {num: '3'}, {num: '4'}, {num: '6'}, {num: '7'}] let downNumbers = [{num: '2'}, {num: '3'}, {num: '5'}, {num: '6'}] let acrossWithNumbers = [] let downWithNumbers = [] for (let i=0; i<across.length; i++){ let clue = across[i] let num = acrossNumbers[i] let numClue = Object.assign({}, {clue: clue}, num) acrossWithNumbers.push(numClue) } for (let i=0; i<down.length; i++){ let clue = down[i] let num = downNumbers[i] let numClue = Object.assign({}, {clue: clue}, num) downWithNumbers.push(numClue) } this.setState({ acrossClues: acrossWithNumbers, downClues: downWithNumbers }) } render() { console.log(this.state) return ( <Grid> <div className="App"> <Dashboard handleGenerate={this.handleGenerate} nextCrossword={this.state.nextCrossword}/> <Crossword crosswordData={this.state.currentCrossword} generateBool={this.state.clickedGen} resetGen={this.resetGen}/> {this.state.acrossClues.length > 0 && this.state.downClues.length > 0 ? <Clues across={this.state.acrossClues} down={this.state.downClues}/> : null} </div> </Grid> ); } } export default App;
/** * 화면 초기화 - 화면 로드시 자동 호출 됨 */ function _Initialize() { // 단위화면에서 사용될 일반 전역 변수 정의 $NC.setGlobalVar({ CLIENT1: "" }); // 합포장가능여부 콤보 $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "PASS_DIV", P_CODE_CD: "%", P_SUB_CD1: "", P_SUB_CD2: "" }) }, { selector: "#cboPass_Div", codeField: "CODE_CD", nameField: "CODE_CD", fullNameField: "CODE_CD_F", onComplete: function() { $NC.setValue("#cboPass_Div"); } }); // 합포장가능여부 콤보 $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "SESSION_DIV", P_CODE_CD: "%", P_SUB_CD1: "", P_SUB_CD2: "" }) }, { selector: "#cboSession_item_Reference", codeField: "CODE_CD", nameField: "CODE_CD", fullNameField: "CODE_CD_F", onComplete: function() { $NC.setValue("#cboSession_item_Reference"); _Inquiry(); } }); // 버튼 활성화 처리 $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "1"; $NC.G_VAR.buttons._cancel = "0"; $NC.G_VAR.buttons._delete = "0"; $NC.G_VAR.buttons._print = "0"; $NC.setInitTopButtons($NC.G_VAR.buttons); } /** * 화면 리사이즈 Offset 세팅 */ function _SetResizeOffset() { $NC.G_OFFSET.nonClientHeight = $NC.G_LAYOUT.nonClientHeight; } /** * Window Resize Event - Window Size 조정시 호출 됨 */ function _OnResize(parent) { var clientWidth = parent.width() - $NC.G_LAYOUT.border1; var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight; $NC.resizeContainer("#divMasterView", clientWidth, clientHeight); } /** * Input Change Event - Input, Select Change 시 호출 됨 */ function _OnInputChange(e, view, val) { var id = view.prop("id").substr(3).toUpperCase(); masterOnCellChange(e, { view: view, col: id, val: val }); } function masterOnCellChange(e, args) { var col = args.col.split("_"); if (col[3] == "2") { return; } switch (args.col) { case "PASS_DIV": $NC.G_VAR.CLIENT1.PASS_DIV = args.val; break; case "PASS_ITEM_REFERENCE": $NC.G_VAR.CLIENT1.PASS_ITEM_REFERENCE = args.val; break; case "SESSION_ITEM_REFERENCE": $NC.G_VAR.CLIENT1.SESSION_ITEM_REFERENCE = args.val; break; } if ($NC.G_VAR.CLIENT1.CRUD === "R") { $NC.G_VAR.CLIENT1.CRUD = "U"; } } /** * Inquiry Button Event - 메인 상단 조회 버튼 클릭시 호출 됨 */ function _Inquiry() { // 데이터 조회 $NC.serviceCall("/CS01080E/getDataSet.do", { P_QUERY_ID: "CS01080E.RS_MASTER", P_QUERY_PARAMS: $NC.getParams({ P_USER_ID: $NC.G_USERINFO.USER_ID }) }, onGetClientIp); } /** * New Button Event - 메인 상단 신규 버튼 클릭시 호출 됨 */ function _New() { } /** * Save Button Event - 메인 상단 저장 버튼 클릭시 호출 됨 */ function _Save() { var CLIENT1_CRUD; if ($NC.isNull($NC.G_VAR.CLIENT1.PASS_ITEM_REFERENCE)) { alert("비밀번호 변경 기간을 숫자로 입력하세요."); $NC.setFocus("#edtPass_Item_Reference"); return; } if ($NC.isNull($NC.G_VAR.CLIENT1.SESSION_ITEM_REFERENCE)) { alert("세션유지 시간을 분 단위로 입력하세요."); $NC.setFocus("#edtSession_item_Reference"); return; } if ($NC.isNull($NC.G_VAR.CLIENT1)) { CLIENT1_CRUD = "C"; } else { CLIENT1_CRUD = "U"; } var saveDS = [ ]; var subDS = [ ]; var saveData; if ($NC.G_VAR.CLIENT1.CRUD !== "R") { saveData = { P_USER_ID: $NC.G_USERINFO.USER_ID, P_PRINT_LI_BILL: $NC.G_VAR.CLIENT1.PASS_DIV, P_PRINT_LO_BILL: $NC.G_VAR.CLIENT1.PASS_ITEM_REFERENCE, P_PRINT_RI_BILL: $NC.G_VAR.CLIENT1.SESSION_ITEM_REFERENCE, P_USER_ID: $NC.G_USERINFO.USER_ID }; saveDS.push(saveData); } saveData = { P_PASS_DIV: $NC.getValue("#cboPass_Div"), P_PASS_ITEM_REFERENCE: $NC.getValue("#edtPass_Item_Reference"), P_SESSION_ITEM_REFERENCE: $NC.getValue("#edtSession_item_Reference"), P_USER_ID: $NC.G_USERINFO.USER_ID, P_CRUD: CLIENT1_CRUD }; subDS.push(saveData); $NC.serviceCall("/CS01080E/save.do", { P_DS_MASTER: $NC.toJson(saveDS), P_DS_SUB: $NC.toJson(subDS), P_REG_USER_ID: $NC.G_USERINFO.USER_ID }, onSave); } /** * Delete Button Event - 메인 상단 삭제 버튼 클릭시 호출 됨 */ function _Delete() { } /** * Cancel Button Event - 메인 상단 취소 버튼 클릭시 호출 됨 */ function _Cancel() { } /** * Print Button Event - 메인 상단 출력 버튼 클릭시 호출 됨 * * @param printIndex * 선택한 출력물 Index */ function _Print(printIndex, printName) { } function onGetClientIp(ajaxData) { var resultData = $NC.toArray(ajaxData); if (!$NC.isNull(resultData)) { $NC.G_VAR.CLIENT1 = resultData[0]; if ($NC.G_VAR.CLIENT1) { $NC.setValue("#cboPass_Div", $NC.G_VAR.CLIENT1.PASS_DIV); $NC.setValue("#edtPass_Item_Reference", $NC.G_VAR.CLIENT1.PASS_ITEM_REFERENCE); $NC.setValue("#edtSession_item_Reference", $NC.G_VAR.CLIENT1.SESSION_ITEM_REFERENCE); } } } function onSave(ajaxData) { _Inquiry(); } function onlyNumber(event) { var key = window.event ? event.keyCode : event.which; if ((event.shiftKey == false) && ((key > 47 && key < 58) || (key > 95 && key < 106) || key == 35 || key == 36 || key == 37 || key == 39 // 방향키 좌우,home,end || key == 8 || key == 46 ) ) { return true; }else { return false; } };
// const osmosis = require('osmosis') // const uber = [] // const cabify = [] // const lyft = [] // const taxify = [] // const mytaxi = [] // const grab = [] // const substitutions = { // uber: { // 'Southern Netherlands': 'Rotterdam', // }, // } // const fixCityName = (city, company) => // substitutions[company] && substitutions[company][city] // ? substitutions[company][city] // : city // osmosis // .get('https://www.uber.com/en-GB/cities/') // .find('h3 + div a') // .set('city') // .data(data => { // uber.push({ // name: fixCityName(data.city, 'uber'), // }) // }) // .error(error => error) // .done(() => console.log(uber)) // osmosis // .get('https://cabify.com/en#cities-list') // .find('.countries-list--cities li a') // .set('city') // .data(data => { // cabify.push({ // name: data.city, // }) // }) // .done(() => console.log(cabify)) // osmosis // .get('https://www.lyft.com/cities') // .find('h6 + button + ul li a') // .set('city') // .data(data => { // lyft.push({ // name: data.city, // }) // }) // .done(() => console.log(lyft)) // osmosis // .get('https://taxify.eu/cities/') // .find('.list-inline li h4') // .set('city') // .data(data => { // taxify.push({ // name: data.city, // }) // }) // .done(() => console.log(taxify)) // osmosis // .get('http://ie.mytaxi.com/europeanavailability') // .find('.content__body p') // .data(data => { // console.log(data) // mytaxi.push({ // name: data, // }) // }) // // .done(() => console.log(mytaxi)) // osmosis // .get('https://www.grab.com/sg/where-we-are/') // .find('.city') // .set('city') // .data(data => { // grab.push({ // name: data.city, // company: 'Grab', // }) // }) // .done(() => console.log(JSON.stringify(grab)))
import React, {Fragment} from "react"; import {Link} from "react-router-dom"; import { postService } from "../../../services/postService"; export const SingleAuthor = (props) => { return( <Fragment> <h4><Link to={"/authors/" + props.author.id}>{props.author.name} ({postService.fetchNumberOfPosts(props.author.id)} - posts)</Link></h4> <hr /> </Fragment> ) }
var SpotifyPlaylistRepository = SpotifyPlaylistModel.repository; SpotifyPlaylistRepository.loadPlaylists = function(successCallback, errorCallback) { $.get(app.config.api + "/mopidy/playlists").then(function(response) { var playlists = []; for(var i in response.data) { var data = response.data[i]; if(data.uri.indexOf('spotify') != 0) { // Skip non-spotify playlist continue; } var playlist = new app.models['SpotifyPlaylist'](data); for(var j in playlist.tracks) { var track = playlist.tracks[j]; track.playlistUri = playlist.uri; track.playlistNum = j; } playlists.push(playlist); } successCallback(playlists); }, errorCallback); } SpotifyPlaylistRepository.loadPlaylist = function(uri, successCallback, errorCallback) { $.get(app.config.api + "/mopidy/playlists/lookup", { uri: decodeURIComponent(uri) }).then(function(response) { var data = response.data; if(data.uri.indexOf('spotify') != 0) { // Non-spotify playlist return null; } var playlist = new app.models['SpotifyPlaylist'](data); successCallback(playlist); }, errorCallback); } SpotifyPlaylistRepository.getPlaylists = function(url) { if(!app.container.Spotify.playlists) { return null; } return app.container.Spotify.playlists; } SpotifyPlaylistRepository.getPlaylist = function(uri) { if(!app.container.Spotify.playlists) { return null; } uri = decodeURIComponent(uri); for(var i in app.container.Spotify.playlists) { var playlist = app.container.Spotify.playlists[i]; if(playlist.uri == uri) { return playlist; } } return null; }
import React from 'react' import { render } from 'react-dom'; import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom' import Login from './components/login/login' import UserCreate from './components/login/create' import SeasonSelect from './components/season/select' import SeasonCreate from './components/season/create' import SeasonDetail from './components/season/detail' import ProductList from './components/product/list' import ProductCreate from './components/product/create' import ProductEdit from './components/product/edit' import gameCreate from './components/game/create' import gameEdit from './components/game/edit' import VerifyLogin from './components/login/verifyLogin' class App extends React.Component { constructor() { super(); this.state = { loggedIn: false, }; this.login = this.login.bind(this); this.logout = this.logout.bind(this); this.refresh = this.refresh.bind(this); } login() { this.setState({ loggedIn: true, }); } refresh() { fetch('/api/me', { method: 'GET', credentials: 'include' }) .then((res) => res.json()) .then((user) => { if (user._id) { this.setState({ user: user, }); this.login(); } }); } logout() { fetch('/api/logout', { method: 'GET', credentials: 'include', }).then(() => { this.setState({ loggedIn: false, user: null, }); }); } componentDidMount() { this.refresh(); } render() { return <div> <Router> <div className="inventory-app"> {this.state.loggedIn && <div className='sidebar'> <ul> <li><Link to="/season">Season Overview</Link></li> <li><Link to="/products">Products</Link></li> </ul> <div className="logout"> <button onClick={this.logout} className="btn btn-primary">Log Out</button> </div> </div> } <div className="content"> <Switch> <Route exact path='/' render={(props) => (<Login refresh={this.refresh} {...props} />)} /> <Route exact path='/login/create' render={(props) => (<UserCreate refresh={this.refresh} {...props} />)} /> <Route exact path='/products' component={ProductList} /> <Route path='/products/create' component={ProductCreate} /> <Route path='/products/:id' component={ProductEdit} /> <Route exact path='/season' component={SeasonSelect} /> <Route exact path={`/season/create`} component={SeasonCreate} /> <Route exact path={`/season/:id`} component={SeasonDetail} /> <Route exact path={`/season/:id/game/create`} component={gameCreate} /> <Route exact path={`/game/:gameid`} component={gameEdit} /> </Switch> </div> </div> </Router> </div> } } render(<App />, document.getElementById('app'));
const Lab = require('lab') const lab = exports.lab = Lab.script() const Code = require('code') const GUID = require('node-uuid') const knex = require('../server/models/knex') const User = require('../server/models/user') const Poll = require('../server/models/poll') const PollOpinion = require('../server/models/pollOpinion') const { server } = require('../index') global.lab = lab global.describe = lab.describe global.it = lab.it; global.before = lab.before global.beforeEach = lab.beforeEach global.after = lab.after global.afterEach = lab.afterEach global.expect = Code.expect global.Code = Code global.GUID = GUID global.server = server global.User = User global.Poll = Poll global.PollOpinion = PollOpinion global.knex = knex beforeEach((done) => { knex .migrate .rollback() .then(() => knex.migrate.latest()) .then(() => knex.seed.run()) .then(() => done()) })
export const userReducer = (state={}, action) => { switch (action.type) { case 'USER_SUCCESS': return action.user; case 'USER_FAIL': return action.error default: return state; } } export const userLoading = (state=false, action) => { switch (action.type) { case 'USER_IS_LOADING': return action.userLoading; default: return state; } }
$(document).ready(function(){ //列表下拉 $('img[ectype="flex"]').click(function(){ var status = $(this).attr('status'); if(status == 'open'){ var pr = $(this).parent('td').parent('tr'); var id = $(this).attr('fieldid'); var code = $(this).attr('fieldcode'); var loghash = $(this).attr('loghash'); var url = $(this).attr('url'); var admin_url = $(this).attr('admin_url'); var js = $(this).attr('js'); var obj = $(this); $(this).attr('status','none'); //ajax $.ajax({ url: admin_url+'content/article/ajax_category_class/?code='+code+'&loghash='+loghash+'&parent_id='+id+'&rrr='+Math.random(), dataType: 'json', success: function(data){ var src=''; for(var i = 0; i < data.length; i++){ var tmp_vertline = "<img class='preimg' src='"+url+"vertline.gif'/>"; src += "<tr class='"+pr.attr('class')+" row"+id+"'>"; src += "<td class='w36'><input type='checkbox' name='check_ac_id[]' value='"+data[i].ac_id+"' class='checkitem'>"; /*if(data[i].have_child == 1){ src += " <img fieldid='"+data[i].ac_id+"' status='open' loghash="+loghash+" js="+js+" url="+url+" admin_url="+admin_url+" ectype='flex' src='"+url+"tv-expandable.gif' />"; }else{ src += "<img fieldid='"+data[i].ac_id+"' status='none' ectype='flex' src='"+url+"tv-item.gif' />"; }*/ //图片 src += "</td><td class='w48 sort'>"; //排序 src += "<input type='hidden' name='hdnid[]' value='"+data[i].ac_id+"' /><input type='text' value='"+data[i].listorder+"' name='listorder[]' id='listorder[]' class='txt-short'></td>"; //名称 src += "<td class='name'>"; for(var tmp_i=1; tmp_i < (data[i].deep-1); tmp_i++){ src += tmp_vertline; } if(data[i].have_child == 1){ src += " <img fieldid='"+data[i].ac_id+"' fieldcode='"+code+"' status='open' ectype='flex' src='"+url+"tv-item1.gif' />"; }else{ src += " <img fieldid='"+data[i].ac_id+"' fieldcode='"+code+"' status='none' ectype='flex' src='"+url+"tv-expandable1.gif' />"; } src += " <span title='不可编辑' required='1' fieldid='"+data[i].ac_id+"' ajax_branch='article_class_name' fieldname='ac_name' ectype='inline_edit' class='editable'>"+data[i].ac_name+"</span>"; //新增下级 if(data[i].deep < 2){ src += "<a class='btn-add-nofloat marginleft' href='"+admin_url+"content/article/article_category_add/?code="+code+"&loghash="+loghash+"&parent_id="+data[i].ac_id+"'><span>新增下级</span></a>"; } src += "</td>"; //操作 src += "<td class='w84'>"; src += "<a href='"+admin_url+"content/article/article_category_edit/?loghash="+loghash+"&ac_id="+data[i].ac_id+"'>编辑</a>"; src += " | <a href=\"javascript:del('"+admin_url+"content/article/article_category_del/?loghash="+loghash+"','check_ac_id[]',"+data[i].ac_id+");\">删除</a>"; src += "</td>"; src += "</tr>"; } //插入 pr.after(src); obj.attr('status','close'); obj.attr('src',obj.attr('src').replace("tv-expandable","tv-collapsable")); $('img[ectype="flex"]').unbind('click'); $('span[ectype="inline_edit"]').unbind('click'); //重现初始化页面 $.getScript(js+"jquery.edit.js"); $.getScript(js+"jquery.article_class.js"); $.getScript(js+"jquery.tooltip.js"); $.getScript(js+"admincp.js"); }, error: function(){ alert('获取信息失败'); } }); } if(status == 'close'){ $(".row"+$(this).attr('fieldid')).remove(); $(this).attr('src',$(this).attr('src').replace("tv-collapsable","tv-expandable")); $(this).attr('status','open'); } }) });
import { showSnackBar } from "./../../../global/snackBar"; import './../css/main.css'; const VAPID_PUBLIC_KEY = 'BCvnBFnsPt6MPzwX_LOgKqVFG5ToFJ5Yl0qDfwrT-_lqG0PqgwhFijMq_E-vgkkLli7RWHZCYxANy_l0oxz0Nzs'; const API_URL = 'https://ecommerce-pwa.herokuapp.com'; const SERVICE_WORKER_SCOPE = '/push-examples/'; // const SERVICE_WORKER_SCOPE = window.location.href.match('localhost') ? '/' : '/push-examples/'; window.addEventListener('load', () => { if ('serviceWorker' in navigator) { navigator.serviceWorker.register('./service-worker.js', { scope: SERVICE_WORKER_SCOPE }); // TODO import(/* webpackChunkName: "sw-util" */ './../../../global/sw-util.js') // TODO .then(util => util.registerServiceWorker('/push-examples/service-worker.js', SERVICE_WORKER_SCOPE)); } if (!navigator.onLine) { handleOfflineEvent(); } const queryString = document.location.search; if (!!queryString) { // ? get push-notifications-are-cool parameter from the URL bar const urlQueryObject = getUrlQueryObject(queryString); console.log("TCL: urlQueryObject", urlQueryObject) if ( urlQueryObject.hasOwnProperty('push-notifications-are-cool') && urlQueryObject['push-notifications-are-cool'] === "true" ) { document.body.classList.remove('cool', 'not-cool'); void document.body.offsetWidth; // * trigger reflow event document.body.classList.add(urlQueryObject ? 'cool' : 'not-cool'); // remove class after animation has ended (1.5s) and clean up search bar setTimeout(() => { document.body.classList.remove('cool', 'not-cool'); window.history.replaceState({}, document.title, document.location.pathname); }, 2500); } } }); window.wipeData = async () => { // * Removes user data from the database // * Also removes the httpOnly cookie const response = await fetch(`${API_URL}/user/remove`, { credentials: 'include', method: 'GET' }); if (response.status === 400) { showSnackBar("There was an error while deleting your data 😕. Please Try again."); return; } // * wipe cache caches.keys() .then(cacheNames => { cacheNames.map(cache => caches.delete(cache)); }); // * unregister service worker const registration = await navigator.serviceWorker.getRegistration(SERVICE_WORKER_SCOPE); await registration.unregister(); // ! Cannot revoke browser notification permissions yet. // ! https://stackoverflow.com/questions/28478185/remove-html5-notification-permissions/ showSnackBar("All your data has been deleted!"); } // ! ask for permission only when the user clicks window.requestNotificationPermission = () => { navigator.serviceWorker.getRegistration(SERVICE_WORKER_SCOPE).then(registration => { registration.pushManager.permissionState({userVisibleOnly: true}).then(permission => { // Possible values are 'prompt', 'denied', or 'granted' if (permission === "prompt" || permission === "granted") { subscribeToPushManager(registration); } }); }); } window.requestNotification = notificationType => { navigator.serviceWorker.getRegistration(SERVICE_WORKER_SCOPE).then(async registration => { if (!registration) { showSnackBar("Push subscription has been deleted or expired."); registration = await navigator.serviceWorker.register('./service-worker.js', { scope: SERVICE_WORKER_SCOPE }); await subscribeToPushManager(registration); } const permission = await registration.pushManager.permissionState({userVisibleOnly: true}); if (permission !== "granted") { // * ask for permission await subscribeToPushManager(registration); } try { const response = await fetch(`${API_URL}/user/push/${notificationType}`, { credentials: 'include', method: 'GET' }); if (response.status === 400) { showSnackBar("Push subscription has been deleted or expired. Try requesting permission again."); } else if (response.status === 404) { showSnackBar("Push subscription has been deleted or expired."); await subscribeToPushManager(registration); window.requestNotification(notificationType); } else { console.log("Push notification sent!"); } } catch (error) { showSnackBar("Oops! There was an error while hitting the API. Check the console for errors."); console.error(error); } }); } const subscribeToPushManager = async registration => { showSnackBar('Subscribing to the Push Manager...'); const subscription = await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY) }); if (!subscription) { showSnackBar("Couldn't subscribe to the Push Manager!"); return; } console.log('Sending subscription to the API...'); try { await fetch(`${API_URL}/user/push-subscription/`, { method: 'POST', credentials: 'include', body: JSON.stringify({ subscription }), headers: { 'content-type': 'application/json' } }); showSnackBar("Subscription saved in database by the API"); } catch (error) { showSnackBar("Oops! There was an error while hitting the API. Check the console for errors."); console.error(error); } } const handleOfflineEvent = () => { markOfflineUnavailableContent(); showSnackBar('You are offline 📴'); } const handleOnlineEvent = () => { unmarkOfflineUnavailableContent(); showSnackBar('You are back online! 🎉'); } const markOfflineUnavailableContent = () => { const buttons = Array.prototype.slice.call(document.querySelectorAll('main button')) buttons.map(button => { button.classList.add('unavailable-offline'); }); } const unmarkOfflineUnavailableContent = () => { const buttons = Array.prototype.slice.call(document.querySelectorAll('main button')) buttons.map(button => { button.classList.remove('unavailable-offline'); }); } window.addEventListener('offline', function() { handleOfflineEvent(); }); window.addEventListener('online', function() { handleOnlineEvent(); }); const getUrlQueryObject = queryString => { const queryStringCharactersArr = queryString.split(''); // ? remove the ? character queryStringCharactersArr.splice(0, 1); const sanitisedQueryString = queryStringCharactersArr.join(''); const pair = sanitisedQueryString.split('='); const key = decodeURIComponent(pair[0]); const value = decodeURIComponent(pair[1]); return {[key]: value}; } const urlBase64ToUint8Array = base64String => { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding) .replace(/\-/g, '+') .replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; }
import React, { Component } from 'react'; import styled from 'styled-components'; const Wrapper = styled.div` width: 100%; height: 5vh; display: flex; justify-content: center; `; export default class SubRaceChoice extends Component { constructor(props) { super(props); this.state = {}; } render() { let subRaceArr = []; if (this.props.race === 'Dwarf') { subRaceArr = ['Hill Dwarf', 'Mountain Dwarf']; } else if (this.props.race === 'Elf') { subRaceArr = ['High Elf', 'Wood Elf', 'Drow']; } else if (this.props.race === 'Halfling') { subRaceArr = ['Lightfoot', 'Stout']; } else if (this.props.race === 'Human') { subRaceArr = []; } else if (this.props.race === 'Dragonborn') { subRaceArr = []; } else if (this.props.race === 'Gnome') { subRaceArr = ['Forest Gnome', 'Rock Gnome']; } else if (this.props.race === 'Half-Elf') { subRaceArr = []; } else if (this.props.race === 'Half-Orc') { subRaceArr = []; } else if (this.props.race === 'Tiefling') { subRaceArr = []; } const raceElements = subRaceArr.map((subrace, i) => ( <button onClick={() => this.props.handleSelected('subRace', subRaceArr[i])} type="button" > {subRaceArr[i]} </button> )); return <Wrapper>{raceElements}</Wrapper>; } }
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('StoreWebsite', { website_id: { autoIncrement: true, type: DataTypes.SMALLINT.UNSIGNED, allowNull: false, primaryKey: true, comment: "Website ID" }, code: { type: DataTypes.STRING(32), allowNull: true, comment: "Code", unique: "STORE_WEBSITE_CODE" }, name: { type: DataTypes.STRING(64), allowNull: true, comment: "Website Name" }, sort_order: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: "Sort Order" }, default_group_id: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: "Default Group ID" }, is_default: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: true, defaultValue: 0, comment: "Defines Is Website Default" } }, { sequelize, tableName: 'store_website', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "website_id" }, ] }, { name: "STORE_WEBSITE_CODE", unique: true, using: "BTREE", fields: [ { name: "code" }, ] }, { name: "STORE_WEBSITE_SORT_ORDER", using: "BTREE", fields: [ { name: "sort_order" }, ] }, { name: "STORE_WEBSITE_DEFAULT_GROUP_ID", using: "BTREE", fields: [ { name: "default_group_id" }, ] }, ] }); };
export default class message{ constructor(id, channel_id, author, message, date) { this.id = id; this.channel_id = channel_id; this.author = author; this.message = message; this.date = date; } }
import React from 'react'; import Component from './' export default { title: 'repo' }; export const Story = () => <Component />;
import { renderString } from '../../src/index'; describe(`A filter that groups up items within a sequence`, () => { it(`unnamed case 0`, () => { const html = renderString(` {%- set items=[1, 2, 3, 4, 5] -%} <table> {%- for row in items|batch(3, '&nbsp;') %} <tr> {%- for column in row %} <td>{{ column }}</td> {%- endfor %} </tr> {%- endfor %} </table>`); expect(html).toBe(`<table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>&nbsp;</td> </tr> </table>`); }); });
import React from "react"; import { BrowserRouter, Route } from "react-router-dom"; import CreateBoard from "./CreateBoard"; import BoardList from "./BoardList"; import BoardDetail from "./BoardDetail"; const App = () => { return ( <div className="ui container"> <BrowserRouter> <Route path="/" exact component={CreateBoard} /> <br /> <Route path="/" exact component={BoardList} /> <Route path="/:id" exact component={BoardDetail} /> </BrowserRouter> </div> ); }; export default App;
import { useState, createContext } from 'react' export const TodoContext = createContext() export const TodoProvider = ({ children }) => { const [todos, setTodos] = useState([]) return <TodoContext.Provider value={[todos, setTodos]}>{children}</TodoContext.Provider> }
import { Redirect, Route, Switch } from "react-router" import useContent from "../../helpers/useDb" import { Feed } from "../../pages" import ArticleInfo from "../../pages/ArticleInfo" import { Container, Inner, Photo, Title, Description, Info, Name, Time, ReadMore, } from "./styles/article" export default function Article({ item }) { function addDefaultSrc(e) { e.target.src = "images/article/markus-spiske-iar-afB0QQw-unsplash.jpg" } return ( <Container> <Photo src={item.photoURL} onError={e => addDefaultSrc(e)} alt="article photo" /> <Inner> <Title>{item.title}</Title> <Description>{item.description}</Description> <Info> <div> <Time>{item.time}</Time> <span></span> <Name>{item.name}</Name> </div> <div> <ReadMore to={{ pathname: `/article/${item.path}`, state: item }} > Read More </ReadMore> </div> </Info> </Inner> </Container> ) }
//搜索框效果 $(function(){ $(".txt").focus(function(){ $(this).addClass("focus"); if($(this).val() == this.defaultValue){ $(this).val(""); } }).blur(function(){ $(this).removeClass("focus"); if($(this).val() == ""){ $(this).val(this.defaultValue); } }).keyup(function(){ if(e.which == 13){ alert("回车提交表单"); } }) }); //轮播图 $(".banner-image").banner({ aimg:$(".banner-image").find("img"), left:$(".banner-left").find("#left"), right:$(".banner-left").find("#right"), isList:true, autoPlay:true, delayTime:1500, moveTime:200, index:0 }) //导航栏隐藏及显示 $(function(){ $(window).scroll(function(){ var h =$(window).scrollTop(); if(h > 500){ $(".top-bar").fadeIn() }else{ $(".top-bar").fadeOut() } }); }) //三级菜单 $(function(){ $(".top-logo-menu .menu-title").mouseover(function(){ // $(".first").css("display","block") $(this).children("ul").css("display","block") }).mouseout(function(){ $(this).children("ul").css("display","none") }) }) //$(function(){ // $("li").has(".menu-title ul").mouseover(function(){ // $(this).children("ul").css("display","block"); // }).mouseout(function(){ // $(this).children("ul").css("display","none"); // }) //}) //楼层隐藏及显示 $(function(){ $(window).scroll(function(){ var h =$(window).scrollTop(); if(h > 900){ $(".left-bar").show() }else{ $(".left-bar").hide() } }); }) //楼层 $(".btns").children("li").click(function(){ var index = $(this).index(); var iNowFloor = $(".consumables").eq(index); var t = iNowFloor.offset().top; $("html").stop().animate({ scrollTop:t }) }) $(".commodities ul").children("li").click(function(){ var index = $(this).index(); var iNowFloor = $(".consumables").eq(index); var t = iNowFloor.offset().top; $("html").stop().animate({ scrollTop:t }) }) //回到顶部按钮 $(".goup").click(function(){ $("html,body").animate({scrollTop: "0px"},500) }) //调到底部按钮 $(".godown").click(function(){ var down = $("#footer").offset().top; $("html,body").animate({scrollTop: down},500) }) //选项卡 class Tab{ constructor(){ this.list = document.querySelector(".goods_lists"); this.li = document.querySelectorAll("goods_title li"); this.url = "http://localhost/1905/EAST/data/goods.json"; this.init(); this.addEvent(); } init(){ var that = this; ajaxPost(this.url,function(res){ that.res = JSON.parse(res); that.display(); }) } addEvent(){ $(".goods_title").find("li").mouseover(function(){ console.log($(this).index()) $(".goods_title").find("li").removeClass("active") $(this).addClass("active") $(".goodsList").addClass("none") $(".goodsList").eq($(this).index()).removeClass("none") }) // var that = this; // for(var i=0;i<this.li.length;i++){ // this.li[i].index = i; // this.li[i].onclick = function(){ // for(var j=0;j<this.li.length;j++){ // this.li[j].className = ""; // this.List[j].style.display = "none"; // } // this.li[i].className = "active"; // this.List[this.index].style.display = "block"; // } // } // } } display(){ var n =0; var str = ""; for(var i=0;i<5;i++){ var arr = ""; for(var j=n*6;j<n*6+6;j++){ arr +=`<div class="goods_list1" index="${this.res[j].goodsId}"> <li> <a href="goodsMsg.html?goodsid=${this.res[j].goodsId}"><img src="${this.res[j].src}" /></a> <p>${this.res[j].name}</p> <span>${this.res[j].price}</span> </li> </div>`; } str +=`<div class="goodsList none"><div class="flexbox">${arr}</div></div>`; n++; } console.log(n) this.list.innerHTML = str; // console.log($(".goodsList")) $(".goodsList").eq(0).removeClass("none"); } } new Tab();
const FirstKBT = artifacts.require("MyFirstKBT"); module.exports = function (deployer) { deployer.deploy(FirstKBT); };
var firebaseConfig = { apiKey: "AIzaSyCoifsQZU4X_ARBbMGEiIQSjlk5g3qpUuU", authDomain: "clone-two-8c1f5.firebaseapp.com", projectId: "clone-two-8c1f5", storageBucket: "clone-two-8c1f5.appspot.com", messagingSenderId: "793216905054", appId: "1:793216905054:web:a652681c4d0ae55c3069cf", measurementId: "G-LC641H0GZV" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); firebase.analytics();
class chess_piece { constructor(color, piece, starting_square, position=[0,0], starting_position=[0,0]) { this.color = color; this.piece = piece this.identifier = starting_square this.position = position; } } let chess_piece_url = "Classic/" //White pieces let white_rook_a = new chess_piece("White", "Rook", "A"); let white_rook_h = new chess_piece("White", "Rook", "H"); let white_knight_b = new chess_piece("White", "Knight", "B"); let white_knight_g = new chess_piece("White", "Knight", "G"); let white_bishop_c = new chess_piece("White", "Bishop", "C"); let white_bishop_f = new chess_piece("White", "Bishop", "F"); let white_king = new chess_piece("White", "King", "D"); let white_queen = new chess_piece("White", "Queen", "E"); let white_pawns = [new chess_piece("White", "Pawn", "A"), new chess_piece("White", "Pawn", "B"), new chess_piece("White", "Pawn", "C"), new chess_piece("White", "Pawn", "D"), new chess_piece("White", "Pawn", "E"), new chess_piece("White", "Pawn", "F"), new chess_piece("White", "Pawn", "G"), new chess_piece("White", "Pawn", "G")]; //Black pieces let black_rook_a = new chess_piece("Black", "Rook", "A"); let black_rook_h = new chess_piece("Black", "Rook", "H"); let black_knight_b = new chess_piece("Black", "Knight", "B"); let black_knight_g = new chess_piece("Black", "Knight", "G"); let black_bishop_c = new chess_piece("Black", "Bishop", "C"); let black_bishop_f = new chess_piece("Black", "Bishop", "F"); let black_king = new chess_piece("Black", "King", "D"); let black_queen = new chess_piece("Black", "Queen", "E"); let black_pawns = [new chess_piece("Black", "Pawn", "A"), new chess_piece("Black", "Pawn", "B"), new chess_piece("Black", "Pawn", "C"), new chess_piece("Black", "Pawn", "D"), new chess_piece("Black", "Pawn", "E"), new chess_piece("Black", "Pawn", "F"), new chess_piece("Black", "Pawn", "G"), new chess_piece("Black", "Pawn", "G")]; let piece_positions = [ [black_rook_a, black_knight_b, black_bishop_c, black_queen, black_king, black_bishop_f, black_knight_g, black_rook_h], [black_pawns[0], black_pawns[1], black_pawns[2], black_pawns[3], black_pawns[4], black_pawns[5], black_pawns[6], black_pawns[7]], ["Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty"], ["Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty"], ["Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty"], ["Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty", "Empty"], [white_pawns[0], white_pawns[1], white_pawns[2], white_pawns[3], white_pawns[4], white_pawns[5], white_pawns[6], white_pawns[7]], [white_rook_a, white_knight_b, white_bishop_c, white_queen, white_king, white_bishop_f, white_knight_g, white_rook_h], ]; let move_history = [] //Replacing "Empty" with chess_piece class to save position for swapping for (let y = 0; y < piece_positions.length; y++) { console.log(y) for (let x = 0; x < piece_positions[y].length; x++) { if (piece_positions[y][x] == "Empty") { piece_positions[y][x] = new chess_piece("None", "Empty", "None", [y, x], [y, x]) } else { piece_positions[y][x].position = [y, x] piece_positions[y][x].starting_position = [y, x] } } } function move_piece(current_pos, move_pos){ let legal = false; move_pos[0] = parseInt(move_pos[0], 10); move_pos[1] = parseInt(move_pos[1], 10); let piece = piece_positions[current_pos[0]][current_pos[1]]; let legal_moves = available_moves(piece.piece, piece.position, piece_positions, piece.color, piece.starting_position); for (let i = 0; i < legal_moves.length; i++) { if (legal_moves[i].equals(move_pos)) { console.log('Legal move'); legal = true; break; } } if (legal) { //After confirming the move is legal let temp = [...piece_positions][current_pos[0]][current_pos[1]]; let temp2 = piece_positions[current_pos[0]][current_pos[1]].position; //Move current piece to the movement target square piece_positions[current_pos[0]][current_pos[1]].position = piece_positions[move_pos[0]][move_pos[1]].position; piece_positions[current_pos[0]][current_pos[1]] = piece_positions[move_pos[0]][move_pos[1]]; //Swaping move_pos with previous position piece_positions[move_pos[0]][move_pos[1]].position = temp2; piece_positions[move_pos[0]][move_pos[1]] = temp; //If move is a capture if (piece_positions[move_pos[0]][move_pos[1]].piece != "Empty") { //Replace the other piece with a new empty piece piece_positions[current_pos[0]][current_pos[1]].position = temp2; piece_positions[current_pos[0]][current_pos[1]] = new chess_piece("None", "Empty", "None", temp2, temp2); //Add captured piece to captured_pieces } //Refresh board to have all pieces show correct positions refresh_board() move_history.push([temp.color, temp.piece, temp.color + " " + temp.piece + " moved to " + move_pos]) console.log(move_history) } else { console.log("Illegal move!") } } function clicked_piece(td) { console.log(td.id) //If player has not yet clicked if (document.getElementsByClassName('clicked first').length != 1) { let piece = piece_positions[td.id.split(",")[0]][td.id.split(",")[1]]; let legal_moves = available_moves(piece.piece, piece.position, piece_positions, piece.color, piece.starting_position); if (legal_moves.length > 0) { td.classList.add("clicked"); td.classList.add("first"); //Add all available moves to the board for display for (let i = 1; i < 9; i++) { for (let j = 1; j < 9; j++) { for (let k = 0; k < legal_moves.length; k++) { if (legal_moves[k].equals([i-1, j-1])) { let current_tile = document.getElementById([i-1, j-1]); current_tile.classList.add('available'); } } } } } } //Otherwise this is the second click else { td.classList.add("clicked"); td.classList.add("second"); let second_element = document.getElementsByClassName('clicked second')[0]; let first_element = document.getElementsByClassName('clicked first')[0]; //Refresh board to remove all excess classes refresh_board() move_piece(first_element.id.split(","), second_element.id.split(",")); } } function refresh_board(){ for (let y = 0; y < 8; y++) { for (let x = 0; x < 8; x++) { let current_tile = document.getElementById([y, x]) current_tile.style.backgroundImage = `url('ChessPieceImages/${chess_piece_url}${piece_positions[y][x].color}_${piece_positions[y][x].piece}.png')` if (y%2 == x%2) { current_tile.className = "white"; } else { current_tile.className = "black"; } if (piece_positions[y][x] == "Empty") { piece_positions[y][x] = new chess_piece("None", "Empty", "None", [y, x], [y, x]); } } } } function create_board(){ let table = document.createElement("table"); table.className = "mainChessBoard"; for (let i = 1; i < 9; i++) { let tr = document.createElement('tr'); for (let j = 1; j < 9; j++) { let td = document.createElement('td'); td.id = [i-1, j-1]; td.style.backgroundImage = `url('ChessPieceImages/${chess_piece_url}${piece_positions[i-1][j-1].color}_${piece_positions[i-1][j-1].piece}.png')` console.log('Chess/' + piece_positions[i-1][j-1].color + "_" + piece_positions[i-1][j-1].piece) td.addEventListener('click', function() {clicked_piece(this)}); if (i%2 == j%2) { td.className = "white"; } else { td.className = "black"; } tr.appendChild(td); } table.appendChild(tr); } document.body.appendChild(table); } function available_moves(piece, position, board, color, starting_position) { console.log(position); let available_moves = []; //Check if piece whose turn it is is trying to move or if it is the first turn if (move_history.length === 0 && color == "White" || color != move_history[move_history.length - 1][0]) { if (piece == "Empty") { return available_moves; } if (piece == "Rook" || piece == "Queen") { let moves = [ [1, 0], [-1, 0], [0, -1], [0, 1] ] for (let i = 0; i < moves.length; i++) { let testing_pos = [...position]; while (true) { testing_pos[0] += moves[i][0]; testing_pos[1] += moves[i][1]; if (testing_pos[0] < 8 && testing_pos[0] >= 0) { if (testing_pos[1] < 8 && testing_pos[1] >= 0) { let piece_at_position = piece_positions[testing_pos[0]][testing_pos[1]] if (piece_at_position.piece != "Empty" && color == piece_at_position.color) { break } legal_move = [...testing_pos]; available_moves.push(legal_move); if (piece_at_position.piece != "Empty" && color != piece_at_position.color) { break } } else { break; } } else { break; } } } } if (piece == "Bishop" || piece == "Queen") { let moves = [ [1, 1], [-1, 1], [1, -1], [-1, -1] ] for (let i = 0; i < moves.length; i++) { let testing_pos = [...position]; while (true) { testing_pos[0] += moves[i][0]; testing_pos[1] += moves[i][1]; if (testing_pos[0] < 8 && testing_pos[0] >= 0) { if (testing_pos[1] < 8 && testing_pos[1] >= 0) { let piece_at_position = piece_positions[testing_pos[0]][testing_pos[1]] if (piece_at_position.piece != "Empty" && color == piece_at_position.color) { break } legal_move = [...testing_pos]; available_moves.push(legal_move); if (piece_at_position.piece != "Empty" && color != piece_at_position.color ) { break } } else { break; } } else { break; } } } } else if (piece == "Knight") { let moves = [ [2, 1], [-2, 1], [2, -1], [-2, -1], [1, 2], [-1, 2], [1, -2], [-1, -2] ]; for (let i = 0; i < moves.length; i++) { testing_pos = [...position]; testing_pos[0] += moves[i][0]; testing_pos[1] += moves[i][1]; if (testing_pos[0] < 8 && testing_pos[0] >= 0) { if (testing_pos[1] < 8 && testing_pos[1] >= 0) { let piece_at_position = piece_positions[testing_pos[0]][testing_pos[1]] if (piece_at_position.piece == "Empty" || color != piece_at_position.color) { available_moves.push(testing_pos); } } } } } else if (piece == "King") { let moves = [ [1, 1], [-1, 1], [1, -1], [-1, -1], [1, 0], [-1, 0], [0, 1], [0, -1] ] for (let i = 0; i < moves.length; i++) { testing_pos = [...position]; testing_pos[0] += moves[i][0]; testing_pos[1] += moves[i][1]; if (testing_pos[0] < 8 && testing_pos[0] >= 0) { if (testing_pos[1] < 8 && testing_pos[1] >= 0) { available_moves.push(testing_pos); } } } } else if (piece == "Pawn") { testing_pos = [...position]; let moves = [1, 2] let capture_moves = [[1, 1], [1, -1]] //If pawn started at lower part of board subtraction to move up if (starting_position[0] === 6) { moves[0] *= -1; moves[1] *= -1; for (let index = 0; index < capture_moves.length; index++) { capture_moves[index][0] *= -1; capture_moves[index][1] *= -1; } } //if Pawn is still in starting position an extra step can be taken if (position[0] === starting_position[0]) { available_moves.push([testing_pos[0] + moves[1], testing_pos[1]]); } testing_pos[0] += moves[0]; for (let index = 0; index < capture_moves.length; index++) { let piece_at_position = piece_positions[position[0] + capture_moves[index][0]][position[1] + capture_moves[index][1]] if (piece_at_position.piece != "Empty" && color != piece_at_position.color) { available_moves.push([position[0] + capture_moves[index][0], position[1] + capture_moves[index][1]]) } } if (testing_pos[0] < 8 && testing_pos[0] >= 0) { if (testing_pos[1] < 8 && testing_pos[1] >= 0) { let piece_at_position = piece_positions[testing_pos[0]][testing_pos[1]] if (piece_at_position.piece == "Empty") { available_moves.push(testing_pos); } } } } //Remove all moves where piece moves into it's own colors pieces for (let i = 0; i < available_moves.length; i++) { piece_at_position = piece_positions[available_moves[i][0]][available_moves[i][1]] if (piece_at_position.piece != "Empty" && color == piece_at_position.color) { available_moves[i] = [] } } } return available_moves; } Array.prototype.equals = function (array) { // if the other array is a falsy value, return if (!array) return false; // compare lengths - can save a lot of time if (this.length != array.length) return false; for (let i = 0, l=this.length; i < l; i++) { // Check if we have nested arrays if (this[i] instanceof Array && array[i] instanceof Array) { // recurse into the nested arrays if (!this[i].equals(array[i])) return false; } else if (this[i] != array[i]) { // Warning - two different object instances will never be equal: {x:20} != {x:20} return false; } } return true; } // Hide method from for-in loops Object.defineProperty(Array.prototype, "equals", {enumerable: false}); create_board();
import React from 'react'; import styled from 'styled-components'; const Wrapper = styled.footer` padding: 1.5rem; text-align: center; width: 100%; color: grey; `; function Footer() { return ( <Wrapper> &copy;2020 | Made with &#10084;&#65039; Naveen Shaw.{' '} <a rel="noreferrer" href="https://github.com/naveen666/" > GitHub Repository </a> </Wrapper> ); } export default Footer;
'use strict'; const baseUrl = '/api'; // const baseUrl = 'http://78.245.98.112:42080/api'; const cameraUrl = 'http://78.245.98.112:25081'; const cameraAuth = { user: 'guest', pwd: 'sothiscam' }; angular.module('SothisBotUi', []) .directive('imageonload', function() { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('load', function() { //call the function that was passed scope.$apply(attrs.imageonload); }); } }; }) .directive('imageonerror', function() { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('error', function() { //call the function that was passed scope.$apply(attrs.imageonload); }); } }; }) .controller('SothisCtrl', ['$scope', '$http', '$interval', '$timeout', function($scope, $http, $interval, $timeout) { $scope.temperature = null; $scope.humidity = null; $scope.switches = [ { icon: 'telescope' }, { icon: 'camera' }, { icon: 'usb' }, { icon: 'fan' }, { icon: 'flatscreen' }, {}, {}, {} ]; $scope.shutter_scope = false; $scope.shutter_guide = false; $scope.nout = 'shutdown'; // Get temperature and humidity every 60 seconds (not updated more than that by sensors) let fetchSensors = function() { ['temperature', 'humidity'].forEach(stype => { $http .get(`${baseUrl}/sensor/${stype}`) .then(resp => $scope[stype] = resp.data); }) }; $interval(fetchSensors, 60000); fetchSensors(); // Get switches and shutters statuses every 10 seconds let fetchSwitchesAndShutters = function() { for (let num = 1; num <= 8; num++) { $http.get(baseUrl + '/relay/' + num).then(resp => { $scope.switches[num-1].status = resp.data == 'true'; }); } ['scope', 'guide'].forEach(piece => { $http.get(baseUrl + '/shutter/' + piece).then(resp => { $scope['shutter_'+piece] = resp.data == 'true'; }); }) }; $interval(fetchSwitchesAndShutters, 10000); fetchSwitchesAndShutters(); // Get Nout status every 20 seconds let fetchNout = function() { $http.get(baseUrl + '/nout').then(resp => { if (resp.data == 'true') $scope.nout = 'started' }); }; $interval(fetchNout, 20000); fetchNout(); // Toggle switch $scope.toggleSwitch = function(idx) { let sw = $scope.switches[idx]; if (!sw) return; let newStatus = sw.status === true ? 'off' : 'on'; $http.post(baseUrl + '/relay/' + (idx+1) + '/' + newStatus).then(resp => { $scope.switches[idx].status = resp.data == 'true'; }); } // Toggle shutter $scope.toggleShutter = function(piece) { let sh = $scope['shutter_'+piece]; if (!angular.isDefined(sh)) return; let newStatus = sh === true ? 'close' : 'open'; $http.post(baseUrl + '/shutter/' + piece + '/' + newStatus).then(resp => { $scope['shutter_'+piece] = resp.data == 'true'; }); } // Wake Nout $scope.wakeNout = function() { $http.post(baseUrl + '/nout').then(resp => { $scope.nout = 'waking'; }); } // Get camera every 1 second let fetchCamSnapshot = function() { let params = []; angular.forEach( angular.merge({}, cameraAuth, {_ts: Date.now()}), (v, k) => params.push(`${k}=${v}`) ) $scope.cameraLoading = true; $scope.cameraUrl = cameraUrl + '/snapshot.cgi?' + params.join('&'); }; fetchCamSnapshot(); $scope.cameraLoaded = function() { $scope.cameraLoading = false; $timeout(fetchCamSnapshot, 1000); }; $scope.cameraError = $scope.cameraLoaded; // Move camera $scope.cameraMove = function(dir) { let cmd = null; switch(dir) { case 'up': cmd = 0; break; case 'down': cmd = 2; break; case 'left': cmd = 4; break; case 'right': cmd = 6; break; } if (angular.isNumber(cmd)) { let params = [ `loginuse=${cameraAuth.user}`, `loginpas=${cameraAuth.pwd}`, `command=${cmd}`, `onestep=1` ]; let url = cameraUrl + '/decoder_control.cgi?' + params.join('&'); $http.get(url); } } }])
const _id=Symbol("id") const _name=Symbol("name") const _blood=Symbol("blood") const _contact=Symbol("contact") class Person{ constructor(id,name){ this[_id]=id; this[_name]=name; this[_blood]=null; this[_contact]=null; } get name(){ return this[_id] } get blood(){ return this[_blood] } get contact(){ return this[_contact] } set name(value){ this[_name]=value; } set blood(value){ this[_blood]=value } set contact(value){ this[_contact]=value } toString(){ return `id:${this[_id]} name :${this[_name]} blood:${this[_blood]} contact:${this[_contact]} ` } } module.exports=Person;
class API { constructor(ipc, manager, opts={}) { this.manager = manager; this.opts = opts; ipc.on("playlist.all", (e, args) => this.allPlaylists(e, args)); ipc.on("playlist.one", (e, args) => this.getPlaylist(e, args)); ipc.on("playlist.new", (e, args) => this.newPlaylist(e, args)); ipc.on("playlist.empty", (e, args) => this.removeAllFromPlaylist(e, args)); ipc.on("playlist.remove", (e, args) => this.removeFromPlaylist(e, args)); ipc.on("playlist.swap", (e, args) => this.swapPlaylistTracks(e, args)); ipc.on("playlist.add", (e, args) => this.addToPlaylist(e, args)); ipc.on("playlist.delete", (e, args) => this.deletePlaylist(e, args)); } allPlaylists(event, { replyTo }) { const playlists = this.manager.GetAllPlaylists(); event.sender.send(replyTo, playlists); } getPlaylist(event, { replyTo, args: { name }}) { const playlist = this.manager.GetPlaylist(name); event.sender.send(reply, playlist); } newPlaylist(event, { replyTo, args: { name, contents }}) { const playlist = this.manager.CreatePlaylist(name, contents); event.sender.send(replyTo, playlist); } removeAllFromPlaylist(event, { replyTo, args: { name }}) { const playlist = this.manager.EmptyPlaylist(name); event.sender.send(replyTo, playlist); } removeFromPlaylist(event, { replyTo, args: { name, trackIndex }}) { const playlist = this.manager.RemovePlaylistTrack(name, trackIndex); event.sender.send(replyTo, playlist); } swapPlaylistTracks(event, { replyTo, args: { name, track1, track2 }}) { const playlist = this.manager.SwapPlaylistTracks(name, track2, track2); event.sender.send(replyTo, playlist); } addToPlaylist(event, { replyTo, args: { name, track }}) { const playlist = this.manager.AddPlaylistTrack(name, track); event.sender.send(replyTo, playlist); } deletePlaylist(event, { replyTo, args: { name }}) { const playlist = this.manager.DeletePlaylist(name); event.sender.send(replyTo, playlist); } } module.exports = API;
// for mongo const db = require('../database/db.js'); // for postgresql // const db = require('../database/db_sql.js'); module.exports = { fetchAllPropertyData: (callback) => { db.readAllProperties((err, propertyData) => { if (err) { callback(err); } db.readAllComparableHomes((err, comparableHomesData) => { if (err) { callback(err); return; } db.readAllLocalHomes((err, localHomesData) => { if (err) { callback(err); return; } var data = { propertyData: propertyData, comparableHomesData: comparableHomesData, localHomesData: localHomesData, }; callback(null, data); }); }); }); }, fetchSinglePropertyData: (id, callback) => { db.readSingleProperty(id, (err, singlePropertyData) => { if (err) { callback(err); return; } // Grab the results of the query and clean var singleProperty = { singlePropertyData: singlePropertyData }; callback(null, singleProperty); }); }, postSingleProperty: (propObj, callback) => { db.saveAProperty(propObj, (err, data) => { if (err) { callback(err, null); return; } callback(null, data); }); }, deleteSingleProperty: (propId, callback) => { db.deleteAProperty(propId, (err, data) => { if (err) { callback(err, null); return; } callback(null, data); }); }, updateSingleProperty: (propObj, callback) => { db.updateAProperty(propObj, (err, data) => { if (err) { callback(err, null); return; } callback(null, data); }); } };
const argv = require('./config/yargs').argv; const colors = require('colors'); const { crearArchivo } = require('./multiplicar/multiplicar') const { listarTabla } = require('./multiplicar/listarTabla'); let comando = argv._[0]; let base = argv.base; let limite = argv.limite; switch (comando) { case 'listar': listarTabla(base, limite) .then(resp => console.log(resp)) .catch(err => console.log(err)) break; case 'crear': let getRespuesta = async(base, limite) => { let resp = await crearArchivo(base, limite); return `ARCHIVO CREADO: ${resp}` } getRespuesta(base, limite).then(archivo => console.log(archivo)) .catch(err => console.log(err)) break; default: console.log('Comando no reconocido'); break; } //let base = '3'; //let argv = process.argv; // let parametro = argv[2]; // let base = parametro.split('=')[1]; //let argv2 = process.argv //onsole.log('Limite', argv.limite); // console.log(argv.base); // console.log(argv2); // crearArchivo(base) // .then((archivo) => { // let resp = await archivo; // console.log(`ARCHIVO CREADO: ${ resp}`) // });
import React, { useEffect, useState } from "react"; import "./CustomerReview.css"; const Review = () => { const [reviews, setReviews] = useState([]); useEffect(() => { fetch("http://localhost:4000/reviewFromCustomer") .then((res) => res.json()) .then((data) => { setReviews(data); }); }); return ( <section className="reviewContainer "> <div className="container"> <h1 className="reviewHeading">Our Clients Opinion About Us</h1> <div class="row row-cols-1 row-cols-md-3 g-4 mt-3"> {reviews.map((review) => ( <div class="col "> <div class="card h-100 shadow bg-body rounded"> <div class="card-body"> <h5 class="card-title text-primary">- {review.name}</h5> <h6 class="card-subtitle mb-2 text-muted"> - {review.company} </h6> <p class="card-text">{review.description}</p> </div> </div> </div> ))} </div> </div> </section> ); }; export default Review;
//Considerando que todos os meses tenham 30 dias, calcular o total de dias de n meses. var assert = require('assert') function numberDaysMonths(nMeses){ return nMeses * 30; } try { assert.equal(150, numberDaysMonths(5),"deve retornar o valor esperado 150") } catch (error) { console.log(error) } console.log(numberDaysMonths(5))
var express = require('express') var router = express.Router() router.get('/eventMonthsSource', function(req, res) { var eventMonthsSource = { msg: 'Get data success!', state: true, code: 200, data: [0.6, 0.5, 0.4, 0.3] } res.header("Content-Type", "application/json;charset=utf-8") res.end(JSON.stringify(eventMonthsSource)) }) module.exports = router
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import PropTypes from 'prop-types'; import BlogService from '../services/BlogService'; import ArticleList from '../components/ArticleList'; import Loader from '../components/Loader'; import { setArticle, setArticles, setCategory } from '../actions/blog'; class ArticlesContainer extends Component { async componentDidMount() { const { category, setCategory, setArticles, history, } = this.props; setCategory(category); try { const articles = await BlogService.getArticles(category); setArticles(articles); } catch (e) { history.push('/articles'); } } componentDidUpdate() { const { unsetArticle } = this.props; unsetArticle(); } render() { const { category, articles, setArticle } = this.props; if (!articles) return <Loader />; return ( <div className="articles container"> <ArticleList articles={articles} category={category} onSelect={setArticle} /> </div> ); } } const mapStateToProps = (state, ownProps) => ({ articles: state.blog.articles, category: ownProps.match.params.category, categories: state.blog.categories, }); const mapDispatchToProps = dispatch => ({ setCategory(category) { dispatch(setCategory(category)); }, setArticles(articles) { dispatch(setArticles(articles)); }, setArticle(article) { dispatch(setArticle(article)); }, unsetArticle() { dispatch(setArticle(null)); }, }); ArticlesContainer.propTypes = { category: PropTypes.any, articles: PropTypes.arrayOf(PropTypes.any), setArticle: PropTypes.func, unsetArticle: PropTypes.func, }; export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ArticlesContainer));
var fs = require("fs"); var karmaFile = "karma.json"; function save_karma(karma) { fs.writeFileSync(karmaFile, JSON.stringify(karma)); } function load_karma() { var text; try { text = fs.readFileSync(karmaFile); } catch (err) { // We expect err.code === 'ENOENT' for the first run through return {}; } if (null === text || undefined == text || "" == text) { return {}; } try { return JSON.parse(text); } catch (err) { console.log("failed to parse " + karmaFile); console.log(err); return {}; } } function modify(user, amount) { var karma = load_karma(); if (karma.hasOwnProperty(user)) { karma[user] += amount; } else { karma[user] = amount; } save_karma(karma); } function config(sess) { function karmaIncrement(msg, match) { msg.typing(); var candidateName = match[1]; if (candidateName.charAt(0) == '@') { // normalize candidateName = candidateName.substring(1); } for (var i = 0; i < sess.data.users.length; i++) { var u = sess.data.users[i]; if (u.name == candidateName) { modify(candidateName, 1); break; } } } sess.on(/([a-z0-9_]+)\+\+/i, karmaIncrement); sess.on(/thanks ([a-z0-9_]+)/i, karmaIncrement); sess.on(/ty ([a-z0-9_]+)/i, karmaIncrement); sess.on(/karma\?/, function (msg, ignoredMatch) { var karma = load_karma(); var pairs = []; for (var key in karma) { if (karma.hasOwnProperty(key)) { pairs.push({name: key, value: karma[key]}); } } pairs.sort(function (a, b) { return b.value - a.value; }); var message = ""; for (var i = 0; i < pairs.length; i++) { message += pairs[i].name + ": " + pairs[i].value + "\n"; } msg.reply({ text: '', attachments: [{ title: "Karma", text: message, mrkdwn_in: ["text"] }] }); }); } module.exports = config;
import React from 'react'; import { NavLink } from 'react-router-dom'; import s from './Navbar.module.css'; function Navbar(props) { return ( <nav className={s.appNavbar}> <div className={s.navLinkWrapper}> <NavLink to='/profile' className={s.link} activeClassName={s.activeNavLink}>Profile</NavLink> </div> <div className={s.navLinkWrapper}> <NavLink to='/dialogs' className={s.link} activeClassName={s.activeNavLink}>Dialogs</NavLink> </div> <div className={s.navLinkWrapper}> <NavLink to='/users' className={s.link} activeClassName={s.activeNavLink}>Friends</NavLink> </div> <div className={s.navLinkWrapper}> <NavLink to='/news' className={s.link} activeClassName={s.activeNavLink}>News</NavLink> </div> <div className={s.navLinkWrapper}> <NavLink to='/music' className={s.link} activeClassName={s.activeNavLink}>Music</NavLink> </div> <div className={s.navLinkWrapper}> <NavLink to='/settings' className={s.link} activeClassName={s.activeNavLink}>Settings</NavLink> </div> </nav> ); } export default Navbar;
import { Navigation } from 'react-native-navigation'; import { registerScreens } from '../Screen'; registerScreens(); Navigation.startSingleScreenApp({ screen: { screen: 'screen.Home', }, });
import React, { Component } from 'react'; class Button extends Component { constructor(props) { super(props); } render() { return ( <div> <div className="button" onClick={() => { console.log('Button Clicked!'); }}> <i className="fas fa-chevron-circle-left" /> <span>Previous</span> </div> <div className="button" onClick={() => { console.log('Button Clicked!'); }}> <span>Next</span> <i className="fas fa-chevron-circle-right" /> </div> </div> ); } } export default Button;
Template.citationsList.helpers({ citations: function() { return Citations.getColl({}); } });
module.exports = function (hook, unhook) { return require('virtual-hook')( { hook: function (el) { setTimeout(function () { hook(el) }, 0) } , unhook: unhook }); }
const passingCars = array => { // const west = array.reduceRight((s, i) => [i+s[0] || i].concat(s), []); const west = []; let i; for(i = array.length - 1; i >= 0; i--) { west[i] = array[i] + west[i+1] || array[i]; }; console.log(west); let sum = 0; for(i = 0; i < array.length; i++) { if(array[i] == 0) sum += west[i]; } return sum; } module.exports = passingCars;
// import model from '../model/model.js'; import { error } from 'node:console'; import productsManager from '../managers/productsManager.js'; class ProductsController { /** * Liste les produits */ listProducts(request,response) { productsManager.readDB((err,products) => { if(err !== null) { response.status(400); response.send({ error: error.message }); return; } response.status(200).json(products); }); } /** * Ajoute un produit de la liste */ addProduct(request,response) { productsManager.writeDB(request.body,(err) => { if(err !== null) { response.status(400); response.send({ error: err.message }); return; } response.status(201).end(); }); } /** * Retire un produit de la liste */ deleteProduct(request,response) { productsManager.deleteDB(request.params.id,(err) => { if(err !== null) { response.status(400); response.send({ error: err.message }); return; } response.end(); }); } /** * Modifie un produit de la liste */ modifyProduct(request,response) { productsManager.modfifyDB(request.body,request.params.id,(err) => { if(err !== null) { response.status(400); response.send({ error: err.message }); return; } response.status(204).end(); }); } } export default new ProductsController();
import React, { Fragment } from 'react'; import { PeopleContext } from './PeopleContext'; import Heading from './components/Heading'; import UnorderedList from './components/UnorderedList'; class People extends React.Component { render() { const people = this.context; return ( <Fragment> <Heading headingText="People" headingSubText={`Data about all ${people.count} star wars people`} /> { people.results && <UnorderedList items={people.results.map((item) => { return { key: item.url, listItem: item.name, } })} /> } </Fragment> ) } } People.contextType = PeopleContext; export default People;
import test from 'tape'; import HTTPBridge from '../src'; import WebTorrent from 'webtorrent'; import DHT from 'bittorrent-dht'; import auto from 'run-auto'; import finalhandler from 'finalhandler'; import fs from 'fs'; import http from 'http'; import parseTorrent from 'parse-torrent'; import path from 'path'; import serveStatic from 'serve-static'; const leavesPath = path.resolve(__dirname, 'static', 'Leaves of Grass by Walt Whitman.epub'); const leavesFilename = 'Leaves of Grass by Walt Whitman.epub'; const leavesFile = fs.readFileSync(leavesPath); const leavesTorrent = fs.readFileSync(path.resolve(__dirname, 'torrents', 'leaves.torrent')); const leavesParsed = parseTorrent(leavesTorrent); test('Seed file and download', (t) => { t.plan(9); let httpServer; let dhtServer; let bridge; let client; auto({ httpPort: (cb) => { const serve = serveStatic(path.join(__dirname, 'static')); httpServer = http.createServer((req, res) => { const done = finalhandler(req, res); serve(req, res, done); }); httpServer.on('error', (err) => { t.fail(err); }); httpServer.listen(() => { const port = httpServer.address().port; cb(null, port); }); }, dhtPort: (cb) => { dhtServer = new DHT({ bootstrap: false }); dhtServer.on('error', t.fail.bind(t)); dhtServer.on('warning', t.fail.bind(t)); dhtServer.listen(() => { const port = dhtServer.address().port; cb(null, port); }); }, bridge: ['dhtPort', 'httpPort', (cb, r) => { bridge = new HTTPBridge({ dht: { bootstrap: '127.0.0.1:' + r.dhtPort }, tracker: false, }); const url = 'http://127.0.0.1:' + r.httpPort + '/' + leavesFilename; t.comment(url); bridge.seed(url, leavesParsed, (err) => { t.error(err, 'no bridge.seed error'); cb(); }); }], client: ['bridge', (cb, r) => { t.comment('client download'); client = new WebTorrent({ tracker: false, dht: { bootstrap: '127.0.0.1:' + r.dhtPort }, }); client.on('error', t.fail.bind(t)); client.on('warning', t.fail.bind(t)); const magnetUri = 'magnet:?xt=urn:btih:' + leavesParsed.infoHash; t.comment(magnetUri); let gotBuffer = false; let gotDone = false; const maybeDone = () => { if (gotBuffer && gotDone) cb(null, client); }; client.add(magnetUri, (torrent) => { torrent.files[0].getBuffer((err, buf) => { t.error(err); t.deepEqual(buf, leavesFile, 'downloaded correct content'); gotBuffer = true; maybeDone(); }); torrent.once('done', () => { t.pass('client2 downloaded torrent from bridge'); gotDone = true; maybeDone(); }); }); }], }, (err) => { t.error(err); httpServer.close(() => { t.pass('httpServer destroyed'); }); dhtServer.destroy(() => { t.pass('dhtServer destroyed'); }); bridge.destroy(() => { t.pass('bridge destroyed'); }); client.destroy(() => { t.pass('client destroyed'); }); }); });
import styled from 'styled-components'; import Link from 'next/link'; import React, { useState, useEffect } from 'react'; import NavProfilePic from './NavProfileIcon'; import { useInView } from 'react-intersection-observer'; import { useSelector } from 'react-redux'; import { userSelector } from '../../store/user'; import router from 'next/router'; const index = () => { const [nav, setNav] = useState(false); const { userInfo } = useSelector(userSelector); const { ref, inView, entry } = useInView({ threshold: 0, }); if (typeof window !== 'undefined') { const checkWindow = () => { const ws = window.scrollY; if (ws > 50) { setNav(true); } else { setNav(false); } }; window.addEventListener('scroll', checkWindow); } return ( <> {router.pathname !== '/login' ? ( <Nav ref={ref} ws={nav} className="container sticky-top"> <LeftWrapper ws={nav}> {userInfo ? ( <NavProfilePic /> ) : ( <> <Link href="/register"> <a>تسجيل</a> </Link> <hr /> <Link href="/login"> <a>دخول</a> </Link> </> )} </LeftWrapper> <RightWrapper ws={nav}> <Logo> <Link href="/"> <a>خدماتي</a> </Link> </Logo> </RightWrapper> </Nav> ) : ( <div></div> )} </> ); }; const Nav = styled.div` height: 80px; width: 100%; background: ${(props) => (props.ws ? '#747474' : 'transparent')}; display: flex; align-items: center; border-bottom: ${(props) => (props.ws ? '1px solid #A5A5A5' : 'none')}; transition: 0.2s ease-in-out; a { color: ${(props) => (props.ws ? 'white' : 'black')}; } `; const LeftWrapper = styled.div` display: flex; justify-content: flex-start; align-items: center; width: 50%; height: 100%; hr { height: 1px; width: 20px; color: black; margin: 13px 5px; transform: rotate(90deg); } `; const RightWrapper = styled.div` display: flex; justify-content: flex-end; width: 50%; `; const Logo = styled.div` font-size: 36px; `; export default index;
/** * Created by Ziv on 2017/1/24. */ /** * 一个数组的所有元素的平方都是第二个数组的元素 * @param array1 * @param array2 * @returns {boolean} */ //clever solution function comp(array1, array2) { if(array1 == null || array2 == null) return false; array1.sort((a, b) => a - b); array2.sort((a, b) => a - b); return array1.map(v => v * v).every((v, i) => v == array2[i]); } //test: a = [121, 144, 19, 161, 19, 144, 19, 11] // b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19] // //unfinished solution 忽略了条件必须对应位置 // // function comp(array1, array2) { // if(array1 == null || array2 =null) { // return false; // } // return array2.map(el => Math.sqrt(el)).every(ix => array1.includes(ix)); // }
import { takeLatest, all } from 'redux-saga/effects' import { AppointmentsTypes } from 'App/Stores/Appointments/Actions' import { StartupTypes } from 'App/Stores/Startup/Actions' import { fetchAppointments } from './AppointmentsSaga' import { startup } from './StartupSaga' export default function* root() { yield all([ takeLatest(StartupTypes.STARTUP, startup), takeLatest(AppointmentsTypes.FETCH_APPOINTMENTS, fetchAppointments), ]) }
$(document).ready(function() { $(document).on('change', '.btn-file :file', function() { var input = $(this), numFiles = input.get(0).files ? input.get(0).files.length : 1, label = input.val().replace(/\\/g, '/').replace(/.*\//, ''); input.trigger('fileselect', [numFiles, label]); }); $('.btn-file :file').on('fileselect', function(event, numFiles, label) { var input = $(this).parents('.input-group').find(':text'), log = numFiles > 1 ? numFiles + ' files selected' : label; if( input.length ) { input.val(log); } else { if( log ) alert(log); } }); $('#summernote').summernote({ height: 300, callbacks: { onBlur: function() { $("#eventDescription").val($("#summernote").summernote('code')); }, onImageUpload: function(files, editor, welEditable) { sendFile(files[0],$("#summernote"),welEditable); } } }); $("#eventDescription").val($("#summernote").summernote('code')); $('#driverBioEditor').summernote({ height: 300, callbacks: { onBlur: function() { $("#driverBio").val($("#driverBioEditor").summernote('code')); }, onImageUpload: function(files, editor, welEditable) { sendFile(files[0],$("#driverBioEditor"),welEditable); } } }); $("#driverBio").val($("#driverBioEditor").summernote('code')); $('#vehicleDescriptionEditor').summernote({ height: 300, onBlur: function() { $("#vehicleDescription").val($("#vehicleDescriptionEditor").summernote('code')); }, onImageUpload: function(files, editor, welEditable) { sendFile(files[0],$("#vehicleDescriptionEditor"),welEditable); } }); $("#vehicleDescription").val($("#vehicleDescriptionEditor").summernote('code')); $("#partnerLinkDiv").hide(); $("#eventType").change(toggleEventType); toggleEventType(); $("#addParticipantForm").validator().on('submit', function(e) { if (e.isDefaultPrevented()) { } else { e.preventDefault(); $.ajax({ data: $("#addParticipantForm").serialize(), type: "POST", url: "/profile/participant", cache: false, processData: false, success: function(hash) { $("#addParticipant").modal('hide'); $("#addParticipantForm").trigger('reset'); $("#participantsTable").bootstrapTable('refresh'); } }); } }); $("#participantsTable").on('dbl-click-row.bs.table', function(e, row, element) { $('#event_participant_id').val(row.event_participant_id).change(); $('#addFirstName').val(row.first_name).change(); $('#addLastName').val(row.last_name).change(); $('#add_emergency_contact_name').val(row.emergency_contact_name).change(); $('#add_emergency_contact_phone').val(row.emergency_contact_phone).change(); $('#add_medical_info').val(row.medical_info).change(); $("#addParticipant").modal('show'); }); $("#registerEventForm").on('submit', function(e) { var v = $("#participantsTable").bootstrapTable('getSelections').map(function(a) { return a.event_participant_id; }).join(','); $("#participants").val(v).change(); }); $("#newsTable").on('dbl-click-row.bs.table', function(e, row, element) { window.location='/admin/news/'+row.news_id+'/edit'; }); }); function toggleEventType() { var val = $("#eventType").val(); if (val == "normal") { $("#dateFields").show(); $("#partnerLinkDiv").hide(); } else if (val == "tentative") { $("#dateFields").hide(); $("#partnerLinkDiv").hide(); } else if (val == "partner") { $("#dateFields").show(); $("#partnerLinkDiv").show(); } } function addParticipant() { } function sendFile(file,editor,welEditable) { data = new FormData(); data.append("file", file); $.ajax({ data: data, type: "POST", url: "/image", cache: false, contentType: false, processData: false, success: function(hash) { var url = "/image/"+hash; editor.summernote("insertImage", url, hash); } }); } function formatUserEmail(value, row, index) { return '<a href="/admin/users/'+row.user_id+'">'+value+"</a>"; } function formatNewsDelete(value, row, index) { return '<a href="/admin/news/'+row.news_id+'/edit">Edit</a>&nbsp;|&nbsp;<a href="/admin/news/'+row.news_id+'/delete">Delete</a>'; } function formatSponsorsDelete(value, row, index) { return '<a href="/admin/sponsors/'+row.sponsor_id+'/edit">Edit</a>&nbsp;|&nbsp;<a href="/admin/sponsors/'+row.sponsor_id+'/delete">Delete</a>'; }
import Theme from 'components/Theme' import React from 'react' import glamorous from 'glamorous' import { Link } from 'react-router-dom' const ballSize = 2 const ThemedHeader = glamorous.header( { position: 'relative', height: '4.5rem', '&::after, &::before': { content: '""', borderRadius: '50%', position: 'absolute', left: '50%', transform: 'translateX(-50%)' }, '&::after': { backgroundColor: '#f6f6f6', width: `${ballSize - 0.5}rem`, height: `${ballSize - 0.5}rem`, bottom: `-${(ballSize - 0.5) / 2}rem` }, '&::before': { width: `${ballSize}rem`, height: `${ballSize}rem`, bottom: `-${ballSize / 2}rem`, }, }, ({ theme }) => ({ color: theme.text, background: theme.primary, '&::before': { backgroundColor: theme.primary } }) ) const CloseButton = glamorous(Link)( { position: 'absolute', top: '1.5rem', right: '1.5rem', fontWeight: '300', lineHeight: '1rem', display: 'block', fontSize: '3rem', opacity: '0.5' }, ({ theme }) => ({ color: theme.text }) ) const Header = ({ children, pokemonType }) => ( <Theme type={ pokemonType }> <ThemedHeader> <CloseButton to='/pokemon'> &times; </CloseButton> </ThemedHeader> </Theme> ) export default Header
import "./App.css"; import "semantic-ui-css/semantic.min.css"; import { Form, Button, Card, Image, Icon } from "semantic-ui-react"; import { useState } from "react"; function App() { // default pin // const defaultPin = "110001"; // const defaultDate = "16-05-2021"; const defaultPin = ""; const defaultDate = ""; // define states const api_base_url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin"; const [pincodeInput, setPincodeInput] = useState(defaultPin); const [dateInput, setDateInput] = useState(defaultDate); const [data, setData] = useState([]); const [noResults, setNoResults] = useState(false); const [searchInput, setSearchInput] = useState(""); const [searchDone, setSearchDone] = useState(false); // function to handle changes to input columns function handleChange(event) { // console.log(event); var source = event.target.name; var value = event.target.value; if (source === "pincodeInput") { setPincodeInput(value); } else if (source === "dateInput") { var formatted_date = new Date(value); var date_string = formatted_date.getDate() + "-" + (formatted_date.getMonth() + 1) + "-" + formatted_date.getFullYear(); console.log(date_string); setDateInput(date_string); } else if (source === "searchInput") { setSearchInput(value); } } // function to handle submit function handleSubmit() { const api_url = api_base_url + "?pincode=" + pincodeInput + "&date=" + dateInput; console.log(api_url); fetch(api_url) .then((res) => res.json()) .then((data) => { console.log(data.centers); if (data.centers.length === 0) { console.log("No results"); setNoResults(true); } else { setNoResults(false); } setData(data.centers); }); setSearchInput(""); setSearchDone(true); } function handleSearch() { console.log("Searching for hospitals matching - " + searchInput); const filtered_data = data.filter((center) => { return center.name.includes(searchInput); }); console.log(filtered_data); setData(filtered_data); } return ( <div className="App"> <div className="header-nav-bar">COWIN</div> <div className="input-form"> <Form onSubmit={handleSubmit}> <Form.Group> <Form.Input onChange={handleChange} name="pincodeInput" placeholder="Pincode" width={3} value={pincodeInput} autofocus /> <Form.Input onChange={handleChange} name="dateInput" type="date" // label="Date in dd-mm-yyyy format" placeholder="Date in dd-mm-yyyy format" width={3} value={dateInput} /> {/* <Form.Input label='Last Name' placeholder='Last Name' width={6} /> */} <Button type="submit" className="submit-button"> Submit </Button> </Form.Group> </Form> </div> <hr></hr> <div className="search-form"> {noResults ? null : searchDone ? ( <Form onSubmit={handleSearch}> <Form.Group> <Form.Input onChange={handleChange} name="searchInput" placeholder="Search for hospital" width={8} /> <Button type="submit" className="submit-button"> Search </Button> <Button className="submit-button" onClick={handleSubmit}> Clear search </Button> </Form.Group> </Form> ) : null} </div> <div> {data.map((center_element) => { return ( <Card fluid> <Card.Content> <Card.Header> <h1>{center_element.name}</h1> </Card.Header> <Card.Meta> <span className="date">{center_element.address}</span> </Card.Meta> <Card.Description></Card.Description> </Card.Content> {center_element.sessions.map((sessions) => { return ( <Card.Content extra> <h3> Availability of {sessions.vaccine} on {sessions.date} </h3> Minimum Age Limit: {sessions.min_age_limit} <p> <strong>Dose 1:</strong>{" "} {sessions.available_capacity_dose1} </p> <p> <strong>Dose 2:</strong>{" "} {sessions.available_capacity_dose2} </p> </Card.Content> ); })} </Card> ); })} </div> <div>{noResults ? <h3>No results found</h3> : null}</div> </div> ); } export default App;
/** * @format * @flow */ import React from 'react'; import { FlatList, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import colors from '@config/colors'; function ListElement({ title, data, setValue, value }) { return ( <View style={styles.container}> <Text style={styles.title}>{title}</Text> <FlatList showsHorizontalScrollIndicator={false} horizontal data={data} keyExtractor={(item, index) => { return index.toString(); }} renderItem={({ item }) => { return <Item name={item.display} onPress={() => setValue(item.display)} isSelected={value === item.display} /> } } /> </View> ); }; const Item = ({ name, onPress, isSelected }) => { return ( <TouchableOpacity style={[styles.button, {borderColor : isSelected ? colors.colorPrimary : '#CCCCCC'}]} onPress={onPress} > <Text style={styles.city}>{name}</Text> </TouchableOpacity> ) } const styles = StyleSheet.create({ container: { marginTop: 16 }, title: { color: '#242424', fontSize: 17, fontWeight: '600' }, city: { fontSize: 15, color: '#242424', }, button: { borderWidth: 1, paddingBottom: 8, alignItems: 'center', paddingHorizontal: 8, paddingVertical: 10, justifyContent: 'center', marginRight: 16, marginTop: 16, borderRadius: 8 } }); export default ListElement;
/** * Created by huangpan on 2017/4/4. */ const {resolve, join} = require("path"); const config = require("./webpack.config.base.js"); const webpack = require("webpack"); const port = 9000; config.module.rules.push({ enforce: "pre", test: /\.js(x)?$/, include: [resolve(__dirname, "src/js")], use: "eslint-loader", }); config.devtool = "eval-source-map"; config.plugins.push( new webpack.HotModuleReplacementPlugin(), new webpack.NamedModulesPlugin(), new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("development") }) ); config.entry.unshift("react-hot-loader/patch", `webpack-dev-server/client?http://localhost:${port}`, "webpack/hot/only-dev-server"); config.devServer = { contentBase: join(__dirname, "src"), compress: true, port: port, historyApiFallback: true, hot: true, open: true, inline: true, publicPath: "/assets/" }; module.exports = config;
/** * BLOCK: guten-slider * * Registering a basic block with Gutenberg. * Simple block, renders and saves the same content without any interactivity. */ // External deps // Import CSS. import "./style.scss"; import "./editor.scss"; // Sub components import { default as edit } from "./edit"; const { __ } = wp.i18n; // Import __() from wp.i18n const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks const { MediaUpload } = wp.editor; const { Button } = wp.components; const attributes = { slides: { type: "number", default: 1 }, imgID: { type: "number" }, thumbs: { type: "array", default: [], source: "query", selector: ".block--slides-container li", query: { url: { source: "attribute", selector: "img", attribute: "src" }, alt: { source: "attribute", selector: "img", attribute: "alt", default: "" }, id: { source: "attribute", selector: "img", attribute: "data-id" } } } }; registerBlockType("cgb/block-guten-slider", { // Block name. Block names must be string that contains a namespace prefix. Example: my-plugin/my-custom-block. title: __("Guten Slider"), // Block title. icon: "images-alt2", // Block icon from Dashicons. category: "common", // Block category — Group blocks together based on common traits E.g. common, formatting, layout widgets, embed. keywords: [ __("guten-slider — CGB Block"), __("CGB Example"), __("create-guten-block") ], attributes, edit, save: function(props) { const { attributes: { slides, thumbs, imgID }, className } = props; return ( <div className={className}> <ul className={`block--slides-container slides-${slides}`}> {thumbs.map((thumb, i) => ( <li key={i}> <img data-id={thumb.id} src={thumb.url} alt={thumb.alt} /> </li> ))} </ul> </div> ); } });
import React, { useState } from 'react'; import { View, StyleSheet, Text, TouchableOpacity, Image } from 'react-native'; import { GameEngine } from 'react-native-game-engine'; import Matter from 'matter-js'; import firestore from '@react-native-firebase/firestore'; import Constants from '../util/constants'; import Plane from '../components/Plane'; import Floor from '../components/Floor'; import Physics, { resetHazards } from '../util/physics'; const Game = (props) => { const setupWorld = () => { let engine = Matter.Engine.create({ enableSleeping: false }); let world = engine.world; world.gravity.y = 0.0; let plane = Matter.Bodies.rectangle( Constants.MAX_WIDTH / 4, Constants.MAX_HEIGHT / 2, Constants.PLANE_WIDTH, Constants.PLANE_HEIGHT, ); let floor1 = Matter.Bodies.rectangle( Constants.MAX_WIDTH / 2, Constants.MAX_HEIGHT, Constants.MAX_WIDTH + 4, 50, { isStatic: true }, ); let floor2 = Matter.Bodies.rectangle( Constants.MAX_WIDTH + Constants.MAX_WIDTH / 2, Constants.MAX_HEIGHT, Constants.MAX_WIDTH + 4, 50, { isStatic: true }, ); Matter.World.add(world, [floor1, floor2, plane]); Matter.Events.on(engine, 'collisionStart', (event) => { let pairs = event.pairs; gameEngine.dispatch({ type: 'game-over' }); }); return { physics: { engine: engine, world: world }, plane: { body: plane, pose: 1, renderer: Plane, ship: props.route.params.ship, }, floor1: { body: floor1, renderer: Floor }, floor2: { body: floor2, renderer: Floor }, }; }; let entities = setupWorld(); const [running, flipGameState] = useState(true); const [score, addToScore] = useState(0); const onEvent = (event) => { if (event.type === 'game-over') { running === true ? flipGameState(false) : flipGameState(true); updatePlayerOnGameOver(); } else if (event.type === 'score') { addToScore(score + 1); } }; const updatePlayerOnGameOver = async () => { score > props.route.params.player.highScore ? await firestore() .collection('users') .doc(props.route.params.refId) .update({ highScore: score }) : null; }; const reset = () => { resetHazards(); gameEngine.swap(setupWorld()); flipGameState(true); addToScore(0); }; return ( <View style={styles.container}> <Image style={{ width: Constants.MAX_WIDTH, height: Constants.MAX_HEIGHT }} source={{ uri: 'https://firebasestorage.googleapis.com/v0/b/space-jump-f89fa.appspot.com/o/Space_1.png?alt=media&token=4a0cb26b-d699-4f06-9751-8740100ddfa5' }} /> <GameEngine ref={(ref) => (gameEngine = ref)} style={styles.gameContainer} running={running} onEvent={onEvent} systems={[Physics]} entities={entities}></GameEngine> <Text style={styles.gameScore}>{score}</Text> {!running && ( <View style={styles.fullScreenButton}> <View style={{ alignItems: 'center' }}> <Text style={styles.gameOverText}>GAME OVER</Text> <Text style={styles.gameOverText}>{score}</Text> </View> <View style={styles.gameOverOptions}> <TouchableOpacity onPress={() => reset()} style={styles.gameOverButtons}> <Text style={styles.gameSubOverText}>Try Again</Text> </TouchableOpacity> <TouchableOpacity onPress={() => props.navigation.navigate('Menu')} style={styles.gameOverButtons}> <Text style={styles.gameSubOverText}>Menu</Text> </TouchableOpacity> </View> </View> )} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', }, backgroundImage: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, width: Constants.MAX_WIDTH, height: Constants.MAX_HEIGHT, }, gameContainer: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0, }, gameOverText: { color: 'white', fontSize: 48, alignItems: 'center', }, gameSubOverText: { color: 'white', fontSize: 24, padding: 5, margin: 5, }, gameOverOptions: { flexDirection: 'row', justifyContent: 'space-around', }, gameOverButtons: { marginTop: 50, width: 150, backgroundColor: 'tomato', borderRadius: 10, alignItems: 'center', }, gameScore: { position: 'absolute', color: 'white', fontSize: 72, top: 50, left: Constants.MAX_WIDTH / 2 - 30, textShadowColor: '#444', textShadowOffset: { width: 2, hegj: 2 }, textShadowRadius: 2, }, fullScreenButton: { position: 'absolute', height: Constants.MAX_HEIGHT, width: Constants.MAX_WIDTH, flex: 1, backgroundColor: 'black', opacity: 0.8, justifyContent: 'center', }, }); export default Game;
"use strict"; /* eslint-disable */ function User(firstname, lastname, birthDate) {     this.firstname = firstname;     this.lastname = lastname;     this.birthDate = birthDate; } let user1 = new User('John', 'Smith', new Date('2000-10-01')); let user2 = new User('Edward', 'Hopkins', new Date('1991-11-14')); function getFullName() { return this.firstname + ' ' + this.lastname;} function getAge() {return new Date().getFullYear() - this.birthDate.getFullYear();} User.prototype.getAge = getAge; User.prototype.getFullName = getFullName; //complete the code so that the above functions reside in a single object and are inherited by all User objects //that are created using User as a constructor function. console.log(user1.getFullName()); //John Smith console.log(user1.getAge()); //21
appicenter.filter("boolean", function() { return function(input) { if (input === true) return 'Yes'; else return 'No'; } });