text
stringlengths
7
3.69M
/* eslint no-var:0 */ var webpack = require('webpack'); var base = require('./webpack.config'); base.plugins = [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.AggressiveMergingPlugin(), new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } }) ]; base.entry = ['./src/index']; base.devtool = 'cheap-module-source-map'; module.exports = base;
define([ 'dojo/_base/declare', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin', 'gis/dijit/_FloatingWidgetMixin', 'dojo/_base/lang', 'dojo/on', 'dojo/dom-construct', 'dijit/registry', 'dojo/text!./LocatorControl/templates/LocatorControl.html', 'dojo/i18n!./LocatorControl/nls/LocatorControl', 'dijit/form/Form', 'dijit/form/CheckBox', 'dijit/form/NumberTextBox', 'xstyle/css!./LocatorControl/css/LocatorControl.css' ], function ( declare, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, _FloatingWidgetMixin, lang, on, domConstruct, registry, template, i18n ) { return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, _FloatingWidgetMixin], { widgetsInTemplate: true, templateString: template, i18n: i18n, baseClass: 'cmwLocatorControlWidget', html: '<i class="fa fa-compass fa-2x fa-fw" style="cursor:pointer;color:#FF0"></i>', domTarget: 'helpDijit', draggable: true, locatorWidgetID: 'locateButton_widget', locateWidget: null, postCreate: function () { this.inherited(arguments); if (!this.parentWidget.toggleable) { this.parentWidget.draggable = this.draggable; var btn = domConstruct.place(this.html, this.domTarget); on(btn, 'click', lang.hitch(this.parentWidget, 'show')); } this.widgetChecker = window.setInterval(lang.hitch(this, 'checkForLocator'), 100); }, onValueChange: function () { if (this.locateWidget) { this.locateWidget.set('centerAt', this.centerAtDijit.get('checked')); this.locateWidget.set('useTracking', this.useTrackingDijit.get('checked')); this.locateWidget.set('setScale', this.setScaleDijit.get('checked')); this.locateWidget.set('scale', this.scaleDijit.get('value')); } }, checkForLocator: function () { var widget = registry.byId(this.locatorWidgetID); if (widget) { this.locateWidget = widget; this.centerAtDijit.set('checked', this.locateWidget.get('centerAt')); this.useTrackingDijit.set('checked', this.locateWidget.get('useTracking')); this.setScaleDijit.set('checked', this.locateWidget.get('setScale')); this.scaleDijit.set('value', this.locateWidget.get('scale')); window.clearInterval(this.widgetChecker); return; } } }); });
"use strict"; require("run-with-mocha"); const assert = require("assert"); const DistanceModelType = require("../../src/types/DistanceModelType"); describe("types/DistanceModelType", () => { it("Symbol.hasInstance", () => { [ DistanceModelType.LINEAR, "linear", DistanceModelType.INVERSE, "inverse", DistanceModelType.EXPONENTIAL, "exponential", ].forEach((value) => { assert(DistanceModelType[Symbol.hasInstance](value)); }); }); });
import PropTypes from "prop-types"; export const propTypes = { color: PropTypes.string, start: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number }), end: PropTypes.shape({ x: PropTypes.number, y: PropTypes.number }) }; export const defaultProps = { color: "#8E91A8", start: { x: 0, y: 0 }, end: { x: 0, y: 0 } };
const test = require('../../test'); module.exports = function(argv) { let options = { fnName: 'lengthAnnouncer', esVersion: 5, allowHigherOrderFns: false }; let test1 = { input: 'lengthAnnouncer("Science")', expected: 'Science has 7 characters!' }; let test2 = { input: 'lengthAnnouncer("Arts")', expected: 'Arts has 4 characters!' }; let test3 = { input: 'lengthAnnouncer("all your base is belong to us")', expected: 'all your base is belong to us has 29 characters!' }; test(argv, [test1, test2, test3], options); };
import React, { Component } from "react"; import "./App.css"; import FakeWeather from "./data/FakeWeather.json"; import Search from "./search.js"; import CurrentWeather from "./CurrentWeather"; import WeatherLater from "./WeatherLater"; class App extends Component { constructor(props) { super(props); this.state = { result: null, WriteCity: "Beirut" }; } async ApiInfo(a) { const api = "http://api.openweathermap.org/data/2.5/forecast?q=" + this.state.WriteCity + "&cnt=8&units=metric&appid=571df88d447302a15fda544e0999ffbe"; const response = await fetch(api); const r = await response.json(); this.setState({ result: r }); } callbackFunction = (call2) => { this.setState({ WriteCity: call2 }); this.ApiInfo(call2); } async componentDidMount() { this.ApiInfo(this.state.WriteCity); } render() { return ( <div className="app"> <Search {this.callbackFunction(this.state.WriteCity)} /> {this.state.result !== null ? <CurrentWeather hum={this.state.result.list[0].main.humidity} /> : "loading"} <div className="forecast"> {this.state.result ? this.state.result.list.map((item, value) => { if (value > 0 && value < 8) return <WeatherLater weather_list={item} />; }) : "loading"} </div> <main className="appmain"></main> </div> ); } } export default App;
// Generated by CoffeeScript 1.6.3 var BuildTask, CompileStylus, Future, fs, mkdirp, nib, path, pathToCore, pathUtils, replaceImportRe, stylus, stylusLib, _pathUtils, _ref, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; fs = require('fs'); path = require('path'); mkdirp = require('mkdirp'); stylus = require('stylus'); nib = require('nib'); Future = require('../../utils/Future'); BuildTask = require('./BuildTask'); pathToCore = 'bundles/cord/core'; stylusLib = function(style) { style.define('url', stylus.url()); style.use(nib()); return style["import"]('nib'); }; replaceImportRe = /^@import ['"](.*\/\/.+)['"]$/gm; _pathUtils = null; pathUtils = function(baseDir) { /* Lazy val */ if (_pathUtils == null) { _pathUtils = require("" + (path.join(baseDir, 'public', pathToCore)) + "/requirejs/pathUtils"); } return _pathUtils; }; CompileStylus = (function(_super) { __extends(CompileStylus, _super); function CompileStylus() { _ref = CompileStylus.__super__.constructor.apply(this, arguments); return _ref; } CompileStylus.totalPreprocessTime = [0, 0]; CompileStylus.prototype.run = function() { var basename, dirname, dst, src, _this = this; dirname = path.dirname(this.params.file); basename = path.basename(this.params.file, '.styl'); src = "" + this.params.baseDir + "/" + this.params.file; dst = "" + this.params.targetDir + "/" + dirname + "/" + basename + ".css"; return Future.call(fs.readFile, src, 'utf8').flatMap(function(stylusStr) { var preprocessedStr, pu, styl; pu = pathUtils(_this.params.targetDir); preprocessedStr = stylusStr.replace(replaceImportRe, function(match, p1) { return "@import '" + (pu.convertCssPath(p1, src)) + "'"; }); styl = stylus(preprocessedStr).set('filename', src).set('compress', true).include(_this.params.baseDir).use(stylusLib); return Future.call([styl, 'render']); }).zip(Future.call(mkdirp, path.dirname(dst))).flatMap(function(cssStr) { return Future.call(fs.writeFile, dst, cssStr); }).flatMapFail(function(err) { if (err.constructor.name === 'ParseError') { console.error("Stylus ParseError:\n" + err.message); return Future.rejected(new BuildTask.ExpectedError(err)); } else { return Future.rejected(err); } }).link(this.readyPromise); }; return CompileStylus; })(BuildTask); module.exports = CompileStylus;
import React from 'react' import firebase from '../Config/Firebase' import TouchableScale from 'react-native-touchable-scale' import { Text, View, StyleSheet, Image, TextInput, ActivityIndicator } from 'react-native' const VerifyScreen = ({ route, navigation }) => { const { verificationId } = route.params const [visibleModal, setVisibleModal] = React.useState(false) const [code, setCode] = React.useState('') const [loading, setLoading] = React.useState(false) const verifyCode = () => { setLoading(true) const credential = firebase.auth.PhoneAuthProvider.credential( verificationId, code ) firebase .auth() .signInWithCredential(credential) .then((result) => { if (result.user) { setLoading(false) displayModal() navigation.navigate('HomeApp') } }) .catch((e) => console.log(e)) } const displayModal = () => { setVisibleModal(true) } return ( <View style={styles.container}> <Image source={require('../assets/images/image.png')} /> <Text style={styles.title}>Entrer le code reçu par SMS</Text> <TextInput placeholder='Code' placeholderTextColor='white' style={styles.input} onChangeText={setCode} returnKeyType='done' keyboardType='phone-pad' /> <TouchableScale onPress={verifyCode} style={styles.button} activeScale={1.2}> {loading ? ( <ActivityIndicator color='#87c965' /> ) : ( <Text style={styles.textButton}>Valider</Text> )} </TouchableScale> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#9400d3' }, title: { textAlign: 'center', marginTop: 20, width: '60%', fontSize: 17, marginBottom: 20, color: 'white', fontFamily: 'muli' }, input: { width: '60%', color: 'white', borderRadius: 10, padding: 15, borderWidth: 1, borderColor: 'white', fontFamily: 'muli', marginBottom: 20 }, button: { width: 220, marginTop: 20, backgroundColor: 'white', paddingHorizontal: 20, paddingVertical: 15, borderRadius: 40 }, textButton: { fontFamily: 'muli', color: '#9400d3', textAlign: 'center', fontWeight: 'bold' } }) export default VerifyScreen
import React, {Component} from 'react'; import {View, Text} from 'react-native'; import PropTypes from 'prop-types'; import PPRefreshLayout from '../widget/PPRefreshLayout'; import WeatherHeaderWidget from '../widget/WeatherHeaderWidget'; import WeatherHeaderComponent from './WeatherHeaderComponent'; import HourWeatherComponent from './HourWeatherComponent'; import DailyWeatherComponent from './DailyWeatherComponent'; import AirQualityComponent from './AirQualityComponent'; import LifeIndexComponent from './LifeIndexComponent'; import SunriseAndSunsetComponent from './SunriseAndSunsetComponent'; import WeatherDataUtil from '../utils/WeatherDataUtil'; import Util from '../utils/Index'; import CityListManager from './CityListManager'; // 天气头部 const ITEM_TYPE_HEADER = 0; // 小时天气 const ITEM_TYPE_HOUR_WEATHER = 1; // 每日天气 const ITEM_TYPE_DAILY_WEATHER = 2; // 空气质量 const ITEM_TYPE_AIR_QUALITY = 3; // 生活指数 const ITEM_TYPE_LIFE_INDEX = 4; // 日出和日落 const ITEM_TYPE_SUNRISE_AND_SUNSET = 5; const ITEM_COUNT = 6; const APP_BAR_HEIGHT = Util.getAppBarHeight(); // let weatherDataBean; export default class WeatherComponent extends Component { static propTypes = { cityItem: PropTypes.object, refreshMainPage: PropTypes.func, }; constructor(props) { super(props); this.state = { weatherHeaderInfo: { currentTemp: -1, weatherDesc: null, updateTime: null, }, }; } render() { return ( <View style={{ flex: 1, }}> <PPRefreshLayout style={{marginTop: APP_BAR_HEIGHT}} nestedScrollEnabled={true} overScrollMode={'never'} ref={ref => (this.refreshLayout = ref)} renderItem={({item}) => { return this.convert(item, this.props.navigation); }} onScroll={e => { // alert(e.nativeEvent.contentOffset.y); this.headerWidget.runAnimation(e); }} onScrollEndDrag={e => this.onScrollEnd(e)} needDivide={false} loadMoreEnable={false} dataRequest={() => this.getWeatherData()} /> <WeatherHeaderWidget ref={ref => (this.headerWidget = ref)} cityItem={this.props.cityItem} weatherHeaderInfo={this.state.weatherHeaderInfo} otherStyle={{position: 'absolute', top: 22}} onCityClick={weatherHeaderInfo => { if (weatherHeaderInfo && weatherHeaderInfo.currentTemp !== -1) { const navigation = this.props.navigation; navigation.navigate('CityManager', { callBack: (haveDelete, cityList) => { if (haveDelete) { this.props.refreshMainPage && this.props.refreshMainPage(cityList); } }, }); } }} /> </View> ); } onScrollEnd = e => { const scrollY = e.nativeEvent.contentOffset.y; if (scrollY > 0 && scrollY <= this.headerWidget.getBottomScrollDistance()) { this.refreshLayout.scrollToTop(); } }; scrollToTop = () => { this.refreshLayout && this.refreshLayout.scrollToTop(false); }; convert = (item, navigation) => { const weatherData = item.weatherData; if (!weatherData) return null; switch (item.itemType) { case ITEM_TYPE_HEADER: default: return ( <WeatherHeaderComponent forecast15={weatherData.forecast15} observe={weatherData.observe} /> ); case ITEM_TYPE_HOUR_WEATHER: return ( <HourWeatherComponent hourfc={weatherData.hourfc} hourMaxTemp={weatherData.hourMaxTemp} hourMinTemp={weatherData.hourMinTemp} /> ); case ITEM_TYPE_DAILY_WEATHER: return ( <DailyWeatherComponent forecast15={weatherData.forecast15} dailyDayMaxTemp={weatherData.dailyDayMaxTemp} dailyDayMinTemp={weatherData.dailyDayMinTemp} dailyNightMaxTemp={weatherData.dailyNightMaxTemp} dailyNightMinTemp={weatherData.dailyNightMinTemp} /> ); case ITEM_TYPE_AIR_QUALITY: return <AirQualityComponent evnBean={weatherData.evnBean} />; case ITEM_TYPE_LIFE_INDEX: return ( <LifeIndexComponent indexes={weatherData.indexes} normalIndexes={weatherData.normalIndexes} /> ); case ITEM_TYPE_SUNRISE_AND_SUNSET: return ( <SunriseAndSunsetComponent currentDateBean={weatherData.currentDateBean} /> ); } }; componentDidMount() { this.getWeatherData(); } getWeatherData = () => { const url = 'http://zhwnlapi.etouch.cn/Ecalender/api/v2/weather?' + 'date=20170817&app_key=99817749&citykey=' + this.props.cityItem.cityId; fetch(url) .then(response => { if (response.ok) { return response.json(); } }) .then(weatherData => { this.onSuccess(weatherData); }) .catch(error => { this.onFailure(error); }); }; onSuccess = weatherData => { // weatherDataBean = weatherData; const forecast15 = weatherData.forecast15; const observe = weatherData.observe; CityListManager.updateCity( this.props.cityItem.cityId, this.props.cityItem.cityName, this.props.cityItem.district, this.props.cityItem.province, observe.temp, forecast15[1].high, forecast15[1].low, observe.wthr, observe.type, false, ); this.setState({ weatherHeaderInfo: { currentTemp: observe.temp, weatherDesc: observe.wthr, updateTime: observe.up_time, }, }); let dataList = []; for (let i = 0; i < ITEM_COUNT; i++) { dataList.push({ itemType: i, weatherData: WeatherDataUtil.getWeatherData(i, weatherData), }); } this.refreshLayout.refreshComplete(dataList); }; onFailure = error => {}; }
const fs = require('fs'); const path = require ('path'); const { buildSchema } = require('graphql'); const commentClient = require('../client/comment'); const praiseClient = require('../client/praise'); const schema = buildSchema( fs.readFileSync(path.resolve(__dirname, '../protocols/comment.gql'), 'utf-8') ); schema .getQueryType() .getFields() .comments .resolve = (source, {articleId} = {}) => new Promise((resolve, reject) => { console.log(articleId); commentClient.write({ articleId, }, (err, res) => err ? reject(err) : resolve(res.comments)) }); schema .getMutationType() .getFields() .praise .resolve = (source, {commentId} = {}) => new Promise((resolve, reject) => { praiseClient.write({ commentId, }, (err, res) => err ? reject(err) : resolve(res.praiseNum)) }); module.exports = schema;
export default function editorUrl(config, file, lineNumber) { const editor = config.editor; const editors = { sublime: 'subl://open?url=file://%path&line=%line', textmate: 'txmt://open?url=file://%path&line=%line', emacs: 'emacs://open?url=file://%path&line=%line', macvim: 'mvim://open/?url=file://%path&line=%line', phpstorm: 'phpstorm://open?file=%path&line=%line', idea: 'idea://open?file=%path&line=%line', vscode: 'vscode://file/%path:%line', 'vscode-insiders': 'vscode-insiders://file/%path:%line', 'vscode-remote': 'vscode://vscode-remote/%path:%line', 'vscode-insiders-remote': 'vscode-insiders://vscode-remote/%path:%line', vscodium: 'vscodium://file/%path:%line', atom: 'atom://core/open/file?filename=%path&line=%line', nova: 'nova://core/open/file?filename=%path&line=%line', netbeans: 'netbeans://open/?f=%path:%line', xdebug: 'xdebug://%path@%line', }; file = (config.remoteSitesPath || false).length > 0 && (config.localSitesPath || false).length > 0 ? file.replace(config.remoteSitesPath, config.localSitesPath) : file; if (!Object.keys(editors).includes(editor)) { console.error( `'${editor}' is not supported. Support editors are: ${Object.keys(editors).join(', ')}`, ); return null; } return editors[editor] .replace('%path', encodeURIComponent(file)) .replace('%line', encodeURIComponent(lineNumber)); }
const path = require('path'); const nodeExternals = require('webpack-node-externals'); const ESLintPlugin = require('eslint-webpack-plugin'); const config = { entry: './src/index.ts', output: { path: path.resolve(__dirname, 'dist'), filename: 'createjs-accessibility.js', library: { name: 'createjs-accessibility', type: 'umd', umdNamedDefine: true, }, }, externals: [nodeExternals()], performance: { hints: false }, module: { rules: [ { test: /\.(ts|tsx)$/, exclude: /node_modules/, use: [ { loader: 'ts-loader', }, ], }, { test: /\.(js|jsx)$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { presets: [ ['@babel/preset-env', { targets: { chrome: '88', ie: '11', edge: '88', firefox: '79', safari: '13.1.3', }, } ], ], }, }, ], }, ], }, mode: 'production', resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'], }, plugins: [new ESLintPlugin()], }; if (process.env.NODE_ENV !== 'production') { config.watch = true; config.watchOptions = { ignored: /node_modules/, }; } module.exports = config;
[{ 'id' : "1", 'icon' : "images/menuPanel/tag_blue3.gif", 'text' : "\u6625\u5B63", 'leaf' : true }, { 'id' : "2", 'icon' : "images/menuPanel/tag_blue3.gif", 'text' : "\u590F\u5B63", 'leaf' : true }, { 'id' : "3", 'icon' : "images/menuPanel/tag_blue3.gif", 'text' : "\u79CB\u5B63", 'leaf' : true }, { 'id' : "4", 'icon' : "images/menuPanel/tag_blue3.gif", 'text' : "\u51AC\u5B63", 'leaf' : true }, { 'id' : "5", 'icon' : "images/menuPanel/tag_blue3.gif", 'text' : "\u56DB\u5B63", 'leaf' : true }, { 'id' : "6", 'icon' : "images/menuPanel/tag_blue3.gif", 'text' : "\u6625\u79CB\u5B63", 'leaf' : true }]
var $btn = $('#btn') var $changeColor = $('#change-color-div') var $inputSth = $('#input-show-box>input') var $select = $('#select-box>select') var $showScrollTop = $('#showscrollTop>p') var $window = $(window) //点击方块连续变色 $btn.on('click',function(){ $(this).css('background-color','red') setTimeout(function(){ $btn.css('background-color','blue') },1000) // .delay(1000) // $(this).animate({backgroundColor:'red'}) }) //放上、移开鼠标变色 $changeColor.on('mouseenter',function(){ $(this).css('background-color','red') }).on('mouseleave',function(){ $(this).css('background-color','#fff') }) //获取滚动后的垂直滚动距离 $window.scroll(function(){ $showScrollTop.text($window.scrollTop()) }) //文本输入的改变与展现 $inputSth.on('focus',function(){ $(this).addClass('blueBorder') }).on('blur',function(){ $(this).removeClass('blueBorder') }) $inputSth.change(function(){ console.log($(this).context.value) $inputSth.parents('#input-show-box').find('.input-show').text($(this).context.value) $(this).context.value = $(this).context.value.toUpperCase() }) //显示 select的选择结果 $select.parents('#select-box').find('.input-show').text($('#select-box>select>option:selected').text()) $select.change(function(){ console.log($('#select-box>select>option:selected').text()) $(this).parents('#select-box').find('.input-show').text($('#select-box>select>option:selected').text()) })
//toUpperCase(); //toLowerCase(); let someTxt="I'm a lit-tle tea pot"; function titleCase(str) { let allLettersLowerCase=""; let regMachWord=/\w*['-]?\w*\S/ig; // don't know how to exclude some symbols, for intance if we're gonna have a comma. let arrSepWords=[]; let transformedSentence=""; allLettersLowerCase=str.toLowerCase(); arrSepWords=allLettersLowerCase.match(regMachWord); let getLastItemInArr=arrSepWords[arrSepWords.length-1]; let lastIndex=arrSepWords.indexOf(getLastItemInArr); for(let i=0;i<arrSepWords.length;i++){ transformedSentence+=arrSepWords[i].slice(0,1).toUpperCase(); transformedSentence+=arrSepWords[i].slice(1,arrSepWords[i].length); if(lastIndex!=i){ transformedSentence+=" "; } } return console.log(transformedSentence); } titleCase(someTxt)
angular.module("MainApp").directive('templateForm', function ($compile,$http) { return { restrict: 'EA', scope: { tMode:'@', printParams:'@', tForm: '=', tTemplate:'=', }, // template: '<div><input type="text" ng-model="tForm.BP"></div><textbox ng-model="tForm.BP"></textbox>', link: function (scope, element, attrs) { var getTemplateDetailsById = function(successFunction){ if( scope.tTemplate == null || scope.tTemplate == undefined ){ return; } $http.get('/template/getTemplateDetailsById?templateId='+scope.tTemplate).success(function (data) { successFunction(data); }); } var appendTemplate = function(data) { element.html($compile(data.html)(scope)); } var printTemplate = function(data) { if($('#myFrame').length > 0){ $('#myFrame').remove(); } $('<iframe id="myFrame" name="myFrame" style="display:none;"/>').appendTo("body").ready(function(){ $('#myFrame').contents().find('head').append('<link rel="stylesheet" href="assets/styles/print.css">'); // Ignore for now /*$('#myFrame').contents().find('head') .append('<link rel="stylesheet" href="assets/styles/bootstrap.css">'); $('#myFrame').contents().find('head') .append('<link rel="stylesheet" href="assets/styles/main.css">');*/ if(scope.printParams != null || scope.printParams != undefined){ $http.get('/print?'+scope.printParams).success(function (header) { $('#myFrame').contents().find('body').append($compile(header.printData)(scope)); $('#myFrame').contents().find('body').append($compile("<tr><td>&nbsp;&nbsp;</td></tr>")(scope)); print(data); }); } else { print(data); } }); } var print = function(data) { $('#myFrame').contents().find('body').append($compile(data.html)(scope)); setTimeout(function(){ $('#myFrame').get(0).contentWindow.focus(); $('#myFrame').get(0).contentWindow.print(); },50); } if( scope.tMode == 'view' || scope.tMode == 'edit' ) { getTemplateDetailsById(appendTemplate); } else if( scope.tMode == 'print' ) { element.on('click', function (e) { getTemplateDetailsById(printTemplate); }); } } }; }); //angular.module("MainApp").directive('templateForm', function ($compile,$http) { //return { //restrict: 'E', //scope:{ //tMode:'@', //tForm:'=', //tTemplate:'=' //}, //replace: true, //template :'<div><textbox ng-model="tForm.BP"></textbox><input type="text" ng-model="tForm.BP"></input></div>', ////template : "<div ng-include=\"'template/getTemplateDetailsById?templateId='+tTemplate\"></div>", ////'<div ng-include='=+tTemplate'></div>', //link: function (scope, element, attrs) { ////scope.$watch('tTemplate', function(templateId) { ////if(templateId!=null){ ////$http.get('/template/getTemplateDetailsById?templateId='+scope.tTemplate) ////.success(function (data, status, headers, config) { ////element.html($compile(data.html)(scope)); ////}); ////}else{ ////element.html(''); ////} ////}); //} //}; //}); /*angular.module("MainApp").directive('textbox', function () { return { restrict: "E", scope:{ ngModel:'=' }, template: "<div><label class=' col-lg-4 col-xs-2 control-label'>Contact{{ngModel}}</label>" + "<div class='col-lg-8 col-xs-10'>" + "<input ng-show=\"$parent.tMode=='edit'\" type='text' class='form-control' ng-model='ngModel'>" + "<div ng-show=\"$parent.tMode=='view'\" style='padding-top: 7px;margin-bottom: 0;text-align: left;'>{{ngModel}}</div></div></div>" } });*/
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const THREE = SupEngine.THREE; class P2Body extends SupEngine.ActorComponent { constructor(actor) { super(actor, "P2Body"); this.actorPosition = new THREE.Vector3(); this.actorAngles = new THREE.Euler(); this.body = new window.p2.Body(); SupEngine.P2.world.addBody(this.body); } setIsLayerActive(active) { } setup(config) { this.mass = (config.mass != null) ? config.mass : 0; this.fixedRotation = (config.fixedRotation != null) ? config.fixedRotation : false; this.offsetX = (config.offsetX != null) ? config.offsetX : 0; this.offsetY = (config.offsetY != null) ? config.offsetY : 0; this.actor.getGlobalPosition(this.actorPosition); this.actor.getGlobalEulerAngles(this.actorAngles); this.body.mass = this.mass; this.body.type = (this.mass === 0) ? window.p2.Body.STATIC : window.p2.Body.DYNAMIC; this.body.material = SupEngine.P2.world.defaultMaterial; this.body.fixedRotation = this.fixedRotation; this.body.updateMassProperties(); this.shape = config.shape; switch (this.shape) { case "box": { this.width = (config.width != null) ? config.width : 0.5; this.height = (config.height != null) ? config.height : 0.5; this.angle = (config.angle != null) ? config.angle * (Math.PI / 180) : 0; this.body.addShape(new window.p2.Box({ width: this.width, height: this.height })); } break; case "circle": { this.radius = (config.radius != null) ? config.radius : 1; this.angle = 0; this.body.addShape(new window.p2.Circle({ radius: this.radius })); } break; } this.body.position = [this.actorPosition.x, this.actorPosition.y]; this.body.shapes[0].position = [this.offsetX, this.offsetY]; this.body.angle = this.actorAngles.z + this.angle; } update() { this.actorPosition.x = this.body.position[0]; this.actorPosition.y = this.body.position[1]; this.actor.setGlobalPosition(this.actorPosition); this.actorAngles.z = this.body.angle - this.angle; this.actor.setGlobalEulerAngles(this.actorAngles); } _destroy() { SupEngine.P2.world.removeBody(this.body); this.body = null; super._destroy(); } } exports.default = P2Body;
const args = require('minimist')( process.argv.slice(2), { default: { accounts: '../accounts.txt' }, alias: { accounts: ['a', 'acc'] } }) require('./consolescreens.js') const mineflayer = require('mineflayer') const pvpwarsPlugin = require('./pvpwars.plugin.js') const server = require('./settings.js').serverBlock const helper = require('./helper.js') ;(async function () { console.log('Starting the bot') console.log() const accounts = helper.readAccounts(args.accounts).filter(acc => acc.isMaster) for (const acc of accounts) { const username = acc.username const password = acc.password const bot = mineflayer.createBot({ host: 'pvpwars.net', port: 25565, username: username, password: password, version: '1.8', verbose: true, plugins: { pvpwarsPlugin } }) console.log() console.log('--- ' + username + ' ---') bot.on('login', () => { console.log('Username: ' + bot.username) }) try { await bot.pvpwars.selectServer(server) await bot.pvpwars.getCommandAccess() await bot.pvpwars.goHome() await bot.pvpwars.acceptAllTps() await levelDupePet(bot) } catch (err) { console.log(err) console.log('Disconnecting from minecraft') await bot.disconnectSafely() } await sleep(1000) } })() async function levelDupePet (bot) { bot.chatAddPattern(/.\/is coop (.*)/, 'isCoop') bot.on('isCoop', (msg) => { let username = msg.trim().split(' ')[0].trim() bot.chat('/is coop ' + username) console.log('Sending /is coop ' + username) console.log("'" + msg + "'") }) console.log('Waiting for some time') await sleep(30 * 1000) console.log(bot.inventory.slots.filter(it => it).map(it => JSON.stringify(it.nbt))) await sleep(10 * 1000) // start with only one type of spawners. // Start with one stack and one stac placed. // while true: // spawners // if first hand is not empty move item to empty space in inventory // get all spawners near us // create a map<spawner, count> // for each spawners near // while there is a stack of the type same type in the inventory // increase the map<spawner> += stack.count // place all spawners in the stack onto the spawners nearby // end // end // mine count spawners of every type const refSpawner = bot.findBlock({ matching: it => it && it.type === 52, maxDistance: 3 }) console.log(refSpawner) while (true) { bot.setQuickBarSlot(0) await sleep(100) bot.putAway(0) await sleep(100) let totalCount = 0 while (true) { const spawners = bot.inventory.slots .filter(it => it && it.type === refSpawner.type && it.metadata === refSpawner.metadata)[0] if (!spawners) break console.log(spawners) bot.transfer({ sourceStart: spawners.slot, destStart: 36, itemType: spawner.type, metadata: spawner.metadata }, (err) => { if (err) console.log(err) }) await sleep(1500) totalCount += spawners.count let i = 0 while (bot.inventory.slots[36] && bot.inventory.slots[36].count) { bot.placeBlock(refSpawner, new Vec3(0, 1, 0)) await sleep(500) if (i++ > 64 * 2) { console.log('Could not place spawners') break } } } // put pickaxe in first slot const pick = bot.inventory.slots.filter(it => it && it.name.indexOf('pickaxe') === -1)[0] bot.transfer({ sourceStart: pick.slot, destStart: 36, itemType: pick.type, metadata: pick.metadata }, (err) => { if (err) console.log(err) }) await (1500) while (totalCount--) { await digBlock(bot, refSpawner) await (100) } } } function digBlock (bot, block) { return new Promise((resolve, reject) => { bot.dig(block, (err) => { if (err) reject(err) else resolve() }) }) }
import React from 'react' import { ReactComponent as Comments } from './assets/comments.svg' import { ReactComponent as Likes } from './assets/likes.svg' import { ReactComponent as Reposts } from './assets/reposts.svg' import { ReactComponent as Views } from './assets/views.svg' const icons = { comments: Comments, likes: Likes, reposts: Reposts, views: Views } export default props => { const Icon = icons[props.type] return (<Icon { ...props } />) }
class MyChildren extends React.Component{ render(){ return ( <CardBlock> <Card content="This is card A." /> <Card content="This is card B." /> <Card content="This is card C." /> </CardBlock> ); } } class CardBlock extends React.Component{ render(){ return ( <div> {this.props.children} </div> ); } } class Card extends React.Component{ render(){ const cardStyle = { width: "100px", height: "30px", marginBotton: "20x", backgroundColor: "gray" }; return ( <div style={cardStyle}>{this.props.content}</div> ); } } ReactDOM.render( <MyChildren />, document.getElementById('myChildren') )
import React from "react"; import "./styles/botonesOpciones.css"; import items from '../items.json'; import salsa from '../images/salse.jpg'; import adiciones from '../images/adicion.jpg'; import hamburguesa from '../images/hamburguesa.jpg' function BotonesOpciones (props){ const facturaAdiciones = (element) => { let newObjeto = {name: element.name, price: element.price}; props.envio(oldArray => [...oldArray, newObjeto]) console.log(newObjeto); } const data = items; const listSalsa = []; const listTipo = []; const adicion = []; function filtrar (string, array) { return array.filter( item => item.type === string ) } let arrayEnviar = filtrar(props.tipoFiltro , data) arrayEnviar.forEach((element) => { if(element.type.includes('Salsas')){ listSalsa.push( <React.Fragment key={element.id}> <li className="listFact" key={element.id}> <div className='botones' type="button" value= {element.type} onClick={()=> {facturaAdiciones(element)} }> <img className='imgAdicion' src={salsa} alt='imagen' /> <div><center>{element.name}</center></div> </div> </li> </React.Fragment> ) } if(element.type.includes('Adición')){ listSalsa.push( <React.Fragment key={element.id}> <li className="listFact"> <div className='botones' type="button" value= {element.type} onClick={()=> {facturaAdiciones(element)} }> <img className='imgAdicion' src={adiciones} alt='imagen' /> <div><center>{element.name}</center></div> </div> </li> </React.Fragment> ) } if(element.type.includes('Tipo')){ listSalsa.push( <React.Fragment key={element.id}> <li className="listFact"> <div className='botones' type="button" value= {element.type} onClick={()=> {facturaAdiciones(element)} }> <img className='imgAdicion' src={hamburguesa} alt='imagen' /> <div><center>{element.name}</center></div> </div> </li> </React.Fragment> ) } }); return ( <div className='botonesOpciones'> <ul className='intentoList'> {listSalsa} </ul> <ul className='intentoList'> {listTipo} </ul> <ul className='intentoList'> {adicion} </ul> </div> ) // } } export default BotonesOpciones;
import Taro from '@tarojs/taro' import * as Service from '../service'; export default { namespace: 'productSelect', state: { searchTypes: [ { key: '商品名', value: 'productName' }, { key: '类别', value: 'customerType' }, { key: '备注', value: 'customerRemark' } ], prevModel: '', keyword: '', products: [], productList: [] }, effects: { * fetchProducts({ payload }, { put, call }) { const res = yield call(Service.getMaterials, payload) yield put({ type: 'save', payload }) if (res && res.data && res.data.length > 0) { yield put({ type: 'save', payload: { productList: res.data } }) } else { const { error } = res; if (!error === 'request:fail') { Taro.showToast({ title: '没有对应客户', icon: 'none', duration: 2200, }); } } } }, reducers: { save(state, { payload }) { return { ...state, ...payload } } } }
import localforage from 'localforage' import { app } from '~/services/firebaseConfig' export default { async initApp ({ rootState, commit, dispatch }) { if (this.$router.currentRoute.name === 'login') { commit('setAppStatus', 'loading') } await dispatch('demo/getDemoDataStatus', null, { root: true }) app.auth().onAuthStateChanged(async (user) => { if (this.$router.currentRoute.name === 'login') { commit('setAppStatus', 'loading') } if (user) { try { if (rootState.user.user && rootState.user.user.uid && rootState.user.user.uid !== user.uid) { dispatch('clearUserData') } await dispatch('user/initUser', user, { root: true }) await dispatch('currencies/initCurrencies', null, { root: true }) await dispatch('categories/initCategories', null, { root: true }) await dispatch('wallets/initWallets', null, { root: true }) await dispatch('trns/initTrns', null, { root: true }) await dispatch('groups/initGroups', null, { root: true }) await dispatch('lang/initDbLang', null, { root: true }) dispatch('trns/uploadOfflineTrns', null, { root: true }) if (this.$router.currentRoute.name === 'login') { this.app.context.redirect('/') setTimeout(() => { commit('setAppStatus', 'ready') }, 100) } } catch (e) { console.error(e) } } else { dispatch('clearUserData') } }) }, async initAppFromCache ({ commit, dispatch }, resolve) { dispatch('lang/initLocalLang', null, { root: true }) dispatch('ui/initUi', null, { root: true }) dispatch('chart/initChart', null, { root: true }) const [ativeTab, user, currencies, categories, wallets, trns, filterPeriod] = await Promise.all([ localforage.getItem('finapp.activeTab'), localforage.getItem('finapp.user'), localforage.getItem('finapp.currencies'), localforage.getItem('finapp.categories'), localforage.getItem('finapp.wallets'), localforage.getItem('finapp.trns'), localforage.getItem('finapp.filter.period') ]) if (ativeTab) { dispatch('ui/setActiveTab', ativeTab, { root: true }) } if (user) { commit('user/setUser', user, { root: true }) } if (currencies) { commit('currencies/setCurrencies', currencies, { root: true }) } if (categories) { commit('categories/setCategories', categories, { root: true }) } if (wallets) { commit('wallets/setWallets', wallets, { root: true }) } if (trns) { commit('trns/setTrns', trns, { root: true }) } if (filterPeriod) { dispatch('filter/setPeriod', filterPeriod, { root: true }) } // ready if (categories && user && trns && wallets) { if (this.$router.currentRoute.name === 'login') { this.app.context.redirect('/') } resolve() } else { resolve() } commit('setAppStatus', 'ready') }, async clearUserData ({ commit, dispatch }) { commit('setAppStatus', 'loading') dispatch('ui/setActiveTab', 'stat', { root: true }) await dispatch('user/setUser', null, { root: true }) await dispatch('categories/setCategories', null, { root: true }) await dispatch('wallets/setWallets', null, { root: true }) await dispatch('trns/setTrns', null, { root: true }) setTimeout(() => { commit('setAppStatus', 'ready') }, 100) } }
require('../js/app.js'); require('../css/post.css');
import createAsyncAction from '../../../createAsyncAction'; import ApiService from '../../services/api.service'; import HttpService from '../../services/http.service'; export const FETCH_EXAMPLE = '@@{{ component_name }}/FETCH_EXAMPLE'; export const FetchExampleAction = createAsyncAction(FETCH_EXAMPLE, () => { const options = ApiService.getOptions('fetchExample'); return HttpService.fetch(options); });
$('#post-form').on('submit', function (e) { //задаем действие при отправке данных формы аякс запросом e.preventDefault(); $.ajax({ url: '/ajax', type: 'POST', dataType: 'JSON', data: $('#post-form').serialize(), success: function (data) { if (data.msg==true){ //при успехе показываем кнопку Копировать кастомную ссылку $(".copyCust").show(); //скрываем кнопку кастомизации и выводим сообщение $(".msg").css('color', '#227dc7'); $(".msg").text('Your link confirmed and saved!!!'); $("#customUrl").attr('disabled', true); $(".btnCustomize").hide(); $(".newUrl").hide(); } else //при ошибке валидации выводим сообщение { $(".msg").css('color', '#e9605c'); $(".msg").text('You enter wrong link, try again!!!'); } }, error: function () { //при ошибке отправки выводим сообщение $('.msg').text('Error, try again!!!') } }); }); function copyToClipboard(id) { //функция для копирования ссылки из поля формы в буфер обмена const str = document.getElementById(id).value; //создаем за границами видимости текстовое поле, копируем в него значение const el = document.createElement('textarea'); //формы, из него копируем в буфер и удаляем текстовое поле el.value = str; el.setAttribute('readonly', ''); el.style.position = 'absolute'; el.style.left = '-9999px'; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el); }
const User = require("../modal/user.modal") const { StatusCodes } = require('http-status-codes') const jwt = require('jsonwebtoken') const { OAuth2Client } = require('google-auth-library') const client = new OAuth2Client('566957944883-4ovoi05bh8g3ktjqju57r7s2fgte1e36.apps.googleusercontent.com') // node mailer to send verify email const nodemailer = require('nodemailer') // to compare password in login const bcrypt = require("bcrypt"); //** regestration **// const sign_up = async (req, res) => { let { name, email, phone, location, password, confirm_password } = req.body try { // check if this email is exist const user = await User.findOne({ email }); if (user) { // is case email is exist res.status(StatusCodes.BAD_REQUEST).json({ message: 'this email is already exist' }) } else { if (password != confirm_password) { // in case confirm password is not match res.status(StatusCodes.BAD_REQUEST).json({ message: 'Both password should match' }) } else { // hash password using hooks and save in db const newUser = new User({ name, email, password, location, phone }); await newUser.save(); res.status(StatusCodes.CREATED).json({ message: 'created success', newUser }); //make a token and send him to user mail to verify his account const token = jwt.sign({ email: email }, process.env.SECRET_KEY); // information about sender const Transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.GMAIL_USER, pass: process.env.GMAIL_PASS, } }); // make a mail let info = await Transporter.sendMail({ from: `"golde-pizza" <foo@example.com>`, to: email, subject: 'verify your account', text: 'verify your account here', html: `<div> <p>verify your account here</p> <a href='${process.env.BASE_URL}/verifyUser/${token}'>verify </div>` }); } } } catch (error) { // catch error res.status(StatusCodes.BAD_REQUEST).json({ message: 'error in regestration', error }) } } //** login **// const sign_in = async (req, res) => { let { email, password } = req.body; try { // check if this email is sign up or no let user = await User.findOne({ email }) if (!user) { res.status(StatusCodes.BAD_REQUEST).json({ message: 'email is not found' }) } else { // check if this the password is correct const match = await bcrypt.compare(password, user.password) if (match) { const token = await jwt.sign({ _id: user._id, role: user.role }, process.env.SECRET_KEY, { expiresIn: '1d' }) console.log(process.env.SECRET_KEY); res.status(StatusCodes.OK).json({ message: 'login success', user, token }) } else { res.status(StatusCodes.BAD_REQUEST).json({ message: 'wrong password' }) } } } catch (error) { res.status(StatusCodes.BAD_REQUEST).json({ message: 'can not sign in', error }) } } //** login with google **// const sign_in_withGoogle = async (req, res) => { let { token } = req.body; client.verifyIdToken({ idToken: token, audience: '566957944883-4ovoi05bh8g3ktjqju57r7s2fgte1e36.apps.googleusercontent.com' }).then(async (result) => { console.log(result); let decoded = result.payload // check if this user is verified or no if (decoded.email_verified) { const user = await User.findOne({ email: decoded.email }) // check if this user is regesterd before or this the first time if (user) { // make a token to send it to front // const token = jwt.sign({ email: email }, process.env.SECRET_KEY); // console.log(process.env.SECRET_KEY); const token = jwt.sign({ email: decoded.email, role: 'user', isVerified: decoded.email_verified }, process.env.SECRET_KEY, { expiresIn: '1h' }); res.status(StatusCodes.OK).json({ message: 'login success', token }) } // if this is the first time for this user in my site i will save in database else { // make a token to send it to front const token = jwt.sign({ email: decoded.email, role: 'user', isVerified: decoded.email_verified }, process.env.SECRET_KEY, { expiresIn: '1h' }); // save in database const newUser = await User.insertMany({ email: decoded.email, name: decoded.name, isVerified: decoded.email_verified, role: 'user', phone: "not here", location: "not here", password: "not here", }) res.status(StatusCodes.CREATED).json({ message: 'created success ', token }) } } else { res.status(StatusCodes.BAD_REQUEST).json({ message: 'this email is not verified' }) } }).catch((error) => { console.log(error); res.status(StatusCodes.BAD_REQUEST).json({ message: error }) }) } // validate on token const verifyUser = async (req, res) => { let { token } = req.params; // console.log(token); //undefined // console.log(req.params); // {} console.log('hi before try'); try { const decoded = await jwt.verify(token, process.env.SECRET_KEY) console.log(decoded); const user = await User.findOne({ email: decoded.email }) console.log(user); if (user) { const newUser = await User.updateOne({ email: decoded.email }, { isVerified: true }) res.json({ message: 'updated success', newUser }) } else { res.json({ message: 'this acc is not here' }) } } catch (error) { res.json({ message: 'errrr verify', error }) } } const getAllUsers = async (req, res) => { try { const users = await User.find({}) if (users) { res.json({ message: 'all users is here', users }) } else { res.json({ message: 'no users here' }) } } catch (error) { res.json({ message: 'error in getting all users', error }) } } const getUserByEmail = async (req, res) => { let { email } = req.body; try { const user = await User.findOne({ email }) console.log(user); if (user) { res.json({ message: 'this user is here', user }) } else { res.json({ message: 'this user is not here' }) } } catch (error) { res.json({ message: 'error in getting this user', error }) } } const getUserByPhone = async (req, res) => { let { phone } = req.body; try { const user = await User.findOne({ phone }) console.log(user); if (user) { res.json({ message: 'this user is here', user }) } else { res.json({ message: 'this user is not here' }) } } catch (error) { res.json({ message: 'error in getting this user', error }) } } const blockUserByEmail = async (req, res) => { let { email } = req.body; try { const user = await User.findOne({ email }) console.log(user); if (user) { await User.updateOne({ email } ,{blocked:true}) res.json({ message: 'this user is blocked success', user }) } else { res.json({ message: 'this user is not here' }) } } catch (error) { res.json({ message: 'error in block this user', error }) } } const blockUserByPhone = async (req, res) => { let { phone } = req.body; console.log(phone); try { const user = await User.findOne({ phone }) const users = await User.find({ phone }) console.log(phone); console.log(users); console.log(user); if (user) { await User.updateOne({ phone } ,{blocked:true}) res.json({ message: 'this user is blocked success', user }) } else { res.json({ message: 'this user is not here' }) } } catch (error) { res.json({ message: 'error in block this user', error }) } } module.exports = { sign_up, sign_in, verifyUser, getAllUsers, sign_in_withGoogle, getUserByEmail, getUserByPhone , blockUserByEmail, blockUserByPhone } // console.log(decoded.payload); // let client = decoded.payload; // res.status(StatusCodes.OK).json({ msg: 'ok ya bro'}) // try { // // check if this email is sign up or no // let user = await User.findOne({ email:client.email }) // if (user) { // res.status(StatusCodes.BAD_REQUEST).json({ msg: 'login' }) // } else { // // check if this the password is correct // const match = await bcrypt.compare(password, user.password) // if (match) { // const token = await jwt.sign({ _id: user._id, role: user.role }, process.env.SECRET_KEY) // console.log(process.env.SECRET_KEY); // res.status(StatusCodes.OK).json({ msg: 'this user is here', user, token }) // } // else { // res.status(StatusCodes.BAD_REQUEST).json({ msg: 'wrong password' }) // } // } // } catch (error) { // res.status(StatusCodes.BAD_REQUEST).json({ msg: 'can not sign in', error }) // }
const express = require('express'); const app = express(); const path = require('path') var cookieParser = require('cookie-parser'); const apiRouter = require('./routes/index'); const port = 8080; const getPath = (file) => { return path.join(__dirname + file); } app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.use(express.static('public')); app.use(express.static('images')); // 사진 비교용 app.use(cookieParser()); app.use('/api', apiRouter) app.post('/cookie', (req, res) => { const token = req.cookies.token; res.json({ login: (token ? token : null) }); }) app.get('/', (req, res) => { res.sendFile(getPath('/views/home.html')); }) app.get('/login', (req, res) => { if (req.cookies.token) { return res.redirect('/'); } res.sendFile(getPath('/views/signin.html')) }) app.get('/signup', (req, res) => { res.sendFile(getPath('/views/signup.html')); }) app.get('/signupnext', (req, res) => { res.sendFile(getPath('/views/validateProfile.html')); }) app.get('/posts', (req, res) => { res.sendFile(getPath('/views/search_post.html')); }) app.get('/posts/write', (req, res) => { if (!req.cookies.token) { return res.redirect('/login'); } res.sendFile(getPath('/views/create_post.html')); }) app.post('/sendImg', (req, res) => { let base64StringUploadImage = req.uploadImage; // upload사진 let base64StringPicture = req.pictureImage; // 웹캡 사진 let base64UploadImage = base64StringUploadImage.split(';base64,').pop(); let base64PictureImage = base64StringPicture.split(';base64,').pop(); require("fs").writeFile("/images/upload.png", base64UploadImage, 'base64', function(err) { console.log(err); }); require("fs").writeFile("/images/picture.png", base64PictureImage, 'base64', function(err) { console.log(err); }); }) app.listen(port, () => { console.log("start server"); });
const USER_ID = Math.floor(Math.random() * 1000000001); class IM { constructor(client, userName) { return (async () => { // All async code here this.client = await client.login({ token: "", uid: userName, }); return this; // when done })(); } async createChannel(channelId) { let channel = await this.client.createChannel(channelId); channel.join(); } sendMsg() {} } // const useAgoraRtm = (userName, client) => { // // const [messages, setMessages] = useState<IMessage[]>([]); // // const channel = useRef(client.createChannel("channelId")).current; // // const color = useRef(randomColor({ luminosity: "dark" })).current; // const initRtm = async () => { // await client.login({ // uid: USER_ID.toString(), // }); // await channel.join(); // await client.setLocalUserAttributes({ // name: userName, // color, // }); // }; // useEffect(() => { // initRtm(); // // eslint-disable-next-line consistent-return // }, []); // useEffect(() => { // channel.on("ChannelMessage", (data, uid) => { // handleMessageReceived(data, uid); // }); // }, []); // const handleMessageReceived = async (data: RtmMessage, uid: string) => { // const user = await client.getUserAttributes(uid); // console.log(data); // if (data.messageType === "TEXT") { // const newMessageData = { user, message: data.text }; // setCurrentMessage(newMessageData); // } // }; // const [currentMessage, setCurrentMessage] = useState<IMessage>(); // const sendChannelMessage = async (text: string) => { // channel // .sendMessage({ text }) // .then(() => { // setCurrentMessage({ // user: { name: "Current User (Me)", color }, // message: text, // }); // }) // .catch((error) => { // console.log(error); // }); // }; // useEffect(() => { // if (currentMessage) setMessages([...messages, currentMessage]); // }, [currentMessage]); // return { sendChannelMessage, messages }; // }; export default IM;
import PersonModel from '../models/personsModel.js' import XlsGoogleParser from './xlsGoogleParser.js' import DateHelper from '../helper/dateHelper.js' import Jimp from 'jimp' import ImageHelper from '../helper/imageHelper.js' import StrHelper from '../helper/strHelper.js' export default class XlsGoogleParserPersons extends XlsGoogleParser { constructor(log) { super() this.log = log this.name = 'ВОВ. Герои' this.pageUrls = ['surname', 'name'] this.spreadsheetId = process.env.GOOGLE_SHEET_ID_PERSONS this.range = 'A1:Q' this.model = PersonModel // this.maxRow = 5 this.colCorresponds = { 'loadStatus': 'статус загрузки', 'surname': 'фамилия', 'name': 'имя', 'middlename': 'отчество', 'dateBirthStr': 'дата рождения', 'placeBirth': 'место рождения', 'isInvertor': 'изобретатель', 'activity': 'профессия', 'description': 'краткое описание', 'photoUrl': 'фото', 'dateDeathStr': 'дата смерти', 'placeDeath': 'место смерти', 'dateAchievementStr': 'дата подвига', 'placeAchievement': 'место подвига', 'fullDescription': 'полное описание', 'srcUrl': 'источник', 'links': 'дописточники' } } async getJsonFromRow(headerColumns, row) { let json = {errorArr: [], warningArr: [], lineSource: 0} try { json.surname = row[headerColumns.surname] json.name = row[headerColumns.name] json.middlename = row[headerColumns.middlename] json.dateBirth = DateHelper.ignoreAlterDate(row[headerColumns.dateBirthStr]) json.dateBirthStr = row[headerColumns.dateBirthStr] json.dateDeath = DateHelper.ignoreAlterDate(row[headerColumns.dateDeathStr]) json.dateDeathStr = row[headerColumns.dateDeathStr] json.dateAchievement = DateHelper.ignoreAlterDate(row[headerColumns.dateAchievementStr]) json.dateAchievementStr = row[headerColumns.dateAchievementStr] json.deathYearStr = DateHelper.betweenYearTwoDates( json.dateBirthStr, json.dateDeathStr) json.achievementYearStr = DateHelper.betweenYearTwoDates( json.dateBirthStr, json.dateAchievementStr) json.description = row[headerColumns.description] json.fullDescription = row[headerColumns.fullDescription] json.srcUrl = row[headerColumns.srcUrl] const pageUrl = this.getPageUrl(json) try { let photoUrl = row[headerColumns.photoUrl] if (photoUrl) { photoUrl = photoUrl.replaceAll('\\', '/') if (photoUrl[0] == '/') { const filename = StrHelper.getLastAfterDelim(photoUrl, '/') photoUrl = `public/img/person/${filename}` } else { const middleUrl = `public/img/person-middle/${pageUrl}.png` const res = await ImageHelper.loadImageToFile(photoUrl, middleUrl) if (res.error) { throw Error(`Не удалось обработать фото ${row[headerColumns.photoUrl]}`) } photoUrl = middleUrl } const destFullUrl = `public/img/person-full/${pageUrl}.png` let photo = await Jimp.read(photoUrl) await photo.getBufferAsync(Jimp.MIME_PNG) let writeResult = await photo.writeAsync(destFullUrl) const destShortUrl = `public/img/person-short/${pageUrl}.png` photo.resize(600, Jimp.AUTO).quality(100) writeResult = await photo.writeAsync(destShortUrl) json.photoFullUrl = `/img/person-full/${pageUrl}.png` json.photoShortUrl = `/img/person-short/${pageUrl}.png` } } catch (err) { // console.error(err) json.warningArr.push('' + err) } if (row[headerColumns.links]) { json.linkUrls = row[headerColumns.links].split(' http') json.linkUrls = json.linkUrls.filter(item => (item && item.length != 0)) json.linkUrls = json.linkUrls.map((item, idx) => (idx == 0 ? item : 'http' + item)) } json.placeAchievement = row[headerColumns.placeAchievementStr] json.placeAchievementCoords = await this.getCoords(row[headerColumns.placeAchievement]) if (!json.placeAchievementCoords) json.warningArr.push(`Не удалось найти координату достижения ${json.placeAchievement}`) json.placeBirth = row[headerColumns.placeBirth] json.placeBirthCoords = await this.getCoords(json.placeBirth) if (!json.placeBirthCoords) json.errorArr.push(`Не удалось найти координату рождения ${json.placeBirth}`) json.placeDeath = row[headerColumns.placeDeath] json.placeDeathCoords = await this.getCoords(json.placeDeath) if (!json.placeDeathCoords) json.errorArr.push(`Не удалось найти координату рождения ${json.placeDeath}`) json.activity = row[headerColumns.activity] json.isInvertor = row[headerColumns.isInvertor] == 'да' ? true : false } catch(err) { console.log(err) json.errorArr.push('' + err) } return json } }
// @flow /* eslint no-bitwise: 0 */ /* eslint no-plusplus: 0 */ /* ********************************************************** * File: test/factories/sensorsFactory.js * * Brief: Factory for creating pseudorandom sensor objects * * Authors: Craig Cheney * * 2017.09.22 CC - Document created * ********************************************************* */ import { micaIDs } from '../../app/utils/mica/micaConstants'; export function sensorFactory() { } /* [] - END OF FILE */
import React from 'react'; import { render } from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import App from './App'; import EventEmitter from 'events'; import getTheme from './themes'; import mkDebug from 'debug'; import parseUrl from 'url-parse'; const debug = mkDebug('budgeteer-landing'); const emitter = new EventEmitter(); global.emit = emitter.emit.bind(emitter); const root = document.querySelector('main'); function doRender({ theme, AppComponent = App } = {}) { const url = parseUrl(global.location.href, true); const themeName = getTheme(theme, url.query); debug(`Loaded theme ${themeName}`); render( <AppContainer><AppComponent theme={themeName} /></AppContainer>, root ); } emitter.once('onThemeChange', theme => doRender({ theme })); doRender(); if (module.hot) { /* eslint-disable global-require */ require('extract-text-webpack-plugin/hotModuleReplacement'); module.hot.accept('./App', () => { // If you use Webpack 2 in ES modules mode, you can // use <App /> here rather than require() a <NextApp />. const AppComponent = require('./App').default; doRender({ AppComponent }); }); /* eslint-enable global-require */ }
'use strict'; angular.module('Normal', ["chart.js"]) .controller('NormalController', function ($scope, $confirm, $uibModal, Notification) { $scope.colors = ['#E54125', '#059BFF', '#4BC0C0', '#FFCE56', '#E7E9ED']; $scope.dataSeries = ['Numeros Aleatorios']; $scope.onClick = function(points, evt) { }; $scope.datasetOverride = [{ yAxisID: 'y-axis-1' }]; $scope.options1 = { scales: { yAxes: [{ id: 'y-axis-1', type: 'linear', display: true, position: 'left', ticks: { beginAtZero: true } }] } }; $scope.disabledButton = false; $scope.randomNormal = function(media,sigma,cantidad, intervalos){ if(sigma<0) { Notification.error({message: 'Sigma no puede ser negativo', delay: 3000, replaceMessage: true}); return; } $scope.labels = new Array(); $scope.series = new Array(); $scope.data = new Array(); $scope.zetas = new Array(); $scope.randoms = new Array(); var max = -Number.MAX_VALUE, min = Number.MAX_VALUE; for (var i = 0; i < cantidad; i++) { var aux1 = Math.random(); var aux2 = Math.random(); var z = (Math.sqrt(-2*Math.log(aux1)))*Math.cos(2*Math.PI*aux2); var random = (media+(z*sigma)); $scope.zetas.push(random); if (max < random) { max = random; } if (min > random) { min = random; } if($scope.randoms.length < 5000) { $scope.randoms.push(random.toFixed(2)); } } // var max = Math.max(...$scope.zetas); // var min = Math.min(...$scope.zetas); $scope.paso = (max-min)/intervalos; for (var i = 1; i <= intervalos; i++) { min = (min + $scope.paso); $scope.labels.push(min); $scope.data.push(0); } for (var i = 0; i <= $scope.zetas.length; i++) { var labels = $scope.labels; var random = $scope.zetas[i]; for(var j = 0; j < labels.length; j++){ if(random <= labels[j]){ $scope.data[j]++; break; } } } for (var i = 0; i < $scope.labels.length; i++) { $scope.series.push(($scope.labels[i]-($scope.paso/2)).toFixed(2)); } if($scope.data.length > 0){ $scope.disabledButton = true; } }; $scope.random1 = function(media,sigma){ var aux1 = Math.random(); var aux2 = Math.random(); var z = (Math.sqrt(-2*Math.log(aux1)))*Math.cos(2*Math.PI*aux2); var random = (media+(z*sigma)); $scope.zetas.push(random); if($scope.randoms.length < 5000) { $scope.randoms.push(random.toFixed(2)); } for(var j = 0; j < $scope.labels.length; j++){ if(random <= $scope.labels[j]){ $scope.data[j]++; break; } } }; $scope.pruebaChi = function(media, sigma, cantidad, intervalos, alfa){ if(alfa<0 || alfa >1) { Notification.error({message: 'Alfa debe estar entre 0 y 1', delay: 3000, replaceMessage: true}); return; } $scope.frecuenciaEsperada = new Array(); $scope.suma = 0; $scope.sumaFrecuenciaEsperada = 0; $scope.arrayChi = new Array(); for(var i = 0; i < $scope.labels.length; i++){ var aux1 = jStat.normal.cdf($scope.labels[i], media, sigma); var aux2 = jStat.normal.cdf($scope.labels[i]-$scope.paso, media, sigma); var aux3 = (aux1-aux2)*cantidad; $scope.frecuenciaEsperada.push(aux3); $scope.sumaFrecuenciaEsperada = $scope.sumaFrecuenciaEsperada+aux3; } for(var i = 0; i < $scope.data.length; i++){ var aux = (Math.pow($scope.data[i]-$scope.frecuenciaEsperada[i], 2))/$scope.frecuenciaEsperada[i]; $scope.arrayChi.push(aux); $scope.suma = $scope.suma+aux; } $scope.gdl = intervalos - 2 - 1; $scope.chi = jStat.chisquare.inv(1-alfa,$scope.gdl); if($scope.suma<$scope.chi){ $scope.verifica = 'VERDADERO' } else { $scope.verifica = "FALSO" } }; });
import React from "react"; import classes from "./SectionStatus.module.css"; import { Link } from "react-router-dom"; const SectionStatus = (props) => { return( <> <div className = {classes.innerDiv}> <Link to = "problem" className = {classes.linkDesign}> <div className ={classes.statusDiv}> <div> <p className = {classes.TopicName}>{props.id}.)</p> <p className = {classes.TopicName}>{props.title}</p> </div> <p className = {classes.showStatus}>{props.status}</p> </div> </Link> </div> </> ) } export default SectionStatus
"usestrict" let message; const ADMIN_PASSWORD = "12Rat"; let password = prompt("Input your password, please", ); if ( password === null ) { message = 'Скасовано користувачем!'; } else if ( password == ADMIN_PASSWORD) { message = 'Ласкаво просимо!'; } else message = 'Доступ заборонений, невірний пароль!'; alert(message);
import { Container } from 'pixi.js'; /** * Base class for current game state representation * Provides utilities for state manipulation */ export default class State extends Container { constructor(name, gameContext) { super(); this.name = name; this.gameContext = gameContext; } /** * This method is called when current state becomes visible */ onStart() { } /** * This method is called right before hiding (changing) state to another */ onEnd() { } /** * Method for updating state * @param delta Default PIXI.Ticker deltaTime value */ update(delta) { } }
var API_getNewslistByPage = require("../../../../utils/config.js").API_getNewslistByPage, API_referQr = require("../../../../utils/config.js").API_referQr; var app = getApp(); Page({ onLoad() { // 页面初次加载,请求第一页数据 this.getNewslist(1,true) }, onShow() { wx.reportAnalytics('enter_home_programmatically', {}) }, onShareAppMessage() { return { title: '新闻列表', path: 'page/home/pages/news-list/news-list' } }, data: { pageNum:1, //当前第几页,默认从第1页查询 pages:0, //总页数 newsList: [], }, onReachBottom() { // 下拉触底,先判断是否有请求正在进行中 // 以及检查当前请求页数是不是小于数据总页数,如符合条件,则发送请求 console.log("onReachBottom.... ") if (!this.loading && this.data.pageNum < this.data.pages) { this.getNewslist(this.data.pageNum + 1) } }, onPullDownRefresh() { // 上拉刷新 console.log(" 上拉刷新onPullDownRefresh.... ") if (!this.loading) { this.getNewslist(1,true).then(() => { // 处理完成后,终止下拉刷新 wx.stopPullDownRefresh() }) } }, // 资讯 jumpNewsDetail: function (e) { console.log(e.currentTarget.dataset.newsId) var newsId = e.currentTarget.dataset.newsId; wx.navigateTo({ url: '../news-detail/news-detail?newsId=' + newsId, success: function (res) { // success }, fail: function () { // fail }, complete: function () { // complete } }) }, getNewslist(pageNum,override) { const self = this this.loading = true var pageSize = 10; // 向后端请求指定页码的数据 return this.getNewslistByPage(pageNum,pageSize).then(res => { if(res.data.code == 0){ //日期字符串截取 var newsList = res.data.pageInfo.list; newsList.forEach((item) => { item.createTime = item.createTime.substring(0, 10); var API_referQr = "https://golden-adviser.com:8443/" item.iconUrl = API_referQr + item.iconUrl; }) self.setData({ pageNum: pageNum, //当前的页号 pages: res.data.pageInfo.pages, //总页数 newsList: override ? newsList : this.data.newsList.concat(newsList) }) } }).catch(err => { console.log("==> [ERROR]", err) }).then(() => { self.loading = false }) }, getNewslistByPage: function (pageNum,pageSize) { return new Promise(function (resolve, reject) { wx.request({ url: API_getNewslistByPage, data: { pageNum:pageNum, pageSize:pageSize }, success(res) { resolve(res) }, fail(res) { var res = { code: 1, msg:'出错了' } reject(res); } }) }) } })
function ageInDays(){ var birthYear = prompt('What year were you born?'); var ageInDayss =(2020-birthYear)*365; var h1 = document.createElement('h1'); var textAnswer = document.createTextNode('You are '+ ageInDayss +' days old.'); h1.setAttribute('id','ageInDays'); h1.appendChild(textAnswer); document.getElementById('flex-box-result').appendChild(h1); } function reset(){ document.getElementById('ageInDays').remove(); } function generateCat(){ var d = new Date(); var image =document.createElement('img'); var div = document.getElementById('flex-cat-gen') image.src= "http://thecatapi.com/api/images/get?format=src&type=gif&size=small" + d.getTime(); div.appendChild(image); } function rpsGame(yourChoice){ console.log(yourChoice) var humanChoice, botChoice humanChoice = yourChoice.id botChoice = numberToChoice(randToRpsInt()) console.log('computer choice:', botChoice) result =decideWinner(humanChoice,botChoice); console.log(result) //[0,1] means human lose | bot win message = finalMessage(result) // {'message': 'you won'; 'color': "green"} console.log(message); rpsFrontEnd(yourChoice.id,botChoice,message); } function randToRpsInt(){ return Math.floor(Math.random()*3) } function numberToChoice(number){ return ['rock','paper','scissor'][number]; } function decideWinner(yourChoice,computerChoice){ var rpsDatabase = { 'rock': {'scissor': 1, 'rock': 0.5, 'paper':0}, 'paper': {'scissor': 0, 'rock': 1, 'paper': 0.5}, 'scissor':{'scissor': 0.5, 'rock': 0, 'paper':1}, } var yourScore = rpsDatabase[yourChoice][computerChoice]; var computerScore = rpsDatabase[computerChoice][yourChoice]; return [yourScore,computerScore] } function finalMessage([yourScore, computerScore]){ if(yourScore=== 0){ return {'message': 'you lost', 'color': 'red'};} else if(yourScore=== 0.5){ return {'message': 'you tied', 'color': 'blue'};} else{ return {'message': 'you win', 'color': 'green'};} } function rpsFrontEnd(humanImageChoice, botImageChoice, finalMessage){ var imageDatabase ={ 'rock': document.getElementById('rock').src, 'paper': document.getElementById('paper').src, 'scissor': document.getElementById('scissor').src, } //lets remove the pictures document.getElementById('rock').remove() document.getElementById('paper').remove() document.getElementById('scissor').remove() var humanDiv = document.createElement('div'); var botDiv = document.createElement('div'); var messageDiv = document.createElement('div'); humanDiv.innerHTML = "<img src='"+ imageDatabase[humanImageChoice] +"' height=150 width=150 style= 'box-shadow: 0px 10px 50px rgba(35,50,233,1) ;'>" messageDiv.innerHTML = "<h1 style = 'color : "+ finalMessage['color'] +"; font-size = 60px padding= 30px;'>" +finalMessage['message'] + "</h1>" botDiv.innerHTML = "<img src='"+ imageDatabase[botImageChoice] +"' height=150 width=150 style= 'box-shadow: 0px 10px 30px rgba(243,38,24,1) ;'>" document.getElementById('flex-box-rps-div').appendChild(humanDiv); document.getElementById('flex-box-rps-div').appendChild(messageDiv); document.getElementById('flex-box-rps-div').appendChild(botDiv); }
import React from 'react'; import { css } from 'react-emotion'; import { onlyUpdateForKeys } from 'recompose'; import { readableColor, transparentize, tint } from 'polished'; import { T } from 'ramda'; import { RIEInput } from 'riek'; import PropTypes from 'prop-types'; import { shevy, colors, transitionTimes, styles, bs, isCursor, mq } from '../../settings'; import { notEmpty } from '../../shared'; const validate = required => (required ? notEmpty : T); const headlineEditing = css({ border: 0, margin: 0, outline: 0, padding: 0, paddingRight: '0 !important', width: 'auto', boxShadow: 'none', display: 'inline-block' }); const headline = ({ headingStyles, color }) => { const singleLineHeight = headingStyles.lineHeight * parseInt(headingStyles.fontSize.replace('px', ''), 10); return css( headingStyles, mq({ color, position: 'relative', cursor: 'pointer', border: 0, margin: 0, outline: 0, padding: 0, paddingRight: bs(2), display: 'inline-block', maxWidth: '100%', '&::before': { content: '"Edit"', position: 'absolute', right: 0, top: singleLineHeight * 0.5, fontSize: 10, lineHeight: 1, backgroundColor: color, padding: styles.fn.pad(0.25, 0.25), color: readableColor(color), opacity: [0, 1], transform: ['translateY(-150%)', 'translateY(-50%)'], transition: `opacity ${transitionTimes.minimal}ms, transform ${ transitionTimes.minimal }ms ease-out`, willChange: 'opacity, transform' }, [`&:not(.${headlineEditing}):hover`]: { color: [transparentize(0.4, color), 'currentColor'], '&::before': { opacity: 1, transform: 'translateY(-50%)' } }, [`&.${headlineEditing}`]: { borderBottom: `1px dashed ${tint(0.3, color)}`, '&::selection': { backgroundColor: tint(0.1, color) } } }) ); }; const EditableHeadline = ({ value, onChange, required, headingStyles, color, ...props }) => ( <RIEInput value={value} propName="newValue" change={onChange} validate={validate(required)} className={headline({ headingStyles, color })} classEditing={headlineEditing} {...props} /> ); EditableHeadline.defaultProps = { headingStyles: shevy.h3, color: colors.black }; EditableHeadline.propTypes = { value: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, color: PropTypes.string, headingStyles: PropTypes.object }; const enhance = onlyUpdateForKeys(['value']); export default enhance(EditableHeadline);
const TestDataEnvironment = require('./resources/test-data-environment.js'); const jasmineReporters = require('jasmine-reporters'); const testDataEnvironment = new TestDataEnvironment(); // conf.js exports.config = { restartBrowserBetweenSuites: true, specs: ['**/*.spec.js'], suites: { e2e: 'e2e/**/*.spec.js', }, capabilities: { browserName: 'chrome', chromeOptions: { args: ['disable-infobars=true'], prefs: { credentials_enable_service: false, download: { prompt_for_download: false, default_directory: './downloads', }, }, }, }, jasmineNodeOpts: {}, onPrepare() { const env = jasmine.getEnv(); browser.waitForAngularEnabled(false); browser.driver.manage().window().maximize(); env.addReporter(new jasmineReporters.TapReporter({ })); }, params: testDataEnvironment, };
import React from 'react' import Heading from "../resuable/Heading" import TextField from "@material-ui/core/TextField" import { makeStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; export default function ContactForm() { const useStyles = makeStyles({ root: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', }, label: { textTransform: 'capitalize', }, }); const inputStyle = { width: "inherit", margin: "10px" } const buttonStyle = { marginLeft: "auto", marginRight: "auto" } const classes = useStyles(); return ( <section className="my-2"> <div className="container"> <Heading title="Contact us" /> <TextField id="id-name" label="Name" variant="outlined" style={inputStyle} /> <TextField id="id-email" label="Email" variant="outlined" style={inputStyle} /> <TextField id="id-message" label="Message" multiline rows={4} variant="outlined" style={inputStyle} /> <div className="text-center"> <Button classes={{ root: classes.root, // class name, e.g. `classes-nesting-root-x` label: classes.label, // class name, e.g. `classes-nesting-label-x` }} style={buttonStyle} > Submit </Button> </div> </div> </section> ) }
const btnTrigger = document.querySelector('.btnTrigger'); const notification = document.querySelector('.small-notif-notification'); const close = document.querySelector('.small-notif-close'); btnTrigger.addEventListener('click', (e) => { e.preventDefault(); // console.log(btnTrigger); if (!notification.classList.contains('small-notif-show')) { notification.classList.add('small-notif-show'); setTimeout(() => { notification.classList.remove('small-notif-show'); }, 3000); } document.body.scrollTop = 0; document.documentElement.scrollTop = 0; }); close.addEventListener('click', (e) => { e.preventDefault(); notification.classList.remove('small-notif-show'); });
$(document).ready(function () { /* var beatMe1 = document.getElementById('beat1'); var beatMe2 = document.getElementById('beat2'); var beatMe3 = document.getElementById('beat3'); var beatMe4 = document.getElementById('beat4'); var beatMe5 = document.getElementById('beat5'); var bassMe1 = document.getElementById('bass1'); var bassMe2 = document.getElementById('bass2'); var bassMe3 = document.getElementById('bass3'); var bassMe4 = document.getElementById('bass4'); var bassMe5 = document.getElementById('bass5'); var keyMe1 = document.getElementById('key1'); var keyMe2 = document.getElementById('key2'); var keyMe3 = document.getElementById('key3'); var keyMe4 = document.getElementById('key4'); var keyMe5 = document.getElementById('key5'); */ $('#create_beat').click(function() { for (var i = 1; i < 6; i++) { var beatMei = document.getElementById('beat'+i); beatMei.play(); } for (var i = 1; i < 6; i++) { var bassMei = document.getElementById('bass'+i); bassMei.play(); } for (var i = 1; i < 6; i++) { var keyMei = document.getElementById('key'+i); keyMei.play(); } for (var i = 1; i < 6; i++) { var miscMei = document.getElementById('misc'+i); miscMei.play(); } /* start playing all tracks beatMe1.play(); beatMe2.play(); beatMe3.play(); beatMe4.play(); beatMe5.play(); bassMe1.play(); bassMe2.play(); bassMe3.play(); bassMe4.play(); bassMe5.play(); keyMe1.play(); keyMe2.play(); keyMe3.play(); keyMe4.play(); keyMe5.play(); */ for (var i = 1; i < 6; i++) { document.getElementById('beat'+i).muted = true; } for (var i = 1; i < 6; i++) { document.getElementById('bass'+i).muted = true; } for (var i = 1; i < 6; i++) { document.getElementById('key'+i).muted = true; } for (var i = 1; i < 6; i++) { document.getElementById('misc'+i).muted = true; } /* mute all tracks document.getElementById('beat1').muted = true; document.getElementById('beat2').muted = true; document.getElementById('beat3').muted = true; document.getElementById('beat4').muted = true; document.getElementById('beat5').muted = true; document.getElementById('bass1').muted = true; document.getElementById('bass2').muted = true; document.getElementById('bass3').muted = true; document.getElementById('bass4').muted = true; document.getElementById('bass5').muted = true; document.getElementById('key1').muted = true; document.getElementById('key2').muted = true; document.getElementById('key3').muted = true; document.getElementById('key4').muted = true; document.getElementById('key5').muted = true; */ var rand0 = Math.floor(Math.random()*5); var rand1 = Math.floor(Math.random()*5); var rand2 = Math.floor(Math.random()*5); var rand3 = Math.floor(Math.random()*5); if (rand0 === 4) { toggle_drums1(); $('#drum').html("1") } else if (rand0 === 3) { toggle_drums2(); $('#drum').html("2") } if (rand0 === 2) { toggle_drums3(); $('#drum').html("3") } else if (rand0 === 1) { toggle_drums4(); $('#drum').html("4") } else if (rand0 === 0) { toggle_drums5(); $('#drum').html("5") } if (rand1 === 4) { toggle_bass1(); $('#bass').html("1") } else if (rand1 === 3) { toggle_bass2(); $('#bass').html("2") } if (rand1 === 2) { toggle_bass3(); $('#bass').html("3") } else if (rand1 === 1) { toggle_bass4(); $('#bass').html("4") } else if (rand1 === 0) { toggle_bass5(); $('#bass').html("5") } if (rand2 === 4) { toggle_key1(); $('#key').html("1") } else if (rand2 === 3) { toggle_key2(); $('#key').html("2") } if (rand2 === 2) { toggle_key3(); $('#key').html("3") } else if (rand2 === 1) { toggle_key4(); $('#key').html("4") } else if (rand2 === 0) { toggle_key5(); $('#key').html("5") } if (rand3 === 4) { toggle_misc1(); $('#misc').html("1") } else if (rand3 === 3) { toggle_misc2(); $('#misc').html("2") } if (rand3 === 2) { toggle_misc3(); $('#misc').html("3") } else if (rand3 === 1) { toggle_misc4(); $('#misc').html("4") } else if (rand3 === 0) { toggle_misc5(); $('#misc').html("5") } var audio_beat1 = document.getElementById('beat1'); var audio_beat2 = document.getElementById('beat2'); var audio_beat3 = document.getElementById('beat3'); var audio_beat4 = document.getElementById('beat4'); var audio_beat5 = document.getElementById('beat5'); var audio_bass1 = document.getElementById('bass1'); var audio_bass2 = document.getElementById('bass2'); var audio_bass3 = document.getElementById('bass3'); var audio_bass4 = document.getElementById('bass4'); var audio_bass5 = document.getElementById('bass5'); var audio_key1 = document.getElementById('key1'); var audio_key2 = document.getElementById('key2'); var audio_key3 = document.getElementById('key3'); var audio_key4 = document.getElementById('key4'); var audio_key5 = document.getElementById('key5'); var audio_misc1 = document.getElementById('misc1'); var audio_misc2 = document.getElementById('misc2'); var audio_misc3 = document.getElementById('misc3'); var audio_misc4 = document.getElementById('misc4'); var audio_misc5 = document.getElementById('misc5'); function toggle_drums1() { $('#mute_beat').click(function () { document.getElementById('beat1').muted = true; }); $('#play_beat').click(function () { if (audio_beat1.muted == false) { document.getElementById('beat1').muted = true; } else { audio_beat1.muted = true; document.getElementById('beat1').muted = false; } }); } function toggle_drums2() { $('#mute_beat').click(function () { document.getElementById('beat2').muted = true; }); $('#play_beat').click(function () { if (audio_beat2.muted == false) { document.getElementById('beat2').muted = true; } else { audio_beat2.muted = true; document.getElementById('beat2').muted = false; } }); } function toggle_drums3() { $('#mute_beat').click(function () { document.getElementById('beat3').muted = true; }); $('#play_beat').click(function () { if (audio_beat3.muted == false) { document.getElementById('beat3').muted = true; } else { audio_beat3.muted = true; document.getElementById('beat3').muted = false; } }); } function toggle_drums4() { $('#mute_beat').click(function () { document.getElementById('beat4').muted = true; }); $('#play_beat').click(function () { if (audio_beat4.muted == false) { document.getElementById('beat4').muted = true; } else { audio_beat4.muted = true; document.getElementById('beat4').muted = false; } }); } function toggle_drums5() { $('#mute_beat').click(function () { document.getElementById('beat5').muted = true; }); $('#play_beat').click(function () { if (audio_beat5.muted == false) { document.getElementById('beat5').muted = true; } else { audio_beat5.muted = true; document.getElementById('beat5').muted = false; } }); } function toggle_bass1() { $('#mute_bass').click(function () { document.getElementById('bass1').muted = true; }); $('#play_bass').click(function () { if (audio_bass1.mute == false) { document.getElementById('bass1').muted = true; } else { audio_bass1.mute = true; document.getElementById('bass1').muted = false; } }); } function toggle_bass2() { $('#mute_bass').click(function () { document.getElementById('bass2').muted = true; }); $('#play_bass').click(function () { if (audio_bass2.mute == false) { document.getElementById('bass2').muted = true; } else { audio_bass2.mute = true; document.getElementById('bass2').muted = false; } }); } function toggle_bass3() { $('#mute_bass').click(function () { document.getElementById('bass3').muted = true; }); $('#play_bass').click(function () { if (audio_bass3.mute == false) { document.getElementById('bass3').muted = true; } else { audio_bass3.mute = true; document.getElementById('bass3').muted = false; } }); } function toggle_bass4() { $('#mute_bass').click(function () { document.getElementById('bass4').muted = true; }); $('#play_bass').click(function () { if (audio_bass4.mute == false) { document.getElementById('bass4').muted = true; } else { audio_bass4.mute = true; document.getElementById('bass4').muted = false; } }); } function toggle_bass5() { $('#mute_bass').click(function () { document.getElementById('bass5').muted = true; }); $('#play_bass').click(function () { if (audio_bass5.mute == false) { document.getElementById('bass5').muted = true; } else { audio_bass5.mute = true; document.getElementById('bass5').muted = false; } }); } function toggle_key1() { $('#mute_keyboard').click(function () { document.getElementById('key1').muted = true; }); $('#play_keyboard').click(function () { if (audio_key1.mute == false) { document.getElementById('key1').muted = true; } else { audio_key1.mute = true; document.getElementById('key1').muted = false; } }); } function toggle_key2() { $('#mute_keyboard').click(function () { document.getElementById('key2').muted = true; }); $('#play_keyboard').click(function () { if (audio_key2.mute == false) { document.getElementById('key2').muted = true; } else { audio_key2.mute = true; document.getElementById('key2').muted = false; } }); } function toggle_key3() { $('#mute_keyboard').click(function () { document.getElementById('key3').muted = true; }); $('#play_keyboard').click(function () { if (audio_key3.mute == false) { document.getElementById('key3').muted = true; } else { audio_key3.mute = true; document.getElementById('key3').muted = false; } }); } function toggle_key4() { $('#mute_keyboard').click(function () { document.getElementById('key4').muted = true; }); $('#play_keyboard').click(function () { if (audio_key4.mute == false) { document.getElementById('key4').muted = true; } else { audio_key4.mute = true; document.getElementById('key4').muted = false; } }); } function toggle_key5() { $('#mute_keyboard').click(function () { document.getElementById('key5').muted = true; }); $('#play_keyboard').click(function () { if (audio_key5.mute == false) { document.getElementById('key5').muted = true; } else { audio_key5.mute = true; document.getElementById('key5').muted = false; } }); } function toggle_misc1() { $('#mute_misc').click(function () { document.getElementById('misc1').muted = true; }); $('#play_misc').click(function () { if (audio_misc1.mute == false) { document.getElementById('misc1').muted = true; } else { audio_misc1.mute = true; document.getElementById('misc1').muted = false; } }); } function toggle_misc2() { $('#mute_misc').click(function () { document.getElementById('misc2').muted = true; }); $('#play_misc').click(function () { if (audio_misc2.mute == false) { document.getElementById('misc2').muted = true; } else { audio_misc2.mute = true; document.getElementById('misc2').muted = false; } }); } function toggle_misc3() { $('#mute_misc').click(function () { document.getElementById('misc3').muted = true; }); $('#play_misc').click(function () { if (audio_misc3.mute == false) { document.getElementById('misc3').muted = true; } else { audio_misc3.mute = true; document.getElementById('misc3').muted = false; } }); } function toggle_misc4() { $('#mute_misc').click(function () { document.getElementById('misc4').muted = true; }); $('#play_misc').click(function () { if (audio_misc4.mute == false) { document.getElementById('misc4').muted = true; } else { audio_misc4.mute = true; document.getElementById('misc4').muted = false; } }); } function toggle_misc5() { $('#mute_misc').click(function () { document.getElementById('misc5').muted = true; }); $('#play_misc').click(function () { if (audio_misc5.mute == false) { document.getElementById('misc5').muted = true; } else { audio_misc5.mute = true; document.getElementById('misc5').muted = false; } }); } $('#previous_bass').click(function () { if (document.getElementById('bass1').muted == false) { document.getElementById('bass1').muted = true; document.getElementById('bass5').muted = false; toggle_bass5(); $('#bass').html('5'); } else if (document.getElementById('bass2').muted == false) { document.getElementById('bass2').muted = true; document.getElementById('bass1').muted = false; toggle_bass1(); $('#bass').html('1'); } else if (document.getElementById('bass3').muted == false) { document.getElementById('bass3').muted = true; document.getElementById('bass2').muted = false; toggle_bass2(); $('#bass').html('2'); } else if (document.getElementById('bass4').muted == false) { document.getElementById('bass4').muted = true; document.getElementById('bass3').muted = false; toggle_bass3(); $('#bass').html('3'); } else if (document.getElementById('bass5').muted == false) { document.getElementById('bass5').muted = true; document.getElementById('bass4').muted = false; toggle_bass4(); $('#bass').html('4'); } }) $('#next_bass').click(function () { if (document.getElementById('bass1').muted == false) { document.getElementById('bass1').muted = true; document.getElementById('bass2').muted = false; toggle_bass2(); $('#bass').html('2'); } else if (document.getElementById('bass2').muted == false) { document.getElementById('bass2').muted = true; document.getElementById('bass3').muted = false; toggle_bass3(); $('#bass').html('3'); } else if (document.getElementById('bass3').muted == false) { document.getElementById('bass3').muted = true; document.getElementById('bass4').muted = false; toggle_bass4(); $('#bass').html('4'); } else if (document.getElementById('bass4').muted == false) { document.getElementById('bass4').muted = true; document.getElementById('bass5').muted = false; toggle_bass5(); $('#bass').html('5'); } else if (document.getElementById('bass5').muted == false) { document.getElementById('bass5').muted = true; document.getElementById('bass1').muted = false; toggle_bass1(); $('#bass').html('1'); } }) $('#previous_drums').click(function () { if (document.getElementById('beat1').muted == false) { document.getElementById('beat1').muted = true; document.getElementById('beat5').muted = false; toggle_drums5(); $('#drum').html('5'); } else if (document.getElementById('beat2').muted == false) { document.getElementById('beat2').muted = true; document.getElementById('beat1').muted = false; toggle_drums1(); $('#drum').html('1'); } else if (document.getElementById('beat3').muted == false) { document.getElementById('beat3').muted = true; document.getElementById('beat2').muted = false; toggle_drums2(); $('#drum').html('2'); } else if (document.getElementById('beat4').muted == false) { document.getElementById('beat4').muted = true; document.getElementById('beat3').muted = false; toggle_drums3(); $('#drum').html('3'); } else if (document.getElementById('beat5').muted == false) { document.getElementById('beat5').muted = true; document.getElementById('beat4').muted = false; toggle_drums4(); $('#drum').html('4'); } }) $('#next_drums').click(function () { if (document.getElementById('beat1').muted == false) { document.getElementById('beat1').muted = true; document.getElementById('beat2').muted = false; toggle_drums2(); $('#drum').html('2'); } else if (document.getElementById('beat2').muted == false) { document.getElementById('beat2').muted = true; document.getElementById('beat3').muted = false; toggle_drums3(); $('#drum').html('3'); } else if (document.getElementById('beat3').muted == false) { document.getElementById('beat3').muted = true; document.getElementById('beat4').muted = false; toggle_drums4(); $('#drum').html('4'); } else if (document.getElementById('beat4').muted == false) { document.getElementById('beat4').muted = true; document.getElementById('beat5').muted = false; toggle_drums5(); $('#drum').html('5'); } else if (document.getElementById('beat5').muted == false) { document.getElementById('beat5').muted = true; document.getElementById('beat1').muted = false; toggle_drums1(); $('#drum').html('1'); } }) $('#next_keyboard').click(function () { if (document.getElementById('key1').muted == false) { document.getElementById('key1').muted = true; document.getElementById('key2').muted = false; toggle_key2(); $('#key').html('2'); } else if (document.getElementById('key2').muted == false) { document.getElementById('key2').muted = true; document.getElementById('key3').muted = false; toggle_key3(); $('#key').html('3'); } else if (document.getElementById('key3').muted == false) { document.getElementById('key3').muted = true; document.getElementById('key4').muted = false; toggle_key4(); $('#key').html('4'); } else if (document.getElementById('key4').muted == false) { document.getElementById('key4').muted = true; document.getElementById('key5').muted = false; toggle_key5(); $('#key').html('5'); } else if (document.getElementById('key5').muted == false) { document.getElementById('key5').muted = true; document.getElementById('key1').muted = false; toggle_key1(); $('#key').html('1'); } }) $('#previous_keyboard').click(function () { if (document.getElementById('key1').muted == false) { document.getElementById('key1').muted = true; document.getElementById('key5').muted = false; toggle_key5(); $('#key').html('5'); } else if (document.getElementById('key2').muted == false) { document.getElementById('key2').muted = true; document.getElementById('key1').muted = false; toggle_key1(); $('#key').html('1'); } else if (document.getElementById('key3').muted == false) { document.getElementById('key3').muted = true; document.getElementById('key2').muted = false; toggle_key2(); $('#key').html('2'); } else if (document.getElementById('key4').muted == false) { document.getElementById('key4').muted = true; document.getElementById('key3').muted = false; toggle_key3(); $('#key').html('3'); } else if (document.getElementById('key5').muted == false) { document.getElementById('key5').muted = true; document.getElementById('key4').muted = false; toggle_key4(); $('#key').html('4'); } }) $('#next_misc').click(function () { if (document.getElementById('misc1').muted == false) { document.getElementById('misc1').muted = true; document.getElementById('misc2').muted = false; toggle_misc2(); $('#misc').html('2'); } else if (document.getElementById('misc2').muted == false) { document.getElementById('misc2').muted = true; document.getElementById('misc3').muted = false; toggle_misc3(); $('#misc').html('3'); } else if (document.getElementById('misc3').muted == false) { document.getElementById('misc3').muted = true; document.getElementById('misc4').muted = false; toggle_misc4(); $('#misc').html('4'); } else if (document.getElementById('misc4').muted == false) { document.getElementById('misc4').muted = true; document.getElementById('misc5').muted = false; toggle_misc5(); $('#misc').html('5'); } else if (document.getElementById('misc5').muted == false) { document.getElementById('misc5').muted = true; document.getElementById('misc1').muted = false; toggle_misc1(); $('#key').html('1'); } }) $('#previous_misc').click(function () { if (document.getElementById('misc1').muted == false) { document.getElementById('misc1').muted = true; document.getElementById('misc5').muted = false; toggle_misc5(); $('#misc').html('5'); } else if (document.getElementById('misc2').muted == false) { document.getElementById('misc2').muted = true; document.getElementById('misc1').muted = false; toggle_misc1(); $('#misc').html('1'); } else if (document.getElementById('misc3').muted == false) { document.getElementById('misc3').muted = true; document.getElementById('misc2').muted = false; toggle_misc2(); $('#misc').html('2'); } else if (document.getElementById('misc4').muted == false) { document.getElementById('misc4').muted = true; document.getElementById('misc3').muted = false; toggle_misc3(); $('#misc').html('3'); } else if (document.getElementById('misc5').muted == false) { document.getElementById('misc5').muted = true; document.getElementById('misc4').muted = false; toggle_misc4(); $('#misc').html('4'); } }) }); $( "#bass_slider" ).slider({ value : 75, step : 1, range : 'min', min : 0, max : 100, change : function(){ var value = $("#bass_slider").slider("value"); document.getElementById("bass1").volume = (value / 100); document.getElementById("bass2").volume = (value / 100); document.getElementById("bass3").volume = (value / 100); document.getElementById("bass4").volume = (value / 100); document.getElementById("bass5").volume = (value / 100); } }); $( "#drums_slider" ).slider({ value : 75, step : 1, range : 'min', min : 0, max : 100, change : function(){ var value = $("#drums_slider").slider("value"); document.getElementById("beat1").volume = (value / 100); document.getElementById("beat2").volume = (value / 100); document.getElementById("beat3").volume = (value / 100); document.getElementById("beat4").volume = (value / 100); document.getElementById("beat5").volume = (value / 100); } }); $( "#keyboard_slider" ).slider({ value : 75, step : 1, range : 'min', min : 0, max : 100, change : function(){ var value = $("#keyboard_slider").slider("value"); document.getElementById("key1").volume = (value / 100); document.getElementById("key2").volume = (value / 100); document.getElementById("key3").volume = (value / 100); document.getElementById("key4").volume = (value / 100); document.getElementById("key5").volume = (value / 100); } }); $( "#misc_slider" ).slider({ value : 75, step : 1, range : 'min', min : 0, max : 100, change : function(){ var value = $("#misc_slider").slider("value"); document.getElementById("misc1").volume = (value / 100); document.getElementById("misc2").volume = (value / 100); document.getElementById("misc3").volume = (value / 100); document.getElementById("misc4").volume = (value / 100); document.getElementById("misc5").volume = (value / 100); } }); $('#create_beat').click(function () { $('#play_bass').click(); $('#play_beat').click(); $('#play_keyboard').click(); $('#play_misc').click(); }); $('#refresh').click(function () { location.reload(); }); })
/** * ER (Enterprise RIA) * Copyright 2013 Baidu Inc. All rights reserved. * * @file 杂而乱的工具对象 * @author otakustay, errorrik */ /** * * Modified on June 2013 * To fit in the Baidu frontia JS SDK framework. * @author tongyao@baidu.com */ baidu.frontia.util = {}; (function (namespace_) { var now = +new Date(); /** * 工具模块,放一些杂七杂八的东西 */ var util = {}; /** * 获取一个唯一的ID * * @return {number} 一个唯一的ID */ util.guid = function () { return 'baidu_frontia_' + now++; }; /** * 混合多个对象 * * @param {Object} source 源对象 * @param {...Object} destinations 用于混合的对象 * @return 返回混合了`destintions`属性的`source`对象 */ util.mix = function (source) { for (var i = 1; i < arguments.length; i++) { var destination = arguments[i]; // 就怕有人传**null**之类的进来 if (!destination) { continue; } // 这里如果`destination`是字符串的话,会遍历出下标索引来, // 认为这是调用者希望的效果,所以不作处理 for (var key in destination) { if (destination.hasOwnProperty(key)) { source[key] = destination[key]; } } } return source; }; /** * 空函数 * * @type {function} * @const */ util.noop = function () {}; /** * 将一段文本变为JSON对象 * * @param {string} text 文本内容 * @return {*} 对应的JSON对象 */ util.parseJSON = function (text) { if (window.JSON && typeof JSON.parse === 'function') { return JSON.parse(text); } else { return eval('(' + text + ')'); } }; var whitespace = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g; /** * 移除字符串前后空格字符 * * @param {string} source 源字符串 * @return {string} 移除前后空格后的字符串 */ util.trim = function (source) { return source.replace(whitespace, ''); }; /** * 对字符中进行HTML编码 * * @param {string} 源字符串 * @param {string} HTML编码后的字符串 */ util.encodeHTML = function (source) { source = source + ''; return source .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); }; /** * 将参数对象转换为URL字符串 * * @param {Object} query 参数对象 * @return {string} 转换后的URL字符串,相当于search部分 */ util.serializeURL = function (query) { if (!query) { return ''; } var search = ''; for (var key in query) { if (query.hasOwnProperty(key)) { var value = query[key]; // 如果`value`是数组,其`toString`会自动转为逗号分隔的字符串 search += '&' + encodeURIComponent(key) + '=' + encodeURIComponent(value); } } return search.slice(1); }; /** * base64 tool */ (function(global) { 'use strict'; if (global.Base64) return; var version = "2.1.2"; // if node.js, we use Buffer var buffer; if (typeof module !== 'undefined' && module.exports) { buffer = require('buffer').Buffer; } // constants var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var b64tab = function(bin) { var t = {}; for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i; return t; }(b64chars); var fromCharCode = String.fromCharCode; // encoder stuff var cb_utob = function(c) { if (c.length < 2) { var cc = c.charCodeAt(0); return cc < 0x80 ? c : cc < 0x800 ? (fromCharCode(0xc0 | (cc >>> 6)) + fromCharCode(0x80 | (cc & 0x3f))) : (fromCharCode(0xe0 | ((cc >>> 12) & 0x0f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | ( cc & 0x3f))); } else { var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00); return (fromCharCode(0xf0 | ((cc >>> 18) & 0x07)) + fromCharCode(0x80 | ((cc >>> 12) & 0x3f)) + fromCharCode(0x80 | ((cc >>> 6) & 0x3f)) + fromCharCode(0x80 | ( cc & 0x3f))); } }; var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g; var utob = function(u) { return u.replace(re_utob, cb_utob); }; var cb_encode = function(ccc) { var padlen = [0, 2, 1][ccc.length % 3], ord = ccc.charCodeAt(0) << 16 | ((ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8) | ((ccc.length > 2 ? ccc.charCodeAt(2) : 0)), chars = [ b64chars.charAt( ord >>> 18), b64chars.charAt((ord >>> 12) & 63), padlen >= 2 ? '=' : b64chars.charAt((ord >>> 6) & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63) ]; return chars.join(''); }; var btoa = global.btoa || function(b) { return b.replace(/[\s\S]{1,3}/g, cb_encode); }; var _encode = buffer ? function (u) { return (new buffer(u)).toString('base64') } : function (u) { return btoa(utob(u)) } ; var encode = function(u, urisafe) { return !urisafe ? _encode(u) : _encode(u).replace(/[+\/]/g, function(m0) { return m0 == '+' ? '-' : '_'; }).replace(/=/g, ''); }; var encodeURI = function(u) { return encode(u, true) }; // decoder stuff var re_btou = new RegExp([ '[\xC0-\xDF][\x80-\xBF]', '[\xE0-\xEF][\x80-\xBF]{2}', '[\xF0-\xF7][\x80-\xBF]{3}' ].join('|'), 'g'); var cb_btou = function(cccc) { switch(cccc.length) { case 4: var cp = ((0x07 & cccc.charCodeAt(0)) << 18) | ((0x3f & cccc.charCodeAt(1)) << 12) | ((0x3f & cccc.charCodeAt(2)) << 6) | (0x3f & cccc.charCodeAt(3)), offset = cp - 0x10000; return (fromCharCode((offset >>> 10) + 0xD800) + fromCharCode((offset & 0x3FF) + 0xDC00)); case 3: return fromCharCode( ((0x0f & cccc.charCodeAt(0)) << 12) | ((0x3f & cccc.charCodeAt(1)) << 6) | (0x3f & cccc.charCodeAt(2)) ); default: return fromCharCode( ((0x1f & cccc.charCodeAt(0)) << 6) | (0x3f & cccc.charCodeAt(1)) ); } }; var btou = function(b) { return b.replace(re_btou, cb_btou); }; var cb_decode = function(cccc) { var len = cccc.length, padlen = len % 4, n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) | (len > 3 ? b64tab[cccc.charAt(3)] : 0), chars = [ fromCharCode( n >>> 16), fromCharCode((n >>> 8) & 0xff), fromCharCode( n & 0xff) ]; chars.length -= [0, 0, 2, 1][padlen]; return chars.join(''); }; var atob = global.atob || function(a){ return a.replace(/[\s\S]{1,4}/g, cb_decode); }; var _decode = buffer ? function(a) { return (new buffer(a, 'base64')).toString() } : function(a) { return btou(atob(a)) }; var decode = function(a){ return _decode( a.replace(/[-_]/g, function(m0) { return m0 == '-' ? '+' : '/' }) .replace(/[^A-Za-z0-9\+\/]/g, '') ); }; // export Base64 global.mix(global, { VERSION: version, atob: atob, btoa: btoa, fromBase64: decode, toBase64: encode, utob: utob, encode: encode, encodeURI: encodeURI, btou: btou, decode: decode }); })(util); util.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; } namespace_.util = util; } )(baidu.frontia);
import React from 'react' import { Draggable } from 'react-beautiful-dnd' import PropTypes from 'prop-types' import s from './DraggableItem.css' import DeleteIcon from '@components/icons/DeleteIcon' import GeoIcon from '@components/icons/GeoIcon' const DraggableItem = ({ itemData, onItemRemove, onItemClick, onShowDetails }) => { const onClick = (e) => { e.stopPropagation() onItemRemove(itemData.id) } return ( <Draggable draggableId={itemData.id}> {provided => ( <div> <div className={s.item} style={provided.draggableStyle} ref={provided.innerRef} {...provided.dragHandleProps} > <div onClick={() => onShowDetails(itemData.wID)} className={s.content}> <span>{itemData.content}</span> </div> <div className={s.buttonsBlock}> <button className={s.button} onClick={onClick}> <DeleteIcon /> </button> <button className={s.button} onClick={() => onItemClick(itemData.position)} > <GeoIcon /> </button> </div> </div> {provided.placeholder} </div> )} </Draggable> ) } export default DraggableItem DraggableItem.propTypes = { itemData: PropTypes.shape({ id: PropTypes.number, content: PropTypes.string, position: PropTypes.arrayOf(PropTypes.number), }).isRequired, onItemRemove: PropTypes.func.isRequired, onItemClick: PropTypes.func.isRequired, onShowDetails: PropTypes.func.isRequired, }
//all of the variables used on cover page of the quiz var backgroundImg, coverImg, quiztitleImg, quiztitle, toppictureframeImg, toppictureframe, midpictureframeImg var midpictureframe, bottompictureframe, bottompictureframeImg, toppictureframephotoImg, toppictureframephoto var midpictureframephoto, midpictureframephotoImg, bottompictureframephoto, bottompictureframephotoImg var level1Img, level1, level2, level2Img var music_play, music_playImg var music_stop, music_stopImg, bgmusic var flag = true; function preload() { //loading all the images for the cover page of the quiz backgroundImg = loadImage("Quiz/Quiz/images/bg1-sheet0.png"); quiztitleImg = loadImage("Quiz/Quiz/images/title-sheet0.png"); toppictureframeImg = loadImage("Quiz/Quiz/images/topim-sheet0.png"); midpictureframeImg = loadImage("Quiz/Quiz/images/midim-sheet0.png"); bottompictureframeImg = loadImage("Quiz/Quiz/images/botim-sheet0.png"); toppictureframephotoImg = loadImage("Quiz/Quiz/images/sprite3-sheet0.png"); midpictureframephotoImg = loadImage("Quiz/Quiz/images/sprite4-sheet0.png"); bottompictureframephotoImg = loadImage("Quiz/Quiz/images/sprite5-sheet0.png"); level1Img = loadImage("Quiz/Quiz/images/easybutton-sheet0.png"); level2Img = loadImage("Quiz/Quiz/images/hardbutton-sheet0.png"); music_playImg = loadImage("Quiz/Quiz/images/mute-sheet1.png"); music_stopImg = loadImage("Quiz/Quiz/images/mute-sheet0.png"); bgmusic = loadSound("Quiz/Quiz/media/background music.ogg"); } function setup() { //setting the canvas size var canvas = createCanvas(1400, 620); //setting the background of the cover page coverImg = createSprite(690, 300, 800, 800); coverImg.addImage("pujyashreephoto", backgroundImg); coverImg.scale = 0.65; //adding in the quiz title quiztitle = createSprite(1050, 100, 450, 100); quiztitle.addImage("title_of_the_quiz", quiztitleImg); quiztitle.scale = 0.7; //setting up the picture frames //adding the top frame toppictureframe = createSprite(230, 180, 100, 100); toppictureframe.addImage("toppictureframeforcoverpageofquiz", toppictureframeImg); toppictureframe.scale = 0.5; //adding the photo in the top frame toppictureframephoto = createSprite(188, 160, 100, 100); toppictureframephoto.addImage("picturetoputinthetopframe", toppictureframephotoImg); toppictureframephoto.scale = 0.5 //adding the middle frame midpictureframe = createSprite(290, 300, 100, 100); midpictureframe.addImage("midpictreframeforcoverpageofquiz", midpictureframeImg); midpictureframe.scale = 0.5; //adding the photo in the middle frame midpictureframephoto = createSprite(281, 285, 100, 100); midpictureframephoto.addImage("picturetoputinthemiddleframe", midpictureframephotoImg); midpictureframephoto.scale = 0.5; //adding the bottom picture frame bottompictureframe = createSprite(330, 420, 100, 100); bottompictureframe.addImage("bottompictureframeforcoverpageofquiz", bottompictureframeImg); bottompictureframe.scale = 0.5 //adding the photo in the bottom frame bottompictureframephoto = createSprite(326, 427, 100, 100); bottompictureframephoto.addImage("phototoputinthebottomframe", bottompictureframephotoImg); bottompictureframephoto.scale = 0.5 //creating the level 1 object level1 = createSprite(1050, 230, 200, 50); level1.addImage("level1display", level1Img); level1.scale = 0.7 //creating the level 2 object level2 = createSprite(1050, 330, 200, 50); level2.addImage("level2display", level2Img); level2.scale = 0.7; //creating the sound object music_play = createSprite(1250, 568, 50, 50); music_play.addImage("unmuted sound", music_playImg); //creating the muted object music_stop = createSprite(1245, 564, 50, 50); music_stop.addImage("mutedsound", music_stopImg); music_stop.visible = false; // won't work } function draw() { background("black"); if (flag) { console.log("here") bgmusic.play(); flag = false; } if (mousePressedOver(music_play)) { console.log("stop") bgmusic.stop() } drawSprites(); // level 1 display textSize(30); fill(0); text("Level 1", 1000, 220, 200, 50); //level 2 display textSize(30) fill(0) text("Level 2", 1000, 320, 200, 50); } //function clicked(){ //let d= dist(mouseX, mouseY, this.x, this.y); //if(d< this.r){ // console.log("CLICKED ON THE SOUND BUTTON!", d); // bgmusic.stop(); // music_play.changeImage(music_stop); // music_stop.visible=true; // music_play.visible=false; // } //} //function mousePressed(){ // clicked(); //} //else if(d<24)){ //bgmusic.play(); // music_stop.changeImage(music_play); //}
require('./bundle.js') module.exports.search = global.search module.exports.alexa = global.alexa module.exports.suggest = global.suggest
var slice = Object.call.bind(Array.prototype.slice); var forEach = Object.call.bind(Array.prototype.forEach); var isToken = RegExp.prototype.test.bind(/^[A-Z]+$/); function Statement(token, expression, param){ this.token = token; if(expression) this.expression = expression; if(param!==undefined) this.param = param; } var Empty = new Statement(); function Param(value, token){ if(!(this instanceof Param)) return new Param(value, token); if(value!==undefined) this.v=value; if(token) this.token = token; } Param.prototype = { get DESC() { return new Param(this.v, 'DESC'); }, get ASC() { return new Param(this.v, 'ASC'); }, toString: function(){ var tkn = this.token? this.token : '$'; return "[" + tkn + " Param]"; } } function Group(token, args){ var group = [], i=0; group.token=token; if(args && args.length){ //$(expression[,param]) if(typeof args[0]==="string" && token!='_'){ var param = args[1]; if(param instanceof Param){ i=2; if(param.hasOwnProperty("v")) group.push(new Statement(token, args[0], param)); } else{ i=1; group.push(new Statement(token, args[0])); } } for(;i<args.length;i++){ var arg = args[i]; if(typeof arg==="function" && isToken(arg.name)){ //the next arg must be the expression and then maybe a param var subargs = [args[++i]]; var param = args[i+1]; if(param instanceof Param){ i++; subargs.push(param) } var member = tokens[arg.name].apply(this, subargs); if(member!==Empty) group.push(member); } else if((arg instanceof Statement && arg!==Empty) || (Array.isArray(arg) && arg.token)){ group.push(arg); } else if(arg instanceof Param){ if(arg.hasOwnProperty("v")) group.push(arg); } else if(arg instanceof Context){ Array.prototype.splice.apply(args, [i+1,0].concat(arg.out)); } else if(typeof arg==="string"){ group.push(new Statement('_', arg)); } else if(typeof arg==="object" && arg!==Empty){ Object.keys(arg).forEach(function(k) { group.push(tokens.AND(k+'=', tokens.$(arg[k]))); }); } } } if(!group.length) return Empty; //look for a redundant member if(group.length===1){ var token0 = group[0].token; if(token0===token || token0 == '$'){ group[0].token = token; return group[0]; } } return group; } function NumberOnly(token, number){ if(isNaN(number)) number = 0; return new Statement(token, number.toString()); } var tokens = module.exports = { $: function $(arg0){ if(arguments.length<=1 && (!(arg0 instanceof Statement) || typeof arg0==="undefined")){ return Param(arg0); } return Group('$', arguments); }, _: function _(){ return Group('_', arguments); }, AND: function AND(){ return Group('AND', arguments); }, OR: function OR(){ return Group('OR', arguments); }, ON: function ON(){ return Group('ON', arguments); }, WHERE: function WHERE(){ return Group('WHERE', arguments); }, "DELETE FROM": function(table){ if(typeof table!=="string") return Empty; return new Statement('DELETE FROM', table); }, "INSERT INTO": function(table, data){ if(typeof table !== "string" || !data) return Empty; var columns = Object.keys(data); if(columns.length===0) return Empty; var params = []; columns.forEach(function(column){ params.push(new Param(data[column])); }); return new Statement('INSERT INTO', table, [columns,params]); }, IN: function IN(){ var out = []; var values = []; function add(value, fromArray){ if(value===undefined) return; var v = value instanceof Param? value.v : value; if(~values.indexOf(v)) return; values.push(v); out.push(arguments.length>1 && !(value instanceof Param)? new Param(value) : value); } forEach(arguments, function(arg){ if(Array.isArray(arg)){ return arg.forEach(add); } add(arg); }); out = out.filter(function(item){ return typeof item==="string" || item.hasOwnProperty("v"); }); //we must return an empty Param object or Statements like AND // will not know if a Param was used. eg: AND("1=", $(99)) if(!out.length) return new Param(); return new Param(out, 'IN'); }, BETWEEN: function BETWEEN(low, high){ if(low===undefined && high===undefined) return new Param(); return new Param([new Param(low), new Param(high)], 'BETWEEN'); }, FROM: function(table){ if(typeof table!=="string") return Empty; return new Statement('FROM', table); }, SET: function(data){ if(!data || Object.keys(data).length===0) return Empty; return new Statement('SET', null, data); }, ORDERBY: function(columns){ return xBY('ORDERBY', arguments) }, GROUPBY: function(){ return xBY('GROUPBY', arguments) }, LIMIT: function(number){ return NumberOnly('LIMIT', number); }, OFFSET: function(number){ return NumberOnly('OFFSET', number); } }; function xBY(token, args){ var columns = args[0]; if(!Array.isArray(columns)){ columns = slice(args); } else { columns = columns.map(function(item){ return item instanceof Param? item: new Param(item); }); } args = columns.filter(function removeNonStrings(item){ return (typeof item === "string") || (item instanceof Param && typeof item.v ==="string"); }); if(!args.length) return Empty; var stmt = new Statement(token) stmt.args = args; return stmt; } function Context(){ var params=[], sql=""; var collapse = !!Context.collapse; var parameterized; var out = this.out = []; function getValues(){ if(!parameterized){ parameterized = out.slice(); this.parameterize(parameterized, params); sql = parameterized.join(''); } return params; } function getText(){ if(!parameterized){ parameterized = out.slice(); this.parameterize(parameterized, params); sql = parameterized.join(''); } return sql; } Object.defineProperties(this, { sql: {get: getText}, text: {get: getText}, params: {get: getValues}, values: {get: getValues}, collapse: { get: function () { return collapse;}, set: function (value) { parameterized=false; collapse = value;} } }); this.parameterize = function parameterize(out, params){ for(var i=0;i<out.length;i++){ var item = out[i]; if(typeof item !== "string"){ var value = item.v; // don't collate nulls, in SQL they are not equal // Can cause inconsistent type deduced error in Postgres var idx = (!collapse || value === null) ? -1 : params.indexOf(value); idx = (~idx? idx+1 : params.push(value) ); out[i] = this.createParam(idx); } } }; } Context.collapse = false; Context.prototype = { createParam: function(idx){ return '$'+idx; }, toString: function(){ return this.sql; }, processToken: function(){ throw new Error("Not Implemented"); }, SQL: function(){ var stmt = tokens._.apply(this, arguments); return processAndReturnSubcontext(stmt, this); }, SELECT: function(expression){ var stmt = typeof expression==="string"? new Statement('SELECT', expression) : Empty; return processAndReturnSubcontext(stmt, this); }, get INSERT(){ var ctx = this; return { INTO: function(table, data){ var stmt = tokens["INSERT INTO"].apply(this, arguments); return processAndReturnSubcontext(stmt, ctx); } } }, get DELETE(){ var ctx = this; return { FROM: function(table){ var stmt = tokens["DELETE FROM"].apply(this, arguments); return processAndReturnSubcontext(stmt, ctx); } } }, UPDATE: function(table){ var stmt = typeof table==="string"? new Statement('UPDATE', table) : Empty; return processAndReturnSubcontext(stmt, this); } }; Object.keys(tokens).forEach(function(key){ Context.prototype[key] = function(){ var stmt = tokens[key].apply(tokens, arguments); return processAndReturnSubcontext(stmt, this); } }); function processAndReturnSubcontext(stmt, parent){ var start = parent.out.length; parent.processToken(stmt, parent.out); if(parent.hasOwnProperty("end")) { parent.end=parent.out.length; return parent; } var sub = { end:parent.out.length }; sub.toString = function(){ parent.params;//for it to parameterize return parent.out.slice(start, this.end).join(''); }; sub.__proto__=parent; return sub; } module.exports.Statement = Statement; module.exports.Param = Param; module.exports.Empty = Empty; module.exports.Context = Context;
/** * @type {Number} * * @properties={typeid:35,uuid:"EAF8EA85-09CD-4E2A-9634-AE491D9F2EDB",variableType:8} */ var _idDittaLegata = null; /** * @type {Number} * * @properties={typeid:35,uuid:"BCA6E9A2-A99B-4899-B06F-93EE1D691890",variableType:8} */ var _idDitta = null; /** * @type {Number} * * @properties={typeid:35,uuid:"0757ABE2-CC51-4AE1-93AD-EB6B494DD9EB",variableType:4} */ var _tipologiaDitta = 0; /** * @type {Number} * * @properties={typeid:35,uuid:"35E0E229-2F92-46BA-B946-80A839376323",variableType:4} */ var _tipoEsterni = 0; /** * @type {Number} * * @properties={typeid:35,uuid:"0F67957E-E9D5-4861-99B2-F6F39F6D6825",variableType:8} */ var _codiceLegata = null; /** * @type {String} * * @properties={typeid:35,uuid:"8FC3D7DB-E940-4543-BFD2-13453332B9A2"} */ var _ragioneSocialeLegata = null; /** * @type {Number} * * @properties={typeid:35,uuid:"543A2BAD-BDC4-4F86-AD31-8F81643782DF",variableType:8} */ var _codice = null; /** * @type {String} * * @properties={typeid:35,uuid:"1D26848B-58BD-4683-979A-B9CF39549958"} */ var _ragioneSociale = null; /** * @type {String} * * @properties={typeid:35,uuid:"FA51E579-E91E-45CB-AE3E-E6067374CA4D"} */ var _codTipoSoggetto = null; /** * @type {String} * * @properties={typeid:35,uuid:"FF97263D-34FD-4BC0-8A9B-00CB419F45B2"} */ var _descTipoSoggetto = ''; /** * @type {String} * * @properties={typeid:35,uuid:"5E5FF0A0-928A-4057-B314-A124F12E2BB6"} */ var _codNaturaGiuridica = null; /** * @type {String} * * @properties={typeid:35,uuid:"24C3823B-DC7C-4B21-96B5-C7D49229B833"} */ var _descNaturaGiuridica = ''; /** * @type {String} * * @properties={typeid:35,uuid:"F48C8F2E-C36E-49EC-ACC1-C280A8CFBD37"} */ var _partitaIVA = null; /** * @type {String} * * @properties={typeid:35,uuid:"10690179-382C-4CD3-88D0-41AB1F567713"} */ var _codiceFiscale = null; /** * @type {String} * * @properties={typeid:35,uuid:"EEB715F8-C57B-43A4-B1F0-9F6A91A40F16"} */ var _indirizzoSedeLegale = null; /** * @type {String} * * @properties={typeid:35,uuid:"48FD817D-BF98-44A3-BB7B-8AE0FFCFE097"} */ var _codComuneSedeLegale = null; /** * @type {String} * * @properties={typeid:35,uuid:"EA32B142-E0BB-4495-BB5B-4A27DEAFEF6A"} */ var _comuneSedeLegale = null; /** * @type {String} * * @properties={typeid:35,uuid:"B7C0E0F1-D589-4C23-8B32-CC6B7F963988"} */ var _provSedeLegale = null; /** * @type {String} * * @properties={typeid:35,uuid:"A16F430C-6519-4611-A55F-AF107DC3B31F"} */ var _capSedeLegale = null; /** * @type {Date} * * @properties={typeid:35,uuid:"9E1FE9D3-B6C7-4294-BE2A-E716BBEE563D",variableType:93} */ var _inizioGestione = null; /** * @type {Date} * * @properties={typeid:35,uuid:"C556D9CE-BA05-47C4-9139-DBDC9556D88A",variableType:93} */ var _fineGestione = null; /** * @type {Number} * * @properties={typeid:35,uuid:"038AD8CC-7F02-483B-94BE-7BAA935F2B5D",variableType:8} */ var _periodoInizioGestione = null; /** * @type {Number} * * @properties={typeid:35,uuid:"A73DCC26-D2FA-4229-A24A-8E849FE523FC",variableType:8} */ var _periodoFineGestione = null; /** * @type {Number} * * @properties={typeid:35,uuid:"B1C97F78-1B3D-4FD8-93B7-AC6684D0D313",variableType:4} */ var _usaTracciato = 0; /** * @type {Number} * * @properties={typeid:35,uuid:"F2B1679D-BB94-47EF-BC5F-51412D57D09E",variableType:4} */ var _gestioneOrologio = 0; /** * @type {Number} * * @properties={typeid:35,uuid:"09345FD5-7122-42D8-9A93-EF066F9196FD",variableType:4} */ var _gestioneGGSucc = 0; /** * @type {Number} * * @properties={typeid:35,uuid:"7E8CABD6-CEB5-4D09-AEAB-E4EDD19FC578",variableType:4} */ var _gestioneTurnisti = 0; /** * @type {Number} * * @properties={typeid:35,uuid:"E68BB522-DC27-451C-BFD1-E52B8BFB930C",variableType:4} */ var _usaMensa = 0; /** * @type {Number} * * @properties={typeid:35,uuid:"8969BAC7-6B3C-474A-8386-16C8F7B8638C",variableType:4} */ var _mesePrecedente = 0; /** * @type {Number} * * @properties={typeid:35,uuid:"E87A14B9-86A2-4C05-893F-B5F1201A4556",variableType:4} */ var _gestioneRatei = 0; /** * @type {String} * * @properties={typeid:35,uuid:"5B86DEA5-073C-4814-83A4-964C428ADB3A"} */ var _indirizzoAggiuntivo = null; /** * @type {String} * * @properties={typeid:35,uuid:"231B172B-37F0-466F-9A73-C17281A1701B"} */ var _codComuneAggiuntivo = null; /** * @type {String} * * @properties={typeid:35,uuid:"853C486D-6314-48D0-9FC7-A1E825EE36EC"} */ var _comuneAggiuntivo = null; /** * @type {String} * * @properties={typeid:35,uuid:"07C71C34-A13D-4968-A0DF-502D1D02047C"} */ var _provAggiuntivo = null; /** * @type {String} * * @properties={typeid:35,uuid:"821BB139-42AE-4B41-B073-3394AF18B132"} */ var _capAggiuntivo = null; /** * @type {String} * * @properties={typeid:35,uuid:"FD627FF9-184B-4F05-ADFA-064257C920B3"} */ var _telefonoAggiuntivo = null; /** * @type {String} * * @properties={typeid:35,uuid:"672AA0CA-92D8-4D36-9AE6-CB3CD0A5862F"} */ var _faxAggiuntivo = null; /** * @type {String} * * @properties={typeid:35,uuid:"B40921E5-AF5E-4A38-A78F-1FEAED60A7EE"} */ var _mailAggiuntivo = null; /** * @properties={typeid:24,uuid:"75D9B517-DD60-4D27-88DE-47680BB7449D"} */ function inizializzaCampi() { _idDittaLegata = null; _idDitta = null; _tipologiaDitta = 0; _tipoEsterni = 0; _codiceLegata = null; _ragioneSocialeLegata = null; _codice = null; _ragioneSociale = null; _codTipoSoggetto = null; _descTipoSoggetto = ''; _codNaturaGiuridica = null; _descNaturaGiuridica = ''; _partitaIVA = null; _codiceFiscale = null; _indirizzoSedeLegale = null; _codComuneSedeLegale = null; _comuneSedeLegale = null; _provSedeLegale = null; _capSedeLegale = null; _inizioGestione = null; _fineGestione = null; _periodoInizioGestione = null; _periodoFineGestione = null; _usaTracciato = 0; _gestioneOrologio = 0; _gestioneGGSucc = 0; _gestioneTurnisti = 0; _usaMensa = 0; _mesePrecedente = 0; _gestioneRatei = 0; _indirizzoAggiuntivo = null; _codComuneAggiuntivo = null; _comuneAggiuntivo = null; _provAggiuntivo = null; _capAggiuntivo = null; _telefonoAggiuntivo = null; _faxAggiuntivo = null; _mailAggiuntivo = null; } /** * @param {JSRecord} _rec * * @properties={typeid:24,uuid:"1975F03B-9B42-4F42-B902-5034150E4AF1"} * @AllowToRunInFind */ function AggiornaSelezioneDittaLegata(_rec) { _idDittaLegata = _rec['idditta']; _codiceLegata = _rec['codice']; _ragioneSocialeLegata = _rec['ragionesociale']; } /** * Handle changed data. * * @param oldValue old value * @param newValue new value * @param {JSEvent} event the event that triggered the action * * @returns {Boolean} * * @properties={typeid:24,uuid:"4C2E018B-9BBA-4943-A94F-569EB4F28879"} * @AllowToRunInFind */ function onDataChangeDitta(oldValue, newValue, event) { _ragioneSocialeLegata = '' /** @type {JSFoundSet<db:/ma_anagrafiche/lavoratori>} */ var _foundset = databaseManager.getFoundSet(globals.Server.MA_ANAGRAFICHE,globals.Table.DITTE); var arrDitteEpi = globals.getDitteGestiteEpi2(); _foundset.addFoundSetFilterParam('idditta','IN',arrDitteEpi);_foundset.addFoundSetFilterParam('codice', '=', newValue) _foundset.loadAllRecords() if (_foundset.getSize() == 1) { //aggiorniamo la parte di selezione ditta _idDitta = _foundset['idditta'] _ragioneSociale = _foundset['ragionesociale'] } else globals.svy_nav_showLookupWindow(event, '_idditta', 'LEAF_Lkp_Ditte', 'AggiornaSelezioneDitta', 'filterDitta', null, null, '', true) return true; } /** * Salva la nuova anagrafica ditta ed i dati inseriti per la gestione presenze * * @param {JSEvent} event the event that triggered the action * * @private * * @properties={typeid:24,uuid:"274C71CE-1E26-4707-B8CB-DB9C48C2A968"} */ function confermaNuovaDitta(event) { try { if(validaDatiDitta()) { databaseManager.setAutoSave(false); databaseManager.startTransaction(); // crea l'anagrafica ditta /** @type {JSFoundSet<db:/ma_anagrafiche/ditte>} */ var fs = databaseManager.getFoundSet(globals.Server.MA_ANAGRAFICHE,globals.Table.DITTE); /** @type {JSRecord<db:/ma_anagrafiche/ditte>} */ var newDitta = fs.getRecord(fs.newRecord()); if(!newDitta) throw new Error('Errore durante la creazione della ditta'); newDitta.codice = _codice; newDitta.ragionesociale = _ragioneSociale; newDitta.tipologia = globals.Tipologia.GESTITA_UTENTE; if(_codTipoSoggetto) newDitta.codtiposoggetto = _codTipoSoggetto; if(_codNaturaGiuridica) newDitta.codnaturagiuridica = _codNaturaGiuridica; if(_partitaIVA) newDitta.partitaiva = _partitaIVA; if(_codiceFiscale) newDitta.codicefiscale = _codiceFiscale; /** @type {JSRecord<db:/ma_anagrafiche/ditte_indirizzi>} */ var newDittaIndirizzo = newDitta.ditte_to_ditte_indirizzi.getRecord(newDitta.ditte_to_ditte_indirizzi.newRecord()); if(!newDittaIndirizzo) throw new Error('Errore durante la creazione dell\'indirizzo della nuova anagrafica'); newDittaIndirizzo.indirizzo = _indirizzoSedeLegale; newDittaIndirizzo.codtipoindirizzo = globals.TipiIndirizzoDitta.SEDE_LEGALE; newDittaIndirizzo.descrizione = 'Sede legale'; newDittaIndirizzo.codcomune = _codComuneSedeLegale; newDittaIndirizzo.cap = _capSedeLegale; newDittaIndirizzo.codstatoestero = '1'; var _dataRilevazione = new Date(); newDittaIndirizzo.datarilevazione = _dataRilevazione; // TODO tipologia ditta... // crea il record in ditte_presenze per la gestione con EpiWeb /** @type {JSRecord<db:/ma_anagrafiche/ditte_presenze>} */ var newDittaGestEpiWeb = newDitta.ditte_to_ditte_presenze.getRecord(newDitta.ditte_to_ditte_presenze.newRecord()); if(!newDittaGestEpiWeb) throw new Error('Errore durante la creazione del record relativo alle presenze'); newDittaGestEpiWeb.ore_gestioneepi2 = 1; newDittaGestEpiWeb.ore_iniziogestione = _periodoInizioGestione; newDittaGestEpiWeb.ore_finegestione = _periodoFineGestione; newDittaGestEpiWeb.ore_gestionemp = _mesePrecedente; newDittaGestEpiWeb.ore_gestioneturno = _gestioneTurnisti; newDittaGestEpiWeb.ore_utilizzatracciato = _usaTracciato; newDittaGestEpiWeb.timbrature_gestioneorologio = _gestioneOrologio; newDittaGestEpiWeb.timbrature_ggsuccessivo = _gestioneGGSucc; var success = databaseManager.commitTransaction(); if(!success) { var failedRecords = databaseManager.getFailedRecords(); if (failedRecords && failedRecords.length > 0) throw new Error('Errore durante la creazione della ditta : ' + failedRecords[0].exception.getMessage()); } if(_indirizzoAggiuntivo != '' || _codComuneAggiuntivo != '') { databaseManager.startTransaction(); // gestiamolo momentaneamente come un indirizzo di tipo UNITA' OPERATIVA /** @type {JSRecord<db:/ma_anagrafiche/ditte_indirizzi>} */ var newDittaIndirizzoAgg = newDitta.ditte_to_ditte_indirizzi.getRecord(newDitta.ditte_to_ditte_indirizzi.newRecord()); if(!newDittaIndirizzoAgg) throw new Error('Errore durante la creazione dell\'indirizzo della nuova anagrafica'); newDittaIndirizzoAgg.indirizzo = _indirizzoAggiuntivo; newDittaIndirizzoAgg.codtipoindirizzo = globals.TipiIndirizzoDitta.UNITA_OPERATIVA; newDittaIndirizzoAgg.descrizione = 'Unità operativa'; newDittaIndirizzoAgg.codcomune = _codComuneAggiuntivo; newDittaIndirizzoAgg.cap = _capAggiuntivo; newDittaIndirizzoAgg.codstatoestero = '1'; newDittaIndirizzoAgg.datarilevazione = _dataRilevazione; success = databaseManager.commitTransaction(); if(!success) { var failedRecordsEst = databaseManager.getFailedRecords(); if (failedRecordsEst && failedRecordsEst.length > 0) throw new Error('Errore durante il salvataggio dell\indirizzo della ditta : ' + failedRecordsEst[0].exception.getMessage()); } } databaseManager.refreshRecordFromDatabase(fs,-1); globals.lookupFoundset(newDitta.idditta,forms.agd_header_dtl.foundset); globals.ma_utl_setStatus(globals.Status.BROWSE,controller.getName()); globals.svy_mod_closeForm(event); } else globals.ma_utl_showWarningDialog('Controlla i dati inseriti prima di proseguire','Inserisci ditta '); } catch(ex) { application.output(ex.message, LOGGINGLEVEL.ERROR); databaseManager.rollbackTransaction(); globals.ma_utl_setStatus(globals.Status.BROWSE,controller.getName()); globals.svy_mod_closeForm(event); globals.ma_utl_showErrorDialog('Inserimento nuova ditta non riuscito. Contattare lo studio'); } finally { databaseManager.setAutoSave(false); } } /** * @return Boolean * * @properties={typeid:24,uuid:"6AADD5A5-FD9E-45ED-B27D-C4A9F8E83CE8"} */ function validaDatiDitta() { if(!_codice) { setStatusWarning('Specificare un codice numerico per identificare la nuova ditta',null,1000); return false; } if(_ragioneSociale == null || _ragioneSociale == '') { setStatusWarning('Specificare un nome per la nuova ditta',null,1000); return false; } if(!globals.isCodiceDittaDisponibile(_codice)) { setStatusWarning('Esiste già una ditta con il codice scelto, specificarne un altro',null, 1000); return false; } if(_tipoEsterni == 1 && _idDittaLegata == null) { setStatusWarning('Specificare la ditta principale a cui la nuova ditta è legata',null, 1000); return false; } return true; } /** * @param _firstShow * @param _event * * @properties={typeid:24,uuid:"DA405B96-A47F-42BF-B392-1C033D8C245D"} */ function onShowForm(_firstShow, _event) { _super.onShowForm(_firstShow, _event); inizializzaCampi(); globals.ma_utl_setStatus(globals.Status.EDIT,controller.getName()); } /** * Perform the element default action. * * @param {JSEvent} event the event that triggered the action * * @private * * @properties={typeid:24,uuid:"B5BE46E7-0D9C-4A67-A5E0-D205513CE0CC"} */ function annullaInserimentoDitta(event) { databaseManager.rollbackTransaction(); globals.ma_utl_setStatus(globals.Status.BROWSE,controller.getName()); globals.svy_mod_closeForm(event); } /** * @param _rec * * @properties={typeid:24,uuid:"888B6B1D-9446-4731-92D1-3D7AA97CA20E"} */ function updateTipoSoggetto(_rec) { _codTipoSoggetto = _rec['codice']; _descTipoSoggetto = _rec['descrizione']; } /** * @param _rec * * @properties={typeid:24,uuid:"7D2BDEDC-34BF-488D-9FED-354953CA1512"} */ function updateNaturaGiuridica(_rec) { _codNaturaGiuridica = _rec['codice']; _descNaturaGiuridica = _rec['descrizione']; } /** * @param _rec * * @properties={typeid:24,uuid:"3FE317BD-78ED-4938-BE50-D95C46AF8A65"} */ function updateComuneSl(_rec) { _codComuneSedeLegale = _rec['codcomune']; _comuneSedeLegale = _rec['descrizione']; _provSedeLegale = _rec['provincia']; _capSedeLegale = _rec['cap']; } /** * @param _rec * * @properties={typeid:24,uuid:"7DBBF7A5-0ADA-48DA-8B57-00D1FB589FDB"} */ function updateComuneAgg(_rec) { _codComuneAggiuntivo = _rec['codcomune']; _comuneAggiuntivo = _rec['descrizione']; _provAggiuntivo = _rec['provincia']; _capAggiuntivo = _rec['cap']; } /** * * @param {JSEvent} event * * @properties={typeid:24,uuid:"15FD1DDB-ABB8-4FD2-995A-D5A2F6913586"} */ function onHide(event) { annullaInserimentoDitta(event); }
import React from 'react'; import './index.css'; import moment from 'moment'; import { Link } from 'react-router-dom'; import style from './voteStyle.css'; let postDate = (timestamp) => { return moment(timestamp).format('DD/MM/YY HH:mm:ss'); } export default function List(props) { if (props.type === "post") { return ( <React.Fragment> {props.items.length === 0 && <p>Empty list</p>} {props.items && props.items.map((post) => ( <div key={post.id} className="question" data-color={props.color(post.voteScore)}> <div className="votes"> <div className="upvote" onClick={() => props.vote(post.id, 'upVote')}></div> <div className="number-of-votes">{post.voteScore}</div> <div className="downvote" onClick={() => props.vote(post.id, 'downVote')}></div> </div> <div className="question-and-answer"> <Link to={process.env.PUBLIC_URL + '/' + post.category + '/' + post.id} > <h2>{post.title}</h2> </Link> <p className="author">{post.author} - {postDate(post.timestamp)}</p> <p>{post.body}</p> </div> <div className="social"> <div className="post-comments">{post.commentCount}</div> </div> </div> ))} </React.Fragment> ) } else { return ( <React.Fragment> {props.items && props.items.map((item, index) => ( <li key={item.id}> <div className={`user-comment ${item.voteScore > 2 ? style.green : item.voteScore >= 0 && item.voteScore <= 2 ? style.yellow : style.red}`}> <div className="comment-votes"> <div className="upvote" onClick={() => props.vote(item.id, 'upVote')}></div> <div className="number-of-votes">{item.voteScore}</div> <div className="downvote" onClick={() => props.vote(item.id, 'downVote')}></div> </div> <img src={"https://cdn1.iconfinder.com/data/icons/flat-business-icons/128/user-32.png"} alt="" /> <header> <a className="name">{item.author}</a> <span>{postDate(item.timestamp)}</span> </header> <div className="content"> <p>{item.body}</p> </div> <a className="edit" onClick={() => { props.editComment(item) }}>edit</a> <a className="delete" onClick={() => { props.onDeleteComment(item) }}>delete</a> </div> </li> ))} {props.items.length === 0 && <p>There is not comments, be the first to comment.</p> } </React.Fragment> ) } }
angular.module("app") /// seguindo assim pode ser sem modulos novos só pedir sempre o modulo de app fodasse a performance :) .component("inicialApp", { //// nomo do componente no html trasformar as maiusculas em traço mais a letra maiscula em minuscula exemplo view-teste templateUrl: '../html/inicial.html', ///caminho do seu html brown bindings: { name: '@' }, /// se precisar binda pra passar parametros para seus componentes mas recomendo usar uma serivice controller: function (gk2vService) { /// chamada ao iniciar seu componente var $ctrl = this; // $("body").css("background", ""); //// aqui as logicas da tela/regras da tela criando functions e suas properts lembra de usar o $ctrl na view par apontar console.log("inicial"); } });
import $ from '../../core/renderer'; import Toolbar from '../toolbar'; import ContextMenu from '../context_menu'; import DiagramBar from './diagram.bar'; import { extend } from '../../core/utils/extend'; import { hasWindow, getWindow } from '../../core/utils/window'; import DiagramPanel from './ui.diagram.panel'; import DiagramMenuHelper from './ui.diagram.menu_helper'; import { getDiagram } from './diagram.importer'; import '../select_box'; import '../color_box'; import '../check_box'; var ACTIVE_FORMAT_CLASS = 'dx-format-active'; var DIAGRAM_TOOLBAR_CLASS = 'dx-diagram-toolbar'; var DIAGRAM_TOOLBAR_SEPARATOR_CLASS = 'dx-diagram-toolbar-separator'; var DIAGRAM_TOOLBAR_MENU_SEPARATOR_CLASS = 'dx-diagram-toolbar-menu-separator'; var DIAGRAM_MOBILE_TOOLBAR_COLOR_BOX_OPENED_CLASS = 'dx-diagram-mobile-toolbar-color-box-opened'; class DiagramToolbar extends DiagramPanel { _init() { this._commands = []; this._itemHelpers = {}; this._commandContextMenus = {}; this._contextMenuList = []; this._valueConverters = {}; this.bar = new DiagramToolbarBar(this); this._createOnInternalCommand(); this._createOnCustomCommand(); this._createOnSubMenuVisibilityChangingAction(); super._init(); } _initMarkup() { super._initMarkup(); var isServerSide = !hasWindow(); if (!this.option('skipAdjustSize') && !isServerSide) { this.$element().width(''); } this._commands = this._getCommands(); this._itemHelpers = {}; this._commandContextMenus = {}; this._contextMenuList = []; var $toolbar = this._createMainElement(); this._renderToolbar($toolbar); if (!this.option('skipAdjustSize') && !isServerSide) { var $toolbarContent = this.$element().find('.dx-toolbar-before'); this.$element().width($toolbarContent.width()); } } _createMainElement() { return $('<div>').addClass(DIAGRAM_TOOLBAR_CLASS).appendTo(this._$element); } _getCommands() { return this.option('commands') || []; } _renderToolbar($toolbar) { var beforeCommands = this._commands.filter(command => ['after', 'center'].indexOf(command.position) === -1); var centerCommands = this._commands.filter(command => command.position === 'center'); var afterCommands = this._commands.filter(command => command.position === 'after'); var dataSource = [].concat(this._prepareToolbarItems(beforeCommands, 'before', this._executeCommand)).concat(this._prepareToolbarItems(centerCommands, 'center', this._executeCommand)).concat(this._prepareToolbarItems(afterCommands, 'after', this._executeCommand)); this._toolbarInstance = this._createComponent($toolbar, Toolbar, { dataSource }); } _prepareToolbarItems(items, location, actionHandler) { return items.map(item => extend(true, { location: location, locateInMenu: this.option('locateInMenu') }, this._createItem(item, location, actionHandler), this._createItemOptions(item), this._createItemActionOptions(item, actionHandler))); } _createItem(item, location, actionHandler) { if (item.getCommandValue || item.getEditorValue || item.getEditorDisplayValue) { this._valueConverters[item.command] = { getCommandValue: item.getCommandValue, getEditorValue: item.getEditorValue, getEditorDisplayValue: item.getEditorDisplayValue }; } if (item.widget === 'separator') { return { template: (data, index, element) => { $(element).addClass(DIAGRAM_TOOLBAR_SEPARATOR_CLASS); }, menuItemTemplate: (data, index, element) => { $(element).addClass(DIAGRAM_TOOLBAR_MENU_SEPARATOR_CLASS); } }; } return { widget: item.widget || 'dxButton', cssClass: item.cssClass, options: { stylingMode: this.option('buttonStylingMode'), type: this.option('buttonType'), text: item.text, hint: item.hint, icon: item.icon || item.iconUnchecked || item.iconChecked, iconChecked: item.iconChecked, iconUnchecked: item.iconUnchecked, onInitialized: e => this._onItemInitialized(e.component, item), onContentReady: e => this._onItemContentReady(e.component, item, actionHandler) } }; } _createItemOptions(_ref) { var { widget, command, items, valueExpr, displayExpr, showText, hint, icon } = _ref; if (widget === 'dxSelectBox') { return this._createSelectBoxItemOptions(command, hint, items, valueExpr, displayExpr); } else if (widget === 'dxTextBox') { return this._createTextBoxItemOptions(command, hint); } else if (widget === 'dxColorBox') { return this._createColorBoxItemOptions(command, hint, icon); } else if (!widget || widget === 'dxButton') { return { showText: showText || 'inMenu' }; } } _createSelectBoxItemOptions(command, hint, items, valueExpr, displayExpr) { var options = this._createTextEditorItemOptions(hint); options = extend(true, options, { options: { dataSource: items, displayExpr: displayExpr || 'text', valueExpr: valueExpr || 'value', dropDownOptions: { container: this.option('container') } } }); var isSelectButton = items && items.every(i => i.icon !== undefined); var nullIconClass = 'dx-diagram-i-selectbox-null-icon dx-diagram-i'; if (isSelectButton) { options = extend(true, options, { options: { fieldTemplate: (data, container) => { $('<i>').addClass(data && data.icon || nullIconClass).appendTo(container); $('<div>').dxTextBox({ readOnly: true, stylingMode: 'outlined' }).appendTo(container); }, itemTemplate: (data, index, container) => { $(container).attr('title', data.hint); return "<i class=\"".concat(data.icon, "\"></i>"); } } }); } return options; } _createTextBoxItemOptions(command, hint) { var options = this._createTextEditorItemOptions(hint); options = extend(true, options, { options: { readOnly: true, focusStateEnabled: false, hoverStateEnabled: false, buttons: [{ name: 'dropDown', location: 'after', options: { icon: 'spindown', disabled: false, stylingMode: 'text', onClick: e => { var contextMenu = this._commandContextMenus[command]; if (contextMenu) { this._toggleContextMenu(contextMenu); } } } }] } }); return options; } _createColorBoxItemOptions(command, hint, icon) { var options = this._createTextEditorItemOptions(hint); if (icon) { options = extend(true, options, { options: { openOnFieldClick: true, fieldTemplate: (data, container) => { $('<i>').addClass(icon).css('borderBottomColor', data).appendTo(container); $('<div>').dxTextBox({ readOnly: true, stylingMode: 'outlined' }).appendTo(container); } } }); } options = extend(true, options, { options: { dropDownOptions: { container: this.option('container') }, onOpened: () => { if (this.option('isMobileView')) { $('body').addClass(DIAGRAM_MOBILE_TOOLBAR_COLOR_BOX_OPENED_CLASS); } }, onClosed: () => { $('body').removeClass(DIAGRAM_MOBILE_TOOLBAR_COLOR_BOX_OPENED_CLASS); } } }); return options; } _createTextEditorItemOptions(hint) { return { options: { stylingMode: this.option('editorStylingMode'), hint: hint } }; } _createItemActionOptions(item, handler) { switch (item.widget) { case 'dxSelectBox': case 'dxColorBox': case 'dxCheckBox': return { options: { onValueChanged: e => { var parameter = DiagramMenuHelper.getItemCommandParameter(this, item, e.component.option('value')); handler.call(this, item.command, item.name, parameter); } } }; case 'dxTextBox': return {}; default: return { options: { onClick: e => { if (!item.items) { var parameter = DiagramMenuHelper.getItemCommandParameter(this, item); handler.call(this, item.command, item.name, parameter); } else { var contextMenu = e.component._contextMenu; if (contextMenu) { this._toggleContextMenu(contextMenu); } } } } }; } } _toggleContextMenu(contextMenu) { this._contextMenuList.forEach(cm => { if (contextMenu !== cm) { cm.hide(); } }); contextMenu.toggle(); } _onItemInitialized(widget, item) { this._addItemHelper(item.command, new DiagramToolbarItemHelper(widget)); } _onItemContentReady(widget, item, actionHandler) { if ((widget.NAME === 'dxButton' || widget.NAME === 'dxTextBox') && item.items) { var isTouchMode = this._isTouchMode(); var $menuContainer = $('<div>').appendTo(this.$element()); widget._contextMenu = this._createComponent($menuContainer, ContextMenu, { items: item.items, target: widget.$element(), cssClass: DiagramMenuHelper.getContextMenuCssClass(), showEvent: '', closeOnOutsideClick: e => { return !isTouchMode && $(e.target).closest(widget._contextMenu._dropDownButtonElement).length === 0; }, focusStateEnabled: false, position: { at: 'left bottom' }, itemTemplate: function itemTemplate(itemData, itemIndex, itemElement) { DiagramMenuHelper.getContextMenuItemTemplate(this, itemData, itemIndex, itemElement); }, onItemClick: _ref2 => { var { component, itemData } = _ref2; DiagramMenuHelper.onContextMenuItemClick(this, itemData, actionHandler.bind(this)); if (!itemData.items || !itemData.items.length) { component.hide(); } }, onShowing: e => { if (this._showingSubMenu) return; this._showingSubMenu = e.component; this._onSubMenuVisibilityChangingAction({ visible: true, component: this }); e.component.option('items', e.component.option('items')); delete this._showingSubMenu; }, onInitialized: _ref3 => { var { component } = _ref3; return this._onContextMenuInitialized(component, item, widget); }, onDisposing: _ref4 => { var { component } = _ref4; return this._onContextMenuDisposing(component, item); } }); // prevent showing context menu by toggle "close" click if (!isTouchMode) { widget._contextMenu._dropDownButtonElement = widget.$element(); // i.e. widget.NAME === 'dxButton' if (widget.NAME === 'dxTextBox') { widget._contextMenu._dropDownButtonElement = widget.getButton('dropDown').element(); } } } } _isTouchMode() { var { Browser } = getDiagram(); if (Browser.TouchUI) { return true; } if (!hasWindow()) { return false; } var window = getWindow(); return window.navigator && window.navigator.maxTouchPoints > 0; } _onContextMenuInitialized(widget, item, rootWidget) { this._contextMenuList.push(widget); if (item.command) { this._commandContextMenus[item.command] = widget; } this._addContextMenuHelper(item, widget, [], rootWidget); } _addItemHelper(command, helper) { if (command !== undefined) { if (this._itemHelpers[command]) { throw new Error('Toolbar cannot contain duplicated commands.'); } this._itemHelpers[command] = helper; } } _addContextMenuHelper(item, widget, indexPath, rootWidget) { if (item.items) { item.items.forEach((subItem, index) => { var itemIndexPath = indexPath.concat(index); this._addItemHelper(subItem.command, new DiagramToolbarSubItemHelper(widget, itemIndexPath, subItem.command, rootWidget)); this._addContextMenuHelper(subItem, widget, itemIndexPath, rootWidget); }); } } _onContextMenuDisposing(widget, item) { this._contextMenuList.splice(this._contextMenuList.indexOf(widget), 1); delete this._commandContextMenus[item.command]; } _executeCommand(command, name, value) { if (this._updateLocked) return; if (typeof command === 'number') { var valueConverter = this._valueConverters[command]; if (valueConverter && valueConverter.getCommandValue) { value = valueConverter.getCommandValue(value); } this.bar.raiseBarCommandExecuted(command, value); } else if (typeof command === 'string') { this._onInternalCommandAction({ command }); } if (name !== undefined) { this._onCustomCommandAction({ name }); } } _createOnInternalCommand() { this._onInternalCommandAction = this._createActionByOption('onInternalCommand'); } _createOnCustomCommand() { this._onCustomCommandAction = this._createActionByOption('onCustomCommand'); } _setItemEnabled(command, enabled) { if (command in this._itemHelpers) { var helper = this._itemHelpers[command]; if (helper.canUpdate(this._showingSubMenu)) { helper.setEnabled(enabled); } } } _setEnabled(enabled) { this._toolbarInstance.option('disabled', !enabled); this._contextMenuList.forEach(contextMenu => { contextMenu.option('disabled', !enabled); }); } _setItemValue(command, value) { try { this._updateLocked = true; if (command in this._itemHelpers) { var helper = this._itemHelpers[command]; if (helper.canUpdate(this._showingSubMenu)) { var valueConverter = this._valueConverters[command]; if (valueConverter && valueConverter.getEditorValue) { value = valueConverter.getEditorValue(value); } var displayValue; if (valueConverter && valueConverter.getEditorDisplayValue) { displayValue = valueConverter.getEditorDisplayValue(value); } var contextMenu = this._commandContextMenus[command]; helper.setValue(value, displayValue, contextMenu, contextMenu && command); } } } finally { this._updateLocked = false; } } _setItemSubItems(command, items) { this._updateLocked = true; if (command in this._itemHelpers) { var helper = this._itemHelpers[command]; if (helper.canUpdate(this._showingSubMenu)) { var contextMenu = this._commandContextMenus[command]; helper.setItems(items, contextMenu, contextMenu && command); } } this._updateLocked = false; } _createOnSubMenuVisibilityChangingAction() { this._onSubMenuVisibilityChangingAction = this._createActionByOption('onSubMenuVisibilityChanging'); } _optionChanged(args) { switch (args.name) { case 'isMobileView': $('body').removeClass(DIAGRAM_MOBILE_TOOLBAR_COLOR_BOX_OPENED_CLASS); this._invalidate(); break; case 'onSubMenuVisibilityChanging': this._createOnSubMenuVisibilityChangingAction(); break; case 'onInternalCommand': this._createOnInternalCommand(); break; case 'onCustomCommand': this._createOnCustomCommand(); break; case 'container': case 'commands': this._invalidate(); break; case 'export': break; default: super._optionChanged(args); } } _getDefaultOptions() { return extend(super._getDefaultOptions(), { isMobileView: false, export: { fileName: 'Diagram', proxyUrl: undefined }, locateInMenu: 'auto', buttonStylingMode: 'text', buttonType: 'normal', editorStylingMode: 'filled', skipAdjustSize: false }); } setCommandChecked(command, checked) { this._setItemValue(command, checked); } setCommandEnabled(command, enabled) { this._setItemEnabled(command, enabled); } } class DiagramToolbarBar extends DiagramBar { getCommandKeys() { return this._getKeys(this._owner._commands); } setItemValue(key, value) { this._owner._setItemValue(key, value); } setItemEnabled(key, enabled) { this._owner._setItemEnabled(key, enabled); } setEnabled(enabled) { this._owner._setEnabled(enabled); } setItemSubItems(key, items) { this._owner._setItemSubItems(key, items); } } class DiagramToolbarItemHelper { constructor(widget) { this._widget = widget; } canUpdate(showingSubMenu) { return showingSubMenu === undefined; } setEnabled(enabled) { this._widget.option('disabled', !enabled); } setValue(value, displayValue, contextMenu, rootCommandKey) { if ('value' in this._widget.option()) { this._updateEditorValue(value, displayValue); } else if (value !== undefined) { this._updateButtonValue(value); } if (contextMenu) { this._updateContextMenuItemValue(contextMenu, '', rootCommandKey, value); } } setItems(items, contextMenu, rootCommandKey) { if (contextMenu) { this._updateContextMenuItems(contextMenu, '', rootCommandKey, items); } else { this._updateEditorItems(items); } } _updateContextMenuItems(contextMenu, itemOptionText, rootCommandKey, items) { DiagramMenuHelper.updateContextMenuItems(contextMenu, itemOptionText, rootCommandKey, items); } _updateEditorItems(items) { if ('items' in this._widget.option()) { this._widget.option('items', items.map(item => { return { 'value': DiagramMenuHelper.getItemValue(item), 'text': item.text }; })); } } _updateEditorValue(value, displayValue) { this._widget.option('value', value); if (!this._widget.option('selectedItem') && displayValue) { this._widget.option('value', displayValue); } } _updateButtonValue(value) { if (this._widget.option('iconChecked') && this._widget.option('iconUnchecked')) { this._widget.option('icon', value ? this._widget.option('iconChecked') : this._widget.option('iconUnchecked')); } else { this._widget.$element().toggleClass(ACTIVE_FORMAT_CLASS, value); } } _updateContextMenuItemValue(contextMenu, itemOptionText, rootCommandKey, value) { DiagramMenuHelper.updateContextMenuItemValue(contextMenu, itemOptionText, rootCommandKey, value); } } class DiagramToolbarSubItemHelper extends DiagramToolbarItemHelper { constructor(widget, indexPath, rootCommandKey, rootWidget) { super(widget); this._indexPath = indexPath; this._rootCommandKey = rootCommandKey; this._rootWidget = rootWidget; } canUpdate(showingSubMenu) { return super.canUpdate(showingSubMenu) || showingSubMenu === this._widget; } setEnabled(enabled) { this._widget.option(this._getItemOptionText() + 'disabled', !enabled); var rootEnabled = this._hasEnabledCommandItems(this._widget.option('items')); this._rootWidget.option('disabled', !rootEnabled); } _hasEnabledCommandItems(items) { if (items) { return items.some(item => item.command !== undefined && !item.disabled || this._hasEnabledCommandItems(item.items)); } return false; } setValue(value) { this._updateContextMenuItemValue(this._widget, this._getItemOptionText(), this._rootCommandKey, value); } setItems(items) { this._updateContextMenuItems(this._widget, this._getItemOptionText(), this._rootCommandKey, items); } _getItemOptionText() { return DiagramMenuHelper.getItemOptionText(this._widget, this._indexPath); } } export default DiagramToolbar;
angular.module("mainModule", [ "ngTouch" ]);
/*global Collection, PagedCollection */ describe('PagedCollection', function() { var collection; beforeEach(function() { collection = new PagedCollection(); collection.url = 'foo'; collection.collectionField = 'item'; collection.countField = 'totalCount'; collection.pageSize = 3; }); it('should read fields', function() { collection.fetch(); this.requests[0].respond(200, {}, JSON.stringify({item: [{id: 1}, {id: 2}, {id: 3}], totalCount: 5})); expect(_.pluck(collection.models, 'id')).to.eql([1, 2, 3]); expect(collection.totalCount).to.equal(5); collection.collectionField = 'otherShit'; collection.countField = 'totalCount2'; collection.fetch(); this.requests[1].respond(200, {}, JSON.stringify({otherShit: [{id: 11}, {id: 2}, {id: 3}], totalCount2: 6})); expect(_.pluck(collection.models, 'id')).to.eql([11, 2, 3]); expect(collection.totalCount).to.equal(6); }); it('should read subsequent content on the next page', function() { collection.fetch(); this.requests[0].respond(200, {}, JSON.stringify({item: [{id: 1}, {id: 2}, {id: 3}], totalCount: 5})); expect(_.pluck(collection.models, 'id')).to.eql([1, 2, 3]); expect(collection.totalCount).to.equal(5); expect(collection.hasMore()).to.be.true; collection.nextPage(); this.requests[1].respond(200, {}, JSON.stringify({item: [{id: 4}, {id: 5}, {id: 6}], totalCount: 5})); expect(_.pluck(collection.models, 'id')).to.eql([1, 2, 3, 4, 5, 6]); expect(collection.totalCount).to.equal(5); }); it('should not read subsequent content on the next page', function() { collection.fetch(); this.requests[0].respond(200, {}, JSON.stringify({item: [{id: 1}, {id: 2}, {id: 3}], totalCount: 3})); expect(collection.hasMore()).to.be.false; collection.nextPage(); expect(this.requests.length).to.equal(1); }); describe('#mergeFetch', function() { var collection; beforeEach(function() { collection = new Collection(); collection.url = 'foo'; collection.fetch = PagedCollection.mergeFetch(); }); it('should load from multiple pages', function() { var spy = this.spy(), startSpy = this.spy(), endSpy = this.spy(); collection.on('load:start', startSpy); collection.on('load:end', endSpy); collection.fetch({success: spy}); for (var i = 0; i < 3; i++) { expect(this.requests.length).to.equal(i + 1); expect(this.requests[i].url).to.match(/pagenum=(\d+)/); expect(RegExp.$1).to.equal(i+1+''); expect(startSpy).to.have.been.calledOnce; expect(endSpy).to.not.have.been.called; this.requests[i].respond(200, {}, JSON.stringify({ totalResult: 150, item: _.range(50*i, 50*(i+1)).map(function(value) { return { id: value }; }) })); if (i < 2) { expect(spy).to.not.have.been.called; } } expect(startSpy).to.have.been.calledOnce; expect(endSpy).to.have.been.calledOnce; expect(spy).to.have.been.called; expect(collection.length).to.equal(150); expect(collection.at(0).id).to.equal(0); expect(collection.at(0).collection).to.equal(collection); expect(collection.at(149).id).to.equal(149); }); it('should forward errors', function() { this.stub(Phoenix, 'trackError'); this.stub(Phoenix, 'setView'); var collection = new Collection(), spy = this.spy(), errorSpy = this.spy(); collection.on('error', errorSpy); collection.fetch = PagedCollection.mergeFetch(); collection.fetch({error: spy}); this.requests[0].respond(404, {}, ''); expect(spy).to.have.been.calledOnce; expect(errorSpy).to.have.been.calledOnce; }); }); });
/** * * jQuery Tooltips by Nick Snyder (http://nicksnyder.is) * * Copyright (c) 2015 Nick Snyder * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ (function($) { "use strict" var defaults, methods; defaults = { action: 'hover', speed: 500 }; methods = { // init // Starts the plugin init: function(options) { options = $.extend({}, defaults, options) return this.each(function() { var elem = $(this), box = elem.children('.tooltip-box'), arrow = box.children('.triangle'), offset = box.offset(), width = box.outerWidth(), height = box.outerHeight(); if (options.action === "click") { methods.onClick(elem, box, options.speed); } else { methods.onHover(elem, box, options.speed); } if (elem.hasClass('top')) { box.css({ left: (width / 2 - 10) * -1, top: (height + (height / 4)) * -1 }); arrow.css({ left: (width / 2) - 10, top: height - 7 }); } if (elem.hasClass('right')) { box.css({ left: 30, top: (height / 3) * -1 }); arrow.css({ left: -7, top: height / 2 - 7 }); } if (elem.hasClass('left')) { box.css({ left: (width + 10) * -1, top: (height / 3) * -1 }); arrow.css({ left: (width - 7), top: height / 2 - 7 }); } if (elem.hasClass('bottom')) { box.css({ left: (width / 2 - 10) * -1, top: height / 2 }); arrow.css({ left: (width / 2) - 10, top: -7 }); } }); }, // ----------------------------------------------------------------------- // Animation Methods // ----------------------------------------------------------------------- // onHover // If the tooltip gets created because of a hover onHover: function(elem, box, speed) { console.log(elem); elem.children('.fa').on('mouseenter', function(e) { e.preventDefault(); elem.children('.tooltip-box').fadeIn(speed); }).on('mouseleave', function(e) { e.preventDefault(); elem.children('.tooltip-box').fadeOut(speed); }); }, // onClick // If the tooltip gets created because of a click onClick: function(elem, box, speed) { elem.children('.fa').on('click', function(e) { e.preventDefault(); if (elem.hasClass('clicked')) { elem.removeClass('clicked'); elem.children('.tooltip-box').fadeOut(speed); } else { elem.children('.tooltip-box').fadeIn(speed); elem.addClass('clicked'); } }); }, // ----------------------------------------------------------------------- // Helper Methods // ----------------------------------------------------------------------- // remove // Removes a character from the passed string remove: function(item, string) { return item.replace(string, ''); }, }; $.fn.tooltips = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === "object" || $.isFunction(method) || !method) { return methods.init.apply(this, arguments); } else { $.error("Method " + method + " does not exist."); } }; })(jQuery);
var jsonQuery = require('../src/index.js'); var testJSON = [ ['name', 'owner', 'species', 'sex', 'birth', 'death'], ["Fluffy", "Harold", "cat", "f", "1993-02-04", null], ["Claws", "Gwen", "cat", "m", "1994-03-17", null], ["Buffy", "Harold", "dog", "f", "1989-05-13", null], ["Fang", "Benny", "dog", "m", "1990-08-27", null], ["Bowser", "Diane", "dog", "m", "1979-08-31", "1995-07-29"], ["Chirpy", "Gwen", "bird", "f", "1998-09-11", null], ["Whistler", "Gwen", "bird", null, "1997-12-09", null], ["Slim", "Benny", "snake", "m", "1996-04-29", null], ["Puffball", "Diane", "hamster", "f", "1999-03-30", null] ]; var results = new jsonQuery(testJSON) .Select(['name', 'owner', 'species', 'sex']) .Where([ ['OR', ['AND', ['sex', '=', 'f'], ['death', '!=', null] ], ['species', 'IN', ['cat', 'dog']] ] ]) .Execute(); console.log(results);
import db from '../models/index' var bcrypt = require('bcryptjs'); var salt = bcrypt.genSaltSync(10); let handleUserLogin = (email, password) => { return new Promise ( async (thanhcong,thatbai) => { try { let userData = {} let isExist = await checkUserEmail(email) // check Email có tồn tại trong database if(isExist){ let user = await db.User.findOne({ attributes: ['id','email', 'password', 'roleId','firstName','lastName'], where :{email : email}, raw : true }) if(user){ let check = await bcrypt.compareSync(password, user.password); // kiểm tra password có khới vs db delete user.password; // xóa password if(check){ userData.errCode = 0 userData.errMessage = 'thành công' userData.user = user }else{ userData.errCode = 3 userData.errMessage = 'sai thông tin email hoặc mật khẩu' } }else{ userData.errCode = 2 userData.errMessage = 'sai thông tin email hoặc mật khẩu' } }else{ userData.errCode = 1 userData.errMessage = 'sai thông tin email hoặc mật khẩu' } thanhcong(userData) } catch (error) { thatbai(error) } }) } let checkUserEmail = (email) => { return new Promise ( async (thanhcong, thaibai) => { try { let user = await db.User.findOne({ where : {email : email} }) if(user) { thanhcong(true) }else{ thanhcong(false) } } catch (error) { thatbai(error) } }) } let getAllUser = (userId) => { return new Promise ( async (thanhcong, thatbai) => { try { let user = ''; if(userId === 'ALL'){ user = await db.User.findAll({// tìm tất cả các user raw : false, attributes: { // include: [], // define columns that you want to show exclude: ['password'] // define columns that you don't want } }) } if(userId && userId !== 'ALL'){ // tim user theo id user = await db.User.findOne({ raw : true, where : {id : userId}, attributes: { // include: [], // define columns that you want to show exclude: ['password'] // define columns that you don't want } }) } thanhcong(user) } catch (error) { thatbai(error) } }) } let createNewUser = (data) => { return new Promise ( async (thanhcong, thatbai) => { try { let check = await checkUserEmail(data.email); console.log(check) if(check === true){// check email có tồn tại không console.log('check') thanhcong({ errCode : 1, messageCode : "Email này đã tồn tại" }) }else{ let hashUserPasswordByBcrypt = await hashUserPassword(data.password); // đợi lbr bcrypt băm pw ra đã await db.User.create({ email: data.email, password: hashUserPasswordByBcrypt, firstName: data.firstName, lastName: data.lastName, address: data.address, gender: data.gender, roleId: data.roleId, positionId : data.positionId, phonenumber: data.phonenumber, image: data.avatar }) thanhcong({ errCode:0, errMessage: ' oke' }) } } catch (error) { thatbai(error) } }) } let deleteUser = (id) => { return new Promise ( async (thanhcong,thatbai) => { try { let user = await db.User.findOne({ where:{id : id} }) if(!user){ thanhcong({ errCode : 2, errMessage : 'Người dùng không tồn tại' }) } if(user){ await user.destroy() thanhcong({ errCode : 0, messageCode : 'Xóa thành công' }) } } catch (error) { thatbai(error) } }) } let updateUser = (data) => { return new Promise(async (thanhcong,thatbai) => { try { if(!data.id || !data.roleId || !data.positionId || !data.gender){ // if(!data.id){ console.log("check 1") thanhcong({ errCode : 2, messageCode : 'Id 2 không tồn tại' }) } let user = await db.User.findOne({ where : {id : data.id} }) console.log("check 2") if(!user){ thanhcong({ errCode : 1, messageCode : 'Người dùng không tồn tại' }) } console.log("check 3") user.firstName = data.firstName user.lastName = data.lastName user.address = data.address user.roleId = data.roleId user.positionId = data.positionId user.gender = data.gender user.phonenumber = data.phonenumber if(data.avatar){ user.image = data.avatar } await user.save(); thanhcong({ errCode : 0, messageCode : 'update thành công' }) } catch (e) { thatbai(e) } }) } /// let hashUserPassword = (pw) => { // băm lại mật khẩu return new Promise((thanhcong, thatbai) => { // trả về một promise try { var hash = bcrypt.hashSync(pw, salt); // sử lý băm pw thanhcong(hash) // trả về pw đã được băm } catch (error) { thatbai(error) // nếu lỗi trả về error exception } }) } let getAllCodeService = (type) => { return new Promise ( async (thanhcong,thaibai) => { try { if(!type){ thanhcong({ errorCode : 1, messageCode : "THIẾU THAM SỐ TRUYỀN VÀO" }) }else{ let res = {} let allCode = await db.Allcode.findAll({ raw : true, where : {type : type } }) res.errCode = 0 res.data = allCode thanhcong(res) } } catch (error) { thaibai(error) } }) } module.exports = { handleUserLogin, getAllUser, createNewUser, deleteUser, updateUser, getAllCodeService }
var $data = []; var currentPage = 1; var recordsPerPage = 5; let getData = new Promise((resolve, reject) => { resolve( fetch("/assets/data/data.json") .then(res => res.json()) .then(data => data._embedded.episodes) ); }); getData.then(data => { $data = data; changePage(1); }); function prevPage() { if (currentPage > 1) { currentPage--; changePage(currentPage); } } function nextPage() { if (currentPage < numPages()) { currentPage++; changePage(currentPage); } } function changePage(page) { var table = document.createElement("table"); table.setAttribute("class", "table"); var col = []; var btn_next = document.getElementById("btn_next"); var btn_prev = document.getElementById("btn_prev"); var listing_table = document.getElementById("listingTable"); var page_span = document.getElementById("page"); // Validate page if (page < 1) page = 1; if (page > numPages()) page = numPages(); listing_table.innerHTML = ""; for (var i = 0; i < $data.length; i++) { for (var key in $data[i]) { if (col.indexOf(key) === -1) { col.push(key); } } } var tr = table.insertRow(-1); for (var i = 0; i < col.length; i++) { var th = document.createElement("th"); th.innerHTML = col[i] + `<span class="filter ${col[i]}"><i class="fa fa-chevron-down" aria-hidden="true"></i></span>`; tr.appendChild(th); } for ( var i = (page - 1) * recordsPerPage; i < page * recordsPerPage; i++ ) { var innerData = $data[i]; var tr = table.insertRow(-1); for (let item in innerData) { var tabCell = tr.insertCell(-1); if (item == "_links") { tabCell.innerHTML = $data[i][item].self.href; } else if (item == "image") { tabCell.innerHTML = `<img src='${$data[i][item].medium}' />`; } else { tabCell.innerHTML = $data[i][item]; } } } page_span.innerHTML = page; if (page == 1) { btn_prev.classList.add("hidden"); btn_prev.classList.remove("visible"); } else { btn_prev.classList.add("visible"); btn_prev.classList.remove("hidden"); } if (page == numPages()) { btn_next.classList.add("hidden"); btn_next.classList.remove("visible"); } else { btn_next.classList.add("visible"); btn_next.classList.remove("hidden"); } var divContainer = document.getElementById("listingTable"); divContainer.innerHTML = ""; divContainer.appendChild(table); var el = document.querySelectorAll('.filter'); for(var i=0; i < el.length; i++){ el[i].addEventListener('click', function () { var filterName = this.classList[1]; var newArr = []; var getdata = $data.map(item=>{ newArr.push(item[filterName]) }) let unique = newArr.filter((item, i, ar) => ar.indexOf(item) === i); console.log(unique); var divElement = document.createElement('div'); divElement.classList="popUp"; const createPop = unique.map(item=>{ return `<div>${item}</div>` }) divElement.innerHTML = createPop; this.appendChild(divElement) }, false); } } function numPages() { return Math.ceil($data.length / recordsPerPage); }
import {UserDropdownSystemItem} from "../userDropdownItem"; /** Div which contains Logo svg */ export const StyledDropdownSettingsItem = UserDropdownSystemItem
var searchData= [ ['h_5fto_5fintl',['H_TO_INTL',['../envelope_8c.html#a9ddc5b683d5a87677c1756fe44ff4217',1,'envelope.c']]], ['hc_5ffext',['HC_FEXT',['../pop_8c.html#ab0029aa20b987416bdcd51e73e7091b5',1,'pop.c']]], ['hc_5ffirst',['HC_FIRST',['../history_8c.html#a405244b558f153aeea5586728370eb85',1,'history.c']]], ['hc_5ffname',['HC_FNAME',['../pop_8c.html#a33dd225b4dd2d3c29644e01b60cf4723',1,'pop.c']]], ['hcache_5fget_5fops',['hcache_get_ops',['../hcache_8c.html#a51511cd14787b537b38ed24431384743',1,'hcache.c']]], ['hexval',['hexval',['../mime_8h.html#ac212ee80d510d8f8af8fde1675b910a3',1,'mime.h']]], ['hspace',['HSPACE',['../rfc2047_8c.html#ae5a216c48811ce4274751b1ffed405da',1,'rfc2047.c']]] ];
//Module dependencies. var express = require('express'); var app = express(); var http = require('http'); var path = require('path'); var cors = require('cors') var handlebars = require('express3-handlebars') bodyParser = require('body-parser'); app.set('views', path.join(__dirname, 'views')); app.engine('handlebars', handlebars()); app.set('view engine', 'handlebars'); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); app.use(cors()); // Routes var routes = require("./routes/metricsRoutes"); routes(app); port = process.env.PORT || 3000; var server = app.listen(8081, function () { console.log('Express server listening on port ' + server.address().port); })
import React, { Component } from 'react'; import { Container, Text } from 'react-pixi-fiber'; import Box from 'Client/Components/Box'; import FlatButton from 'Client/Components/FlatButton'; import Animated from 'animated'; import { connect } from 'react-redux'; const AnimatedBox = Animated.createAnimatedComponent(Box); //const AnimatedFlatButton = Animated.createAnimatedComponent(FlatButton); const AnimatedContainer = Animated.createAnimatedComponent(Container); class Modal extends Component { componentDidMount = () => { window.onkeydown = e => { if(e.keyCode === 27) { this.props.onDismiss(); } } } componentWillUnmount = () => { window.onkeydown = null; } render() { const { offset, width, height } = this.props; return ( <AnimatedContainer interactive width={this.props.contentWidth} height={this.props.contentHeight} alpha={offset}> <AnimatedBox width={this.props.contentWidth} height={this.props.contentHeight} alpha={0.5} /> <Container x={this.props.contentWidth/2 - width/2} y={this.props.contentHeight/2 - height/2} width={width} height={height}> <Box color={0x0} alpha={0.7} width={width} height={height} /> <Text anchor={[0.5, 0.5]} position={[width/2, height/2]} text={this.props.text} style={{ fill: 0xffffff, fontSize: 16, align: 'center' }} /> <FlatButton x={width/2 - 50} y={height - 50} width={100} height={36} text={this.props.buttonText} onClick={this.props.onDismiss} /> </Container> </AnimatedContainer> ); } } export default connect( state => ({ contentWidth: state.canvasModule.contentWidth, contentHeight: state.canvasModule.contentHeight, }), )(Modal);
import React from "react"; import Dialog from "@material-ui/core/Dialog"; // import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogActions from "@material-ui/core/DialogActions"; // import DialogContentText from "@material-ui/core/DialogContentText"; import DialogTitle from "@material-ui/core/DialogTitle"; import Slide from "@material-ui/core/Slide"; import withStyles from "@material-ui/core/styles/withStyles"; import IconButton from "@material-ui/core/IconButton"; import Tooltip from "@material-ui/core/Tooltip"; import DeleteIcon from "@material-ui/icons/Delete"; // @material-ui/icons import Close from "@material-ui/icons/Close"; import modalStyle from "../../assets/jss/material-kit-react/modalStyle"; import Button from "../../components/CustomButtons/Button"; function Transition(props) { return <Slide direction="up" {...props} />; } class DeleteTableItemModal extends React.Component { constructor(props) { super(props); this.state = { open: false, }; } componentWillReceiveProps(newsProps) { const { openModal } = this.props; if (newsProps.openModal !== undefined && openModal !== newsProps.openModal) { this.setState({ open: newsProps.openModal, }); } } handleClickOpen = () => { this.setState({ open: true }); }; handleClose = () => { this.setState({ open: false }); }; render() { const { classes, itemName, numberOfItems, onDeleteItem, mainTitle, mainCtn, buttonCtn, children, } = this.props; const { open } = this.state; let mainHeader; let mainContant; let buttonContent; if (mainTitle === undefined) { mainHeader = ( <h4 className={classes.modalTitle}> Delete&nbsp; {numberOfItems === 1 ? itemName.single : itemName.plural} </h4> ); } else { mainHeader = mainTitle; } if (mainCtn === undefined) { mainContant = ( <h5> You are about to delete&nbsp; {numberOfItems} &nbsp; {numberOfItems === 1 ? itemName.single : itemName.plural} </h5> ); } else { mainContant = mainCtn; } if (buttonCtn === undefined) { buttonContent = ` Delete ${numberOfItems} ${numberOfItems === 1 ? itemName.single : itemName.plural} `; } else { buttonContent = buttonCtn; } return ( <div> <Tooltip title="Delete"> { children !== undefined ? children : ( <IconButton aria-label="Delete"> <DeleteIcon onClick={this.handleClickOpen} style={{ fontSize: "18px" }} /> </IconButton> ) } </Tooltip> <Dialog classes={{ root: classes.center, paper: classes.modal, }} open={open} TransitionComponent={Transition} keepMounted onClose={this.handleClose} aria-labelledby="modal-slide-title" aria-describedby="modal-slide-description" > <DialogTitle id="classic-modal-slide-title" disableTypography className={classes.modalHeader} > <IconButton className={classes.modalCloseButton} key="close" aria-label="Close" color="inherit" onClick={this.handleClose} > <Close className={classes.modalClose} /> </IconButton> {mainHeader} </DialogTitle> <DialogContent id="modal-slide-description" className={classes.modalBody} > {mainContant} </DialogContent> <DialogActions className={`${classes.modalFooter} ${classes.modalFooterCenter}`} > <Button color="primary" onClick={this.handleClose} > Cancel </Button> <Button color="danger" onClick={onDeleteItem} > {buttonContent} </Button> </DialogActions> </Dialog> </div> ); } } export default withStyles(modalStyle)(DeleteTableItemModal);
export * from './DateInputs'
// Render the circles using React! const App = (props) => { let { circles } = props; let circleComponents = circles.map( (circle, arrayIndex) => { return <Circle circle={circle} key={arrayIndex}/> }); return <div>{circleComponents}</div> }
$(function() { // let backMusic = $("<audio src='../music/background.mp3' autoplay id='hint'/>");//加bg音乐 // backMusic.appendTo("body"); /*自动播放 */ let index = 0; //当前按钮的位置 let next = 0; let per = 0; let btnT = false; //判断是否能继续点击 let backMusic = document.getElementsByClassName("backMusic")[0]; $("body").on("click", function() { setTimeout(function() { backMusic.play(); //继续bg音乐 }, 2000); }) /*点击门打开 */ $(".door").on("click", function() { showSound("../music/playDoor.mp3"); $(".leftDoor").css({ animation: "leftRun 3s linear forwards" }) $(".rightDoor").css({ animation: "rightRun 3s linear forwards" }) setTimeout(function() { $(".door").css({ "left": "-200%" }); }, 3000); // $(".leftDoor").animate({transform: "rotateY(120deg)"},5000) // $(".rightDoor").animate({transform: "rotateY(-120deg)"},5000,function(){ // $(".door").css({left:"-200%"}); // }) }) //点击按钮播放视频 $(".playBtn").on("click", function() { showSound("../music/clickOn.mp3"); $(".videos").css({ "left": "50%" }); $(".videos video").trigger("load"); //重新加载视频 $(".videos video").trigger("play"); //播放视频 backMusic.pause(); //暂停bg音乐 }) //点击X按钮关闭视频 $(".close").on("click", function() { showSound("../music/clickOn.mp3"); $(".videos").css({ "left": "500%" }); $(".videos video").trigger("pause"); //暂停视频 backMusic.play(); //继续bg音乐 }) let srcArr = [{ src1: "../image/promptBox/star2.png", src2: "../image/promptBox/star1.png" }, { src1: "../image/promptBox/ruleGame2.png", src2: "../image/promptBox/ruleGame1.png" }, { src1: "../image/promptBox/setGame2.png", src2: "../image/promptBox/setGame1.png" }, { src1: "../image/promptBox/exitGame2.png", src2: "../image/promptBox/exitGame1.png" } ] for (let i = 0; i < $(".lunbo").length; i++) { //鼠标放在标签上改变图片 $(".lunbo").eq(i).mouseover(function() { $(".lunbo:eq(" + i + ") img").attr({ src: srcArr[i].src1 }) }); //鼠标移开标签上改变图片 $(".lunbo").eq(i).mouseout(function() { $(".lunbo:eq(" + i + ") img").attr({ src: srcArr[i].src2 }) }); } //点击左边按钮左移 $(".left").on("click", function() { showSound("../music/clickOn.mp3"); //判断是否继续执行 if (btnT == true) { return; } btnT = true; for (let i = 0; i < $(".lunboContent .lunbo").length; i++) { if (i > index) { $(".lunboContent .lunbo").eq(i).css({ "left": "100%" }) } if (i < index) { $(".lunboContent .lunbo").eq(i).css({ "left": "-70%" }) } if (index == 3) { $(".lunboContent .lunbo").eq(0).css({ "left": "100%" }) } } next = index + 1; if (next == 4) { next = 0 } $(".lunboContent .lunbo").eq(next).addClass("lunbo1"); $(".lunboContent .lunbo").eq(next).animate({ "left": "15%" }, 1000) $(".lunboContent .lunbo").eq(index).animate({ "left": "-70%" }, 1000, function() { $(".lunboContent .lunbo").eq(index).removeClass("lunbo1"); index++; if (index == 4) { index = 0; } btnT = false; }); }) //点击右边按钮左移 $(".right").on("click", function() { showSound("../music/clickOn.mp3"); //判断是否继续执行 if (btnT == true) { return; } btnT = true; for (let i = 0; i < $(".lunboContent .lunbo").length; i++) { if (i > index) { $(".lunboContent .lunbo").eq(i).css({ "left": "100%" }) } if (i < index) { $(".lunboContent .lunbo").eq(i).css({ "left": "-70%" }) } if (index == 0) { $(".lunboContent .lunbo").eq(3).css({ "left": "-70%" }) } } per = index - 1; if (per == -1) { per = 3; } $(".lunboContent .lunbo").eq(per).addClass("lunbo1"); $(".lunboContent .lunbo").eq(per).animate({ "left": "15%" }, 1000) $(".lunboContent .lunbo").eq(index).animate({ "left": "100%" }, 1000, function() { $(".lunboContent .lunbo").eq(index).removeClass("lunbo1"); index--; if (index == -1) { index = 3; } btnT = false; }); }) /*点击退出游戏按钮 */ $(".exit").on("click", function() { showSound("../music/clickOn.mp3"); $(".quit").css({ "left": "0" }) }) /*点击取消退出游戏 */ $(".quitNo").on("click", function() { showSound("../music/clickOn.mp3"); $(".quit").css({ "left": "-200%" }); }) /*点击确定退出游戏 */ $(".quitOk").on("click", function() { showSound("../music/clickOn.mp3"); window.close(); }) /** * 产生音效 * @param audioSrc :音频路径 */ function showSound(audioSrc) { $("#hint").remove(); /**因为音效元素是追加的,所以每次生成之前,将原来的删除掉*/ var audioJQ = $("<audio src='" + audioSrc + "' autoplay id='hint'/>"); audioJQ.appendTo("body"); /**创建 audio 标签的 Jquery 对象,然后追加到 body 进行播放*/ } /*滚动滚轮事件,通过滑动滚轮实现按钮上下移动 */ $(".lunboContent").on("mousewheel DOMMouseScroll", function(e) { let delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) || (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1)); //获得当前对象的位置 if (delta > 0) { //判断滚轮是向上滚动还是向下滚动 $(".right").click(); } if (delta < 0) { $(".left").click(); } }); let mid = document.getElementsByClassName("mid")[0]; let shuoming = document.getElementById("shuoming"); let gameset = document.getElementById("gameset") let setflag = 0; let settings = document.getElementsByClassName("settings")[0]; gameset.addEventListener("click", function() { if (setflag == 0) { settings.style.display = "block"; setflag = 1; } else { settings.style.display = "none"; setflag = 0; } }); shuoming.addEventListener("click", function() { mid.style.display = "block"; }); let close1 = document.getElementsByClassName("close1")[0]; close1.addEventListener("click", function() { mid.style.display = "none"; }); let pros = document.getElementById("changePro").getElementsByTagName("ul")[0].getElementsByTagName("li"); let proshow = document.getElementsByClassName("info") for (let i = 0; i < pros.length; i++) { pros[i].onmouseover = () => { let new_index1 = i; index1 = new_index1; changePro(index1) changeProshow(index1) } } function changeProshow(index1) { for (let i = 0; i < proshow.length; i++) { proshow[i].style.display = "none"; } proshow[index1].style.display = "block"; } function changePro(index1) { for (let i = 0; i < pros.length; i++) { pros[i].className = ""; } pros[index1].className = "on"; } })
import React from 'react' import { ActivityIndicator, KeyboardAvoidingView, Platform, ScrollView, Image, TouchableOpacity, FlatList, View, Dimensions, TextInput, DeviceEventEmitter, TouchableHighlight, Alert, ImageBackground, Linking, } from 'react-native' import { colors } from '../../theme'; import { DIMENS, API, KEY, LOCALES, FONT_FAMILIY, SCREEN } from '../../constants'; import { storeData, retrieveData, clearData } from '../../common/AsyncStorage' //Library import Orientation from 'react-native-orientation'; import Svg, { Circle, G, LinearGradient, Path, Defs, Stop, Line, Text } from 'react-native-svg'; import range from 'lodash.range'; export default class AssignmentOne extends React.PureComponent { constructor(props) { super(props) this.state = { radius: 150, strokeWidth: 20, showClockFace: true, } } componentDidMount() { console.log('componentDidMount of AssignmentOne screen') Orientation.lockToPortrait(); } componentWillUnmount() { console.log('componentWillUnmount of AssignmentOne screen') } getContainerWidth() { const { strokeWidth, radius } = this.state; return strokeWidth + radius * 2 + 2; } toRadians(angle) { return angle * (Math.PI / 180); } getRadianForHour(h, m){ return this.toRadians(((h*30) + (m*0.5)) - 90) } getRadianForMinute(m){ return this.toRadians(m * 6 - 90) } render() { const { data, loading } = this.props const { radius, strokeWidth, showClockFace } = this.state; const containerWidth = this.getContainerWidth(); const textRadius = (radius - strokeWidth / 2) - 20; //20 = external padding for text return ( <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <View style={{ width: containerWidth, height: containerWidth, }}> <Svg height={containerWidth} width={containerWidth} ref={circle => this._circle = circle} > <G transform={{ translate: `${strokeWidth / 2 + radius}, ${strokeWidth / 2 + radius}` }}> <Circle r={radius} strokeWidth={strokeWidth} fill="transparent" stroke={colors.color_primary} /> { showClockFace && ( <G> { range(12).map((h, i) => ( <Text key={i} fill={colors.color_black} fontSize="16" textAnchor="middle" x={textRadius * Math.cos(this.toRadians(i * 30 - 60))} y={textRadius * Math.sin(this.toRadians(i * 30 - 60)) + 16 / 2} //16/2 = Half of font size > {h + 1} </Text> )) } </G> ) } { <Line stroke={colors.color_primary} strokeWidth={5} x1={0} y1={0} x2={(textRadius - 40) * Math.cos(this.getRadianForHour(4,13))} y2={(textRadius - 40) * Math.sin(this.getRadianForHour(4,13))} /> } { <Line stroke={colors.color_primary} strokeWidth={5} x1={0} y1={0} x2={(textRadius - 10) * Math.cos(this.getRadianForMinute(13))} y2={(textRadius - 10) * Math.sin(this.getRadianForMinute(13))} /> } </G> </Svg> </View> </View> ) } }
var UnityWebGlHttpHandlerPlugin = { HttpRequest: function (requestPointer) { var debug = false; debug && console.debug("HttpRequest"); try { var requestString = Pointer_stringify(requestPointer); debug && console.debug("HttpRequest::requestString::" + requestString); var request = JSON.parse(requestString); debug && console.debug("HttpRequest::XMLHttpRequest::request" + request); debug && console.debug("HttpRequest::XMLHttpRequest::Open"); var xhr = new XMLHttpRequest(); xhr.open(request.method, request.url, false); debug && console.debug("HttpRequest::XMLHttpRequest::withCredentials"); var headers = Object.getOwnPropertyNames(request.headers); if (headers.indexOf("Authorization") > -1 && headers["Authorization"]) { debug && console.debug("HttpRequest::XMLHttpRequest::authHeaderFound"); xhr.withCredentials = true; } xhr.setRequestHeader('Content-Type', 'application/json'); debug && console.debug("HttpRequest::XMLHttpRequest::setRequestHeader"); Object.getOwnPropertyNames(request.headers) .forEach(function(headerName) { xhr.setRequestHeader(headerName, request.headers[headerName]); }); debug && console.debug("HttpRequest::XMLHttpRequest::send"); xhr.send(request.content); debug && console.debug("HttpRequest::XMLHttpRequest::getAllResponseHeaders"); var headersObj = {}; xhr.getAllResponseHeaders() .split(/\r|\n/) .forEach(function(pair) { var pairsplit = pair.split(': '); if (pairsplit != "") { headersObj[pairsplit[0]] = pairsplit[1]; } }); debug && console.debug("HttpRequest::responseObj"); var responseObj = { content: xhr.responseText, headers: headersObj, statusCode: xhr.status }; var responseString = JSON.stringify(responseObj); debug && console.debug("HttpRequest::responseString::" + responseString); var buffer = _malloc(lengthBytesUTF8(responseString) + 1); debug && console.debug("HttpRequest::writeStringToMemory"); writeStringToMemory(responseString, buffer); return buffer; } catch (exception) { debug && console.debug("HttpRequest::Exception::" + exception); return JSON.stringify({ statusCode: 599 }); } } }; mergeInto(LibraryManager.library, UnityWebGlHttpHandlerPlugin);
/** * Controller */ class Controller { constructor(){ this.scope = new Scope(); } init(){ parseDom(document.body, this.scope); digest(); } }
/* * Sample implementation */ $(function(){ // Implementation $('#swipe').swipe({ swipeTime: 800, swipeX: 100, left: swipeLeft, right: swipeRight }); // Left/Right custom functions function swipeLeft(){ console.log('user swiped left'); } function swipeRight(){ console.log('user swiped right'); } });
let counter = 0; function nextId() { const res = `[${counter}]`; ++counter; return res; } cc.Class({ extends: cc.Component, properties: { label: { default: null, type: cc.Label }, }, // use this for initialization onLoad: function () { this.clearLog(); this.test("ws://echo.websocket.org") .then(() => this.test("wss://echo.websocket.org")); }, log: function (msg) { this.label.string += msg; this.label.string += "\n"; }, clearLog: function () { this.label.string = ""; }, test: function (url) { return new Promise((resolve, reject) => { const id = nextId(); const ws = new WebSocket(url, [], "cacert.pem"); this.log(id + "new: " + url); ws.onopen = (ev) => { this.log(id + "open: " + JSON.stringify(ev)); ws.send("ping"); }; ws.onmessage = (ev) => { this.log(id + "message: " + ev.data); ws.close(); resolve(); }; ws.onclose = (ev) => { this.log(id + "close: " + JSON.stringify(ev)); resolve(); } ws.onerror = (ev) => { this.log(id + "error: " + JSON.stringify(ev)); resolve(); } }); } });
const mongoose = require('mongoose') const config = require('config') const databaseLink = config.get('mongoURI') const connectDB = async () => { //any kind of connection need try-catch try { await mongoose.connect(databaseLink, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true }) console.log('MongoDB connected...'); } catch (error) { console.log(error.message); process.exit(1); //fail -> exit the process } } module.exports = connectDB;
/* * @lc app=leetcode id=1002 lang=javascript * * [1002] Find Common Characters */ // @lc code=start /** * @param {string[]} A * @return {string[]} */ var commonChars = function(A) { const cMap = {}; for (let i = 0; i < A.length; i++) { const string = A[i]; for (let c of string) { if (cMap[c]) { cMap[c][i]++; } else { cMap[c] = Array(A.length).fill(0); cMap[c][i] = 1; } } } let result = ''; for (let c in cMap) { const minCount = cMap[c].reduce((min, i) => Math.min(min, i)) if (minCount) { result += c.repeat(minCount); } } return result.split(''); }; // @lc code=end
$('li.hot')
var express = require('express'); var mongoose = require ('mongoose'); var app = express(); var port = process.env.PORT || 21000; var User = require('./model/user'); var bodyParser = require('body-parser'); var mongodb = require('mongodb'); var ObjectID = mongodb.ObjectID; var CONT_C = "users"; var expressValidator = require('express-validator'); var Register = require('./routes/register'); var Login = require('./routes/login'); var Changepass = require('./routes/chgpass'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(expressValidator()); mongoose.connect(process.env.MONGODB_URI ); //mongoose.connect( 'mongodb://localhost:27017/t4'); //mongodb.MongoClient.connect(process.env.MONGODB_URI || 'mongodb://heroku_kvw9cb8w:m6o009iinbrs95k6s3nl1m2843@ds119585.mlab.com:19585/heroku_kvw9cb8w' , function(err, database) //mongodb.MongoClient.connect(process.env.MONGODB_URI || 'mongodb://localhost/tento' , function(err, database) // //{ // if(err) // { // console.log(err); // process.exit(1); // } // // db = database; // console.log("database connection ready"); //}) app.get('/home',function(req, res) { res.json({"status":"welcome to OAU suppoert, what may we do for you today?"}); }); app.post('/api/signUp', function(req, res) { var firstname = req.body.firstname; var lastname = req.body.lastname; var username = req.body.username; var email = req.body.email; var password = req.body.password; var phone = req.body.phone; req.checkBody('email', 'Email is required').notEmpty(); req.checkBody('firstname', 'First Name is required').notEmpty(); req.checkBody('lastname', 'Last Name is required').notEmpty(); req.checkBody('username', 'Username is required').notEmpty(); req.checkBody('phone', 'phone is not valid').notEmpty(); req.checkBody('email', 'Email is not valid').isEmail(); req.sanitize('email').normalizeEmail({ remove_dots: false }); // Check for validation errors var errors = req.validationErrors(); if (errors) { return res.status(400).send(errors); } else { //Register.register(email,password,phone,firstname,lastname,username, function (found) console.log('inside now') Register.register(email,password,phone,username,firstname,lastname, function (found) { console.log(found); res.json(found); }); } }) app.post('/api/login', function (req, res) { var username = req.body.username; var password = req.body.password; Login.login(username, password, function (found) { console.log(found); res.json(found); }); }); app.post('/api/chgpass', function(req, res) { var id = req.body.id; var opass = req.body.oldpass; var npass = req.body.newpass; Changepass.cpass(id,opass,npass,function(found){ console.log(found); res.json(found); }); }); app.post('/api/resetpass', function(req, res) { var email = req.body.email; Changepass.respass_init(email,function(found){ console.log(found); res.json(found); }); }); app.post('/api/resetpass/chg', function(req, res) { var email = req.body.email; var code = req.body.code; var npass = req.body.newpass; Changepass.respass_chg(email,code,npass,function(found){ console.log(found); res.json(found); }); }); app.listen(process.env.PORT || 9000, function() { console.log('listening on: 9000') });
import React, { useContext } from 'react'; import { FormControl } from 'react-bootstrap'; import { UiContext } from '../../contexts/ui/ui.context'; import { updateSearchField } from '../../contexts/ui/ui.actions'; const SearchBar = () => { const { state: { searchField }, dispatch } = useContext(UiContext); const handleSearchField = e => { dispatch(updateSearchField(e.target.value)); }; return ( <FormControl style={{opacity: 0.8}} type="text" value={searchField} placeholder="Search" onChange={handleSearchField} /> ); }; export default SearchBar;
import React from "react"; import CardList from "./CardList"; const CardSection = props => { return ( <div className="row"> <CardList key={props.id} /> </div> ); }; export default CardSection;
var searchData= [ ['_7ecollar',['~Collar',['../class_collar.html#a01eb61e5442322342d2823e3238a6b49',1,'Collar']]], ['_7edog',['~Dog',['../class_dog.html#aeacf410641eab28eabea6bc5269eb4ef',1,'Dog']]], ['_7emyvect',['~MyVect',['../class_my_vect.html#a4d71588bb6915adbd6cf32554bdc4264',1,'MyVect']]] ];
self.__precacheManifest = [ { "revision": "ea41e95b8dcdef16e751", "url": "/static/css/main.8ab80e09.chunk.css" }, { "revision": "ea41e95b8dcdef16e751", "url": "/static/js/main.d16627b9.chunk.js" }, { "revision": "42ac5946195a7306e2a5", "url": "/static/js/runtime~main.a8a9905a.js" }, { "revision": "65dff4bb236bf37ff1a8", "url": "/static/js/2.5ba26064.chunk.js" }, { "revision": "7a77301f5a15e5a0b5f280b4a7e388bb", "url": "/index.html" } ];
import React from 'react'; import uuid from "uuid/v4"; import {getIndentSpace, INDENT_SPACE} from "@/pages/drag-page/utils"; export const category = '原生HTML元素'; export const icon = 'html5'; export default { text: { component: 'text', title: '纯文本', visible: false, noWrapper: true, // 直接渲染,不拖拽包裹 defaultProps: { content: '纯文本', }, render: props => props.content, toSource: ({props}) => props.content, }, tip: { component: 'pre', title: '额外说明', toSource: ({props, __indent}) => { const {children: [{content}]} = props; const indentSpace = getIndentSpace(__indent); const indentSpace2 = getIndentSpace(__indent + INDENT_SPACE); return content ? `{/* TODO\n${indentSpace2}${content.split('\n').join('\n' + indentSpace2)} \n${indentSpace}*/}` : ''; }, description: ( <div> <div>一般可以用来添加一些额外的说明,给开发人员一些提示。</div> <div>生成代码时,将会转换成注释。</div> </div> ), editType: 'textarea', defaultProps: { style: { padding: 8, border: '1px dashed #ffa39e', background: '#fff1f0', wordBreak: 'break-all', overflowWrap: 'break-word', }, children: [ { __type: 'text', __id: uuid(), content: '额外说明:', }, ], }, }, span: { component: 'span', title: '行内元素', display: 'inline-block', // 如果使用inline,布局会有些问题,这里使用inline-block defaultProps: { children: [ { __type: 'text', __id: uuid(), content: '行内元素(span)', } ], }, }, div: { component: 'div', title: '块级元素', container: true, defaultProps: { style: { minHeight: 30, minWidth: 50, }, children: [ { __type: 'text', __id: uuid(), content: '块级元素(div)', } ], }, }, divInline: { component: 'div', title: '行内块级元素', container: true, display: 'inline-block', defaultProps: { style: { display: 'inline-block', minHeight: 30, minWidth: 50, }, children: [ { __type: 'text', __id: uuid(), content: '行内块级元素(div)', } ], }, }, };
import jsonld from 'jsonld'; var RoutableTilesToGeoJSON = require('./RoutableTilesToGeoJSON'); //Make sure the client works var Client = require('demo-routable-tiles-client'); /* * 🍂class VectorGrid.RoutableTiles * 🍂extends VectorGrid * * A `VectorGrid` for routable tiles fetched from the internet. * Tiles are supposed to be json-ld documents * containing data which complies with the * [Routable Tiles Specification](https://github.com/openplannerteam/website/pull/2). * * This is the format used by the [Open Planner Team](https://openplanner.team) * * 🍂example * * You must initialize a `VectorGrid.RoutableTiles` with a URL template, just like in * `L.TileLayer`s. The difference is that the template must point to routable tiles * instead of raster (`.png` or `.jpg`) tiles, and that * you should define the styling for all the features. * */ L.VectorGrid.RoutableTiles = L.VectorGrid.extend({ options: { // 🍂section // As with `L.TileLayer`, the URL template might contain a reference to // any option (see the example above and note the `{key}` or `token` in the URL // template, and the corresponding option). // // 🍂option subdomains: String = 'abc' // Akin to the `subdomains` option for `L.TileLayer`. subdomains: 'abc', // Like L.TileLayer // // 🍂option fetchOptions: Object = {} // options passed to `fetch`, e.g. {credentials: 'same-origin'} to send cookie for the current domain fetchOptions: {} }, initialize: function (url, options) { // Inherits options from geojson-vt! // this._slicer = geojsonvt(geojson, options); this._url = url; L.VectorGrid.prototype.initialize.call(this, options); }, // 🍂method setUrl(url: String, noRedraw?: Boolean): this // Updates the layer's URL template and redraws it (unless `noRedraw` is set to `true`). setUrl: function (url, noRedraw) { this._url = url; if (!noRedraw) { this.redraw(); } return this; }, _getSubdomain: L.TileLayer.prototype._getSubdomain, _isCurrentTile: function (coords, tileBounds) { if (!this._map) { return true; } var zoom = this._map._animatingZoom ? this._map._animateToZoom : this._map._zoom; var currentZoom = zoom === coords.z; var tileBounds = this._tileCoordsToBounds(coords); var currentBounds = this._map.getBounds().overlaps(tileBounds); return currentZoom && currentBounds; }, _getVectorTilePromise: function (coords, tileBounds) { var data = { s: this._getSubdomain(coords), x: coords.x, y: coords.y, // z: coords.z // z: this._getZoomForUrl() /// TODO: Maybe replicate TileLayer's maxNativeZoom z: 14 //hard-coded for now }; if (this._map && !this._map.options.crs.infinite) { var invertedY = this._globalTileRange.max.y - coords.y; if (this.options.tms) { // Should this option be available in Leaflet.VectorGrid? data['y'] = invertedY; } data['-y'] = invertedY; } if (!this._isCurrentTile(coords, tileBounds)) { return Promise.resolve({ layers: [] }); } var tileUrl = L.Util.template(this._url, L.extend(data, this.options)); var context = { "tiles": "https://w3id.org/tree/terms#", "hydra": "http://www.w3.org/ns/hydra/core#", "osm": "https://w3id.org/openstreetmap/terms#", "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "geo": "http://www.w3.org/2003/01/geo/wgs84_pos#", "dcterms": "http://purl.org/dc/terms/", "dcterms:license": { "@type": "@id" }, "hydra:variableRepresentation": { "@type": "@id" }, "hydra:property": { "@type": "@id" }, "osm:hasNodes": { "@container": "@list", "@type": "@id" }, "osm:highway" :{ "@type":"@id" } }; //, this.options.fetchOptions ? return jsonld.promises.compact(tileUrl, context).then(function (json) { var feats = RoutableTilesToGeoJSON(json); //geojsonvt outputs tags properties cfr. the vector spec, yet this library needs properties instead let vtfeatures = geojsonvt(feats).getTile(14, coords.x, coords.y).features.map((item) => { return { type: item.type, geometry: item.geometry, id: item.id, properties: item.tags } }); let result = { layers: { "Routable Tiles": { extent: 4096, features: vtfeatures, name: "Routable Tiles", length: feats.length } } }; return result; }); } }); // 🍂factory L.vectorGrid.routableTiles(url: String, options) // Instantiates a new routable tiles VectorGrid with the given URL template and options L.vectorGrid.routableTiles = function (url, options) { return new L.VectorGrid.RoutableTiles(url, options); };
// Chart design for T scores based on original bullet chart by Mike Bostock: // http://bl.ocks.org/mbostock/4061961 // with d3.chart.js (0.1.2) // http://misoproject.com/d3-chart/ d3.chart("BulleT", { initialize: function() { var chart = this; this.xScale = d3.scale.linear(); this.base.classed("BulleT", true); this.titleGroup = this.base.append("g"); this.title = this.titleGroup.append("text") .attr("class", "title"); this.dimension = this.titleGroup.append("text") .attr("class", "subtitle s2"); this.subtitle = this.titleGroup.append("text") .attr("class", "subtitle s2"); // Default configuration this._margin = { top: 0, right: 0, bottom: 0, left: 0 }; this.orientation(""); this.duration(0); this.markers = "0"; this.measures(function(d) { return d.measures; }); this.width(100); this.height(100); this.tickFormat(this.xScale.tickFormat(d3.format("+.0d"))); this.reverse(true); this.orient("left"); this.limits(function(d) { return d.limits; }); this.ranges(function(d) { return d.ranges; }); this.rangesLine(function(d) { return d.rangesLine; }); this.layer("ranges", this.base.append("g").classed("ranges", true), { dataBind: function(data) { var data_ranges = new Array(); // @CodeXmonk: a bit of hack too - ToDo later. This layer operates on "ranges" data, ranges[2] not needed data_ranges[0] = data.ranges[0]; data_ranges[1] = data.ranges[1]; data_ranges[2] = data.ranges[2]; data_ranges[3] = data.ranges[3]; limits = data.limits; data_ranges.unshift(limits[1]); return this.selectAll("rect.range").data(data_ranges); }, insert: function() { return this.append("rect"); }, events: { enter: function(d, i) { var orientation = chart.orientation(); var limits = chart.limits; this.attr("class", function(d, i) { return "range s" + i; }) .attr("width", chart.xScale) .attr("height", function(){ if( orientation == "vertical" ){ return chart.width(); }else{ return chart.height(); } }) .attr("x", this.chart()._reverse ? chart.xScale : limits[0]); //Usage: condition ? value-if-true : value-if-false }, "merge:transition": function() { var limits = chart.limits; this.duration(chart.duration()) .attr("width", chart.xScale) .attr("x", chart._reverse ? chart.xScale : limits[0]); }, exit: function() { this.remove(); } } }); /******************************************************************************/ this.layer("rangesLine", this.base.append("g").classed("rangesLine", true), { dataBind: function(data) { // @CodeXmonk: This layer operates on "ranges" data data_rangesLine = data.rangesLine; return this.selectAll("line.range").data(data_rangesLine); }, insert: function() { return this.append("line"); }, events: { enter: function(d, i) { var orientation = chart.orientation(); this.attr("class", function(d, i) { return "range line"; }) .attr("x1", chart.xScale) .attr("x2", chart.xScale) .attr("y1", 0) .attr("y2", function(){ if( orientation == "vertical" ){ return chart.width(); }else{ return chart.height(); } }); }, "merge:transition": function() { var orientation = chart.orientation(); this.attr("class", function(d, i) { return "range line"; }) .attr("x1", chart.xScale) .attr("x2", chart.xScale) .attr("y1", 0) .attr("y2", function(){ if( orientation == "vertical" ){ return chart.width(); }else{ return chart.height(); } }); }, exit: function() { this.remove(); } } }); /******************************************************************************/ this.layer("measures", this.base.append("g").classed("measures", true), { dataBind: function(data) { // @CodeXmonk: This layer operates on "measures" data data_measures = data.measures; var limits = data.limits; data_measures.unshift(limits[1]); return this.selectAll("rect.measure").data(data_measures); }, insert: function() { return this.append("rect"); }, events: { enter: function() { var orientation = chart.orientation(); var hy; if( orientation == "vertical" ){ hy = chart.width() / 2; }else{ hy = chart.height() / 2; } var limits = chart.limits(); this.attr("class", function(d, i) { return "measure s" + i; }) .attr("width", chart.xScale) .attr("height", hy) .attr("x", limits[0]) .attr("y", hy/2); }, "merge:transition": function() { var limits = chart.limits; this.duration(chart.duration()) .attr("width", chart.xScale) .attr("x", limits[0]) } } }); /******************************************************************************/ this.layer("markerSample", this.base.append("g").classed("markerSample", true), { dataBind: function(data) { // @CodeXmonk: This layer operates on "markerSample" datum data = data.markers; return this.selectAll("line.marker").data("0"); }, insert: function() { return this.append("line"); }, events: { enter: function() { var orientation = chart.orientation(); var whichOne; if( orientation == "vertical" ){ whichOne = chart.width(); }else{ whichOne = chart.height(); } this.attr("class", "marker Sample") .attr("x1", chart.xScale) .attr("x2", chart.xScale) .attr("y1", whichOne / 4) .attr("y2", whichOne - (whichOne/4) ); }, "merge:transition": function() { var orientation = chart.orientation(); var whichOne; if( orientation == "vertical" ){ whichOne = chart.width(); }else{ whichOne = chart.height(); } this.duration(chart.duration()) .attr("x1", chart.xScale) .attr("x2", chart.xScale) .attr("y1", whichOne / 4) .attr("y2", whichOne - (whichOne/4) ); } } }); /******************************************************************************/ this.layer("ticks", this.base.append("g").classed("ticks", true), { dataBind: function() { var format = this.chart().tickFormat(); return this.selectAll("g.tick").data(this.chart().xScale.ticks(8), function(d) { return this.textContent || format(d); }); }, insert: function() { var orientation = chart.orientation(); var whichOne; if( orientation == "vertical" ){ whichOne = chart.width(); }else{ whichOne = chart.height(); } var tick = this.append("g").attr("class", "tick"); var height = whichOne; var format = chart.tickFormat(); tick.append("line") .attr("y1", whichOne) .attr("y2", whichOne * 7 / 6); tick.append("text") .attr("text-anchor", "middle") .attr("dy", "1em") .attr("y", whichOne * 7 / 6) .attr("transform", function(){ if( orientation == "vertical" ){ return "translate("+(whichOne+whichOne/2)+","+(whichOne+whichOne/2)+")rotate(90)"; } /* @CodeXmonk: if vertical BUT its not exact yet - ToDo */ }) .text(format); return tick; }, events: { enter: function() { this.attr("transform", function(d) { return "translate(" + chart.xScale(d) + ",0)"; }) .style("opacity",1); }, "merge:transition": function() { var orientation = chart.orientation(); var whichOne; if( orientation == "vertical" ){ whichOne = chart.width(); }else{ whichOne = chart.height(); } this.duration(chart.duration()) .attr("transform", function(d) { return "translate(" + chart.xScale(d) + ",0)"; }) .style("opacity", 1); this.select("line") .attr("y1", whichOne) .attr("y2", whichOne * 7 / 6); this.select("text") .attr("y", whichOne * 7 / 6); }, "exit:transition": function() { this.duration(chart.duration()) .attr("transform", function(d) { return "translate(" + chart.xScale(d) + ",0)"; }) .style("opacity", 1e-6) .remove(); } } }); d3.timer.flush(); }, transform: function(data) { var orientation = this.orientation(); var height = this.height(); if( orientation == "vertical" ){ this.base.attr("transform","translate(15," + ( height + 10 ) + ")rotate(-90)"); } // misoproject: Copy data before sorting var newData = { title: data.title, dimension: data.dimension, randomizer: data.randomizer, limits: data.limits.slice(), ranges: data.ranges.slice().sort(d3.descending), rangesLine: data.rangesLine.slice(), measures: data.measures.slice().sort(d3.descending), }; this.xScale.domain([newData.limits[0], newData.limits[1]]); this.titleGroup .style("text-anchor", function(){ if( orientation == "vertical" ){ return "middle"; }else{ return "end"; } } ); if( orientation == "vertical" ){ this.titleGroup.attr("transform", function(){ return "translate(-15,10)rotate(90)"}); } this.dimension .attr("dy", function(){ if( orientation == "vertical" ){ return "12px"; }else{ return "1.2em"; } }); this.subtitle .attr("dy", function(){ if( orientation == "vertical" ){ return "26px"; }else{ return "2.4em"; } }); this.title.text(data.title); this.dimension.text(data.dimension); //this.subtitle.text(data.markers[1]); return newData; }, // misoproject: reverse or not reverse: function(x) { if (!arguments.length) return this._reverse; this._reverse = x; return this; }, // misoproject: left, right, top, bottom orient: function(x) { if (!arguments.length) return this._orient; this._orient = x; this._reverse = this._orient == "right" || this._orient == "bottom"; return this; }, // @CodeXmonk: limits (20,80) limits: function(x) { if (!arguments.length) return this._limits; this._limits = x; return this; }, // misoproject: ranges (bad, satisfactory, good) ranges: function(x) { if (!arguments.length) return this._ranges; this._ranges = x; return this; }, // @CodeXmonk: for sample mean rangesLine: function(x) { if (!arguments.length) return this._ranges; this._ranges = x; return this; }, // misoproject: markers (previous, goal) markers: function(x) { if (!arguments.length) return this._markers; this._markers = x; return this; }, // misoproject: measures (actual, forecast) measures: function(x) { if (!arguments.length) return this._measures; this._measures = x; return this; }, width: function(x) { var margin, width_tmp; if (!arguments.length) { return this._width; } margin = this.margin(); width_tmp = x[0]; width_tmp = width_tmp - (margin.left + margin.right); this._width = width_tmp; if (x.length == 1){ /* @CodeXmonk: Scale needs to be put here when it's horizontal */ this.xScale.range(this._reverse ? [width_tmp, 0] : [0, width_tmp]); } this.base.attr("width", width_tmp); return this; }, height: function(x) { var margin, height_tmp; if (!arguments.length) { return this._height; } margin = this.margin(); height_tmp = x[0]; height_tmp = height_tmp - (margin.top + margin.bottom); this._height = height_tmp; if (x.length != 1){ /* @CodeXmonk: Scale needs to be put here when it's vertical */ this.xScale.range(this._reverse ? [height_tmp, 0] : [0, height_tmp]); } this.base.attr("height", height_tmp); this.titleGroup.attr("transform", "translate(-16," + height_tmp / 3 + ")"); return this; }, margin: function(margin) { if (!margin) { return this._margin; } var margin_tmp = margin; ["top", "right", "bottom", "left"].forEach(function(dimension) { if (dimension in margin_tmp) { this._margin[dimension] = margin_tmp[dimension]; } }, this); this.base.attr("transform", "translate(" + this._margin.left + "," + this._margin.top + ")"); return this; }, tickFormat: function(x) { if (!arguments.length) return this._tickFormat; this._tickFormat = x; return this; }, orientation: function(x) { if (!arguments.length) return this._orientation; this._orientation = x; return this; }, duration: function(x) { if (!arguments.length) return this._duration; this._duration = x; return this; } });
import React from 'react'; import { View, Text, StyleSheet, TextInput, TouchableOpacity, Image, Button } from 'react-native'; const Login = props => { return ( <View style={styles.container}> <Image style={styles.dcimg} source={require('../assets/DCLogo.png')} /> {/* <Text style={styles.greeting}>{`Hello agian.\n Welcome back.`}</Text> */} <View style={styles.errorMessage}> <Text>Error</Text> </View> <View style={styles.form}> <View> <Text style={styles.inputTitle}>Email Address</Text> <TextInput style={styles.input} autoCapitalize="none"></TextInput> </View> <View style={{marginTop: 32}}> <Text style={styles.inputTitle}>Password</Text> <TextInput style={styles.input} secureTextEntry autoCapitalize="none"></TextInput> </View> <Button onPress={() => { props.navigation.navigate({routeName: 'Home'}) }} style={styles.button} title="Sign In" > </Button> </View> </View> ) } const styles = StyleSheet.create({ container:{ flex: 1, backgroundColor:"#b753ef" }, dcimg:{ height: 250, width: 390, }, greeting:{ marginTop: 32, fontSize:18, fontWeight: "400", textAlign: "center" }, errorMessage:{ height: 72, alignItems: "center", justifyContent: "center", marginHorizontal: 30 }, form:{ marginBottom: 48, marginHorizontal: 30, marginTop: 80 }, inputTitle:{ color: "#8A8F9E", fontSize: 10, textTransform: 'uppercase' }, input:{ borderBottomColor: "#8A8F9E", borderBottomWidth: StyleSheet.hairlineWidth, height: 40, fontSize: 15, color: "#161F30" }, button: { marginHorizontal: 80, backgroundColor: "black", borderRadius: 4, height: 52, marginTop: 15, alignItems: "center", justifyContent: "center" } }) export default Login;
import { GET_GENRES, GET_GENRE, DELETE_GENRE, FETCH_GENRE_SEARCH, GENRE_LOADING } from "../actions/types"; const initialState = { genres : [], genre : {}, loading : true, searchQuery:'' } export default function(state = initialState, action){ switch (action.type) { case GENRE_LOADING: return { ...state, loading: true }; case GET_GENRES: return { ...state, genres: action.payload, loading: false }; case GET_GENRE: return { ...state, genre: action.payload, loading: false }; case DELETE_GENRE: return { ...state, genres: state.genres.filter(genre => genre._id !== action.payload) }; ///pembuatan case state genre search case FETCH_GENRE_SEARCH: return{ ...state, searchQuery : action.payload } default: return state; } }
import connection from "../../Bd/connection.js"; const deleteRent = async (req, res) => { try{ const id = req.params.id; const rental = await connection.query('SELECT * FROM rentals WHERE id = $1', [id]); if(!rental.rows[0]) return res.sendStatus(404); if(rental.rows[0].returnDate) return res.sendStatus(400); await connection.query('DELETE FROM rentals WHERE id = $1', [id]); res.sendStatus(200); }catch { res.sendStatus(500); } } export default deleteRent;
import auth from "../services/auth.js"; let view = undefined; function initialize(domElement) { view = domElement } async function getView() { return view; } let homePage = { initialize, getView } export default homePage;
// I've added several key-value paris to a list originally written by Colt Steele and edited by Jaime Pagan var keyData = { q: { sound: new Howl({ src: ['sounds/bubbles.mp3'] }), color: '#1abc9c', size: 500, num: 3, speed: .9, pulse: 8 }, w: { sound: new Howl({ src: ['sounds/clay.mp3'] }), color: '#2ecc71', size: 800, num: 1, speed: .85, pulse: 2 }, e: { sound: new Howl({ src: ['sounds/confetti.mp3'] }), color: '#3498db', size: 200, num: 1, speed: .9, pulse: 2, scatter: true }, r: { sound: new Howl({ src: ['sounds/corona.mp3'] }), color: '#9b59b6', size: 30, num: 50, speed: .96, pulse: 2 }, t: { sound: new Howl({ src: ['sounds/dotted-spiral.mp3'] }), color: '#34495e', size: 1000, num: 1, speed: .95, pulse: 5 }, y: { sound: new Howl({ src: ['sounds/flash-1.mp3'] }), color: '#16a085', size: 10, num: 200, speed: .8, pulse: 10 }, u: { sound: new Howl({ src: ['sounds/flash-2.mp3'] }), color: '#27ae60', size: 80, num: 100, speed: .31, pulse: 1 }, i: { sound: new Howl({ src: ['sounds/flash-3.mp3'] }), color: '#2980b9', size: 200, num: 1, speed: .75, pulse: 2 }, o: { sound: new Howl({ src: ['sounds/glimmer.mp3'] }), color: '#8e44ad', size: 100, num: 10, speed: .9, pulse: 5 }, p: { sound: new Howl({ src: ['sounds/moon.mp3'] }), color: '#2c3e50', size: 800, num: 3, speed: .95, pulse: 2 }, a: { sound: new Howl({ src: ['sounds/pinwheel.mp3'] }), color: '#f1c40f', size: 500, num: 1, speed: .9, pulse: 5 }, s: { sound: new Howl({ src: ['sounds/piston-1.mp3'] }), color: '#e67e22', size: 1000, num: 1, speed: .5, pulse: 1 }, d: { sound: new Howl({ src: ['sounds/piston-2.mp3'] }), color: '#e74c3c', size: 200, num: 1, speed: .8, pulse: 2 }, f: { sound: new Howl({ src: ['sounds/prism-1.mp3'] }), color: '#95a5a6', size: 200, num: 30, speed: .9, pulse: 2 }, g: { sound: new Howl({ src: ['sounds/prism-2.mp3'] }), color: '#f39c12', size: 200, num: 3, speed: .9, pulse: 10 }, h: { sound: new Howl({ src: ['sounds/prism-3.mp3'] }), color: '#d35400', size: 5, num: 100, speed: .98, pulse: 2 }, j: { sound: new Howl({ src: ['sounds/splits.mp3'] }), color: '#1abc9c', size: 300, num: 8, speed: .85, pulse: 3 }, k: { sound: new Howl({ src: ['sounds/squiggle.mp3'] }), color: '#2ecc71', size: 200, num: 1, speed: .9, pulse: 2 }, l: { sound: new Howl({ src: ['sounds/strike.mp3'] }), color: '#3498db', size: 100, num: 25, speed: .88, pulse: 3 }, z: { sound: new Howl({ src: ['sounds/suspension.mp3'] }), color: '#9b59b6', size: 100, num: 8, speed: .85, pulse: 8 }, x: { sound: new Howl({ src: ['sounds/timer.mp3'] }), color: '#34495e', size: 40, num: 80, speed: .9, pulse: 5 }, c: { sound: new Howl({ src: ['sounds/ufo.mp3'] }), color: '#16a085', size: 400, num: 1, speed: .9, pulse: 1 }, v: { sound: new Howl({ src: ['sounds/veil.mp3'] }), color: '#27ae60', size: 500, num: 1, speed: .85, pulse: 2 }, b: { sound: new Howl({ src: ['sounds/wipe.mp3'] }), color: '#2980b9', size: 100, num: 10, speed: .8, pulse: 4 }, n: { sound: new Howl({ src: ['sounds/zig-zag.mp3'] }), color: '#8e44ad', size: 200, num: 5, speed: .9, pulse: 2 }, m: { sound: new Howl({ src: ['sounds/moon.mp3'] }), color: '#2c3e50', size: 1000, num: 2, speed: .95, pulse: 2 } } // function scatter(circle, destination){ // // Each frame, move the path 1/30th of the difference in position // // between it and the destination. // // The vector is the difference between the position of // // the circle(s) and the destination point: // var vector = destination - circle.position; // console.log("scatter function: circle is" + circle); // // Add 1/30th of the vector to the position property // // of the text item, to move it in the direction of the // // destination point // circle.position += vector / 300; // }
function hola(){} asdfasd
/** * Miguel Ramirez * @param idBtn */ function adMasterButton(idBtn){ $("#"+idBtn).addClass("ad-button"); $("#"+idBtn).addClass("ad-widget"); $("#"+idBtn).addClass("ad-state-default"); $("#"+idBtn).addClass("ad-button-text-only"); $("#"+idBtn).addClass("ad-button-text"); $("#"+idBtn+" span:first").addClass("ad-button-text"); } /** * Miguel Ramírez * @param idButton * Esta funcion se utiliza para modiificar el fondo de los botones deshabilitados, * evitando que se confundan con los habilitados. */ function removeDisabled(idButton){ var id = "#"+idButton; var bandera = $("#"+idButton).attr("disabled"); //para volver a activar el botón ponemos la sig. linea en donde queremos habilitarlo. // $("#idBtn").addClass('ad-state-default'); y se pone cuando el código // tiene una linea como esta: document.getElementById("btn_fotosSecundaria").disabled = ""; //ó como: document.getElementById("btn_reemplazarDummie").disabled = false; if(bandera == 'disabled'){ // alert("desactivado: "+bandera+" button: "+idButton); $(id).removeClass('ad-state-default'); } }
"use strict"; let HTML = ""; let weatherDataArray = []; const containerReference = document.querySelector(".container"); const searchBoxReference = document.querySelector("#searchbox"); const weatherDataHTML = function (i, main, description) { let kelvinTempAtZeroCelzius = 273.15; let temperatureInCelzius = weatherDataArray[i].temp.day - kelvinTempAtZeroCelzius; const html = ` <div class="content"> <div class="weather-image"> <img src="Images/${ main ? main : description }.png" height="150" width="200" /> </div> <div class="temp"> <h1>${temperatureInCelzius.toFixed(0)} &#8451</h1> </div> <div class="weather-data"> <span class="clouds all">clouds: ${ weatherDataArray[i].clouds } % </span> <span class="wind all">wind speed: ${ weatherDataArray[i].wind_speed } km/h </span> <span class="humidity all">humidity: ${weatherDataArray[i].humidity} % </span> <span class="pressure all">pressure: ${ weatherDataArray[i].pressure } mb </span> </div> </div> `; /* adding all strings of variable html for different weather data together, after looping */ HTML += html; }; searchBoxReference.addEventListener("change", (town) => { fetch(`https://geocode.xyz/${searchBoxReference.value}?json=1`) .then((res) => res.json()) .then((data) => { const lattitude = data.latt; const longitude = data.longt; if (lattitude && longitude) { return fetch(` https://api.openweathermap.org/data/2.5/onecall?lat=${lattitude}&lon=${longitude}&exclude=hours&appid=2e0141ee8d7a8a999deb09d7df83cb10`); } else { alert(`Something wen't wrong in the first AJAX call`); } }) .then((res) => res.json()) .then((data) => { weatherDataArray = data.daily; HTML = ""; for (let i = 0; i < 7; i++) { let { main, description } = weatherDataArray[i].weather[0]; if (description === "light rain") { weatherDataHTML(i, description); } else if (main === "Clear") { weatherDataHTML(i, main); } else if (main === "Clouds") { weatherDataHTML(i, main); } else if (description === "rain") { weatherDataHTML(i, description); } else if (main === "Snow") { weatherDataHTML(i, main); } else { weatherDataHTML(i, main); } } containerReference.innerHTML = HTML; }) .catch((err) => alert(`${err.message}.Try again`)); });
// This function does not modify the lockfile. It asserts that packages do not use SSH // when specifying git repository function afterAllResolved(lockfile, context) { const pkgs = lockfile['packages']; for (const [pkg, entry] of Object.entries(pkgs)) { const repo = entry.resolution['repo']; if (repo !== undefined) { if (repo.startsWith('git@github.com')) { throw new Error(`Invalid git ssh specification found for package ${pkg}. Ensure sure that the dependencies do not reference SSH-based git repos before running installing them`); } } } return lockfile } module.exports = { hooks: { afterAllResolved } }
import PropTypes from "prop-types"; import styled from "styled-components"; const mapScaleToPixels = scale => { switch (scale) { case "s": return 4; case "m": return 8; case "l": return 16; case "xl": return 24; case "xxl": return 32; default: return 4; } }; const Inset = styled.div`padding: ${props => mapScaleToPixels(props.scale)}px;`; Inset.propTypes = { scale: PropTypes.oneOf(["s", "m", "l", "xl"]) }; Inset.defaultProps = { scale: "m" }; export default Inset;
import FileUpload from "./FileUpload"; export {FileUpload} export default FileUpload
//Correction function isPalindrome(str) { // The charecters that I'll remove from the string var specialChars = ' 0123456789,.;:-_'; // Initialize var strInverse = ''; var strNoSpecialChars = ''; // Loops each letter of the string for (var i = 0; i < str.length; i++) { // Checks if the actual char is one of my special chars that I want to skip if (specialChars.search(str[i]) === -1) { // If it's not, then we add the char to my new clean str strNoSpecialChars += str[i]; // And also in the inverse way strInverse = str[i] + strInverse; } } // Returns if the str with no special chars is written the same in both ways return strNoSpecialChars == strInverse; } // Test cases console.log(isPalindrome('test')) console.log(isPalindrome('never odd or even')) console.log(isPalindrome('e0ye')) console.log(isPalindrome('kayak')) console.log(isPalindrome('ka...:;ya112k')) console.log(isPalindrome('a.a a'))
var vm = new Vue({ el:'#app', mixins:[myMixin], data:{ navIndex:1,//当前所在导航项的index keyword:'', pid:'',//省 cid:'',//市id aid:'',//区县id addressList:[], pLists:[], cLists:[], aLists:[], hospitalLists:[], pageData:{currentPage:1,totalPage:10,total:90}, mHide:false, popTitle:'油站信息', hospitalName:'', tel:'', sort:'', pid2:'',//省 cid2:'',//市id aid2:'',//区县id typeid:'', cuztypeid:"",//卒中id pLists2:[], cLists2:[], aLists2:[], thisHosId:'',//当前修改或删除的医院id watchFlag:false,//是否监听pid2 cid2 aid2的标志 mHide2:true }, computed:{ //权限 thisAuthns:function(){ var authns=JSON.parse(getStorage("authns")); for(var i=0;i<authns.length;i++){ if(authns[i].authnName==='医院管理'){ return authns[i]; } } } }, methods:{ //分页组件绑定事件 changePage:function(page){ this.getHosList(page); }, //获取筛选条件下所有的省市区 getAddress:function(){ var _this = this; $.ajax( { type: "GET", url: urlPrefix + "/pc/record/getAddressData.do", success: function( data ){ console.log( data ); if( data.success ) { _this.addressList = data.data.addressList; _this.pLists = _this.addressList.filter( function( item ){ return item.parentId === 0; }); setTimeout('layui.form.render("select");',100); }else{ if(data.data===401){ layOut(); } } }, error: function( data ){ console.log( data ); } } ); }, //获取所有省(新增/修改) getProvinces:function(){ var _this = this; $.ajax( { type: "POST", url: urlPrefix + "/pc/org/province.do", success: function( data ){ console.log( data ); if( data.success ) { _this.pLists2 = data.data; setTimeout('layui.form.render("select");',100); }else{ if(data.data===401){ layOut(); } } }, error: function( data ){ console.log( data ); } } ); }, //获取对应市/区县/街道(新增/修改) getCitys:function(parm1,parm2){ var _this=this; $.ajax( { type: "POST", url: urlPrefix+"/pc/org/city.do", data:{proId:_this[parm1]}, success: function( data ) { console.log( data); if( data.success ) { _this[parm2] = data.data; setTimeout('defaultVal();layui.form.render("select");',100); }else { if(data.data===401){ layOut(); } } }, error: function( data ) { console.log( data ); } } ); }, //获取医院列表 getHosList:function(page){ var _this=this; $.ajax( { type: "GET", url: urlPrefix+"/pc/org/getOrgList.do", data: { orgName:this.keyword, pid:this.pid, cid:this.cid, aid:this.aid, currentPage:page, pageSize:10 }, success: function( data ) { console.log( data ); if( data.success ) { _this.hospitalLists = data.data; var totalPage = data.totalPage; var currentPage = data.currentPage; _this.pageData = data; }else { if(data.data===401){ layOut(); } } }, error: function( data ) { console.log( data ); } } ); }, //医院等级转换 getHosGrade:function(level){ switch(level) { case 1: return '三级甲等'; break; case 2: return '三级乙等'; break; case 3: return '二级甲等'; break; case 4: return '二级乙等'; break; case 5: return '其他'; break; } }, //获取医院信息(修改) getHosMsg:function(id){ var _this=this; $.ajax( { type: "POST", url: urlPrefix+"/pc/org/detail.do", data:{orgId:id}, success: function( data ) { console.log( data); if( data.success ) { var item=data.data; _this.hospitalName = item.orgName; _this.watchFlag=false;//此时的省市区的改变不被监听。 _this.pid2 = item.provinceId; _this.cid2 = item.cityId; _this.aid2 = item.areaId; _this.typeid = item.level; _this.cuztypeid = item.type; _this.getCitys('pid2','cLists2'); _this.getCitys('cid2','aLists2'); }else { if(data.data===401){ layOut(); } } }, error: function( data ) { console.log( data ); } } ); }, //出现医院弹窗 showHosPop:function(type,id){ var _this=this; _this.mHide=true; if(type === 1){//新增 _this.popTitle='新增医院'; //清空原有内容 _this.hospitalName = ''; _this.tel = ''; _this.sort = ''; _this.typeid=''; _this.cuztypeid = ""; _this.pid2=''; _this.cid2=''; _this.aid2=''; defaultVal(); }else if(type ===2 ){//修改 _this.popTitle='修改医院'; _this.thisHosId=id; _this.getHosMsg(id); } }, closeHosPop:function(){ this.mHide=false; }, //增加/修改医院 submitHos:function(){ var _this=this; console.log(/^\d+$/.test(_this.sort)); if(!/[\u4e00-\u9fa5]+/g.test(_this.hospitalName)){ layer.msg('请填写正确的医院名称'); return; } if(_this.pid2 ==='' || _this.cid2 ==='' ||_this.aid2 ==='' ){ layer.msg('请选择医院地址'); return; } if(_this.typeid ===''){ layer.msg('请选择医院类型'); return; } if(_this.cuztypeid ===''){ layer.msg('请选择卒中类型'); return; } var text='',data={}; if(_this.popTitle==='新增医院'){ text = '新增成功'; data={ orgName:_this.hospitalName, provinceId:_this.pid2, cityId:_this.cid2, areaId:_this.aid2, level:_this.typeid, type:_this.cuztypeid }; }else{ text = '修改成功'; data={ id:_this.thisHosId, orgName:_this.hospitalName, provinceId:_this.pid2, cityId:_this.cid2, areaId:_this.aid2, level:_this.typeid, type:_this.cuztypeid }; } $.ajax( { type: "POST", url: urlPrefix+"/pc/org/saveOrUpdate.do", data:data, success: function( data ) { console.log( data); if( data.success ) { _this.closeHosPop(); layer.msg(text); _this.getHosList(_this.pageData.currentPage); }else{ myAlert({type:2,msg:data.message}); if(data.data===401){ layOut(); } } }, error: function( data ) { console.log( data ); } } ); }, //点击删除 deleteBtn:function(id){ this.thisHosId = id; myAlert({msg:'确定要删除该医院吗?'},this.deleteHos); }, //删除医院 deleteHos:function(){ var _this=this; $.ajax( { type: "POST", url: urlPrefix+"/pc/org/delete.do", data:{orgId:_this.thisHosId,time:new Date().getTime()}, success: function( data ) { console.log( data); if( data.success ) { layer.msg('删除成功'); _this.getHosList(); }else { layer.msg(data.message); if(data.data===401){ layOut(); } } }, error: function( data ) { console.log( data ); } } ); } }, watch:{ hospitalName:function( newVal ){ this.hospitalName=newVal.replace(/[&\|\\*^%$#@\-\s¥—+_、,。,.:;:;~…!!??\"\'“”‘’/{}\[\]【】=<>《》\·`]/g,""); }, sort:function( newVal ){ this.sort=newVal.replace(/[\u4e00-\u9fa5\&\|\\*^%$#@\-\s¥—+_、,。,.:;:;~…!!??\"\'“”‘’/{}\[\]【】=<>《》\·`]/g, ""); }, pid:function(newVal,oldVal){ if(newVal){ this.cLists = this.addressList.filter( function( item ){ return item.parentId == newVal; } ); }else{ this.cLists=[]; } this.aLists=[]; this.cid=''; this.aid=''; defaultVal(); setTimeout( 'layui.form.render("select");', 100 ); }, cid:function(newVal,oldVal){ if(newVal){ this.aLists = this.addressList.filter( function( item ){ return item.parentId == newVal; } ) }else{ this.aLists=[]; } this.aid=''; defaultVal(); setTimeout( 'layui.form.render("select");', 100 ); }, pid2:function(newVal,oldVal){ if(this.watchFlag){ this.cLists2=[]; this.cid2=''; this.aLists2=[]; this.aid2 ='' ; setTimeout('layui.form.render("select");',100); if(newVal!==''){ this.getCitys('pid2','cLists2'); } } }, cid2:function(newVal,oldVal){ if(this.watchFlag){ this.aLists2=[]; this.aid2=''; setTimeout('layui.form.render("select");',100); if(newVal!==''){ this.getCitys('cid2','aLists2'); } } } }, mounted:function(){ //this.getHosList(1); //this.getAddress(); //this.getProvinces(); }, components:{'m-page':mPage} }); (function( ){ var form=layui.form; var element = layui.element; form.render(); element.render(); //监听省的选择 form.on('select(province)', function(data){ //console.log(data.elem); //得到select原始DOM对象 //console.log(data.othis); //得到美化后的DOM对象 vm.pid = data.value; //得到被选中的值 }); //市 form.on('select(city)', function(data){ vm.cid = data.value; //得到被选中的值 }); //区县 form.on('select(area)', function(data){ vm.aid = data.value; //得到被选中的值 }); //新增或修改医院-省 form.on('select(province2)', function(data){ vm.watchFlag=true;//原信息已加载,可以监听地区选择 vm.pid2 = data.value; //得到被选中的值 }); //市 form.on('select(city2)', function(data){ vm.watchFlag=true;//原信息已加载,可以监听地区选择 vm.cid2 = data.value; //得到被选中的值 }); //区县 form.on('select(area2)', function(data){ vm.watchFlag=true;//原信息已加载,可以监听地区选择 vm.aid2 = data.value; //得到被选中的值 }); //油站类型 form.on('select(oilStationType)', function(data){ vm.typeid = data.value; //得到被选中的值 }); //油站名称 form.on('select(oilStationName)', function(data){ //vm.cuztypeid = data.value; //得到被选中的值 console.log(data.value); }); form.on('select(handle)', function(data){ console.log(data.elem.dataset.id);//select元素data-id属性 console.log(data.value); layui.form.val('table-form',{ "handle": '' }); layui.form.render(); }); })(); //给select赋值 function defaultVal() { layui.form.val('hospitalForm',{ "citySelect": vm.cid, "districtSelect": vm.aid }); layui.form.val('oilStationPop',{ "provinceSelect2":vm.pid2, "citySelect2": vm.cid2, "districtSelect2": vm.aid2, "hosType":vm.typeid, "CUZType":vm.cuztypeid }); }
import { html, LitElement } from "@polymer/lit-element"; import { FormMixin } from "../../function/form-function"; import { connect } from "pwa-helpers/connect-mixin.js"; // This element is connected to the Redux store. import { store } from "../../store/store"; // These are the actions needed by this element. import { formSaveRegister } from "../../actions/form-input-action"; // We are lazy loading its reducer. import formInput from "../../reducers/form-input-reducer"; store.addReducers({ formInput }); import ownStyle from "../../style/own-style"; import { mahaniyomFont, CSChatThaiFont, notosansthaiFont, rsuFont } from "../../style/fonts-style"; import to from "../../function/to"; // import "../../components/my-input"; import bulmaStyles from "../../style/bulma-styles"; // class pageForm extends connect(store)(Mixin(PageViewElement).with(FormMixin)) { class pageForm extends connect(store)(FormMixin(LitElement)) { // class pageForm extends connect(store)(LitElement) { static get properties() { return { data: Object, data2: Object, number: Object, btn: Boolean }; } _stateChanged(state) { console.log("state", state); // this.count = state.data.count; } constructor() { super(); this.data = { firstName: "ชื่อ", lastName: "นามสกุล" }; this.data2 = { firstName: "ชื่อ" }; this.number = { num: 0 }; this.btn = true; // this.value = "x" } render() { return html` ${bulmaStyles(this)} ${ownStyle} ${rsuFont} ${mahaniyomFont} ${CSChatThaiFont} ${notosansthaiFont} ลอง <!-- <style> .testRsu{ font-size: 1em; font-family: 'rsuregular', sans-serif; -webkit-font-smoothing: antialiased; } .testmahaniyom{ font-size: 1em; font-family: 'mahaniyom', sans-serif; -webkit-font-smoothing: antialiased; } .testCSChatThai{ font-size: 1em; font-family: 'CSChatThai', sans-serif; -webkit-font-smoothing: antialiased; } .testnotoSansThaiRegular{ font-size: 1em; font-family: 'notoSansThaiRegular', sans-serif; -webkit-font-smoothing: antialiased; } </style> <div class=""> ทดสอบ no style font 232 </div> <div class="testRsu"> ทดสอบ font </div> <div class="testmahaniyom"> ทดสอบ font </div> <div class="testCSChatThai"> ทดสอบ font </div> <div class="testnotoSansThaiRegular"> ทดสอบ font own-style-flex own-flex-middle </div> --> <!-- <my-input testxxx="test" disabled$=${btn} classnylon="input is-primary" type="text" placeholder="Text input"></my-input> --> <button on-click="${e => this.changePopInsert(e)}"> ลองเปลี่ยนค่า</button> <br> <button on-click="${e => this._test(e)}"> เรียกค่า</button> จำนวนการคลิก ${this.number.num} <- <div class=""> pageForm sdfsf ได้ ${data2.firstName} -- <input id="lastName" name="firstName" value="${data2.firstName}" on-input="${e => this._formOnInputObject(e)}" on-focus="${e => this._formSetSeleteValue(e)}"> "" > ${data.firstName} <---- <input id="firstName" name="firstName" number value="${data.firstName}" on-input="${e => this._formOnInputObject(e)}" on-focus="${e => this._formSetSeleteValue(e)}"> ${data.lastName} <input id="lastName" name="lastName" value="${data.lastName}" on-input="${e => this._formOnInputObject(e)}" on-focus="${e => this._formSetSeleteValue(e)}"> <button on-click="${e => this.test(e)}">ดึงค่า</button> </div> <button on-click="${e => this.saveRedux(e)}"> บันทึก</button> `; } _didRender(props, changedProps, prevProps) { // console.log(props, changedProps, prevProps); // console.log("-----------------------------------"); } changePopInsert() { let el = this.shadowRoot.querySelector("my-input"); this.btn = !this.btn; console.log("this.btn ", this.btn); // el.setAttribute('disabled', false) // el.setAttribute('placeholder', 'ลองสิ') console.log(el); el.reflection(); } saveRedux() { console.log("this.data asds >", this.data); console.log("เข้า"); store.dispatch(formSaveRegister(this.data)); } test(e) { // console.log(e); // console.log(this.data); // let nextParams = { x: 2 } // this._redirect('/page-exporter', nextParams) } } customElements.define("page-form", pageForm);
import React, { Component } from 'react'; export class ListPane extends Component { render() { return ( <div className='list-group list-pane' > { this.props.recipeNames.map((item) => { return <li className="list-group-item" id={item.recipe.replace(/ /g, '-')} onClick={this.props.listPaneHandler}>{item.recipe}</li> })} </div> ); } }
import React, { Component } from "react" import { connect } from 'react-redux'; import * as actions from '../../../store/actions/general'; import Image from "../../Image/Index" import imageCompression from 'browser-image-compression'; import swal from 'sweetalert' import axios from "../../../axios-orders" import Translate from "../../../components/Translate/Index"; class Images extends Component { constructor(props) { super(props) this.state = { images:props.images, movie:props.movie } this.deleteImage = this.deleteImage.bind(this); this.uploadImage = this.uploadImage.bind(this) } static getDerivedStateFromProps(nextProps, prevState) { if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){ return null; } if(prevState.localUpdate){ return {...prevState,localUpdate:false} }else { return { images:nextProps.images ? nextProps.images : [], } } } updateValues = (values) => { //update the values this.props.updateSteps({key:"images",value:values}) } updateState = (data,message) => { if(message && data){ this.props.openToast(Translate(this.props,message), "success"); } const items = [...this.state.images] items.unshift(data) this.setState({submitting:false},() => { this.updateValues(items) }) } uploadImage = async (picture) => { var url = picture.target.value; let imageFile = "" var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase(); if (picture.target.files && picture.target.files[0] && (ext === "png" || ext === "jpeg" || ext === "jpg" || ext === 'PNG' || ext === 'JPEG' || ext === 'JPG' || ext === 'gif' || ext === 'GIF')) { imageFile = picture.target.files[0]; } else { return; } if(this.state.submitting){ return } this.setState({submitting:true}); const options = { maxSizeMB: 1, maxWidthOrHeight: 1200, useWebWorker: true } let compressedFile = picture.target.files[0]; if(ext != 'gif' && ext != 'GIF'){ try { compressedFile = await imageCompression(imageFile, options); } catch (error) { } } const formData = new FormData() formData.append('image', compressedFile,url) let uploadurl = '/movies/upload-image/'+this.state.movie.movie_id axios.post(uploadurl, formData) .then(response => { if (response.data.error) { swal("Error", response.data.error[0].message, "error"); } else { this.setState({submitting:false},() => { this.updateState({...response.data.item},response.data.message) }) } }).catch(err => { swal("Error", Translate(this.props, "Something went wrong, please try again later"), "error"); }); } deleteImage = (id,e) => { e.preventDefault(); swal({ title: Translate(this.props,"Delete Image"), text: Translate(this.props,"Are you sure you want to delete this image?"), icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { const formData = new FormData() formData.append('id', id) formData.append('movie_id', this.state.movie.movie_id); const url = "/movies/delete-image" axios.post(url, formData) .then(response => { if (response.data.error) { swal("Error", Translate(this.props,"Something went wrong, please try again later", "error")); } else { let message = response.data.message this.props.openToast(Translate(this.props,message), "success"); const items = [...this.state.images] const itemIndex = items.findIndex(p => p["photo_id"] == id) if(itemIndex > -1){ items.splice(itemIndex, 1) this.updateValues(items) } } }).catch(err => { swal("Error", Translate(this.props,"Something went wrong, please try again later"), "error"); }); //delete } else { } }); } render(){ const imageref = React.createRef(); return ( <div className="movie_photos"> <button className="add_photo" onClick={e => { imageref.current.click(); }}> { this.props.t(this.state.submitting ? "Uploading Image..." : "Upload Image") } </button> <input className="fileNone" onChange={this.uploadImage.bind(this)} ref={imageref} type="file" /> <ul className="movie_photos_cnt"> { this.state.images.map((item,index) => { return ( <li className="image" key={item.photo_id}> <Image className="img" image={item.image} title={""} imageSuffix={this.props.pageInfoData.imageSuffix} /> <a href="#" className="btn btn-danger btn-sm" onClick={this.deleteImage.bind(this,item.photo_id)}>{this.props.t("Delete")}</a> </li> ) }) } </ul> </div> ) } } const mapStateToProps = state => { return { pageInfoData: state.general.pageInfoData }; }; const mapDispatchToProps = dispatch => { return { openToast: (message, typeMessage) => dispatch(actions.openToast(message, typeMessage)) }; } export default connect(mapStateToProps, mapDispatchToProps)(Images);
/** * Created by John on 2015-10-17. */ var a=1; var b=2;
import Vue from 'vue' import { mapState, mapGetters } from 'vuex' import IntlMessageFormat from 'intl-messageformat' import { get } from 'lodash' export const localizeMixin = { computed: { ...mapState(['localizedStrings', 'locale']), ...mapGetters(['getCountryShortName', 'getIsCountryAustralia']) }, methods: { localize (value, options) { if (!value && value !== 0) return if (options && options === 'currency') { typeof value === 'string' && (value = +value) const currencyValue = countDecimals(value) ? value.toFixed(2) : value let preResult = [this.currencySymbol, currencyValue] if (this.currencyPosition === 'after') { preResult.reverse() } if (!this.skipCurrencySpace) { preResult.splice(1, 0, ' ') // adding space between currency symbol and price } return preResult.join('') } if (!get(this.localizedStrings, value, '') && process.env.NODE_ENV === 'production') { const errorMessage = `Missing translation in ${this.locale} locale, key: ${value}` this.$sentry.captureException(new Error(errorMessage)) } if (options) { return new IntlMessageFormat( get(this.localizedStrings, value, value), this.locale ).format(options) } return new IntlMessageFormat( get(this.localizedStrings, value, value), this.locale ).format() }, localizeDate (date, type) { const isTime = type === 'time' const options = isTime ? { hour: '2-digit', minute: '2-digit' } : { year: 'numeric', month: 'long', day: 'numeric' } const methodName = isTime ? 'toLocaleTimeString' : 'toLocaleDateString' return date[methodName](this.locale, options) } } } function countDecimals (value) { const decimals = value.toString().split('.')[1] return decimals ? decimals.length : 0 } Vue.mixin(localizeMixin)