text
stringlengths
7
3.69M
!function () { function Controller($scope) { }; angular.module('DNNT').controller('homeController', Controller); }();
const mongoose = require('mongoose') const eventSchema = new mongoose.Schema({ eventName : { type : String, required : true}, startingDate : { type: Date, required : true}, duration : { type : Number, required : true}, maximumLimitDate : { type: Date, required : true}, timeSlotDuration : { type: String, required : true}, numberOfTeachers : { type: Number, required : true}, schoolYearId : { type: mongoose.ObjectId, required : true}, timeSlots : [{type: mongoose.ObjectId, ref: "timeSlots"}] }) module.exports = mongoose.model('Event', eventSchema)
import './App.css'; import React from "react"; import { BrowserRouter as Router, Switch, Route, Redirect } from "react-router-dom"; import HeaderMenu from './components/HeaderMenu/HeaderMenu'; import HomePage from './pages/home/HomePage'; import SpeakersPage from './pages/speakers/SpeakersPage'; const App = () => { return ( <Router> <div> <HeaderMenu/> <Switch> <Route path="/home"> <HomePage /> </Route> <Route path="/speakers"> <SpeakersPage /> </Route> <Redirect exact from="/" to="home" /> </Switch> </div> </Router> ); } export default App;
'use strict' const rollup = require('rollup').rollup const cleanup = require('../') const expect = require('expect') const path = require('path') const fs = require('fs') process.chdir(__dirname) function concat(name, subdir) { let file = path.join(__dirname, subdir || 'expected', name) file = file.replace(/\\/g, '/') if (!path.extname(file)) { file += '.js' } return file } function testLines(code, expected, lines) { const options = { comments: 'all', functions: false, debuggerStatements: false } if (lines != null) { if (typeof lines == 'object') { Object.assign(options, lines) } else { options.maxEmptyLines = lines } } const promise = cleanup(options).transform(code, 'test.js') expect(promise).toBeA(Promise) return promise.then((result) => { expect(result && result.code).toBe(expected) }) } function testFile(file, opts, fexp, save) { // eslint-disable-line max-params const fname = concat(file, 'fixtures') const expected = fexp === null ? null : fs.readFileSync(concat(fexp || file), 'utf8') const code = fs.readFileSync(fname, 'utf8') const promise = cleanup(opts).transform(code, fname) if (fexp === null) { return expect(promise).toBe(null) } expect(promise).toBeA(Promise) return promise.then((result) => { if (save && result) { fs.writeFileSync(concat(file + '_out'), result.code, 'utf8') } expect(result && result.code).toBe(expected) }) } // =========================================================================== describe('rollup-plugin-cleanup', function () { const emptyLines10 = '\n\n\n\n\n\n\n\n\n\n' const emptyLinesTop = emptyLines10 + 'X' const emptyLinesBottom = 'X' + emptyLines10 const emptyLinesMiddle = emptyLines10 + 'X' + emptyLines10 + 'X' + emptyLines10 const emptyLinesTemplate = emptyLines10 + '`' + emptyLines10 + '`' + emptyLines10 it('by default removes all the empty lines and normalize to unix', function () { return testLines([ '', 'abc ', 'x\t', '\r\ny \r', '\n\n\r\t', 'z ', ].join('\n'), 'abc\nx\ny\nz') }) it('do not touch current indentation of non-empty lines', function () { return testLines(' \n X\n X ', ' X\n X') }) it('has fine support for empty lines with `maxEmptyLines`', function () { const promises = [ testLines(emptyLinesTop, 'X'), testLines(emptyLinesBottom, 'X\n'), testLines(emptyLinesTemplate, '`' + emptyLines10 + '`\n'), testLines(emptyLinesTop, '\nX', 1), testLines(emptyLinesBottom, 'X\n\n', 1), testLines(emptyLinesMiddle, '\nX\n\nX\n\n', 1), testLines(emptyLinesTemplate, '\n`' + emptyLines10 + '`\n\n', 1), testLines(emptyLinesTop, '\n\n\nX', 3), testLines(emptyLinesBottom, 'X\n\n\n\n', 3), testLines(emptyLinesMiddle, '\n\n\nX\n\n\n\nX\n\n\n\n', 3), testLines(emptyLinesTemplate, '\n\n\n`' + emptyLines10 + '`\n\n\n\n', 3), ] return Promise.all(promises) }) it('can keep all the lines by setting `maxEmptyLines` = -1', function () { return Promise.all([ testLines(emptyLinesTop, emptyLinesTop, -1), testLines(emptyLinesBottom, emptyLinesBottom, -1), testLines(emptyLinesMiddle, emptyLinesMiddle, -1), testLines(emptyLinesTemplate, emptyLinesTemplate, -1), ]) }) it('can convert to Windows line-endings with `normalizeEols` = "win"', function () { const opts = { maxEmptyLines: 1, normalizeEols: 'win' } return Promise.all([ testLines(emptyLinesTop, '\r\nX', opts), testLines(emptyLinesBottom, 'X\r\n\r\n', opts), testLines(emptyLinesMiddle, '\r\nX\r\n\r\nX\r\n\r\n', opts), testLines(emptyLinesTemplate, '\r\n`' + emptyLines10 + '`\r\n\r\n', opts), ]) }) it('and convertion to Mac line-endings with `normalizeEols` = "mac"', function () { const opts = { maxEmptyLines: 1, normalizeEols: 'mac' } return Promise.all([ testLines(emptyLinesTop, '\rX', opts), testLines(emptyLinesBottom, 'X\r\r', opts), testLines(emptyLinesMiddle, '\rX\r\rX\r\r', opts), testLines(emptyLinesTemplate, '\r`' + emptyLines10 + '`\r\r', opts), ]) }) it('makes normalization to the desired `normalizeEols` line-endings', function () { const opts = { maxEmptyLines: -1, normalizeEols: 'mac' } return testLines('\r\n \n\r \r\r\n \r\r \n', '\r\r\r\r\r\r\r\r', opts) }) it('handles ES7', function () { return testFile('es7') }) it('throws with the rollup `this.error` method.', function () { const opts = { input: 'fixtures/with_error.js', plugins: [cleanup()], } return rollup(opts).catch((err) => { expect(err.code).toBe('PLUGIN_ERROR') expect(err).toIncludeKey('loc').toBeA(Object) }) }) }) describe('Removing comments', function () { it('with `comments: ["some", "eslint"]', function () { return testFile('defaults', { comments: ['some', 'eslint'], }) }) it('with `comments: "none"`', function () { return testFile('defaults', { comments: 'none' }, 'comments_none') }) it('with `comments: false`', function () { return testFile('defaults', { comments: false }, 'comments_none') }) it('with `comments: true`', function () { return testFile('defaults', { comments: true }, 'comments_all') }) it('with `comments: /@preserve/`', function () { return testFile('defaults', { comments: /@preserve/ }, 'comments_regex') }) it('with long comments', function () { return testFile('long_comment') }) it('with no changes due normalization nor emptyLines', function () { return testFile('comments') }) it('with "ts3s" preserves TypeScript Triple-Slash directives.', function () { return testFile('ts3s', { comments: 'ts3s' }) }) it('"srcmaps" is an alias to "sources"', function () { const opts = { comments: 'srcmaps' } const lines = [ '//', '0', '//# sourceURL=a.map', '//# sourceMappingURL=a.js.map', ] return testLines(lines.join('\n'), lines.slice(1).join('\n'), opts) }) it('throws on unknown filters', function () { return expect(() => { cleanup({ comments: 'foo' }) }).toThrow('unknown') }) }) describe('Extension handling', function () { it('with `extensions: ["*"] must process all extensions', function () { return testFile('extensions.foo', { extensions: ['*'], }) }) it('with specific `extensions` must process given extensions', function () { return testFile('extensions.foo', { extensions: 'foo', }) }) it('must skip non listed extensions', function () { return testFile('comments', { extensions: 'foo' }, null) }) it('must handle empty extensions', function () { const opts = { extensions: '.', sourcemap: false } const source = 'A' expect(cleanup(opts).transform(source, 'a.ext')).toBe(null) const promise = cleanup(opts).transform(source, 'no-ext') expect(promise).toBeA(Promise) return promise.then((result) => { expect(result.code).toBe(source) }) }) }) describe('Issues', function () { it('must handle .jsx files (issue #1)', function () { const jsx = require('rollup-plugin-jsx') const opts = { input: 'fixtures/issue_1.jsx', plugins: [ jsx({ factory: 'React.createElement' }), cleanup(), ], external: ['react'], } return rollup(opts).then((bundle) => bundle.generate({ format: 'cjs', exports: 'auto' }).then((result) => { expect(result.output).toBeAn(Array) const output = result.output[0] expect(output).toExist() expect(output.code).toMatch(/module\.exports/) expect(output.code).toNotMatch(/to_be_removed/) expect(output.map).toNotExist() }) ) }) it('must support spread operator by default (issue #10)', function () { return testFile('issue_10') }) it('must support import() by default (issue #11)', function () { return testFile('issue_11') }) it('#15 must handle "$" ending the string', function () { const opts = { sourceMap: false, } /* eslint-disable no-template-curly-in-string */ const result = [ 'const s = `${v}$`', 'const s = `$${v}$`', 'const s = `${v}$$`', 'const s = `\\$`', 'const s = `$0`', 'const s = `$$`', 'const s = `$`', ].map(function (str) { return cleanup(opts).transform(str, 'a.js').then((res) => { expect(res.code).toBe(str) }) }) /* eslint-enable no-template-curly-in-string */ return Promise.all(result) }) it('#16 rollup hang up when running with this plugin in node.js', function () { testFile('issue_16') }) }) describe('SourceMap support', function () { const validator = require('sourcemap-validator') const buble = require('@rollup/plugin-buble') it('bundle generated by rollup w/sourcemap', function () { return rollup({ input: 'maps/bundle-src.js', plugins: [ buble({ ie: 11 }), cleanup(), ], }).then(function (bundle) { return bundle.generate({ format: 'iife', indent: true, name: 'myapp', sourcemap: true, sourcemapFile: 'maps/bundle.js', // generates source filename w/o path banner: '/*\n plugin version 1.0\n*/\n/*eslint-disable*/', footer: '/* follow me on Twitter! @amarcruz */', }).then((result) => { result = result.output && result.output[0] expect(result).toBeAn(Object).toExist() const code = result.code const expected = fs.readFileSync('maps/output.js', 'utf8') expect(code).toBe(expected, 'Genereted code is incorrect!') expect(result.map).toBeAn(Object).toExist() validator(code, JSON.stringify(result.map)) }) }) }) it('must skip sourcemap generation with `sourceMap: false`', function () { const fname = 'fixtures/defaults.js' const code = fs.readFileSync(fname, 'utf8') const promise = cleanup({ sourceMap: false }).transform(code, fname) expect(promise).toBeA(Promise) return promise.then((result) => { expect(result.map).toNotExist() }) }) it('must skip sourcemap generation with `sourcemap: false` (lowercase)', function () { const fname = 'fixtures/defaults.js' const code = fs.readFileSync(fname, 'utf8') const promise = cleanup({ sourcemap: false }).transform(code, fname) expect(promise).toBeA(Promise) return promise.then((result) => { expect(result.map).toNotExist() }) }) })
var Service = require('node-linux').Service; // Create a new service object var svc = new Service({ name:'Vandelay', script:'../../server.js', }); // Listen for the stop event, which indicates that the process has stopped. svc.on('stop',function(){ console.log("Service stopped."); }); svc.stop();
/** * Created by gurusrikar on 5/8/17. */ (function (){ console.log("Welcome to CSE110!"); })(); // var testCasesList = ['', '']; var testCaseObject = { "setup": "", "execute": "", "passed_feedback": "", "failed_feedback": "" }; var totalTestCases = 1; var ractive = new Ractive({ el: '#form-container', template: '#template', modifyArrays: true, // Here, we're passing in some initial data data: { lang: 'Python', code: '', testCasesList: { case1: getNewTestCaseObj() }, hiddenCode: '', score: '0' } }); var previousUpdate = undefined; updateJSON(); function saveJson() { console.log(ractive.get()); updateJSON(); return false; } function addTestCase() { console.log("adding new test case"); // testCasesList.push(''); totalTestCases = totalTestCases + 1; var caseString = "case"+totalTestCases; ractive.set('testCasesList.'+caseString, getNewTestCaseObj()); return false; } function updateJSON() { var outputElement = document.getElementById("output-json"); outputElement.innerHTML = JSON.stringify(ractive.get(), undefined, 4); } function downloadJson() { var fileName = (document.getElementById("inputFileName").value || "sample") + ".json"; var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(ractive.get(), undefined, 4)); var downloadSimulateElem = document.getElementById("hiddenDownloadElem"); downloadSimulateElem.setAttribute("href", dataStr); downloadSimulateElem.setAttribute("download", fileName); downloadSimulateElem.click(); } function getNewTestCaseObj() { return { "setup": "", "execute": "", "passed_feedback": "", "failed_feedback": "" }; } setInterval(function () { previousUpdate = ractive.get(); updateJSON(); }, 1500);
$(function() { $(".button-collapse").sideNav(); }); ////home//// $(function() { $(window).on('scroll', function() { if ($(document).scrollTop() > 135) { $('.fixbar').addClass('fixed'); } else { $('.fixbar').removeClass('fixed'); } }); }); $(function() { $(".link").click(function(e){ e.preventDefault(); var target = $(this).attr("href"); var offset = $(target).offset().top; $("body, html").animate({ scrollTop: offset - 160 }, 1000); }); }); $(function() { $("side_link").click(function(e){ e.preventDefault(); window.location.href = "/"; var target = $(this).attr("href"); var offset = $(target).offset().top; $("body, html").animate({ scrollTop: offset - 160 }, 1000); }); }); $(function(){ $('#notice_button').click(function(e){ e.preventDefault(); //preloader $(".progress").css("visibility", "visible"); var js_keyword = $(":text[id='keyword']").val(); var js_url = $("#url").val(); var js_email = $("#email").val(); console.log(js_keyword); console.log(js_url); console.log(js_email); $.ajax({ type: 'POST', url: '/notice', data: { keyword: js_keyword, url: js_url, email: js_email }, success: function(json){ //alert("正常に操作が完了しました。"); var notification = document.querySelector('.mdl-js-snackbar'); var data = { message: '正常に操作が完了しました。', actionHandler: function(event) {}, //actionText: 'Undo', actionText: 'OK', timeout: 2000 }; notification.MaterialSnackbar.showSnackbar(data); //preloader $(".progress").css("visibility", "hidden"); }, error: function(){ var notification = document.querySelector('.mdl-js-snackbar'); var data = { message: '調子が悪いようです... \n 時間をおいてお試し下さい。', actionHandler: function(event) {}, //actionText: 'Undo', actionText: 'OK', timeout: 2000 }; notification.MaterialSnackbar.showSnackbar(data); //preloader $(".progress").css("visibility", "hidden"); } }); }); }); $(function(){ $('#contact_button').click(function(e){ e.preventDefault(); //preloader $(".progress").css("visibility", "visible"); var js_contact_email = $("#contact_email").val(); var js_message = $("#message").val(); $.ajax({ type: 'POST', url: '/contact', data: { contact_email: js_contact_email, message: js_message }, success: function(json){ //alert("製作者にメッセージを送信しました。"); var notification = document.querySelector('.mdl-js-snackbar'); var data = { message: '製作者にメッセージを送信しました。', actionHandler: function(event) {}, actionText: 'OK', timeout: 2000 }; notification.MaterialSnackbar.showSnackbar(data); //preloader $(".progress").css("visibility", "hidden"); }, error: function(){ var notification = document.querySelector('.mdl-js-snackbar'); var data = { message: '調子が悪いようです... \n 時間をおいてお試し下さい。', actionHandler: function(event) {}, //actionText: 'Undo', actionText: 'OK', timeout: 2000 }; notification.MaterialSnackbar.showSnackbar(data); //preloader $(".progress").css("visibility", "hidden"); } }); }); }); ////config///// $(function(){ $('.url').click(function(e){ e.preventDefault(); var url = $(this).attr("href"); window.open(url); }); }); //汚いので変えたい、でもめんどい $(function(){ $('#update_button').click(function(e){ e.preventDefault(); //preloader $(".progress").css("visibility", "visible"); var js_notice_box = []; var js_notice_box_id = []; var js_delete_box = []; var js_length = $("#update_button").data("length") var js_email = $("#update_button").data("email") for(var i = 0; i < js_length; i++){ if ($("#notice_box" + i).is(":checked")){ //checked = 通知してない = 0 js_notice_box.push(0); }else{ js_notice_box.push(1); } js_notice_box_id.push($("#notice_box" + i).data("notice_id")); if($("#delete_box" + i).is(":checked")){ js_delete_box.push($("#delete_box" + i).data("delete_id")); } } console.log(js_notice_box); console.log(js_delete_box); $.ajax({ type: 'POST', url: '/config', data: { notice_box: js_notice_box, delete_box: js_delete_box, email: js_email, notice_box_id: js_notice_box_id }, success: function(json){ //alert("正常に操作が完了しました。"); var notification = document.querySelector('.mdl-js-snackbar'); var data = { message: '正常に操作が完了しました。', actionHandler: function(event) {}, //actionText: 'Undo', actionText: 'OK', timeout: 2000 }; notification.MaterialSnackbar.showSnackbar(data); //preloader $(".progress").css("visibility", "hidden"); }, error: function(){ var notification = document.querySelector('.mdl-js-snackbar'); var data = { message: '調子が悪いようです... \n 時間をおいてお試し下さい。', actionHandler: function(event) {}, //actionText: 'Undo', actionText: 'OK', timeout: 2000 }; notification.MaterialSnackbar.showSnackbar(data); //preloader $(".progress").css("visibility", "hidden"); } }); }); }); ////config_start//// $(function(){ $('#sys_button').click(function(e){ e.preventDefault(); config = "/config/" + $("#config_email").val(); window.location.href = config; }); });
import { createRouter, createWebHistory, createMemoryHistory } from "vue-router"; import Home from "../views/Home.vue"; import Index from "../views/Index.vue"; import About from "../views/About.vue"; import Test from "../views/Test.vue"; import NotFound from "../views/404.vue"; const routes = [ { path: "/home", name: "Home", component: Home, meta: { title: "Home", keywords: "damowang, 标签,home", description: "www.damowangzhu.com" } }, { path: "/", alias: "/index", name: "Index", component: Index, meta: { title: "首页 | Index" } }, { path: "/about", name: "About", component: About // component: () => // 报错 编译路径问题? // // // import(/* webpackChunkName: "about" */ "../views/About.vue") // import("../views/About.vue") }, { path: "/test", name: "Test", component: Test }, { path: "/404", name: "NotFound", component: NotFound } ]; export default function() { return createRouter({ history: process.env.VUE_APP_SSR ? createMemoryHistory() : createWebHistory(), routes }); }
import mongoose from 'mongoose' const DataPointSchema = new mongoose.Schema({ // handles are the official syntax published in internal documentation // uses lowercase acronmym with @ symbol, such as @mrr for monthly recurring revenue handle: { type: String }, //the industry standard name of the metric, such as Trailing Twelve Month's Revenue completeName: { type: String }, //the commonly used acronym, such as TTMR for Trailing Twelve Month's Revenue acronym: { type: String }, //possible user inputs that should save to this DataPoint inputVariations: [{ type: String }], //relates it to the many Categories that will include this DataPoint classifiers: [{ type: String }], //describes the metric so that others can use it appropriately description: { type: String } }); export default mongoose.model('DataPoint', DataPointSchema);
const { ApolloServer, gql, PubSub } = require("apollo-server"); const { GraphQLScalarType } = require("graphql"); const { Kind } = require("graphql/language"); const mongoose = require("mongoose"); require("dotenv").config(); mongoose.connect( `mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@cluster0.haie3.mongodb.net/<dbname>?retryWrites=true&w=majority`, { useNewUrlParser: true } ); const db = mongoose.connection; const movieSchema = new mongoose.Schema({ title: String, releaseDate: Date, rating: Number, status: String, actorIds: [String], }); const Movie = mongoose.model("Movie", movieSchema); // gql`` parses your string into an AST - see 'what-is-an-ast.md' const typeDefs = gql` fragment Meta on Movie { releaseDate rating } scalar Date enum Status { WATCHED INTERESTED NOT_INTERESTED UNKNOWN } type Actor { id: ID! name: String! } # Schema type Movie { id: ID! title: String! releaseDate: Date rating: Int status: Status actor: [Actor] # Valid null or [] or [... some data]. Not Valid [... some data without name or id] # actor: [Actor]! # Valid [] or [...some data] # actor: [Actor!]! # Valid [...some data] } type Query { movies: [Movie] movie(id: ID): Movie } input ActorInput { id: ID name: String } input MovieInput { id: ID title: String releaseDate: Date rating: Int status: Status actor: [ActorInput] } type Mutation { addMovie(movie: MovieInput): [Movie] } type Subscription { movieAdded: Movie } `; const actors = [ { id: "gordon", name: "Gordon Liu", }, { id: "bruce", name: "Bruce Lee", }, ]; const movies = [ { id: "321", title: "5 Deadly Venoms", releaseDate: new Date("10-10-1983"), rating: 5, actor: [ { id: "bruce", }, ], }, { id: "456", title: "36 Chambers", releaseDate: new Date("8-20-1983"), rating: 5, actor: [ { id: "gordon", }, ], }, ]; const pubsub = new PubSub(); const MOVIE_ADDED = "MOVIE_ADDED"; const resolvers = { Subscription: { movieAdded: { subscribe: () => { return pubsub.asyncIterator([MOVIE_ADDED]); }, }, }, Query: { movies: async () => { try { const allMovies = await Movie.find(); return allMovies; } catch (error) { console.log("movies", error); return []; } }, movie: async (obj, { id }, context, info) => { try { const foundMovie = await Movie.findById(id); return foundMovie; } catch (error) { console.log("allmovies", error); return {}; } }, }, Movie: { actor: (obj, args, context) => { console.log(obj); const actorIds = obj.actor.map((actor) => actor.id); const filteredActors = actors.filter((actor) => { return actorIds.includes(actor.id); }); return filteredActors; }, }, Mutation: { addMovie: async (obj, { movie }, context) => { try { const newMovie = await Movie.create({ ...movie, }); pubsub.publish(MOVIE_ADDED, { movieAdded: newMovie }); return [newMovie]; // console.log("context", context); // // Do mutation and/or database stuff // const newMoviesList = [ // ...movies, // // new movie data goes here, comes from destructured args // movie, // ]; // // Return data as expected in schema // return newMoviesList; } catch (error) { console.log("addMovie", error); return []; } }, }, Date: new GraphQLScalarType({ name: "Date", description: "It's a date, deal with it!", parseValue(value) { // value from the client return new Date(value); }, serialize(value) { // value sent to the client return value.getTime(); }, parseLiteral(ast) { if (ast.kind === Kind.INT) { return new Date(ast.value); } }, }), }; const server = new ApolloServer({ typeDefs, resolvers, introspection: true, // fixes GET query missing playground: true, // fixes GET query missing context: ({ req }) => { const fakeUser = { useId: "Fake User ID", }; return { ...fakeUser }; }, }); db.on("error", console.error.bind(console, "connection error:")); db.once("open", function () { // we're connected! console.log("✅ database connected! ✅"); server .listen({ port: process.env.PORT || 4000, }) .then(({ url }) => { console.log(`Server started at ${url}`); }); });
var text = prompt("Enter a name: "); function capitalize(text) { return (text.charAt(0).toUpperCase() + text.slice(1)); } console.log("Output: " + capitalize(text));
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const clientSchema = new Schema({ clientId: String, clientSecret: String, users: [ { type: mongoose.Schema.Types.ObjectId, ref: 'User' } ] }); exports.Client = mongoose.model('Client', clientSchema);
const ObjectId = require('mongoose').Schema.Types.ObjectId module.exports = function (app) { const mongooseClient = app.get('mongooseClient') const { Schema } = mongooseClient const addresses = new Schema( { streetNumber: { type: Number, required: true }, suite: { type: String, required: [true, 'Error, cannot be blank'] }, street: { type: String, required: [true, 'Error, cannot be blank'] }, city: { type: String, required: [true, 'Error, cannot be blank'] }, province: { type: String, required: [true, 'Error, cannot be blank'] }, postalCode: { type: String, required: [true, 'Error, cannot be blank'] }, country: { type: String, required: [true, 'Error, cannot be blank'] }, latitude: { type: Number }, longtitude: { type: Number } }, { timestamps: true } ) const orderDetails = new Schema( { productId: { type: ObjectId, ref: 'products' }, title: { type: String, required: true }, price: { type: Number, required: true }, displayName: { type: String, required: true }, address: { type: addresses, required: true } }, { timestamps: true } ) const orders = new Schema( { status: { type: Number, required: true }, orderDetails: [orderDetails], total: {type: Number, required: true}, transactionIds: [ { type: ObjectId, ref: 'transactions' } ] }, { timestamps: true } ) return mongooseClient.model('orders', orders) }
module.exports = Host; var Transceiver = require("./Transceiver"); var Frame = require("./Frame"); function Host(name, macAddress) { this.name = name; this.macAddress = macAddress; this.port = new Transceiver("Port0", receiveHandler, this); var that = this; function receiveHandler(srcPort, frame) { if (frame.destMac === that.macAddress) { console.log(that.name + " has received the frame"); } else { console.log(that.name + " dropped frame - not intended recipient"); } } } Host.prototype.transmitLayer2 = function(destMac, payload) { var frame = new Frame(destMac, this.macAddress, payload); this.port.transmit(frame); };
const request = require('request'); const schedule = require('node-schedule'); var client = require ('cheerio-httpcli'); // 봇이 시작하면 시작했다고 메세지 보내기 request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "봇을 시작합니다." }' }); // 월요일부터 금요일까지 각 시간별로 시간 보내기 schedule.scheduleJob('30 7 * * 1-5', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "아침 식사하러 갑시다." }' }); }); schedule.scheduleJob('55 12 * * 1-5', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "점심 식사하러 갑시다." }' }); }); schedule.scheduleJob('48 17 * * 1-4', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "저녁 식사하러 갑시다." }' }); }); // 금요일 저녁은 따로 공지 schedule.scheduleJob('00 18 * * 5', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "저녁 식사하러 갑시다." }' }); }); // 토요일 일요일 식사시간 알리미 schedule.scheduleJob('30 8 * * 6-7', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "아침 식사하러 갑시다." }' }); }); schedule.scheduleJob('00 12 * * 6-7', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "점심 식사하러 갑시다." }' }); }); schedule.scheduleJob('00 18 * * 6-7', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "저녁 식사하러 갑시다." }' }); }); console.log("봇이 작동을 시작했습니다.") // 유리시 schedule.scheduleJob('20 10 * * 1-7', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "유리시 2분전입니다. 준비하세요." }' }); }); schedule.scheduleJob('20 22 * * 1-7', function(){ request.post({ headers: { 'content-type': 'application/json' }, url: 'WebHookUrl', body: '{ "text": "유리시 2분전입니다. 준비하세요." }' }); }); // const cheerio = require('cheerio'); // var url = "https://search.naver.com/search.naver?query=AWS&where=news"; // request(url, function(error, response, html){ // if (error) {throw error}; // var $ = cheerio.load(html); // $('.news_tit').each(function(){ // // var output = process.stdout.write($(this).text()); // // request.post({ // // headers: { 'content-type': 'application/json' }, // // url: 'WebHookUrl', // // body: '{"text":'+ process.stdout.write($(this).text()) +'}' // // }); // console.log('{"text":'+ process.stdout.write($(this).text()) +'}') // }) // });
import React from 'react' import InputField from './input-field' export default { title: 'Input field', component: InputField } export const Default = () => (<InputField/>)
var mongoose = require('mongoose'); var config = require('../etc/config.json'); module.exports = function setUpConnection(env) { if ('undefined' == typeof env) { env = 'development'; } mongoose.connect( // `mongodb://kostiantyn.manko:password@ds263367.mlab.com:63367/bookshop` `mongodb://${config[env].db.host}:${config[env].db.port}/${config[env].db.name}`, { useMongoClient: true, socketTimeoutMS: 0, keepAlive: true, reconnectTries: 30 }); }
import sinon from 'sinon'; import launchDarklyClient from 'ldclient-js'; import { takeEvery } from 'redux-saga/effects'; import { FEATURES_INIT_REQUESTED } from '../store/features'; import { getInitialFeatures, createFeatureChannel, watchInitialiseFeatures, intialiseLaunchDarkly, } from './features'; describe('features saga', () => { const mockFeatures = { mockFlag: true }; const mockFeaturesUpdate = { mockFlag: { previous: true, current: true } }; const mockClient = {}; const sandbox = sinon.sandbox.create(); beforeEach(() => { mockClient.off = sandbox.stub(); mockClient.allFlags = sandbox.stub().returns(mockFeatures); sandbox.stub(launchDarklyClient, 'initialize').returns(mockClient); }); afterEach(() => { sandbox.restore(); }); describe('getInitialFeatures', () => { beforeEach(() => { mockClient.on = sandbox.stub().callsArg(1); }); test('resolves with features and removes the event listener', () => getInitialFeatures(mockClient).then((features) => { expect(mockClient.on.calledOnce).toBe(true); expect(features).toBe(mockFeatures); expect(mockClient.off.calledOnce).toBe(true); }) ); }); describe('createFeatureChannel', () => { beforeEach(() => { mockClient.on = sandbox.stub().callsArg(1, mockFeaturesUpdate); }); test('returns an off function', () => { const featureChannel = createFeatureChannel(mockClient); featureChannel.close(); expect(mockClient.off.calledOnce).toBe(true); }); }); describe('watchInitialiseFeatures', () => { test('takes every result of the initialiseFeature saga', () => { const generator = watchInitialiseFeatures(); expect(generator.next().value) .toEqual(takeEvery(FEATURES_INIT_REQUESTED, intialiseLaunchDarkly)); }); }); });
(function() { var OMeta, Stack, subclass, _ref; OMeta = require('./ometa-base'); _ref = require('./ometa-lib'), subclass = _ref.subclass, Stack = _ref.Stack; BSDentParser = subclass(OMeta, { "initialize": function() { return this.mindent = new Stack().push(-1) }, "exactly": function() { var other; return this._or((function() { return (function() { switch (this._apply('anything')) { case "\n": return this._applyWithArgs("apply", "nl"); default: throw this.fail } }).call(this) }), (function() { return (function() { other = this._apply("anything"); return OMeta._superApplyWithArgs(this, 'exactly', other) }).call(this) })) }, "inspace": function() { return (function() { this._not((function() { return this._applyWithArgs("exactly", '\n') })); return this._apply("space") }).call(this) }, "nl": function() { var p; return (function() { at = this._idxConsumedBy((function() { return (function() { OMeta._superApplyWithArgs(this, 'exactly', '\n'); p = this._apply("pos"); return this.lineStart = p }).call(this) })); return '\n' }).call(this) }, "blankLine": function() { return (function() { this._many((function() { return this._apply("inspace") })); return this._applyWithArgs("exactly", "\n") }).call(this) }, "dent": function() { var ss; return (function() { at = this._idxConsumedBy((function() { return (function() { this._many((function() { return this._apply("inspace") })); this._applyWithArgs("exactly", "\n"); this._many((function() { return this._apply("blankLine") })); return ss = this._many((function() { return this._applyWithArgs("exactly", " ") })) }).call(this) })); return ss.length }).call(this) }, "linePos": function() { var p; return (function() { at = this._idxConsumedBy((function() { return p = this._apply("pos") })); return p - (this.lineStart || 0) }).call(this) }, "stripdent": function() { var d, p; return (function() { at = this._idxConsumedBy((function() { return (function() { d = this._apply("anything"); return p = this._apply("anything") }).call(this) })); return '\n' + Array(d - p).join(' ') }).call(this) }, "nodent": function() { var p, d; return (function() { p = this._apply("anything"); d = this._apply("dent"); return this._pred(d === p) }).call(this) }, "moredent": function() { var p, d; return (function() { p = this._apply("anything"); d = this._apply("dent"); this._pred(d >= p); return this._applyWithArgs("stripdent", d, p) }).call(this) }, "lessdent": function() { var p, d; return (function() { p = this._apply("anything"); return this._or((function() { return (function() { d = this._apply("dent"); return this._pred(d <= p) }).call(this) }), (function() { return (function() { this._many((function() { return this._apply("inspace") })); return this._apply("end") }).call(this) })) }).call(this) }, "setdent": function() { var p; return (function() { p = this._apply("anything"); return this.mindent.push(p) }).call(this) }, "redent": function() { return this.mindent.pop() }, "spacedent": function() { return (function() { this._pred(this.mindent.top() >= 0); return this._applyWithArgs("moredent", this.mindent.top()) }).call(this) } });; module.exports = BSDentParser; }).call(this);
const {groupBy} = require('../../Helpers/dbHelper'); const {knex} = require('../../knex/knex') const allowedFields = ["user_id", "clicked_by"] const moment = require('moment'); getDbFields = (data) => { let obj = {}; allowedFields.forEach(column => { if (data.hasOwnProperty(column)) { obj[column] = data[column] } }) return obj } getFilteredContactViews = async (userId, startDate, endDate) => { return await knex('directory_impressions').where('user_id', userId).where('created_at', '>=', startDate) .where('created_at', '<=', endDate).select(); } getUserGroupByData = async (userId, dateFilter = null) => { let startDate = null; if (dateFilter === 'Last month') { startDate = moment().subtract(30, 'days').startOf("day").format(); } else { startDate = moment().subtract(15, 'days').startOf("day").format(); } var records = await getFilteredContactViews(userId, startDate, moment().add(1, 'day').format()); groupedRecords = await groupBy(records) let count = []; let labels = []; let total = 0; for (let property in groupedRecords) { labels.push(property) count.push(groupedRecords[property].length); total += groupedRecords[property].length } return {labels, count, total} } module.exports.getUserGroupByData = getUserGroupByData
export { default } from './ScrumMasterPanel';
import $ from 'jquery'; import Backbone from 'backbone'; import _ from 'underscore'; const SquareView = Backbone.View.extend({ // To get each square wrapped in: <li class="symbol-card large-4 medium-4 small-4 columns"> tagName: 'li', className: 'symbol-card large-4 medium-4 small-4 columns', initialize: function() { this.template = _.template(Backbone.$('#tmpl-symbol-card').html()); // Backbone does not seem to matter }, events: { 'click': 'selectSquare', }, selectSquare: function(e) { this.trigger('play', this); // console.log("Symbol Square: "+ this.model.attributes.location + '(' +this.model.attributes.contents + ") was clicked"); // We return false to tell jQuery not to run any more event handlers. // Otherwise, it would run the 'click' event handler on BoardView // as well. return false; }, render: function() { this.$el.html(this.template(this.model.attributes)); return this; } }); export default SquareView;
module.exports = (sequelize, Sequelize) => { const TestReview = sequelize.define("testReviews", { testId: { type: Sequelize.INTEGER }, userId: { type: Sequelize.INTEGER }, status: { type: Sequelize.STRING }, comment: { type: Sequelize.ARRAY(Sequelize.TEXT) }, history: { type: Sequelize.ARRAY(Sequelize.TEXT) }, }); return TestReview; };
import React from 'react'; class Profile extends React.Component { constructor(props) { super(props); } render() { var details = this.props.details; var profile = Object.keys(details).map(function(keyName, keyIndex) { return <p key={keyIndex}><h5 className="keyName">{keyName}:</h5> <h5>{details[keyName]}</h5></p>; }) return( <div className="col-xs-6 col-md-12"> <h2>Profile</h2> {profile} </div> ) } }; export default Profile;
var XMLConstant = { TYPE_ELEMENT:1, TYPE_TEXT:3, TYPE_COMMENT:8, TYPE_DECLARATION:16 }; export default XMLConstant;
import { Grid, CircularProgress} from '@material-ui/core'; import Post from './Post'; import Styles from './PostsStyle'; import axios from 'axios'; import { useState, useEffect} from 'react'; const fetchPost = () => { return axios.get('http://localhost:5000/posts') .then(res => { //console.log(res.data) return res.data; }) .catch(err => { console.log(err); }) }; const Posts = ({setCurrentId}) => { const [posts,setPosts] = useState([]); useEffect(() => { fetchPost().then((postData) => { setPosts(postData); })}, [posts]); const styles= Styles(); return ( !posts.length? <CircularProgress />:( <Grid className={styles.mainContainer} container alignItems="stretch" spacing={4} > { posts.map((post) => ( <Grid key={post._id} item xs={12} sm={6} > <Post post={post} setCurrentId={setCurrentId} /> </Grid> ))}; </Grid> ))}; export default Posts
/** * Layout component that queries for data * with Gatsby's useStaticQuery component * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React from "react" import PropTypes from "prop-types" import { useStaticQuery, graphql } from "gatsby" import Header from "./header" import Footer from "../components/Footer" import MobileContact from "../components/MobileContact" import MessengerCustomerChat from 'react-messenger-customer-chat'; import "./layout.css" const Layout = ({ children }) => { const data = useStaticQuery(graphql` query SiteTitleQuery { site { siteMetadata { title, logo } }, file(absolutePath: {regex: "/images/logo.png/"}) { absolutePath relativePath } } `) return ( <> <Header siteTitle={data.site.siteMetadata.title} logo={data.site.siteMetadata.logo}/> <div> <main>{children}</main> {/*<MessengerCustomerChat pageId="1480527812217145" appId="296614704926289" page_id="1480527812217145" theme_color="#F24C3D" logged_in_greeting="Dzień dobry, jak możemy Ci pomóc?" logged_out_greeting="Dzień dobry, jak możemy Ci pomóc?" />*/} <MobileContact /> <Footer /> </div> </> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
'use strict'; // Module dependencies var mongoose = require('mongoose'); var extend = require('mongoose-schema-extend'); var Schema = mongoose.Schema; require('../models/user.server.model'); var UserSchema = mongoose.model('User').schema; var AdminSchema = UserSchema.extend({ responsibility: [{ type: Schema.Types.ObjectId, ref: 'University' }] }); module.exports = mongoose.model('Admin', AdminSchema);
import React from "react"; import { FaCloudDownloadAlt } from "react-icons/fa"; import profilePic from "../assets/images/IMG_1552.jpg"; const About = () => ( <section id="about"> <div className="row"> <div className="three columns"> <img className="profile-pic" src={profilePic} alt="" /> </div> <div className="nine columns main-col"> <h2>Hey There!</h2> <p> My name is William DiFulvio and I'm a Full-Stack Web Developer specializing in front end development. In addition, I have a strong background in high-level project and operations management as well as with client and customer relations. I started my Web Development journey in early 2018 when I began at Lambda School. Nine grueling months later, I am a qualified Full-Stack Web developer with specialties in React and Javascript. I have completed over 15 projects over the past nine months, starting with the simple and continuing with more and more complex applications. Take a look at some of them below! </p> <div className="row"> <div className="columns contact-details"> <h2>Contact Details</h2> <p className="address"> <span>William DiFulvio Jr.</span> <br /> <span>Orlando, FL</span> <br /> <span>(386) 717 - 1109</span> <br /> <span>w.difulvio523@gmail.com</span> </p> </div> <div className="columns download"> <p> <a href="https://resume.creddle.io/resume/e66vldf68ar" target="_blank" className="button"> <span className="dlresume-span">See Resume</span> </a> </p> </div> </div> </div> </div> </section> ); export default About;
import Vue from 'vue'; import App from './App.vue'; Vue.config.productionTip = false; // global mixin to make static files available on the inner objects // https://stackoverflow.com/a/40897670/8207 Vue.mixin({ data: function() { return { staticFiles: STATIC_FILES, // STATIC_FILES must be defined in the template above vue bundle import. }; } }); new Vue({ render: h => h(App), }).$mount('#object-lifecycle-home')
var path = require('path'); var request = require('request'); process.env.PATH += path.delimiter + path.join(__dirname, 'chromedriver'); exports.path = process.platform === 'win32' ? path.join(__dirname, 'chromedriver', 'chromedriver.exe') : path.join(__dirname, 'chromedriver', 'chromedriver'); exports.version = '2.35'; exports.start = function(args) { exports.defaultInstance = require('child_process').execFile(exports.path, args); var port = 9515; var urlBase = ''; if (args) { args.forEach(function(arg) { var matched = arg.match(/--port=([0-9]+)/i); if (matched) { port = Number(matched[1]); } matched = arg.match(/--url-base=(.+)/i); if (matched) { urlBase = matched[1]; } }); } exports.defaultInstance.port = port; exports.defaultInstance.urlBase = urlBase; return exports.defaultInstance; }; exports.stop = function () { if (exports.defaultInstance != null){ exports.defaultInstance.kill(); exports.defaultInstance = null; } }; exports.isRunning = function() { if (!exports.defaultInstance) return Promise.resolve(false) var port = exports.defaultInstance.port; var urlBase = exports.defaultInstance.urlBase; var requestOptions = { uri: 'http://127.0.0.1:' + port + urlBase + '/status', followAllRedirects: true, json: true }; return new Promise(function(resolve) { request(requestOptions, function (error, response, body) { if (error) return resolve(false); if (response.statusCode !== 200) return resolve(false); resolve(body && body.status === 0); }); }); }; exports.waitUntilRunning = function() { return new Promise(function(resolve, reject) { var attempts = 20; function checkRunning() { exports.isRunning().then(function(running) { if (!exports.defaultInstance || attempts === 0) { return reject('ChromeDriver is not started.'); } if (running) { return resolve(); } attempts--; setTimeout(checkRunning, 200); }); } checkRunning(); }); };
var bcrypt = require('bcrypt-nodejs'); bcrypt.compare('paul', '$2a$10$FlqBp1ZEmDJVZb4gkYd9ruzR7DohcRxkBPcFuq9MMtuf17swDCYSC', function(err, results) { if (err) { console.error(err); } else { console.log(results); } });
import React, { Fragment } from 'react' import milify from "millify" import {Typography , Row , Col , Statistic } from "antd" import {Link} from "react-router-dom" import {useGetCryptosQuery} from "../services/cryptoApi" import { Cryptocurrencies, News } from '../components' import Loader from './Loader' const {Title} = Typography const Homepage = () => { const {data , isFetching} = useGetCryptosQuery(10); const globalStats = data?.data?.stats if(isFetching){ return <Loader/> } return ( <Fragment> <Title level={2} className="heading"> Global Crypto Stats </Title> <Row> <Col span={12}> <Statistic title="Total Cryptocurrencies" value={globalStats.total}/> </Col> <Col span={12}> <Statistic title="Total Exchanges" value={milify(globalStats.totalExchanges)}/> </Col> <Col span={12}> <Statistic title="Total Market Cap" value={milify(globalStats.totalMarketCap)}/> </Col> <Col span={12}> <Statistic title="Total 24h Volume" value={milify(globalStats.total24hVolume)}/> </Col> <Col span={12}> <Statistic title="Total Markets" value={milify(globalStats.totalMarkets)}/> </Col> </Row> <div className="home-heading-container"> <Title level={2} className="home-title"> Top 10 Cryptocurrencies </Title> <Title level={3} className="show-more"> <Link to="/cryptocurrencies"> Show More </Link> </Title> </div> <Cryptocurrencies simplified/> <div className="home-heading-container"> <Title level={2} className="home-title"> Latest Crypto News </Title> <Title level={3} className="show-more"> <Link to="/news"> Show More </Link> </Title> </div> <News simplified/> </Fragment> ); } export default Homepage;
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* TODO: need to manage zIndex for all popup */ //var zIndex = 2 ; //var popupArr = new Array() ; /** * Main class to manage popups */ function UIPopup() { this.zIndex = 3 ; } ; /** * Inits the popup * . calls changezIndex when the users presses the popup */ UIPopup.prototype.init = function(popup, containerId) { if(typeof(popup) == "string") popup = document.getElementById(popup) ; if(containerId) popup.containerId = containerId ; popup.onmousedown = this.changezIndex ; } ; /** * Increments the current zIndex value and sets this popup's zIndex property to this value */ UIPopup.prototype.changezIndex = function() { this.style.zIndex = ++eXo.webui.UIPopup.zIndex; } ; /** * Creates and returns a div element with the following style properties * . position: relative * . display: none */ UIPopup.prototype.create = function() { var popup = document.createElement("div") ; with(popup.style) { position = "relative" ; display = "none" ; } return popup ; } ; /** * Sets the size of the popup with the given width and height parameters */ UIPopup.prototype.setSize = function(popup, w, h) { popup.style.width = w + "px" ; popup.style.height = h + "px" ; } ; /** * Shows (display: block) the popup */ UIPopup.prototype.show = function(popup) { if(typeof(popup) == "string") { popup = document.getElementById(popup) ; } var uiMaskWS = document.getElementById("UIMaskWorkspace"); if(uiMaskWS) { uiMaskWSzIndex = eXo.core.DOMUtil.getStyle(uiMaskWS, "zIndex"); if(uiMaskWSzIndex && (uiMaskWSzIndex > eXo.webui.UIPopup.zIndex)) { eXo.webui.UIPopup.zIndex = uiMaskWSzIndex; } } popup.style.zIndex = ++eXo.webui.UIPopup.zIndex ; popup.style.display = "block" ; } ; /** * Shows (display: none) the popup */ UIPopup.prototype.hide = function(popup) { if(typeof(popup) == "string") { popup = document.getElementById(popup) ; } popup.style.display = "none" ; } ; /** * Sets the position of the popup to x and y values * changes the style properties : * . position: absolute * . top and left to y and x respectively * if the popup has a container, set its position: relative too */ UIPopup.prototype.setPosition = function(popup, x, y, isRTL) { if(popup.containerId) { var container = document.getElementById(popup.containerId) ; container.style.position = "relative" ; } popup.style.position = "absolute" ; popup.style.top = y + "px" ; if(isRTL) { popup.style.right = x + "px" ; popup.style.left = "" ; } else { popup.style.left = x + "px" ; popup.style.right = "" ; } } ; /** * Aligns the popup according to the following values : * 1 : top left * 2 : top right * 3 : bottom left * 4 : bottom right * other : center */ UIPopup.prototype.setAlign = function(popup, pos, hozMargin, verMargin) { if ( typeof(popup) == 'string') popup = document.getElementById(popup) ; var stdLeft = eXo.core.Browser.getBrowserWidth() - eXo.core.Browser.findPosX(document.getElementById("UIWorkingWorkspace")); var intTop = 0 ; var intLeft = 0 ; if(!hozMargin) hozMargin = 0; if(!verMargin) verMargin = 0; switch (pos) { case 1: // Top Left intTop = verMargin; intLeft = hozMargin; break; case 2: // Top Right intTop = verMargin; intLeft = (stdLeft - popup.offsetWidth) - hozMargin; break ; case 3: // Bottom Left intTop = (eXo.core.Browser.getBrowserHeight() - popup.offsetHeight) - verMargin; intLeft = hozMargin ; break ; case 4: // Bottom Right intTop = (eXo.core.Browser.getBrowserHeight() - popup.offsetHeight) - verMargin; intLeft = (stdLeft - popup.offsetWidth) - hozMargin; break ; default: intTop = (eXo.core.Browser.getBrowserHeight() - popup.offsetHeight) / 2 ; intLeft = (uiWorkingWS.offsetWidth - popup.offsetWidth) / 2 ; break ; } this.setPosition(popup, intLeft, intTop, eXo.core.I18n.isRT()) ; } ; /** * Inits the DragDrop class with empty values */ UIPopup.prototype.initDND = function(evt) { var DragDrop = eXo.core.DragDrop ; DragDrop.initCallback = null ; DragDrop.dragCallback = null ; DragDrop.dropCallback = null ; var clickBlock = this ; var dragBlock = eXo.core.DOMUtil.findAncestorByClass(this, "UIDragObject") ; DragDrop.init(null, clickBlock, dragBlock, evt) ; } ; /** * Browses the popups on the page and closes them all * Clears the popupArr array (that contains the popups dom objects) */ //UIPopup.prototype.closeAll = function() { // var len = popupArr.length ; // for(var i = 0 ; i < len ; i++) { // popupArr[i].style.display = "none" ; // } // popupArr.clear() ; //} ; eXo.webui.UIPopup = new UIPopup() ;
module.exports = require('./state-data.json')
import React from 'react'; import PropTypes from 'prop-types'; import Avatar from '@material-ui/core/Avatar'; import Button from '@material-ui/core/Button'; import CssBaseline from '@material-ui/core/CssBaseline'; import FormControl from '@material-ui/core/FormControl'; import { ToastsContainer, ToastsStore, ToastsContainerPosition } from 'react-toasts'; import Input from '@material-ui/core/Input'; import InputLabel from '@material-ui/core/InputLabel'; import LockOutlinedIcon from '@material-ui/icons/LockOutlined'; import Paper from '@material-ui/core/Paper'; import Typography from '@material-ui/core/Typography'; import withStyles from '@material-ui/core/styles/withStyles'; import Dashboard from './Dashboard'; const styles = theme => ({ main: { width: 'auto', display: 'block', // Fix IE 11 issue. marginLeft: theme.spacing.unit * 3, marginRight: theme.spacing.unit * 3, [theme.breakpoints.up(400 + theme.spacing.unit * 3 * 2)]: { width: 400, marginLeft: 'auto', marginRight: 'auto', margin: '0 auto', paddingTop: '2%', }, }, paper: { marginTop: theme.spacing.unit * 8, display: 'flex', flexDirection: 'column', alignItems: 'center', padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 3}px ${theme.spacing.unit * 3}px`, // background: 'linear-gradient( #50c878,#5FB5A7 )', }, avatar: { margin: theme.spacing.unit, backgroundColor: theme.palette.secondary.main, }, form: { width: '100%', // Fix IE 11 issue. marginTop: theme.spacing.unit, }, submit: { marginTop: theme.spacing.unit * 3, }, }); class SignIn extends React.Component { constructor(props) { super(props); this.state = { email: '', password: '', success: false, failed: false, }; } onsignout = () => { this.setState({ success: false }); this.setState({ email: '', password: '' }); } buttonsubmit = () => { if ('admin' === this.state.email && '123' === this.state.password) { this.setState({ success: true }); } else { ToastsStore.error("UserName or Password doesn't match !"); this.setState({ failed: true }); } } onEmail = (event) => { this.setState({ email: event.target.value }); } onPassword = (event) => { this.setState({ password: event.target.value }); } render() { const { classes } = this.props; return ( <div style={{ background: 'linear-gradient( #50c878,#5FB5A7 )', height: '100vh' }}> { (this.state.success === false) ? (<main className={classes.main} > <CssBaseline /> <Paper className={classes.paper} > <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> Sign in </Typography> <form className={classes.form} onKeyPress={this.onkey}> <FormControl margin="normal" required fullWidth> <InputLabel htmlFor="name">User Name</InputLabel> <Input id="name" name="name" autoComplete="name" required="true" autoFocus onChange={this.onEmail} /> </FormControl> <FormControl margin="normal" required fullWidth> <InputLabel htmlFor="password">password</InputLabel> <Input id="password" name="password" type="password" autoComplete="current-password" onChange={this.onPassword} style={{ marginTop: '27px' }} /> </FormControl> <Button fullWidth variant="contained" color="primary" className={classes.submit} onClick={this.buttonsubmit}>Sign in</Button> { (this.state.failed === true) ? <ToastsContainer store={ToastsStore} position={ToastsContainerPosition.BOTTOM_CENTER} /> : null } </form> </Paper> </main> ) : (this.state.success === true) ? <Dashboard onsignout={this.onsignout} success={this.state.success} /> : null } </div> ); } } SignIn.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(SignIn);
// FUCAO CONSTRUTORA function Pessoa(nome) { this.nome = nome this.falar = function () { console.log(`Meu nome é ${nome}`) } } const p1 = new Pessoa('Suellen Souza') p1.falar() // factory - funçao que retorna um obj
const rp = require('request-promise-native'); const logger = require('../logger'); const INSPECTION_URL = 'https://data.cityofchicago.org/resource/4ijn-s7e5.json'; /** * Hit the SODA api to retrieve the most recent inspections. * @param {Integer} limit the number of records to retrieve * @param {Object} sodaAPIOptions any options that you would like to pass to the * SODA api. More info here: https://dev.socrata.com/consumers/getting-started.html * @returns {Promise<Array<Object>>} returns an array of inspection objects * @throws will throw an error if the API call is rejected, error handling should * be implemented in the calling context */ const getInspections = async (limit, sodaAPIOptions) => { const options = { uri: INSPECTION_URL, qs: { $limit: limit || 1000, $order: 'inspection_date DESC', ...sodaAPIOptions, }, json: true, }; return rp(options); }; /** * Parse the raw inspection objects returned from the api. Get any violations * and comments with those violations from the objects. * @param {Array<Object>} allInspections An array of inspection objects * @returns {Object} return an object with fields inspectionsArr and allViolationsArr, * where each array is an array of objects that holds inspection and violations objects */ const parseInspections = (allInspections) => allInspections.reduce((accum, inspection) => { const { violations, location, ...inspectionOb } = inspection; accum.inspectionsArr.push(inspectionOb); if (violations) { // need to get each separate violation; const violationsArr = inspection.violations.split('|'); // for each violation, there could be comments violationsArr.forEach((violation) => { const [name, comments] = violation.split('- Comments:'); // ##. <rest of name> // split on period // const [violationId, violationName] = name.split('.') try { const violationOb = { name: name.trim(), inspection_id: parseInt(inspectionOb.inspection_id, 10), }; if (comments) violationOb.comments = comments.trim(); accum.allViolationsArr.push(violationOb); } catch (e) { logger.error(e, name, comments); throw e; } }); } return accum; }, { inspectionsArr: [], allViolationsArr: [] }); module.exports = { getInspections, parseInspections, };
#!/usr/bin/env node const fs = require("fs"); const obj = require("through2").obj; const pager = require("default-pager"); const msee = require("msee"); const join = require("path").join; const boxen = require("boxen"); const chalk = require("chalk"); const updateNotifier = require("update-notifier"); const pkg = require("./package.json"); const meow = require("meow"); const cli = meow( [ "Usage", " wtfjs", "", "Options", " --lang, -l Translation language", "", "Examples", " wtfjs", " wtfjs --lang pt-br", ], { flags: { lang: { type: "string", alias: "l", default: "", }, }, } ); const boxenOpts = { borderColor: "yellow", margin: { bottom: 1, }, padding: { right: 1, left: 1, }, }; const mseeOpts = { paragraphEnd: "\n\n", }; const notifier = updateNotifier({ pkg }); process.env.PAGER = process.env.PAGER || "less"; process.env.LESS = process.env.LESS || "FRX"; const lang = (cli.flags.lang || "") .toLowerCase() .split("-") .map((l, i) => (i === 0 ? l : l.toUpperCase())) .join("-"); const translation = join( __dirname, !lang ? "./README.md" : `./README-${lang}.md` ); fs.stat(translation, function (err, stats) { if (err) { console.log("The %s translation does not exist", chalk.bold(lang)); return; } fs.createReadStream(translation) .pipe( obj(function (chunk, enc, cb) { const message = []; if (notifier.update) { message.push( `Update available: {green.bold ${notifier.update.latest}} {dim current: ${notifier.update.current}}` ); message.push(`Run {blue npm install -g ${pkg.name}} to update.`); this.push(boxen(message.join("\n"), boxenOpts)); } this.push(msee.parse(chunk.toString(), mseeOpts)); cb(); }) ) .pipe(pager()); });
import component from "./component"; import "./main.scss"; document.body.appendChild(component());
const moons = require('./moons'); module.exports = input => moons(input, 1000);
function ViewOrders() { var indexOfDir = window.location.href.indexOf("/", 7); var subString = window.location.href.substr(indexOfDir) var queryLocation = ""; if (subString.startsWith("/Home")) queryLocation = "Orders"; else queryLocation = "Home/Orders"; $.ajax({ url: queryLocation, success: function (data) { //alert("success"); window.location.href = queryLocation; } }); }
import React, { Component } from 'react' import { connect } from 'react-redux' import { pushState } from 'redux-router' import { connectSendbird } from '../../redux/actions/sendbird' import styles from './SendbirdConnect.scss' @connect( state => ({ sendbird: state.sendbird }), dispatch => ({ connect: (id, user) => dispatch(connectSendbird(id, user)), goToChat: () => dispatch(pushState(null, '/messenger')) }) ) export default class SendbirdConnect extends Component { onConnect() { if (this.state && this.state.userName) { this.props.connect(this.state.userName) this.props.goToChat() } } onChange(event) { this.setState({ userName: event.target.value }) } onKeyUp(event) { if (event.keyCode === 13) { this.onConnect() } } render() { return ( <div> <input type="text" placeholder="nickname" className={styles.loginName} disabled={this.props.sendbird.connecting} onKeyUp={this.onKeyUp.bind(this)} onChange={this.onChange.bind(this)} /> <div className={styles.enter} onClick={this.onConnect.bind(this)}>enter</div> </div> ) } }
(function () { 'use strict'; angular .module('0621fetedlm') .config(config); function config($stateProvider) { $stateProvider .state('0621fetedlm', { url: '/archiv-2018/06-21-fetedlm', templateUrl: 'archiv-2018/06-21-fetedlm/views/06-21-fetedlm.tpl.html', controller: 'C0621fetedlmCtrl', controllerAs: '0621fetedlm' }); } }());
'use strict'; let file = null; const displayUserInfo = user => { const { photoURL } = user; const photoEl = document.getElementById('currentPhoto'); if(photoURL) { photoEl.src = photoURL; } else { photoEl.src = "http://pluspng.com/img-png/user-png-icon-male-user-icon-512.png"; } } const checkUserAuth = () => { firebase.auth().onAuthStateChanged(function(user) { if (!user) { window.location.replace("../login"); } else { displayUserInfo(user); } }); }; const onFileChange = e => { file = e.target.files[0]; console.log("file: ", file) const blobUrl = window.URL.createObjectURL(file) console.log("brobUrl: ", blobUrl) document.getElementById('photoPreview').src = blobUrl; } const updatePhotoUrl = (photoURL) => { const user = firebase.auth().currentUser; user.updateProfile({ photoURL }).then(() => { alert("User profile updated!") window.location.replace("../my-account"); }) } const onUploadButtonClicked = () => { const storageRef = firebase.storage().ref().child(`images/${file.name}`); console.log(storageRef) if(file) { storageRef.put(file) .then((snapshot) => { console.log(snapshot) snapshot.ref.getDownloadURL() .then((downloadURL) => { console.log(downloadURL) updatePhotoUrl(downloadURL) }) }) .catch(() => { alert("error to upload file") }) } else { alert("no file chosen !") } } const main = () => { checkUserAuth(); const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', onFileChange); const uploadButton = document.getElementById('uploadButton'); uploadButton.addEventListener('click', onUploadButtonClicked) } window.addEventListener('DOMContentLoaded', main);
import { StaticQuery, graphql } from "gatsby"; import React from "react"; const ImageParallax = () => ( <StaticQuery query={graphql` query { wordpressAcfPages(wordpress_id: { eq: 43 }) { acf { image_histoire { alt_text source_url } } } } `} render={data => ( <div className="se-cover-images se-parallax" style={{ backgroundImage: `url(${data.wordpressAcfPages.acf.image_histoire.source_url})` }} /> )} /> ); export default ImageParallax;
import {Grid} from "@material-ui/core"; import React, {useEffect} from "react"; import {useDispatch, useSelector} from "react-redux"; import * as athleteActions from "../store/actions/athleteActions"; import moment from "moment"; const AthleteDisplay = () => { const athleteState = useSelector(state => state.athlete); const dispatch = useDispatch(); useEffect(() => { (async () => { await dispatch(athleteActions.getAthletes()); })(); }, [dispatch]); if (athleteState.loading) { return <h1>Loading...</h1>; } return ( <Grid> <Grid item xs={12}> {athleteState.loading ? ( <h1>Loading...</h1> ) : ( athleteState.athletes.map(athlete => ( <> <div key={athlete._id} style={{ backgroundColor: "lightGray", padding: "10px", marginTop: "25px", outline: ".5px solid black", }}> <img src={athlete.image} alt="<Athlete Image>" height={100} width={75} /> <p>Name: {athlete.name}</p> <p>Date of birth: {moment(athlete.dateOfBirth).format("LL")}</p> <p>Gender: {athlete.gender}</p> <p>Sports: {athlete.sports}</p> <p>About: {athlete.about}</p> <p>Interests: {athlete.interests}</p> <p>Location: {athlete.location}</p> </div> </> )) )} </Grid> </Grid> ); }; export default AthleteDisplay;
const modulo1 = require('./mod1') const modulo2 = require('./mod2') modulo1('teste modulo 1') modulo2.teste('teste modulo 2') const obj = modulo2.obj console.log(JSON.stringify(obj))
import { Typography,Box, Grid,Divider,Button } from '@material-ui/core'; import {makeStyles} from "@material-ui/core/styles"; import { GetApp } from '@material-ui/icons'; import React from 'react'; import './style.scss'; const useStyle = makeStyles((theme)=>({ resumeBox:{ minHeight:'100vh' }, downloadBox:{ [theme.breakpoints.up('md')]:{ height:"30vH", }, height:'20vH', backgroundColor:'#222', }, downloadButton:{ color:'#222', backgroundColor:'#08d665', [theme.breakpoints.up('md')]:{ margin:'70px 0' }, margin:'50px 0', height:'10vh' }, descriptionBox:{ padding:'70px 100px 100px 100px', }, ContentBox:{ marginTop:'100px', } })) export default function Resume(){ const classes=useStyle() return( <Grid container className={classes.resumeBox}> <Grid item xs={12} sm={12}> <Typography variant="h3" style={{textAlign:'center',marginTop:'100px'}}>Resume</Typography> <Divider variant='middle' style={{backgroundColor:'green'}}/> </Grid> <Grid item xs={12} sm={12} className={classes.descriptionBox}> <Box component='div' className='ContentBox'> <Typography variant="h4">Diploma in Electronic and communication</Typography> <Typography variant="p">Kongu polytechnic college,Erode</Typography> <br/> <Typography variant="p"><strong>YEAR</strong>: 2011 - 2014</Typography> </Box> <Box component='div' className='ContentBox'> <Typography variant="h4">Production Incharge</Typography> <Typography variant="p">Express PowerTech,Erode</Typography> <br/> <Typography variant="p"><strong>YEAR</strong>: 2014 - 2015</Typography> </Box> <Box component='div' className='ContentBox'> <Typography variant="h4">B.E Electronics and communication Engineering</Typography> <Typography variant="p">Hindusthan college of engineering and Technology,Coimbatore</Typography> <br/> <Typography variant="p"><strong>YEAR</strong>: 2016 - 2019</Typography> </Box> <Box component='div' className='ContentBox'> <Typography variant="h4">Cloud Imax</Typography> <Typography variant="p">Front-end developer</Typography> <br/> <Typography variant="p"><strong>YEAR</strong>: 2019 - present</Typography> </Box> </Grid> <Grid item container xs={12} sm={12} justify='center' className={classes.downloadBox}> <Box component="div" > <Button variant="contained" href="./nandha.Resume.docx.pdf" download="./nandha_resume.pdf" endIcon={<GetApp />} className={classes.downloadButton} > Download Resume </Button> </Box> </Grid> </Grid> ) }
import axios from "axios"; import { sessionService } from "redux-react-session"; export const loginUser = ( credentials, history, setFieldError, setSubmitting ) => { // Make checks and get some data return () => { axios .post( "https://amalitech-tms.herokuapp.com/auth/login", credentials, { headers: { "Content-Type": "application/json", }, } ) .then((response) => { const { data } = response; console.log(data) if (response.status === 200) { const userData = data.role_type; const token = data.token; // localStorage.setItem("token", token); sessionService .saveSession(token) .then(() => { sessionService .saveUser(userData) .then(() => { if (data.role_type === "admin") { history.push("/admin"); } else if (userData === "user") history.push("/trainee"); }) .catch((err) => console.error(err)); }) .catch((err) => console.error(err)); } //complete submission setSubmitting(false); }) .catch((err) => { // const { message } = err.message; const message = "wrong credentials" // check for specific error if (message.includes("credentials")) { setFieldError("email", message); setFieldError("password", message); } else if (message.includes("password")) { setFieldError("password", message); } }); } }; export const logoutUser = (history) => { return () => { sessionService.deleteSession(); sessionService.deleteUser(); history.push('/'); } };
"use strict"; var Cylinder = { numSides: 120, positions : { numComponents:3 }, indices:{}, program: undefined, init: function(){ var dTheta = 2.0 * Math.PI / this.numSides; var positions = [ 0, 0, 0 ]; var indices = [ ]; //verteces for bottom disk generated in following for loop for ( var i = 0; i < this.numSides; ++i){ var theta = i * dTheta; var x = Math.cos(theta), y = Math.sin(theta), z = 0; positions.push(x, y, z);} //verteces for top disk are generated in following for loop for ( var i = 0; i < this.numSides; ++i){ var theta = i * dTheta; var x = Math.cos(theta), y = Math.sin(theta), z = 3; positions.push(x, y, z);} positions.push(0, 0, 3); this.positions.count = positions.length/this.positions.numComponents; indices.push(0, 1); for(var i = this.numSides; i > 0; --i){ indices.push(i); } indices.push(this.numSides*2+1); for(var i = 0; i < this.numSides; ++i){ indices.push(i+this.numSides+1); } indices.push(this.numSides+1); indices.push(1, this.numSides+1); for(var i = 1; i < this.numSides+1; ++i) { indices.push(this.numSides+1-i); indices.push(this.numSides*2+1-i) } console.log(indices); this.program = initShaders(gl, "Cylinder-vertex-shader", "Cylinder-fragment-shader"); this.positions.buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, this.positions.buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW); this.indices.buffer = gl.createBuffer(); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indices.buffer); gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW); this.positions.attribute = gl.getAttribLocation(this.program, "vPosition"); }, draw: function(){ gl.useProgram(this.program); gl.bindBuffer(gl.ARRAY_BUFFER, this.positions.buffer); gl.vertexAttribPointer(this.positions.attribute, this.positions.numComponents, gl.FLOAT, gl.FALSE, 0, 0); gl.enableVertexAttribArray(this.positions.attribute); gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indices.buffer); /*gl.drawArrays(gl.POINTS, 0, this.positions.count);*/ //drawing the top disk var count = this.numSides+2; var offset = 0; gl.drawElements(gl.TRIANGLE_FAN, count, gl.UNSIGNED_SHORT, offset); //drawing the bottom disk offset += 2*count; count = this.numSides+2; gl.drawElements(gl.TRIANGLE_FAN, count, gl.UNSIGNED_SHORT, offset); //drawing the sides offset += 2*count; count = this.numSides*2+2; gl.drawElements(gl.TRIANGLE_STRIP, count, gl.UNSIGNED_SHORT, offset); } };
const test = require("ava"); const fs = require("fs"); const rimraf = require("rimraf"); const build = require("../index"); const OUTPUT = "test/tmp/unused/"; rimraf.sync(OUTPUT); test("remove unused items", async (t) => { return new Promise((resolve, reject) => { build({ silent: true, output: OUTPUT, components: "test/fixtures/components.json", onComplete: () => { build({ silent: true, output: OUTPUT, components: "test/fixtures/components2.json", onComplete: () => { t.true( fs.existsSync("test/tmp/unused/component1.html"), "component1 HTML exists" ); t.true( fs.existsSync("test/tmp/unused/component1.json"), "component1 JSON exists" ); t.true( fs.existsSync("test/tmp/unused/component2.html"), "component2 HTML exists" ); t.true( fs.existsSync("test/tmp/unused/component2.json"), "component2 JSON exists" ); t.false( fs.existsSync("test/tmp/unused/component3.html"), "component3 HTML doesn't exist" ); t.false( fs.existsSync("test/tmp/unused/component3.json"), "component3 JSON doesn't exist" ); t.true( fs.existsSync("test/tmp/unused/.config.json"), "component3 JSON exists" ); resolve(); }, }); }, }); }); });
function Student(fname, lname) { this.fname = fname, this.lname = lname, this.courses = [] } Student.prototype.name = function() { return this.fname + " " + this.lname; } Student.prototype.enroll = function(course) { if (this.courses.indexOf(course) === -1) { for (var i = 0; i < this.courses.length; i++) { if (this.courses[i].conflicts_with(course)) { return; } } this.courses.push(course); course.students.push(this); } } function Course(name, department, credits, block, days) { this.name = name, this.department = department, this.credits = credits, this.block = block, this.days = days, this.students = [] } Course.prototype.add_student = function(student) { student.enroll(this); } Student.prototype.course_load = function() { dept_credits = {} for (var i = 0; i < this.courses.length; i++) { if (this.courses[i].department in dept_credits) { dept_credits[this.courses[i].department] += this.courses[i].credits; // increment by this.courses[i].credits } else { dept_credits[this.courses[i].department] = this.courses[i].credits; } } return dept_credits; } Course.prototype.conflicts_with = function(course) { if (this.block == course.block) { for (var i = 0; i < this.days.length; i++) { if (course.days.indexOf(this.days[i]) !== -1) { return true; } } } return false; } var mary = new Student("mary", "smith"); var english_course = new Course("english 101", "English", 3, 2, ["Mon", "Tues"]); var english_course2 = new Course("english 201", "English", 4, 2, ["Mon", "Wed"]); var math_course = new Course("english 101", "Math", 2, 3, ["Mon", "Tues"]); mary.enroll(english_course); mary.enroll(english_course2); mary.enroll(math_course); console.log(mary.course_load());
export { default as Login } from './Login'; export { default as Movies } from './Movies'; export { default as Detail } from './Detail';
class Animal{ constructor(props){ this.legs = props.legs; this.eyes = props.eyes; this.head = props.head; this.fingles = props.fingles; } } class Cat extends Animal{ constructor(props){ super(props); this.ears = props.ears; this.name = props.name; } } let myCat = new Cat({ legs : 4, eyes : 2, head : 1, fingles : 10, ears : 2, name : 'little white' }) let [a,b,c] = [1,2]; console.log(`${a}. I have a cat who name is ${myCat.name},it has ${myCat.ears} ears and ${myCat.fingles} fingles ${b}. waiting ${c}. none`);
$(function($) { $('._js_dropdown-menu').hover(function() { $(this).find('.header-dropdown-menu').addClass('show'); }, function() { $(this).find('.header-dropdown-menu').removeClass('show'); }); }); // Выбор количества (function() { var quantity = document.querySelectorAll('._js_quantity'); Array.prototype.forEach.call(quantity, function (container) { var input = container.querySelector('._js_input'); input.addEventListener('change', fixInputValue); var subtractBut = container.querySelector('._js_minus'); var addBut = container.querySelector('._js_plus'); subtractBut.relatedInput = input; subtractBut.addEventListener('click', subtractOne); addBut.relatedInput = input; addBut.addEventListener('click', addOne); }); function fixInputValue() { var min = this.dataset.min || 1; var max = this.dataset.max || Infinity; var val = +this.value; if (isNaN(val) || val < min) { this.value = min; } else if (val > max) { this.value = max } } function subtractOne() { this.relatedInput.value -= 1; fixInputValue.call(this.relatedInput); } function addOne() { this.relatedInput.value = +this.relatedInput.value + 1; fixInputValue.call(this.relatedInput); } })();
import { userApi } from '../../api' import * as types from '../mutation-types' import co from 'co' export const addCategory = ({ dispatch, state }, newValue) => { co(function* () { var res dispatch(types.ADD_A_CATEGORY, newValue) const temp = { category: state.category.list } try { res = yield userApi.update(temp) } catch (err) { if (err) { const warn = '添加分类同步失败,目录已重置' dispatch(types.RERENDER_WARN, warn) dispatch(types.TOGGLE_WARN_MODAL) dispatch(types.DEL_A_CATEGORY, newValue) res = false } } if (res) { const notice = '添加分类完成' dispatch(types.RERENDER_NOTICE_CONTENT, notice) dispatch(types.SHOW_NOTICE) } }) } export const delCategory = ({ dispatch, state }, value) => { co(function* () { var res dispatch(types.DEL_A_CATEGORY, value) const { list, content } = state.category const temp = { category: list, articles: content } try { res = yield userApi.update(temp) } catch (err) { if (err) { const warn = '删除分类同步失败,目录已重置' dispatch(types.RERENDER_WARN, warn) dispatch(types.TOGGLE_WARN_MODAL) dispatch(types.ADD_A_CATEGORY, value) } } if (res) { const notice = '删除分类完成' dispatch(types.RERENDER_NOTICE_CONTENT, notice) dispatch(types.SHOW_NOTICE) } }) } export const renameCategory = ({ dispatch, state }, oldName, newName) => { co(function* () { var res dispatch(types.RENAME_A_CATEGORY, oldName, newName) const temp = { category: state.category.list } try { res = yield userApi.update(temp) } catch (err) { if (err) { const warn = '重命名分类同步失败,目录已重置' dispatch(types.RERENDER_WARN, warn) dispatch(types.TOGGLE_WARN_MODAL) dispatch(types.RENAME_A_CATEGORY, newName, oldName) } } if (res) { const notice = '重命名分类完成' dispatch(types.RERENDER_NOTICE_CONTENT, notice) dispatch(types.SHOW_NOTICE) } }) }
import React from "react"; import "./styles.css"; import smirnoff from "../../resources/carouselImgs/1smirnoff.png"; import cocacola from "../../resources/carouselImgs/2cocacola.png"; import Hennessy from "../../resources/carouselImgs/3Hennessy.png"; import Bacardi from "../../resources/carouselImgs/4Bacardi.png"; import JackDaniels from "../../resources/carouselImgs/5JackDaniels.png"; import JohnnieWalker from "../../resources/carouselImgs/6JohnnieWalker.png"; import Absolut from "../../resources/carouselImgs/7Absolut.png"; import ChivasRegal from "../../resources/carouselImgs/8ChivasRegal.png"; import Patrón from "../../resources/carouselImgs/9Patrón.png"; import Jägermeister from "../../resources/carouselImgs/10Jägermeister.png"; import Genshin from "../../resources/carouselImgs/11Genshin.png"; import Baileys from "../../resources/carouselImgs/2cocacola.png"; import Ballantines from "../../resources/carouselImgs/13Ballantines.png"; import GreyGoose from "../../resources/carouselImgs/14GreyGoose.png"; export const Carousel = () => { return ( <div className="CarouselDiv"> <div className="slider"> <div className="slide-track"> <div className="slide"> <img src={Hennessy} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={cocacola} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={smirnoff} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={Bacardi} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={JackDaniels} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={JohnnieWalker} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={Absolut} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={ChivasRegal} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={Patrón} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={Jägermeister} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={Genshin} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={Baileys} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={Ballantines} height="100" width="250" alt="" /> </div> <div className="slide"> <img src={GreyGoose} height="100" width="250" alt="" /> </div> </div> </div> </div> ); };
import CollegeFooter from './college-footer.vue' import DefaultFooter from './default-footer.vue' export { CollegeFooter, DefaultFooter }
import { TRACEID_SHADER_ALLOC } from '../../core/constants.js'; import { Debug } from '../../core/debug.js'; import { Preprocessor } from '../../core/preprocessor.js'; import { DebugGraphics } from './debug-graphics.js'; let id = 0; /** * A shader is a program that is responsible for rendering graphical primitives on a device's * graphics processor. The shader is generated from a shader definition. This shader definition * specifies the code for processing vertices and fragments processed by the GPU. The language of * the code is GLSL (or more specifically ESSL, the OpenGL ES Shading Language). The shader * definition also describes how the PlayCanvas engine should map vertex buffer elements onto the * attributes specified in the vertex shader code. * * @category Graphics */ class Shader { /** * Format of the uniform buffer for mesh bind group. * * @type {import('./uniform-buffer-format.js').UniformBufferFormat} * @ignore */ meshUniformBufferFormat; /** * Format of the bind group for the mesh bind group. * * @type {import('./bind-group-format.js').BindGroupFormat} * @ignore */ meshBindGroupFormat; /** * Creates a new Shader instance. * * Consider {@link createShaderFromCode} as a simpler and more powerful way to create * a shader. * * @param {import('./graphics-device.js').GraphicsDevice} graphicsDevice - The graphics device * used to manage this shader. * @param {object} definition - The shader definition from which to build the shader. * @param {string} [definition.name] - The name of the shader. * @param {Object<string, string>} [definition.attributes] - Object detailing the mapping of * vertex shader attribute names to semantics SEMANTIC_*. This enables the engine to match * vertex buffer data as inputs to the shader. When not specified, rendering without * vertex buffer is assumed. * @param {string} definition.vshader - Vertex shader source (GLSL code). * @param {string} [definition.fshader] - Fragment shader source (GLSL code). Optional when * useTransformFeedback is specified. * @param {boolean} [definition.useTransformFeedback] - Specifies that this shader outputs * post-VS data to a buffer. * @param {string} [definition.shaderLanguage] - Specifies the shader language of vertex and * fragment shaders. Defaults to {@link SHADERLANGUAGE_GLSL}. * @example * // Create a shader that renders primitives with a solid red color * * // Vertex shader * const vshader = ` * attribute vec3 aPosition; * * void main(void) { * gl_Position = vec4(aPosition, 1.0); * } * `; * * // Fragment shader * const fshader = ` * precision ${graphicsDevice.precision} float; * * void main(void) { * gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); * } * `; * * const shaderDefinition = { * attributes: { * aPosition: pc.SEMANTIC_POSITION * }, * vshader, * fshader * }; * * const shader = new pc.Shader(graphicsDevice, shaderDefinition); */ constructor(graphicsDevice, definition) { this.id = id++; this.device = graphicsDevice; this.definition = definition; this.name = definition.name || 'Untitled'; Debug.assert(definition.vshader, 'No vertex shader has been specified when creating a shader.'); Debug.assert(definition.fshader, 'No fragment shader has been specified when creating a shader.'); // pre-process shader sources definition.vshader = Preprocessor.run(definition.vshader); definition.fshader = Preprocessor.run(definition.fshader, graphicsDevice.webgl2); this.init(); this.impl = graphicsDevice.createShaderImpl(this); Debug.trace(TRACEID_SHADER_ALLOC, `Alloc: ${this.label}, stack: ${DebugGraphics.toString()}`, { instance: this }); } /** * Initialize a shader back to its default state. * * @private */ init() { this.ready = false; this.failed = false; } /** @ignore */ get label() { return `Shader Id ${this.id} ${this.name}`; } /** * Frees resources associated with this shader. */ destroy() { Debug.trace(TRACEID_SHADER_ALLOC, `DeAlloc: Id ${this.id} ${this.name}`); this.device.onDestroyShader(this); this.impl.destroy(this); } /** * Called when the WebGL context was lost. It releases all context related resources. * * @ignore */ loseContext() { this.init(); this.impl.loseContext(); } /** @ignore */ restoreContext() { this.impl.restoreContext(this.device, this); } } export { Shader };
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Modal, Button } from 'antd'; import { hideConfigurationModal } from '../../../ducks/online/ui'; import { hideJsonEditor } from '../../../ducks/classifier_editor'; import ClassClassifierConfiguration from './classClassifierConfiguration/ClassClassifierConfiguration'; import DatasetClassifierConfiguration from './datasetClassifierConfiguration/DatasetClassifierConfiguration'; import ComponentClassifierConfiguration from '../../common/componentClassifierConfiguration/ComponentClassifierConfiguration'; // For component classifier: import { fetchComponentClassifiers, deleteComponentClassifier, editComponentClassifier, newComponentClassifier } from '../../../ducks/online/classifiers/component'; class ConfigurationModal extends Component { render() { const { configuration_modal_visible, hideConfigurationModal, hideJsonEditor, children, configuration_modal_type } = this.props; const { fetchComponentClassifiers, deleteComponentClassifier, editComponentClassifier, newComponentClassifier } = this.props; const title_options = { class_classifiers: 'Set automatic classifiers for class of run selection', dataset_classifiers: 'Set automatic classifiers for datasets considered significant', component_classifiers: "Set automatic classifiers for each component's status" }; return ( <div> <Modal title={title_options[configuration_modal_type]} visible={configuration_modal_visible} onOk={hideConfigurationModal} onCancel={ hideConfigurationModal // confirmLoading={confirmLoading} } footer={[ <Button key="submit" onClick={hideConfigurationModal}> Close </Button> ]} width="90vw" maskClosable={false} destroyOnClose={true} afterClose={hideJsonEditor} > {configuration_modal_type === 'class_classifiers' && ( <ClassClassifierConfiguration /> )} {configuration_modal_type === 'dataset_classifiers' && ( <DatasetClassifierConfiguration /> )} {configuration_modal_type === 'component_classifiers' && ( <ComponentClassifierConfiguration online_or_offline="online" fetchComponentClassifiers={ fetchComponentClassifiers } deleteComponentClassifier={ deleteComponentClassifier } editComponentClassifier={editComponentClassifier} newComponentClassifier={newComponentClassifier} /> )} </Modal> </div> ); } } const mapStateToProps = state => { return { configuration_modal_visible: state.online.ui.configuration_modal_visible, configuration_modal_type: state.online.ui.configuration_modal_type }; }; export default connect( mapStateToProps, { hideConfigurationModal, hideJsonEditor, fetchComponentClassifiers, deleteComponentClassifier, editComponentClassifier, newComponentClassifier } )(ConfigurationModal);
//var Module = { TOTAL_MEMORY: 256*1024*1024 }; var Ar, ArLng, ArPos, ArMax; var key; var timeStep = 1/60; var isBuffer = false; var world = null; var test; // forces //var tmpForce = [];//null; // kinematic //var tmpMatrix = []; var tmpPos, tmpZero; var tmpMat, tmpQuat; self.onmessage = function ( e ) { var data = e.data; var m = data.m; var o = data.o; // ------- buffer data if( data.Ar ) Ar = data.Ar; if( data.key ) key = data.key; switch( m ){ case 'init': init( data ); break; case 'step': step(); break; case 'start': start(); break; case 'reset': reset(); break; case 'set': world.set( o ); break; case 'add': world.add( o ); break; case 'joint': world.joint( o ); break; //case 'vehicle': world.addVehicle( o ); break; //case 'motion': world.setMotionVector( o ); break; //case 'terrain': world.updateTerrain( o ); break; //case 'control': world.takeControl( o ); break; case 'force': world.tmpForce.push( o ); break; case 'matrix': world.tmpMatrix.push( o ); break; } } function step(){ if( !world ) return; world.updateMatrix(); world.updateForce(); world.step( world.stepSize ); //world.stepVehicle(); world.stepRigidBody( Ar, ArPos[0] ); if( isBuffer ) self.postMessage({ m:'step', Ar:Ar },[ Ar.buffer ]); else self.postMessage( { m:'step', Ar:Ar } ); } function init ( o ) { isBuffer = o.isBuffer || false; ArLng = o.settings[0]; ArPos = o.settings[1]; ArMax = o.settings[2]; importScripts( o.blob ); start(); } function start(){ world = new OIMO.World(); world.set(); self.postMessage( { m:'initEngine' } ); } function reset ( o ) { // create self tranfere array if no buffer if( !isBuffer ) Ar = new Float32Array( ArMax ); world.reset(); self.postMessage({ m:'start' }); }
import React, {Component} from 'react'; import { View, Image, Text, TouchableWithoutFeedback, ScrollView, } from 'react-native'; import httpRequest from '@/src/utils/request'; import globals from '@/src/styles/globals'; import indexStyleSheet from './setting_styles'; const _styleSheet = indexStyleSheet; class Setting extends Component { static navigationOptions = { title: '设置', }; state = { list: [], }; componentDidMount() { httpRequest('/api/v1/contents/1/176').then(r => { this.setState({ list: r.value, }); }); } render() { const {list} = this.state; return ( //里面只能包含值或表达式,不能有逻辑语句,但可以调用包含逻辑语句的函数表达式 <ScrollView automaticallyAdjustContentInsets={false} onScroll={() => { console.log('onScroll!'); }} scrollEventThrottle={200} style={globals.scrollViewContainer}> <View style={_styleSheet.setting}> <View style={_styleSheet['setting-link']}> {list.map(item => ( <TouchableWithoutFeedback key={item.id} onPress={() => this.props.navigation.navigate('ArticleDetail', { url: `/api/v1/contents/${item.siteId}/${item.channelId}/${ item.id }`, title: item.title, }) } style={_styleSheet.index__Navigator}> <View style={_styleSheet['setting-link__item']}> <View style={_styleSheet['setting-link__title']}> <Text style={_styleSheet['setting-link__title-text']}> {item.title} </Text> </View> <View style={_styleSheet['setting-link__arrow']}> <Image style={_styleSheet['setting-link__arrow--active']} source={require('@/src/assets/images/other/arrow_right.png')} /> </View> </View> </TouchableWithoutFeedback> ))} {/* <TouchableWithoutFeedback onPress={() => this.props.navigation.navigate('Webview', { sourceUri: 'https://www.codekid.top/#/pages/webview/about', title: '关于我们', }) } style={_styleSheet.index__Navigator}> <View style={_styleSheet['setting-link__item']}> <View style={_styleSheet['setting-link__title']}> <Text style={_styleSheet['setting-link__title-text']}> 关于我们 </Text> </View> <View style={_styleSheet['setting-link__extra']}> <Text style={_styleSheet['setting-link__extra-text']}> 1.0.0 </Text> </View> <View style={_styleSheet['setting-link__arrow']}> <Image style={_styleSheet['setting-link__arrow--active']} source={require('@/src/assets/images/other/arrow_right.png')} /> </View> </View> </TouchableWithoutFeedback> <TouchableWithoutFeedback onPress={() => this.props.navigation.navigate('Webview', { sourceUri: 'https://www.codekid.top/#/pages/webview/agreement_detail', title: '使用协议', }) } style={_styleSheet.index__Navigator}> <View style={_styleSheet['setting-link__item']}> <View style={_styleSheet['setting-link__title']}> <Text style={_styleSheet['setting-link__title-text']}> 使用协议 </Text> </View> <View style={_styleSheet['setting-link__arrow']}> <Image style={_styleSheet['setting-link__arrow--active']} source={require('@/src/assets/images/other/arrow_right.png')} /> </View> </View> </TouchableWithoutFeedback> <TouchableWithoutFeedback onPress={() => this.props.navigation.navigate('Webview', { sourceUri: 'https://www.codekid.top/#/pages/webview/privacy_detail', title: '隐私政策', }) } style={_styleSheet.index__Navigator}> <View style={_styleSheet['setting-link__item']}> <View style={_styleSheet['setting-link__title']}> <Text style={_styleSheet['setting-link__title-text']}> 隐私政策 </Text> </View> <View style={_styleSheet['setting-link__arrow']}> <Image style={_styleSheet['setting-link__arrow--active']} source={require('@/src/assets/images/other/arrow_right.png')} /> </View> </View> </TouchableWithoutFeedback> */} </View> </View> </ScrollView> ); } } export default Setting;
const chalk = require('chalk'); module.exports = function(){ console.log(chalk.yellow( ` 1) In Jasmine, test suites are declared by using the "describe" function 2) In Jasmine, test specs are declared using the "it" function inside test suites 3) When in doubt, look at the documentation at jasmine.github.io - it's pretty good 4) You generally can (and should) have multiple specs within a suite 5) You generally can (and should) have multiple expects within a spec 6) You should generally start a spec with an expect that expects a correct behavior from correct input before writing expects with incorrect input 7) Specs (it) should describe a specific rule 8) When writing a test to fail, make sure it fails in only one specific way - that way you're testing the code for that specific behavior ` )); process.exit(); };
// original authors below, modified to use ES6 exports and support mocks // http://paulirish.com/2011/requestanimationframe-for-smart-animating/ // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating // requestAnimationFrame polyfill by Erik Möller. fixes from Paul Irish and Tino Zijdel // MIT license var raf = { requestAnimationFrame: window.requestAnimationFrame && window.requestAnimationFrame.bind(window) }; var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !raf.requestAnimationFrame; ++x) { raf.requestAnimationFrame = raf[vendors[x]+'RequestAnimationFrame'] && raf[vendors[x]+'RequestAnimationFrame'].bind(window); raf.cancelAnimationFrame = raf[vendors[x]+'CancelAnimationFrame'] && raf[vendors[x]+'CancelAnimationFrame'].bind(window) || raf[vendors[x]+'CancelRequestAnimationFrame'] && raf[vendors[x]+'CancelRequestAnimationFrame'].bind(window); } if (!raf.requestAnimationFrame) raf.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!raf.cancelAnimationFrame) raf.cancelAnimationFrame = function(id) { clearTimeout(id); }; raf.real_requestAnimationFrame = raf.requestAnimationFrame; raf.callbacks = []; raf.mock_requestAnimationFrame = function(callback) { this.callbacks.push(callback); } raf.mock = function(mock) { this.requestAnimationFrame = mock ? this.mock_requestAnimationFrame : this.real_requestAnimationFrame; }; raf.step = function() { var toRun = this.callbacks; this.callbacks = []; toRun.forEach(function(cb) { cb(performance.now()); }); } // XXX if (!window.performance) window.performance = { now: function() { return Date.now(); } }; export default raf;
const courseIndex = {"CNA":"metric1", "HCA-CNA Bridging":"metric2", "Basic Life Support (BLS)":"metric3", "Adult CPR/FA":"metric4"} const Locations = { 'Des Moines': { address: '22659 Pacific Highway South Suite 301 Des Moines WA 98198', tel: "206 271 1946", email: 'desmoines@excelcna.com', website: 'www.excelcna.com' } } module.exports = { Courses, courseIndex, Locations }
const knx = require('knx') const dptlib = require('knx-dpt') module.exports = function (RED) { function knxEasyConfigNode(n) { RED.nodes.createNode(this, n) var node = this node.host = n.host node.port = n.port var knxErrorTimeout node.inputUsers = {} node.outputUsers = {} node.register = function (userType, knxNode) { userType == "in" ? node.inputUsers[knxNode.id] = knxNode : node.outputUsers[knxNode.id] = knxNode if (Object.keys(node.inputUsers).length + Object.keys(node.outputUsers).length === 1) { node.connect(); } } node.deregister = function (userType, knxNode) { userType == "in" ? delete node.inputUsers[knxNode.id] : delete node.outputUsers[knxNode.id] if (Object.keys(node.inputUsers).length + Object.keys(node.outputUsers).length === 0) { node.knxConnection = null } } node.readInitialValues = function () { var delay = 50 for (var id in node.inputUsers) { if (node.inputUsers.hasOwnProperty(id)) { let inputNode = node.inputUsers[id] if (inputNode.initialread) { setTimeout(inputNode._events.input, delay) delay = delay + 50 } } } } node.setStatusHelper = function (fill, text) { for (var id in node.inputUsers) { if (node.inputUsers.hasOwnProperty(id)) { node.inputUsers[id].status({ fill: fill, shape: "dot", text: text }) } } for (var id in node.outputUsers) { if (node.outputUsers.hasOwnProperty(id)) { node.outputUsers[id].status({ fill: fill, shape: "dot", text: text }) } } } node.setStatus = function (status) { switch (status) { case "connected": node.setStatusHelper("green", "node-red:common.status.connected") break case "knxError": node.setStatusHelper("yellow", "connected, but error on knx-bus") break case "disconnected": node.setStatusHelper("red", "node-red:common.status.disconnected") break default: } } node.connect = function () { node.setStatus("disconnected") node.knxConnection = new knx.Connection({ ipAddr: node.host, ipPort: node.port, handlers: { connected: function () { if (knxErrorTimeout == undefined) { node.setStatus("connected") node.readInitialValues() } }, error: function (connstatus) { node.error(connstatus) if (connstatus == "E_KNX_CONNECTION") { node.setStatus("knxError") } else { node.setStatus("disconnected") } } } }) node.knxConnection.on("event", function (evt, src, dest, value) { if (evt == "GroupValue_Write" || evt == "GroupValue_Response" || evt == "GroupValue_Read") { for (var id in node.inputUsers) { if (node.inputUsers.hasOwnProperty(id)) { var input = node.inputUsers[id] if (input.topic == dest) { if (evt == "GroupValue_Read") { // Notify only in case option 'Notify read requests' is enabled if (input.notifyreadrequest) { // In case of GroupValue_Read event no payload / value is available value = null var msg = buildInputMessage(src, dest, evt, value, input.dpt) input.send(msg) } } else { var msg = buildInputMessage(src, dest, evt, value, input.dpt) input.send(msg) } } } } } }) } function buildInputMessage(src, dest, evt, value, inputDpt) { // Resolve DPT and convert value if available var dpt = dptlib.resolve(inputDpt) var jsValue = null if (dpt && value) { var jsValue = dptlib.fromBuffer(value, dpt) } // Build final input message object var msg = { topic: dest , payload: jsValue , knx: { event: evt , dpt: inputDpt , dptDetails: dpt , source: src , destination: dest , rawValue: value } } return msg } node.on("close", function () { node.setStatus("disconnected") node.knxConnection.Disconnect() node.knxConnection = null }) } RED.nodes.registerType("knxEasy-config", knxEasyConfigNode); }
document.querySelector(".search-handle").addEventListener('click',function(){ let handle = document.querySelector(".getHandle").value; document.querySelector(".getHandle").value = ''; document.querySelector(".getHandle").placeholder = 'Search'; // console.log(handle); requiem(handle); }); requiem("tourist"); function requiem(handle){ let url = `https://codeforces.com/api/user.info?handles=${handle}`; // let statsURL = `https://codeforces.com/api/user.status?handle=Fefer_Ivan&from=1&count=10`; let statsURL = `https://codeforces.com/api/user.status?handle=${handle}`; fetch(url) .then((response) => { return response.json(); }).then((data) => { // console.log(data); // console.log(data.result[0].rating); setUser(data); }); fetch(statsURL) .then((response) => { return response.json(); }).then((data) => { changeDetails(data); }); } function setUser(data){ // USER INFO API let handle = data.result[0].handle; let shandle = handle.slice(1); document.querySelector(".handle").innerHTML = `<span>${handle[0]}</span>${shandle}`; document.querySelector(".currentRating").textContent = data.result[0].rating; document.querySelector(".currentRank").textContent = data.result[0].rank; document.querySelector(".numberOfFriends").textContent = `Friend of ${data.result[0].friendOfCount} Users 🐾`; document.querySelector("img").src = data.result[0].titlePhoto; // console.log(data.result[0].titlePhoto); document.querySelector(".max-rating").textContent = data.result[0].maxRating; document.querySelector(".max-rank").textContent = data.result[0].maxRank; let maxRank = data.result[0].maxRank console.log(maxRank); console.log(data.result[0].rank); sus(maxRank); imposter(data.result[0].rank); } function changeDetails(data){ // https://codeforces.com/api/user.status?handle=Fefer_Ivan&from=1&count=10 let totalSubmissions = data.result.length; let submissions = data.result; const acceptedSubmissions = submissions.filter(function(submission){ if(submission.verdict === "OK"){ return true; } }).length; // console.log(acceptedSubmissions); document.querySelector(".ac-count").textContent = acceptedSubmissions; document.querySelector(".accuracy").textContent = `${(acceptedSubmissions/totalSubmissions*100).toFixed(2)} %`; const easyProblems = submissions.filter(submission => submission.verdict === "OK") .filter(submission => submission.problem.rating <= 1300).length; console.log(easyProblems); const mediumProblems = submissions.filter(submission => submission.verdict === "OK") .filter(submission => submission.problem.rating <= 2000).length; console.log(mediumProblems); const hardProblems = submissions.filter(submission => submission.verdict === "OK") .filter(submission => submission.problem.rating <= 3500).length; console.log(hardProblems); document.querySelector(".easy-problems").textContent = easyProblems; document.querySelector(".medium-problems").textContent = mediumProblems-easyProblems; document.querySelector(".hard-problems").textContent = hardProblems-mediumProblems; document.querySelector(".unrated-problems").textContent = acceptedSubmissions-(hardProblems); // const retailCompanies = companies.filter(function(company){ // if(company.category==='auto'){ // return true; // } // }); } function sus(maxRank){ if(maxRank === "newbie"){ document.querySelector(".max-rating-header").style.backgroundColor = "grey"; document.querySelector(".max-rank-header").style.backgroundColor = "grey"; document.querySelector(".max-rating-header").style.color = "white"; document.querySelector(".max-rank-header").style.color = "white"; } else if(maxRank === "pupil"){ document.querySelector(".max-rating-header").style.backgroundColor = "green"; document.querySelector(".max-rank-header").style.backgroundColor = "green"; document.querySelector(".max-rating-header").style.color = "white"; document.querySelector(".max-rank-header").style.color = "white"; } else if(maxRank === "specialist"){ document.querySelector(".max-rating-header").style.backgroundColor = `#03a89e`; document.querySelector(".max-rank-header").style.backgroundColor = `#03a89e`; } else if(maxRank === "expert"){ document.querySelector(".max-rating-header").style.backgroundColor = "blue"; document.querySelector(".max-rank-header").style.backgroundColor = "blue"; document.querySelector(".max-rating-header").style.color = "white"; document.querySelector(".max-rank-header").style.color = "white"; } else if(maxRank === "candidate master"){ document.querySelector(".max-rating-header").style.backgroundColor = "blueviolet"; document.querySelector(".max-rank-header").style.backgroundColor = "blueviolet"; document.querySelector(".max-rating-header").style.color = "white"; document.querySelector(".max-rank-header").style.color = "white"; } else if(maxRank === "master" || maxRank === "international master"){ document.querySelector(".max-rating-header").style.backgroundColor = "orange"; document.querySelector(".max-rank-header").style.backgroundColor = "orange"; } else if(maxRank === "grandmaster" || maxRank === "international grandmaster"){ document.querySelector(".max-rating-header").style.backgroundColor = "red"; document.querySelector(".max-rank-header").style.backgroundColor = "red"; document.querySelector(".max-rating-header").style.color = "white"; document.querySelector(".max-rank-header").style.color = "white"; } else if(maxRank === "legendary grandmaster"){ document.querySelector(".max-rating-header").style.backgroundColor = "red"; document.querySelector(".max-rank-header").style.backgroundColor = "red"; } } function imposter(currentRank){ if(currentRank === "newbie"){ document.querySelector(".handle").style.color = "grey"; document.querySelector(".currentRating").style.color = "grey"; document.querySelector(".currentRank").style.color = "grey"; } else if(currentRank === "pupil"){ document.querySelector(".handle").style.color = "green"; document.querySelector(".currentRating").style.color = "green"; document.querySelector(".currentRank").style.color = "green"; } else if(currentRank === "specialist"){ document.querySelector(".handle").style.color = `#03a89e`; document.querySelector(".currentRating").style.color = `#03a89e`; document.querySelector(".currentRank").style.color = `#03a89e`; } else if(currentRank === "expert"){ document.querySelector(".handle").style.color = "blue"; document.querySelector(".currentRating").style.color = "blue"; document.querySelector(".currentRank").style.color = "blue"; } else if(currentRank === "candidate master"){ document.querySelector(".handle").style.color = "blueviolet"; document.querySelector(".currentRating").style.color = "blueviolet"; document.querySelector(".currentRank").style.color = "blueviolet"; } else if(currentRank === "master" || currentRank === "international master"){ document.querySelector(".handle").style.color = "orange"; document.querySelector(".currentRating").style.color = "orange"; document.querySelector(".currentRank").style.color = "orange"; } else if(currentRank === "grandmaster" || currentRank === "international grandmaster"){ document.querySelector(".handle").style.color = "red"; document.querySelector(".currentRating").style.color = "red"; document.querySelector(".currentRank").style.color = "red"; } else if (currentRank === "legendary grandmaster"){ document.querySelector(".handle").style.color = "red"; document.querySelector("span").style.color = "black"; document.querySelector(".currentRating").style.color = "red"; document.querySelector(".currentRank").style.color = "red"; } } // #03a89e -> cyan
'use strict' const yo = require('yo-yo') const render = require('./render') const dom = render(0, 40) document.body.appendChild(dom) const slider = document.querySelector('#slider') const update = () => { yo.update(dom, render(Math.PI * 2 * slider.value, 40)) } update() slider.addEventListener('change', update) slider.addEventListener('mousedown', () => { slider.addEventListener('mousemove', update) }) slider.addEventListener('mouseup', () => { slider.removeEventListener('mousemove', update) })
import constants from '../constants.js' export { handleInvalidDateInput } const handleInvalidDateInput = (dateInputField, notificationElement) => { const userDate = dateInputField.value const userDateObj = new Date(userDate) const currentDateTime = new Date() if(userDateObj > currentDateTime) { dateInputField.classList.add('invalid-input') notificationElement.textContent = constants.MELDUNG_DATUM_IN_ZUKUNFT } }
const path = require('path'); const fs = require('fs'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); const ManifestPlugin = require('webpack-manifest-plugin'); const getPublicUrlOrPath = require('react-dev-utils/getPublicUrlOrPath'); const appDirectory = fs.realpathSync(process.cwd()); const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath); const publicUrlOrPath = getPublicUrlOrPath(process.env.NODE_ENV === 'development', require(resolveApp('package.json')).homepage, process.env.PUBLIC_URL); module.exports = { entry: path.resolve(__dirname, './src') + '/index.tsx', mode: 'development', devtool: 'source-map', resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'], alias: { types: path.resolve(__dirname, 'src/types'), screens: path.resolve(__dirname, 'src/screens'), common: path.resolve(__dirname, 'src/common'), containers: path.resolve(__dirname, 'src/containers'), views: path.resolve(__dirname, 'src/views'), rdx: path.resolve(__dirname, 'src/rdx'), api: path.resolve(__dirname, 'src/api'), components: path.resolve(__dirname, 'src/components'), '@': path.resolve(__dirname, 'src'), }, }, output: { path: path.join(__dirname, '/dist'), filename: './index.js', publicPath: '/', }, module: { rules: [ { test: /\.(js|ts)x?$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { presets: ['@babel/env'], }, }, ], }, { test: /\.css$/, use: ['css-loader'], }, { test: /\.s[ac]ss$/i, use: [ // Creates `style` nodes from JS strings 'style-loader', // Translates CSS into CommonJS 'css-loader', // Compiles Sass to CSS { loader: 'sass-loader', options: { // Prefer `dart-sass` implementation: require('node-sass'), }, }, ], }, ], }, devServer: { historyApiFallback: true, hot: true, contentBase: [path.join(__dirname, '/public'), path.join(__dirname, '/dist'), path.join(__dirname, '/public/avatars')], port: 5000, host: process.env.HOST || '0.0.0.0', transportMode: 'ws', // sockHost: '0.0.0.0', // sockPath: '/sockjs-node', // sockPort: '5000', watchContentBase: true, injectClient: false, // contentBasePublicPath: publicUrlOrPath, // publicPath: publicUrlOrPath.slice(0, -1), disableHostCheck: true, public: '0.0.0.0:5000', }, plugins: [ new CleanWebpackPlugin(), new HtmlWebpackPlugin({ template: './public/index.html', favicon: './public/favicon.ico', }), new ManifestPlugin({ writeToFileEmit: true, seed: { // eslint-disable-next-line @typescript-eslint/camelcase short_name: 'CoreUI-React Admin panel for Radioavionica', name: 'CoreUI-React sample', icons: [ { src: './public/favicon.ico', sizes: '100x100', type: 'image/ico', }, ], // eslint-disable-next-line @typescript-eslint/camelcase start_url: '.', display: 'standalone', // eslint-disable-next-line @typescript-eslint/camelcase theme_color: '#000000', // eslint-disable-next-line @typescript-eslint/camelcase background_color: '#ffffff', }, }), ], };
import React, {useState} from 'react'; const TextInput = function (props) { const [value, setValue] = useState(props.value); const handleChange = (e) => setValue(e.target.value); const handleSubmit = function (e) { e.preventDefault(); if (value) { props.onSubmit(value); setValue(''); } }; return ( <form onSubmit={handleSubmit}> <input type="text" value={value} onChange={handleChange} /> </form> ); }; TextInput.defaultProps = {value: ''}; export default TextInput;
import React, { useEffect, useState } from 'react' import CourseNavbar from '../Navbars/CourseNavbar' import { clearCurrentCourse, setCurrentCourse } from '../../store/courses/reducer' import { clearCurrentLesson, setCurrentLesson } from '../../store/lesson/reducer' import { useDispatch, useSelector } from 'react-redux' import { Button, Col, Container, Modal, Row } from 'react-bootstrap' import { updateLesson } from '../../store/lesson/thunks' import TextStepEditor from '../Steps/TextStep/TextStepEditor' import { getCurrentLesson } from '../../store/lesson/selectors' import { setSteps } from '../../store/lessonSteps/reducer' import { getSteps } from '../../store/lessonSteps/selectors' import VideoStepEditor from '../Steps/VideoStep/VideoStepEditor' import { useTranslation } from 'next-i18next' import Loader from '../Loader/Loader' import { createTextAnswerLesson, createTextLesson, createVideoLesson } from '../../store/lessonSteps/thunks' import OpenAnswerStepEditor from '../Steps/OpenAnswerStep/OpenAnswerStepEditor' import TestStepEditor from '../Steps/TestTaskStep/TestStepEditor' import { createTestStep } from '../../store/lessonSteps/test.thunk' const stepTypes = { Text: TextStepEditor, Video: VideoStepEditor, TextWithAnswer: OpenAnswerStepEditor, Test: TestStepEditor, } const stepIcons = { Text: 'fa-align-left', Video: 'fa-film', TextWithAnswer: 'fa-question', Test: 'fa-list-alt', } const LessonEditor = ({ lesson, course }) => { const { t } = useTranslation('editLesson') const [show, setShow] = useState(false) const dispatch = useDispatch() const [lessonTitle, setLessonTitle] = useState('') const [stepNumber, setStepNumber] = useState(0) const currentLesson = useSelector(getCurrentLesson) const steps = useSelector(getSteps) useEffect(() => { dispatch(setCurrentCourse(course)) dispatch(setCurrentLesson(lesson)) dispatch(setSteps(lesson.steps)) setLessonTitle(lesson.title) return () => { dispatch(clearCurrentCourse()) dispatch(clearCurrentLesson()) } }, []) const onTitleSave = () => { dispatch(updateLesson(lesson._id, { title: lessonTitle })) } if (!currentLesson) { return <Loader /> } const onChangeStep = (stepNum) => { setStepNumber(stepNum) } const onCreateTextLesson = async () => { setShow(false) dispatch(createTextLesson(currentLesson._id)) } const onCreateVideoLesson = async () => { setShow(false) dispatch(createVideoLesson(currentLesson._id)) } const onCreateTextAnswerLesson = async () => { setShow(false) dispatch(createTextAnswerLesson(currentLesson._id)) } const onCreateTestLesson = async () => { setShow(false) dispatch(createTestStep(currentLesson._id)) } const stepIconBlock = steps.map((step, index) => { return ( <a className="mr-1" style={{ textDecoration: 'none' }} key={step.stepId}> <button onClick={() => onChangeStep(index)} className="lesson-btn d-flex" style={{ backgroundColor: stepNumber === index ? '#63c76a' : '#212529' }}> <i className={`fas ${stepIcons[step.stepModel]}`}/> </button> </a> ) }) const StepBlock = stepTypes[steps[stepNumber].stepModel] return ( <div> <div className="container my-5"> <div className="row"> <div className="col-sm-3 col-md-2"> <CourseNavbar/> </div> <div className="col-sm-9 col-md-10"> <h1 className="editor-title mb-5">{t('title')}</h1> <h3 className="editor-lesson-title mb-3">{t('lessonTitle')}</h3> <input className={'editor-input d-block my-auto'} value={lessonTitle} onChange={(event) => setLessonTitle(event.target.value)} type="text" placeholder="Lesson title" name="title" id="title"/> <Button className="mt-3" onClick={onTitleSave}>{t('saveTitle')}</Button> <div className="my-5"> <h3 className="editor-lesson-title mb-3">{t('plan')}</h3> <div className="d-flex"> {stepIconBlock} <a className="mr-1" style={{ textDecoration: 'none' }}> <button className="lesson-btn d-flex" onClick={() => setShow(true)}> <i className="fas fa-plus"/> </button> </a> </div> </div> <h3 className="editor-lesson-title mt-5 mb-3">{t('step')} {stepNumber + 1} | {t('taskDescription')}</h3> <StepBlock stepId={steps[stepNumber].stepId}/> </div> <Modal show={show} onHide={() => setShow(false)} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Header closeButton> <Modal.Title id="example-custom-modal-styling-title"> {t('modalType')} </Modal.Title> </Modal.Header> <Modal.Body> <Container> <Row> <Col xs={12} md={6}> <div className="modal-task-type" onClick={onCreateTextLesson}> <i className="fas fa-align-left modal-task-ill"/> <div className="pl-3"> <h3 className="modal-task-title">{t('text')}</h3> <span className="modal-task-subtitle">{t('textDesc')}</span> </div> </div> </Col> <Col xs={12} md={6}> <div className="modal-task-type" onClick={onCreateVideoLesson}> <i className="fas fa-film modal-task-ill"/> <div className="pl-3"> <h3 className="modal-task-title">{t('video')}</h3> <span className="modal-task-subtitle">{t('videoDesc')}</span> </div> </div> </Col> </Row> <Row> <Col xs={12} md={6}> <div className="modal-task-type" onClick={onCreateTextAnswerLesson}> <i className="fas fa-question modal-task-ill"/> <div className="pl-3"> <h3 className="modal-task-title">{t('answer')}</h3> <span className="modal-task-subtitle">{t('answerDesc')}</span> </div> </div> </Col> <Col xs={12} md={6}> <div className="modal-task-type" onClick={onCreateTestLesson}> <i className="fas fa-list-alt modal-task-ill"/> <div className="pl-3"> <h3 className="modal-task-title">{'Create test'}</h3> <span className="modal-task-subtitle">{'Create and edit test tasks'}</span> </div> </div> </Col> </Row> </Container> </Modal.Body> </Modal> </div> </div> </div> ) } export default LessonEditor
import React from 'react' import { Card, CardText, CardBody, CardTitle, CardSubtitle } from 'reactstrap' export default function WeatherCard({ content }) { let days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] const day = new Date(content.applicable_date) const dayOfWeek = days[day.getDay()] return ( <Card className="m-2"> <CardBody> <CardTitle tag="h5">{dayOfWeek}</CardTitle> <CardSubtitle tag="h6" className="mb-2 text-muted"> {content.weather_state_name} </CardSubtitle> <img alt="weather-icon" src={`https://www.metaweather.com/static/img/weather/${content.weather_state_abbr}.svg`} ></img> <CardText>Max Temp: {Math.round(content.max_temp)}°</CardText> <CardText>Min Temp: {Math.round(content.min_temp)}°</CardText> <CardText> Wind: {content.wind_direction_compass}{' '} {Math.round(content.wind_speed)} mph </CardText> </CardBody> </Card> ) }
module.exports = function(app, mongoose, db) { var userModel1 = require("./models/user.model.js") (mongoose, db); require("./services/user.service.server.js") (app, userModel1); var petModel = require("./models/pet.model.js") (mongoose, db); require("./services/pet.service.server.js") (app, petModel); var favoriteModel = require("./models/favorite.model.js") (mongoose, db); require("./services/favorite.service.server.js") (app, favoriteModel); };
/** * Created by supervlad on 23.04.16. */ 'use strict'; const webpack = require('webpack'), path = require('path'), precss = require('precss'), autoprefixer = require('autoprefixer'); module.exports = { entry: [ './index.jsx' ], output: { path: path.join(__dirname, '/build'), filename: 'index.js' }, plugins: [ new webpack.NoErrorsPlugin() ], devtool: 'source-map', resolve: { modulesDirectories: ['node_modules'], extensions: ['', '.js', '.jsx'] }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel'] }, { test: /\.scss$/, loader: 'style!css!postcss!sass' }, { test: /\.css$/, loader: 'style!css' }, { test: /\.(jpg|png|woff|woff2|ttf|eot|svg)$/, loader: 'file-loader?name=[path][name].[ext]' } ] }, postcss: function () { return [precss, autoprefixer]; } };
import React, { useState, useEffect, useCallback } from 'react'; import Aux from '../../hoc/Auxiliary/Auxiliary'; import Burger from '../../components/Burger/Burger'; import BuildControls from '../../components/Burger/BuildControls/BuildControls' import Modal from '../../components/UI/Modal/Modal'; import OrderSummary from '../../components/Burger/OrderSummary/OrderSummary' import Spinner from '../../components/UI/Spinner/Spinner'; import withErrorHandler from '../../hoc/withErrorHandler/withErrorHandler'; import { useDispatch, useSelector } from 'react-redux'; import * as actions from '../../store/actions/index'; import axios from '../../axios-orders'; export const burgerBuilder = props => { const [purchaseClicked, setPurchaseClicked] = useState(false); const dispatch = useDispatch(); const onIngredientAdded = (ingredientName) => dispatch(actions.addIngredient(ingredientName)); const onIngredientRemoved = (ingredientName) => dispatch(actions.removeIngredient(ingredientName)); const onGetBurgerFromServer = useCallback(() => dispatch(actions.getBurgerFromServer()), [dispatch]); const onPurchaseInit = () => dispatch(actions.purchaseInit()); const onSetAuthRedirectPath = (path) => dispatch(actions.setAuthRedirectPath(path)); const ings = useSelector(state => state.burgerBuilderReducer.ingredients); const price = useSelector(state => state.burgerBuilderReducer.totalPrice); const error = useSelector(state => state.burgerBuilderReducer.error); const isAuth = useSelector(state => state.authReducer.idToken !== null); useEffect(() => { onGetBurgerFromServer(); }, [onGetBurgerFromServer]); const updatePutchaseableState = (updateIngredients) => { const sum = Object.keys(updateIngredients) .map(igKey => { return updateIngredients[igKey]; }) .reduce((sum, el) => { return sum + el; }, 0); return sum > 0; } const purchaseHandler = () => { if (isAuth) setPurchaseClicked(true) else { onSetAuthRedirectPath('/checkout'); props.history.push('/auth'); } } const closeModalAndBackdropHandler = () => { setPurchaseClicked(false) } const purchaseContinueHandler = () => { onPurchaseInit(); props.history.push('/checkout'); } const disableInfo = { ...ings }; for (let key in disableInfo) { disableInfo[key] = disableInfo[key] <= 0; } let orderSummary = null; let burger = error ? <p style={{ textAlign: 'center' }}>Ingredients can't be loaded!</p> : <Spinner />; if (ings) { burger = ( <Aux> <Burger ingredients={ings} /> <BuildControls ordered={purchaseHandler} price={price} ingredientAdded={(ingredientName) => onIngredientAdded(ingredientName)} ingredientRemoved={(ingredientName) => onIngredientRemoved(ingredientName)} disabled={disableInfo} isAuth={isAuth} disabledOrder={!updatePutchaseableState(ings)} /> </Aux> ); orderSummary = <OrderSummary totalPrice={price} purchaseContinue={() => purchaseContinueHandler(ings)} purchaseCanceled={closeModalAndBackdropHandler} ingredients={ings} /> } return ( <Aux> <Modal modalClosed={closeModalAndBackdropHandler} show={purchaseClicked}> {orderSummary} </Modal> {burger} </Aux> ) } export default withErrorHandler(burgerBuilder, axios);
import React from 'react' import { View, Image, StyleSheet } from 'react-native' import { Subheading } from 'react-native-paper' import PropTypes from 'prop-types' import sports from '../assets/sports' import calendarIcon from '../assets/images/calendar.png' import globeIcon from '../assets/images/globe.png' import moneyIcon from '../assets/images/money.png' import peopleIcon from '../assets/images/people.png' import noteIcon from '../assets/images/note.png' const TYPES = { sport: 'sport', place: 'place', datetime: 'datetime', price: 'price', players: 'players', notes: 'notes', } const ICONS = { place: globeIcon, datetime: calendarIcon, price: moneyIcon, players: peopleIcon, notes: noteIcon, } function getDatetimeString(datetime) { return datetime ? `${datetime.toLocaleDateString(undefined, { weekday: 'long', month: 'long', day: 'numeric', })}, ${datetime.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}` : '' } function getPriceString(price) { if (Number(price.value) === 0) return 'FREE' return `${price.value} ${price.currency.toUpperCase()}` } function getPlayersString(players) { const signedPlayers = players.filter(player => player.id !== 'player') return `${signedPlayers.length} of ${players.length} players signed` } function getText(type, value) { switch (type) { case TYPES.sport: return sports[value].name case TYPES.place: return value.description case TYPES.price: return getPriceString(value) case TYPES.players: return getPlayersString(value) case TYPES.notes: return value case TYPES.datetime: default: return getDatetimeString(value) } } const styles = StyleSheet.create({ row: { flexDirection: 'row', alignItems: 'center', paddingVertical: 16, }, image: { width: 48, height: 48, marginRight: 16, }, text: { flex: 1, justifyContent: 'center', fontWeight: '500', }, }) export default function InfoRow({ type, value }) { const imageSource = type === 'sport' ? sports[value].icon : ICONS[type] const text = getText(type, value) return ( <View style={styles.row}> <Image source={imageSource} style={styles.image} /> <Subheading style={styles.text}>{text}</Subheading> </View> ) } InfoRow.propTypes = { type: PropTypes.oneOf(Object.keys(TYPES)).isRequired, value: PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ description: PropTypes.string }), PropTypes.instanceOf(Date), PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string })), ]).isRequired, }
import React from 'react'; import './Image.css'; import placeholderLarge from '../../assets/user_L/user_3x.png'; import placeholderSmall from '../../assets/user_S/user_2x.png'; const Image = ({ src, alt, isSmall }) => { return ( <img className={isSmall ? 'Image--small' : 'Image--large'} src={src} alt={alt} onError={e => { e.target.onerror = null; e.target.src = isSmall ? placeholderSmall : placeholderLarge; }} /> ); }; export default Image;
(function() { 'use strict'; angular .module('iconlabApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider .state('documents', { parent: 'entity', url: '/documents?page&sort&search', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'Documents' }, views: { 'content@': { templateUrl: 'app/entities/documents/documents.html', controller: 'DocumentsController', controllerAs: 'vm' } }, params: { page: { value: '1', squash: true }, sort: { value: 'id,asc', squash: true }, search: null }, resolve: { pagingParams: ['$stateParams', 'PaginationUtil', function ($stateParams, PaginationUtil) { return { page: PaginationUtil.parsePage($stateParams.page), sort: $stateParams.sort, predicate: PaginationUtil.parsePredicate($stateParams.sort), ascending: PaginationUtil.parseAscending($stateParams.sort), search: $stateParams.search }; }], } }) .state('documents-detail', { parent: 'entity', url: '/documents/{id}', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'], pageTitle: 'Documents' }, views: { 'content@': { templateUrl: 'app/entities/documents/documents-detail.html', controller: 'DocumentsDetailController', controllerAs: 'vm' } }, resolve: { entity: ['$stateParams', 'Documents', function($stateParams, Documents) { return Documents.get({id : $stateParams.id}).$promise; }] } }) .state('documents.new', { parent: 'documents', url: '/new', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-dialog.html', controller: 'DocumentsDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { titre: null, sender:null, fichier: null, fichierContentType: null, mode: null, actif: null, id: null }; } } }).result.then(function() { $state.go('documents', null, { reload: true }); }, function() { $state.go('documents'); }); }] }) .state('home.newuserdocument', { parent: 'home', url: '/new/document', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-dialogU.html', controller: 'DocumentsDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { titre: null, fichier: null, fichierContentType: null, mode: null, actif: null, id: null }; } } }).result.then(function() { $state.go('home', null, { reload: true }); }, function() { $state.go('home'); }); }] }) .state('app.patache.newdocpa', { parent: 'app.patache', url: '/new/documentpa', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-dialogU.html', controller: 'DocumentsDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { titre: null, fichier: null, fichierContentType: null, mode: null, actif: null, id: null }; } } }).result.then(function() { $state.go('app.patache', null, { reload: true }); }, function() { $state.go('app.patache'); }); }] }) .state('app.tacheprojet.newuserdocument', {//nouveau document vu du chef d'un projet parent: 'app.tacheprojet', url: '/new/document1', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-dialogU.html', controller: 'DocumentsDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { titre: null, fichier: null, fichierContentType: null, mode: null, actif: null, id: null }; } } }).result.then(function() { $state.go('app.tacheprojet', null, { reload: true }); }, function() { $state.go('app.tacheprojet'); }); }] }).state('app.projetcompte.newuserdocument', {//nouveau document vu du chef de compte parent: 'app.projetcompte', url: '/new/document', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-dialogU.html', controller: 'DocumentsDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { titre: null, fichier: null, fichierContentType: null, mode: null, actif: null, id: null }; } } }).result.then(function() { $state.go('app.projetcompte', null, { reload: true }); }, function() { $state.go('app.projetcompte'); }); }] }) .state('documents.edit', {//etat de l'édition d'un document par l'administrateur parent: 'documents', url: '/{id}/edittAd', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-dialog.html', controller: 'DocumentsDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Documents', function(Documents) { return Documents.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('documents', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('app.projetcompte.edituserdocument', { parent: 'app.projetcompte', url: '/{iddoc}/editus', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-dialogU.html', controller: 'DocumentsDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Documents', function(Documents) { return Documents.get({id : $stateParams.iddoc}).$promise; }] } }).result.then(function() { $state.go('app.projetcompte', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('documents.delete', { parent: 'documents', url: '/{id}/delete', data: { authorities: ['ROLE_USER'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-delete-dialog.html', controller: 'DocumentsDeleteController', controllerAs: 'vm', windowClass:'center-modal', size: 'md', resolve: { entity: ['Documents', function(Documents) { return Documents.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('documents', null, { reload: true }); }, function() { $state.go('^'); }); }] }); } })();
chrome.contextMenus.create({ "title" : chrome.i18n.getMessage("generate"), "type" : "normal", "id": "createUnitTest", "contexts" : ["page"], "documentUrlPatterns": [ "*://*.contest.atcoder.jp/tasks/*", "*://atcoder.jp/contests/*/tasks/*" ] }); chrome.contextMenus.onClicked.addListener(function(info, tab) { chrome.tabs.query({ "active": true, "currentWindow": true }, function (tabs) { chrome.tabs.sendMessage(tabs[0].id, { "functiontoInvoke": "onClick" }); }); });
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "c79ebe4f9a662a08fcc192f0aec4bd37", "url": "/dev-gd_startseite/index.html" }, { "revision": "74fb0e964ce62fa334f1", "url": "/dev-gd_startseite/static/css/main.db796546.chunk.css" }, { "revision": "fc36a0405f1de8bc3bdb", "url": "/dev-gd_startseite/static/js/2.1e6acbb2.chunk.js" }, { "revision": "74fb0e964ce62fa334f1", "url": "/dev-gd_startseite/static/js/main.082f9cdb.chunk.js" }, { "revision": "080c043a98251ccc688a", "url": "/dev-gd_startseite/static/js/runtime-main.ffa4f6c5.js" }, { "revision": "463d295edb5fd4591117c5bc121782c1", "url": "/dev-gd_startseite/static/media/layered-landscape.463d295e.png" }, { "revision": "37abad0ce0cd88118be4f5962dc73461", "url": "/dev-gd_startseite/static/media/layered-lions.37abad0c.png" }, { "revision": "08686175e61621b3c2fc74a38b143619", "url": "/dev-gd_startseite/static/media/nebula-opt-2.08686175.jpg" }, { "revision": "2df3c8c138dbca266d3cddac8e7c3d7a", "url": "/dev-gd_startseite/static/media/portal2.2df3c8c1.png" } ]);
import React from 'react'; import { func, string} from 'prop-types'; const SendMessageDisplay = ({ onInputChange, inputValue, onButtonClick }) => ( <div> <input type="text" onChange={onInputChange} value={inputValue} /> <button onClick={onButtonClick}>Send</button> </div> ); SendMessageDisplay.propTypes = { onInputChange: func.isRequired, inputValue: string.isRequired, onButtonClick: func.isRequired, }; export default SendMessageDisplay;
// this is the view of the entire rolodex with all of the Contacts import $ from 'jquery'; import _ from 'underscore'; import Backbone from 'backbone'; import ContactView from 'app/views/contact_view'; import Contact from 'app/models/contact'; const RolodexView = Backbone.View.extend({ initialize: function(options) { this.contactTemplate = _.template($('#tmpl-contact-card').html()); // the <ul> element that the contact cards will live within this.listElement = this.$('#contact-cards'); this.contactDetails = $('#contact-details'); this.contactDetailsTemplate = _.template($('#tmpl-contact-details').html()); // // a list of contact views this.cardList = []; this.model.forEach(function(rawContact) { this.addContact(rawContact); //triggers the listener for `add` and `update` }, this); this.input = { name: this.$('.contact-form input[name="name"]'), email: this.$('.contact-form input[name="email"]'), phone: this.$('.contact-form input[name="phone"]') }; //when a model is added to the collection, create a card for that model and add it to our list of cards this.listenTo(this.model, 'add', this.addContact); //when the model updates, re-render the list of cards this.listenTo(this.model, 'update', this.render); this.hideModal(); }, render: function() { //clear the list in the DOM this.listElement.empty(); //Loop through the card list this.cardList.forEach(function(card) { card.render(); //append this.listElement.append(card.$el); }, this); return this; //enable chained calls }, events: { 'click .btn-save': 'createContact', 'click .btn-cancel': 'clearInput', 'click': 'hideModal', 'click #contact-details': 'stopProp' }, stopProp: function(event) { event.stopPropagation(); }, clearInput: function(event) { // console.log("====clearInput====="); this.input.name.val(""); this.input.email.val(""); this.input.phone.val(""); }, createContact: function(event) { // console.log("========CREATING CONTACT======="); event.preventDefault(); // Get the input data from the form and turn it into a contact var rawContact = this.getInput(); //add the contact to our collection this.model.add(rawContact); // Clear the input form so the user can add another contact this.clearInput(); }, addContact: function(contact) { var card = new ContactView({ model: contact, template: this.contactTemplate }); // console.log("======the card is:" + JSON.stringify(card)); this.listenTo(card, 'modal', this.showModal); this.cardList.push(card); }, getInput: function() { var contact = { name: this.input.name.val(), email: this.input.email.val(), phone: this.input.phone.val(), }; // console.log("==========Contact name is: " + JSON.stringify(contact)); return contact; }, showModal: function(contact) { // replace contents of modal with this person's info this.contactDetails.empty(); // the data I'm passing to the template var details = this.contactDetailsTemplate({name: contact.attributes.name, email: contact.attributes.email, phone: contact.attributes.phone}); // putting the html from this contact into the modal. this.contactDetails.append(details); // display the modal this.contactDetails.show(); }, hideModal: function() { this.contactDetails.hide(); } }); export default RolodexView;
/* global module require */ module.exports = () => { require('./starter'); };
import types from './actionTypes'; const initialState = { installable: false, installing: false, installed: false, }; function pwa(state = initialState, action) { switch(action.type) { case types.readyToInstall: { return { ...state, installable: action.payload.installable, } } case types.installCompleted: { return { ...state, installable: false, installing: action.payload.result === 'accepted', } } case types.installDetected: { return { ...state, installable: false, installing: false, installed: true, } } } return state; } export default pwa;
import React, { useState, useEffect } from 'react' import styled from 'styled-components/macro' import uploadImg from '../../assets/icons/cloud-computing-dark.svg' import rightArrow from '../../assets/icons/right-arrow-light.svg' import leftArrow from '../../assets/icons/left-arrow-light.svg' import NewPlayerInput from './NewPlayerInput' import Slugify from '../../common/Slugify' import Player from './Player.js' import ImageUploadInputs from './ImageUploadInputs' import ImageUpload from '../../common/ImageUpload' import { useHistory } from 'react-router-dom' export default function NewPlayer({ onSubmit, onBackClick }) { const history = useHistory() const [loading, setLoading] = useState({ profileImageLoading: false, }) const [newPlayer, setNewPlayer] = useState({ name: '', slug: '', profileImage: '', mail: '', phoneNumber: '', instagram: '', facebook: '', }) useEffect(() => { const newPlayerData = JSON.parse(localStorage.getItem('newPlayer')) if (newPlayerData) { setNewPlayer({ ...newPlayerData }) } else { setNewPlayer(newPlayer => newPlayer) } }, []) useEffect(() => { localStorage.setItem('newPlayer', JSON.stringify(newPlayer)) }, [newPlayer]) return ( <NewPlayerForm onSubmit={handleSubmit}> <InputContainer> <h1>DEIN PROFIL</h1> <ImageUploadInputs newPlayer={newPlayer} loading={loading} uploadImg={uploadImg} onChange={event => ImageUpload(event, setLoading, onImageSave)} /> <Player handleNameChange={handleNameChange} handleChange={handleChange} newPlayer={newPlayer} /> </InputContainer> <ButtonsWrapper> <ButtonLabel htmlFor="buttonBack" onClick={onBackClick}> <img src={leftArrow} alt="" /> </ButtonLabel> <NewPlayerInput id="buttonBack" type="button" /> <ButtonLabel htmlFor="submit"> <img src={rightArrow} alt="" /> </ButtonLabel> <NewPlayerInput id="submit" type="submit" /> </ButtonsWrapper> </NewPlayerForm> ) function handleNameChange(event) { const playerName = event.target.value const name = event.target.name const slugedName = Slugify(event, playerName) setNewPlayer({ ...newPlayer, [name]: playerName, slug: slugedName }) } function handleChange(event) { const name = event.target.name setNewPlayer({ ...newPlayer, [name]: event.target.value }) } function onImageSave(response, name) { if (name === 'profileImage') { setNewPlayer({ ...newPlayer, profileImage: response.data.secure_url }) setLoading({ profileImageLoading: false }) } } function handleSubmit(event) { event.preventDefault() onSubmit(newPlayer) history.push('/player') } } const NewPlayerForm = styled.form` display: grid; grid-template-rows: auto 60px; height: 100vh; gap: 16px; padding: 10px 20px; ` const InputContainer = styled.div` display: grid; grid-template-rows: auto auto 1fr; gap: 24px; overflow: scroll; h1 { justify-self: center; margin: 0; color: var(--dark); font-size: 2.8rem; } ` const ButtonsWrapper = styled.div` display: flex; justify-content: space-between; margin: 10px 0; padding: 0 10px; ` const ButtonLabel = styled.label` border-radius: 16px; background: var(--dark); width: 50px; height: 50px; padding: 5px; text-decoration: none; img { height: 100%; width: 100%; object-fit: contain; } `
export { convert, createTree, } from '../../../../../../../../lib/jcampconverter/9.0.1/jcampconverter.min';
/* O JavaScript map faz parte do conjunto de métodos disponíveis na linguagem para a manipulação de objetos do tipo array. Ele funciona como uma estrutura de repetição, pois percorre todos os elementos do array, executa determinada ação e retorna um novo conteúdo. Por isso, sua utilização reduz a necessidade de uso das estruturas de repetição tradicionais como while, for ou do.while. Isso significa executar ações com menos linhas de código, o que contribui para o desenvolvimento uma aplicação mais fácil de entender e de fazer manutenções. */ const nomes = ['Sílvia', 'Hellen', 'Larissa']; nomes.map((nome, i) => console.log('[forEach]', nome, i));
import React from 'react'; import { makeStyles } from '@material-ui/styles'; import { ActivitiesTable } from './index'; import ErrorBoundary from 'views/ErrorBoundary/ErrorBoundary'; // styles import 'assets/css/location-registry.css'; import { withPermission } from '../../containers/PageAccess'; const useStyles = makeStyles((theme) => ({ root: { padding: theme.spacing(3) }, content: { marginTop: theme.spacing(2) //fontFamily: 'Open Sans' }, title: { fontWeight: 700, color: '#000000', fontSize: 24, fontFamily: 'Open Sans' } })); const ActivitiesRegistry = () => { const classes = useStyles(); return ( <ErrorBoundary> <div className={classes.root}> {/* <SiteToolbar /> */} <div className={classes.content}> <ActivitiesTable /> </div> </div> </ErrorBoundary> ); }; export default withPermission(ActivitiesRegistry, 'CREATE_UPDATE_AND_DELETE_NETWORK_SITES');
var RSS = require('rss'); var fs = require('fs'); var moment = require('moment'); var pubDate = null; var path = require('path'); var Constants = require('./constants'); var util = require('./util'); module.exports = generateRSS; function generateRSS(podcast) { console.log('generateRSS:', podcast); var titleSlug = podcast.slug; var localDir = path.join(Constants.DOWNLOADS_DIR, titleSlug); var title = util.titleForSlug(titleSlug); var webPath = `martianrover.com/assets/audiobooks/${titleSlug}`; var podcastFileName = 'podcast.xml'; pubDate = moment(podcast.pubDate); var feed = new RSS({ title: title, description: 'Audiobook', feed_url: `http://${webPath}/${podcastFileName}`, site_url: 'http://martianrover.com', image_url: `http://${webPath}/cover.jpg`, docs: 'http://blogs.law.harvard.edu/tech/rss', managingEditor: null, webMaster: '', copyright: 'Copyright 2016', language: 'en', categories: ['Audiobook'], pubDate: pubDate.format(), ttl: '60', custom_namespaces: { 'itunes': 'http://www.itunes.com/dtds/podcast-1.0.dtd' }, custom_elements: [] }); var files = listMP3Files(localDir); var itemDate = pubDate.clone().add(files.length, 'minutes'); files.forEach(function(filePath, i) { var fileName = path.basename(filePath); var url = `http://${webPath}/${fileName}`; var fileSize = fs.statSync(filePath).size; var h = i + 1; itemDate.subtract(1, 'minute'); feed.item({ title: `${i}:00 ${util.capFirsts(title)}`, description: `Hour ${h}`, url: url, guid: null, categories: ['Audiobook'], author: '', // optional - defaults to feed author property date: itemDate.format(), // any format that js Date can parse. lat: null, long: null, size:fileSize, enclosure: { url:url, size:fileSize, type:"audio/mpeg" }, custom_elements: null }); }); // for each file return new Promise(function(resolve, reject) { // cache the xml to send to clients var xml = feed.xml(); var xmlPath = path.join(localDir, podcastFileName); fs.writeFile(xmlPath, xml, function(err) { if (err) { console.log('can\'t write', xmlPath); reject(err); } else { resolve(localDir); } }); }); } function listMP3Files(dir) { var files = fs.readdirSync(dir); return files.map(function (file) { return path.join(dir, file); }).filter(function (file) { return fs.statSync(file).isFile() && path.extname(file) === '.mp3'; }); }
import React, { Component } from "react"; import { View, Text, Dimensions, StyleSheet, TouchableOpacity, Image, ScrollView, Platform, StatusBar } from "react-native"; import Svg from "react-native-svg"; import { VictoryAxis, VictoryChart, VictoryGroup, VictoryBar, VictoryLegend, createContainer } from "victory-native"; import Colors from "../constants/Colors"; import { getData } from '../utils/firebaseUtil'; import firebase from 'firebase'; import { VictoryTheme } from "victory-core"; const styles = StyleSheet.create({ container: { alignItems: "center", backgroundColor: "#fff", paddingLeft: 50, paddingRight: 50, paddingBottom: 50, }, text: { fontSize: 18, fontFamily: Platform.OS === "ios" ? "Menlo" : "monospace", fontWeight: "bold", marginTop: 10, marginBottom: 30 } }); const legendData = [ { name: "BloodTest", symbol: { type: "circle", fill: "#006064" } }, { name: "CTscan", symbol: { type: "circle", fill: "#00796B" } }, { name: "Surgery", symbol: { type: "circle", fill: "#FFF59D" } } ]; export default class Chart extends React.Component { // constructor(props){ // super(props); // this.state = { // Flexon: [], // CTscan: [], // Surgery: [] // } // this.update = this.update.bind(this); // } state = { BloodTest: [], CTscan: [], Surgery: [] } alt(val){ alert(val.toString()); } componentDidMount(){ var ref = firebase.database().ref('data_imgs'); console.log("ffff"); ref.on('value', (snapshot) => { const a = []; var s1="",s2="",s3=""; snapshot.forEach((childSnapshot) => { var childData = childSnapshot.val(); var t = JSON.parse(childData["data"]); // s1 = s1 + " " + t.BloodTest.toString(); // s2 = s2 + " " + t.BloodTest.toString(); // s3 = s3 + " " + t.BloodTest.toString(); // s1 = t.BloodTest.toString(); // s2 = t.CTscan.toString(); // s3 = t.Surgery.toString(); console.log(t); s1 = t.BloodTest.toString(); s2 = t.CTscan.toString(); s3 = t.Surgery.toString(); // a.push({ // f: t.BloodTest, // c: t.CTscan, // p: t.Surgery // }); }); var s = "BloodTest : " + s1 + "\n" + "Surgery : " + s2 +"\n" + "CTscan : " + s3; // console.log(s); this.alt(s); }); // var ref = firebase.database().ref('data_imgs'); // ref.on('value', function(snapshot){ // snapshot.forEach(function(childSnapshot){ // var childData = childSnapshot.val(); // console.log(childData["data"]); // var t = JSON.parse(childData["data"]); // let f = this.state.Flexon.slice(); // let c = this.state.Surgery.slice(); // let p = this.state.CTscan.slice(); // f.push(t.Flexon); // c.push(t.Surgery); // p.push(t.CTscan); // this.setState({ // Flexon: f, // CTscan: p, // Surgery: c // }) // console.log("ffff"); // }); // }); //console.log(this.state.Flexon); } // state = { // Flexon: [], // CTscan: [], // Surgery: [] // } // componentDidMount(){ // console.log("jai"); // console.log(this.state.Flexon); // // this.update().then(()=>{ // // consloe.log("peace to hai!!"); // // }); // } // componentDidMount(){ // //console.log(this.state.Flexon); // var ref = firebase.database().ref('data_imgs'); // ref.on('value', function(snapshot){ // snapshot.forEach(function(childSnapshot){ // var childData = childSnapshot.val(); // console.log(childData["data"]); // var t = JSON.parse(childData["data"]); // let f = this.state.Flexon.slice(); // let c = this.state.Surgery.slice(); // let p = this.state.CTscan.slice(); // f.push(t.Flexon); // c.push(t.Surgery); // p.push(t.CTscan); // this.setState({ // Flexon: f, // CTscan: p, // Surgery: c // }) // // Surgery.push(t.Surgery); // // CTscan.push(t.CTscan); // //console.log(this.state.has); // // d.push(30); // //this.setState({flexon: dictionary}); // // let f = this.state.flexon; // // f.push(30); // // this.setState({ // // flexon:f // // }) // }); // }); // } renderHeader() { return ( <View style={{ flexDirection: "row", height: 72, backgroundColor: Colors.mainStrong, paddingTop: 24, padding: 8, alignItems: "center" }} > <TouchableOpacity onPress={() => this.props.navigation.goBack()} hitSlop={{ top: 8, right: 8, left: 8, bottom: 8 }} > <Image style={{ width: 24, height: 24 }} source={require("../assets/images/icons8-left_4.png")} /> </TouchableOpacity> <Text style={{ fontSize: 18, fontWeight: "600", marginLeft: 4, color: "white" }} > Uploaded Documents </Text> </View> ); } render() { return ( <View style={{ flex: 1 }}> <StatusBar barStyle='light-content'/> {this.renderHeader()} <ScrollView contentContainerStyle={styles.container} style={{ flex: 1, backgroundColor: "#fff" }} > <Text style={{ textAlign: "center", color: Colors.text, fontWeight: "600", fontSize: 18, marginTop: 28 }} > Price Comparison for Lung Cancer Treatment </Text> <Text style={{fontWeight: '600', color: Colors.main, textAlign: 'center', fontSize: 24, marginTop: 8}}>38% Higher than Average</Text> <Svg width={Dimensions.get("window").width} height={200}> <VictoryLegend x={5} y={100} data={legendData} standalone={false} itemsPerRow={3} /> </Svg> <VictoryChart domain={{ x: [0, 3] }}> <VictoryGroup offset={25} colorScale={"qualitative"}> <VictoryBar data={[ { x: 1, y: 100 }, { x: 2, y: 200 }, { x: 3, y: 300 } ]} /> <VictoryBar data={[ { x: 1, y: 400 }, { x: 2, y: 500 }, { x: 3, y: 600 } ]} /> <VictoryBar data={[ { x: 1, y: 700 }, { x: 2, y: 800 }, { x: 3, y: 900 } ]} /> </VictoryGroup> </VictoryChart> </ScrollView> </View> ); } }
import React, { Component } from 'react'; import { BrowserRouter as Router, Route} from "react-router-dom"; import Home from './pages/Home/Home'; import Saved from './pages/Saved/Saved'; import './App.css'; import Navbar from './components/Navbar/Navbar'; import Jumbotrom from './components/Jumbotrom/Jumbotrom'; class App extends Component { render() { return ( <div className="App"> <Router> <div> <Navbar/> <Jumbotrom/> <Route exact path="/" component={Home} /> <Route exact path="/books" component={Saved} /> </div> </Router> </div> ); } } export default App;
import {atom} from "recoil"; export const configuratorState = atom({key: "configuratorState", default: null}); export const segmentState = atom({key: "segmentState", default: null}); export const tagsState = atom({key: "tagsState", default: null}); export const addSegmentState = atom({key: "addSegmentState", default: null}); export const deleteSegmentState = atom({key: "deleteSegmentState", default: null});
import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, applyMiddleware, compose } from 'redux'; import { Provider } from 'react-redux'; import createSagaMiddleware from 'redux-saga'; import reducer from './reducers'; const sagas = require('./sagas'); const createSocketMiddleware = require('./sockets'); import './index.css'; import App from './App'; const actions = require('./actions'); const defaultState = { uuid: undefined, username: undefined, role: undefined, theme: undefined, // HOST properties players: [], }; const sagaMiddleware = createSagaMiddleware(); const socketMiddleware = createSocketMiddleware({ port: 4000 }); const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore( reducer, composeEnhancers(applyMiddleware( sagaMiddleware, socketMiddleware )) ); sagaMiddleware.run(sagas); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
var express = require('express'); var router = express.Router(); var Campgrounds = require('../models/campgrounds'); var middleware = require('../middleware'); var NodeGeocoder = require('node-geocoder'); var options = { provider: 'google', httpAdapter: 'https', apiKey: process.env.Geocoder_API, formatter: null }; var geocoder = NodeGeocoder(options); checkOwner = middleware.checkOwner; isLoggedIn = middleware.isLoggedIn; router.get("/", function (req, res) { res.render("landing"); }); router.get("/campground", function (req, res) { if (req.query.search) { const regex = new RegExp(escapeRegex(req.query.search), 'gi'); Campgrounds.find({name:regex}, function (err, campgrounds) { if (err) { console.log(err); } else { res.render("campground/campground", { campgrounds: campgrounds, userInfo: req.user }); } }); } else { Campgrounds.find({}, function (err, campgrounds) { if (err) { console.log(err); } else { res.render("campground/campground", { campgrounds: campgrounds, userInfo: req.user }); } }); } }); router.get("/new", isLoggedIn, function (req, res) { res.render("campground/new"); }); router.post("/campground", function (req, res) { Campgrounds.create({ name: req.body.name, price: req.body.price, image: req.body.img, description: req.body.description }, function (err, newCampground) { if (err) { req.flash("error", "Sorry, could not create campground. Try again."); console.log(err); } else { newCampground.creator.id = req.user._id; newCampground.creator.username = req.user.username; newCampground.save(); req.flash("success", "Campground added successfully."); res.redirect("/campground"); } }); }); router.get("/campground/:id", function (req, res) { Campgrounds.findById(req.params.id).populate("comments").exec(function (err, foundCampground) { if (req.user) { res.render("campground/camp", { camp: foundCampground, user: req.user, id: req.user._id }); } else { res.render("campground/camp", { camp: foundCampground, user: req.user }) } }); }); router.get("/campground/:id/update", checkOwner, (req, res) => { Campgrounds.findById(req.params.id, (err, foundCampground) => { if (err) { console.log(err); } else { res.render("campground/update", { campground: foundCampground }); } }) }) router.put("/campground/:id", (req, res) => { Campgrounds.findById(req.params.id, (err, foundCampground) => { if (err) { req.flash("error", "Update Unsuccessful"); console.log(err); } else { foundCampground.name = req.body.name; foundCampground.image = req.body.img; foundCampground.price = req.body.price; foundCampground.description = req.body.description; foundCampground.save(); req.flash("success", "Successfully updated the campground"); res.redirect("/campground/" + req.params.id); } }); }); router.delete("/campground/:id", checkOwner, (req, res) => { Campgrounds.findByIdAndRemove(req.params.id, (err) => { if (err) { req.flash("error", "Sorry, Could not delete the campground"); console.log(err); } else { req.flash("success", "Deleted successfully"); res.redirect("/campground"); } }) }) function escapeRegex(text) { return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }; module.exports = router;
import React from 'react'; import { mount, shallow } from 'enzyme'; import LogsTable from '../../views/pages/Logs/logs_table'; import { Provider } from 'react-redux'; import store from '../../store'; import { LOAD_ACTIVE_SERVICE_SUCCESS } from '../../redux/Logs/actions'; import CustomMaterialTable from '../../views/components/Table/CustomMaterialTable'; describe('LogsTable Component', () => { let wrapper; beforeEach(() => { wrapper = mount( <Provider store={store}> <LogsTable service="auth" /> </Provider> ); }); it('displays loading indicator initially', () => { expect(wrapper.contains('[data-testid="loading-indicator"]')); }); it('displays logs when data is fetched', () => { const logsData = [ { meta: { username: 'user1', email: 'user1@example.com' }, message: 'Logged in' } ]; store.dispatch({ type: LOAD_ACTIVE_SERVICE_SUCCESS, payload: 'auth' }); expect(wrapper.contains(<CustomMaterialTable data={logsData} />)).toEqual(true); }); });
/*global Template*/ Template.indexPage.helpers({ name: 'Weclome to Voda Chat' });
'use strict'; import mongoose from 'mongoose'; var TicketSchema = new mongoose.Schema({ ticketNo : Number, owner : String, owneremail : String, category: String, subcategory: String, status : String, status_cycle : [], priority : String, Assigned_to : String, description : String, spoc: String, creationdate: Date, type: String, categoryheademail : String, categoryhead : String }); export default mongoose.model('Ticket', TicketSchema);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class CameraUpdater { constructor(client, camera, config) { this.onResourceReceived = (resourceId, resource) => { this.resource = resource; this.updateRatio(); }; this.onResourceEdited = (resourceId, command, propertyName) => { this.updateRatio(); }; this.client = client; this.camera = camera; this.config = config; this.camera.setConfig(this.config); this.camera.setRatio(5 / 3); this.client.subResource("gameSettings", this); } destroy() { if (this.resource != null) this.client.unsubResource("gameSettings", this); } config_setProperty(path, value) { this.camera.setConfig(this.config); } updateRatio() { if (this.resource.pub.ratioNumerator != null && this.resource.pub.ratioDenominator != null) this.camera.setRatio(this.resource.pub.ratioNumerator / this.resource.pub.ratioDenominator); else this.camera.setRatio(5 / 3); } } exports.default = CameraUpdater;