text
stringlengths
7
3.69M
export default { blogTitle : "Hablando Con Máquinas", blogDescription : "Blog personal sobre informática y programación", authorName : "Jonay Godoy", social_networks: { twitter: "https://twitter.com/godoyjonay", github: "https://github.com/jonayGodoy" }, linkPrefix : "/hablando_con_maquinas_dev", email : "jonay.godoy.reyes@gmail.com", disqus_shortname : "hablandoconmaquinas" };
var column_num; var row_num; var environmentNameValue; $(document).ready(function(){ $("#myTable td").click(function() { if (typeof environmentNameValue == "undefined" || environmentNameValue == null || environmentNameValue==""){ $( "#addEnvErrorMsg" ).html("Please configure environment first!").css('color','red'); return false; } column_num = parseInt( $(this).index() ) + 1; row_num = parseInt( $(this).parent().index() ); //alert("row_num -"+row_num+" column_num-"+column_num) if(!(column_num == "1" || column_num == "3")){ if(column_num == "2"){ $.ajax({url: "getCmts/"+environmentNameValue+"/"+userNetworkId+"/"+column_num+"/"+row_num, async: false, success: function(result){ $( "#addCmtsErrorMsg" ).html(""); $('#cmtsModal').on('show.bs.modal', function (e) { $("#userName").val(result.userName); $("#password").val(result.password); $("#ipAddress").val(result.ipAddress); }) } }); }else{ $.ajax({url: "getCpe/"+environmentNameValue+"/"+userNetworkId+"/"+column_num+"/"+row_num, async: false, success: function(result){ $( "#addCpeErrorMsg" ).html(""); $('#deleteConfirmation').on('show.bs.modal', function (e) { $("#cpeVendor").val(result.cpeVendor); $("#cpeModel").val(result.cpeModel); $("#cmMac").val(result.cmMac); $("#mtaMac").val(result.mtaMac); $("#telephoneOne").val(result.telephoneOne); $("#telephoneTwo").val(result.telephoneTwo); }) } }); } } }); }); function validateAddEnv(){ var environmentName = $('#environmentName').val().trim(); var networkId = $('#networkId').val().trim(); var location = $('#location').val().trim(); var json = {"environmentName" : environmentName,"ownerNetworkId" : userNetworkId,"adminNetworkId" : networkId,"location" : location}; if ((typeof environmentName == "undefined" || environmentName == null || environmentName=="") || (typeof networkId == "undefined" || networkId == null || networkId=="") || (typeof location == "undefined" || location == null || location=="")) { $( "#addEnvErrorMsg" ).html("All the fields are mandatory").css('color','red'); }else{ $.ajax({ url: "user/addEnvironment", type: 'POST', data: JSON.stringify(json), cache:false, beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json"); }, success:function(response){ if(response){ $( "#addEnvErrorMsg" ).html("You have successfully added an Environment!").css('color','blue'); environmentNameValue = environmentName; }else{ $( "#addEnvErrorMsg" ).html("Please enter valid admin network id").css('color','red'); } } }); } return true; } function verifyCpeDetails(){ //$( "#b11").addClass('btn btn-success'); //$( "#b11").addClass('btn btn-danger'); } function deleteEnv(){ alert("Add logic to remove the env."); return true; } function resetAddEnv(){ var frm = document.getElementsByName('add-form')[0]; frm.reset(); return true; } function saveAddCpe(){ var cpeVendor = $('#cpeVendor').val().trim(); var cpeModel = $('#cpeModel').val().trim(); var cmMac = $('#cmMac').val().trim(); var mtaMac = $('#mtaMac').val().trim(); var telephoneOne = $('#telephoneOne').val().trim(); var telephoneTwo = $('#telephoneTwo').val().trim(); var json = {"cpeVendor" : cpeVendor,"cpeModel" : cpeModel,"cmMac" : cmMac,"mtaMac" : mtaMac,"telephoneOne" : telephoneOne,"telephoneTwo" : telephoneTwo,"columnNo" : column_num,"rowNo" : row_num,"environmentName" : environmentNameValue,"ownerNtId":userNetworkId}; if ((typeof cpeVendor == "undefined" || cpeVendor == null || cpeVendor=="") || (typeof cpeModel == "undefined" || cpeModel == null || cpeModel=="") || (typeof cmMac == "undefined" || cmMac == null || cmMac=="") || (typeof mtaMac == "undefined" || mtaMac == null || mtaMac=="") || (typeof telephoneOne == "undefined" || telephoneOne == null || telephoneOne=="")|| (typeof telephoneTwo == "undefined" || telephoneTwo == null || telephoneTwo=="")) { $( "#addCpeErrorMsg" ).html("All the fields are mandatory").css('color','red'); }else{ $.ajax({ url: "user/addCpe", type: 'POST', data: JSON.stringify(json), cache:false, beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json"); }, success:function(response){ if(response){ $( "#addCpeErrorMsg" ).html("You have successfully added an CPE!").css('color','blue'); var imgData = "<img src=\"images/"+cpeModel+".jpg\">" $( "#"+row_num+column_num ).html(imgData); }else{ $( "#addCpeErrorMsg" ).html("Please configure CMTS before CPE").css('color','red'); } } }); } return true; } function resetAddCpe(){ var frm = document.getElementsByName('addCpe-form')[0]; frm.reset(); return true; } function saveAddCmts(){ var userName = $('#userName').val().trim(); var password = $('#password').val().trim(); var ipAddress = $('#ipAddress').val().trim(); var json = {"userName" : userName,"password" : password,"ipAddress" : ipAddress,"columnNo" : column_num,"rowNo" : row_num,"environmentName" : environmentNameValue,"ownerNtId":userNetworkId}; if ((typeof userName == "undefined" || userName == null || userName=="") || (typeof password == "undefined" || password == null || password=="") || (typeof ipAddress == "undefined" || ipAddress == null || ipAddress=="")) { $( "#addCmtsErrorMsg" ).html("All the fields are mandatory").css('color','red'); }else{ $.ajax({ url: "user/addCmts", type: 'POST', data: JSON.stringify(json), cache:false, beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json"); }, success:function(response){ if(response){ $( "#addCmtsErrorMsg" ).html("You have successfully added an CMTS!").css('color','blue'); //var imgData = "<img src=\"images/"+cpeModel+".jpg\">" //$( "#"+row_num+column_num ).html(imgData); } } }); } return true; } function resetAddCmts(){ var frm = document.getElementsByName('addCmts-form')[0]; frm.reset(); return true; }
var searchData= [ ['state_5ftype_0',['state_type',['../classAIFriendOfStatefulTask.html#a5ec41fa75a5eda7923dc635a97e7b707',1,'AIFriendOfStatefulTask::state_type()'],['../classAIStatefulTask.html#a5bdb546808c3ff5820246f45b8a54973',1,'AIStatefulTask::state_type()']]] ];
function getBuildBody(project,organization,azurePipelineId){ return({ "triggers": [ { "branchFilters": [ "+refs/heads/master" ], "pathFilters": [], "batchChanges": false, "maxConcurrentBuildsPerBranch": 1, "pollingInterval": 0, "triggerType": "continuousIntegration" } ], "process": { "phases": [ { "steps": [ { "environment": {}, "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "Use Node version ", "timeoutInMinutes": 0, "condition": "succeeded()", "task": { "id": "31c75bbb-bcdf-4706-8d7c-4da6a1959bc2", "versionSpec": "0.*", "definitionType": "task" }, "inputs": { "versionSpec": "10", "checkLatest": "true" } }, { "environment": {}, "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "PowerShell Script", "timeoutInMinutes": 0, "condition": "succeeded()", "task": { "id": "e213ff0f-5d5c-4791-802d-52ea3e7be1f1", "versionSpec": "2.*", "definitionType": "task" }, "inputs": { "targetType": "inline", "filePath": "", "arguments": "", "script": "# Fetching src folder path\n$filePath = Get-ChildItem $(Build.Repository.LocalPath) -Filter package.json -Recurse | % { $_.FullName } | Out-String\n\n# Splitting src's Parent path\n$dirPath = Split-Path $filePath\n\n# Move to code's Base Path\ncd $dirPath\n\n# Install angular CLI\nnpm install -g @angular/cli@8.3.26\n\n# Install all node packages\nnpm install\n\n# Build code\nng build\n\n#Create a new folder named Code\nNew-Item -Path '..\\AZcodeBase' -ItemType Directory\n\n#Copy all data to Code directory\nCopy-Item -Path $dirPath\\* -Destination ..\\AZcodeBase -Force\n\nWrite-Host \"##vso[task.setvariable variable=DirPath;]$dirPath\"\n", "errorActionPreference": "stop", "failOnStderr": "false", "ignoreLASTEXITCODE": "false", "pwsh": "false", "workingDirectory": "" } }, { "environment": {}, "enabled": false, "continueOnError": false, "alwaysRun": false, "displayName": "PowerShell Script", "timeoutInMinutes": 0, "condition": "succeeded()", "task": { "id": "e213ff0f-5d5c-4791-802d-52ea3e7be1f1", "versionSpec": "2.*", "definitionType": "task" }, "inputs": { "targetType": "inline", "filePath": "", "arguments": "", "script": "ls $(System.DefaultWorkingDirectory)\\AZcodeBase\\dist", "errorActionPreference": "stop", "failOnStderr": "false", "ignoreLASTEXITCODE": "false", "pwsh": "false", "workingDirectory": "" } }, { "environment": {}, "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "Copy Files web.config", "timeoutInMinutes": 0, "condition": "succeeded()", "task": { "id": "5bfb729a-a7c8-4a78-a7c3-8d717bb7c13c", "versionSpec": "2.*", "definitionType": "task" }, "inputs": { "SourceFolder": "$(System.DefaultWorkingDirectory)", "Contents": "web.config", "TargetFolder": "$(System.DefaultWorkingDirectory)/out", "CleanTargetFolder": "false", "OverWrite": "false", "flattenFolders": "false", "preserveTimestamp": "false" } }, { "environment": {}, "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "Archive files", "timeoutInMinutes": 0, "condition": "succeeded()", "task": { "id": "d8b84976-e99a-4b86-b885-4849694435b0", "versionSpec": "2.*", "definitionType": "task" }, "inputs": { "rootFolderOrFile": "$(DirPAth)\\dist", "includeRootFolder": "false", "archiveType": "zip", "sevenZipCompression": "5", "tarCompression": "gz", "archiveFile": "$(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip", "replaceExistingArchive": "true", "verbose": "false", "quiet": "false" } }, { "environment": {}, "enabled": true, "continueOnError": false, "alwaysRun": false, "displayName": "Publish Artifact: drop", "timeoutInMinutes": 0, "condition": "succeeded()", "task": { "id": "2ff763a7-ce83-4e1f-bc89-0ae63477cebe", "versionSpec": "1.*", "definitionType": "task" }, "inputs": { "PathtoPublish": "$(Build.ArtifactStagingDirectory)", "ArtifactName": "drop", "ArtifactType": "Container", "TargetPath": "", "Parallel": "false", "ParallelCount": "8", "FileCopyOptions": "" } } ], "name": "Agent job 1", "refName": "Job_1", "condition": "succeeded()", "target": { "executionOptions": { "type": 0 }, "allowScriptsAuthAccessOption": false, "type": 1 }, "jobAuthorizationScope": "projectCollection" } ], "target": { "agentSpecification": { "identifier": "vs2017-win2016" } }, "type": 1 }, "repository": { "properties": { "cleanOptions": "0", "labelSources": "0", "labelSourcesFormat": "$(build.buildNumber)", "reportBuildStatus": "true", "gitLfsSupport": "false", "skipSyncSource": "false", "checkoutNestedSubmodules": "false", "fetchDepth": "0" }, "type": "TfsGit", "name": project, "url": `https://dev.azure.com/${organization}/${project}/_git/${project}`, "defaultBranch": "refs/heads/master", "clean": "false", "checkoutSubmodules": false }, "processParameters": {}, "quality": "definition", "queue": { "_links": { "self": { "href": `https://dev.azure.com/${organization}/_apis/build/Queues/${azurePipelineId}` } }, "id": azurePipelineId, "name": "Azure Pipelines", "url": "", "pool": { "id": 9, "name": "Azure Pipelines", "isHosted": true } }, "name": project+"-CI", "type": "build", "queueStatus": "enabled" }) } module.exports = {getBuildBody}
import React, { memo } from "react"; // grid import { AgGridReact } from "ag-grid-react"; const RowDragging = () => { return ( <div className="ag-theme-balham" style={{ height: "500px", width: "750px" }} > <AgGridReact /> </div> ); }; export default memo(RowDragging);
$(".cate-title").click(function () { $(".cate-list").stop().slideToggle(); }); $(".lt-menu").click(function () { $(".lt-aside").toggleClass("lt-out"); $(".main-head,body").toggleClass("pl-180"); }); $(".login-out").click(function () { $.ajax({ type: "GET", url: "/employee/employeeLogout", dataType: "json", success: function (data) { if (data.success) { location.href = "./login.html"; } }, }); });
const Generator = require('yeoman-generator'); const yosay = require('yosay'); const chalk = require('chalk'); module.exports = class extends Generator { constructor(args, opts) { super(args, opts); this.hasBeenRecordedInFidjOvh = true; this.templateName = 'app2021'; //'app2021'; //'app2018' ''ionic2020' this.option('skip-welcome-message', { desc: 'Skips the welcome message', type: Boolean }); this.argument('appname', {type: String, required: false, desc: 'Your app name'}); this.argument('appType', {type: String, required: false, desc: 'For ex: "app2021" '}); this.argument('appId', {type: String, required: false}); this.argument('appOptions', {type: String, required: false}); this.argument('appUserName', {type: String, required: false}); this.argument('appDescription', {type: String, required: false}); this.argument('appWelcome', {type: String, required: false}); this.argument('appContent', {type: String, required: false}); } async initializing() { this.pkg = require('../../package.json'); } async prompting() { if (!this.options['skip-welcome-message'] && !this.options.appId) { this.log(yosay('\'Allo \'Welcome to ' + chalk.red('fidj.ovh') + ' generator')); const promptConditions = [{ type: 'confirm', name: 'hasBeenRecordedInFidjOvh', message: 'Did you recorded your app in fidj.ovh and received your appId ?', default: false }]; const conditions = await this.prompt(promptConditions); this.hasBeenRecordedInFidjOvh = !!conditions.hasBeenRecordedInFidjOvh; if (!this.hasBeenRecordedInFidjOvh) { const err = 'You need to submit your app on https://fidj.ovh first. ' + 'It will help you to build a valid app name and give you a appId.'; this.log(yosay('Sorry : ' + chalk.red(err) + ' See you in 2 minutes ?')); } } if (!this.options.appname || !this.options.appUserName || !this.options.appDescription) { const prompts = [ { type: 'input', name: 'appUserName', message: 'Your (github) user name' }, { type: 'input', name: 'appName', message: 'Your app name (as shown on device)', default: this.appname.replace(/[^\w\s]/gi, '').replace(/\s/g, '_').replace(/\s+/g, '').replace(/[\. ,:-]+/g, '').toLowerCase() }, { type: 'input', name: 'appDescription', message: 'App description', default: this.appname } ]; this.props = await this.prompt(prompts); } else { this.props = { appName: this.options.appname, appUserName: this.options.appUserName, appDescription: this.options.appDescription, appWelcome: this.options.appWelcome || '<h1>Welcome</h1>', appContent: this.options.appContent || '<h1>Hello</h1>' }; } const pack = this.props.appUserName.replace(/[^\w\s]/gi, '').replace(/\s+/g, '').replace(/[\. ,:-]+/g, '').toLowerCase(); const age = this.props.appName.replace(/[^\w\s]/gi, '').replace(/\s/g, '_').replace(/\s+/g, '').replace(/[\. ,:-]+/g, '').toLowerCase(); const packageDefault = 'ovh.' + (pack ? pack : 'fidj') + '.' + age; if (!this.options.appId) { const prompts02 = [{ type: 'input', name: 'appId', message: 'Your app Id' }, { type: 'input', name: 'appPackage', message: 'Your app package name', default: packageDefault }, { type: 'input', name: 'appHomepage', message: 'Home page url', default: 'https://fidj.ovh/_/' + age } ]; this.props02 = await this.prompt(prompts02); } else { this.props02 = { appId: this.options.appId, appPackage: packageDefault, appHomepage: 'https://fidj.ovh/_/' + age }; } } async writing() { if (!this.hasBeenRecordedInFidjOvh) { return; } let copyAll = true; if (this.options.appType === 'app2018') { this.templateName = 'app2018'; } else { this.templateName = 'app2021'; } const now = new Date(); const version = '' + ('' + now.getFullYear()).substr(2) + '.' + (now.getMonth() + 1) + '.' + now.getDate(); const appArguments = { appName: this.props.appName, appNameStrict: this.props.appName.replace(/[^\w\s]/gi, '').replace(/\s+/g, '').replace(/[\. ,:-]+/g, '').toLowerCase(), appDescription: this.props.appDescription, appWelcome: this.props.appWelcome, appContent: this.props.appContent, appUserName: this.props.appUserName, appHomepage: this.props02.appHomepage, appPackage: this.props02.appPackage, appId: this.props02.appId, appOptions: this.options.appOptions ? ', {' + this.options.appOptions + '}' : '', appVersion: version, appKeywords: 'fidj', appYear: now.getFullYear(), appColor: 'white' }; this.fs.copyTpl( this.templatePath(this.templateName + '/*'), this.destinationPath(), appArguments ); this.fs.copyTpl( this.templatePath(this.templateName + '/.*'), this.destinationPath(), appArguments ); this.fs.copyTpl( this.templatePath(this.templateName + '/src'), this.destinationPath('src'), appArguments ); if (copyAll) { this.fs.copy( this.templatePath(this.templateName + '/platforms'), this.destinationPath('platforms') ); this.fs.copy( this.templatePath(this.templateName + '/resources'), this.destinationPath('resources') ); this.fs.copy( this.templatePath(this.templateName + '/tests'), this.destinationPath('tests') ); //this.fs.copy( // this.templatePath(this.templateName + '/www'), // this.destinationPath('www') //); } } async install() { if (!this.hasBeenRecordedInFidjOvh) { return; } this.npmInstall(); } async end() { } };
import React, { Component } from 'react'; import './App.css'; import Button from './components/Button'; import DogFigure from './containers/DogFigure'; import ADJECTIVES from './data'; class App extends Component { state = { dogURL: null, mediaType: null, caption: 'Finding doggos.', }; createCaption() { return `A ${ ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)] } Doggo!`; } getDog() { console.log('Get dog'); //Fetch dog data fetch('https://random.dog/woof.json') .then(res => res.json()) .then(data => { console.log(data); const dogURL = data.url; let mediaType; // Check file type if (dogURL.endsWith('mp4')) { //Create video element mediaType = 'video'; } else { mediaType = 'img'; } const caption = this.createCaption(); this.setState({ caption, dogURL, mediaType, }); }) .catch(err => this.setState({ caption: 'Doggos Unavailable!', }) ); } onClick = () => { this.getDog(); }; render() { return ( <div className="App"> <DogFigure dogURL={this.state.dogURL} mediaType={this.state.mediaType} caption={this.state.caption} /> <Button onClick={this.onClick} /> </div> ); } } export default App;
import styled from "styled-components"; export const StyledLanding = styled.div` height: 100vh; background: url(require("../resources/mohammad-metri-421904-unsplash.jpg")); background-size: cover; background-repeat: no-repeat; `;
const replace = (content, regexp, callback) => { let result = content; let match, matchValues = []; while(match = regexp.exec(content)) { const { index } = match; [ old ] = match; length = old.length; const replacement = callback(null, match); matchValues.unshift({ index, length, replacement }) } matchValues.forEach(({ index, length, replacement }) => { result = result.slice(0, index) + replacement + result.slice(index + length) }) return result } // same as replace, but takes an async callback function const replaceAsync = async (content, regexp, callbackAsync) => { let result = content; let match, matchValues = []; while(match = regexp.exec(content)) { const { index } = match; [ old ] = match; length = old.length; const replacement = await callbackAsync(null, match) .then(content => content) .catch(e => console.log('Replacement Error:', e)); matchValues.unshift({ index, length, replacement }) } matchValues.forEach(({ index, length, replacement }) => { result = result.slice(0, index) + replacement + result.slice(index + length) }) return result } module.exports = { replace, replaceAsync, }
(function(){ var cssClasses = ["cke-index-primary", "cke-index-secondary", "cke-index-tertiary", "cke-index-reference"]; var defaultText = ["primary", "secondary", "tertiay", "see ..."]; IndexTermManager = function(){ this.indexterms = {}; this.termCount = 0; this.globalVisibility = true; }; IndexTermManager.prototype.removeTerm = function(key){ delete this.indexterms[key]; //TODO: remove span in dom }; IndexTermManager.prototype.addTerm = function(term){ var key = this.createSlug(); this.indexterms[key] = term; return key; }; IndexTermManager.prototype.createSlug = function(){ var base = "cke-indexterm-"; var count = this.termCount; slug = base + this.termCount; while(slug in this.indexterms){ count++; slug = base + count; }; return slug; }; IndexTermManager.prototype.toggleGlobalVisibility = function(){ this.globalVisibility = this.globalVisibility?false:true; for(term in this.indexterms){ this.indexterms[term].setVisibility(this.globalVisibility); } }; CKEDITOR["IndexTermManager"] = new IndexTermManager(this.globalVisibility); IndexTerm = function(editor){ this.editor = editor; this.visible = true; this.id = null; this.indexSpan = null; this.termSpans = []; this.registerTerm(); this.renderSpan(); }; IndexTerm.prototype.registerTerm = function(){ this.id = CKEDITOR["IndexTermManager"].addTerm(this); } IndexTerm.prototype.renderSpan = function() { var selectedText = this.editor.getSelection().getSelectedText(); this.indexSpan = this.editor.document.createElement("span"); this.indexSpan.setAttribute("class", "cke-indexterm"); for(var i=0; i<4; i++){ var span = this.editor.document.createElement("span"); span.setAttribute("class", cssClasses[i]); if(selectedText.length > 0){ if(i===0){ span.setText(selectedText); } else{ span.$.innerHTML = "&#160;"; } } else{ span.setText(defaultText[i]); } this.termSpans.push(span); this.indexSpan.setAttribute("id", this.id); this.indexSpan.append(span); }; this.editor.insertElement(this.indexSpan); this.editor.insertText(selectedText); }; IndexTerm.prototype.setVisibility = function(state){ this.visible = state; if(state) this.indexSpan.setAttribute("class", "cke-indexterm"); else this.indexSpan.setAttribute("class", "cke-indexterm-hidden"); for(var i in this.termSpans){ if(state){ this.termSpans[i].setAttribute("class", cssClasses[i]); } else{ this.termSpans[i].setAttribute("class", cssClasses[i] + "-hidden"); } } }; CKEDITOR.plugins.add('indexterms', { "icons": "indexterms", "init" : function(editor){ CKEDITOR.dialog.add("indextermDialog", this.path + "dialogs/indextermsDialog.js"); editor.addCommand("indextermDialog", new CKEDITOR.dialogCommand("indextermDialog")); editor.addCommand("add_iterm", { "exec": function(editor){ var term = new IndexTerm(editor); } }); editor.addCommand("toggle_indexterms", { "exec": function(editor){ CKEDITOR.IndexTermManager.toggleGlobalVisibility(); } }); editor.ui.addButton("indexterms", { "label": "Insert Index Term", "command" : "add_iterm", "toolbar": "insert" }); editor.ui.addButton("toggle_indexterms", { "icon" : this.path + "icons/toggle_indexterms.png", "label": "Toggle index term visibility", "command" : "toggle_indexterms", "toolbar": "insert" }); if(editor.contextMenu){ editor.addMenuGroup("indextermGroup"); editor.addMenuItem('indexItem', { "label": "Edit Index Term", "command": "indextermDialog", "group": "indextermGroup" }); editor.contextMenu.addListener(function(element){ var parent = element.getAscendant("span"); if(parent && parent.getName() === "span" && parent.getAttribute("class") === "cke-indexterm"){ return {"indexItem": CKEDITOR.TRISTATE_OFF }; } }); } } }); })();
define(function(require) { var $ = require('jquery'); var HTTP = require('http'); var uploadButton = document.getElementById('upload'); var data = {}; function readData(event) { var files = event.target.files; if (files && (window.File && window.FileReader && window.FileList && window.Blob)) { for (var i=0, f; f=files[i]; i++) { var r = new FileReader(); r.onload = (function(f) { return function(e) { var contents = e.target.result; var aFile = {}; /* alert('Data retreived:\n' + 'name: ' + f.name + '\n' + 'type: ' + f.type + '\n' + 'size: ' + f.size + ' bytes\n' + 'data:\n ' + contents); */ data[f.name] = aFile; aFile.size = f.size; aFile.type = f.type; aFile.content = btoa(contents); }; }) (f); r.readAsBinaryString(f); console.log(r); console.log(r.result); console.log(atob(r.result)); } } else { alert('Failed to load file'); } } document.getElementById('getFile').addEventListener('change', readData, false); uploadButton.addEventListener('click', function() { /* var formData = new FormData(document.forms[0]); Array.from(document.getElementsByTagName('input')).map(function(file) { if (file.getAttribute('type') === 'file') formData.append('upload[]', file.files[0], file.files[0].name); }); //formData.append("keykey", "can"); //files.append("upload", document.getElementById('getFile').files[0]); console.log(formData); console.log(formData.toString()); console.log(document.getElementById('getFile').files[0]); */ console.log(data); HTTP.POST({ url: 'https://ivn8oxnaaj.execute-api.us-west-1.amazonaws.com/default/BWProducerData', //'https://b4il8kzd93.execute-api.us-west-1.amazonaws.com/default/BWProducerData', data: JSON.stringify(data), //formData, //JSON.stringify({ email: 'jack@bankerwealth.com', password: 'T2U3iOiGc' }), //email: 'me@testing.com', passowrd: 'didntworkandnowdoes' , success: (data) => { console.log(data); console.log(JSON.parse(data)); console.log(JSON.parse(JSON.parse(data))); //console.log(data.json()); //var body = data }, error: (xhr)=> { console.log(xhr); } }); }); });
'use strict'; var unsatisfiedRequirement = { }; function insertRequires(instance, requireArray) { for (var i = 0; i < requireArray.length; i++) { if (!instance._components[requireArray[i]]) { instance._components[requireArray[i]] = unsatisfiedRequirement; } } } function insertProvides(instance, name, promise, context, replace) { if (!replace && ( instance._components[name] && instance._components[name] !== unsatisfiedRequirement ) ) throw new Error('Plugin that provides ' + name + ' is already registered.'); instance._components[name] = { context: context, promise: promise }; } function useOne(instance, plugin, replace) { if (!plugin) return; insertRequires(instance, plugin.req); insertProvides( instance, plugin.provides, plugin.providePromise, plugin.context, replace ); } /** * Simple container to provide a DI. All components are returned as promises. * Lifecycle of components are handled by client application by nesting promises. **/ module.exports = function (){ return { _components: {}, /** * Registeres a component to inject. If there is a component with the same name * already registered and replaceIfExists is false, throws. * @param {Object|Object[]} component - Definition of a component(s) * @param {boolean} replaceIfExists - Specifies whether a component with the same name should be replaced with this one. * @returns {Object} Container **/ use: function use (component, replaceIfExists) { if(component instanceof Array) { for(var i = 0; i < component.length; i++ ) { useOne(this, component[i], replaceIfExists); } } else { useOne(this, component, replaceIfExists); } return this; }, /** * Check whether all compontents have satisfied dependecies. * @returns {Object} Container **/ check: function check () { //make sure no _plugin is unsatisfied requirement for(var name in this._components){ if(this._components[name] === unsatisfiedRequirement) { throw new Error(name + ' hasn\'t been satisfied'); } } return this; }, /** * Returns all components with name matching the regular expression * @param {Regex} nameRegex - regular expression to filter components * @param {Object} lifecycleContainer - object that holds already resolved components * @return {Promise[]} All matching components. If none of the components matches returns promise of an empty array. **/ allComponents: function allComponents (nameRegex, lifecycleContainer){ var promises = []; for(var name in this._components) { if(name.match(nameRegex)) { promises.push(this.component(name, lifecycleContainer)); } } return Promise.all(promises); }, /** * Returns first component that matches the name * @param {string} name - Component name to match * @param {Object} lifecycleContainer - object that holds already resolved components * @return {Promise} Matched component or throws **/ component: function component (name, lifecycleContainer) //promise for registered component { if(!this._components[name]) throw new Error('Cant provide ' + name); var component = this._components[name]; if (lifecycleContainer && lifecycleContainer[name]) { //context already contains this component return lifecycleContainer[name]; } var componentPromise = component.promise.call(component.context || this, this); if (lifecycleContainer) lifecycleContainer[name] = componentPromise; return componentPromise; } }; };
lolDmgApp.directive('matchInfo', function(){ return { restrict: 'E', templateUrl: '/templates/pages/match/index.html' }; }); lolDmgApp.directive('matchChampions', function(){ return { restrict: 'E', templateUrl: '/templates/pages/match/matchChampions.html' }; }); lolDmgApp.directive('matchVsLine', function(){ return { restrict: 'E', templateUrl: '/templates/pages/match/matchVsLine.html' }; });
import React, { Component } from 'react'; import Search from './Search'; import { contacts, getContactes} from '../Service/DataService'; class Home extends Component { constructor(props) { super(props); this.state = {} } render() { return ( <div className="container d1" > <h1>Réservez une consultation physique chez un professionnel de santé</h1> <Search search={this.search}></Search> </div> ); } } export default Home;
//**** TAREAS DE ALUMNOS ****// $("#alumno-tareas").on("click", function(){ $(".loader").css("display", "block"); // Cargamos tras el inicio de la página todas las tareas a realizar por el usuario. $.ajax({ type: "POST", dataType: "json", async: false, url: "../../Ver_tareas", success: function(resp){ for(var i = 0; i < resp.length; i++){ for(j = 0; j < 4; j++){ if(resp[i][j] == null){ resp[i][j] = ""; } } } var fechaactual = $.datepicker.formatDate('yy/mm/dd', new Date()); for(var i = 0; i < resp.length; i++){ if(fechaactual <= $.datepicker.formatDate('yy/mm/dd', new Date(resp[i][3]))){ $("#alumn-table-tareas tbody").append("<tr>"); $("#alumn-table-tareas tbody tr:last-child").append("<td>"+resp[i][0]+"</td>"); $("#alumn-table-tareas tbody tr:last-child").append("<td>"+$.datepicker.formatDate('dd/mm/yy', new Date(resp[i][3]))+"</td>"); if(resp[i][1].length > 15){ $("#alumn-table-tareas tbody tr:last-child").append("<td>"+resp[i][1].substr(0,15)+" ...</td>"); }else{ $("#alumn-table-tareas tbody tr:last-child").append("<td>"+resp[i][1]+"</td>"); } $("#alumn-table-tareas tbody tr:last-child").append("<td class='descr-act text-xs-center'><a href='' data-id="+resp[i][0]+" data-toggle='modal' data-target='#modal-actividad'><i class='fa fa-file-text text-primary' aria-hidden='true'></i></a></td>"); $("#alumn-table-tareas tbody tr:last-child").append("<td><input type='file'></td>"); $("#alumn-table-tareas tbody tr:last-child").append("<td class='sube-tarea text-xs-center'><i class='fa fa-upload text-success' aria-hidden='true'></i></td>"); $("#alumn-table-tareas tbody tr:last-child").append("<td class='act-ok text-xs-center'><i class='fa fa-times text-danger' aria-hidden='true'></i></td>") $("#alumn-table-tareas tbody").append("</tr>"); } } $("#alumn-table-tareas").DataTable({ "language":{ "lengthMenu":"Mostrar _MENU_ registros por página.", "zeroRecords": "Sin resultados en su búsqueda.", "info": "Hay un total de _MAX_ tareas.", "infoEmpty": "No hay registros aún.", "infoFiltered": "(filtrados de un total de _MAX_ registros)", "search" : "Búsqueda: ", "LoadingRecords": "Cargando ...", "Processing": "Procesando...", "SearchPlaceholder": "Comience a teclear...", "paginate": { "previous": "Anterior", "next": "Siguiente", } } }); }, complete: function(){ $(".loader").fadeOut(2000); } }); }); //**** EXÁMENES DE ALUMNOS ****// $("#alumno-examenes").on("click", function(){ $(".loader").css("display", "block"); // Cargamos tras el inicio de la página todos los exámenes a realizar por el usuario. $.ajax({ type: "POST", dataType: "json", async: false, url: "../../Ver_examenes", success: function(resp){ for(var i = 0; i < resp.length; i++){ for(j = 0; j < 4; j++){ if(resp[i][j] == null){ resp[i][j] = ""; } } } var fechaactual = $.datepicker.formatDate('yy/mm/dd', new Date()); for(var i = 0; i < resp.length; i++){ if(fechaactual <= $.datepicker.formatDate('yy/mm/dd', new Date(resp[i][3]))){ $("#alumn-table-examenes tbody").append("<tr>"); $("#alumn-table-examenes tbody tr:last-child").append("<td>"+resp[i][0]+"</td>"); $("#alumn-table-examenes tbody tr:last-child").append("<td>"+$.datepicker.formatDate('dd/mm/yy', new Date(resp[i][3]))+"</td>"); if(resp[i][1].length > 15){ $("#alumn-table-examenes tbody tr:last-child").append("<td>"+resp[i][1].substr(0,15)+" ...</td>"); }else{ $("#alumn-table-examenes tbody tr:last-child").append("<td>"+resp[i][1]+"</td>"); } $("#alumn-table-examenes tbody tr:last-child").append("<td class='descr-act text-xs-center'><a href='' data-id="+resp[i][0]+" data-toggle='modal' data-target='#modal-actividad'><i class='fa fa-file-text text-primary' aria-hidden='true'></i></a></td>"); $("#alumn-table-examenes tbody tr:last-child").append("<td><input type='file' style='color: transparent; width:10px;'></td>"); $("#alumn-table-examenes tbody tr:last-child").append("<td class='sube-tarea text-xs-center'><i class='fa fa-upload text-success' aria-hidden='true'></i></td>"); $("#alumn-table-examenes tbody tr:last-child").append("<td class='act-ok text-xs-center'><i class='fa fa-times text-danger' aria-hidden='true'></i></td>") $("#alumn-table-examenes tbody").append("</tr>"); } } $("#alumn-table-examenes").DataTable({ "language":{ "lengthMenu":"Mostrar _MENU_ registros por página.", "zeroRecords": "Sin resultados en su búsqueda.", "info": "Hay un total de _MAX_ exámenes.", "infoEmpty": "No hay registros aún.", "infoFiltered": "(filtrados de un total de _MAX_ registros)", "search" : "Búsqueda: ", "LoadingRecords": "Cargando ...", "Processing": "Procesando...", "SearchPlaceholder": "Comience a teclear...", "paginate": { "previous": "Anterior", "next": "Siguiente", } } }); }, complete: function(){ $(".loader").fadeOut(2000); } }); }); //Recoge el data-id del alumno para hacer una consulta más exhaustiva en un modal. $(document).delegate(".descr-act a", "click", function(event){ var idactividad = $(this).data("id"); $("#modal-actividad").css("cursor", "default"); $.ajax({ type: "POST", dataType: "json", data: {idactividad:idactividad}, url: "../../Actividad_individual", success: function(resp){ for(var i = 0; i < resp.length; i++){ if(resp[i] == null){ resp[i] = ""; } } $(".modal-body").empty(); $(".modal-body").append("<div class='text-xs-center'><h3 class='text-primary font-weight-bold'>"+resp[0]+"</h3></div>"); $(".modal-body").append("<hr/>"); if(resp[3] == "T"){ $(".modal-body").append("<div class='text-xs-justify'><span class='font-weight-bold'>Descripción de la tarea: </span><p>"+resp[1]+"</p></div>"); }else{ $(".modal-body").append("<div class='text-xs-justify'><span class='font-weight-bold'>Descripción del examen: </span><p>"+resp[1]+"</p></div>"); } $(".modal-body").append("<div><span class='font-weight-bold text-danger'>¡Recuerda!</span> <br/> Tienes hasta el <b>"+$.datepicker.formatDate('dd/mm/yy', new Date(resp[2]))+"</b> para hacer la entrega. </div>") } }); }); // Recoge las actividades (tareas y exámenes) y las imprime en un listado. $("#alumno-calendario").on("click", function(){ $.ajax({ url: '../../Recoge_fecactividades', type: 'POST', dataType: "json", async: false, success: function(resp){ var fechaactual = $.datepicker.formatDate('dd/mm/yy', new Date()); for(var i = 0; i < resp.length; i++){ var fechaactividad = $.datepicker.formatDate('dd/mm/yy', new Date(resp[i][0])); diferencia_dias = difDias(fechaactual, fechaactividad); // Si la diferencia de días entre la actividad y la actual son entre 0 y 15 días. if(diferencia_dias <= 15 && diferencia_dias >= 0){ var tipo; if(resp[i][1] == "E"){ tipo = "Examen"; }else{ tipo = "Tarea"; } $("#prox-actividades > div").append( "<span class='font-weight-bold col-md-3 text-xs-right'>Fecha de entrega: </span> "+ "<span class='col-md-9 text-xs-left'>"+$.datepicker.formatDate('dd/mm/yy', new Date(resp[i][0]))+"</span><br/> "+ "<span class='font-weight-bold col-md-3 text-xs-right'>Nombre de actividad: </span> "+ "<span class='col-md-9 text-xs-left'>"+resp[i][2]+"</span><br/> "+ "<span class='font-weight-bold col-md-3 text-xs-right'>Tipo: </span> "); if(tipo == "Examen"){ $("#prox-actividades > div").append("<span class='col-md-9 text-xs-left text-danger'>"+tipo+" <i class='fa fa-exclamation text-danger' aria-hidden='true'></i></span><br/><hr/> "); }else{ $("#prox-actividades > div").append("<span class='col-md-9 text-xs-left text-success'>"+tipo+" </span><br/><hr/>"); } } } } }); }); // Retorna la diferencia de días entre 2 fechas pasadas. function difDias (f1,f2){ var aFecha1 = f1.split('/'); var aFecha2 = f2.split('/'); var fFecha1 = Date.UTC(aFecha1[2],aFecha1[1]-1,aFecha1[0]); var fFecha2 = Date.UTC(aFecha2[2],aFecha2[1]-1,aFecha2[0]); var dif = fFecha2 - fFecha1; var dias = Math.floor(dif / (1000 * 60 * 60 * 24)); return dias; }
require('!style!css!dc/web/css/dc.min.css'); var dc = require('dc'); var d3 = require('d3'); var crossfilter = require('crossfilter'); var DataTransformer = require('./data.transformer.js'); var TitleHoldVolumeChart = require('./titlechart.js'); var LibraryHoldChart = require('./librarychart.js'); var HoldVolumeChart = require('./holdvolumechart.js') d3.csv('data/popular_books_epl.csv', function(data) { var transformer = new DataTransformer(data); transformer.init(); var ndx = transformer.getNdx(); var titleHoldVolumeChart = new TitleHoldVolumeChart(ndx, '#title-hold-chart'); titleHoldVolumeChart.init(); var libraryHoldChart = new LibraryHoldChart(ndx, '#library-hold-chart'); libraryHoldChart.init(); var holdVolumeChart = new HoldVolumeChart(ndx, '#weekly-volume-chart', transformer.dateFormat); holdVolumeChart.init(); dc.renderAll(); window.titleHoldVolumeChart = titleHoldVolumeChart.getChart(); window.libraryHoldChart = libraryHoldChart.getChart(); window.holdVolumeChart = holdVolumeChart.getChart(); }); window.dc = dc;
/** * Created by ssanchez on 28/03/16. */ var gulp = require('gulp'), sass = require('gulp-sass'), cleancss = require('gulp-clean-css'), uglify = require('gulp-uglifyjs'); gulp.task('css', function () { return gulp .src('./statics/css/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(cleancss({'debug': true}, function (details) { console.log('Original size: ' + details.stats.originalSize); console.log('Minified size: ' + details.stats.minifiedSize); })) .pipe(gulp.dest('./statics/css/')); }); gulp.task('js', function () { return gulp .src([ './statics/js/jquery-1.11.1.min.js', './statics/js/bootstrap.js', './statics/js/liveicons.js', './statics/js/icons.js', './statics/js/angular.min.js', './statics/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js', './statics/ng-scrollbars/dist/scrollbars.min.js', './statics/js/app.js', './statics/js/parallax.js', './statics/js/FBFactory.js', './statics/js/ngGallery.js', './statics/ng-droplet/dist/ng-droplet.min.js', './statics/angular-bootstrap/ui-bootstrap.min.js', './statics/angular-bootstrap/ui-bootstrap-tpls.min.js' ]) .pipe(uglify('welkomiapp.js', { 'mangle': false })) .pipe(gulp.dest('./statics/js/')) }); gulp.task('css:watch', function () { gulp.watch('./statics/css/*.scss', ['css']) });
/** * Created by Administrator on 2017/4/4. */ angular.module("turnPage") .directive("turnPageNum",function () { return{ restrict:"ACE", replace:true, templateUrl:'../turnPage/turnPage_template.html', controller:['$scope','$routeParams','$http','allActivity',function ($scope,$routeParams,$http,allActivity) { $scope.dataNum=allActivity.length; $scope.pages=Math.ceil($scope.dataNum/3); $scope.pageNum=[]; for(var i=0;i<$scope.pages;i++){ $scope.pageNum.push(i); } $scope.currentPage = 0; //设置当前页是 0 $scope.listsPerPage = 3; $scope.setPage = function(num){ // 当点击页码数字时执行的函数 $scope.currentPage = num; //将当前页 设置为 页码数 } $scope.prevPage = function(){ //点击上一页执行的函数 if($scope.currentPage > 0){ $scope.currentPage--; } } $scope.nextPage = function(){ //点击下一页执行的函数 if ($scope.currentPage < $scope.pages-1){ $scope.currentPage++; } } }] } })
/* * grunt-tight-sprite * https://github.com/uhop/grunt-tight-sprite * * Copyright (c) 2013 Eugene Lazutkin * Licensed under the New BSD license. */ "use strict"; var iconPath = "tests/icons/"; module.exports = function(grunt) { grunt.initConfig({ tight_sprite: { sprite1: { options: { hide: iconPath }, src: [iconPath + "*/**/*.{png,jpg,jpeg,gif}"], dest: iconPath + "sprite1.png" } } }); grunt.loadTasks("tasks"); grunt.registerTask("default", "tight_sprite"); grunt.registerTask("test", "tight_sprite"); };
const leagueKey = '?api_key=' + Config.leagueKey; const request = require('request'); const requestError = new Error('There is something wrong with your request. Check your spelling or try again later.'); const serverError = new Error('There was a server error in processing your request. Try again later.'); exports.getSummonerObj = function (name, region, callback) { request('https://' + exports.getPlatform(region) + '/lol/summoner/v4/summoners/by-name/' + toId(name) + leagueKey, (error, response, body) => { let myError = error ? 'Error: ' + error : null; if(String(response.statusCode).charAt(0) == 4) myError = requestError; if(String(response.statusCode).charAt(0) == 5) myError = serverError; if(!error && response.statusCode == 200) return callback(myError, JSON.parse(body)); }); } exports.getSummonerId = function(name, region, callback) { exports.getSummonerObj(name, region, (err, body) => { return callback(err, body.id); }) } exports.getLeagueObj = function(id, region, callback) { request('https://' + exports.getPlatform(region) + '/lol/league/v4/positions/by-summoner/' + id + leagueKey, (error, response, body) => { let myError = error ? 'Error: ' + error : null; if(String(response.statusCode).charAt(0) == 4) myError = requestError; if(String(response.statusCode).charAt(0) == 5) myError = serverError; if(!error && response.statusCode == 200) return callback(myError, JSON.parse(body)); }); } exports.getLeagueByName = function(name, region, callback) { exports.getSummonerId(name, region, (err, id) => { if(err) return callback(err, id); exports.getLeagueObj(id, region, (err, body) => {return callback(err, body[0])}); }); } exports.getPlatform = function(region) { var platforms = { 'na': 'NA1', 'euw': 'EUW1', 'eune': 'EUN1', 'lan': 'LA1', 'las': 'LA2', 'oce': 'OC1', 'tr': 'TR1', 'ru': 'RU', 'br': 'BR1', 'jp': 'JP1', 'kr': 'KR', 'pbe': 'PBE1', } return platforms[region] + '.api.riotgames.com'; };
var express = require('express'); var app = express(); var isMobile = require('cloud/utils/mobile-detection'); app.set('views','cloud/views'); app.set('view engine', 'ejs'); app.use(express.bodyParser()); app.get('/', function(req, res) { if (isMobile(req)) { res.render('index'); } else { res.render('index'); } }); app.get('/mdl', function(req, res) { res.render('mdl'); }); app.listen(); app.use(function(req, res, next){ res.status(404).render('404'); });
/* VUEX Data Store. Copyright (c) 2019. Scott Henshaw, Kibble Online Inc. All Rights Reserved. */ import Vue from 'vue' import Vuex from 'vuex' import TelemetryRecord from '@/../lib/TelemetryRecord'; import Connection from '@/../lib/Connection' Vue.use( Vuex ) const cloud = new Connection() // Modules // Store with modules /* const store = new Vuex.Store({ modules: { ModelStore, PlayerStore, GameStore, ChatStore, } }); */ // OR // Store with local definitions const store = new Vuex.Store({ state: { currentRec: new TelemetryRecord(), telemetryArray: [], stringRecords: "", }, mutations: { SET_CURRENT_RECORD: (state, newRecord) => { state.currentRec = newRecord state.telemetryArray.push(newRecord) }, SET_RECORDS: (state, loadedRecords) => { state.stringRecords = loadedRecords }, SET_TM: (state, records) => { state.telemetryArray = records }, CLEAR_RECORDS: (state) => state.telemetryArray = [] }, actions: { async updateRecord({commit}, newRec){ commit('SET_CURRENT_RECORD', newRec) let id = await cloud.post('telemetry', newRec) .catch(err =>{ console.log(err) return }) }, async getRecords({commit}){ let get = await cloud.get('telemetry') .catch(err => { console.log(err) return }) commit('SET_RECORDS', get) }, clearRecords({commit}){ commit('CLEAR_RECORDS') }, setTMRecords({commit}, telemetry){ commit('SET_TM', telemetry) } }, getters: { getCurrentRecord: state => state.currentRec, getTelemetryArray: state => state.telemetryArray, getStringRecords: state => state.stringRecords, } }); export default store;
import React from 'react'; import SliderItem from '../SliderItem/SliderItem' const Slider = () => { return( <div className="features-slider_items"> <SliderItem bgImage={'1.svg'} label={'Первое целевое преимущество'}/> <SliderItem bgImage={'2.svg'} label={'Второе целевое преимущество'}/> <SliderItem bgImage={'3.svg'} label={'Третье целевое преимущество'}/> <SliderItem bgImage={'4.svg'} label={'Четвертое целевое преимущество'}/> </div> ) } export default Slider;
const { req } = require('../../framework/index.js'); const typeMap = { COMMON: 'common', BLACKLIST: 'blacklist', ATTENDANCE: 'attendance', }; const getList = (data) => { const { type, cid, pid, codes, superAdmin, companySuperAdmin, page, size, attendanceGroupId, } = data; if (type === typeMap.ATTENDANCE) { return req.project.getListAttendanceApplyApprovers({ attendanceGroupId, }) .then((res) => { if (res.code !== 0) { return res; } const { list, total } = res.data; return { code: 0, data: { list: list.map(u => ({ img: u.headImg, name: u.name || u.userName || u.nikeName, id: u.id, preUser: u.preUser, })), total, }, }; }); } if (type === typeMap.BLACKLIST) { return req.company.getBlacklistAuditors({ companyId: cid, }) .then((res) => { if (res.code !== 0) { return res; } const { list, total } = res.data; return { code: 0, data: { list: list.map(u => ({ img: u.img, name: u.name || u.userName || u.nikeName, id: u.id, preUser: u.preUser, })), total, }, }; }); } const d = {}; if (page) { d.page = page; } if (size) { d.size = size; } if (pid) { d.projectId = pid; d.permissionCodes = codes; d.includeCompanySuperAdmin = companySuperAdmin; d.incluedeProjectSuperAdmin = superAdmin; return req.project.getAuditors(d) .then((res) => { if (res.code !== 0) { return res; } const { list, total } = res.data; return { code: 0, data: { list: list.map(u => ({ img: u.headImg, name: u.name || u.nickName, id: u.userId, preUser: u.preUser === '01', })), total, }, }; }); } d.companyId = cid; d.permissionCodes = codes; d.includeSuperAdmin = superAdmin; return req.company.getAuditors(d) .then((res) => { if (res.code !== 0) { return res; } const { list, total } = res.data; return { code: 0, data: { list: list.map(u => ({ img: u.headImg, name: u.userName, id: u.userId, preUser: u.preUser === '01', })), total, }, }; }); }; module.exports = { typeMap, getList, };
import { render } from '@testing-library/react'; import Display from './display'; describe('Display', () => { it('should render successfully', () => { const { baseElement } = render(<Display />); expect(baseElement).toBeTruthy(); }); });
const MongoClient = require('mongodb').MongoClient; const ObjectID = require('mongodb').ObjectID; const config = require('../config.json'); const errors = require('../errors.json'); const logger = require('../utils/logger'); const connect = () => { return new Promise((resolve, reject) => { MongoClient.connect(config.DB_URL, {useNewUrlParser: true}) .then((client) => resolve(client.db(config.DB_NAME))) .catch((err) => { logger.error('Could not connect to database', err); reject(errors.DB_CONNECT); }); }); }; const query = (type, collection, obj) => { return new Promise((resolve, reject) => { connect() .then((db) => { const allowedFnc = ['insertOne', 'updateOne', 'deleteOne', 'find']; if (!allowedFnc.includes(type)) return reject(errors.DB_UNKNOWN_TYPE); const dbCollection = db.collection(collection); exec(type, dbCollection, obj) .then((result) => resolve(result)) .catch((err) => { logger.error('Error on database query', err); reject(errors.DB_QUERY); }); }) .catch((err) => reject(err)); }); }; const exec = (fnc, collection, obj) => { return new Promise((resolve, reject) => { if (fnc === 'find') { collection[fnc](obj).toArray() .then((result) => resolve(result)) .catch((err) => reject(err)); } else if (fnc === 'updateOne') { const updateObj = obj.inc ? { $inc: obj.inc} : { $set: obj.obj}; collection[fnc](obj.filter, updateObj) .then((result) => resolve(result)) .catch((err) => reject(err)); } else { collection[fnc](obj) .then((result) => resolve(result)) .catch((err) => reject(err)); } }); }; const convertID = (id) => { return new ObjectID(id); }; module.exports.query = query; module.exports.convertID = convertID;
Discourse.KbFilterSetView = Discourse.View.extend({ templateName: 'javascripts/diaedu/templates/filter_set', // handle clicks on checkboxes click: function(e) { // send an event to the router if the click was on a checkbox if ($(e.target).is('.ember-checkbox')) this.get('controller').send('filterChanged'); } });
import React from 'react' import { View, Text, StyleSheet, TouchableOpacity, TextInput, } from 'react-native' import { SearchBar } from 'react-native-elements' import { Ionicons } from '@expo/vector-icons'; import Searchbar from './SearchBar' const Header = ({ navigation }) => { return ( <View style={styles.container}> <Ionicons name='menu' size={40} style={styles.text1} color='white' onPress={() => { navigation.openDrawer() }} /> <Ionicons name='search' size={30} style={styles.text2} color='white' /> </View> ) } const styles = StyleSheet.create({ container: { flexDirection: 'row', backgroundColor: 'darkgreen', }, text1: { flex: 1, }, text2: { flex: 0, marginTop: 6, marginRight: 7 }, text3: { flex: 0, }, }) export default Header
// JavaScript Document // Preload Functions for Dreamweaver function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } // Initialize the page (header is on all pages) function init() { //========================================================================================== // if supported, initialize TransMenus //========================================================================================== // Check isSupported() so that menus aren't accidentally sent to non-supporting browsers. // This is better than server-side checking because it will also catch browsers which would // normally support the menus but have javascript disabled. // // If supported, call initialize() and then hook whatever image rollover code you need to do // to the .onactivate and .ondeactivate events for each menu. //========================================================================================== MM_preloadImages('images/Home-Hover.gif','images/Catering-Hover.gif','images/Our-Menu-Hover.gif','images/Location-Hover.gif', 'images/History-Hover.gif') if (TransMenu.isSupported()) { TransMenu.initialize(); // hook all the highlight swapping of the main toolbar to menu activation/deactivation // instead of simple rollover to get the effect where the button stays hightlit until // the menu is closed. menu2.onactivate = function() { document.getElementById("Menu").className = "hover"; }; menu2.ondeactivate = function() { document.getElementById("Menu").className = ""; }; menu3.onactivate = function() { document.getElementById("Catering").className = "hover"; }; menu3.ondeactivate = function() { document.getElementById("Catering").className = ""; }; document.getElementById("Home").onmouseover = function() { ms.hideCurrent(); this.className = "hover"; } document.getElementById("Location").onmouseover = function() { ms.hideCurrent(); this.className = "hover"; } document.getElementById("History").onmouseover = function() { ms.hideCurrent(); this.className = "hover"; } document.getElementById("Home").onmouseout = function() { this.className = ""; } document.getElementById("Location").onmouseout = function() { this.className = ""; } document.getElementById("History").onmouseout = function() { this.className = ""; } } }
const MULTIPLIER = 1; const CURSOR_PX = 32; let currentPosX = 0; let currentPosY = 0; let screenOffset = 0; let textMatrix = []; function init() { //TODO Handle different resolution from 320*200 to 1280*800 document.addEventListener("keydown", handleKey); writeStartupScreen(); } function handleKey(event) { const keyCode = event.keyCode; const key = event.key; console.log(event); switch (keyCode) { case 37: //CRSRLEFT moveCursor(-1, 0); return; case 38: //CRSRUP moveCursor(0, -1); return; case 39: //CRSRRIGHT moveCursor(1, 0); return; case 40: //CRSRDOWN moveCursor(0, 1); return; case 13: //ENTER executeLine(); return; case 8: //BACKSPACE event.preventDefault(); handleBackSpace(); case 0: //VARS case 9: //TAB case 16: //SHIFT case 18: //ALT - AltGR WARNING IF USED CHECK!!! case 20: //CAPS case 27: //ESC -> RUN/STOP? case 91: //WIN case 93: //CONTEXT MENU case 112: //F1 case 113: //... case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: //F12 case 181: //Audio mute return; default: writeCharacter(key); } } function moveCursor(deltaX, deltaY) { const cursor = document.getElementById('cursor'); const overlay = document.getElementById('overlay'); const left = isNaN(parseInt(cursor.style.left.split('px')[0])) ? 0 : parseInt(cursor.style.left.split('px')[0]); const top = isNaN(parseInt(cursor.style.top.split('px')[0])) ? 0 : parseInt(cursor.style.top.split('px')[0]); cursor.style.left = (left + deltaX * CURSOR_PX) + 'px'; cursor.style.top = (top + deltaY * CURSOR_PX) + 'px'; currentPosX = Math.floor((left + deltaX * CURSOR_PX) / CURSOR_PX); currentPosY = Math.floor((top + deltaY * CURSOR_PX) / CURSOR_PX); if (currentPosX > 39) { moveCursor(-40, 1); } if (currentPosX < 0) { moveCursor(40, -1); } if (currentPosY < 0) { moveCursor(0, 1); moveScreen(-1); } if (currentPosY > 24) { moveCursor(0, -1); moveScreen(1); } if (!!textMatrix[currentPosY+screenOffset]) { overlay.textContent = textMatrix[currentPosY+screenOffset][currentPosX]; } else { overlay.textContent = ""; } } function writeCharacter(char) { if (!textMatrix[currentPosY+screenOffset]) { textMatrix[currentPosY+screenOffset] = []; } textMatrix[currentPosY+screenOffset][currentPosX] = char.toUpperCase(); moveCursor(1, 0); printTextMatrix(screenOffset); } function writeStartupScreen() { const c64 = document.getElementById('c64-text'); c64.textContent += "\n"; c64.textContent += " **** SCAZZUM VIVENDI ****\n"; c64.textContent += "\n"; c64.textContent += " PROJECT LIST - 38911 BYTES FREE\n"; c64.textContent += "\n"; c64.textContent += "READY.\n"; moveCursor(0, 6); updateTextMatrix(); } function updateTextMatrix() { const c64 = document.getElementById('c64-text'); const writtenText = c64.textContent; let textMatrixX = 0; let textMatrixY = 0; for (let char of writtenText) { if (char == "\n") { textMatrixX += 1; textMatrixY = 0; continue; } if (!textMatrix[textMatrixX]) { textMatrix[textMatrixX] = []; } textMatrix[textMatrixX][textMatrixY] = char; textMatrixY += 1; } console.log(textMatrix); } function printTextMatrix(inputX) { let startX = !!inputX ? inputX : 0; const c64 = document.getElementById('c64-text'); let text = ""; for (let x = startX; x < textMatrix.length; x++) { const xLength = textMatrix[x] ? textMatrix[x].length : 0; for (let y = 0; y < xLength; y++) { if (textMatrix[x][y] != null) { text += textMatrix[x][y]; } else { text += " "; } } text += "\n" } c64.textContent = text; } function executeLine() { moveCursor(0, 2); handleError(); } function moveScreen(delta) { screenOffset += delta; if (screenOffset > -1) { printTextMatrix(screenOffset); } else { screenOffset = 0; } } function handleBackSpace() { if (currentPosX > 0) { for (let x = currentPosX; x < 40; x++) { textMatrix[currentPosY][x-1] = textMatrix[currentPosY][x]; } } printTextMatrix(); moveCursor(-1, 0); } function handleError() { const err = "?SYNTAX ERROR"; const msg = "READY."; for (let i in err) { if (!textMatrix[currentPosY+screenOffset]) { textMatrix[currentPosY+screenOffset] = []; } textMatrix[currentPosY+screenOffset][i] = err[i]; } for (let i in msg) { if (!textMatrix[currentPosY + 1+screenOffset]) { textMatrix[currentPosY + 1+screenOffset] = []; } textMatrix[currentPosY + 1+screenOffset][i] = msg[i]; } moveCursor(-currentPosX, 2); printTextMatrix(screenOffset); }
Trello.Views.CardShow = Backbone.CompositeView.extend({ template: JST['card_show'], events: { 'click .remove-card-button': 'removeCard', 'click .new-card-button': 'addCard' }, tagName: 'li', addCard: function () { }, initialize: function (options) { this.listenTo(this.model,"sync",this.render); }, render: function () { this.$el.html(this.template({card: this.model})); return this; }, });
/** * Created by nisabhar on 3/14/2016. */ define(['ojs/ojcore', 'knockout', 'pcs/startform/services/startformDataService', 'pcs/util/pcsUtil', 'pcs/pcsform/pcsFormUtil' ,'ojs/ojknockout', 'ojs/ojdialog', 'ojs/ojbutton', 'pcs/pcs.attachments', 'ojL10n!pcs/resources/nls/pcsSnippetsResource' ], function(oj, ko, services, pcsUtil, pcsFormUtil) { 'use strict'; /** * The view model for the main content view template */ function StartformContainer(params) { var self = this; var loggerUtil = require('pcs/util/loggerUtil'); //Set the resourcebundle self.bundle = require('ojL10n!pcs/resources/nls/pcsSnippetsResource'); //all the data passed to the container self.data = params.data; //the jquery element where the widget is pushed, all the selectors will work in context of this element self.rootElement = self.data.rootElement; //the main Data object of the plugin self.startformData = self.data.startformData; //Complet Frevvo form url including server path self.formURL = ko.observable(); // Label for submit button self.submitLabel = self.data.submitLabel; //frevvo form URl which we get from the Rest APi , this is a relative path on the server self.formInstanceURL = ''; //Error Message text we will show in the error Dialog self.errorMessage = ko.observable(); //Id for pcs Form tag self.formRendererTagId = 'process-' + pcsUtil.getRandomInt(0, 100); //Hack for waiting for frevvo form to Post submit message . // Also if the frevvo ear doent have the fix for post message // Its required as frevvo fires multiple Post Message self.waitForMessage = false; self.componentRenderCount = 0; var handleComponentRenderStart = function() { self.componentRenderCount++; }; var handleComponentRenderFinish = function() { loggerUtil.log(self.componentRenderCount); self.componentRenderCount--; if (self.componentRenderCount === 0) { setTimeout(function() { self.rootElement.trigger('startform:loaded'); }, 1000); } }; //This method is to get the frevvo form URL and the list of saved attachments function initStartForm() { var onloadStartFormResponse = function(e) { var map; var attachments; var customMsg; try { try { map = pcsUtil.multipartParse(e.currentTarget); // map will have data of type fileName : content-Type ,data //loggerUtil.log(map); } catch (error) { customMsg = self.bundle.pcs.startform.form_url_error; self.ajaxErrorHandler(null, customMsg); //Hide loadinf $('#pcs-startform-loading', self.rootElement).hide(); } if (map) { if (map.pcsFormUrl && map.pcsFormUrl.data) { // CHeck if its PCS form if (self.startformData.startType && self.startformData.startType === 'START_PCS_FORM') { self.loadPCSForm(map.pcsFormUrl.data); } else { handleComponentRenderStart(); //One of the entry in the map will be of frevvo form URl self.formInstanceURL = map.pcsFormUrl.data; self.formURL(pcsUtil.getServerURL() + self.formInstanceURL); $('#pcs-startapp-form-frame', self.rootElement).show(); handleComponentRenderFinish(); } } else { customMsg = self.bundle.pcs.startform.form_unavailable_error; self.ajaxErrorHandler(null, customMsg); } var fileName; attachments = []; for (fileName in map) { if (fileName === 'pcsFormUrl') { //Do Nothing } else { var file = map[fileName]; var tmpStr = 'Saved earlier'; var content; content = file.data; var attachment = { filename: fileName, fileInfoText: tmpStr, href: '', contentType: file.contentType, content: content }; attachments.push(attachment); } } } if (!self.data.hideAttachment) { if (self.startformData.isDocsEnabled) { self._getStartFolderName(attachments); } else { self._attachAttachmentPlugin(attachments, ''); } } } catch (error) { customMsg = self.bundle.pcs.startform.form_url_error; self.ajaxErrorHandler(null, customMsg); //Hide loadinf $('#pcs-startform-loading', self.rootElement).hide(); } }; var onError = function(e) { self.ajaxErrorHandler(e.currentTarget, ''); //Hide loadinf $('#pcs-startform-loading', self.rootElement).hide(); }; if (self.startformData.startType && self.startformData.startType === 'START_DP_FORM') { self.loadDpForm(); } else { services.getStartFormObject(self.startformData.processDefId, self.startformData.serviceName, self.startformData.operation, self.startformData.startType, onloadStartFormResponse, onError); } } self.loadPCSForm = function(dataString) { // TODO: following fix is done to revert back the multi byte chars that were translated // to protect from .charCodeAt() api. // Fix for - Embedded PCS Start Form UI fails with multi-byte characters var data = JSON.parse(decodeURIComponent(window.escape(dataString))); var formMetadataUrl = data['form']; var payload = data['payload']; if (payload) { //Do nothing } else { // Pre populate the form if payload is passed as an option if (self.data.payload && !$.isEmptyObject(self.data.payload)) { payload = self.data.payload; } } var properties = { formMetadataUrl: formMetadataUrl, payload: payload }; self.loadForm(properties); }; self.loadForm = function(properties) { var webFormContainer = $('#pcs-startform-iframe-container', self.rootElement); properties['webFormContainer'] = webFormContainer; properties['formRendererId'] = self.formRendererTagId; properties['outcomeCallback'] = self._saveOrSubmitWebForm; handleComponentRenderStart(); pcsFormUtil.loadPCSForm(properties) .then(function() { $('#pcs-startform-loading', self.rootElement).hide(); handleComponentRenderFinish(); }, function(jqXHR) { var msg = self.bundle.pcs.startform.form_retrieve_error; self.ajaxErrorHandler(jqXHR, msg); handleComponentRenderFinish(); }); }; //For dp forms self.loadDpForm = function() { $('#pcs-startform-save', self.rootElement).hide(); $('#pcs-startform-attachment-area', self.rootElement).hide(); var formMetadataURL = self.startformData.dpForm.formMetadataURL; if (!formMetadataURL) { $('#pcs-startform-loading', self.rootElement).hide(); return; } //create the completeURL formMetadataURL = pcsUtil.getDpRestURL() + formMetadataURL; var properties = { formMetadataUrl: formMetadataURL, convertJSON: true }; self.loadForm(properties); }; //Function to clean up the element and un apply its bindings self.cleanUpFormContainer = function(){ //no frevvo in EC, so no need to check var node = $('#pcs-startform-iframe-container', self.rootElement); if(node && node.length > 0){ ko.cleanNode(node['0']); //Un apply the bindings for the node and its children, pcsUtil.unApplyBindings(node, false); } }; self._getStartFolderName = function(attachments) { services.getStartFolderName(self.startformData.processDefId).done( function(data, textStatus, jqXHR) { // loggerUtil.log(data); self._attachAttachmentPlugin(attachments, data); } ).fail( function(jqXHR) { // Hide the loading indicator $('#pcs-startform-loading', self.rootElement).hide(); var customMsg = self.bundle.pcs.startform.form_url_error; self.ajaxErrorHandler(jqXHR, customMsg); } ); }; self._attachAttachmentPlugin = function(attachments, startFolderName) { var attachmentDiv = $('#pcs-startform-attachment', self.rootElement); //if the plugin was already used clean it up if (attachmentDiv && attachmentDiv.data() && !$.isEmptyObject(attachmentDiv.data())) { attachmentDiv.attachments('destroy'); } ko.cleanNode(attachmentDiv['0']); handleComponentRenderStart(); self.attachmentPlugin = attachmentDiv.attachments({ attachments: attachments, startFolderName: startFolderName, hideTitle: true, isDocsEnabled: self.startformData.isDocsEnabled }); // Defining the event listeners -- attachmentDiv.on('attachments:loaded', function(event) { handleComponentRenderFinish(); }); }; // Error handler method for the plugin self.ajaxErrorHandler = function(jqXHR, customMsg) { var msg = customMsg; if (jqXHR && jqXHR.status === 0) { msg = self.bundle.pcs.common.server_not_reachable; } if (jqXHR && jqXHR.status === 500) { msg = self.bundle.pcs.common.internal_server_err; } else if (jqXHR && jqXHR.status === 401) { // reset valid authInfo as the current auth is invalid msg = self.bundle.pcs.common.access_error_msg; } //self.errorMessage(msg); //$('#pcs-startform-error-dialog', self.rootElement).ojDialog('open'); $('#pcs-startform-error-msg', self.rootElement).text(msg); $('#pcs-startform-error-msg-container', self.rootElement).show(); }; // method called when user clicks discard self.discardForm = function(data, event) { $('#pcs-startform-discard-dialog', self.rootElement).ojDialog('open'); }; // method called when user clicks save self.saveForm = function(data, event) { if (self.data.startformData.startType === 'START_PCS_FORM') { self._saveWebForm('save'); } else { self._saveOrSubmitFrevvoForm('save'); } }; // method called when user clicks submit self.submitForm = function(data, event) { if (self.data.startformData.startType === 'START_PCS_FORM') { self._submitWebForm('submit'); } else if (self.data.startformData.startType === 'START_DP_FORM') { self._submitDPForm('submit'); } else { var iframe = $('#pcs-startform-iframe', self.rootElement)[0].contentWindow; //submit the form for validation iframe.postMessage('formValidation', pcsUtil.getServerURL()); self.waitForMessage = true; //Start the loading indicator $('#pcs-startform-overlay').addClass('pcs-common-load-overlay'); //Call it when Post message fails to come back even after 5 seconds setTimeout(function() { if (self.waitForMessage) { self.waitForMessage = false; loggerUtil.log('Frevvo did not respond on time submitting form without validation'); self._saveOrSubmitFrevvoForm('submit'); } }, 5000); // 10 seconds } }; function showValidationError(error) { var errorMsg = self.bundle.pcs.startform.form_validation_error; if(error && error.id === 'CANCELED'){ errorMsg = error.message; } $('#pcs-startform-error-msg', self.rootElement).text(errorMsg); $('#pcs-startform-error-msg-container', self.rootElement).show().delay(5000).fadeOut(2000); //Hide overlay $('#pcs-startform-overlay').removeClass('pcs-common-load-overlay'); } // method which does the post call to save the webform self._saveWebForm = function(action) { self._saveOrSubmitWebForm(action, ''); }; self._saveOrSubmitWebForm = function(action, outcome) { self._saveOrSubmitWebFormCommon(action, self._createProcessInstance, outcome); }; self._saveOrSubmitWebFormCommon = function(action, callback, outcome) { var formRender = $('form-renderer[id*=\'' + self.formRendererTagId + '\']', self.rootElement); if(!formRender || formRender.length ===0 ){ return ; } $('#pcs-startform-overlay', self.rootElement).addClass('pcs-common-load-overlay'); pcsFormUtil.saveOrSubmitPCSForm(formRender, action, outcome) .then(function(payloadToUpdate) { try { callback(payloadToUpdate, action); } catch (err) { if (action === 'save') { self.ajaxErrorHandler(null, self.bundle.pcs.startform.form_save_error); } else { self.ajaxErrorHandler(null, self.bundle.pcs.startform.form_submit_error); } // remove overlays for loading $('#pcs-startform-overlay').removeClass('pcs-common-load-overlay'); } }, function(error) { showValidationError(error); }); }; // method which does the post call to save or submit the webform self._submitWebForm = function(action) { self._saveOrSubmitWebForm(action, 'SUBMIT'); }; // method which does the post call to save or submit the webform in DP self._submitDPForm = function(action) { var formMetadataURL = self.startformData.dpForm.formMetadataURL; if (!formMetadataURL) { self._createDPInstance(); return; } self._saveOrSubmitWebFormCommon(action, self._createDPInstance); }; //method to create dp insance self._createDPInstance = function(payloadToUpdate) { var dataObjectName = self.startformData.dpForm.inputParam; var payload = {}; if (payloadToUpdate && dataObjectName) { payload[dataObjectName] = JSON.parse(payloadToUpdate); } payload = JSON.stringify(payload); var processDefId = self.startformData.processDefId; services.createDPInstance({ '{processDefinitionId}': processDefId }, payload).done(function(data) { //call the success handler self._createInstanceSuccess ('submit',data); }).fail( function(jqXHR) { //call the error handler self._createInstanceError ('submit',jqXHR); } ); }; // method which does the post call to save or submit the frevvo form self._saveOrSubmitFrevvoForm = function(action) { //Start the loading indicator $('#pcs-startform-overlay', self.rootElement).addClass('pcs-common-load-overlay'); // First try to get the form payload services.getFormPayload(self.startformData.processDefId, self.startformData.serviceName, self.startformData.operation, self.formInstanceURL).done( function(data) { //using the payload perform the action self._createProcessInstance(data, action); } ).fail( function(jqXHR) { var customMsg; if (action === 'save') { customMsg = self.bundle.pcs.startform.form_save_error; } else { customMsg = self.bundle.pcs.startform.form_submit_error; } self.ajaxErrorHandler(jqXHR, customMsg); // remove overlays for loading $('#pcs-startform-overlay').removeClass('pcs-common-load-overlay'); } ); }; // method which crete the pOST payload and perfor the POST call self._createProcessInstance = function(formPayload, action) { // Remove the /n from the form payload as save doent work without it formPayload = formPayload.replace(/\n\s*/g, ''); // To be removed once fix from REST is in: Workaround for the current mismatch in payload and wat REST expects //if(self.data.startformData.startType !== 'START_PCS_FORM') { // var indexOf = formPayload.indexOf('>'); // formPayload = formPayload.substring(indexOf + 1); // var lastIndexOf = formPayload.lastIndexOf('<'); // formPayload = formPayload.substring(0, lastIndexOf); // formPayload = '<payload>' + formPayload + '</payload>'; //} var payload = { 'action': action, 'operation': self.startformData.operation, 'payload': formPayload, 'processDefId': self.startformData.processDefId, 'serviceName': self.startformData.serviceName }; // ---- Create boundary part data ------ var boundary = 'Boundary_' + '123456789_123456789'; var header = '--' + boundary + '\r\n'; var footer = '\r\n--' + boundary + '--\r\n'; var contentType = 'multipart/mixed; boundary=' + boundary; // Put the payload to the multipart data var contents = header; contents += 'Content-Type: application/json\r\n'; contents += 'Content-Disposition: form-data; name=\'json\'\r\n'; contents += 'Content-Length: ' + JSON.stringify(payload).length + '\r\n\r\n'; //contents += JSON.stringify(payload) + '\r\n'; // TODO: following fix is done to 'protect the multi byte UTF-8 chars in the future when they // undergo .charCodeAt() api. // Fix for - Embedded PCS Start Form UI fails with multi-byte characters contents += window.unescape(encodeURIComponent(JSON.stringify(payload))) + '\r\n'; if (!self.data.hideAttachment) { // Put the attachments to the multipart data var attachments = self.attachmentPlugin.attachments('getAttachments'); //var widget = $('#pcs-startform-attachment',self.rootElement).data('pcs-attachments'); //var attachments = widget.getAttachments(); for (var i = 0, len = attachments.length; i < len; i++) { var attachment = attachments[i]; contents += header; contents += 'Content-Type: ' + attachment.contentType + '\r\n'; contents += 'Content-Transfer-Encoding: binary\r\n'; /*jshint validthis:true */ contents += 'Content-Disposition: form-data; filename="' + encodeURI(attachment.filename) + '"; name="' + encodeURI(attachment.filename) + '"\r\n'; contents += 'Content-Length: ' + attachment.content.length + '\r\n'; contents += 'Content-Transfer-Encoding: binary\r\n\r\n'; contents += attachment.content; if (i !== attachments.length - 1) { contents += '\r\n'; } } } // close the boundary contents += footer; services.createProcessInstance(contents, contentType).done( function(data) { self._createInstanceSuccess (action,data); } ).fail( function(jqXHR) { self._createInstanceError (action,jqXHR); } ); }; /** * method called on sucess of create Instance */ self._createInstanceSuccess = function (action,data){ // remove overlays for loading $('#pcs-startform-overlay').removeClass('pcs-common-load-overlay'); //Trigger the event self.rootElement.trigger('startform:' + action, [self.startformData, data]); var msg = ''; if (action === 'save') { msg = self.bundle.pcs.startform.action_save; } else { msg = self.bundle.pcs.startform.action_submit; msg = oj.Translations.applyParameters(msg, { '0': data.title }); } self.cleanUpFormContainer(); //Load the form again if ((action === 'save' && self.data.reloadOnSave) || (action === 'submit' && self.data.reloadOnSubmit)) { //Show local Message $('#pcs-startform-success-msg', self.rootElement).text(msg).show(1000).delay(2000).fadeOut(); initStartForm(); } else { $('#pcs-startform-mainContainer', self.rootElement).hide(); $('#pcs-startform-mainContainer-submitted', self.rootElement).show(); $('#pcs-startform-success-msg-submitted', self.rootElement).text(msg); } }; /** * method called on failur of create Instance */ self._createInstanceError = function (action,jqXHR){ var customMsg; if (action === 'save') { customMsg = self.bundle.pcs.startform.form_save_error; } else { customMsg = self.bundle.pcs.startform.form_submit_error; } self.ajaxErrorHandler(jqXHR, customMsg); // remove overlays for loading $('#pcs-startform-overlay').removeClass('pcs-common-load-overlay'); }; // Method called when yest button clicked on the discard dialog self.yesDiscardDialog = function() { $('.pcs-startform-discard-dialog').ojDialog('close'); self.rootElement.trigger('startform:discard', [self.startformData]); self.cleanUpFormContainer(); if (!self.data.consumed){ //Load the form again initStartForm(); } }; // Method called when yest button clicked on the discard dialog self.noDiscardDialog = function() { $('.pcs-startform-discard-dialog').ojDialog('close'); }; // Method called when closed button clicked on the Error dialog self.closeErrorDialog = function() { $('.pcs-startform-error-dialog').ojDialog('close'); }; /* Method to receive postMessage , for submitting form or setting page height */ self.receivePostMessage = function(event) { if (event.origin !== pcsUtil.getServerURL()) { return; } var key = event.message ? 'message' : 'data'; var data = event[key]; //If its a form submit success, submit the form if (data === 'formValidation:success') { //loggerUtil.log('trying to save') if (self.waitForMessage) { self.waitForMessage = false; self._saveOrSubmitFrevvoForm('submit'); } } //If its a form submit error, Show error message if (data.startsWith('formValidation:error')) { if (self.waitForMessage) { self.waitForMessage = false; var errorMsg = self.bundle.pcs.startform.form_validation_error; var msg = data.substring('formValidation:error'.length + 1); errorMsg = errorMsg + '\r\n\r\n' + msg; //Show local Message $('#pcs-startform-error-msg', self.rootElement).text(errorMsg); $('#pcs-startform-error-msg-container', self.rootElement).show().delay(5000).fadeOut(2000); //Hide overlay $('#pcs-startform-overlay').removeClass('pcs-common-load-overlay'); } } // if its the form height , change iframe height if (data.startsWith('formHeight')) { var formHeight = data.substring('formHeight'.length + 1); var height; try { height = parseInt(formHeight) + 20; } catch (err) { height = 400; } // Check if the user specified form Height is more than actual form height if (self.data.formHeight && self.data.formHeight !== '') { try { var userHeight = parseInt(self.data.formHeight, 10); if (userHeight > height) { height = userHeight; } } catch (err) { height = height; } } $('#pcs-startform-iframe', self.rootElement).css('height', height); } // loggerUtil.log( ' ;recieved Message from frame-' +data); }; //Method to attach to Iframe load event to hide the loading indicator self.attachEvents = (function() { $('#pcs-startform-iframe', self.rootElement).on('load', function() { $('#pcs-startform-loading', self.rootElement).hide(); if (self.data.formHeight && self.data.formHeight !== '') { $('#pcs-startform-iframe', self.rootElement).css('height', self.data.formHeight); } }); }()); /** * method to clean all eevnts associsated */ self.cleanEvents = function() { // Remove the PostMessage handler pcsUtil.eventHandler.removeHandler(window, 'message', self.receivePostMessage); $('#pcs-startform-attachment', self.rootElement).off(); $(self.rootElement).off(); }; /** * method to clean up everything */ self.dispose = function() { loggerUtil.log('dispose in startform Containor'); // clean up the events self.cleanEvents(); self.cleanUpFormContainer(); }; /** * method to add evebnts */ self.addEvents = (function() { // Add the PostMessage handler pcsUtil.eventHandler.addHandler(window, 'message', self.receivePostMessage); }()); // Method to read widget options and do required UI tweaking self.readOptions = (function() { if (self.data.hideDiscard) { $('#pcs-startform-discard', self.rootElement).hide(); } if (self.data.hideSave) { $('#pcs-startform-save', self.rootElement).hide(); } if (self.data.hideSubmit) { $('#pcs-startform-submit', self.rootElement).hide(); } if (self.data.hideAttachment) { $('#pcs-startform-attachment-area', self.rootElement).hide(); } if (self.data.formHeight && self.data.formHeight !== '') { $('#pcs-startform-form-frame', self.rootElement).css('height', self.data.formHeight); } }()); //Load the form initStartForm(); } return StartformContainer; });
$(function(){ $(".bg-slogo>div").click(function(){ $(".leftimg").addClass("pc-img"); $(".weichat-login").addClass("pc-login"); $(".chform").hide(); $(".change").show(); }) })
/* global PassThroughNode, extend */ var Looper = function(audiolet) { "use strict"; PassThroughNode.call(this, audiolet, 1, 1); this.linkNumberOfOutputChannels(0, 0); this.time = 0; this.seconds = 0; this.beatLength = 0; this.lastBeatTime = 0; this.callback = false; }; extend(Looper, PassThroughNode); Looper.prototype.play = function(callback) { "use strict"; this.callback = callback; }; Looper.prototype.stop = function() { "use strict"; this.callback = false; }; Looper.prototype.tick = function() { "use strict"; PassThroughNode.prototype.tick.call(this); this.time += 1; this.seconds = this.time / this.audiolet.device.sampleRate; if (this.time >= this.lastBeatTime + this.beatLength) { if (this.callback) { this.callback(); } this.lastBeatTime += this.beatLength; } }; Looper.prototype.toString = function() { "use strict"; return 'Looper'; };
function wait(ms) { var d = new Date(); var d2 = null; do { d2 = new Date(); } while (d2 - d < ms); } function tweenQuadOut(t, b, c, d) { //QUADRATIC EASE OUT t = t / d; value = -1 * c * t * (t - 2) + b; return value; } function tweenLinear(t, b, c, d) { //LINEAR EASE value = c * t / d + b; return value; } function easeInOutCubic(t, b, c, d) { // cubic easing in/out - acceleration until halfway, then deceleration t /= d / 2; if (t < 1) return c / 2 * t * t * t + b; t -= 2; return c / 2 * (t * t * t + 2) + b; } function easeInQuad(t, b, c, d) { // quadratic easing in - accelerating from zero velocity t /= d; return c * t * t + b; } function easeOutQuad(t, b, c, d) { // quadratic easing out - decelerating to zero velocity t /= d; return -c * t * (t - 2) + b; } function easeInOutQuad(t, b, c, d) { // quadratic easing in/out - acceleration until halfway, then deceleration t /= d / 2; if (t < 1) return c / 2 * t * t + b; t--; return -c / 2 * (t * (t - 2) - 1) + b; } function easeInQuart(t, b, c, d) { // quartic easing in - accelerating from zero velocity t /= d; return c * t * t * t * t + b; } function easeOutQuart(t, b, c, d) { // quartic easing out - decelerating to zero velocity t /= d; t--; return -c * (t * t * t * t - 1) + b; } function easeInOutQuart(t, b, c, d) { // quartic easing in/out - acceleration until halfway, then deceleration t /= d / 2; if (t < 1) return c / 2 * t * t * t * t + b; t -= 2; return -c / 2 * (t * t * t * t - 2) + b; } function easeInCubic(t, b, c, d) { // cubic easing in - accelerating from zero velocity t /= d; return c * t * t * t + b; } function easeOutCubic(t, b, c, d) { // cubic easing out - decelerating to zero velocity t /= d; t--; return c * (t * t * t + 1) + b; } function tweenCubicInOut(t, b, c, d) { //QUARTIC EASE IN/OUT - accel halfway, decel other half t = t / (d / 2); if (t < 1) { value = c / 2 * t * t * t * t + b; } else { t = t - 2; value = -c / 2 * (t * t * t * t - 2) + b; } return value; } function easeInOutQuad(t, b, c, d) { // quadratic easing in/out - acceleration until halfway, then deceleration t /= d / 2; if (t < 1) return c / 2 * t * t + b; t--; return -c / 2 * (t * (t - 2) - 1) + b; } function calcRect(rectArray) { var rect = { rect : rectArray.join(", "), topLeft : { x : rectArray[0], y : rectArray[1], }, bottomRight : { x : rectArray[2], y : rectArray[3], }, }; rect.width = Math.abs(rect.bottomRight.x - rect.topLeft.x); rect.height = Math.abs(rect.bottomRight.y - rect.topLeft.y); rect.center = [ rect.topLeft.x + (rect.width / 2), rect.topLeft.y - (rect.height / 2) ]; rect.aspectRatio = rect.width / rect.height; return rect; } function calcViewRect(rectArray, zoom) { var rect = { rect: rectArray.join(", "), topLeft: { x: rectArray[0], y: rectArray[1], }, bottomRight: { x: rectArray[2], y: rectArray[3], }, }; rect.width = Math.abs(rect.bottomRight.x - rect.topLeft.x); rect.height = Math.abs(rect.bottomRight.y - rect.topLeft.y); rect.zoom = zoom || 1; rect.actualWidth = rect.width * zoom; rect.actualHeight = rect.height * zoom; rect.aspectRatio = rect.width / rect.height; return rect; } function getSelectionBounds(selection) { var rect = { topLeft: { x: null, y: null, }, bottomRight: { x: null, y: null, }, }; var goToRect = calcRect(selection.goToRect); if (rect.topLeft.x == null) { rect.topLeft.x = goToRect.topLeft.x; } else { if (goToRect.topLeft.x < rect.topLeft.x) { rect.topLeft.x = goToRect.topLeft.x; } } if (rect.topLeft.y == null) { rect.topLeft.y = goToRect.topLeft.y; } else { if (goToRect.topLeft.y > rect.topLeft.y) { rect.topLeft.y = goToRect.topLeft.y; } } if (rect.bottomRight.x == null) { rect.bottomRight.x = goToRect.bottomRight.x; } else { if (goToRect.bottomRight.x > rect.bottomRight.x) { rect.bottomRight.x = goToRect.bottomRight.x; } } if (rect.bottomRight.y == null) { rect.bottomRight.y = goToRect.bottomRight.y; } else { if (goToRect.bottomRight.y < rect.bottomRight.y) { rect.bottomRight.y = goToRect.bottomRight.y; } } rect.rect = [rect.topLeft.x, rect.topLeft.y, rect.bottomRight.x, rect.bottomRight.y]; return rect; } function getDocumentBounds(artboards) { var rect = { topLeft: { x: null, y: null, }, bottomRight: { x: null, y: null, }, }; for (var i = 0; i < artboards.length; i++) { var artboardRect = calcRect(artboards[i].artboardRect); if (rect.topLeft.x == null) { rect.topLeft.x = artboardRect.topLeft.x; } else { if (artboardRect.topLeft.x < rect.topLeft.x) { rect.topLeft.x = artboardRect.topLeft.x; } } if (rect.topLeft.y == null) { rect.topLeft.y = artboardRect.topLeft.y; } else { if (artboardRect.topLeft.y > rect.topLeft.y) { rect.topLeft.y = artboardRect.topLeft.y; } } if (rect.bottomRight.x == null) { rect.bottomRight.x = artboardRect.bottomRight.x; } else { if (artboardRect.bottomRight.x > rect.bottomRight.x) { rect.bottomRight.x = artboardRect.bottomRight.x; } } if (rect.bottomRight.y == null) { rect.bottomRight.y = artboardRect.bottomRight.y; } else { if (artboardRect.bottomRight.y < rect.bottomRight.y) { rect.bottomRight.y = artboardRect.bottomRight.y; } } } rect.rect = [rect.topLeft.x, rect.topLeft.y, rect.bottomRight.x, rect.bottomRight.y]; return rect; } function calcZoom(viewRect, goToRect, margin) { if (goToRect.aspectRatio > viewRect.aspectRatio) { return parseFloat((viewRect.actualWidth - (2 * margin)) / goToRect.width);//.toFixed(5) } else { return parseFloat((viewRect.actualHeight - (2 * margin)) / goToRect.height);//.toFixed(5) } } function fitSel(document) { var goToRect; if (activeDocument.selection.length > 0) { mySelection = activeDocument.selection; //if object is a (collection of) object(s) not a text field. if (mySelection instanceof Array) { //initialize vars initBounds = mySelection[0].visibleBounds; ul_x = initBounds[0]; ul_y = initBounds[1]; lr_x = initBounds[2]; lr_y = initBounds[3]; //check rest of group if any for (i = 1; i < mySelection.length; i++) { groupBounds = mySelection[i].visibleBounds; if (groupBounds[0] < ul_x) { ul_x = groupBounds[0];} if (groupBounds[1] > ul_y) { ul_y = groupBounds[1];} if (groupBounds[2] > lr_x) { lr_x = groupBounds[2];} if (groupBounds[3] < lr_y) { lr_y = groupBounds[3];} } goToRect = calcRect([ul_x, ul_y, lr_x, lr_y]); } } else { // Extents of Artboards // var goToRect = calcRect(getDocumentBounds(document.artboards).rect); //Extents of EVERYTHING // var goToRect = calcRect(app.activeDocument.geometricBounds); goToRect = calcRect(app.activeDocument.geometricBounds); } var view = document.views[0]; var viewRect = calcViewRect(view.bounds, view.zoom); var startzoom = app.activeDocument.views[0].zoom*0.666666; if (activeDocument.selection.length > 0) { targetZoom = calcZoom(viewRect, goToRect, 500);} else { targetZoom = 0.1; } var startpoint = activeDocument.views[0].centerPoint; var endpoint = goToRect.center; amountofsteps = 100; Xdelta = endpoint[0] - startpoint[0]; Ydelta = endpoint[1] - startpoint[1]; zoomDelta = targetZoom - startzoom; // alert(zoomDelta); for (i = 1; i <= amountofsteps; i++) { // Time - Value - Delta - Duration centerX = easeInOutQuad(i, startpoint[0], Xdelta, amountofsteps); centerY = easeInOutQuad(i, startpoint[1], Ydelta, amountofsteps); activeDocument.views[0].centerPoint = [centerX, centerY]; view.centerPoint = [centerX, centerY]; if (zoomDelta > 0) { zoomie = easeInQuart(i, startzoom, zoomDelta, amountofsteps); //easeInCubic } else { zoomie = easeOutQuart(i, startzoom, zoomDelta, amountofsteps); //easeOutQuart } view.zoom = zoomie; // wait(5); } } app.executeMenuCommand('preview'); fitSel(app.activeDocument); app.executeMenuCommand('preview');
console.log("I have crippiling zestpression"); M.AutoInit(); var userDrinkForm = $("#alchiSearch"); var userFoodForm = $("#foodSearch"); var userFoodInput = $("#userFoodInput"); var userDrinkInput = $("#userDrinkInput"); var zestME = $("#zestME"); var foodFave = JSON.parse(localStorage.getItem("foodFave")) || []; var drinkFave = JSON.parse(localStorage.getItem("drinkFave")) || []; console.log(foodFave); console.log(drinkFave); var drinkIngredientarr = []; var drinkMeasurementsarr = []; var ingrediantsarr = []; var measurementsarr = []; function zestmeBTNDrink() { var queryURLRandoDrink = "https://www.thecocktaildb.com/api/json/v1/1/random.php"; $.ajax({ url: queryURLRandoDrink, method: "GET", }).then(function (randoDrinkSearch) { for (randoIngredient in randoDrinkSearch.drinks[0]) { if (randoIngredient.indexOf("strIngredient") !== -1) { ingrediantsarr.push(randoDrinkSearch.drinks[0][randoIngredient]); } } // for loop to cycle through arrar and append li's onto ul for (let i = 0; i < ingrediantsarr.length; i++) { var li = $("<li>"); if (ingrediantsarr[i] !== "") { li.text(ingrediantsarr[i]); $("#ingrediantsDrink").append(li); } } console.log(randoDrinkSearch); // pulls recipe and attaches to the page $("#drinkRecipe").text( "How to make: " + randoDrinkSearch.drinks[0].strInstructions ); // adds drink name to container $("#drinkTitle").text(randoDrinkSearch.drinks[0].strDrink); // empties the arr for a clean new search with no past food ingrediantsarr = []; // for inloop to pull out the strMeasurements and put them on an li and append to ul for (randoMeasurements in randoDrinkSearch.drinks[0]) { if (randoMeasurements.indexOf("strMeasure") !== -1) { measurementsarr.push(randoDrinkSearch.drinks[0][randoMeasurements]); } } // foor loop to cycle through arrar and append li's onto ul for (let i = 0; i < measurementsarr.length; i++) { if (measurementsarr[i] !== "") { var liMeasure = $("<li>"); liMeasure.text(measurementsarr[i]); $("#measurementsDrink").append(liMeasure); } } // empties the arr for a clean new search with no past measurements measurementsarr = []; // grabs image and adds it to html var img = $("#imageDrink"); img.attr("src", randoDrinkSearch.drinks[0].strDrinkThumb); }); } // this function grabs a random food also used to preload a search result onto page function zestmeBTNFood() { var queryURLRando = "https://www.themealdb.com/api/json/v1/1/random.php"; $.ajax({ url: queryURLRando, method: "GET", }).then(function (randoFoodSearch) { console.log(randoFoodSearch); // for inloop to pull out the strIngredients and put them on an li and append to ul for (randoIngredient in randoFoodSearch.meals[0]) { if (randoIngredient.indexOf("strIngredient") !== -1) { ingrediantsarr.push(randoFoodSearch.meals[0][randoIngredient]); } } // for loop to cycle through arrar and append li's onto ul for (let i = 0; i < ingrediantsarr.length; i++) { var li = $("<li>"); if (ingrediantsarr[i] !== "") { li.text(ingrediantsarr[i]); $("#ingrediantsList").append(li); } } // adds food name to container $("#foodTitle").text(randoFoodSearch.meals[0].strMeal); // pulls recipe and attaches to the page $("#recipe").text( "How to make: " + randoFoodSearch.meals[0].strInstructions ); // empties the arr for a clean new search with no past food ingrediantsarr = []; // for inloop to pull out the strMeasurements and put them on an li and append to ul for (randoMeasurements in randoFoodSearch.meals[0]) { if (randoMeasurements.indexOf("strMeasure") !== -1) { measurementsarr.push(randoFoodSearch.meals[0][randoMeasurements]); } } // foor loop to cycle through arrar and append li's onto ul for (let i = 0; i < measurementsarr.length; i++) { if (measurementsarr[i] !== "") { var liMeasure = $("<li>"); liMeasure.text(measurementsarr[i]); $("#measurementsList").append(liMeasure); } } // empties the arr for a clean new search with no past measurements measurementsarr = []; // grabs image and adds it to html var img = $("#imageFood"); img.attr("src", randoFoodSearch.meals[0].strMealThumb); }); } // this function grabs the food via the searched term function getFood() { var queryURLFood = "https://www.themealdb.com/api/json/v1/1/search.php?s=" + userFoodInput.val(); $.ajax({ url: queryURLFood, method: "GET", }).then(function (foodSearchResults) { console.log(foodSearchResults); // for inloop to pull out the strIngredients and put them on an li and append to ul for (Ingredient in foodSearchResults.meals[0]) { if (Ingredient.indexOf("strIngredient") !== -1) { ingrediantsarr.push(foodSearchResults.meals[0][Ingredient]); } } // for loop to cycle through arrar and append li's onto ul for (let i = 0; i < ingrediantsarr.length; i++) { var li = $("<li>"); if (ingrediantsarr[i] !== "") { li.text(ingrediantsarr[i]); $("#ingrediantsList").append(li); } } // adds food name to container $("#foodTitle").text(foodSearchResults.meals[0].strMeal); // pulls recipe and attaches to the page $("#recipe").text( "How to make: " + foodSearchResults.meals[0].strInstructions ); // empties the arr for a clean new search with no past food ingrediantsarr = []; // for inloop to pull out the strMeasurements and put them on an li and append to ul for (Measurements in foodSearchResults.meals[0]) { if (Measurements.indexOf("strMeasure") !== -1) { measurementsarr.push(foodSearchResults.meals[0][Measurements]); } } // foor loop to cycle through arrar and append li's onto ul for (let i = 0; i < measurementsarr.length; i++) { if (measurementsarr[i] !== "") { var liMeasure = $("<li>"); liMeasure.text(measurementsarr[i]); $("#measurementsList").append(liMeasure); } } // empties the arr for a clean new search with no past measurements measurementsarr = []; // grabs image and adds it to html var img = $("#imageFood"); img.attr("src", foodSearchResults.meals[0].strMealThumb); }); } // this function grabs the drink via the searched term function getalcohol() { var queryURLDrinks = "https://www.thecocktaildb.com/api/json/v1/1/search.php?s=" + userDrinkInput.val(); $.ajax({ url: queryURLDrinks, method: "GET", }).then(function (drinkSearchResults) { console.log(drinkSearchResults); // for inloop to pull out the strIngredients and put them on an li and append to ul for (drink in drinkSearchResults.drinks[0]) { if (drink.indexOf("strIngredient") !== -1) { drinkIngredientarr.push(drinkSearchResults.drinks[0][drink]); } } // foor loop to cycle through arrar and append li's onto ul for (let i = 0; i < drinkIngredientarr.length; i++) { if (drinkIngredientarr[i] !== null) { var li = $("<li>"); li.text(drinkIngredientarr[i]); $("#ingrediantsDrink").append(li); } } // adds drink name to container $("#drinkTitle").text(drinkSearchResults.drinks[0].strDrink); // empties the arr for a clean new search with no past ingredients drinkIngredientarr = []; // grabs image and adds it to html var img = $("#imageDrink"); img.attr("src", drinkSearchResults.drinks[0].strDrinkThumb); for (drinkMeasures in drinkSearchResults.drinks[0]) { if (drinkMeasures.indexOf("strMeasure") !== -1) { drinkMeasurementsarr.push(drinkSearchResults.drinks[0][drinkMeasures]); } } // foor loop to cycle through arrar and append li's onto ul for (let i = 0; i < drinkMeasurementsarr.length; i++) { if (drinkMeasurementsarr[i] !== null) { var liMeasures = $("<li>"); liMeasures.text(drinkMeasurementsarr[i]); $("#measurementsDrink").append(liMeasures); } } // empties the arr for a clean new search with no past measurements drinkMeasurementsarr = []; // adds drink recipe var drinkRecipe = drinkSearchResults.drinks[0].strInstructions; $("#drinkRecipe").text("How to make: " + drinkRecipe); }); } // creates cards for zestipies page function createcards() { for (let i = 0; i < foodFave.length; i++) { var loop = foodFave[i]; var card = $("<card>"); var cardimg = $("<img>"); var header = $("<h5>"); cardimg.attr("height", "200px"); cardimg.attr("width", "200px"); header.text(loop.title); cardimg.attr("src", loop.img); card.prepend(cardimg); card.append(header); $("#food").append(card); } } function createcardsdrink() { for (let i = 0; i < drinkFave.length; i++) { var drinkloop = drinkFave[i]; var cardDrink = $("<card>"); var cardimgDrink = $("<img>"); var headerDrink = $("<h5>"); cardimgDrink.attr("height", "200px"); cardimgDrink.attr("width", "200px"); headerDrink.text(drinkloop.drink); cardimgDrink.attr("src", drinkloop.drinkimg); cardDrink.prepend(cardimgDrink); cardDrink.append(headerDrink); $("#drink").append(cardDrink); } } // this takes the users search term and triggers the search on a submit (food) userFoodForm.on("submit", function (event) { event.preventDefault(); $("#measurementsList").empty(); $("#ingrediantsList").empty(); getFood(); }); // this takes the users search term and triggers the search on a submit (drink) userDrinkForm.on("submit", function (event) { event.preventDefault(); $("#ingrediantsDrink").empty(); $("#measurementsDrink").empty(); getalcohol(); }); // runs random on zest me click zestME.on("click", function () { preventDefault(); $("#measurementsList").empty(); $("#ingrediantsList").empty(); $("#ingrediantsDrink").empty(); $("#measurementsDrink").empty(); zestmeBTNFood(); zestmeBTNDrink(); }); // allows for recipes to appear on page load zestmeBTNFood(); zestmeBTNDrink(); // allows to save to local storage when clicked $(document).on("click", "#likeButtonFood", function () { var cardObj = { title: $("#foodTitle").text(), img: $("#imageFood").attr("src"), }; foodFave.push(cardObj); console.log(foodFave); localStorage.setItem("foodFave", JSON.stringify(foodFave)); }); // allows to save to local storage when clicked $(document).on("click", "#likeButtonDrink", function () { console.log("I HATH BEEN CLICKED"); var cardDrinkObj = { drink: $("#drinkTitle").text(), drinkimg: $("#imageDrink").attr("src"), }; drinkFave.push(cardDrinkObj); localStorage.setItem("drinkFave", JSON.stringify(drinkFave)); }); createcards(); createcardsdrink();
import { h, app } from "hyperapp" /** @jsx h */ const toWords = number => { const wordIndex = { 0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine', 10: 'ten', 11: 'eleven', 12: 'twelve', 13: 'thirteen', 14: 'fourteen', 15: 'fifteen', 16: 'sixteen', 17: 'seventeen', 18: 'eighteen', 19: 'nineteen', 20: 'twenty', 30: 'thirty', 40: 'fourty', 50: 'fifty', 60: 'sixty' } if (number > 19) { const ones = number % 10 const tens = Math.floor(number / 10) const oneWord = ones === 0 ? '' : wordIndex[ones] const tenWord = wordIndex[tens * 10] return `${tenWord} ${oneWord}` } else { return wordIndex[number] } } const state = { remaining: 25, focus: 25, rest: 5, mode: 'focus', timer: null } const actions = { plusFocus: () => state => ({focus: state.focus + 1}), minusFocus: () => state => ({focus: state.focus === 1 ? 1 : state.focus - 1}), plusRest: () => state => ({rest: state.rest + 1}), minusRest: () => state => ({rest: state.rest === 1 ? 1 : state.rest - 1}), decrement: () => state => ({remaining: state.remaining - 1}), startFocus: () => (state, actions) => { const timer = new Timer({ tick: 60, ontick: () => actions.decrement(), onend: () => actions.startBreak() }) timer.start(60*state.focus) return {timer, remaining: state.focus, mode: 'focus'} }, startBreak: () => (state, actions) => { const timer = new Timer({ tick: 60, ontick: () => actions.decrement(), onend: () => actions.startFocus() }) timer.start(60*state.rest) return {timer, remaining: state.focus, mode: 'break'} }, reset: () => (state, actions) => { if (state.timer) { state.timer.stop() } return {timer: null, remaining: 25, focus: 25, rest: 5, mode: 'focus'} } } const view = (state, actions) => ( <div class="container"> <div class="display"> <h2 class="display__time display--text">{toWords(state.remaining)}</h2> <h3 class="display__details display--text">MINUTES LEFT ({state.mode})</h3> </div> <div class="options"> <div class="options__box"> <h3 class="options__option focus">{toWords(state.focus)}</h3> <h4 class="options__description"><span onclick={actions.plusFocus}>plus</span> | <span onclick={actions.minusFocus}>minus</span> | <span onclick={actions.startFocus}>start</span> | <span onclick={actions.reset}>reset</span></h4> <h4 class="options__description">FOCUS</h4> </div> <div class="options__box"> <h3 class="options__option rest">{toWords(state.rest)}</h3> <h4 class="options__description"><span onclick={actions.plusRest}>plus</span> | <span onclick={actions.minusRest}>minus</span> | <span onclick={actions.startBreak}>start</span> | <span onclick={actions.reset}>reset</span></h4> <h4 class="options__description">BREAK</h4> </div> </div> </div> ) const main = app(state, actions, view, document.body)
import React from 'react'; import { useTranslation } from 'react-i18next'; const App1 = () => { const {t} = useTranslation(); return ( <div> {t('Hi', {firstName:'sumit', lastName:'kumar'})} </div> ); } export default App1;
export const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; export const daysNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; export const renderMinutes = minutes => { if (/^\d$/.test(minutes)) return '0' + minutes; return minutes === 0 ? '00' : minutes; }
// Naming // node - HTML Node // component - class, function or object which can be used to create HTML node(s) // componentObject - what a class or function component renders, is used to create the HTML node var framework = (() => { const nodes = {}; const definedComponentProps = new Set(['type', 'text', 'children', 'frameworkId', 'id', 'onClick', 'name', 'style', 'className', 'src']); let devMode function sync(node, component) { deleteRecordOfComponentsBeingReplaced(component); const newHtmlNode = makeNode({ component, parentNode: node }); node.replaceWith(newHtmlNode); if (devMode) { console.log('total number of nodes:', Object.keys(nodes).length); console.log('nodes:', nodes); } } function deleteRecordOfComponentsBeingReplaced(component) { const thisId = component.frameworkId; if (!thisId) return; // if this is null we've never rendered this const children = nodes[thisId]?.children; if (children) children.forEach(deleteRecordOfComponentsBeingReplaced) delete nodes[thisId]; } function render(idSelector, component, devModeData = true) { // used for the initial render, all future updates call sync // essentially a replacement for reactDOM.render devMode = devModeData const node = document.getElementById(idSelector); sync(node, component); } function handleEvent({ component, fn, e }) { if (!(fn instanceof Function)) throw new Error('handleEvent passed non-function parameter') fn(e); findEventRootToSync({ component }); } function findEventRootToSync({ component }) { const nodeToUpdate = nodes[component.frameworkId].node; const parentComponent = nodes[component.frameworkId].parentComponent; if (component.isEventRoot || !parentComponent) { sync(nodeToUpdate, component); } else { findEventRootToSync({ component: parentComponent }); } } function makeNode({ component, parentComponent }) { const frameworkId = uuidv4(); component.frameworkId = frameworkId; const componentObject = convertComponentToObject(component); if (devMode) ensureNoExtraneousProperties(componentObject, component); const { type = 'div', text, onClick, children, id, value, onKeyUp, name, style, className, src } = componentObject const node = document.createElement(type); if (text !== undefined) { node.innerText = text; } if (id) { node.id = id; } if (value) { node.value = value; } if (name) { node.dataset.name = name; } if (style) { Object.entries(style).forEach(([styleName, styleValue]) => node.style[styleName] = styleValue); } if (className) { node.className = className; } if (src) { node.src = src; } if (onClick) { node.addEventListener('click', (e) => handleEvent({ e, component, fn: onClick })); } if (onKeyUp) { node.addEventListener('keyup', (e) => handleEvent({ e, component, fn: onKeyUp })); } if (children) { children.forEach(child => node.appendChild(makeNode({ component: child, parentComponent: component }))); } nodes[frameworkId] = { component, node, children, parentComponent }; return node } function convertComponentToObject(component) { if (!component) throw new Error('Component is not defined!') if (Array.isArray(component)) { throw new Error('Arrays not implemented yet - need to figure out how to perform replace efficiently') } else if (component.render) { return component.render() } else if (component instanceof Function) { return component(); } else { return component; } } function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } function ensureNoExtraneousProperties(componentObject, component) { const extraProperties = Object.keys(componentObject).filter( prop => !definedComponentProps.has(prop) ); if (extraProperties.length) { console.error('extra properties:', extraProperties, 'detected on component', component.name ? component.name : component); } } return render; })();
// Keep all classes in one file to increase page speed by optimizing http requests class ExcerciseContent { constructor(id = 0, content = "", answers = [], correct = "", type = 1) { this.id = id; this.content = content; this.answers = answers; this.correct = correct; this.type = type; } fromJson(json) { this.id = json["id"]; this.content = json["content"]; this.answers = json["answers"]; this.correct = json["correct"]; this.more_text = json["more_text"]; this.type = json["type"]; this.explanationContent = json["explanation"] === null ? null : json["explanation"]["content"]; } _getCheckedClass(checkedInThisExcercise, correct, submitted, answer) { if (checkedInThisExcercise !== null) { if (submitted) { if (checkedInThisExcercise == answer.index) { return answer.index == correct ? "selected" : "wrong"; } else { return answer.index == correct ? "selected" : ""; } } else { return checkedInThisExcercise == answer.index ? "selected" : ""; } } else { return submitted && answer.index == correct ? "selected" : ""; } } getContent(answers, questionId) { let checkedInThisExcercise = answers.getAnswer( parseInt(questionId), this.id ); let html = `<div class="answer">`; html += `<h1>${this.content}</h1>`; if (this.more_text !== null) { html += `<p>${this.more_text}</p>`; } switch (this.type) { case 1: case 2: case 4: html += "<ul>"; html += "<li>"; this.answers.forEach((ans) => { html += `<div id="${this.id}-${ans.index }" class="answer-circle ${this._getCheckedClass( checkedInThisExcercise, answers.getCorrectAnswer(questionId, this.id), answers.isQuestionSubmitted(questionId), ans )}">${ans.index}</div>`; }); html += "</li>"; html += "</ul>"; break; case 3: html += "<ul>"; this.answers.forEach((ans) => { html += "<li>"; html += `<div id="${this.id}-${ans.index }" class="answer-circle ${this._getCheckedClass( checkedInThisExcercise, answers.getCorrectAnswer(questionId, this.id), answers.isQuestionSubmitted(questionId), ans )}">${ans.index}</div> ${ans.content}`; html += "<li>"; }); html += "</ul>"; break; default: break; } html += "</div>"; if (answers.isQuestionSubmitted(questionId) && this.explanationContent !== null) { html += `<div class="explanation">`; html += `<h3>Wyjaśnienie</h3>`; html += `<p>${this.explanationContent.replace(/\n/g, "<br>")}</p>`; html += "</div>"; } return html; } } class Excercise { constructor( header = "", content = "", footer = "", more_text = "", audio = "", img = "" ) { this.header = header; this.content = content; this.footer = footer; this.more_text = more_text; this.audio = audio; this.img = img; this.excercise_contents = []; } fromJson(json) { this.header = json["header"]; this.content = json["content"]; this.footer = json["footer"]; this.more_text = json["more_text"]; this.audio = json["audio"]; this.img = json["img"]; json["excercise_contents"].forEach((element) => { let excercise_content = new ExcerciseContent(); excercise_content.fromJson(element); this.excercise_contents.push(excercise_content); }); } getHeader() { let html = ""; if (this.img !== null) { html += `<img class="excercise-img" src="${this.img}">`; } if (this.audio !== null) { html += `<div class="sound-play-holder"> <img src="/static/img/play.svg"> <div class="sound-play-progressbar"> <div class="progressbar-status"></div> </div> </div>`; } return html; } getContent(answers, questionId) { let html = ""; html += this.header === undefined ? "" : `<h1 id="exercise-header">${this.header}</h1>`; html += this.content === undefined ? "" : `<p id="exercise-content">${this.content.replace("\n", "<br>")}</p>`; html += this.footer === undefined ? "" : `<h6 id="exercise-footer">${this.footer}</h6>`; html += this.more_text === undefined ? "" : `<p id="more-text">${this.more_text.replace(/\n/g, "<br>")}</p>`; this.excercise_contents.forEach((ec) => { html += ec.getContent(answers, questionId); }); return html; } } class Question { constructor(id = 0, title = "", content = "", category = "") { this.id = id; this.title = title; this.category = category; this.content = content; this.excercise; } fromJson(json) { this.id = json["id"]; this.title = json["title"]; this.category = json["category"]; this.content = json["content"]; this.excercise = new Excercise(); this.excercise.fromJson(json["excercise"]); } getHeader() { let html = ""; html += `<h6 id="question-category">${this.category}</h6>`; html += `<h1 id="question-title">${this.title}</h1>`; html += `<p id="question-content">${this.content}</p>`; html += this.excercise.getHeader(); return html; } getContent(answers, lastQuestionIndex) { let html = this.excercise.getContent(answers, this.id); if (answers.isQuestionSubmitted(this.id) && lastQuestionIndex == this.id) { html += '<button id="exit-button">Koniec</button>'; } else { html += answers.isQuestionSubmitted(this.id) ? `<button id="next-button">Dalej</button>` : `<button id="check-button">Sprawdź</button>`; } return html; } } class PlayResult { constructor() { this.answerAndCorrect = {}; this.checkedAnswers = {}; this.submittedQuestions = {}; } loadAnswersFromApiJson(json) { json.forEach((question) => { this.answerAndCorrect[question["id"]] = {}; this.checkedAnswers[question["id"]] = {}; this.submittedQuestions[question["id"]] = false; question["excercise"]["excercise_contents"].forEach( (excerciseContent) => { this.answerAndCorrect[question["id"]][excerciseContent["id"]] = excerciseContent["correct"]; this.checkedAnswers[question["id"]][excerciseContent["id"]] = null; } ); }); } getAnswer(questionId, answerId) { return this.checkedAnswers[questionId][answerId]; } selectAnswer(questionId, answerId, buttonIndex) { this.checkedAnswers[questionId][answerId] = buttonIndex; } getCorrectAnswer(questionId, answerID) { return this.answerAndCorrect[questionId][answerID]; } submitQuestion(questionId) { this.submittedQuestions[questionId] = true; } isQuestionSubmitted(questionId) { return this.submittedQuestions[questionId]; } } class QuestionSoundPlayer { constructor(soundUrl) { this.soundUrl = soundUrl; this.progressBar = $("div.progressbar-status"); this.playButton = $("div.sound-play-holder img:first-child"); this._playImg = "/static/img/play.svg"; this._pauseImg = "/static/img/pause.svg"; this._stopped = true; this.audioObject = new Audio(this.soundUrl); this.bindAll(); } stop() { this.audioObject.pause(); this.audioObject.currentTime = 0; } bindAll() { this.bindButton(); this.bindProgressbar(); this.bindProgressbarClick(); this.bindOnEnd(); } bindButton() { this.playButton.click(() => { if (this._stopped) { this.audioObject.play(); this.playButton.attr("src", this._pauseImg); this._stopped = false; } else { this.audioObject.pause(); this.playButton.attr("src", this._playImg); this._stopped = true; } }); } bindProgressbar() { this.audioObject.addEventListener("timeupdate", (event) => { this.progressBar.css( "width", `${(this.audioObject.currentTime / this.audioObject.duration) * 100}%` ); }); } _calculateAudioPercent(clickEvent) { let progressBarHandler = $("div.sound-play-progressbar")[0]; let offset = progressBarHandler.offsetLeft; let progressWidth = progressBarHandler.clientWidth; let clientX = clickEvent.x; return (clientX - offset) / progressWidth; } bindProgressbarClick() { this.progressBar.parent().click((event) => { let percent = this._calculateAudioPercent(event.originalEvent); this.audioObject.currentTime = this.audioObject.duration * percent; }); } bindOnEnd() { this.audioObject.addEventListener("ended", (event) => { this._stopped = true; this.playButton.attr("src", this._playImg); }); } } class Play { constructor() { this.get = this.getParams(); this.questionArray = []; this.actualQuestion = 0; this.makeAPIQuerry(); this.answers = new PlayResult(); this.lastQuestionIndex = 0; } start() { this.actualQuestion = 0; this.refreshNavBar(); this.renderActualQuestion(); this.highlightActiveLink(); } renderActualQuestion() { if (this.actualQuestionSound !== undefined) { this.actualQuestionSound.stop(); delete this.actualQuestionSound; } let questionToRender = this.questionArray[this.actualQuestion]; $("div#play-content-header").html(questionToRender.getHeader()); $("div#play-content-article").html( questionToRender.getContent(this.answers, this.lastQuestionIndex) ); let audioFile = this.questionArray[this.actualQuestion]["excercise"]["audio"]; if (audioFile !== null) { this.actualQuestionSound = new QuestionSoundPlayer(audioFile); } if ( !this.answers.isQuestionSubmitted( this.questionArray[this.actualQuestion]["id"] ) ) { this.attachAnswerButtons(); } this.attachNextAndCheckButtons(); this.showExplanations(); this.refreshNavBarProgress(); } async refreshNavBar() { let html = ""; this.questionArray.forEach((question, i) => { html += `<li id="q-${i}" style="opacity: 0">${question.title}</li>`; }); $("ul#question-links").html(html); this.attachNavButton(); for (let i = 0; i < this.questionArray.length; i++) { await $(`li#q-${i}`) .animate({ opacity: "0", opacity: "1" }, 50) .promise(); } } refreshNavBarProgress(){ let values = $.map(this.answers.submittedQuestions, (v, k) => {return v}); let submitted = 0; values.forEach((val) => { submitted += val === false ? 0 : 1; }) $("div#play-nav-progress").css("width", `${submitted / values.length * 100}%`) } attachNavButton() { $("ul#question-links li").click((action) => { this.changeQuestion.call(this, action); }); } attachAnswerButtons() { $("div.answer ul li").click((event) => { let target = event.target.className.trim() == "answer-circle" ? event.target : $(event.currentTarget).find("div.answer-circle").length == 1 ? $(event.currentTarget).find("div.answer-circle")[0] : null; if (target === null) { return; } let questionId = this.questionArray[this.actualQuestion]["id"]; let answerId = parseInt(target.id.split("-")[0]); let newAnswer = target.id.split("-")[1]; let oldAnswer = this.answers.getAnswer(questionId, answerId); if (oldAnswer == newAnswer) { return; } else { this.answers.selectAnswer(questionId, answerId, newAnswer); $(event.currentTarget) .parent() .find(".selected") .removeClass("selected"); $(target).addClass("selected"); } }); } attachNextAndCheckButtons() { $("button#check-button").click(() => { this.answers.submitQuestion( this.questionArray[this.actualQuestion]["id"] ); this.renderActualQuestion(); this.highlightActiveLink(); }); $("button#next-button").click(() => { this.actualQuestion = parseInt(this.actualQuestion) + 1; this.renderActualQuestion(); this.highlightActiveLink(); }); $("button#exit-button").click(() => { window.location.href = "/#learn"; }); } highlightActiveLink() { $("ul#question-links li").each((i, element) => { let questionId = this.questionArray[element.id.replace("q-", "")]["id"]; let submited = this.answers.isQuestionSubmitted(questionId); if (submited) { $(element).addClass("submited"); } }); $("ul#question-links li.active").removeClass("active"); $(`ul#question-links li#q-${this.actualQuestion}`).addClass("active"); } changeQuestion(action) { let newQuestionId = action.currentTarget.id.substr(2); this.actualQuestion = newQuestionId; this.highlightActiveLink(); this.renderActualQuestion(); } getParams() { this.GET_table = {}; let GET_path = window.location.search.substr(1).split("&"); GET_path.forEach((element) => { this.GET_table[element[0]] = element[1]; }); return this.GET_table; } parseJsonResponse(jsonResponse, status) { this.answers.loadAnswersFromApiJson(jsonResponse); jsonResponse.forEach((element) => { let question = new Question(); question.fromJson(element); this.questionArray.push(question); }); this.lastQuestionIndex = this.questionArray.at(-1)["id"]; this.start(); } async showExplanations(){ let explanations = $("div.explanation") for (let i = 0; i < explanations.length; i++) { await $(explanations[i]).find("h3").animate({"opacity": 0, "opacity": 1}, 500) await $(explanations[i]).find("p").animate({"opacity": 0, "opacity": 1}, 700) } } makeAPIQuerry() { $.getJSON( `/api/generate_quiz${window.location.search}`, "", (jsonResponse) => { this.parseJsonResponse.call(this, jsonResponse); } ); } } let pl = new Play();
import React, { Component } from 'react'; import { Form } from 'antd'; import Input from 'sub-antd/lib/input'; import Checkbox from 'sub-antd/lib/checkbox'; import Radio from 'sub-antd/lib/radio'; import message from 'sub-antd/lib/message'; import axios from 'axios'; import Cookies from 'js-cookie'; import { type, scope, changeitem, selectType, createhistory } from '../constants/enumtype'; import {halfFourColLayout,fourColLayout} from "components/layout/formLayout"; const FormItem = Form.Item; const CheckboxGroup = Checkbox.Group; const RadioGroup = Radio.Group; class OtherInfoEdit extends Component { constructor(props) { super(props); this.state = { desc: '', } } componentDidMount() { this.props.onRef(this) } save = (callback) => { this.props.form.validateFields((errors, values) =>{ const scope = values.scope.reduce((prev, next) => prev += ~~next, 0); const attrType = this.props.baseData.attrType || 0; const orgId = this.props.baseData.attrType || 0; const updateItem = {...this.props.baseData, ...values, scope, attrType, orgId, validateType: 1 }; axios.put(`/sysware/api/org-udef/update`, updateItem, { headers: { 'Authorization': Cookies.get('Authorization')}}).then(res => { if (!res.data.code||res.data.code === 200) { message.success("修改成功"); callback(updateItem); } else{ message.error(res.data.message); } }) }) } render() { const { getFieldProps, setFieldsValue, resetFields } = this.props.form; const nameProps = getFieldProps('attrCode', { initialValue: this.props.baseData.attrCode, rules: [ { required: true, message: '请输入名称' }, { max: 100, message: '请控制内容长度不超过100个字' }, ], }); const scopeProps = getFieldProps('scope', { initialValue: this.props.baseData.scope === 3? [1, 2]:[this.props.baseData.scope], rules: [ { type: 'array' }, ], onChange:(val)=>{ val.includes(2) ? this.setState({ disabledItem: false }) : this.setState({disabledItem: true }); setFieldsValue({'changeItem': undefined}); this.setState({ scope:val }) } }); const createHistoryProps = getFieldProps('createHistory', { initialValue: this.props.baseData.createHistory, rules: [{type: 'number'}] }); const descProps = getFieldProps('describe', { initialValue: this.props.baseData.describe, rules: [ { max: 200, message: '请控制内容长度不超过200个字' }, ], onChange:(e)=>{ this.setState({ desc:e.target.value }) } }); return ( <Form inline> <FormItem label='名称:' {...halfFourColLayout}> <Input type="text" {...nameProps} /> </FormItem> <FormItem label='作用范围:' {...halfFourColLayout}> <CheckboxGroup options={[ { label: '文档', value: 1 }, { label: '条目', value: 2 }, ]} {...scopeProps} /> </FormItem> <FormItem label='数据类型:' {...halfFourColLayout}> {type(this.props.baseData.attrType)} </FormItem> <FormItem label='生成历史记录:' {...halfFourColLayout}> <RadioGroup {...createHistoryProps}> <Radio key="a" value={1}>是</Radio> <Radio key="b" value={0}>否</Radio> </RadioGroup> </FormItem> <FormItem label='描述:' {...fourColLayout}> <Input type="textarea" maxLength='200' {...descProps} /> <p className="form-description-tip">还可输入{200-(this.props.baseData.describe ||this.state.desc ).length>0?200-(this.props.baseData.describe ||this.state.desc ).length:'0'}字</p> </FormItem> </Form> ) } } // OtherInfoEdit = Form.create()(OtherInfoEdit); export default OtherInfoEdit
import React, { Component, PropTypes } from 'react'; import Signup from '../components/auth/Signup'; export default class SignupPage extends Component { render() { const { register, login, loadLocale, pushState } = this.props.children; return ( <div id="SignupPage"> Please Signup: <Signup register={ register } login={ login } loadLocale={ loadLocale } pushState={ pushState } /> </div> ); } } SignupPage.propTypes = { children: PropTypes.object };
console.log('running pets.js') const speciesCells = document.querySelectorAll('.species') // console.log(speciesCells) // Need to add an event listener to each cell // individually; can't just say speciesCells.addEventListener speciesCells.forEach((cell) => { cell.addEventListener('mouseover', (event) => { event.target.style.backgroundColor = '#ddd' }) }) // change background color back to white on mouseout speciesCells.forEach((cell) => { cell.addEventListener('mouseout', (event) => { event.target.style.backgroundColor = '#fff' }) }) const pageChangeBtn = document.querySelector('#change-title') const pageTitle = document.querySelector('#page-title') pageChangeBtn.addEventListener('click', (event) => { if (pageTitle.innerHTML === 'Pets') { pageTitle.innerHTML = 'Super Pets' event.target.innerHTML = 'Change title back' } else if (pageTitle.innerHTML === 'Super Pets') { pageTitle.innerHTML = 'Pets'; event.target.innerHTML = 'Change Title' } else { console.error('I don\'t know what you clicked, but it wasn\'t what I expected') } })
import { splitStartupRedux } from 'utils/WebpackSplit'; const startup = function(element){ import('mgmt/Dashboard/containers/Root').then((Component) => { import('mgmt/Dashboard/store/configureStore').then((store) => { splitStartupRedux(element, Component.default, store.default); }); }); }; export default startup;
const redis = require("redis") const REDIS_PORT = process.env.REDIS_PORT || 6379 const client = redis.createClient(REDIS_PORT) client .once("connect", () => { console.log(`redis connected on port ${process.env.REDIS_PORT}`) }) .on("error", (error) => { console.error(error) }) module.exports = { client }
// import Adonais from './Adonais' // import Parallax from './Parallax' // import Feature from './Feature' // import Sky from './Sky' export { default as Pages } from './Menu' export const Figure = ({ img, alt, children }) => { return <p className="Figure"> <img src={img} alt={alt}/><br/> {children} </p> } /** * The link to the GitHub written as a Badge (`SimpleBadge` class). * @param {GitHubBadgeProps} props The properties. * @param {string} props.org The GitHub organisation. * @param {string} props.name The name of the repository. */ export const GitHubBadge = (props) => { const { org, name } = props return (<a href={'https://github.com/' + `${org}/${name}`} className="SimpleBadge">GitHub</a>) } // export default { // 'adonais': Adonais, // 'parallax': Parallax, // 'github-badge': GitHubBadge, // 'feature': Feature, // 'sky': Sky, // } /** * @typedef {Object} GitHubBadgeProps * @prop {string} props.org The GitHub organisation. * @prop {string} props.name The name of the repository. */
'use strict'; module.exports = function (GroupPermissionsUsers) { var groupController = require('../../server/lvr/groupPermissionsUsers/server-groupPermissionsUsers.js'); GroupPermissionsUsers.recoverPassword = function (values, cb) { var app = GroupPermissionsUsers.app; var dataModels = { GroupPermissionsUsers: app.models.GroupPermissionsUsers, User: app.models.User, ForgotPassword: app.models.ForgotPassword, dataSource: GroupPermissionsUsers.dataSource, type: 'recover' }; groupController.recover(dataModels, values, function (err, res) { if (!res) { cb(null, err); } else { cb(null, res); } }); }; GroupPermissionsUsers.remoteMethod( 'recoverPassword', { http: {verb: 'post'}, returns: {arg: 'transaction', type: 'string', root: true}, accepts: {arg: 'object', type: 'object', http: {source: 'body'}} } ); };
/** * Created by lawrence on 08/01/2018. */
/** * 我的/系统消息 */ import React, { Component, PureComponent } from 'react'; import { StyleSheet, Dimensions, View, Text, Button, TouchableHighlight, Image, TouchableOpacity, ScrollView, Platform, } from 'react-native'; import { connect } from 'rn-dva'; import moment from 'moment'; import Header from '../../components/Header'; import CommonStyles from '../../common/Styles'; import FlatListView from '../../components/FlatListView'; import * as requestApi from '../../config/requestApi'; import * as regular from '../../config/regular'; import * as utils from '../../config/utils'; import ImageView from '../../components/ImageView'; import Line from '../../components/Line'; import Model from '../../components/Model'; import SwipeListView from '../../components/SwipeListView'; import { imJudge } from '../../config/imJudge'; const { width, height } = Dimensions.get('window'); utils.initMomentFromString(); class SystemMessage extends PureComponent { static navigationOptions = { header: null, }; constructor(props) { super(props); const params = props.navigation.state.params || {}; this.state = { listName: `message${params.code}`, code: params.code, page: params.page, title: params.title, }; } componentDidMount() { this.getList(true, false); } getList = (isFirst = false, isLoadingMore = false) => { this.props.fetchList({ witchList: this.state.listName, isFirst, isLoadingMore, paramsPrivate: { code: this.state.code }, api: requestApi.systemMsgList, }); }; navPage = (routeName, params) => { this.props.navPage({ routeName, params }); } // 系统消息 renderSystemItem = item => ( <TouchableOpacity activeOpacity={1} onPress={() => { // if(item.code=='007'){ //商圈订单消息 // imJudge(item.extras, this.props.navigation) // }else{ this.navPage('MessageDetails', item); // } }} style={[styles.item, { flexDirection: 'row', justifyContent: 'space-between' }]} > <Text style={[styles.title, styles.itemLeft]}> {item.msgContent} {' '} </Text> <Text style={[styles.text, styles.itemRight]}>{moment(item.updatedAt * 1000).fromNow()}</Text> </TouchableOpacity> ); // 抽奖消息 renderTicketsItem = item => ( <View style={styles.item}> <View style={styles.itemTop}> <View style={[styles.itemLeft, { flexDirection: 'row', flexWrap: 'wrap' }]}> <Text style={[styles.title]}> 【抽奖】 {item.msgContent} 。 </Text> <TouchableOpacity onPress={() => imJudge(item.extras)}> <Text style={[styles.title, { color: CommonStyles.globalHeaderColor }]}>点击查看详情 </Text> </TouchableOpacity> </View> <Text style={[styles.text, styles.itemRight]}>{moment(item.updatedAt * 1000).format('YYYY-MM-DD')}</Text> </View> </View> ); // 专题活动消息 renderSpecialItem = ({ item }) => ( <View style={[styles.item, { padding: 0 }]}> <View style={[styles.itemTop, { backgroundColor: '#FAFAFA', height: 38, alignItems: 'center', width: width - 20, paddingHorizontal: 15, }]} > <Text style={[styles.title, styles.itemLeft]}> {item.msgContent} 。 </Text> <Text style={[styles.text, styles.itemRight]}>{moment(item.updatedAt * 1000).format('YYYY-MM-DD')}</Text> </View> <View style={{ paddingHorizontal: 15 }}> <ImageView source={{ uri: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1544866675468&di=6e4bfe947fe016a3290e0245d669caff&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F01806f58e4a502a801219c7701b630.jpg' }} sourceWidth={width - 50} sourceHeight={110} resizeMode="cover" /> <View style={styles.itemBottom}> <TouchableOpacity onPress={() => Toast.show('待开发')}> <Text style={[styles.title, { color: CommonStyles.globalHeaderColor }]}>删除</Text> </TouchableOpacity> <TouchableOpacity onPress={() => Toast.show('待开发')}> <Text style={[styles.text]}>点击查看</Text> </TouchableOpacity> </View> </View> </View> ); renderItem = (item) => { const { navigation } = this.props; const extras = item.extras || {}; const defaultSource = 'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=180635262,3469104988&fm=27&gp=0.jpg'; if (item.extras.goodsName && item.extras.orderId && item.extras.sequenceId) { return ( <TouchableHighlight underlayColor="#f1f1f1" activeOpacity={0.5} onPress={() => imJudge(extras, navigation)} > <View style={styles.item} activeOpacity={1}> <View style={styles.itemTop}> <View style={[styles.itemLeft, { flexDirection: 'row', flexWrap: 'wrap' }]}> <Text style={[styles.title]}> {item.msgContent} 。 </Text> { item.extras.sequenceId && ( <TouchableOpacity onPress={() => imJudge(extras, navigation)}> <Text style={[styles.title, { color: CommonStyles.globalHeaderColor }]}>点击查看开奖详情</Text> </TouchableOpacity> ) } </View> <Text style={[styles.text, styles.itemRight]}>{moment(item.updatedAt * 1000).format('YYYY-MM-DD')}</Text> </View> <View style={styles.goods}> <ImageView source={{ uri: extras.goodsPic || defaultSource }} sourceWidth={48} sourceHeight={48} style={{ borderRadius: 8, marginRight: 10 }} resizeMode="cover" /> <View style={{ flex: 1 }}> <Text style={[styles.title, { flex: 1, marginBottom: 10 }]}>{extras.goodsName}</Text> <Text style={[styles.text]}> 订单编号: {extras.orderId} </Text> </View> </View> </View> </TouchableHighlight> ); } return this.renderSystemItem(item); }; onRowDidOpen = (rowKey, rowMap) => { console.log('This row opened', rowKey); this.setState({ rowMap, rowKey }); }; closeRow = () => { const { rowMap, rowKey } = this.state; if (rowMap && rowMap[rowKey]) { rowMap[rowKey].closeRow(); } }; delete = (item) => { requestApi.systemMsgDelete({ msgId: item.id }).then(() => { Toast.show('删除成功'); this.getList(true, false); }).catch(err => { console.log(err) }); } render() { const { navigation, longLists } = this.props; const { title, listName, code } = this.state; let renderItem = () => { }; switch (code) { case '001': renderItem = this.renderSystemItem; break; case '006': renderItem = this.renderTicketsItem; break; case '003': renderItem = this.renderSpecialItem; break; default: renderItem = this.renderItem; break; } // const items = [ // { title: '活动', value: '晓可迎新活动开始啦', time: '12:08', route: 'Message', params: { code: '002' }, icon: require('../../images/message/activity.png') }, // { title: '专题', value: '晓可迎新活动开始啦', time: '12:08', route: 'Message', params: { code: '003' }, icon: require('../../images/message/special.png') }, // { title: '自营商城消息', value: '晓可迎新活动开始啦', time: '12:08', route: 'Message', params: { code: '004' }, icon: require('../../images/message/self.png') }, // { title: '福利商城消息', value: '晓可迎新活动开始啦', time: '12:08', route: 'Message', params: { code: '005' }, icon: require('../../images/message/welfare.png') }, // { title: '抽奖/AA彩', value: '晓可迎新活动开始啦', time: '12:08', route: 'Message', params: { code: '006' }, icon: require('../../images/message/choujiang.png') }, // { title: '系统提示', value: '晓可迎新活动开始啦', time: '12:08', route: 'Message', params: { code: '001' }, icon: require('../../images/message/system.png') }, // { title: '周边消息', value: '晓可迎新活动开始啦', time: '12:08', route: 'Message', params: { code: '007' }, icon: require('../../images/message/around.png') }, // ] return ( <View style={styles.container}> <Header navigation={navigation} goBack title={title} /> { code == '003' ? ( <FlatListView renderItem={data => renderItem(data)} style={styles.listview} store={{ ...longLists[listName], page: longLists[listName] && longLists[listName].listsPage || 1, }} data={longLists[listName] && longLists[listName].lists || []} keyExtractor={item => item.id} numColumns={1} refreshData={() => this.getList(false, false) } loadMoreData={() => this.getList(false, true) } /> ) : ( <SwipeListView useFlatList style={styles.listview} renderItem={(data, secId, rowId, rowMap) => renderItem(data.item) } store={{ ...longLists[listName], page: longLists[listName] && longLists[listName].listsPage || 1, }} data={longLists[listName] && longLists[listName].lists || []} numColumns={1} keyExtractor={item => item.id} // ItemSeparatorComponent={() => ( // <View style={styles.flatListLine} /> // )} refreshData={() => this.getList(false, false)} loadMoreData={() => this.getList(false, true)} renderHiddenItem={(data, secId, rowId, rowMap) => ( <View style={[ styles.rightContainer, ]} > <TouchableOpacity style={styles.delTextContainer} onPress={() => { this.closeRow(); this.delete(data.item); }} > <Text style={styles.deleteTextStyle}> 删除 </Text> </TouchableOpacity> </View> )} leftOpenValue={0} rightOpenValue={-70} previewRowKey="0" previewOpenValue={-40} previewOpenDelay={3000} onRowDidOpen={this.onRowDidOpen} /> ) } </View> ); } } const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, position: 'relative', }, content: { width, }, listview: { width, backgroundColor: CommonStyles.globalBgColor, }, flatListLine: { backgroundColor: CommonStyles.globalBgColor, height: 10, }, item: { borderRadius: 6, backgroundColor: '#fff', width: width - 20, marginLeft: 10, // ...CommonStyles.shadowStyle, padding: 15, minHeight: 66, zIndex: 0, }, title: { fontSize: 14, color: '#222222', marginBottom: 2, lineHeight: 18, }, text: { fontSize: 14, color: '#BBBBBB', }, delTextContainer: { width: 70, backgroundColor: '#EE6161', alignItems: 'center', justifyContent: 'center', height: '100%', }, deleteTextStyle: { color: '#fff', fontSize: 16, letterSpacing: 2, }, rightContainer: { flexDirection: 'row', backgroundColor: CommonStyles.globalBgColor, alignItems: 'center', justifyContent: 'flex-end', flex: 1, width: width - 20, borderRadius: 10, overflow: 'hidden', zIndex: 1, }, itemLeft: { flex: 1, marginRight: 20, }, itemRight: { width: 80, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'flex-start', textAlign: 'right', }, itemTop: { flexDirection: 'row', justifyContent: 'space-between', }, goods: { flexDirection: 'row', borderRadius: 6, backgroundColor: '#F8F8F8', padding: 10, flex: 1, marginTop: 15, }, itemBottom: { flex: 1, flexDirection: 'row', justifyContent: 'space-between', height: 44, justifyContent: 'space-between', alignItems: 'center', borderTopWidth: 1, borderColor: '#F1F1F1', }, }); export default connect( state => ({ userShop: state.user.userShop || {}, longLists: state.shop.longLists || {}, juniorShops: state.shop.juniorShops || [state.user.userShop || {}], }), { fetchList: (params = {}) => ({ type: 'shop/getList', payload: params }), shopSave: (params = {}) => ({ type: 'shop/save', payload: params }), navPage: (params = {}) => ({ type: 'system/navPage', payload: params }), }, )(SystemMessage);
angular .module('SFsecrets', [ 'ngRoute', 'satellizer', 'uiGmapgoogle-maps' ]) .controller('MainController', MainController) .controller('SecretsIndexController', SecretsIndexController) .controller('SecretsNewController', SecretsNewController) .controller('SecretsShowController', SecretsShowController) .controller('SecretsEditController', SecretsEditController) .controller('LoginController', LoginController) .controller('SignupController', SignupController) .controller('LogoutController', LogoutController) .controller('ProfileController', ProfileController) .service('UserService', UserService) .config(configRoutes) ;
(function (w, $) { 'use strict'; var baseUrl = $('base').attr('href'); var form = $('#form'); selectPosition(); form.on('submit', saveData); function saveData(event) { event.preventDefault(); var formData = form.serializeArray(); $.ajax({ method: 'POST', dataType: 'json', url: baseUrl + '/employee-register', data: formData, success: function (response) { clearForm(); toastr.success(response.payloads.message); }, error: function (response) { toastr.error(response.responseText); } }); } function clearForm() { form.find('#name').val(''); form.find('#position_id').val(0); form.find('#email').val(''); form.find('#password').val(''); form.find('#password-confirm').val(''); } function selectPosition(val) { $.ajax({ method: 'GET', dataType: 'json', cache: true, url: baseUrl + '/api/position/data', success: function (response) { var position = response.payloads.data.map(function(data, i) { return { id : data.id, text : data.name } }); $('#position_id').select2({ placeholder: "Select a position", data: position }); $('#position_id').val(val).trigger('change'); }, error: function (response) {} }); } })(window, window.jQuery);
const {ObjectID} = require('mongodb'); global.resolvers = { Cohort: async ({cohortId}, data, {mongo: {Cohorts}}) => { return await Cohorts.findOne({_id: new ObjectID(cohortId)}); }, }
var sql = require("mssql"); var {failureResponseBody,successResponseBody} = require('../../helpers/response') var {sendMailToReceipt} = require('./sendingMail') var {newTicketMatrix,sqlParametersforSP} = require('./responseMatrix') var routeMapping = require('../../helpers/matrix.json') async function createTicket(req,res){ try{ reqBody = req.body mail = reqBody.requestor csmartId = req.headers.csmartid console.log("header...",req.body) if(req.headers.mail == mail && csmartId){ createdTicket = await requestTicketController(reqBody,csmartId).catch(err=>{ res.status(err.statusCode).send(err.body) }) if(createdTicket){ res.send(createdTicket) } }else{ errMsg = failureResponseBody("Error","MailId/csmartId is not valid",400) res.status(errMsg.statusCode).send(errMsg.body) } }catch(err){ //console.log(err) errMsg = failureResponseBody("Error",err,404) res.status(errMsg.statusCode).send(errMsg.body) } } async function requestTicketController(reqBody,csmartId){ return new Promise(async(resolve,reject)=>{ resFromDB = await recordsetsFromDatabase(reqBody,csmartId).catch(err=>{ //console.log("here",err) errMsg = failureResponseBody("Error",err,400) reject(errMsg) }) if(resFromDB && resFromDB.adminMail != null && resFromDB.requestId != null){ let detailsForSendingMail = { role:"Admin", email : resFromDB.adminMail, response:"", requestId:resFromDB.requestId } mailSent = await sendMailToReceipt(detailsForSendingMail).catch(err=>{ error = "error in sending Mail"+err errMsg = failureResponseBody("Error",error,400) reject(errMsg) }) if(mailSent){ res = successResponseBody("success","Request Sent Succesfully",200) resolve(res) } //console.log("mail send to admin") } }) } async function recordsetsFromDatabase(reqBody,csmartId){ return new Promise((resolve,reject)=>{ var request = new sql.Request(); let body = reqBody[newTicketMatrix["RequestPayload"]] var routeStr = routeMapping[body.Name] var reqJsonString = JSON.stringify(body) /* Input Parameters */ request.input("UserMail", sql.VarChar(200), reqBody[newTicketMatrix["UserMail"]]) request.input("RequestDate", sql.DateTime, reqBody[newTicketMatrix["RequestDate"]]) request.input("RequestPayload", sql.VarChar(500), reqJsonString) request.input("RoutePrefix", sql.VarChar(200), routeStr) request.input("Status", sql.VarChar(200), "Pending") request.input("Csmart_Id", sql.VarChar(200), csmartId) request.input("PriorityOrder", sql.Int, 1) /* Output Paramters */ request.output("Name", sql.VarChar(200)) request.output("RequestId", sql.Int) /* Execute Stored Procedure */ request.execute(`[dbo].[makerChecker_save_user_request]` , async function (err, recordset){ if(err){ error = "Error in SP" + err reject(failureResponseBody("Error" , error, 400)) }else { let resFromSP = { "adminMail": recordset.output.Name, "requestId" : recordset.output.RequestId }; resolve(resFromSP) } }) }) } module.exports = { createTicket }
import React, { Component, useState } from "react"; import PropTypes from "prop-types"; const GenericInput = ({ error, isFocused, ...restProps }) => ( <> <input id="input" {...restProps} style={error && isFocused ? { background: "red" } : {}} /> {error && isFocused && <label htmlFor="input">some error message</label>} </> ); export default class AddTodo extends Component { state = { value: '', isFocused: false } onSubmitHandler(event, inputProps) { event.preventDefault(); console.log(`event = ${event.target.value}`) console.log(`inputProps = ${inputProps.value()}`); if (inputProps.value().trim()) { console.log(inputProps.value()); this.props.onCreateMethod(inputProps.value()); inputProps.clear(); } } //this.state = {date: new Date()}; начальное состояние дейта в стейте get inputProps() { const { value, isFocused } = this.state; const error = value.length < 3; return { bind: { value, //ключ совпадает со значением, поэтому можно писать только значение error, isFocused: isFocused, onChange: (event) => this.setState({ value: event.target.value }), onFocus: () => this.setState({ isFocused: true }), onBlur: () => this.setState({ isFocused: false }), }, clear: () => this.setState({ value: '' }), value: () => value, }; } render() { return ( <form style={{ marginBottom: "1rem" }} onSubmit={(event) => this.onSubmitHandler(event, this.inputProps)}> <GenericInput {...this.inputProps.bind} /> <button type="submit"> Add todo </button>{" "} </form> ) } }
import React, { Component } from 'react'; import { StyleSheet, ScrollView, View, Alert, Text, Button, TouchableOpacity } from 'react-native'; import { List, ListItem, Icon, Badge } from 'react-native-elements'; import { AdMobBanner, } from 'react-native-admob'; import { practice } from '../data/RC1/lesson1'; import { connect } from 'react-redux'; import {toggleShowAnswer,toggleTips,toggleChoose,toggleCheck} from '../Redux/action/actionTest'; import styles from '../Styles/styles.js'; class TestContent extends Component { _onPressShow() { this.props.toggleShowAnswer(this.props.stt); } _onPressTips() { this.props.toggleTips(this.props.stt); } _choose(id,choose) { this.props.toggleChoose(id,choose); } _check() { this.props.toggleCheck(this.props.stt); } render() { let display1 = this.props.arrWords[this.props.stt].showTextExplain1 ? `${practice[this.props.stt].ShowExplain}` : ''; let display2 = this.props.arrWords[this.props.stt].showTextExplain2 ? `${practice[this.props.stt].Tips}` : ''; return ( <ScrollView style={styles.scrollview}> <View style={{ flexDirection: 'row', }}> <Text style={{ fontSize: 18, fontWeight: 'bold' }}>Question {practice[this.props.stt].Question} : </Text> <TouchableOpacity style={this.props.arrWords[this.props.stt].checked ? styles.showbutton : styles.hidden} onPress={() => { this._discuss() }}> <Text style={{ fontSize: 20, color: "dodgerblue", backgroundColor: "white", }} >Discuss</Text> </TouchableOpacity> </View> <Text style={{ fontSize: 20, }}>{`${practice[this.props.stt].Content}`}</Text> <View style={styles.button3}> <View style={{ flex: 1, justifyContent: "center", alignItems: "baseline" }}> <TouchableOpacity onPress={() => { this._choose(this.props.stt,"A") }} disabled={this.props.arrWords[this.props.stt].checked}> <View style={{ backgroundColor: 'rgba(0,0,0,0)' }}> <Text style={this.props.arrWords[this.props.stt].answer === "A" ? styles.optionChoose : styles.optionDefault} > (A) {`${practice[this.props.stt].OptionA}`} </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={() => { this._choose(this.props.stt,"B") }} disabled={this.props.arrWords[this.props.stt].checked}> <Text style={this.props.arrWords[this.props.stt].answer === "B" ? styles.optionChoose : styles.optionDefault}> (B) {`${practice[this.props.stt].OptionB}`} </Text> </TouchableOpacity> <TouchableOpacity onPress={() => { this._choose(this.props.stt,"C") }} disabled={this.props.arrWords[this.props.stt].checked}> <Text style={this.props.arrWords[this.props.stt].answer === "C" ? styles.optionChoose : styles.optionDefault} > (C) {`${practice[this.props.stt].OptionC}`} </Text> </TouchableOpacity> <TouchableOpacity onPress={() => { this._choose(this.props.stt,"D") }} disabled={this.props.arrWords[this.props.stt].checked}> <Text style={this.props.arrWords[this.props.stt].answer === "D" ? styles.optionChoose : styles.optionDefault} > (D) {`${practice[this.props.stt].OptionD}`} </Text> </TouchableOpacity> </View> <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <TouchableOpacity style={this.props.arrWords[this.props.stt].showCheck ? styles.showbutton : styles.hidden} onPress={() => { this._check() }}> <Icon reverse name='ios-color-wand' type='ionicon' color='dodgerblue' /> </TouchableOpacity> </View> </View> <View style={styles.button3}> <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <TouchableOpacity style={this.props.arrWords[this.props.stt].checked ? styles.showbutton : styles.hidden} onPress={ () => { this._onPressShow() }}> <Text style={{ fontSize: 20, color: "dodgerblue", backgroundColor: "white", }}>ShowExplain</Text> </TouchableOpacity> </View> <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <TouchableOpacity style={this.props.arrWords[this.props.stt].checked ? styles.showbutton : styles.hidden} onPress={ () => { this._onPressTips() }}> <Text style={{ fontSize: 20, color: "dodgerblue", backgroundColor: "white", }}>Tips</Text> </TouchableOpacity> </View> </View> <View style={styles.textAnswer}> <Text>{display1}{display2}</Text> </View> <AdMobBanner bannerSize="fullBanner" adUnitID="ca-app-pub-7469861277535029/8882938994" testDeviceID="EMULATOR" didFailToReceiveAdWithError={(err) => { console.log("quang cao that bai" + err); }} /> </ScrollView> ); } } function mapStateToProps(state) { return { arrWords: state.arrWords, stt: state.isAdding }; } export default connect(mapStateToProps,{toggleShowAnswer,toggleTips,toggleChoose,toggleCheck})(TestContent);
var panelTpl = require('../../tpl/articles/panel.html') var menuTpl = require('../../tpl/articles/menu.html') var data = { button: null, sections: [], articles: null } function init(){ // 底部菜单 $(".m-footer-nav .item").click(function(e){ e.stopPropagation(); $(this).children("div").show(); $(this).siblings(".item").children("div").hide(); }); // 底部 子菜单 $(".sub-btn-list li").click(function(e){ e.stopPropagation(); hideMenuItem(); //var key = $(this).attr("data-key"); var type = $(this).data("type"); var key, url; switch( type ) { case 'click' : key = $(this).data("key"); getArticles(key); break case 'view' : url = $(this).data("url"); window.location.href = url; break } }) function hideMenuItem(){ $(".m-footer-nav .item").children("div").hide(); } $("html").click(hideMenuItem); } function getArticles(key){ var url = URL_PREFIX + '/index.php' var _data = { key: key, type: 'recommended', controller: 'article', action: 'lists', } $.ajax({ type: 'GET', url: url, dataType: 'json', data: _data, success: function(res){ if(res.error == 0){ //data.sections.push( { articles: res.data.articles } ) data.sections.push( res.data ) renderArticles(); } } }); } function renderArticles(){ if(data.sections.length ){ var html = '' data.sections.forEach(function(item){ //html += template("panel", item) html += panelTpl(item) }) $(".m-content").html(html); $(window).scrollTop(document.documentElement.scrollHeight); // 跳转到全部的路由 $(".m-panel-btn-tatal").click(function(e){ e.stopPropagation(); var key = $(this).data("key") gRouter.setRoute('articleList/'+key) }); } } function renderMenus(){ if(data.button){ //var html = template("menu", data); var html = menuTpl ( data); $("#container").html(html); init(); } } function getMenus(){ var url = URL_PREFIX + '/index.php' var _data = { controller: 'article', action: 'menus', } // 获取底部菜单 $.ajax({ type: 'GET', url: url, dataType: 'json', data: _data, success: function(res){ if(res.error == 0){ data.button = res.data.button; renderMenus(); } } }); } var gFirstEnter = true function menuRouteEntry(){ $("#view-page").html('<div class="m-content" id="js-m-content"></div><div id="container"></div>'); if( gFirstEnter ) { // 默认推送 getArticles("welcomeM"); getMenus(); gFirstEnter = false } else { renderMenus(); renderArticles(); } } module.exports = menuRouteEntry;
class Car { constructor(x, y) { this.x = x; this.y = y; this.canvas = document.getElementById('my-canvas'); this.ctx = this.canvas.getContext('2d'); this.width = 50; this.height = 50; this.img = new Image(this.width, this.height); this.img.src = 'images/car.png'; this.status = true; } draw() { if (this.status === true) { this.ctx.drawImage(this.img, this.x, this.y, this.width, this.height) } } moveLeft() { if (this.status === true) { this.x -= 25; } } moveRight() { if (this.status === true) { this.x += 25; } } checkCollisionCoin(coin) { if ((this.x + this.width > coin.x && this.y <= coin.y + coin.height) && (this.x < coin.x + coin.width && this.y <= coin.y + coin.height) ) { coin.status = false; return false; } } checkCollisionBricks(brick) { if ((this.x + this.width > brick.x && this.y <= brick.y + brick.height) && (this.x < brick.x + brick.width && this.y <= brick.y + brick.height)) { this.status = false; return false; } } }
function convert(x) { //converting return x*60; } console.log(convert(5)+ ' seconds'); console.log(convert(3)+ ' seconds'); console.log(convert(2)+ ' seconds');
var Cloudant = require('cloudant'); var acc = 'e7de31b0-4208-46f8-b8ff-dac1114bdf91-bluemix'; var id = 'catignitimentselledirlyd'; var pass = 'tFk3A37NLPFLClbcMNe7QPCa'; var HOUSE_LOAN_INTEREST = 0.02, CONSUMPTION_LOAN_INTEREST = 0.15, DEPOSIT_INTEREST = 0.015; // exports.getCustomer = function(id, successCallback, errorCallback) { // Cloudant({ // account: 'e7de31b0-4208-46f8-b8ff-dac1114bdf91-bluemix', // key: 'catignitimentselledirlyd', // password: 'tFk3A37NLPFLClbcMNe7QPCa' // }, function(er, cloudant) { // console.log("Database connection ..."); // var db = cloudant.db.use('clients'); // db.get(id, null, function(err, data) { // if (err) { // if (errorCallback) { // errorCallback(err.message); // } // return; // } // if (!data.salary) { // errorCallback("No customer with the id: " + id); // } // var clientObj = { // id: id, // salary: data.salary, // stock_rate: data.stock_rate, // house_loan: data.house_loan, // consumption_loan: data.consumption_loan, // amortized_house_spend: data.amortized_house_spend, // amortized_consumption_spend: data.amortized_consumption_spend, // stock_spend: data.stock_spend, // consumption_spend: data.consumption_spend, // deposit_spend: data.deposit_spend // }; // if (clientObj.stock_rate > 0.07) { // var new_rate = Math.random()*0.07; // clientObj.stock_rate = new_rate; // } // successCallback(clientObj); // }); // }); // }; exports.getGroupedCustomers = function(minSalary, maxSalary, minLoanCosts, maxLoanCosts, successCallback, errorCallback) { Cloudant({ account: 'e7de31b0-4208-46f8-b8ff-dac1114bdf91-bluemix', key: 'catignitimentselledirlyd', password: 'tFk3A37NLPFLClbcMNe7QPCa' }, function(er, cloudant) { console.log("Grouping customers by salary: (" + minSalary + " - " + maxSalary + ") and loan costs: (" + minLoanCosts + " - " + maxLoanCosts + ")"); var db = cloudant.db.use('clients'); var query = { "index": { "fields": ["salary"] } }; db.index(query, function(er, response) { if (er) { errorCallback("Error", er); } console.log('Index creation result: %s', response.result); }); var query2 = { selector: { "salary": { "$gt": parseInt(minSalary), "$lt": parseInt(maxSalary) } } }; db.find(query2, function(er, response) { if (er) { errorCallback("Error", er); } else { var filtered = response.docs.filter(function(client) { var loanCosts = client.house_loan * HOUSE_LOAN_INTEREST + client.consumption_loan * CONSUMPTION_LOAN_INTEREST; return ((loanCosts > minLoanCosts) && (loanCosts < maxLoanCosts)); }); console.log(filtered.length); for (var i = 0; i < filtered.length; ++i) { if (filtered[i].stock_rate > 0.07) { var new_rate = 0.07; filtered[i].stock_rate = new_rate; } } successCallback(filtered); } }); }); }; //exports.getGroupedCustomers(29400, 29500, 10000, 50000, console.log, console.log); // Example: // exports.getCustomerStrategy('13c35a289b9ab6d98b9089c4e3cf68e7', console.log);
import React, { useState, useEffect } from 'react'; import Menu from './components/Menu.js'; import Categories from './components/Categories.js'; import Data from './components/Data.js'; const allUniqueCategories = ['all', ...new Set(Data.map(item => item.category))]; function App() { const [items, setItems] = useState(Data); const [categories, setCategories] = useState(allUniqueCategories); useEffect(()=>{ setCategories(allUniqueCategories) },[]) const filterMenuItems = (category) => { if (category === 'all') { return setItems(Data); } const newItems = Data.filter((item) => item.category === category); setItems(newItems); } return ( <main> <section className="menu section"> <div className="title"> <h2>Our menu</h2> <div className="underline "></div> </div> <Categories category={categories} filterItems={filterMenuItems} /> <Menu items={items} /> </section> </main> ); } export default App;
import {getProtocol} from './Tool'; const delay = ({url, timeout}) => { return new Promise((resolve, reject) => { setTimeout(() => reject(url + '请求超时'), timeout * 1000) }) } const get = ({url, params = {}, headers = {}, timeout = 8}) => { const paramArr = [] if (Object.keys(params).length !== 0) { for (const key in params) { paramArr.push( key + '=' + params[key]) } } url = getProtocol().split('//')[0] + url; const urlStr = url + '?' + paramArr.join('&'); console.log(urlStr); return Promise.race([fetch(urlStr, { method: "GET", headers: { ...headers } }), delay({url, timeout})]) } const post = ({url, params = {}, headers = {}, timeout = 8}) => { const paramArr = [] if (Object.keys(params).length !== 0) { for (const key in params) { paramArr.push(key + '=' + params[key]) } } url = getProtocol().split('//')[0] + url; return fetch(url, { method: "POST", headers: { ...headers, "Content-Type": "application/x-www-form-urlencoded" }, body: paramArr.join('&') }, delay({url, timeout})) } export { get, post }
import React,{Component} from 'react'; import {connect} from 'react-redux' import { Table, Button ,Breadcrumb, BreadcrumbItem , Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap'; import {increase2,setzero,deletePro,changeQ} from '../actions' const mapStateToProps = (state)=>{ return { carts:state.cart, totalPrice:state.detailpro.totalPrice } } class Cart extends Component{ componentWillMount(){ this.props.setzero() } constructor(props) { super(props); this.state = { modal: false }; this.toggle = this.toggle.bind(this); } toggle() { this.setState({ modal: !this.state.modal }); } handleClick=(event,item)=>{ var checkbox=event.target; if(checkbox.checked){ this.props.increase2(item.quantity*item.price) }else{ this.props.increase2(-item.quantity*item.price) } } handleChange=(index)=>{ this.setState({value: event.target.value}); this.props.changeQ(index,event.target.value) } showCarts = ()=>{ var jsx = []; this.props.carts.map((item,index)=>{ jsx.push( <tr key={index} > <td style={{paddingLeft:"35px",width:"125px"}}> <input type="checkbox" onClick={()=>this.handleClick(event,item)} aria-label="..." id="cartCheck" /> </td> <td scope="row" style={{width:"150px"}}>{index+1}</td> <td>{item.name}</td> <td><input type="text" id="num" defaultValue={item.quantity} onChange={()=>this.handleChange(index)} style={{width:"50px"}}/></td> <td>¥{item.price}</td> <td style={{width:"200px"}}>¥{item.quantity*item.price}</td> <td onClick={()=>{this.props.deletePro(index)}} style={{cursor:"pointer"}}><a>删除</a></td> </tr> ); }); return jsx; } sumup=()=>{ var jsx = []; this.props.carts.map((item,index)=>{ jsx.push( <tr key={index}> <td scope="row">{index+1}</td> <td>{item.name}</td> <td>{item.quantity}</td> <td>¥{item.price}</td> <td>¥{item.quantity*item.price}</td> </tr> ); }); return jsx; } render(){ return ( <div style={{fontSize:"1.5rem"}}> <Breadcrumb> <BreadcrumbItem active><b>Cart</b></BreadcrumbItem> </Breadcrumb> <Table id="table"> <thead> <tr> <th></th> <th></th> <th>商品名称</th> <th>商品数量</th> <th>商品单价</th> <th>商品小计</th> </tr> </thead> <tbody style={{height:"500px"}}> {this.showCarts()} </tbody> </Table> <div style={{width:"100%",textAlign:"right",padding:"36px 172px 20px 0"}}> <div style={{fontSize:"1.5rem"}}> <h3 style={{color:"#f40"}}>商品总价:¥ <b style={{display:"inline-block",width:"30px"}}>{this.props.totalPrice}</b> </h3> {/* <h4 onClick={()=>this.Total()}>总计:¥ </h4>*/} <button type="button" className="btn btn-danger" data-toggle="modal" data-target="#exampleModal">结算</button> </div> </div> <div className="modal fade" id="exampleModal" tabIndex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div className="modal-dialog" role="document"> <div className="modal-content"> <div className="modal-header"> <h4 className="modal-title" id="exampleModalLabel" style={{float:"left"}}>确认购买商品</h4> <button type="button" className="close" data-dismiss="modal" aria-label="Close" style={{float:"right"}}> <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> <Table > <thead> <tr> <th></th> <th>商品名称</th> <th>商品数量</th> <th>商品单价</th> <th>商品小计</th> </tr> </thead> <tbody style={{height:"500px"}}> {this.sumup()} </tbody> </Table> <div style={{textAlign:"right",marginRight:"50px",color:"#f40"}}>商品总价:¥{this.props.totalPrice}</div> </div> <div className="modal-footer" style={{paddingRight:"50px"}}> <button type="button" className="btn btn-danger" data-dismiss="modal">确认</button> </div> </div> </div> </div> </div> ) } } export default connect(mapStateToProps,{increase2 , setzero , deletePro , changeQ})(Cart)
/* * * 文件名称:Description.js * 摘 要:單一商品修改和新增 描述頁面 * */ var PRODUCT_ID = '', OLD_PRODUCT_ID = ''; Ext.onReady(function () { var frm = Ext.create('Ext.form.Panel', { id: 'frm', layout: 'anchor', defaults: { anchor: "95%", msgTarget: "side", labelWidth: 130 }, border: false, plain: true, bodyStyle: 'padding:5px 5px 0px 5px', buttonAlign: 'center', buttons: [{ text: SAVE, hidden: true, handler: function () { Save(); } }], width: 900, items: [{ xtype: 'textarea', fieldLabel: CONTENT_1, hidden: true, colName: 'page_content_1', id: 'page_content_1', name: 'page_content_1' }, { xtype: 'textarea', fieldLabel: CONTENT_2, hidden: true, allowBlank: false, colName: 'page_content_2', id: 'page_content_2', name: 'page_content_2' }, { xtype: 'textarea', fieldLabel: CONTENT_3, hidden: true, colName: 'page_content_3', id: 'page_content_3', name: 'page_content_3' }, { border: false, defaults: { labelWidth: 130 }, items: [{ xtype: 'numberfield', decimalPrecision: 0, minValue: 1, value: 20, width: 240, fieldLabel: BUY_LIMIT, hidden: true, colName: 'product_buy_limit', id: 'product_buy_limit', name: 'product_buy_limit' }] }, { xtype: 'textfield', fieldLabel: KEYWORDS, hidden: true, colName: 'product_keywords', id: 'product_keywords', name: 'product_keywords', listeners: { blur: function () { var str = this.getValue().replace(/\s+[ ]{0,}/g, ','); str = str.replace(/[,]{1,}/g, ','); str = str.replace(/[,]{1,}/g, ','); var last = str.substring(str.length - 1, str.length); if (last == ",") { str = str.substring(0, str.length - 1); } this.setValue(str); } } }, { xtype: 'checkboxgroup', fieldLabel: TAG, height: 40, hidden: true, colName: 'product_tag_set', id: 'product_tag_set', name: 'product_tag_set' }, { xtype: 'checkboxgroup', fieldLabel: NOTICE, hidden: true, colName: 'product_notice_set', id: 'product_notice_set', name: 'product_notice_set' }] }); Ext.create('Ext.Viewport', { layout: 'anchor', items: [frm], renderTo: Ext.getBody(), autoScroll: true, listeners: { resize: function () { this.doLayout(); } } }); PRODUCT_ID = window.parent.GetProductId(); OLD_PRODUCT_ID = window.parent.GetCopyProductId(); requestTags(PRODUCT_ID, OLD_PRODUCT_ID); requestNotices(PRODUCT_ID, OLD_PRODUCT_ID); window.parent.GetProduct(this); window.parent.updateAuth(frm, 'colName'); }); function setForm(result) { Ext.getCmp('frm').down('#page_content_1').setValue(Ext.htmlDecode(result.Page_Content_1)) Ext.getCmp('frm').down('#page_content_2').setValue(Ext.htmlDecode(result.Page_Content_2)); Ext.getCmp('frm').down('#page_content_3').setValue(Ext.htmlDecode(result.Page_Content_3)); if (window.parent.GetProductId() != ""&&result.Product_Buy_Limit != 0) {//edit by xiangwang0413w 2014/10/15 修改商品時,當Product_Buy_Limit為0時應顯示為0 Ext.getCmp('frm').down('#product_buy_limit').setValue(result.Product_Buy_Limit); } Ext.getCmp('frm').down('#product_keywords').setValue(Ext.htmlDecode(result.Product_Keywords)); } function requestTags(productId,oldproductId) { Ext.Ajax.request({ url: '/Product/GetProTag', method: 'post', params: { ProductId: productId, OldProductId: oldproductId }, success: function (form, action) { Ext.getCmp('product_tag_set').update(form.responseText); }, failure: function () { Ext.Msg.alert(INFORMATION, DATA_LOAD_FAILURE); return false; } }); } function requestNotices(productId,oldproductId) { Ext.Ajax.request({ url: '/Product/GetProNotice', method: 'post', params: { ProductId: productId, OldProductId: oldproductId }, success: function (form, action) { Ext.getCmp('product_notice_set').update(form.responseText); }, failure: function () { Ext.Msg.alert(INFORMATION, DATA_LOAD_FAILURE); return false; } }); } function save(functionid) { //添加 遮罩層 避免用戶多次點擊 edit by zhuoqin0830w 2015/09/24 var mask; if (!mask) { mask = new Ext.LoadMask(Ext.getBody(), { msg: '請稍等...' }); } mask.show(); //添加disabled屬性 避免用戶多次點擊 edit by zhuoqin0830w 2015/09/24 window.parent.setMoveEnable(false); var success = false; var frm = Ext.getCmp('frm').getForm(); if (frm.isValid()) { var notice_checked = '[', tag_checked = '['; $('input[name="notices"]:checked').each(function (idx) { notice_checked += '{notice_id:' + $(this).val()+"}"; }); $('input[name="tags"]:checked').each(function (idx) { tag_checked += '{tag_id:' + $(this).val()+"}"; }); notice_checked += "]"; tag_checked += "]"; notice_checked = notice_checked.replace(/}{/g, '},{'); tag_checked = tag_checked.replace(/}{/g, '},{'); if (!functionid) { functionid = ''; } Ext.Ajax.request({ url: '/Product/SaveDescription', method: 'post', async: window.parent.GetProductId() == '' ? false : true, params: { page_content_1: Ext.htmlEncode(Ext.getCmp('page_content_1').getValue()), page_content_2: Ext.htmlEncode(Ext.getCmp('page_content_2').getValue()), page_content_3: Ext.htmlEncode(Ext.getCmp('page_content_3').getValue()), product_keywords: Ext.htmlEncode(Ext.getCmp('product_keywords').getValue()), product_buy_limit: Ext.getCmp('product_buy_limit').getValue(), Tags: tag_checked, Notice: notice_checked, ProductId: PRODUCT_ID, OldProductId: OLD_PRODUCT_ID, "function": functionid, "batch": window.parent.GetBatchNo() }, success: function (form, action) { var result = Ext.decode(form.responseText); mask.hide(); if (result.success) { success = true; if (PRODUCT_ID != '') { Ext.Msg.alert(INFORMATION, SUCCESS); } } else { Ext.Msg.alert(INFORMATION, FAILURE); } window.parent.setMoveEnable(true); }, failure: function () { mask.hide(); Ext.Msg.alert(INFORMATION, FAILURE); window.parent.setMoveEnable(true); } }); } else { mask.hide(); window.parent.setMoveEnable(true); } //window.parent.setMoveEnable(true); return success; }
import React from 'react'; import { Text, View, Image, StyleSheet } from 'react-native'; const Header = () => { return ( <View style={styles.container}> <Image style={styles.logo} source={require('../assets/icons/baseline_insights_black_24dp.png')}/> <Text style={styles.title}>Crypto Tracker</Text> </View> ); }; const styles = StyleSheet.create({ container: { // backgroundColor: '#000000', backgroundColor: '#5EA8A7', alignItems: 'center', justifyContent: 'center', padding: 20, }, logo: { width: 48, height: 48, tintColor: 'white', }, title: { fontSize: 24, fontWeight: '600', color: '#ffffff', }, }); export default Header;
/* Copyright 2016-2018 Stratumn SAS. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import memoryStore from '../src/memoryStore'; import { memoryStoreInfo, segment1, segment2, segment3 } from './fixtures'; import hashJson from '../src/hashJson'; describe('MemoryStore', () => { let store; beforeEach(() => { store = memoryStore(); }); describe('#getInfo()', () => { it('resolves with the store info', () => store.getInfo().then(body => body.should.deepEqual(memoryStoreInfo))); }); describe('#createLink()', () => { it('resolves with the segment', () => store .createLink(segment1.link) .then(body => body.should.deepEqual(segment1))); }); describe('#getSegment()', () => { it('resolves with the segment', () => store .createLink(segment1.link) .then(() => store.getSegment('first', segment1.meta.linkHash)) .then(body => body.should.deepEqual(segment1))); it('rejects if there is an error', () => store .getSegment('notFound', 'test') .then(() => { throw new Error('should not resolve'); }) .catch(err => { err.status.should.be.exactly(404); err.message.should.be.exactly('not found'); })); }); describe('#findSegments()', () => { beforeEach(() => store .createLink(segment1.link) .then(() => store.createLink(segment2.link)) .then(() => store.createLink(segment3.link)) ); it('resolves with the segments', () => store.findSegments('first').then(({ segments, totalCount }) => { segments.should.deepEqual([segment2, segment1]); totalCount.should.equal(2); })); it('paginates', () => store .findSegments('first', { offset: 1, limit: 1 }) .then(({ segments, totalCount }) => { segments.should.deepEqual([segment1]); totalCount.should.equal(2); })); it('paginates with default limit', () => { // Save >20 segments const generateSegment = h => { const link = { state: { value: h }, meta: { process: 'third', mapId: 'three', tags: ['three'], priority: 3 } }; return { link, meta: { linkHash: hashJson(link) } }; }; for (let i = 0; i < 22; i += 1) { store.createLink(generateSegment(i).link); } // Check that response only has 20 segments return store.findSegments('third').then(({ segments, totalCount }) => { segments.should.have.length(20); totalCount.should.equal(22); }); }); it('rejects if max limit exceeded', () => store .findSegments('first', { limit: 201 }) .then(() => { throw new Error('should not resolve'); }) .catch(err => { err.status.should.be.exactly(400); err.message.should.be.exactly('maximum limit should be 200'); })); it('filters by map ID', () => store .findSegments('first', { mapId: 'one' }) .then(({ segments, totalCount }) => { segments.should.deepEqual([segment2, segment1]); totalCount.should.equal(2); })); it('filters previous link hash', () => store .findSegments('first', { prevLinkHash: 'segment1' }) .then(({ segments, totalCount }) => { segments.should.deepEqual([segment2]); totalCount.should.equal(1); })); it('filters by linkHashes', () => store .findSegments('first', { linkHashes: [segment2.meta.linkHash] }) .then(({ segments, totalCount }) => { segments.should.deepEqual([segment2]); totalCount.should.equal(1); })); it('filters by tags', () => store .findSegments('first', { tags: ['one', 'two'] }) .then(({ segments, totalCount }) => { segments.should.deepEqual([segment2]); totalCount.should.equal(1); })); }); describe('#getMapIds()', () => { beforeEach(() => store .createLink(segment1.link) .then(() => store.createLink(segment2.link)) .then(() => store.createLink(segment3.link)) ); it('resolves with the map IDs', () => store.getMapIds('first').then(body => body.should.deepEqual(['one']))); it('sends a query', () => store .getMapIds('first', { offset: 0, limit: 1 }) .then(body => body.should.deepEqual(['one']))); }); });
/** * data module * @author Markus J Doetsch mdular.com */ /* global app:true */ app.registerModule('data', function () { "use strict"; var url = 'http://localhost:8888/', id; var init = function () { var frameId = document.querySelector('#frameId'); frameId.addEventListener('change', function (event) { id = event.target.value; }); id = frameId.value; }; var ajax = function (url, data, callback) { var req = new XMLHttpRequest(); req.addEventListener('progress', function (event) { //console.log('progress', event); callback(event); }); req.addEventListener('load', function (event) { //console.log('load', event); callback(event); }); req.addEventListener('error', function (event) { //console.log('error', event); callback(event); }); req.addEventListener('abort', function (event) { //console.log('abort', event); callback(event); }); if (data) { req.open('post', url); req.send(JSON.stringify(data)); } else { req.open('get', url); req.send(); } } var draw = function (data) { ajax(url + 'draw', data, function (event) { if (event.type === "load" && event.target.status === 200) { console.log("draw OK"); } else if (event.target.status !== 200) { console.log("draw error", event.target.status); } }); } var save = function (data) { if (typeof id === 'undefined' || !id) { throw new Error('no id!'); return; } data.reference = id; ajax(url + 'save/' + id, data, function (event) { if (event.type === "load" && event.target.status === 200) { console.log('save OK'); } else if (event.target.status !== 200) { console.log('save error', event.target.status); } }); }; var load = function (callback) { if (typeof id === 'undefined' || !id) { throw new Error('no id!'); return; } ajax(url + 'load/' + id, false, function (event) { if (event.type === 'load' && event.target.status === 200) { callback(JSON.parse(event.target.response)); } else if (event.target.status !== 200) { console.log('load error', event.target.status); } }); }; return { init : init, draw : draw, save : save, load : load }; });
import React from "react"; import {Form, Input, Button, Checkbox, message} from 'antd'; import axios from 'axios'; const layout = { labelCol: { span: 8, }, wrapperCol: { span: 16, }, }; const tailLayout = { wrapperCol: { offset: 8, span: 16, }, }; class signup extends React.Component { constructor() { super(); this.formRef = React.createRef(); } componentDidMount() { console.log("componentDidMount", this.props) } onFinish = (values) => { if(values.password1!=values.password2){ message.error("两次输入的密码不一致!"); this.onReset(); return; } let signData = {"username":values.username,"password":values.password1}; console.log('Success:', values); axios.post('http://localhost:3001/signup',signData,{ /* headers: { 'token': document.cookie }*/ }) .then((res) => { console.log(res); if(res.data.success==true){ message.success("注册成功!"); this.props.history.push("/login"); } else{ message.error(res.data.message); this.onReset(); } }) }; onFinishFailed = (errorInfo) => { console.log('Failed:', errorInfo); }; onReset = () => { this.formRef.current.resetFields(); }; render() { return ( <div style={{'position': 'absolute', 'top': '220px', 'left': '75%', 'marginLeft': '-150px'}}> <h2 style={{'textAlign': 'center','position':'relative','left':'24px'}}>注册</h2> <Form {...layout} /* name="basic"*/ ref={this.formRef} name="control-ref" initialValues={{ remember: true, }} onFinish={this.onFinish} onFinishFailed={this.onFinishFailed} > <Form.Item label="Username" name="username" rules={[ { required: true, message: 'Please input your username!', }, ]} > <Input/> </Form.Item> <Form.Item label="Password" name="password1" rules={[ { required: true, message: 'Please input your password!', }, ]} > <Input.Password/> </Form.Item> <Form.Item label="password again" name="password2" rules={[ { required: true, message: 'Please input your password again!', }, ]} > <Input.Password/> </Form.Item> <Form.Item {...tailLayout}> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> </div>); } } export default signup;
/* eslint-disable no-restricted-syntax */ /* eslint-disable no-plusplus */ const ROW_NUM = 8; const COL_NUM = 10; class TableInsert { constructor() { this.tds = []; this.title = null; const update = this.update.bind(this); this.activeIndex = new Proxy( {}, { set(obj, prop, value) { obj[prop] = value; update(); return true; }, }, ); this.resetActiveIndex(); this.defaultTitle = '选择表格大小'; } buildTableInsert(quill) { this.quill = quill; const container = document.createElement('div'); container.classList.add('table-insert'); container.setAttribute('title', '插入表格'); container.appendChild(this.createButton()); container.appendChild(this.createSelectArea()); document.addEventListener('click', ({ target }) => { if (!container.contains(target)) { this.show(false); } }); return container; } createButton() { const button = document.createElement('button'); const icon = document.createElement('i'); icon.classList.add('button-icon'); button.appendChild(icon); button.addEventListener('click', this.show.bind(this, true)); return button; } createSelectArea() { const container = document.createElement('div'); container.classList.add('select-area'); this.selectArea = container; this.title = document.createElement('p'); this.title.classList.add('table-title'); this.title.innerText = this.defaultTitle; container.appendChild(this.title); const choose = document.createElement('div'); for (let i = 0; i < ROW_NUM; i++) { const tr = document.createElement('div'); tr.classList.add('tr'); for (let j = 0; j < COL_NUM; j++) { const span = document.createElement('span'); span.classList.add('td'); span.dataset.row = i; span.dataset.col = j; span.addEventListener('mouseenter', () => { this.activeIndex.row = i; this.activeIndex.col = j; }); tr.appendChild(span); } choose.appendChild(tr); } choose.addEventListener('mouseleave', this.resetActiveIndex.bind(this)); choose.addEventListener('click', this.insertTable.bind(this)); this.tds = choose.getElementsByClassName('td'); container.appendChild(choose); return container; } update() { for (const node of this.tds) { const { row, col } = node.dataset; if (row <= this.activeIndex.row && col <= this.activeIndex.col) { node.classList.add('active'); } else { node.classList.remove('active'); } } if (!this.title) { return; } if (this.activeIndex.row < 0 || this.activeIndex.col < 0) { this.title.innerText = this.defaultTitle; } else { this.title.innerText = `插入${this.activeIndex.col + 1}x${this.activeIndex .row + 1}表格`; } } resetActiveIndex() { this.activeIndex.row = -1; this.activeIndex.col = -1; } insertTable() { const table = this.quill.getModule('table'); table.insertTable(this.activeIndex.row + 1, this.activeIndex.col + 1); this.show(false); } show(bool) { const displayAttr = bool ? 'block' : 'none'; this.selectArea.style.display = displayAttr; } } export default TableInsert;
//Javascript function to get which item is selected from the dropdown menu function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); }
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsHouseSiding = { name: 'house_siding', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M19 12h3L12 3 2 12h3v8h2v-2h10v2h2v-8zM7.21 10h9.58l.21.19V12H7v-1.81l.21-.19zm7.36-2H9.43L12 5.69 14.57 8zM7 16v-2h10v2H7z"/></svg>` };
import React from "react"; import ReactDOM from "react-dom"; import DataTable from "./dataTable.js"; import "semantic-ui-css/semantic.min.css"; import { Container, Segment } from "semantic-ui-react"; var people = [ { id: "1", name: "Michael", age: "26", gender: "Male" }, { id: "2", name: "Maria", age: "32", gender: "Female" }, { id: "3", name: "Jongku", age: "35", gender: "Male" } ]; function App() { return ( <Container text style={{ marginTop: "4em" }}> <Segment> <DataTable value={people} var="person"> <dataTableColumn headerName="Id" var="id" /> <dataTableColumn headerName="Name" var="name" /> <dataTableColumn headerName="Age" var="age" /> <dataTableColumn headerName="Gender" var="gender" /> <dataTableColumn var="Purposeful error" /> </DataTable> </Segment> </Container> ); } const rootElement = document.getElementById("root"); ReactDOM.render(<App />, rootElement);
import React, {Component} from 'react'; import Details from './Details'; class ProfessionPropositions extends Component { render() { let isPropSelected = (prop) => { return prop.id === this.props.selectedProfessionProposition.id; }; let getPropositionList = this.props.professionPropositions.map((prop) => <button className={"button proposal " + (isPropSelected(prop) ? 'secondary' : '')} key={prop.id} onClick={this.props.onProposalSelect.bind(null, prop)}>{prop.title}</button>); let displayProfessionsPanel = () => { if(this.props.professionPropositions.length === 0){ return ( <p className="text-center">Il n'y a pas de propositions pour ces valeurs.</p> ); } else { return ( <div> <div className="text-center"> {getPropositionList} </div> <Details selectedProp={this.props.selectedProfessionProposition} /> </div> ) } }; return( <div className="medium-6 columns"> <h2 className="text-center">Professions</h2> {displayProfessionsPanel()} </div> ) } } ProfessionPropositions.PropTypes = { professionPropositions: React.PropTypes.arrayOf( React.PropTypes.shape({ id: React.PropTypes.string, title: React.PropTypes.string }) ) }; export default ProfessionPropositions;
var searchData= [ ['jack_5fdescription_5ft_453',['jack_description_t',['../structjack__description__t.html',1,'']]], ['jack_5fposition_5ft_454',['jack_position_t',['../structjack__position__t.html',1,'']]], ['jack_5fproperty_5ft_455',['jack_property_t',['../structjack__property__t.html',1,'']]], ['jack_5fringbuffer_5fdata_5ft_456',['jack_ringbuffer_data_t',['../structjack__ringbuffer__data__t.html',1,'']]], ['jack_5fringbuffer_5ft_457',['jack_ringbuffer_t',['../structjack__ringbuffer__t.html',1,'']]], ['jack_5fsession_5fcommand_5ft_458',['jack_session_command_t',['../structjack__session__command__t.html',1,'']]], ['jack_5ftransport_5finfo_5ft_459',['jack_transport_info_t',['../structjack__transport__info__t.html',1,'']]], ['jackctl_5fparameter_5fvalue_460',['jackctl_parameter_value',['../unionjackctl__parameter__value.html',1,'']]] ];
(function() { 'use strict'; angular .module('acmeApp') .controller('AnsweredQuestionnaireDialogController', AnsweredQuestionnaireDialogController); AnsweredQuestionnaireDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'entity', 'AnsweredQuestionnaire', 'Answer']; function AnsweredQuestionnaireDialogController ($timeout, $scope, $stateParams, $uibModalInstance, entity, AnsweredQuestionnaire, Answer) { var vm = this; vm.answeredQuestionnaire = entity; vm.clear = clear; vm.datePickerOpenStatus = {}; vm.openCalendar = openCalendar; vm.save = save; vm.answers = Answer.query(); $timeout(function (){ angular.element('.form-group:eq(1)>input').focus(); }); function clear () { $uibModalInstance.dismiss('cancel'); } function save () { vm.isSaving = true; if (vm.answeredQuestionnaire.id !== null) { AnsweredQuestionnaire.update(vm.answeredQuestionnaire, onSaveSuccess, onSaveError); } else { AnsweredQuestionnaire.save(vm.answeredQuestionnaire, onSaveSuccess, onSaveError); } } function onSaveSuccess (result) { $scope.$emit('acmeApp:answeredQuestionnaireUpdate', result); $uibModalInstance.close(result); vm.isSaving = false; } function onSaveError () { vm.isSaving = false; } vm.datePickerOpenStatus.answeredDate = false; function openCalendar (date) { vm.datePickerOpenStatus[date] = true; } } })();
import React from 'react' import {mount} from '@shopify/react-testing' import Blog from '../' import PostBlurb from "../../PostBlurb/PostBlurb" import '@shopify/react-testing/matchers'; describe('<Blog />', () => { it('has 3 PostBlurb components', () => { const wrapper = mount(<Blog />); expect(wrapper).toContainReactComponentTimes(PostBlurb, 3); }); });
import React from "react"; import Button from "@material-ui/core/Button"; import CssBaseline from "@material-ui/core/CssBaseline"; import TextField from "@material-ui/core/TextField"; import Link from "@material-ui/core/Link"; import Grid from "@material-ui/core/Grid"; import Typography from "@material-ui/core/Typography"; import { makeStyles } from "@material-ui/core/styles"; import Container from "@material-ui/core/Container"; import MainProvider from "../../state-management/providers/MainProvider"; import { MainContext } from "../../state-management/Context"; import Select from "@material-ui/core/Select"; import MenuItem from "@material-ui/core/MenuItem"; import FormControl from "@material-ui/core/FormControl"; import InputLabel from "@material-ui/core/InputLabel"; const useStyles = makeStyles((theme) => ({ paper: { marginTop: theme.spacing(8), display: "flex", flexDirection: "column", alignItems: "center", }, avatar: { margin: theme.spacing(1), backgroundColor: theme.palette.secondary.main, }, form: { width: "100%", // Fix IE 11 issue. marginTop: theme.spacing(3), }, submit: { margin: theme.spacing(3, 0, 2), }, formControl: { margin: theme.spacing(1), minWidth: 380, }, })); export default function SignUp() { const classes = useStyles(); return ( <MainProvider> <MainContext.Consumer> {(context) => ( <Container component="main" maxWidth="xs"> <CssBaseline /> <div className={classes.paper}> <Typography component="h1" variant="h5"> Sign up </Typography> {context.state.signUpError != null ? ( <h5 style={{ color: "red" }}> {context.state.signUpError.message} </h5> ) : ( <h6>{}</h6> )} <form className={classes.form} noValidate> <Grid container spacing={2}> <Grid item xs={12} sm={6}> <TextField autoComplete="fname" name="firstName" variant="outlined" required fullWidth id="firstName" label="First Name" value={context.state.userSignUpInfo.firstName} onChange={context.handleSignUpInput} autoFocus /> </Grid> <Grid item xs={12} sm={6}> <TextField variant="outlined" required fullWidth id="lastName" label="Last Name" name="lastName" value={context.state.userSignUpInfo.lastName} onChange={context.handleSignUpInput} autoComplete="lname" /> </Grid> <Grid item xs={12}> <TextField variant="outlined" required fullWidth id="email" label="Email Address" name="email" autoComplete="email" value={context.state.userSignUpInfo.email} onChange={context.handleSignUpInput} /> </Grid> <Grid item xs={12}> <TextField variant="outlined" required fullWidth name="password" label="Password" type="password" id="password" value={context.state.userSignUpInfo.password} onChange={context.handleSignUpInput} autoComplete="current-password" /> </Grid> <Grid item xs={12}> <FormControl variant="outlined" className={classes.formControl} > <InputLabel id="demo-simple-select-outlined-label"> Select your role </InputLabel> <Select labelId="demo-simple-select-outlined-label" id="demo-simple-select-outlined" value={context.state.userSignUpInfo.role} onChange={context.handleSignUpInput} name="role" label="Select your role" > {/* <MenuItem value=""> <em>None</em> </MenuItem> */} <MenuItem value={"FarmOwner"}>Farm Owner</MenuItem> <MenuItem value={"vendor"}>Vendor</MenuItem> <MenuItem value={"user"}>Normal User</MenuItem> </Select> </FormControl> </Grid> </Grid> <Button type="submit" fullWidth variant="contained" color="primary" disabled={context.isInvalid} className={classes.submit} onClick={context.handleUserSignUp} > Sign Up </Button> <Grid container justify="flex-end"> <Grid item> <Link href="#" variant="body2"> Already have an account? Sign in </Link> </Grid> </Grid> </form> </div> </Container> )} </MainContext.Consumer> </MainProvider> ); }
// 最新音乐相关API import { request, requestWithoutLoading } from './axios' const API = '/netease-api' // 最新音乐首页列表 export const getTopSongs = (type) => request.get(API + `/top/song?type=${type}`) // 相似音乐 export const getSimiSongs = (id, option) => requestWithoutLoading.get(API + `/simi/song?id=${id}`, option) // 获取歌词 export const getLyric = (id) => request.get(API + `/lyric?id=${id}`)
import appErrors from '../../utils/applicationErrors'; /** * * @param {EntityType} entity * @return {function(action:ActionType): function(...[*]=)} */ export default (entity) => { return (action) => { return (req, res, next) => { try { next( new appErrors.ForbiddenError() ); } catch (e) { next( e ); } }; }; }
module.exports = function(app) { var task = require('./controller'); app.route('/') .get(task.return_entry); app.route('/index') .get(task.return_homepage); app.route('/contact') .get(task.return_contact); app.route('/about') .get(task.return_about); app.route('/signup') .get(task.return_signup) .post(task.signup_new_user); app.route('/dashboard') .get(task.return_dashboard); app.route('/ext-profile') .get(task.return_profile); app.route('/ext-private') .get(task.return_profile_unavailable); app.route('/profile') .get(task.return_my_profile) .post(task.edit_profile_info); app.route('/settings') .get(task.return_settings) app.route('/changedetail') .post(task.change_reg_detail); app.route('/changeavatar') .post(task.change_profile_pic); app.route('/changepassword') .post(task.change_sens_detail); app.route('/changeprivacy') .post(task.change_profile_privacy); app.route('/linkaccounts') .post(task.link_social_media); app.route('/signin') .get(task.return_signin) .post(task.user_login); app.route('/signout') .get(task.user_logoff); app.route('/iforgot') .get(task.return_iforgot) .post(task.forgot_password); app.route('/resetpassword') .get(task.return_reset_password) .post(task.reset_password); app.route('/proceed-register') .get(task.verification_email_sent); app.route('/proceed-reset') .get(task.reset_email_sent); app.route('/verifyemail') .get(task.verify_email); app.route('/showcasedata') .get(task.return_showcase_data); app.route('/updateshowcase') .post(task.update_showcase); app.route('/media') .get(task.return_resource); app.route('/documents') .get(task.resource_handler); app.route('/retrive') .get(task.retrive_resource); app.route('/upload') .get(task.return_resource_upload) .post(task.create_resource); app.route('/message') .post(task.message_profile); app.route('/proceed-message') .get(task.message_sent); app.route('/getmedia') .get(task.retrieve_media); app.route('/stats') .get(task.return_stats_page); app.route('*') .get(task.return_not_found); }
import React, {Component} from 'react'; import {inject, observer} from 'mobx-react'; import './profile.css'; class ProfileMenu extends Component { constructor() { super(); this._handleLogout = this._handleLogout.bind(this); } _handleLogout() { const {_auth_, onClose} = this.props; onClose(); _auth_.logout(); } render() { const {_auth_: {user}, state, onClose} = this.props; if(user === null || typeof user !== 'object' || typeof user.profile === 'undefined') { return null; } return ( <div id="profileMenuWrapper" className={`profile-menu-wrapper-${state}`}> <div id="profileMenuFullBackground" onClick={onClose} /> <div id="profileMenu"> <div className="profile-menu-item">Settings</div> <div className="profile-menu-item" onClick={this._handleLogout}>Log out</div> </div> </div> ); } } export default inject('_auth_')(observer(ProfileMenu));
import React from 'react'; import './categories.css' const Categories = ({list}) => { return ( <div className='column column-categories'> <h2 className='subtitle'>Categorías</h2> { list && list.categories && list.categories.map((cat) => ( <div> <a href={`/category/${cat.id}`} className='link-category'> {cat.name} </a> </div> )) } </div> ); }; export default Categories;
module.exports = (function(){ var express = require('express'), bodyParser = require('body-parser'), path = require("path"); var app = new express(); routerList = {}; app.use("/css", express.static("views/css")); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.set('views', "views"); app.set('view engine', 'pug'); function regist( namespace ){ if(routerList[namespace]){ throw new Error("Namespace Conflict."); } router = express.Router(); router.mount = function(){ app.use("/"+namespace, router); } routerList[namespace] = router; return router; } function start(){ app.listen( process.env.NODE_PORT || 30001, process.env.NODE_IP || "localhost", function( ...args ){ console.log("Server Started."); }); } return { regist, start } })();
'use strict' const CONTENT_TYPE_HEADER = 'content-type' /** * The friendly 'res.send' method * No comments needed ;) */ module.exports.send = (options, req, res) => (data = 200, code = 200, headers = null, cb = () => {}) => { if (headers !== null) { Object.keys(headers).forEach((key) => { res.setHeader(key.toLowerCase(), headers[key]) }) } if (typeof data === 'number') { code = parseInt(data, 10) data = res.body } else if (data instanceof Error) { const errorCode = data.status || data.code || data.statusCode code = typeof errorCode === 'number' ? parseInt(errorCode) : 500 data = { code, message: data.message, data: data.data } res.setHeader(CONTENT_TYPE_HEADER, 'application/json') } if (typeof data === 'object' && data instanceof Buffer === false) { if (!res.hasHeader(CONTENT_TYPE_HEADER)) { res.setHeader(CONTENT_TYPE_HEADER, 'application/json') } data = JSON.stringify(data) } res.statusCode = code // finally end request res.end(data, cb) }
import React, { Component } from 'react'; import cognitiva from './../../../assets/img/cognitiva-logo.svg'; import cariola from './../../../assets/img/cariola-logo.svg'; import logo from './../../../assets/img/lexnova-logo.svg'; import Notification from './../../../components/Notification'; class Recover extends Component { render() { return ( <div className="container heightfull bkg-gray"> <Notification /> <div className="row heightfull vert-align-item"> <div className="col-4 col-offset-4"> <div className="block-padding-x3 block"> <div className="block-logo"> <img src={logo} alt="Lexnova" /> </div> <h1>Recuperar Clave</h1> <p>Ingrese el email de ingreso al sistema, en breve enviaremos un correo con un link para cambiar su clave.</p> <form> <fieldset> <legend>Email</legend> <input type="email" name="email" placeholder="Ej. usuario@correo.cl" /> </fieldset> <button className="primary-button block-button">Ingresar</button> <div className="row block-logos"> <div className="col-5 col-offset-1"> <img src={cognitiva} alt="Cognitiva" /> </div> <div className="col-5"> <img src={cariola} alt="Cariola" /> </div> </div> </form> </div> </div> </div> </div> ) } } export default Recover;
/** * Created by waf on 11/4/15. */ //main.js require.config({ paths: { //libs jquery: "node_modules/jquery/dist/jquery", move : "lib/move/move.min" } }); //Activate app requirejs(['js/main']);
const Discord = require('discord.js'); const client = new Discord.Client(); const prefix = '.' client.on('ready', () => { console.log(`Logged in as ${client.user.tag}!`); client.user.setGame(`.help | .inv | ${client.guilds.size} Servers `,"http://twitch.tv/iMericPvP") console.log('') console.log('') console.log('╔[═════════════════════════════════════════════════════════════════]╗') console.log(`[Start] ${new Date()}`); console.log('╚[═════════════════════════════════════════════════════════════════]╝') console.log('') console.log('╔[════════════════════════════════════]╗'); console.log(`Logged in as * [ " ${client.user.username} " ]`); console.log('') console.log('Informations :') console.log('') console.log(`servers! [ " ${client.guilds.size} " ]`); console.log(`Users! [ " ${client.users.size} " ]`); console.log(`channels! [ " ${client.channels.size} " ]`); console.log('╚[════════════════════════════════════]╝') console.log('') console.log('╔[════════════]╗') console.log(' Bot Is Online') console.log('╚[════════════]╝') console.log('') console.log('') }); client.login(process.env.BOT_TOKEN); client.on('message', message => { var names = ["Meric Bot","One Bot","Duy0 Bot","Robot Bot","Bot Bot","Upload Bot","Normal Bot","Alpha Bot","lol Bot","3zoz Bot"]; if(message.content.startsWith(prefix + 'bot names')) { var alpha = new Discord.RichEmbed() .setTitle("**Get a Name For You Bot !**") .addField(names[Math.floor(Math.random() * names.length)]) message.channel.sendEmbed(alpha); } }); client.on('guildMemberAdd', member=> { member.addRole(member.guild.roles.find("name","●<[Danger-Members]>●")); }); client.on('message', message => { if (message.content.startsWith(".bans")) { message.guild.fetchBans() .then(bans => message.channel.send(`${bans.size} عدد اشخاص المبندة من السيرفر `)) .catch(console.error); } }); client.on("message", message => { if (message.content === ".ping") { const embed = new Discord.RichEmbed() .setColor("RANDOM") .addField('**Pong!:**' , `${Date.now() - message.createdTimestamp}` + ' ms') message.channel.sendEmbed(embed); } }); client.on('message', message => { if(message.content === '.inv') { const embed = new Discord.RichEmbed() .setTitle('Click here') .setURL('https://discordapp.com/oauth2/authorize?client_id=481153982354423808&scope=bot&permissions=36760572') .setColor('RANDOM') message.channel.send({embed: embed}); } }); client.on('message', message => { if(message.content === '.support') { const embed = new Discord.RichEmbed() .setTitle('Click here') .setURL('https://discord.gg/YMhGdtb') .setColor('RANDOM') message.channel.send({embed: embed}); } }); client.on('message', message => { if (message.author.id === client.user.id) return; if (message.guild) { let embed = new Discord.RichEmbed() let args = message.content.split(' ').slice(1).join(' '); if(message.content.split(' ')[0] == prefix + '2bc') { if (!args[1]) { return; } message.guild.members.forEach(m => { if(!message.member.hasPermission('ADMINISTRATOR')) return; var bc = new Discord.RichEmbed() .addField(' » الرسالة : ', args) .setColor('#ff0000') // m.send(`[${m}]`); m.send(`${m}`,{embed: bc}); }); } } else { return; } }); client.on('message' , async (message) => { if (message.content.startsWith(prefix + 'say')) { const args = message.content.substring(prefix.length).split(' '); message.delete(); args.shift() let msg = args.join(' ') message.channel.createWebhook(message.author.username, message.author.avatarURL) .then(wb => { const user = new Discord.WebhookClient(wb.id, wb.token) user.send(msg); user.delete() }) .catch(console.error) } }); client.on('guildMemberAdd', member=> { member.addRole(member.guild.roles.find("name","HulerGames")); }); client.on('typingStart', (ch, user) => { if(user.presence.status === 'offline') { ch.send(`${user} كشفتك يا اوفلاين Noooooooope`) .then(msg => { msg.delete(10000) }) } }) client.on('message', async message => { let messageArray = message.content.split(' '); let args = messageArray.slice(1); if(message.content.startsWith(prefix + "invlink")) { if(!args) return message.reply('**حدد اسم دعوة**'); message.guild.fetchInvites().then(i => { let inv = i.get(args[0]); if(!inv) return message.reply(`**لم اقدر على ايجاد ${args}**`); var iNv = new Discord.RichEmbed() .setAuthor(message.author.username,message.author.avatarURL) .setThumbnail(message.author.avatarURL) .addField('# - صاحب الدعوة',inv.inviter,true) .addField('# - روم الدعوة',inv.channel,true) .addField('# - تاريخ انتهاء الدعوة',moment(inv.expiresAt).format('YYYY/M/DD:h'),true) .addField('# - تم انشاء الدعوة',moment(inv.createdAt).format('YYYY/M/DD:h'),true) .addField('# - مدة الدعوة',moment(inv.maxAge).format('DD **ساعة** h **يوم**'),true) .addField('# - الاستخدامات',inv.uses || inv.maxUses,true) message.channel.send(iNv); }); } }); client.on('message', msg => { if(msg.content === 'wlc') msg.reply('مرحبا بك بالسيرفر') }); client.on('message', msg => { if(msg.content === 'wlc1') msg.reply('Welcome to Danger server') }); client.on('message', msg => { if(msg.content === 'wlc2') msg.reply('Welcome to Danger server') }); client.on('message', msg => { if(msg.content === 'wlc3') msg.reply('Welcome to Danger server') }); client.on("guildMemberAdd", member => { member.createDM().then(function (channel) { return channel.send(`●▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ஜ۩۞۩ஜ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬● ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ░░░░░░░░░░░░░█░█░█░█▀▀▀░█░░░░█▀▀▀░█▀▀█░█▀█▀█░█▀▀▀░░░░░░░░ ░░░░░░░░░░░░░█░█░█░█▀▀▀░█░░░░█░░░░█░░█░█░█░█░█▀▀▀░░░░░░░░ ░░░░░░░░░░░░░▀▀▀▀▀░▀▀▀▀░▀▀▀▀░▀▀▀▀░▀▀▀▀░▀░▀░▀░▀▀▀▀░░░░░░░░ ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ ●▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ஜ۩۞۩ஜ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬● ${member} `) }).catch(console.error) }); client.on('message', message => { if(message.content.startsWith(prefix + "clear")) { var args = message.content.split(" ").slice(1); if (!message.member.hasPermission('MANAGE_MESSAGES')) return message.reply('You need MANAGE_MESSAGES permission noob'); if (!args[0]) return message.channel.send('You didn\'t provide any number!!!'); message.channel.bulkDelete(args[0]).then(() => { const embed = new Discord.RichEmbed() .setColor(0xF16104) .setDescription(`Cleared ${args[0]} messages.`); message.channel.send({ embed }); const actionlog = message.guild.channels.find('name', 'log'); if (!actionlog) return message.channel.send('Can\'t find action-log channel. Are you sure that this channel exists and I have permission to view it? **CANNOT POST LOG.**'); const embedlog = new Discord.RichEmbed() .setDescription('~Purge~') .setColor(0xF16104) .addField('Purged By', `<@${message.author.id}> with ID ${message.author.id}`) .addField('Purged in', message.channel) .addField('Time', message.createdAt); actionlog.send(embedlog); }); }; }); var iMericPvP = ["https://f.top4top.net/p_682it2tg6.png","https://e.top4top.net/p_682a1cus5.png","https://d.top4top.net/p_682pycol4.png","https://c.top4top.net/p_682vqehy3.png","https://b.top4top.net/p_682mlf9d2.png","https://a.top4top.net/p_6827dule1.png","https://b.top4top.net/p_682g1meb10.png","https://a.top4top.net/p_682jgp4v9.png","https://f.top4top.net/p_682d4joq8.png","https://e.top4top.net/p_6828o0e47.png","https://d.top4top.net/p_6824x7sy6.png","https://c.top4top.net/p_682gzo2l5.png","https://b.top4top.net/p_68295qg04.png","https://a.top4top.net/p_682zrz6h3.png","https://f.top4top.net/p_6828vkzc2.png","https://e.top4top.net/p_682i8tb11.png","https://f.top4top.net/p_8816hvic1.png","https://d.top4top.net/p_882020461.png","https://e.top4top.net/p_882s3ftn1.png","https://a.top4top.net/p_882eg9c51.png","https://c.top4top.net/p_882xkcqd1.png","https://f.top4top.net/p_882w7pdi1.png","https://a.top4top.net/p_882gcpmo1.png"] client.on('message', message => { var args = message.content.split(" ").slice(1); if(message.content.startsWith(prefix + 'لو خيروك')) { var cat = new Discord.RichEmbed() .setImage(iMericPvP[Math.floor(Math.random() * iMericPvP.length)]) message.channel.sendEmbed(cat); } }); const moment = require("moment"); const fs = require("fs"); const dateFormat = require('dateformat'); const Canvas = require("canvas"); let profile = JSON.parse(fs.readFileSync("profile.json", "utf8")) client.on("message", message => { if (message.author.bot) return; if(!message.channel.guild)return; if (!profile[message.author.id]) profile[message.author.id] = { tite: 'Super User', rep: 0, reps: 'NOT YET', lastDaily:'Not Collected', level: 0, points: 0, credits: 150, }; fs.writeFile('profile.json', JSON.stringify(profile), (err) => { if (err) console.error(err); }) }); client.on("message", (message) => { let men = message.mentions.users.first() if (message.author.bot) return; if (message.author.id === client.user.id) return; if(!message.channel.guild) return; if (message.content.startsWith(prefix + 'credit')) { if(men) { if (!profile[men.id]) profile[men.id] = { lastDaily:'Not Collected', credits: 1, }; } if(men) { message.channel.send(`** ${men.username}, :credit_card: balance` + " is `" + `${profile[men.id].credits}$` + "`.**") } else { message.channel.send(`** ${message.author.username}, your :credit_card: balance` + " is `" + `${profile[message.author.id].credits}$` + "`.**") } } if(message.content.startsWith(prefix + "daily")) { if(profile[message.author.id].lastDaily != moment().format('day')) { profile[message.author.id].lastDaily = moment().format('day') profile[message.author.id].credits += 498406516210610621062106065109540 message.channel.send(`**${message.author.username} you collect your \`498406516210610621062106065109540\` :dollar: daily pounds**`) } else { message.channel.send(`**:stopwatch: | ${message.author.username}, your daily :yen: credits refreshes ${moment().endOf('day').fromNow()}**`) } } let cont = message.content.slice(prefix.length).split(" "); let args = cont.slice(1); let sender = message.author if(message.content.startsWith(prefix + 'trans')) { if (!args[0]) { message.channel.send(`**Usage: ${prefix}trans @someone amount**`); return; } // We should also make sure that args[0] is a number if (isNaN(args[0])) { message.channel.send(`**1**`); return; // Remember to return if you are sending an error message! So the rest of the code doesn't run. } let defineduser = ''; let firstMentioned = message.mentions.users.first(); defineduser = (firstMentioned) if (!defineduser) return message.channel.send(`**2**`); var mentionned = message.mentions.users.first(); if (!profile[sender.id]) profile[sender.id] = {} if (!profile[sender.id].credits) profile[sender.id].credits = 200; fs.writeFile('profile.json', JSON.stringify(profile), (err) => { if (err) console.error(err); }) var mando = message.mentions.users.id; if (!profile[defineduser.id]) profile[defineduser.id] = {} if (!profile[defineduser.id].credits) profile[defineduser.id].credits = 200; profile[defineduser.id].credits += (+args[0]); profile[sender.id].credits += (-args[0]); let mariam = message.author.username message.channel.send(`**:moneybag: | ${message.author.username}, has transferrerd ` + "`" + args[0] + "$` to " + `<@${defineduser.id}>**`) } }); client.on('message', message => { if(!message.channel.guild) return; if(message.content.startsWith('.bc')) { if(!message.channel.guild) return message.channel.send('**هذا الأمر فقط للسيرفرات**').then(m => m.delete(5000)); if(!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('**للأسف لا تمتلك صلاحية** `ADMINISTRATOR`' ); let args = message.content.split(" ").join(" ").slice(2 + prefix.length); let copy = "MericBot"; let request = `Requested By ${message.author.username}`; if (!args) return message.reply('**يجب عليك كتابة كلمة او جملة لإرسال البرودكاست**');message.channel.send(`**هل أنت متأكد من إرسالك البرودكاست؟ \nمحتوى البرودكاست:** \` ${args}\``).then(msg => { msg.react('✅') .then(() => msg.react('❌')) .then(() =>msg.react('✅')) let reaction1Filter = (reaction, user) => reaction.emoji.name === '✅' && user.id === message.author.id; let reaction2Filter = (reaction, user) => reaction.emoji.name === '❌' && user.id === message.author.id; let reaction1 = msg.createReactionCollector(reaction1Filter, { time: 12000 }); let reaction2 = msg.createReactionCollector(reaction2Filter, { time: 12000 }); reaction1.on("collect", r => { message.channel.send(`☑ | Done ... The Broadcast Message Has Been Sent For ${message.guild.members.size} Members`).then(m => m.delete(5000)); message.guild.members.forEach(m => { var bc = new Discord.RichEmbed() .setColor('RANDOM') .setTitle('Broadcast') .addField('Server', message.guild.name) .addField('Sender', message.author.username) .addField('Message', args) .setThumbnail(message.author.avatarURL) .setFooter(copy, client.user.avatarURL); m.send({ embed: bc }) msg.delete(); }) }) reaction2.on("collect", r => { message.channel.send(`**Broadcast Canceled.**`).then(m => m.delete(5000)); msg.delete(); }) }) } }); client.on('message', message =>{ let args = message.content.split(' '); let prefix = '.'; //تقدر تغير البرفكس if(args[0] === `${prefix}avatar`){ let mentions = message.mentions.members.first() if(!mentions) { let sicon = message.author.avatarURL let embed = new Discord.RichEmbed() .setImage(message.author.avatarURL) .setColor("#f7abab") .setDescription(`**${message.author.username}#${message.author.discriminator}**'s avatar :`); message.channel.send({embed}) } else { let sicon = mentions.user.avatarURL let embed = new Discord.RichEmbed() .setColor("#f7abab") .setDescription(`**${mentions.user.username}#${mentions.user.discriminator}**'s avatar :`) .setImage(sicon) message.channel.send({embed}) } }; }); client.on('message', message => { var prefix = "." if (message.author.x5bz) return; if (!message.content.startsWith(prefix)) return; let command = message.content.split(" ")[0]; command = command.slice(prefix.length); let args = message.content.split(" ").slice(1); if (command == "ban") { if(!message.channel.guild) return message.reply('** This command only for servers**'); if(!message.guild.member(message.author).hasPermission("BAN_MEMBERS")) return message.reply("**You Don't Have ` BAN_MEMBERS ` Permission**"); if(!message.guild.member(client.user).hasPermission("BAN_MEMBERS")) return message.reply("**I Don't Have ` BAN_MEMBERS ` Permission**"); let user = message.mentions.users.first(); let reason = message.content.split(" ").slice(2).join(" "); /*let b5bzlog = client.channels.find("name", "5bz-log"); if(!b5bzlog) return message.reply("I've detected that this server doesn't have a 5bz-log text channel.");*/ if (message.mentions.users.size < 1) return message.reply("**منشن شخص**"); if(!reason) return message.reply ("**اكتب سبب الطرد**"); if (!message.guild.member(user) .bannable) return message.reply("**لايمكنني طرد شخص اعلى من رتبتي يرجه اعطاء البوت رتبه عالي**"); message.guild.member(user).ban(7, user); const banembed = new Discord.RichEmbed() .setAuthor(`BANNED!`, user.displayAvatarURL) .setColor("RANDOM") .setTimestamp() .addField("**User:**", '**[ ' + `${user.tag}` + ' ]**') .addField("**By:**", '**[ ' + `${message.author.tag}` + ' ]**') .addField("**Reason:**", '**[ ' + `${reason}` + ' ]**') message.channel.send({ embed : banembed }) } }); client.on('message', message => { if (message.content.startsWith(".bot")) { message.channel.send({ embed: new Discord.RichEmbed() .setAuthor(client.user.username,client.user.avatarURL) .setThumbnail(client.user.avatarURL) .setColor('RANDOM') .setTitle('``INFO Morro Bot`` ') .addField('``My Ping``' , [`${Date.now() - message.createdTimestamp}` + 'MS'], true) .addField('``RAM Usage``', `[${(process.memoryUsage().rss / 1048576).toFixed()}MB]`, true) .addField('``servers``', [client.guilds.size], true) .addField('``channels``' , `[ ${client.channels.size} ]` , true) .addField('``Users``' ,`[ ${client.users.size} ]` , true) .addField('``My Name``' , `[ ${client.user.tag} ]` , true) .addField('``My ID``' , `[ ${client.user.id} ]` , true) .addField('``My Prefix``' , `[ $$ ]` , true) .addField('``My Language``' , `[ Java Script ]` , true) .setFooter('By | MHSTR') }) } }); client.on('message', message => { if (!message.channel.guild) return; if(message.content =='.count') var SaifDz = new Discord.RichEmbed() .setThumbnail(message.author.avatarURL) .setFooter(message.author.username, message.author.avatarURL) .setTitle('🌷| Members info') .addBlankField(true) .addField('عدد اعضاء السيرفر',`${message.guild.memberCount}`) message.channel.send(SaifDz); }); client.on('message', message => { var prefix = "." if (message.author.x5bz) return; if (!message.content.startsWith(prefix)) return; let command = message.content.split(" ")[0]; command = command.slice(prefix.length); let args = message.content.split(" ").slice(1); if (command == "kick") { if(!message.channel.guild) return message.reply('** This command only for servers**'); if(!message.guild.member(message.author).hasPermission("KICK_MEMBERS")) return message.reply("**You Don't Have ` KICK_MEMBERS ` Permission**"); if(!message.guild.member(client.user).hasPermission("KICK_MEMBERS")) return message.reply("**I Don't Have ` KICK_MEMBERS ` Permission**"); let user = message.mentions.users.first(); let reason = message.content.split(" ").slice(2).join(" "); if (message.mentions.users.size < 1) return message.reply("**منشن شخص**"); if(!reason) return message.reply ("**اكتب سبب الطرد**"); if (!message.guild.member(user) .kickable) return message.reply("**لايمكنني طرد شخص اعلى من رتبتي يرجه اعطاء البوت رتبه عالي**"); message.guild.member(user).kick(); const kickembed = new Discord.RichEmbed() .setAuthor(`KICKED!`, user.displayAvatarURL) .setColor("RANDOM") .setTimestamp() .addField("**User:**", '**[ ' + `${user.tag}` + ' ]**') .addField("**By:**", '**[ ' + `${message.author.tag}` + ' ]**') .addField("**Reason:**", '**[ ' + `${reason}` + ' ]**') message.channel.send({ embed : kickembed }) } }); client.on('message', message => { var prefix = "."; if(!message.channel.guild) return; if(message.content.startsWith(prefix + 'move')) { if (message.member.hasPermission("MOVE_MEMBERS")) { if (message.mentions.users.size === 0) { return message.channel.send("``لاستخدام الأمر اكتب هذه الأمر : " +prefix+ "move [USER]``") } if (message.member.voiceChannel != null) { if (message.mentions.members.first().voiceChannel != null) { var authorchannel = message.member.voiceChannelID; var usermentioned = message.mentions.members.first().id; var embed = new Discord.RichEmbed() .setTitle("Succes!") .setColor("#000000") .setDescription(`لقد قمت بسحب <@${usermentioned}> الى الروم الصوتي الخاص بك✅ `) var embed = new Discord.RichEmbed() .setTitle(`You are Moved in ${message.guild.name}`) .setColor("RANDOM") .setDescription(`**<@${message.author.id}> Moved You To His Channel!\nServer --> ${message.guild.name}**`) message.guild.members.get(usermentioned).setVoiceChannel(authorchannel).then(m => message.channel.send(embed)) message.guild.members.get(usermentioned).send(embed) } else { message.channel.send("``لا تستطيع سحب "+ message.mentions.members.first() +" `يجب ان يكون هذه العضو في روم صوتي`") } } else { message.channel.send("**``يجب ان تكون في روم صوتي لكي تقوم بسحب العضو أليك``**") } } else { message.react("❌") }} }); client.on("guildMemberAdd", member => { member.createDM().then(function (channel) { return channel.send(`:rose: ولكم نورت السيرفر:rose: :crown:اسم العضو ${member}:crown: انت العضو رقم ${member.guild.memberCount} `) }).catch(console.error) }) client.on("guildCreate", guild => { console.log(` شخص ما اضاف بوت في سيرفر اسمه ! ${guild.name} اونر سيرفر هو ${guild.owner.user.username}!`) }); client.on("message", (message) => { if (message.content.startsWith(".ct")) { if (!message.member.hasPermission('MANAGE_CHANNELS')) return message.reply("You Don't Have `MANAGE_CHANNELS` Premissions "); let args = message.content.split(" ").slice(1); message.guild.createChannel(args.join(' '), 'text'); message.channel.sendMessage('تـم إنـشاء روم كـتابـي') } }); client.on("message", (message) => { if (message.content.startsWith(".cv")) { if (!message.member.hasPermission('MANAGE_CHANNELS')) return message.reply("You Don't Have `MANAGE_CHANNELS` Premissions "); let args = message.content.split(" ").slice(1); message.guild.createChannel(args.join(' '), 'voice'); message.channel.sendMessage('تـم إنـشاء روم صـوتي') } }); client.on('message', message => { if (message.content === ".id") { let embed = new Discord.RichEmbed() .setColor("RANDOM") .setThumbnail(message.author.avatarURL) .addField("Name:",`${message.author.username}`, true) .addField('Discrim:',"#" + message.author.discriminator, true) .addField("ID:", message.author.id, true) .addField("Create At:", message.author.createdAt, true) message.channel.sendEmbed(embed); } }); client.on('message', function(msg) { if(msg.content.startsWith ('.server')) { let embed = new Discord.RichEmbed() .setColor('RANDOM') .setThumbnail(msg.guild.iconURL) .setTitle(`Showing Details Of **${msg.guild.name}*`) .addField('🌐** server type**',`[** __${msg.guild.region}__ **]`,true) .addField('🏅** __Roles__**',`[** __${msg.guild.roles.size}__ **]`,true) .addField('🔴**__ Members Number__**',`[** __${msg.guild.memberCount}__ **]`,true) .addField('🔵**__ Members Number who online__**',`[** __${msg.guild.members.filter(m=>m.presence.status == 'online').size}__ **]`,true) .addField('📝**__ Text Channels__**',`[** __${msg.guild.channels.filter(m => m.type === 'text').size}__** ]`,true) .addField('🎤**__ voice Channels__**',`[** __${msg.guild.channels.filter(m => m.type === 'voice').size}__ **]`,true) .addField('👑**__ The Owner__**',`**${msg.guild.owner}**`,true) .addField('🆔**__ Server ID__**',`**${msg.guild.id}**`,true) .addField('📅**__The date when the server created __**',msg.guild.createdAt.toLocaleString()) msg.channel.send({embed:embed}); } }); client.on('message', message => { var prefix ="." if(message.content.startsWith(prefix + "invites")) { message.guild.fetchInvites().then(invs => { let user = message.mentions.users.first() || message.author let personalInvites = invs.filter(i => i.inviter.id === user.id); let inviteCount = personalInvites.reduce((p, v) => v.uses + p, 0); let mmmmEmbed = new Discord.RichEmbed() .setAuthor(client.user.username) .setThumbnail(message.author.avatarURL) .addField(` لقد قمت بدعوة :`, ` ${inviteCount} `) .setFooter(`- Requested By: ${message.author.tag}`); message.channel.send(mmmmEmbed) }); } }); client.on('message' , message => { var prefix = "."; let user = message.mentions.users.first()|| client.users.get(message.content.split(' ')[1]) if(message.content.startsWith(prefix + 'unban')) { if(!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('❌|**\`ADMINISTRATOR\`لا توجد لديك رتبة`**'); if(!user) return message.channel.send(`Do this ${prefix} <@ID user> \n or \n ${prefix}unban ID user`); message.guild.unban(user); message.guild.owner.send(`لقد تم فك الباند عن الشخص \n ${user} \n By : <@${message.author.id}>`) var embed = new Discord.RichEmbed() .setThumbnail(message.author.avatarURl) .setColor("RANDOM") .setTitle('**●Unban** !') .addField('**●User Unban :** ', `${user}` , true) .addField('**●By :**' , ` <@${message.author.id}> ` , true) .setAuthor(message.guild.name) message.channel.sendEmbed(embed) } }); client.on('message' , async (message) => { var prefix = "."; if (message.content.startsWith(prefix + 'bot1')) { const os = require('os'); const arch = os.arch() const used = process.memoryUsage().heapUsed / 1024 / 1024; let totalSeconds = process.uptime(); let realTotalSecs = Math.floor(totalSeconds % 60); let days = Math.floor((totalSeconds % 31536000) / 86400); let hours = Math.floor((totalSeconds / 3600) % 24); let mins = Math.floor((totalSeconds / 60) % 60); var ping = client.ping message.channel.send(`\n= Memory usage: ${Math.round(used * 100) / 100}MB\n= Ping: ${ping}\n= Uptime: Days: ${days} | Hours: ${hours} | Minutes: ${mins} | Seconds: ${realTotalSecs}\n= Node: ${process.version}\n= Library: discord.js\n= ARCH: ${arch}\n= Plataform: ${os.platform}\n= Servers: ${client.guilds.size}\n= Users: ${client.users.size}`, { code: 'AsciiDoc' }) } }); client.on('message', message => { if (message.author.bot) return; var prefix ="." if (message.content === prefix + "help") { message.channel.send('**تم ارسال رسالة في الخاص**'); message.author.sendMessage(` ** ================================================================== ╔[❖════════════❖]╗ اوامر البوت ╚[❖════════════❖]╝ العاب ❖ .لو خيروك قريبا ـــــــــــــــــــ اوامر عامة ❖ .say | يتم تكرار لامك ولكن يبدو حسابك كبوت ❖ .ping | لمعرفة سرعة الاستجابة ~~❖ .credit | لمعرفة عدد الكريديت~~ ~~❖ .daily | الكريديت اليومي~~ ~~❖ .trans | تحويل الكريديت من شخص لاخر ~~ ❖ .invlink (bot mention) | بيعطيك رابط دعوة اي بوت ❖ .support | بيعطيك رابط سيرفر السبورت ❖ .inv | رابط دعوة البوت ❖ .bans | لمعرفة عدد الاشخاص المبندين من السيرفر ❖ .bot names | لاقتراح اسم بوت ❖ .avatar | لعرف صورة الشخص ❖ .bot | لعرض معلومات البوت ❖ .profile | لعرض معلومات الشخص ❖ .server | لعرض معلومات السيرفر ❖ .count | عرض عدد اعضاء السيرفر ❖ .id | اي دي العضو ❖ .invites | لمعرفة عدد الدعوات ~~❖ .top | ترتيب المتفاعلين في الصوت الكتابة ~~ ـــــــــــــــــــــ اوامر ادمنية ❖ .kick (mention) | لطرد شخص ❖ .ban (mention) | لتبنيد شخص ❖ .clear (number) | لحذف الشات مع رقم معلومة : لازم يكون بالسيرفر روم اسمه log ❖ .bc | البرودكاست ❖ .2bc | البرودكاست الثاني ❖ .move | لنقل عضو الى رومك الصوتي ❖ .ct | صنع روم كتابي ❖ .cv | صنع روم صوتي ❖ .osay | لجعل البوت يكرر ما تقول ❖ .unban | فك الباند ================================================================== ** `); } });
import { Component } from "../component"; export class Day extends Component { constructor(parentSelector, tagName, className, dayName = " ", dayNumber = " ", color) { super(parentSelector, tagName, className); this.dayName = dayName; this.dayNumber = dayNumber; this.weekend = false; this.vacation = false; this.color = color; this.labelName = new Component(this.component, "span", "outputDay"); this.labelNumber = new Component(this.component, "span", "outputDate"); } render() { super.render(); this.createCurrentLabel(); this.checkHeadClass(); this.isVacation(); } createCurrentLabel() { this.component.append(this.labelName.component); this.component.append(this.labelNumber.component); } setLabelName(dayName) { if (this.component.classList.contains("weekend")) { this.component.classList.remove("weekend"); } if (this.component.classList.contains("headerDay")) { this.labelName.component.textContent = dayName; } this.dayName = dayName; this.isWeekend(); this.isVacation(); } setLabelNumber(dayNumber) { this.labelNumber.component.append(dayNumber); } hideComponent() { this.component.classList.add("close-item"); } showComponent() { this.component.classList.remove("close-item"); } isWeekend() { if (this.dayName === "Sa" || this.dayName === "Su") { this.component.classList.add("weekend"); this.weekend = true; } } isVacation() { if (this.vacation) { this.component.classList.add(`vacation`); this.component.classList.add(`${this.color}`); this.vacation = true; } else { this.component.classList.remove(`vacation`); this.component.classList.remove(`${this.color}`); } } checkHeadClass() { if (this.component.classList.contains("headerDay")) { this.setLabelName(this.dayName); this.setLabelNumber(this.dayNumber); } } }
export function countsAsAYes(input) { return (input[0] === 'y' || input[0] === 'Y'); }
'use strict'; var should = require('should'), mongoose = require('mongoose'), Toon = require('../models/toon'); var toon; mongoose.connect('mongodb://localhost/tooner-test'); describe('Toon Model Unit Tests:', function() { beforeEach(function(done) { toon = new Toon({ buildTitle: 'Toon Title', }); done(); }); describe('Method Save', function() { it('should be able to save without problems', function(done) { return toon.save(function(err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without buildTitle', function(done) { toon.buildTitle = ''; return toon.save(function(err) { should.exist(err); done(); }); }); }); afterEach(function(done) { Toon.remove().exec(); done(); }); });
const jwt = require('jsonwebtoken'); const redis = require("redis"); function readAppel(req, res) { if (req.session.logged) { const token = req.header('Authorization').replace('Bearer ', ''); try { const payload = jwt.verify(token, process.env.JWT_SECRET) console.log(payload._id) const client = redis.createClient(); client.on("error", function (error) { console.error(error); }); client.exists(token, function (err, reply) { if (err) throw err; if (reply == 0) { client.incr(token, redis.print); client.expire(token, 600); // 600 : 10 min res.status(200).json({ msg: "Appel" }); } else { client.incr(token, redis.print); client.get(token, function (err, cpt) { if (err) throw err; if (!(cpt > 10)) { res.status(200).json({ msg: "Appel" }); } else { res.status(400).json({ msg: "please wait 10 min" }); } }) } }) } catch (error) { console.error(error.message); res.status(400).json({ msg: "unauthorized access" }); } } else { res.status(400).json({ msg: "please sign in" }); } } module.exports.readAppel = readAppel;
// @flow import { combineReducers } from 'redux'; import { handleActions } from 'redux-actions'; import _ from 'lodash'; import * as actions from '../actions'; import type { Pokemon, PokemonNames, ComparablePokemon } from '../types/pokemons'; const pokemonNamesFetchingState = handleActions({ [actions.fetchPokemonNamesRequest]() { return 'requested'; }, [actions.fetchPokemonNamesFailure]() { return 'failed'; }, [actions.fetchPokemonNamesSuccess]() { return 'succeeded'; }, }, 'none'); const pokemonNames = handleActions(new Map( [ [ actions.fetchPokemonNamesSuccess, (state: PokemonNames, action: { payload: { pokemonNames: PokemonNames } }) => action.payload.pokemonNames, ], ], ), []); const pokemonsFetchingState = handleActions({ [actions.fetchPokemonsRequest]() { return 'requested'; }, [actions.fetchPokemonsFailure]() { return 'failed'; }, [actions.fetchPokemonsSuccess]() { return 'succeeded'; }, [actions.changePage]() { return 'requested'; }, [actions.changeItemsCountPerPage]() { return 'requested'; }, }, 'none'); const pokemons = handleActions(new Map( [ [ actions.fetchPokemonsSuccess, (state, action: { payload: { pokemons: Array<Pokemon> } }) => action.payload.pokemons, ], [ actions.changePage, () => [], ], [ actions.changeItemsCountPerPage, () => [], ], ], ), []); export const optionsDropdown = [ { key: 1, text: '5 rows', value: 5 }, { key: 2, text: '10 rows', value: 10 }, { key: 3, text: '15 rows', value: 15 }, { key: 4, text: '20 rows', value: 20 }, ]; export const evalTotalPages = (itemsCountPerPage: number, pokemonsCount: number): number => Math.ceil(pokemonsCount / itemsCountPerPage); export const evalStartIndex = (itemsCountPerPage: number, activePage: number): number => itemsCountPerPage * (activePage - 1); const pokemonListUIState = handleActions(new Map( [ [ actions.fetchPokemonNamesSuccess, (state, action: { payload: { pokemonNames: PokemonNames } }) => { const newTotalPages = evalTotalPages(state.itemsCountPerPage, action.payload.pokemonNames.length); return { ...state, totalPages: newTotalPages, pokemonsCount: action.payload.pokemonNames.length }; }, ], [ actions.changePage, (state, action: { payload: { page: number } }) => { const newStartIndex = evalStartIndex(state.itemsCountPerPage, action.payload.page); return { ...state, startIndex: newStartIndex, activePage: action.payload.page }; }, ], [ actions.changeItemsCountPerPage, (state, action: { payload: { itemsCountPerPage: number } }) => { const newTotalPages = evalTotalPages(action.payload.itemsCountPerPage, state.pokemonsCount); return { ...state, totalPages: newTotalPages, itemsCountPerPage: action.payload.itemsCountPerPage, activePage: 1, startIndex: 0, }; }, ], ], ), { pokemonsCount: 0, activePage: 1, totalPages: 0, startIndex: 0, itemsCountPerPage: optionsDropdown[1].value, optionsDropdown, }); const pokemonsToCompare = handleActions(new Map( [ [ actions.addPokemonToCompare, (state, action: { payload: { pokemon: Pokemon, index: number } }) => ({ ...state, [action.payload.pokemon.name]: action.payload }), ], [ actions.deletePokemonFromComparison, (state, action: { payload: ComparablePokemon }) => _.omit(state, action.payload.pokemon.name), ], ], ), {}); const pokedexUIState = handleActions(new Map( [ [ actions.addPokemonToCompare, state => ({ pokemonsCountToCompare: state.pokemonsCountToCompare + 1 }), ], [ actions.deletePokemonFromComparison, state => ({ pokemonsCountToCompare: state.pokemonsCountToCompare - 1 }), ], ], ), { pokemonsCountToCompare: 0 }); export default combineReducers({ pokemonNamesFetchingState, pokemonNames, pokemons, pokemonsFetchingState, pokemonListUIState, pokemonsToCompare, pokedexUIState, });
import React, { Component } from 'react'; import { inject, observer } from 'mobx-react'; import { getUserInfo, getPersonalInfo } from '@common/api'; import Nav from '../../components/nav/index'; import UserInfos from './components/userInfos/index'; import FavoriteList from './components/favoriteList/index'; import Footer from '../../components/footer/index'; import Style from './index.module.less'; @inject('rootStore') @observer class AboutDetail extends Component { state = { userInfo: {}, hasFollow: false, isSelf: true, }; componentDidMount() { getUserInfo({ userId: this.props.match.params.userId ? this.props.match.params.userId : null }).then(response => { this.setState({ userInfo: response.data, }); }).catch(error => { console.log(error); }); this.initBaseData(); } initBaseData = () => { getPersonalInfo({ userId: this.props.match.params.userId ? this.props.match.params.userId : null }).then(response => { let { isSelf, hasFollow } = response.data; this.props.rootStore.dataStore.savePersonalInfo(response.data); this.setState({ isSelf, hasFollow, }); }).catch(error => { console.log(error); }) }; toggleFollowStatus = () => { this.setState({ hasFollow: !this.state.hasFollow, }); }; render() { let { topic, fansCounts, followCounts } = this.props.rootStore.dataStore.personalInfo; let { isSelf, hasFollow, userInfo } = this.state; return ( <main> <Nav /> <div className="page-container"> <div className={Style['personal-about']}> <UserInfos isSelf={isSelf} hasFollow={hasFollow} toggleFollowStatus={this.toggleFollowStatus} userInfo={userInfo} personalInfo={ { topicCounts: topic.counts, fansCounts, followCounts, } } /> <FavoriteList topicList={topic.topicList} topicCollectList={topic.topicCollectList} /> <Footer /> </div> </div> </main> ); } } export default AboutDetail;
const mathLibrary = { calculateProduct(...rest) { console.log("please use the multiply method instead"); console.log( this.multiply(...rest) ); return this.multiply(...rest); }, multiply(a,b) { return a*b; } }; const result = mathLibrary.calculateProduct(2,3);
import React from "react"; import PropTypes from "prop-types"; import ReactSVG from 'react-svg' import styles from "./styles.module.scss"; import { Grid, Image, } from "semantic-ui-react"; import _ from "lodash"; import ModelInfoModal from "./../ModelInfoModal"; import { TABLE_TYPE, COUNTRY } from "../../config/constants" const ModelTable = (props, context) => ( <div className={styles.RootDivision}> { (props.tableType === TABLE_TYPE.TYPE_A) ? ( <div className={styles.ModelListTypeADivision}> <RenderModelListTypeA model_list={props.model_list} handleOnClick={props.handleOnClick} /> </div> ) : ( <div className={styles.ModelListTypeBDivision}> <RenderModelListTypeB model_list={props.model_list} handleOnClick={props.handleOnClick} /> </div> ) } <ModelInfoModal visible={props.visibleModelInfoModal} handleClose={props.handleCloseModelInfoModal} modelId={props.selectedModelId} /> </div> ) const RenderModelListTypeA = (props, context) => { if (props.model_list === null || props.model_list === undefined || props.model_list.length === 0) { return ( <div className={styles.EmptyDivision}> <p className={styles.Text}>{context.t("등록된 컨텐츠가 아직 없습니다.")}</p> </div> ) } else { return ( <Grid className={styles.ModelGrid}> <Grid.Row className={styles.ModelRow}> { _.map(props.model_list, (t, index) => { return ( <Grid.Column key={index} className={styles.ModelColumn} onClick={() => { props.handleOnClick(t)} } > <RenderCoverImage cover_image_custom={t.cover_image_custom } cover_image={t.cover_image } /> <p className={styles.ModelNameText}>{t.nickname}</p> </Grid.Column> ) }) } </Grid.Row> </Grid> ) } } const RenderModelListTypeB = (props, context) => { if (props.model_list === null || props.model_list === undefined || props.model_list.length === 0) { return ( <div className={styles.EmptyDivision}> <p className={styles.Text}>{context.t("등록된 컨텐츠가 아직 없습니다.")}</p> </div> ) } else { return ( _.map(props.model_list, (t, index) => { return ( <div className={styles.ModelDivision} key={index}> <div className={styles.ListNumberDivision}> <p>{index+1}</p> </div> <div className={styles.CoverImageDivision}> { <RenderCoverImage cover_image_custom={t.cover_image_custom } cover_image={t.cover_image } /> } </div> <div className={styles.TitleDivision}> <p className={styles.DescriptionText}>{context.t("NAME")}</p> <p className={styles.Text}>{t.nickname}</p> </div> <div className={styles.DividerDivision}> </div> <div className={styles.CountryDivision}> <p className={styles.DescriptionText}>{context.t("COUNTRY")}</p> <RenderCountry country={t.country} /> </div> <div className={styles.HeartDivision}> <ReactSVG src={require("images/icons/svg/heart_outline_icon.svg")} svgClassName='HeartIcon' className={styles.HeartIcon} /> <p className={styles.Text}>{t.like_count}</p> </div> <div className={styles.CheckInfoDivision}> <p className={styles.DescriptionText}>{context.t("CHECK INFO")}</p> </div> <RenderShowAllBtn {...props} model={t}/> <div className={styles.RankingDivision}> <Image className={styles.RankingIcon} /> <ReactSVG src={require("images/icons/svg/arrow_state_icon.svg")} svgClassName='RankingIcon' className={styles.RankingIcon} /> </div> </div> ) }) ) } } const RenderShowAllBtn = (props, context) => { return ( <div className={styles.PriceIconDivision} onClick={() => { props.handleOnClick(props.model)} } > <div className={styles.HoverDivision}> <p className={styles.PriceText}>{context.t("10 GEM")}</p> </div> <div className={styles.NomalDivision}> <p className={styles.PriceText}>{context.t("SHOW ALL")}</p> </div> </div> ) } const RenderCountry = (props) => { return ( COUNTRY.map((t, index) => { if (t.id === props.country) { return <p key={index} className={styles.Text}>{t.text}</p> } else { return null; } }) ) } const RenderCoverImage = (props) => { if (props.cover_image_custom === null || props.cover_image_custom === undefined) { if (props.cover_image === null || props.cover_image === undefined) { return null } else { return ( <div className={styles.ImageDivision}> <Image src= {`${props.cover_image.file}`} className={styles.ModelCoverImage} alt="model cover image" /> </div> ) } } else { return ( <div className={styles.ImageDivision}> <Image src= {`${props.cover_image_custom }`} size="small" className={styles.ModelCoverImage} alt="model cover image" /> </div> ) } } ModelTable.propTypes = { model_list: PropTypes.array, tableType: PropTypes.string.isRequired, handleOnClick: PropTypes.func.isRequired, visibleModelInfoModal: PropTypes.bool.isRequired, handleCloseModelInfoModal: PropTypes.func.isRequired, selectedModelId: PropTypes.number, } ModelTable.contextTypes = { t: PropTypes.func.isRequired }; RenderModelListTypeA.contextTypes = { t: PropTypes.func.isRequired }; RenderModelListTypeB.contextTypes = { t: PropTypes.func.isRequired }; RenderShowAllBtn.contextTypes = { t: PropTypes.func.isRequired }; export default ModelTable;
import { Container, Row, Col } from 'reactstrap'; import style from './priceComparisonTable.scss'; export default () => ( <div className="priceComparisonTable"> <Container> <Row className="pctHeader align-items-center"> <Col md={{ size: 3, offset: 6 }} xs={6} sm={6} className="pcTableLogo"> <img src="/static/images/coveTeal.png" className="pcTableLogoStyle" alt="cove logo" /> </Col> <Col md={3} xs={6} sm={6} > <h2>Them</h2> </Col> </Row> <div className="tableRows"> <Row className="firstRow"> <Col xs={12} sm={12} md={6} className="pcTableColLeft"> Long term contracts </Col> <Col xs={6} sm={6} md={3} className="pcTableColMid"> Not our style </Col> <Col xs={6} sm={6} md={3} className="pcTableColRight"> 3-5 years </Col> </Row> <Row> <Col xs={12} md={6} className="pcTableColLeft"> Monthly monitoring </Col> <Col xs={6} md={3} className="pcTableColMid"> $19.99/mo </Col> <Col xs={6} md={3} className="pcTableColRight"> $44.99/mo </Col> </Row> <Row> <Col xs={12} md={6} className="pcTableColLeft titlePadding"> Cancellation fees </Col> <Col xs={6} md={3} className="pcTableColMid titlePadding"> None </Col> <Col xs={6} md={3} className="pcTableColRight"> High as $2000 <p style={{ fontSize: '12px', fontWeight: '300' }}> Crazy, we know! </p> </Col> </Row> <Row> <Col xs={12} md={6} className="pcTableColLeft"> Service windows </Col> <Col xs={6} md={3} className="pcTableColMid"> None </Col> <Col xs={6} md={3} className="pcTableColRight"> 1 - 3 weeks </Col> </Row> <Row className="lastRow"> <Col xs={12} md={6} className="pcTableColLeft titlePadding"> Warranty </Col> <Col xs={6} md={3} className="pcTableColMid titlePadding"> 3 years </Col> <Col xs={6} md={3} className="pcTableColRight"> 3 years<br /> $45 service calls </Col> </Row> </div> </Container> <style jsx global>{style}</style> </div> );
(function(w) { 'use strict'; var $document = w.document.documentElement, objects = [], $body = w.document.getElementsByTagName('body')[0], screenHeight = 0, updateScreenHeight = function() { screenHeight = w.innerHeight || $document.clientHeight || $body.clientHeight; updateScrolledObjects(); }, lastScrolledTime = new Date().getTime(), scrollFramerate = 1000 / 25, updateScrolledObjects = function() { objects.map(function(o) { var newInView = null, elementClientRects = o.element.getClientRects(); if (elementClientRects.length > 0) { elementClientRects = elementClientRects[0]; o.top = Math.round(elementClientRects.top - (screenHeight * o.origin)); o.bottom = Math.round(elementClientRects.bottom - (screenHeight * o.origin)); if (o.top > 0) { // Comming: Distance of top border from middle is > 0 newInView = -1; } else if (o.bottom < 0) { // Was: Distance of bottom border from middle is < 0 newInView = 1; } else { // In view newInView = 0; } // Change if (o.inView !== newInView) { // > +1 FORWARD // < -1 BACKWARD if (newInView === -1) { o.before(); } else if (newInView === 0) { o.during(); } else { o.after(); } } // Commit o.inView = newInView; } }); }, noop = function() {}, throttledScroll = function throttledScroll() { var scrolledTime = new Date().getTime(); if (scrolledTime - lastScrolledTime > scrollFramerate) { lastScrolledTime = scrolledTime; updateScrolledObjects(); } }; w.addScrollingTriggers = function(triggers) { if (Object.prototype.toString.call(triggers) !== '[object Array]') { if (w.console) { w.console.warn('`triggers` must be an array', triggers); } return; } triggers = triggers.filter(function(v) { return typeof v === 'object' && Object.prototype.toString.call(v) !== '[object Array]'; }).map(function(v) { if (v.el instanceof Element) { var el = v.el; } else { var el = w.document.getElementById(v.el); } if (el) { objects.push({ element: el, inView: null, // -1: not yet in view, 0: in view, 1: was in view top: null, bottom: null, before: v.before && typeof v.before === 'function' ? v.before : noop, during: v.during && typeof v.during === 'function' ? v.during : noop, after: v.after && typeof v.after === 'function' ? v.after : noop, origin: (v.origin || v.origin === 0) && v.origin >= 0 && v.origin <= 1 ? v.origin : 0.5 }); } return v; }); updateScreenHeight(); updateScrolledObjects(); }; w.setScrollingTriggersFramerate = function setScrollingTriggersFramerate(newScrollFramerate) { if (newScrollFramerate > 1000 / 10 && newScrollFramerate <= 1000 / 60) { scrollFramerate = newScrollFramerate; } }; w.addEventListener('resize', updateScreenHeight); w.addEventListener('scroll', throttledScroll); }(window));
import { Book } from '../model/book.js'; export const addBook = async (req, res) => { const { title, author, publishedYear } = req.body try { const newBook = new Book({ title, author, publishedYear }) const dbResponse = await newBook.save() if(dbResponse) { return res.status(200).json({ status: 'Success', message: 'Book saved!', data: dbResponse }) } else { return res.status(500).json({ status: 'fail', message: 'Opps!! something went wrong' }) } } catch (err) { console.log(err) } } export const getBooksController = async (req, res) => { try { const getBooks = await Book.find() if(getBooks) { return res.status(200).json({ status: 'Success', data: getBooks }) } } catch (err) { console.log(err) return res.status(500).json({ status: 'Opps! something went wrong', err }) } } export const updateBookController = async(req, res) => { const { bookId } = req.params const {title, author, publishedYear} = req.body const updatedBook = { title, author, publishedYear } try { const updateDb = await Book.findByIdAndUpdate(bookId, {$set: updatedBook}) if(updateDb) { return res.status(200).json({ status: 'Updated successfully' }) } } catch (err) { console.log(err) return res.status(500).json({ status: 'Failed', message: 'Something went wrong', err }) } } export const deleteBook = async(req, res) => { const { bookId } = req.params try { const removeBook = await Book.findByIdAndRemove(bookId) if(removeBook) { return res.status(200).json({ status: 'Success', message: 'Deleted successfuly'}) } } catch (err) { console.log(err) res.status(500).json({status: 'Failed', message: 'An error occured', err }) } }
import React, { useContext, useState } from 'react'; import { Text, View, TouchableWithoutFeedback, Keyboard, KeyboardAvoidingView } from 'react-native'; import { Button, Snackbar } from 'react-native-paper'; import firebase from './config'; import { AppContext } from './AppContext'; import Input from './Input'; import styles from './Styles'; const RegistrationScreen = ({ navigation }) => { const { register, email, setEmail, password, setPassword, visibleSnackbarRegistr, setVisibleSnackbarRegistr, errorInput, setErrorInput, confirmPassword, setConfirmPassword } = useContext(AppContext); const [nameText, setNameText] = useState(''); const clearForm = () => { setNameText(''); setEmail(''); setPassword(''); }; const onToggleSnackBar = () => { setVisibleSnackbarRegistr(!visibleSnackbarRegistr); }; const onSignUpPress = () => { firebase .auth() .createUserWithEmailAndPassword(email, password) .then(() => { register(nameText), clearForm(); navigation.navigate('Form'); }) .catch((e) => { setErrorInput('Podany email już istnieje'); setVisibleSnackbarRegistr(true); }); }; const arrRegistration = [ { label: 'Imię', keyboardType: 'default', value: nameText, onChangeText: (text) => setNameText(text) }, { label: 'Email', keyboardType: 'email-address', onChangeText: (email) => setEmail(email) }, { label: 'Hasło', keyboardType: 'default', secureTextEntry: true, onChangeText: (password) => setPassword(password) }, { label: 'Potwierdź hasło', keyboardType: 'default', secureTextEntry: true, onChangeText: (confirmPassword) => setConfirmPassword(confirmPassword) } ]; const handleFormRegister = () => { if (nameText === '') { setErrorInput('Podaj imię'); onToggleSnackBar(); } else if (password !== confirmPassword) { setErrorInput('Hasła się różnią'); onToggleSnackBar(); } else if (email === '') { setErrorInput('Podaj email'); onToggleSnackBar(); } else if (password === '' && confirmPassword === '') { setErrorInput('Podaj hasło'); onToggleSnackBar(); } else if (password.length < 6 || confirmPassword.length < 6) { setErrorInput('Hasło powinno składać się z conajmniej 6 znaków'); onToggleSnackBar(); } else { onSignUpPress(); } }; return ( <KeyboardAvoidingView behavior={Platform.OS == 'ios' ? 'padding' : 'height'} style={{ flex: 1 }} > <TouchableWithoutFeedback onPress={() => { Keyboard.dismiss(); }} > <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }} > <Text style={{ fontSize: 32, color: 'white', opacity: 0.9, bottom: 10 }} > Create an account </Text> {arrRegistration.map((item) => { return ( <Input key={item.label} label={item.label} value={item.value} onChangeText={item.onChangeText} keyboardType={item.keyboardType} secureTextEntry={item.secureTextEntry} /> ); })} <View style={{ flexDirection: 'row', top: 10 }}> <Button onPress={() => { navigation.navigate('LogIn'); }} style={[styles.button, { width: '30%', margin: 10 }]} color='#5b2a83' labelStyle={{ fontSize: 16 }} > Back </Button> <Button onPress={() => { handleFormRegister(); }} style={[styles.button, { width: '30%', margin: 10 }]} color='#5b2a83' labelStyle={{ fontSize: 16 }} > Next </Button> </View> <Snackbar visible={visibleSnackbarRegistr} onDismiss={() => setVisibleSnackbarRegistr(!visibleSnackbarRegistr)} action={{ label: 'OK', onPress: () => { setVisibleSnackbarRegistr(!visibleSnackbarRegistr); } }} > {errorInput} </Snackbar> </View> </TouchableWithoutFeedback> </KeyboardAvoidingView> ); }; export default RegistrationScreen;