hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
73e2dd1065e18f4e6463870f930f9b59153a24ef
603
js
JavaScript
src/languages-to-json-ast/java/models/enhanced-for-statement.js
FabienBrisset/genese-complexity
2e36316f8444c6808debe251700e04c0143d3887
[ "MIT" ]
3
2020-11-19T14:24:44.000Z
2021-05-26T02:46:09.000Z
src/languages-to-json-ast/java/models/enhanced-for-statement.js
FabienBrisset/genese-complexity
2e36316f8444c6808debe251700e04c0143d3887
[ "MIT" ]
2
2021-01-30T11:41:02.000Z
2021-05-25T15:18:37.000Z
src/languages-to-json-ast/java/models/enhanced-for-statement.js
FabienBrisset/genese-complexity
2e36316f8444c6808debe251700e04c0143d3887
[ "MIT" ]
1
2020-11-24T16:05:17.000Z
2020-11-24T16:05:17.000Z
"use strict"; exports.__esModule = true; exports.EnhancedForStatement = void 0; var location_model_1 = require("./location.model"); var enhanced_for_statement_children_model_1 = require("./enhanced-for-statement-children.model"); var EnhancedForStatement = /** @class */ (function () { function EnhancedForStatement() { this.name = ''; this.children = new enhanced_for_statement_children_model_1.EnhancedForStatementChildren(); this.location = new location_model_1.Location(); } return EnhancedForStatement; }()); exports.EnhancedForStatement = EnhancedForStatement;
40.2
99
0.74461
73e2f03f9f157d35c0f90363e5c55448f375e2a8
203
js
JavaScript
NN_Essences/newstx.js
KLYN74R/NewNews
4200efd76210b00f6882ac2ce7f1c28debf9a6c7
[ "Apache-2.0" ]
3
2022-01-14T09:31:41.000Z
2022-01-15T17:40:20.000Z
NN_Essences/newstx.js
KLYN74R/NewNews
4200efd76210b00f6882ac2ce7f1c28debf9a6c7
[ "Apache-2.0" ]
null
null
null
NN_Essences/newstx.js
KLYN74R/NewNews
4200efd76210b00f6882ac2ce7f1c28debf9a6c7
[ "Apache-2.0" ]
null
null
null
export default class{ constructor(sender,newsHash,nonce){ this.c=sender this.h=newsHash this.n=nonce //this.s=SIG(newshash+chain+nonce,prv) } }
16.916667
46
0.546798
73e338d478e91fbe6459beb5d0c292c621c19d59
2,448
js
JavaScript
src/components/icons/settings.js
medmanager/frontend
1765abc461bd74197693343d6641556c5e44d539
[ "MIT" ]
null
null
null
src/components/icons/settings.js
medmanager/frontend
1765abc461bd74197693343d6641556c5e44d539
[ "MIT" ]
48
2021-02-01T15:29:28.000Z
2021-08-31T19:55:18.000Z
src/components/icons/settings.js
medmanager/frontend
1765abc461bd74197693343d6641556c5e44d539
[ "MIT" ]
null
null
null
import React from 'react'; import Svg, { Path } from 'react-native-svg'; const SettingsIcon = ({ color = 'black', focused }) => ( <Svg fill={focused ? 'rgba(47, 128, 237, 0.25)' : null} stroke={color} width="24" height="24" viewBox="0 0 24 24"> <Path fillRule="evenodd" clipRule="evenodd" d="M8.325 2.317C8.751 0.561 11.249 0.561 11.675 2.317C11.7389 2.5808 11.8642 2.82578 12.0407 3.032C12.2172 3.23822 12.4399 3.39985 12.6907 3.50375C12.9414 3.60764 13.2132 3.65085 13.4838 3.62987C13.7544 3.60889 14.0162 3.5243 14.248 3.383C15.791 2.443 17.558 4.209 16.618 5.753C16.4769 5.98466 16.3924 6.24634 16.3715 6.51677C16.3506 6.78721 16.3938 7.05877 16.4975 7.30938C16.6013 7.55999 16.7627 7.78258 16.9687 7.95905C17.1747 8.13553 17.4194 8.26091 17.683 8.325C19.439 8.751 19.439 11.249 17.683 11.675C17.4192 11.7389 17.1742 11.8642 16.968 12.0407C16.7618 12.2172 16.6001 12.4399 16.4963 12.6907C16.3924 12.9414 16.3491 13.2132 16.3701 13.4838C16.3911 13.7544 16.4757 14.0162 16.617 14.248C17.557 15.791 15.791 17.558 14.247 16.618C14.0153 16.4769 13.7537 16.3924 13.4832 16.3715C13.2128 16.3506 12.9412 16.3938 12.6906 16.4975C12.44 16.6013 12.2174 16.7627 12.0409 16.9687C11.8645 17.1747 11.7391 17.4194 11.675 17.683C11.249 19.439 8.751 19.439 8.325 17.683C8.26108 17.4192 8.13578 17.1742 7.95929 16.968C7.7828 16.7618 7.56011 16.6001 7.30935 16.4963C7.05859 16.3924 6.78683 16.3491 6.51621 16.3701C6.24559 16.3911 5.98375 16.4757 5.752 16.617C4.209 17.557 2.442 15.791 3.382 14.247C3.5231 14.0153 3.60755 13.7537 3.62848 13.4832C3.64942 13.2128 3.60624 12.9412 3.50247 12.6906C3.3987 12.44 3.23726 12.2174 3.03127 12.0409C2.82529 11.8645 2.58056 11.7391 2.317 11.675C0.561 11.249 0.561 8.751 2.317 8.325C2.5808 8.26108 2.82578 8.13578 3.032 7.95929C3.23822 7.7828 3.39985 7.56011 3.50375 7.30935C3.60764 7.05859 3.65085 6.78683 3.62987 6.51621C3.60889 6.24559 3.5243 5.98375 3.383 5.752C2.443 4.209 4.209 2.442 5.753 3.382C6.749 3.99 8.049 3.452 8.325 2.317ZM12.1213 12.1213C12.6839 11.5587 13 10.7956 13 10C13 9.20435 12.6839 8.44129 12.1213 7.87868C11.5587 7.31607 10.7956 7 10 7C9.20435 7 8.44129 7.31607 7.87868 7.87868C7.31607 8.44129 7 9.20435 7 10C7 10.7956 7.31607 11.5587 7.87868 12.1213C8.44129 12.6839 9.20435 13 10 13C10.7956 13 11.5587 12.6839 12.1213 12.1213Z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /> </Svg> ); export default SettingsIcon;
106.434783
1,991
0.720997
73e3f148c9712fdd422432e17a9fe040afff4fd8
1,282
js
JavaScript
doxygen/a00104.js
mmattamala/gtsam.org
2e399d939170cbb169346b9e0b3d105bd6db1dd5
[ "MIT" ]
3
2019-08-03T19:56:35.000Z
2020-10-19T21:29:15.000Z
doxygen/a00104.js
mmattamala/gtsam.org
2e399d939170cbb169346b9e0b3d105bd6db1dd5
[ "MIT" ]
25
2019-05-22T03:46:11.000Z
2022-01-30T19:15:26.000Z
doxygen/a00104.js
mmattamala/gtsam.org
2e399d939170cbb169346b9e0b3d105bd6db1dd5
[ "MIT" ]
13
2019-05-24T13:03:24.000Z
2021-01-26T20:31:26.000Z
var a00104 = [ [ "assert_container_equal", "a00104.html#a2f509195ea2180d0f7dbd3a99a088ff4", null ], [ "assert_container_equal", "a00104.html#a254be27d6d4b416fa2b546c77ae783fc", null ], [ "assert_container_equal", "a00104.html#a0eec17f894b358dd9f30d7af28082ba5", null ], [ "assert_container_equal", "a00104.html#a6d6b2964354593f69848f6bf5d3e0ca1", null ], [ "assert_container_equality", "a00104.html#a59ba6a7db27344c5cb021f1421905020", null ], [ "assert_container_equality", "a00104.html#aa0926a5d779171bd8e1d30fb5982b5c0", null ], [ "assert_equal", "a00104.html#add6d6575582314cc9b5dbdbe2a86374d", null ], [ "assert_equal", "a00104.html#a982034802415eb6e9bd02355257ed96a", null ], [ "assert_equal", "a00104.html#a21e760bc75888053afd86a27d56b6148", null ], [ "assert_equal", "a00104.html#a0931276a9406dfc1bcff6d265704ee39", null ], [ "assert_equal", "a00104.html#a5242be27f83219abc3f9793975986a35", null ], [ "assert_equal", "a00104.html#abb156f7b9ac630cc6fd956b386cf1dab", null ], [ "assert_inequal", "a00104.html#a2f19ba6625a264457805513fefcb5c32", null ], [ "assert_print_equal", "a00104.html#aac8275b9ce53036f2b3ca6fc68f19d07", null ], [ "assert_stdout_equal", "a00104.html#a08641f0f7145716bba9159dd95099a44", null ] ];
71.222222
91
0.76053
73e45a1798c8346515b5bc809e0df2635e79bea2
1,336
js
JavaScript
template/gulp-tasks/copy.js
digiBlink/vue-loopback
58448b7560cfb98f4a405d5254e2e6fa71d8951d
[ "MIT" ]
null
null
null
template/gulp-tasks/copy.js
digiBlink/vue-loopback
58448b7560cfb98f4a405d5254e2e6fa71d8951d
[ "MIT" ]
null
null
null
template/gulp-tasks/copy.js
digiBlink/vue-loopback
58448b7560cfb98f4a405d5254e2e6fa71d8951d
[ "MIT" ]
null
null
null
/* eslint-disable arrow-body-style */ import gulp from 'gulp'; import path from 'path'; import fs from 'fs'; import {argv} from 'yargs'; import {dirs} from './config'; import production from '../server/config.production.json'; gulp.task('copy:client:fa', () => { return gulp .src(path.resolve(dirs.modules, 'font-awesome/fonts/*')) .pipe(gulp.dest(path.resolve(dirs.buildClient, 'static/fonts'))); }); gulp.task('copy:client', ['copy:client:fa'], () => { return gulp .src(`${dirs.srcClient}/**/!(*.vue|*.js)`) .pipe(gulp.dest(path.resolve(dirs.buildClient))); }); gulp.task('copy:package', () => { return gulp.src(`${dirs.root}/package.json`) .pipe(gulp.dest(path.resolve(dirs.build))); }); gulp.task('copy:server', () => { return gulp.src(`${dirs.srcServer}/**/*.json`) .pipe(gulp.dest(path.resolve(dirs.buildServer))); }); gulp.task('copy:config:server', ['copy:server'], (done) => { if (argv.production) { const configPath = path.resolve( dirs.srcServer, 'config.json' ); fs.readFile(configPath, (err, data) => { if (err) done(err); fs.writeFile( path.resolve(dirs.buildServer, 'config.json'), JSON.stringify({ ...JSON.parse(data), ...production, }), done ); }); } else { done(); } });
24.740741
69
0.589072
73e52799052e69c93ff475be603c0fdcf7c7bed0
5,694
js
JavaScript
assets/js/raspisanie.js
AzamatChynasylov/code-example
7bae448e9f8f5179f4f32f03e3243b89b48f2890
[ "MIT" ]
null
null
null
assets/js/raspisanie.js
AzamatChynasylov/code-example
7bae448e9f8f5179f4f32f03e3243b89b48f2890
[ "MIT" ]
null
null
null
assets/js/raspisanie.js
AzamatChynasylov/code-example
7bae448e9f8f5179f4f32f03e3243b89b48f2890
[ "MIT" ]
null
null
null
// $(document).ready(function(){ // var kol_sp=0; // var n_gr=0; // var n_t=0; // for (var j = 1;j < 11; j++) // { // for (var i = 0; i <6; i++) // { // $.each($('#p'+j+i+' p'), function() { // kol_sp++; // }); // //alert(kol_sp); // if(kol_sp>0) // { // for (var i1 = 0; i1 < kol_sp; i1++) // { // $("#p"+j+i+" p:nth-child("+(i1+1)+") input").val(); // n_gr=$("#p"+j+i+" p:nth-child("+(i1+1)+")").attr('class'); // n_t=$("#p"+j+i+" p:nth-child("+(i1+1)+") span").attr('class'); // //alert($("#p1"+i+" p:nth-child("+(i1+1)+")").attr('class')); // $("#g"+j+i+" option:nth-child("+(parseInt(n_gr)+1)+")").hide(); // $("#t"+j+i+" option:nth-child("+(parseInt(n_t)+1)+")").hide(); // }; // } // n_gr=0; // n_t=0; // kol_sp=0; // }; // }; // }); // $(document).ready(function(){ // var kol_p=0; // var id_b=0; // $("img").on("click", function(){ // //alert('ok'); // var id=$(this).attr("id"); // id_b=id; // var gruppa= $('#g'+id).val(); // var teacher= $('#t'+id).val(); // var kol_p1=0; // var kol_vnutri_div=0; // if(gruppa=='' || teacher=='') // { // return false; // } // else // { // kol_p++; // var indexoption =$("#t"+id+" option:selected").index(); // var indexoption_g =$("#g"+id+" option:selected").index(); // //alert(indexoption_g); // $.each($('#p'+id+' p'), function() { // kol_p1++ // }); // //$( '#p'+id ).append("<p id="+kol_p+" class="+indexoption_g+" name='"+'p'+id+kol_p+"'><i id="+kol_p1+"></i><input class='dobavok' type='text' value='"+gruppa+"'><b>"+teacher+"</b><span id="+kol_p+" class="+indexoption+">X</span></p>"); // $("#t"+id+" :selected").hide(); // $("#g"+id+" :selected").hide(); // $("select#t"+id).prop('selectedIndex',0); // $('select#g'+id).prop('selectedIndex',0); // $.each($('#p'+id+' p'), function() { // kol_vnutri_div++; // }); // // alert(kol_vnutri_div); // $( '#p'+id ).append("<p class="+indexoption_g+" name='"+'p'+id+(kol_vnutri_div)+"'><input class='dobavok' type='text' value='"+gruppa+"'><b>"+teacher+"</b><span id='"+id+"' class="+indexoption+" name="+'p'+id+kol_vnutri_div+">X</span></p>"); // } // return false; // }); // $('body').on("click",'span',function(){ // var id=$(this).attr("id"); // var name=$(this).attr("name"); // var class_nomer=$(this).attr("class"); // var p_classnomer=$('p[name ='+name+' ]').attr("class"); // //alert('aza'); // class_nomer=parseInt(class_nomer)+1; // p_classnomer=parseInt(p_classnomer)+1; // //$("#t"+id+" option:nth-child("+class_nomer+")").show(); // //$("#g"+id+" option:nth-child("+p_classnomer+")").show(); // //$('p[name ='+name+' ]').remove(); // /* // var class_nomer=$(this).attr("class"); // var p_classnomer=$("p#"+id).attr("class"); // class_nomer=parseInt(class_nomer)+1; // p_classnomer=parseInt(p_classnomer)+1; // $("#t"+id_b+" option:nth-child("+class_nomer+")").show(); // $("#g"+id_b+" option:nth-child("+p_classnomer+")").show(); // */ // //alert('a'); // //alert(p_classnomer); // //$("p#"+id).remove(); // }); // $('#raspisanie_send').submit(function(){ // var name_group=''; // var name_teacher=''; // var kol_pp=0; // var i2=2; // var val_input=''; // var val_b=''; // var index_g=''; // var index_t=''; // var all_info=''; // var all_info_array=new Array(); // for (var j = 1; j < 11; j++) // { // for (var i = 0; i < 6; i++) // { // kol_pp=0; // $.each($('#p'+j+i+' p'), function() { // kol_pp++ // }); // //alert(kol_pp); // if(kol_pp>0) // { // for (var i1 = 0; i1 < kol_pp; i1++) // { // i2=i2+i1; // val_input=$("#p"+j+i+" p:nth-child("+(i2-1)+") input").val(); // val_b=$("#p"+j+i+" p:nth-child("+(i2-1)+") b").text(); // index_t=$("#p"+j+i+" p:nth-child("+(i2-1)+") span").attr("class"); // index_g=$("#p"+j+i+" p:nth-child("+(i2-1)+")").attr("class"); // //alert(index_t+index_g); // //alert(val_b); // $( '#p'+j+i).append("<input type='hidden' name='p"+j+i+i1+"' value='"+val_input+"|"+val_b+"|"+index_t+"|"+index_g+"'/> "); // i2=2; // val_input=''; // val_b=''; // index_g=''; // index_t=''; // }; // } // //alert(kol_pp); // }; // }; // //alert("aza"); // // return false; // }); // $('body').on("click","i",function(){ // var id_i=$(this).attr("id"); // //alert(id_i); // $('div#div'+id_i).removeClass("hidden"); // $(this).remove(); // }); // $('b').click(function(){ // var id_i=$(this).attr("id"); // //alert(id_i); // $('div#div'+id_i).addClass("hidden"); // $('#i'+id_i).append("<i id="+id_i+" class='btn btn-info bt_i'>+</i>"); // //alert($('i #'+id_i).text()); // }); // });//end document
32.913295
253
0.397436
73e55848ae653178d90824fba56744cf193b489a
366
js
JavaScript
client/src/js/Header.js
fossabot/vento
caaa502720edb1e9888ed03f893ce72b545e2c2e
[ "MIT" ]
null
null
null
client/src/js/Header.js
fossabot/vento
caaa502720edb1e9888ed03f893ce72b545e2c2e
[ "MIT" ]
null
null
null
client/src/js/Header.js
fossabot/vento
caaa502720edb1e9888ed03f893ce72b545e2c2e
[ "MIT" ]
null
null
null
import React from "react"; import Logout from "./Logout"; import MFicon from "./MFicon.png"; const Header = props => { return ( <div className = "Headertitle"> <div className = "Headerlogout"> <Logout hist = {props.history} /> </div> <img src = {MFicon} alt = "Microfocus"/>{" "} VENTO </div> ); }; export default Header;
22.875
51
0.581967
73e60f5628e007393d1581d7b795d82f083b5424
716
js
JavaScript
assets/js/register.js
Zrn-coding/cyshMealSystem.github.io
b61cdcd04b03431d1ae97fec1573a901a3ad5b42
[ "CC-BY-3.0" ]
null
null
null
assets/js/register.js
Zrn-coding/cyshMealSystem.github.io
b61cdcd04b03431d1ae97fec1573a901a3ad5b42
[ "CC-BY-3.0" ]
null
null
null
assets/js/register.js
Zrn-coding/cyshMealSystem.github.io
b61cdcd04b03431d1ae97fec1573a901a3ad5b42
[ "CC-BY-3.0" ]
3
2021-02-10T10:31:55.000Z
2022-01-28T05:56:08.000Z
function confirm(){ var IDnumber= document.getElementById("IDnumber").value; if(IDnumber[0]<'A' || IDnumber[0]>'z'){ alert("身分證字號輸入錯誤!!!"); document.getElementById("IDnumber").value=""; } else if(IDnumber[0]>'Z'){ IDnumber[0] -= 'a'; IDnumber[0] += 'A'; var reply= [document.getElementById("class").value, document.getElementById("number").value, document.getElementById("name").value, document.getElementById("learning-namber").value, IDnumber ] var confirmMsg= "煩請檢查一下資料是否有錯\n\n " + "班級:" + reply[0] + "" var check= confirm(); } }
35.8
69
0.518156
73e6dc9dde4a0404e4c66e65953dec3b0a43bba9
896
js
JavaScript
src/object.js
SoNiceElijah/node-simple-3d
54caf0afdc70a9567e6bfc03c752924eacd29744
[ "MIT" ]
null
null
null
src/object.js
SoNiceElijah/node-simple-3d
54caf0afdc70a9567e6bfc03c752924eacd29744
[ "MIT" ]
null
null
null
src/object.js
SoNiceElijah/node-simple-3d
54caf0afdc70a9567e6bfc03c752924eacd29744
[ "MIT" ]
null
null
null
const { vec } = require('./math'); function makeres(ok) { return { ok : ok, point : null, norm : null, color : null, } } const sphere = { intersects : function (orig,dir) { let result = makeres(false); let a = 1; let b = vec.dot(vec.scale(2,dir),vec.sub(orig,this.C)); let c = vec.dot(vec.sub(orig - this.C)) - Math.pow(this.R,2); let d = b * b - 4 * a * c; if(d < 0) return result; let t0 = (-b + Math.sqrt(d)) / (2 * a); let t1 = (-b - Math.sqrt(d)) / (2 * a); let t = Math.min(t0,t1); if(t < 0) return result; result.point = vec.add(orig, vec.scale(t,dir)); result.norm = vec.norm(vec.sub(result.point,this.C)); result.color = this.color.slice(); return result; } } const objs = { sphere } module.exports = { objs };
19.911111
69
0.491071
73e79df85ea71915d5bcf3044e6980a14a4e89b5
151
js
JavaScript
src/components/Title.js
alex-alina/my-first-react-app
15af79c029ae2bf3f1d9b0648b40e0c537ca2ae4
[ "MIT" ]
null
null
null
src/components/Title.js
alex-alina/my-first-react-app
15af79c029ae2bf3f1d9b0648b40e0c537ca2ae4
[ "MIT" ]
null
null
null
src/components/Title.js
alex-alina/my-first-react-app
15af79c029ae2bf3f1d9b0648b40e0c537ca2ae4
[ "MIT" ]
null
null
null
import React, { Component } from 'react' export default class Title extends Component { render() { return <h1>{ this.props.content }</h1> } }
18.875
46
0.662252
73e7f9f025b5edc4ce2c1989731c58479381172e
1,904
js
JavaScript
ui/src/index.js
bbougon/sensei
b9a4c824f2667cf93b60b3015a27df259851d8c6
[ "BSD-3-Clause" ]
null
null
null
ui/src/index.js
bbougon/sensei
b9a4c824f2667cf93b60b3015a27df259851d8c6
[ "BSD-3-Clause" ]
null
null
null
ui/src/index.js
bbougon/sensei
b9a4c824f2667cf93b60b3015a27df259851d8c6
[ "BSD-3-Clause" ]
null
null
null
import style from './style.css'; import charts from './charts'; import logs from './logs'; import notes from './notes'; import { login } from './auth'; import { summaries, baseSummaries } from './summaries'; import { setUserProfile } from './user.js'; import { formatISODate } from './date.js'; import Navigo from 'navigo'; import { LocalDate } from "@js-joda/core"; document.addEventListener('DOMContentLoaded', () => { google.charts.load('current', { 'packages': ['corechart', 'bar', 'timeline', 'calendar'] }); const root = null; const useHash = true; const router = new Navigo(root, useHash); // default date used to display flows and notes const today = formatISODate(LocalDate.now()); setUserProfile(router); router .on('/flows', function() { charts(router, today); }) .on('/flows/:date', function(params) { charts(router, params.date); }) .on('/login', function() { login(router, document.getElementById('main')); }) .on('/notes', function() { notes.list(router, document.getElementById('main'), today); }) .on('/notes/:page', function(params) { notes.list(router, document.getElementById('main'), params.page); }) .on('/search', function() { notes.search(router, document.getElementById('main')); }) .on('/log/:page', function(params) { logs(router, document.getElementById('main'), params.page); }) .on('/log', function() { logs(router, document.getElementById('main'), 1); }) .on('/summaries/:from/:to/:period', function(params) { summaries(router, document.getElementById('main'), params.from, params.to, params.period); }) .on('/summaries', function() { summaries(router, document.getElementById('main')); }) .on(function() { // default to flows for today router.navigate('/flows/' + today); }).resolve(); });
31.213115
96
0.623424
73e8b0a35890f4a56ba3b9e8a9738b0d86def3aa
6,144
js
JavaScript
MITA.Web/Client/store/actions/projectActions.js
taihon/mita-final
5eee03322af53b9af96f5159dc38f586a5f62503
[ "MIT" ]
null
null
null
MITA.Web/Client/store/actions/projectActions.js
taihon/mita-final
5eee03322af53b9af96f5159dc38f586a5f62503
[ "MIT" ]
1
2018-04-03T08:34:54.000Z
2018-04-03T08:34:54.000Z
MITA.Web/Client/store/actions/projectActions.js
taihon/mita-final
5eee03322af53b9af96f5159dc38f586a5f62503
[ "MIT" ]
null
null
null
import axios from 'axios'; import * as actionTypes from './actionTypes'; export const requestProjects = apiToken => (dispatch, getState) => { dispatch({ type: actionTypes.FETCH_PROJECTS_START }); // because of way react renders components const token = localStorage.getItem("token"); axios.get("/api/projects", { headers: { Authorization: `Bearer ${token}` }, }) .then(response => dispatch({ type: actionTypes.FETCH_PROJECTS_SUCCESS, payload: { ...response.data }, })) .catch(error => dispatch({ type: actionTypes.FETCH_PROJECTS_FAILURE })); }; export const createProject = (title, description, token) => (dispatch) => { dispatch({ type: actionTypes.CREATE_PROJECT_START }); axios .post("/api/projects", { title, description }, { headers: { Authorization: `Bearer ${token}` }, }) .then(response => console.log(response)) .catch(error => console.log(error)); }; export const importProject = (project, token) => (dispatch) => { dispatch({ type: "IMPORT_PROJECT_START" }); axios .post("/api/projects/import", project, { headers: { Authorization: `Bearer ${token}` } }) .then(response => console.log(response.data)) .catch(error => console.log(error)); }; const projectDetails = (id, data) => ({ type: actionTypes.FETCH_PROJECT_DETAILS_SUCCESS, payload: { id, items: data.items }, }); const replaceReturns = (data) => { const o = {}; const keys = Object.keys(data); for (let i = 0; i < keys.length; i += 1) { o[keys[i]] = data[keys[i]] instanceof String ? data[keys[i]].replace('\\n', '\n') : data[keys[i]]; } return o; }; const fetchSingleProject = data => ({ type: actionTypes.FETCH_PROJECT_SUCCESS, payload: replaceReturns(data), }); export const fetchProjectDetails = (projectId, token) => (dispatch) => { dispatch({ type: actionTypes.FETCH_PROJECT_DETAILS_START }); const config = { headers: { Authorization: `Bearer ${token}` } }; axios .get(`/api/projects/${projectId}`, config) .then((response) => { dispatch(fetchSingleProject(response.data)); axios .get(`/api/projects/${projectId}/tasks`, config) .then(res => dispatch(projectDetails(projectId, res.data))); }) .catch(error => console.log(error)); }; export const addTaskToProject = (projectId, data, token) => (dispatch) => { dispatch({ type: actionTypes.ADD_TASK_START }); const config = { headers: { Authorization: `Bearer ${token}` } }; axios .post(`/api/projects/${projectId}/tasks`, data, config) .then(response => console.log(response)) .catch(error => console.log(error)); dispatch({ type: actionTypes.ADD_TASK_SUCCESS, payload: { projectId, data } }); }; export const saveTask = (data, token) => (dispatch) => { dispatch({ type: actionTypes.SAVE_TASK_START }); const config = { headers: { Authorization: `Bearer ${token}` } }; axios .put(`/api/projects/${data.projectId}/tasks/${data.id}`, data, config) .then(response => dispatch({ type: actionTypes.SAVE_TASK_SUCCESS, payload: { projectId: data.projectId, id: response.data.id }, })) .then(() => data.callback && data.callback()) .catch(e => console.log(e)); }; export const deleteTask = (taskId, projectId, token) => (dispatch) => { dispatch({ type: actionTypes.DELETE_TASK_START }); const config = { headers: { Authorization: `Bearer ${token}` } }; axios .delete(`/api/projects/${projectId}/tasks/${taskId}`, config) .then(response => console.log(response)) .catch(e => console.log(e)); dispatch(fetchProjectDetails(projectId, token)); }; export const saveProject = (data, token) => (dispatch) => { dispatch({ type: actionTypes.SAVE_PROJECT_START }); const config = { headers: { Authorization: `Bearer ${token}` } }; axios .put(`/api/projects/${data.id}`, data, config) .then(response => console.log(response)) .catch(e => console.log(e)); dispatch({ type: actionTypes.SAVE_PROJECT_SUCCESS }); }; export const archiveProject = (id, token) => (dispatch) => { dispatch({ type: actionTypes.ARCHIVE_PROJECT_START }); const config = { headers: { Authorization: `Bearer ${token}` } }; axios .post(`/api/projects/${id}/archive`, { projectId: id, confirm: true }, config) .then(response => console.log(response)) .catch(e => console.log(e)); dispatch({ type: actionTypes.ARCHIVE_PROJECT_SUCCESS, payload: id }); }; export const requestArchivedProjects = token => (dispatch) => { dispatch({ type: actionTypes.FETCH_ARCHIVE_START }); // because of way react renders components axios.get("/api/projects?archived=true", { headers: { Authorization: `Bearer ${token}` }, }) .then(response => dispatch({ type: actionTypes.FETCH_ARCHIVE_SUCCESS, payload: { ...response.data }, })) .catch(error => dispatch({ type: actionTypes.FETCH_ARCHIVE_FAILURE })); }; export const unarchiveProject = (id, token) => (dispatch) => { dispatch({ type: actionTypes.UNARCHIVE_PROJECT_START }); const config = { headers: { Authorization: `Bearer ${token}` } }; axios .post(`/api/projects/${id}/restore`, { projectId: id, confirm: true }, config) .then(() => dispatch({ type: actionTypes.UNARCHIVE_PROJECT_SUCCESS, payload: id })) .catch(() => dispatch({ type: actionTypes.UNARCHIVE_PROJECT_FAILURE })); }; export const completeTask = ({ taskId, projectId }, token) => (dispatch) => { dispatch({ type: actionTypes.SAVE_TASK_START }); const config = { headers: { Authorization: `Bearer ${token}` } }; axios .put(`/api/projects/${projectId}/tasks/${taskId}`, { completed: true }, config) .then(() => dispatch(fetchProjectDetails(projectId, token))) .catch(e => dispatch({ type: actionTypes.SAVE_TASK_FAILURE, payload: e })); };
43.574468
106
0.61377
73e8c6f2ebe19aecbc99c3285809f576a6cb8c68
746
js
JavaScript
server/server.js
NewAtoms/Heroku-Express-Polymer-scaffold
c7e91edac0c62aeaeaf444c82f393847cd11a078
[ "Apache-2.0" ]
null
null
null
server/server.js
NewAtoms/Heroku-Express-Polymer-scaffold
c7e91edac0c62aeaeaf444c82f393847cd11a078
[ "Apache-2.0" ]
null
null
null
server/server.js
NewAtoms/Heroku-Express-Polymer-scaffold
c7e91edac0c62aeaeaf444c82f393847cd11a078
[ "Apache-2.0" ]
null
null
null
var express = require('express') var Routes = require('./routes') var Server = function () { var self = this this.start = function () { // Import the Express server module and create an Express app var app = express() // Start the server var server = app.listen( process.env.PORT || 8081, function () { // Find out what address and port the server is running on var host = server .address() .address || self.hostUrl var port = server .address() .port Routes(app) // Tell the command line user the server is running console.log('Server listening at http://' + host + port) } ) } } module.exports = Server
22.606061
66
0.569705
73ea5f156f93eaf32382695e20ad384b775e17c8
816
js
JavaScript
models/user.js
boardwallfloor/smk3-server
930d2cd48e62cab236b4a5093713df29b621f84a
[ "MIT" ]
null
null
null
models/user.js
boardwallfloor/smk3-server
930d2cd48e62cab236b4a5093713df29b621f84a
[ "MIT" ]
null
null
null
models/user.js
boardwallfloor/smk3-server
930d2cd48e62cab236b4a5093713df29b621f84a
[ "MIT" ]
null
null
null
const mongoose = require('mongoose') const Schema = mongoose.Schema const UserSchema = new Schema({ username: { type: String, required: true, unique: true }, first_name: { type: String, required: true }, full_name: { type: String, required: true }, email: { type: String, required: true }, phonenumber: { type: String, required: true }, privilege: { type: String, required: true, enum: ['Admin', 'Operator', 'Kepala Fasyankes', 'Dinas Kesehatan'], default: 'Operator' }, job_title: { type: String, required: true }, user_institution: { type: Schema.Types.ObjectId, ref: 'Institution', required: true }, nip: { type: String, default: null }, password: { type: String, required: true, min: 8 } }, { timestamps: { createdAt: 'created_at' } }) module.exports = mongoose.model('User', UserSchema)
40.8
135
0.680147
73eac71130e9781a76497029d8f7375be8efb892
3,586
js
JavaScript
app/controllers/tag.js
cork-labs/cork-labs.bk
1340b710a1ce06141e31a9d45e0eb06fe53187de
[ "MIT" ]
null
null
null
app/controllers/tag.js
cork-labs/cork-labs.bk
1340b710a1ce06141e31a9d45e0eb06fe53187de
[ "MIT" ]
null
null
null
app/controllers/tag.js
cork-labs/cork-labs.bk
1340b710a1ce06141e31a9d45e0eb06fe53187de
[ "MIT" ]
null
null
null
var response = require('./util/responses'); // -- util functions // -- controller var TagCtrl = function (config, Tag) { var self = this; // -- param middlewares self.prepare = {}; /** * loads a tag by id * * @expects req.params.tagId * @populates req.tag */ self.prepare.loadTagById = function (req, res, next) { var id = req.param('tagId'); Tag.findById(id, function (err, tag) { if (err) { return response.error(res, err); } if (!tag) { return response.notFound(res); } req.tag = tag; return next(); }); }; /** * loads a tag by name * * @expects req.params.tagName * @populates req.tag */ self.prepare.loadTagByName = function (req, res, next) { var name = req.param('tagName'); Tag.findByName(name, function (err, tag) { if (err) { return response.error(res, err); } if (!tag) { return response.notFound(res); } req.tag = tag; return next(); }); }; // -- validation middlewares self.validate = {}; // -- authorization middlewares self.authorize = {}; // -- route controllers self.handle = {}; /** * POST /tag * * saves a new tag */ self.handle.create = function (req, res) { var tag = new Tag(req.body); console.log('this.create', tag); tag.save(function (err) { if (err) { console.log(err); return response.error(res, err); } return response.created(res, tag.asObject()); }); }; /** * PUT /tag/:id * * saves an existing tag * * @expects req.tag */ self.handle.update = function (req, res) { req.tag.update(req.body); req.tag.save(function (err) { if (err) { return response.error(res, err); } return response.data(res, req.tag.asObject()); }); }; /** * GET /tag * * list tags */ self.handle.list = function (req, res) { var options = {}; Tag.list(options, function (err, tags) { if (err) { return response.error(res, err); } Tag.count().exec(function (err, count) { tags = tags.map(function (tag) { return tag.asObject(); }); return response.data(res, tags, response.getCollectionMeta(count)); }); }); }; /** * POST /tag/search * * search tags * * @expects req.body.terms */ self.handle.search = function (req, res) { var terms = req.body.terms; Tag.search(terms, function (err, tags) { if (err) { return response.error(res, err); } Tag.count().exec(function (err, count) { tags = tags.map(function (tag) { return tag.asObject(); }); return response.data(res, tags, response.getCollectionMeta(count)); }); }); }; /** * GET /tag/:id * * load one tag by id * * @expects req.tag */ self.handle.get = function (req, res) { return response.data(res, req.tag.asObject()); }; }; module.exports = TagCtrl;
21.473054
83
0.457055
73eb0b48cd5f4f5301146d05df3fe39df3909044
214
js
JavaScript
src/components/atoms/Info/index.stories.js
protoEvangelion/interactiveTradeFloor
52cd82352771d72ae6dc4833572e0e1cd3c0ac20
[ "MIT", "Unlicense" ]
10
2017-04-19T19:45:40.000Z
2021-05-18T12:44:06.000Z
src/components/atoms/Info/index.stories.js
rdotg/interactiveTradeFloor
52cd82352771d72ae6dc4833572e0e1cd3c0ac20
[ "MIT", "Unlicense" ]
3
2017-04-18T00:46:12.000Z
2021-05-07T03:00:50.000Z
src/components/atoms/Info/index.stories.js
rdotg/interactiveTradeFloor
52cd82352771d72ae6dc4833572e0e1cd3c0ac20
[ "MIT", "Unlicense" ]
2
2017-04-18T00:42:24.000Z
2018-02-08T08:24:05.000Z
import React from 'react' import { storiesOf } from '@kadira/storybook' import Info from '.' storiesOf('Info', module) .add('default', () => <Info>Hello</Info>) .add('reverse', () => <Info reverse>Hello</Info>)
26.75
50
0.654206
73eb2ab25c1155bfe8fc776d6da5f70f55f57f1d
6,640
js
JavaScript
merch-dropper/src/store/actions/index.js
JWNicholson/Merch-Dropper-fe
f3ce23dc5d5a00ab6d1ba2fdc16b25d03fa29d7c
[ "MIT" ]
null
null
null
merch-dropper/src/store/actions/index.js
JWNicholson/Merch-Dropper-fe
f3ce23dc5d5a00ab6d1ba2fdc16b25d03fa29d7c
[ "MIT" ]
8
2020-02-12T17:02:08.000Z
2021-10-06T14:17:23.000Z
merch-dropper/src/store/actions/index.js
BloomTech-Labs/Merch-Dropper-fe
b5cd156c81e90facca61e71e69e2748eb6d9d64e
[ "MIT" ]
9
2020-02-13T21:38:50.000Z
2020-09-09T17:20:16.000Z
import { axiosWithAuth } from '../../utils/axiosWithAuth'; import axios from 'axios'; import { axiosWithEnv } from '../../utils/axiosWithEnv'; // Registration Actions export const REGISTER_START = 'REGISTER_START'; export const REGISTER_SUCCESS = 'REGISTER_SUCCESS'; export const REGISTER_FAILURE = 'REGISTER_FAILURE'; export const postUser = (credentials) => dispatch => { // console.log('credentials', credentials) dispatch({ type: REGISTER_START }) axios.post('https://merch-dropper.herokuapp.com/api/auth/register', credentials) .then(res => { console.log('postUser res', res); dispatch({ type: REGISTER_SUCCESS, payload: res.data }) }) .catch(err => { console.log('postUser err', err) dispatch({ type: REGISTER_FAILURE, payload: err }) }) }; // Login Actions export const LOGIN_START = 'LOGIN_START'; export const LOGIN_SUCCESS = 'LOGIN_SUCCESS'; export const LOGIN_FAILURE = 'LOGIN_FAILURE'; export const userLogin = (loginInfo) => dispatch => { console.log('loginInfo', loginInfo) dispatch({ type: LOGIN_START }) axiosWithAuth() .post('/api/auth/login', loginInfo) .then(res => { console.log(res) localStorage.setItem('token', res.data.token) dispatch({ type: LOGIN_SUCCESS, payload: res.data }) }) .catch(err => { console.log(err) dispatch({ type: LOGIN_FAILURE, payload: err }) }) }; // Product Actions - get request to display products export const GET_PRODUCTS_START = 'GET_PRODUCTS_START'; export const GET_PRODUCTS_SUCCESS = 'GET_PRODUCTS_SUCCESS'; export const GET_PRODUCTS_FAIL = 'GET_PRODUCTS_FAIL'; export const getProducts = (productId) => dispatch => { dispatch({ type: GET_PRODUCTS_START }) axiosWithAuth() .get(`/api/designs/${productId}`) .then(res => { dispatch({ type: GET_PRODUCTS_SUCCESS, payload: res.data }) }) .catch(err => { dispatch({ type: GET_PRODUCTS_FAIL, payload: err }) }) }; //post request to add a new product to store export const ADD_PRODUCT_START = 'ADD_PRODUCT_START'; export const ADD_PRODUCT_SUCCESS = 'ADD_PRODUCT_SUCCESS'; export const ADD_PRODUCT_FAIL = 'ADD_PRODUCT_FAIL'; export const addProduct = newProduct => dispatch => { dispatch({ type: ADD_PRODUCT_START }) axiosWithAuth() .post('/api/designs', newProduct) .then(res => { dispatch({ type: ADD_PRODUCT_SUCCESS, payload: res.data }) }) .catch(err => { dispatch({ type: ADD_PRODUCT_FAIL, payload: err }) }) }; // delete request to remove product from store export const REMOVE_PRODUCT_START = 'REMOVE_PRODUCT_START'; export const REMOVE_PRODUCT_SUCCESS = 'REMOVE_PRODUCT_SUCCESS'; export const REMOVE_PRODUCT_FAIL = 'REMOVE_PRODUCT_FAIL'; export const removeProduct = productId => dispatch => { dispatch({ type: REMOVE_PRODUCT_START }) axiosWithAuth() .delete(`/api/designs/${productId}`) .then(res => { dispatch({ type: REMOVE_PRODUCT_SUCCESS, payload: res.data }) }) .catch(err => { dispatch({ type: REMOVE_PRODUCT_FAIL, payload: err }) }) }; // Shopping Cart Actions - add item to shopping cart export const ADD_CART_PRODUCT = 'ADD_CART_PRODUCT'; export const addToCart = product => { // console.log('action called', product) return { type: ADD_CART_PRODUCT, payload: product } }; // remove one single item from shopping cart. e.g if 10 yellow shirts, remove 1 of the 10 yellow shirts. export const REMOVE_CART_PRODUCT = 'REMOVE_CART_PRODUCT'; export const removeFromCart = product => { // console.log('removeaction called', product) return { type: REMOVE_CART_PRODUCT, payload: product } }; //Clear whole item from cart. e.g if 10 yellow shirts, remove all 10 at once. export const CLEAR_CART_PRODUCT = 'CLEAR_CART_PRODUCT'; export const clearItemFromCart = product => { return { type: CLEAR_CART_PRODUCT, payload: product } }; //toggle shopping cart export const TOGGLE_CART = 'TOGGLE_CART_HIDDEN'; export const toggleCart = () => { return { type: TOGGLE_CART } }; // reset cart to hidden export const RESET_CART = 'RESET_CART' export const resetCart = () =>{ return { type: RESET_CART } } //search for stores export const SEARCH_STORE_START = 'SEARCH_STORE_START'; export const SEARCH_STORE_SUCCESS = 'SEARCH_STORE_SUCCESS'; export const SEARCH_STORE_FAIL = 'SEARCH_STORE_FAIL'; export const searchStoreName = (storeName) => dispatch => { let encodedURI = encodeURI(storeName) // console.log('search action called', encodedURI) dispatch({ type: SEARCH_STORE_START }) axios.get(`https://merch-dropper.herokuapp.com/api/stores/storename/${encodedURI}`) .then(res => { dispatch({ type: SEARCH_STORE_SUCCESS, payload: res.data }) }) .catch(err => { dispatch({ type: SEARCH_STORE_FAIL, payload: err }) }) }; export const GET_QUOTE_START = "GET_QUOTE_START"; export const GET_QUOTE_SUCCESS = "GET_QUOTE_SUCCESS"; export const GET_QUOTE_FAILURE = "GET_QUOTE_FAILURE"; export const GET_STORE_ID = "GET_STORE_ID"; export const NULL_ORDER_TOKEN = "NULL_ORDER_TOKEN"; export const getQuote = (quote) => dispatch => { dispatch({type: GET_QUOTE_START}); axiosWithEnv() .post('/api/quotes', quote) .then(res => { // console.log('POSTED QUOTE',res) if(res.data.quote.orderToken){ dispatch({type: GET_QUOTE_SUCCESS, payload: res.data}) } else { dispatch({type: NULL_ORDER_TOKEN, payload: res.data}) } }) .catch(err => { dispatch({type: GET_QUOTE_FAILURE, payload: err}) }) } export const ADD_ADDRESS_SUCCESS = "ADD_ADDRESS_SUCCESS"; export const ADD_PRODUCT_QUOTE = "ADD_PRODUCT_QUOTE"; export const SET_DESIGNID_QUOTE = "SET_DESIGNID_QUOTE" export const setQuote = (stuff) => dispatch => { dispatch({type: ADD_PRODUCT_QUOTE, payload: stuff}) } export const addAddress = (address) => dispatch => { dispatch({type: ADD_ADDRESS_SUCCESS, payload: address}); } export const ADD_PRODUCT_STATE_START = "ADD_PRODUCT_STATE_START"; export const ADD_PRODUCT_STATE_SUCCESS = "ADD_PRODUCT_STATE_SUCCESS"; export const ADD_PRODUCT_STATE_FAILURE = "ADD_PRODUCT_STATE_FAILURE"; export const addProdToState = (product) => dispatch => { dispatch({type: ADD_PRODUCT_STATE_SUCCESS, payload: product}) }
32.54902
104
0.665211
73eb2d6e6babf1c94b17b852e4c9bbac42c0f559
534
js
JavaScript
server/dist/socketMessage.js
lucasvmiguel/url-shortener
f878d18235b2afd008cb41cbd83024b7dfe3477f
[ "MIT" ]
null
null
null
server/dist/socketMessage.js
lucasvmiguel/url-shortener
f878d18235b2afd008cb41cbd83024b7dfe3477f
[ "MIT" ]
null
null
null
server/dist/socketMessage.js
lucasvmiguel/url-shortener
f878d18235b2afd008cb41cbd83024b7dfe3477f
[ "MIT" ]
null
null
null
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var sendMessage = exports.sendMessage = function sendMessage(_ref) { var client = _ref.client, action = _ref.action, data = _ref.data; client.emit('event', { 'action': action, type: 'success', 'data': data }); }; var sendError = exports.sendError = function sendError(_ref2) { var client = _ref2.client, action = _ref2.action, data = _ref2.data; client.emit('event', { 'action': action, type: 'error', data: data }); };
26.7
76
0.649813
73ec5645f7ab7753cd65d962166bee70710b5b8e
523
js
JavaScript
node-client/start.js
mmonti/consul-sample
cb851b9b81fa1abe07487be64edf843902c64bd4
[ "MIT" ]
null
null
null
node-client/start.js
mmonti/consul-sample
cb851b9b81fa1abe07487be64edf843902c64bd4
[ "MIT" ]
null
null
null
node-client/start.js
mmonti/consul-sample
cb851b9b81fa1abe07487be64edf843902c64bd4
[ "MIT" ]
null
null
null
var consul = require('consul')(); // FOLDER consul.kv.get({recurse: true, path: 'config/authn-service'}, function(err, result) { if (err) throw err; for (var idx in result) { console.log("Value=[%s]", result[idx].Value); } }); // DOCUMENT consul.kv.get('config/node-client/document', function(err, result) { if (err) throw err; console.log("Key=[%s]", result.Key); console.log("Value=[%s]", result.Value); var document = JSON.parse(result.Value); console.log("Address=[%s]", document.address); });
26.15
84
0.642447
73ed17e786860ed2dfddb8fd6c3dcbbbdbe48d8a
59
js
JavaScript
src/index.js
nativecode-dev/livestreamer
b88217cc85812fa2afcaec93e6b3fe9a07f42b8b
[ "MIT" ]
null
null
null
src/index.js
nativecode-dev/livestreamer
b88217cc85812fa2afcaec93e6b3fe9a07f42b8b
[ "MIT" ]
null
null
null
src/index.js
nativecode-dev/livestreamer
b88217cc85812fa2afcaec93e6b3fe9a07f42b8b
[ "MIT" ]
null
null
null
module.exports = { TwitchStreamer: require('./twitch') }
14.75
37
0.677966
73ed7184d19ef8267a9642d848a4464c40974dc8
1,537
js
JavaScript
src/components/interactive/button.js
joefraley/peoples
fcb5b9705ff983d0e3084f72fb157de44e7919b6
[ "MIT" ]
null
null
null
src/components/interactive/button.js
joefraley/peoples
fcb5b9705ff983d0e3084f72fb157de44e7919b6
[ "MIT" ]
null
null
null
src/components/interactive/button.js
joefraley/peoples
fcb5b9705ff983d0e3084f72fb157de44e7919b6
[ "MIT" ]
null
null
null
import React from "react" import { colors, typography } from "../../constants/styles" const styles = { inverted: { color: colors.white, background: colors.transparent, borderColor: colors.white, hover: { color: colors.white, background: "rgba(255, 82, 82, 0.5)", borderColor: "rgba(255, 82, 82, 0.5)", }, }, standard: { color: colors.white, background: colors.black, borderColor: colors.white, hover: { color: colors.white, background: colors.red, borderColor: colors.transparent, }, }, } const Button = ({ text = "", type = "standard", ...props }) => ( <> <style jsx>{` button { border-color: ${styles[type].borderColor}; border-radius: 24px; border-style: solid; border-width: 1px; font-family: ${typography.copy.font}; font-size: 1em; padding: 1em; text-transform: uppercase; transition: background 0.4s, color 0.3s; } button:hover, button:active, button:focus { background-color: ${styles[type].hover.background} !important; border-color: ${styles[type].hover.borderColor} !important; border-width: 1px; color: ${styles[type].hover.color} !important; cursor: pointer; } `}</style> <button style={{ transition: "", ...styles[type], ...props.style, }} {...props} > {text || props.children} </button> </> ) export default Button
23.646154
70
0.55758
73ee62c692b5cbcf7fe27ca7f29c01ac63f3ea74
1,170
js
JavaScript
my-blogs/src/useFetch.js
Yadunandanaacharya/LearnReactWithBlog
36051bc51d34a3d204c2553e307a491792ce51f5
[ "Apache-2.0" ]
null
null
null
my-blogs/src/useFetch.js
Yadunandanaacharya/LearnReactWithBlog
36051bc51d34a3d204c2553e307a491792ce51f5
[ "Apache-2.0" ]
null
null
null
my-blogs/src/useFetch.js
Yadunandanaacharya/LearnReactWithBlog
36051bc51d34a3d204c2553e307a491792ce51f5
[ "Apache-2.0" ]
null
null
null
import { useState,useEffect } from "react"; const useFetch = (url) =>{ const [data, setData ] = useState(null); const [isLoading, setIsPending] = useState(true); const [error, setError] = useState(null); useEffect(()=>{ const abortCont = new AbortController(); setTimeout(()=>{ fetch(url, {signal:abortCont.signal}) .then(res =>{ // console.log(res); if(!res.ok){ throw Error('Could not fetch data for that resource'); } return res.json(); }) .then(data =>{ setData(data); setIsPending(false); setError(null); }) .catch(error => { if(error.name === "AbortError"){ console.log('fetch aborted'); } else{ setIsPending(false); setError(error); } }); },500); // return ()=>console.log('cleanup'); //replace console.log('cleanup'); wit h return ()=> abortCont.abort(); },[url]); return {data, isLoading, error}; } export default useFetch;
27.209302
83
0.481197
73ee836c688033510cd62553f8750cde10a3e82e
2,842
js
JavaScript
src/App.js
Hank-Choi/word2cloudmap
7f3d914336fcc636884426fa0e6611a194571bc7
[ "MIT" ]
null
null
null
src/App.js
Hank-Choi/word2cloudmap
7f3d914336fcc636884426fa0e6611a194571bc7
[ "MIT" ]
null
null
null
src/App.js
Hank-Choi/word2cloudmap
7f3d914336fcc636884426fa0e6611a194571bc7
[ "MIT" ]
null
null
null
import React, {useEffect, useState} from "react"; import './App.css'; import WordCloudMap from "./component/WordCloudMap"; import {Resizable} from "re-resizable"; import "tippy.js/dist/tippy.css"; import "tippy.js/animations/scale.css"; import {getSimilarWords, postParagraph} from "./api/word2vec"; import {Loader, Dimmer, Breadcrumb, Form} from "semantic-ui-react"; const resizeStyle = { display: "flex", alignItems: "center", justifyContent: "center", border: "solid 1px #ddd", background: "#f0f0f0" }; function App() { const [words, setWords] = useState([]) const [currentWords, setCurrentWords] = useState([]) const [baseWord, setBaseWord] = useState([]) const [paragraph, setParagraph] = useState('') const [loading, setLoading] = useState(false) useEffect(() => { if (currentWords && currentWords.length > 0) { getSimilarWords(currentWords.join()).then((response) => { setWords(response.data.words) }) } }, [currentWords]) return ( <div className={'app-header'}> <img src="https://img.icons8.com/clouds/100/000000/cloud-file.png" alt={'b'}/> <div className={'app'}> <Breadcrumb> <Breadcrumb.Section link onClick={() => { setWords(baseWord) setCurrentWords([]) }}>Home</Breadcrumb.Section> {currentWords.map((cur, index) => ( <> <Breadcrumb.Divider/> <Breadcrumb.Section link onClick={() => setCurrentWords(currentWords.slice(0, index + 1))}>{cur} </Breadcrumb.Section> </>)) } </Breadcrumb> <Resizable defaultSize={{ width: '100%', height: 400 }} style={resizeStyle} > <div style={{width: "100%", height: "100%"}}> {loading ? ( <Dimmer active inverted> <Loader inverted>Loading</Loader> </Dimmer>) : null} <WordCloudMap onWordClick={(word,e) => { if(e.shiftKey) setCurrentWords(prev => [...prev, '-'+word.text]) else setCurrentWords(prev => [...prev, word.text]) }} words={words}/> </div> </Resizable> <Form onSubmit={() => { setLoading(true) postParagraph(paragraph).then(r => { setWords(r) setBaseWord(r) setCurrentWords([]) setLoading(false) } ) }}> <Form.TextArea onChange={(event) => setParagraph(event.target.value)} placeholder='Tell us more' style={{minHeight: 200}}/> <Form.Button content='Submit'/> </Form> </div> </div> ); } export default App;
29.915789
110
0.531316
73ef2a75ee8d6f420ac8cfa667fda977d8a61d31
585
js
JavaScript
gatsby-node.js
Rhaant/red-dot
b924495097b7a997700b7e5cd07aa3bfdb257b82
[ "RSA-MD" ]
null
null
null
gatsby-node.js
Rhaant/red-dot
b924495097b7a997700b7e5cd07aa3bfdb257b82
[ "RSA-MD" ]
null
null
null
gatsby-node.js
Rhaant/red-dot
b924495097b7a997700b7e5cd07aa3bfdb257b82
[ "RSA-MD" ]
null
null
null
const path = require("path") const { create } = require("domain") exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions const projectTemplate = path.resolve(`src/layouts/project.js`) const result = await graphql(` query queryCMSPage { allDatoCmsProject { nodes { id } } } `) result.data.allDatoCmsProject.nodes.forEach(project => { createPage({ path: `portfolio/wnetrza/${project.id}`, component: projectTemplate, context: { id: project.id, }, }) }) }
21.666667
64
0.588034
73efde778f9ce258b319d84033bc9b9fceae91bd
429
js
JavaScript
src/components/molecules/socialbutton/index.spec.js
davidc94/Portfolio
ebfce1939661a3b0f48a360a872e298ecde109bb
[ "MIT" ]
null
null
null
src/components/molecules/socialbutton/index.spec.js
davidc94/Portfolio
ebfce1939661a3b0f48a360a872e298ecde109bb
[ "MIT" ]
8
2021-03-09T01:23:23.000Z
2022-02-26T10:03:15.000Z
src/components/molecules/socialbutton/index.spec.js
davidc94/Portfolio
ebfce1939661a3b0f48a360a872e298ecde109bb
[ "MIT" ]
null
null
null
import React from "react" import renderer from "react-test-renderer" import SocialButton from "./index"; describe("SocialButton", () => { it("renders as expected with github", () => { expect(renderer.create(<SocialButton social='github'/>).toJSON()).toMatchSnapshot(); }) it("renders as expected with linkedin", () => { expect(renderer.create(<SocialButton social='linkedin'/>).toJSON()).toMatchSnapshot(); }) })
35.75
90
0.685315
73efea0f9781508039750088665cfa744cd92122
1,885
js
JavaScript
webpack.config.js
ykzts/mastodon-following-list
6769e4852c0a8df4625bf3134707b47b53771fd8
[ "MIT" ]
2
2017-11-07T06:59:27.000Z
2018-03-15T02:00:28.000Z
webpack.config.js
ykzts/sayonara.social
6769e4852c0a8df4625bf3134707b47b53771fd8
[ "MIT" ]
25
2017-05-16T12:57:39.000Z
2018-03-16T09:27:26.000Z
webpack.config.js
ykzts/mastodon-following-list
6769e4852c0a8df4625bf3134707b47b53771fd8
[ "MIT" ]
null
null
null
const CopyPlugin = require('copy-webpack-plugin'); const HtmlPlugin = require('html-webpack-plugin'); const path = require('path'); const { EnvironmentPlugin } = require('webpack'); const { name } = require('./package.json'); module.exports = (env = process.env.NODE_ENV || 'development') => ({ devServer: { historyApiFallback: true, }, devtool: 'source-map', entry: { main: path.resolve(__dirname, 'src', 'main.js'), }, mode: env === 'production' ? 'production' : 'development', module: { rules: [ { test: /\.css$/, use: [ { loader: 'style-loader', }, { loader: 'css-loader', }, ], }, { exclude: /\/node_modules\//, test: /\.js$/, use: { loader: 'babel-loader', }, }, ], }, output: { path: path.resolve(__dirname, 'build', 'public'), publicPath: '/', filename: env === 'production' ? '[name].[chunkhash].js' : '[name].js?[chunkhash]', }, plugins: [ new EnvironmentPlugin({ NODE_ENV: env, }), new HtmlPlugin({ minify: env === 'production' ? { collapseBooleanAttributes: true, collapseInlineTagWhitespace: true, collapseWhitespace: true, includeAutoGeneratedTags: false, removeAttributeQuotes: true, removeComments: true, removeOptionalTags: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true, sortAttributes: true, sortClassName: true, } : false, template: path.resolve(__dirname, 'src', 'templates', 'index.html.ejs'), title: name, }), ...(env === 'production' ? [ new CopyPlugin([ { from: path.resolve(__dirname, 'src', 'templates', '_redirects'), }, ]), ] : []), ], });
25.821918
87
0.53634
73f12e6781d992b23731302775c19381e886ae80
19,230
js
JavaScript
docs/.vitepress/dist/assets/formfields_dynamic-input.md.add6f080.js
voyager-admin/voyager
00a8ed745e0f41cce504a22c0f94bc8d0cc63953
[ "MIT" ]
12
2020-05-03T11:15:22.000Z
2022-03-03T14:10:50.000Z
docs/.vitepress/dist/assets/formfields_dynamic-input.md.add6f080.js
voyager-admin/voyager
00a8ed745e0f41cce504a22c0f94bc8d0cc63953
[ "MIT" ]
5
2020-05-02T17:05:59.000Z
2021-01-09T18:33:24.000Z
docs/.vitepress/dist/assets/formfields_dynamic-input.md.add6f080.js
voyager-admin/voyager
00a8ed745e0f41cce504a22c0f94bc8d0cc63953
[ "MIT" ]
3
2020-06-25T12:02:30.000Z
2021-02-07T19:30:22.000Z
import{_ as t,c as n,o as a,a as s}from"./app.5d92c05f.js";const g='{"title":"Dynamic Input","description":"","frontmatter":{},"headers":[{"level":2,"title":"Available methods","slug":"available-methods"},{"level":3,"title":"addSelect","slug":"addselect"},{"level":3,"title":"addText","slug":"addtext"},{"level":3,"title":"addNumber","slug":"addnumber"},{"level":3,"title":"addCheckboxes","slug":"addcheckboxes"},{"level":3,"title":"addRadios","slug":"addradios"},{"level":3,"title":"addSwitch","slug":"addswitch"},{"level":2,"title":"Knowing the BREAD action","slug":"knowing-the-bread-action"},{"level":2,"title":"Using no keys on inputs","slug":"using-no-keys-on-inputs"},{"level":2,"title":"Examples","slug":"examples"},{"level":3,"title":"Single select without a key","slug":"single-select-without-a-key"},{"level":3,"title":"Single select with a key","slug":"single-select-with-a-key"},{"level":3,"title":"Selects based on previous selection","slug":"selects-based-on-previous-selection"}],"relativePath":"formfields/dynamic-input.md","lastUpdated":1640692859382}',e={},o=s(`<h1 id="dynamic-input" tabindex="-1">Dynamic Input <a class="header-anchor" href="#dynamic-input" aria-hidden="true">#</a></h1><p>The dynamic input is a simple yet powerful formfield allowing you to provide selects, number or text inputs, checkboxes, radios and switches based on your conditions/code.</p><p>To retreive the possible options, Voyager will fetch a route you define in the formfield options.<br> This route has to return a JSON object containing the set of fields you want to show.</p><p>For easy use Voyager provides a class <code>VoyagerAdmin\\Voyager\\Classes\\DynamicInput</code> that helps you create those responses.</p><h2 id="available-methods" tabindex="-1">Available methods <a class="header-anchor" href="#available-methods" aria-hidden="true">#</a></h2><h3 id="addselect" tabindex="-1">addSelect <a class="header-anchor" href="#addselect" aria-hidden="true">#</a></h3><p>Adds a select input to the formfield.</p><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th><th>Default</th></tr></thead><tbody><tr><td>key</td><td>string, null</td><td>The key in the final data</td><td>null</td></tr><tr><td>title</td><td>string, array, null</td><td>The title shown above the input</td><td>null</td></tr><tr><td>options</td><td>array</td><td>An array of key =&gt; value pairs. The key is used as the value in the final data</td><td>[]</td></tr><tr><td>multiple</td><td>bool</td><td>Allow multiple selection</td><td>false</td></tr><tr><td>value</td><td>mixed</td><td>The value selected by the user or the default value</td><td>null</td></tr></tbody></table><h3 id="addtext" tabindex="-1">addText <a class="header-anchor" href="#addtext" aria-hidden="true">#</a></h3><p>Add a text input to the formfield.</p><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th><th>Default</th></tr></thead><tbody><tr><td>key</td><td>string, null</td><td>The key in the final data</td><td>null</td></tr><tr><td>title</td><td>string, array, null</td><td>The title shown above the input</td><td>null</td></tr><tr><td>placeholder</td><td>string, array, null</td><td>An array of key =&gt; value pairs. The key is used as the value in the final data</td><td>null</td></tr><tr><td>value</td><td>mixed</td><td>The value selected by the user or the default value</td><td>null</td></tr></tbody></table><h3 id="addnumber" tabindex="-1">addNumber <a class="header-anchor" href="#addnumber" aria-hidden="true">#</a></h3><p>Add a number input to the formfield.</p><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th><th>Default</th></tr></thead><tbody><tr><td>key</td><td>string, null</td><td>The key in the final data</td><td>null</td></tr><tr><td>title</td><td>string, array, null</td><td>The title shown above the input</td><td>null</td></tr><tr><td>placeholder</td><td>string, array, null</td><td>An array of key =&gt; value pairs. The key is used as the value in the final data</td><td>null</td></tr><tr><td>value</td><td>int, null</td><td>The value selected by the user or the default value</td><td>null</td></tr><tr><td>min</td><td>int, null</td><td>The minimum value that can be entered. Null means negative infinite</td><td>null</td></tr><tr><td>max</td><td>int, null</td><td>The maximum value that can be entered. Null means infinite</td><td>null</td></tr></tbody></table><h3 id="addcheckboxes" tabindex="-1">addCheckboxes <a class="header-anchor" href="#addcheckboxes" aria-hidden="true">#</a></h3><p>Adds multiple checkboxes to the formfield.</p><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th><th>Default</th></tr></thead><tbody><tr><td>key</td><td>string, null</td><td>The key in the final data</td><td>null</td></tr><tr><td>title</td><td>string, array, null</td><td>The title shown above the input</td><td>null</td></tr><tr><td>options</td><td>array</td><td>An array of key =&gt; value pairs. The key is used as the value in the final data</td><td>[]</td></tr><tr><td>value</td><td>mixed</td><td>The values selected by the user or the default value</td><td>null</td></tr></tbody></table><h3 id="addradios" tabindex="-1">addRadios <a class="header-anchor" href="#addradios" aria-hidden="true">#</a></h3><p>Adds multiple radios to the formfield.</p><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th><th>Default</th></tr></thead><tbody><tr><td>key</td><td>string, null</td><td>The key in the final data</td><td>null</td></tr><tr><td>title</td><td>string, array, null</td><td>The title shown above the input</td><td>null</td></tr><tr><td>options</td><td>array</td><td>An array of key =&gt; value pairs. The key is used as the value in the final data</td><td>[]</td></tr><tr><td>value</td><td>mixed</td><td>The value selected by the user or the default value</td><td>null</td></tr></tbody></table><h3 id="addswitch" tabindex="-1">addSwitch <a class="header-anchor" href="#addswitch" aria-hidden="true">#</a></h3><p>Add a simple switch to the formfield.</p><table><thead><tr><th>Parameter</th><th>Type</th><th>Description</th><th>Default</th></tr></thead><tbody><tr><td>key</td><td>string, null</td><td>The key in the final data</td><td>null</td></tr><tr><td>title</td><td>string, array, null</td><td>The title shown above the input</td><td>null</td></tr><tr><td>value</td><td>mixed</td><td>The value when the switch is active</td><td>null</td></tr></tbody></table><h2 id="knowing-the-bread-action" tabindex="-1">Knowing the BREAD action <a class="header-anchor" href="#knowing-the-bread-action" aria-hidden="true">#</a></h2><p>The incoming request contains a parameter <code>bread_action</code> which can be <code>query</code>, <code>browse</code>, <code>edit</code> or <code>add</code>.</p><h2 id="using-no-keys-on-inputs" tabindex="-1">Using no keys on inputs <a class="header-anchor" href="#using-no-keys-on-inputs" aria-hidden="true">#</a></h2><p>Sometimes its useful to use no key on an input.<br> That way a single select with multiple=false will only store the selected value in the database instead of a key-value pair.<br> But be aware that only one input total without a key can exist in a formfield.<br> Otherwise an Exception <code>Only one input without a key can exist!</code> will be thrown.</p><h2 id="examples" tabindex="-1">Examples <a class="header-anchor" href="#examples" aria-hidden="true">#</a></h2><h3 id="single-select-without-a-key" tabindex="-1">Single select without a key <a class="header-anchor" href="#single-select-without-a-key" aria-hidden="true">#</a></h3><p>This example shows a single select with two options <code>English</code> and <code>German</code>.</p><div class="language-php"><pre><code><span class="token php language-php"><span class="token delimiter important">&lt;?php</span> <span class="token keyword">use</span> <span class="token package">VoyagerAdmin<span class="token punctuation">\\</span>Voyager<span class="token punctuation">\\</span>Classes<span class="token punctuation">\\</span>DynamicInput</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name-definition class-name">MyController</span> <span class="token punctuation">{</span> <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">getOptions</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">DynamicInput</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token operator">-&gt;</span><span class="token function">addSelect</span><span class="token punctuation">(</span><span class="token constant">null</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;Select a language&#39;</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string single-quoted-string">&#39;en&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;English&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;de&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;German&#39;</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> </span></code></pre></div><p>The data stored in the database will be <code>en</code> or <code>de</code>.</p><h3 id="single-select-with-a-key" tabindex="-1">Single select with a key <a class="header-anchor" href="#single-select-with-a-key" aria-hidden="true">#</a></h3><p>This example shows a single select with two options <code>English</code> and <code>German</code>.</p><div class="language-php"><pre><code><span class="token php language-php"><span class="token delimiter important">&lt;?php</span> <span class="token keyword">use</span> <span class="token package">VoyagerAdmin<span class="token punctuation">\\</span>Voyager<span class="token punctuation">\\</span>Classes<span class="token punctuation">\\</span>DynamicInput</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name-definition class-name">MyController</span> <span class="token punctuation">{</span> <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">getOptions</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token keyword">return</span> <span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">DynamicInput</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token operator">-&gt;</span><span class="token function">addSelect</span><span class="token punctuation">(</span><span class="token string single-quoted-string">&#39;language&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;Select a language&#39;</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string single-quoted-string">&#39;en&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;English&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;de&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;German&#39;</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> </span></code></pre></div><p>The data stored in the database will be <code>[&#39;language&#39; =&gt; &#39;en&#39;]</code> or <code>[&#39;language&#39; =&gt; &#39;de&#39;]</code>.</p><h3 id="selects-based-on-previous-selection" tabindex="-1">Selects based on previous selection <a class="header-anchor" href="#selects-based-on-previous-selection" aria-hidden="true">#</a></h3><p>In this example the user is asked to select a country first.<br> Once the country is selected, another select is shown which allows the user to enter the state.</p><div class="language-php"><pre><code><span class="token php language-php"><span class="token delimiter important">&lt;?php</span> <span class="token keyword">use</span> <span class="token package">VoyagerAdmin<span class="token punctuation">\\</span>Voyager<span class="token punctuation">\\</span>Classes<span class="token punctuation">\\</span>DynamicInput</span><span class="token punctuation">;</span> <span class="token keyword">class</span> <span class="token class-name-definition class-name">MyController</span> <span class="token punctuation">{</span> <span class="token keyword">public</span> <span class="token keyword">function</span> <span class="token function-definition function">getOptions</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token variable">$country</span> <span class="token operator">=</span> <span class="token variable">$request</span><span class="token operator">-&gt;</span><span class="token function">input</span><span class="token punctuation">(</span><span class="token string single-quoted-string">&#39;country&#39;</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token variable">$input</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">DynamicInput</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token operator">-&gt;</span><span class="token function">addSelect</span><span class="token punctuation">(</span><span class="token string single-quoted-string">&#39;country&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;Select your country&#39;</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string single-quoted-string">&#39;us&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;United States&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;de&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;Germany&#39;</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token variable">$country</span> <span class="token operator">==</span> <span class="token string single-quoted-string">&#39;us&#39;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token variable">$input</span><span class="token operator">-&gt;</span><span class="token function">addSelect</span><span class="token punctuation">(</span><span class="token string single-quoted-string">&#39;state&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;Select your state&#39;</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string single-quoted-string">&#39;ny&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;New York&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;wt&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;Washington&#39;</span><span class="token punctuation">,</span> <span class="token comment">/* ... */</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">elseif</span> <span class="token punctuation">(</span><span class="token variable">$country</span> <span class="token operator">==</span> <span class="token string single-quoted-string">&#39;de&#39;</span><span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token variable">$input</span><span class="token operator">-&gt;</span><span class="token function">addSelect</span><span class="token punctuation">(</span><span class="token string single-quoted-string">&#39;state&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;Select your state&#39;</span><span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token string single-quoted-string">&#39;by&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;Bavaria&#39;</span><span class="token punctuation">,</span> <span class="token string single-quoted-string">&#39;ber&#39;</span> <span class="token operator">=&gt;</span> <span class="token string single-quoted-string">&#39;Berlin&#39;</span><span class="token punctuation">,</span> <span class="token comment">/* ... */</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token keyword">return</span> <span class="token variable">$input</span><span class="token punctuation">;</span> <span class="token punctuation">}</span> <span class="token punctuation">}</span> </span></code></pre></div><p>When selecting country <code>United States</code> and state <code>New York</code>, the data stored in the database will look like this:</p><div class="language-json"><pre><code><span class="token punctuation">{</span> <span class="token property">&quot;country&quot;</span><span class="token operator">:</span> <span class="token string">&quot;us&quot;</span><span class="token punctuation">,</span> <span class="token property">&quot;state&quot;</span><span class="token operator">:</span> <span class="token string">&quot;New York&quot;</span> <span class="token punctuation">}</span> </code></pre></div>`,41),p=[o];function l(i,d,c,r,u,h){return a(),n("div",null,p)}var y=t(e,[["render",l]]);export{g as __pageData,y as default};
457.857143
7,788
0.706084
73f1bf464634333614e3dc0aee362c269aac2ae0
5,219
js
JavaScript
src/controllers/admin/client-details.controller.js
commerceblock/Mainstay-API
e000c69f754e2a34f18e4485d38a79cf2f0471d4
[ "MIT" ]
1
2019-06-19T23:35:52.000Z
2019-06-19T23:35:52.000Z
src/controllers/admin/client-details.controller.js
commerceblock/Mainstay-API
e000c69f754e2a34f18e4485d38a79cf2f0471d4
[ "MIT" ]
136
2018-11-22T15:45:14.000Z
2022-02-26T11:24:30.000Z
src/controllers/admin/client-details.controller.js
commerceblock/mainstay-view
e000c69f754e2a34f18e4485d38a79cf2f0471d4
[ "MIT" ]
1
2020-01-23T15:51:58.000Z
2020-01-23T15:51:58.000Z
const uuidv4 = require('uuid/v4'); const elliptic = require('elliptic'); const models = require('../../models/models'); const ec = new elliptic.ec('secp256k1'); class ClientDetailsController { async list(req, res, next) { const clientDetailsModel = models.clientDetails; try { const list = await clientDetailsModel.find(); res.json({data: list}); } catch (error) { next(error); } } async post(req, res, next) { const clientDetailsModel = models.clientDetails; const clientCommitmentModel = models.clientCommitment; let clientName = ''; let publicKey = ''; let authToken; if (req.body.pubkey && req.body.pubkey.trim()) { publicKey = req.body.pubkey.trim(); try { const publicKeyEc = ec.keyFromPublic(publicKey, 'hex'); const {result, reason} = publicKeyEc.validate(); if (!result) { return res.status(400).json({ error: 'error_public_key', message: `Invalid Public Key: ${reason}` }); } } catch (error) { return res.status(400).json({ error: 'error_public_key', message: `Invalid Public Key: ${error.message}` }); } } if (req.body.client_name && req.body.client_name.trim()) { clientName = req.body.client_name.trim(); } if (req.body.auth_token && req.body.auth_token.trim()) { authToken = req.body.auth_token.trim(); } else { authToken = uuidv4(); } try { // fetch item with max client_position const maxPositionClientDetails = await clientDetailsModel .findOne() .sort({client_position: -1}) .limit(1); let nextClientPosition; if (maxPositionClientDetails === null) { nextClientPosition = 0; } else { nextClientPosition = maxPositionClientDetails.client_position + 1; } // create new client-detail const clientDetailsData = { client_position: nextClientPosition, auth_token: authToken, client_name: clientName, pubkey: publicKey, }; const clientDetails = new clientDetailsModel(clientDetailsData); await clientDetails.save(); // create client-commitment const clientCommitmentData = { client_position: clientDetails.client_position, commitment: '0000000000000000000000000000000000000000000000000000000000000000' }; const clientCommitment = new clientCommitmentModel(clientCommitmentData); await clientCommitment.save(); res.status(201).json({ data: { clientDetails, clientCommitment } }); } catch (error) { next(error); } } async put(req, res, next) { const clientDetailsModel = models.clientDetails; const _id = req.body._id; let clientName = ''; let publicKey = ''; let authToken = ''; if (req.body.pubkey && req.body.pubkey.trim()) { publicKey = req.body.pubkey.trim(); try { const publicKeyEc = ec.keyFromPublic(publicKey, 'hex'); const {result, reason} = publicKeyEc.validate(); if (!result) { return res.status(400).json({ error: 'error_public_key', message: `Invalid Public Key: ${reason}` }); } } catch (error) { return res.status(400).json({ error: 'error_public_key', message: `Invalid Public Key: ${error.message}` }); } } if (req.body.client_name && req.body.client_name.trim()) { clientName = req.body.client_name.trim(); } if (req.body.auth_token && req.body.auth_token.trim()) { authToken = req.body.auth_token.trim(); } else { authToken = uuidv4(); } try { const clientDetails = await clientDetailsModel.findOne({_id}); if (!clientDetails) { return res.status(404).json({ error: { code: 'client_not_found', message: 'Client not found' } }); } clientDetails.auth_token = authToken; clientDetails.pubkey = publicKey; clientDetails.client_name = clientName; await clientDetails.save(); return res.json({ data: clientDetails }); } catch (e) { next(e); } } } module.exports = new ClientDetailsController();
32.61875
94
0.496455
73f1d53aa8832e6d53f8e528240e1dda1790a041
485
js
JavaScript
converter.js
cshum/levi-chinese
33af47ad3f2b088e542c32a67465f559a68f5158
[ "MIT" ]
2
2015-09-15T10:38:31.000Z
2016-08-13T00:49:02.000Z
converter.js
cshum/levi-chinese
33af47ad3f2b088e542c32a67465f559a68f5158
[ "MIT" ]
null
null
null
converter.js
cshum/levi-chinese
33af47ad3f2b088e542c32a67465f559a68f5158
[ "MIT" ]
null
null
null
var ginga = require('ginga') var H = require('highland') var t2s = require('./t2s.json') var UNI = /[^\x00-\xFF]/g // traditional/simplified chinese conversion module.exports = function converter (map) { map = map || t2s function replaceFn (s) { return (s in map) ? map[s] : s } function convert (str) { return str.replace(UNI, replaceFn) } return ginga().use('pipeline', function (ctx) { ctx.tokens = H(ctx.tokens).map(convert) }) }
22.045455
50
0.608247
73f2bbe7d7c08742c0d54af9f275b97f416b3ead
2,341
js
JavaScript
utils/util.js
DongZhe93/miniprogram-connect-bluetooth-device
fcb89911efbc69cb3d5bdaf6e5125358bfec9341
[ "Apache-2.0" ]
null
null
null
utils/util.js
DongZhe93/miniprogram-connect-bluetooth-device
fcb89911efbc69cb3d5bdaf6e5125358bfec9341
[ "Apache-2.0" ]
null
null
null
utils/util.js
DongZhe93/miniprogram-connect-bluetooth-device
fcb89911efbc69cb3d5bdaf6e5125358bfec9341
[ "Apache-2.0" ]
null
null
null
// 根据设备Id拿到随机数解密密钥 function getAESKeyFromDeiviceId(deviceBleId) { const idArray = str2Bytes(deviceBleId).reverse(); // 按照文档截取成数组,且是反序 const AESKey = [] AESKey[0] = idArray[0]; AESKey[1] = idArray[1]; AESKey[2] = idArray[2]; AESKey[3] = idArray[3]; AESKey[4] = idArray[4]; AESKey[5] = idArray[5]; AESKey[6] = idArray[0] + idArray[1]; AESKey[7] = idArray[1] + idArray[2]; AESKey[8] = idArray[2] + idArray[3]; AESKey[9] = idArray[3] + idArray[4]; AESKey[10] = idArray[4] + idArray[5]; AESKey[11] = idArray[0] - idArray[1]; AESKey[12] = idArray[1] - idArray[2]; AESKey[13] = idArray[2] - idArray[3]; AESKey[14] = idArray[3] - idArray[4]; AESKey[15] = idArray[4] - idArray[5]; return AESKey } // 随机16位数据 function getRandom16() { var dataArray = [] for (let i = 0; i < 16; i++) { dataArray.push(Math.random() * 255 | 0) } return bytes2Str(dataArray) } // 数组中是否存在 function inArray(arr, key, val) { for (let i = 0; i < arr.length; i++) { if (arr[i][key] === val) { return i; } } return -1; } // 字符串转16进制数组 function str2Bytes(str) { let pos = 0; let len = str.length; if (len % 2 !== 0) { return null; } len /= 2; const hexA = []; for (let i = 0; i < len; i++) { const s = str.substr(pos, 2); let v = parseInt(s, 16); if (v >= 127) v = v - 255 - 1 hexA.push(v); pos += 2; } return hexA; } // 字节数组转十六进制字符串 function bytes2Str(arr) { let str = ""; for (let i = 0; i < arr.length; i++) { let tmp; const num = arr[i]; if (num < 0) { //此处填坑,当byte因为符合位导致数值为负时候,需要对数据进行处理 tmp = (255 + num + 1).toString(16); } else { tmp = num.toString(16); } if (tmp.length === 1) { tmp = "0" + tmp; } str += tmp; } return str; } // ArrayBuffer转16进度字符串 function ab2hex(buffer) { var hexArr = Array.prototype.map.call( new Uint8Array(buffer), function (bit) { return ('00' + bit.toString(16)).slice(-2) } ) return hexArr.join(''); } // 16进制字符串转ArrayBuffer function hex2ab(hex) { var view = new Uint8Array(hex.length / 2) for (var i = 0; i < hex.length; i += 2) { view[i / 2] = parseInt(hex.substring(i, i + 2), 16) } return view.buffer } module.exports = { getAESKeyFromDeiviceId, getRandom16, inArray, str2Bytes, bytes2Str, ab2hex, hex2ab }
21.09009
69
0.573259
73f3a0a768c98bcef0396a627126f4c76a704a8b
670
js
JavaScript
dist/src/api/controllers/requests/TargetTypeRequest.js
FarmCheck/farm-service
26d8ffd4e2221813ff9c056828ca1d51d10749d2
[ "MIT" ]
null
null
null
dist/src/api/controllers/requests/TargetTypeRequest.js
FarmCheck/farm-service
26d8ffd4e2221813ff9c056828ca1d51d10749d2
[ "MIT" ]
null
null
null
dist/src/api/controllers/requests/TargetTypeRequest.js
FarmCheck/farm-service
26d8ffd4e2221813ff9c056828ca1d51d10749d2
[ "MIT" ]
null
null
null
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.UpdateTargetTypeBody = void 0; const tslib_1 = require("tslib"); const class_transformer_1 = require("class-transformer"); const class_validator_1 = require("class-validator"); // class CreateTargetTypeBody extends BaseTargetType {} class UpdateTargetTypeBody { } tslib_1.__decorate([ class_transformer_1.Expose(), class_validator_1.IsOptional(), class_validator_1.IsString(), tslib_1.__metadata("design:type", String) ], UpdateTargetTypeBody.prototype, "name", void 0); exports.UpdateTargetTypeBody = UpdateTargetTypeBody; //# sourceMappingURL=TargetTypeRequest.js.map
39.411765
62
0.779104
73f450e0500214b450e2893ff4b849b64bee866b
663
js
JavaScript
middlewares/misc.js
theworkflow/iot-home
8f23348dc5cb29f7243dda21be22d231b92e0e4f
[ "MIT" ]
null
null
null
middlewares/misc.js
theworkflow/iot-home
8f23348dc5cb29f7243dda21be22d231b92e0e4f
[ "MIT" ]
2
2015-04-13T17:10:40.000Z
2015-04-13T17:12:58.000Z
middlewares/misc.js
theworkflow/iot-home
8f23348dc5cb29f7243dda21be22d231b92e0e4f
[ "MIT" ]
null
null
null
const Util = require('util') const Debug = require('debug')('iot-home:middlewares:misc') const Helpers = require('./../helpers/helpers') var Miscellaneous = {} Debug('init') function Misc (server) { if (server) require('./../server/miscRoutes').init(server, Misc) else throw new Error('SERVER_NOT_INITIALIZED') } Miscellaneous.init = (server) => { return new Misc(server) } Misc.index = (req, res, next) => { Debug('Index') return res.send('Hello') } Misc.miscRoute = (req, res, next) => { var error = Util.format('%s not found', req.url) Debug('miscRoute') return Helpers.sendFailureResponse(res, error) } module.exports = Miscellaneous
20.71875
66
0.677225
73f60adf1164918da54dbc413a2353d778276df9
2,017
js
JavaScript
src/interfaces/EditInterface/EditInterface.test.js
peterboehm/ui-organizations
a6ee1b561eb3dd8980d82b307172d73a03e37218
[ "Apache-2.0" ]
null
null
null
src/interfaces/EditInterface/EditInterface.test.js
peterboehm/ui-organizations
a6ee1b561eb3dd8980d82b307172d73a03e37218
[ "Apache-2.0" ]
344
2019-04-12T12:11:22.000Z
2022-03-31T16:53:04.000Z
src/interfaces/EditInterface/EditInterface.test.js
peterboehm/ui-organizations
a6ee1b561eb3dd8980d82b307172d73a03e37218
[ "Apache-2.0" ]
4
2019-10-01T07:36:09.000Z
2022-02-23T13:59:30.000Z
import React from 'react'; import { render } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { useHistory } from 'react-router'; import { HasCommand, } from '@folio/stripes/components'; import { orgInterface } from '../../../test/jest/fixtures'; import { ORGANIZATIONS_ROUTE } from '../../common/constants'; import EditInterface from './EditInterface'; jest.mock('react-router', () => ({ ...jest.requireActual('react-router'), useHistory: jest.fn(), })); jest.mock('@folio/stripes-components/lib/Commander', () => ({ HasCommand: jest.fn(({ children }) => <div>{children}</div>), })); const defaultProps = { onSubmit: jest.fn(), initialValues: orgInterface, onClose: jest.fn(), paneTitle: orgInterface.firstName, }; const renderEditInterface = (props = defaultProps) => render( <EditInterface {...props} />, { wrapper: MemoryRouter }, ); describe('EditContact', () => { beforeEach(() => { global.document.createRange = global.document.originalCreateRange; }); afterEach(() => { global.document.createRange = global.document.mockCreateRange; }); it('should render correct form structure', () => { const { asFragment } = renderEditInterface(); expect(asFragment()).toMatchSnapshot(); }); describe('Shortcuts', () => { beforeEach(() => { HasCommand.mockClear(); }); it('should cancel form when cancel shortcut is called', () => { renderEditInterface(); HasCommand.mock.calls[0][0].commands.find(c => c.name === 'cancel').handler(); expect(defaultProps.onClose).toHaveBeenCalled(); }); it('should navigate to list view when search shortcut is called', () => { const pushMock = jest.fn(); useHistory.mockClear().mockReturnValue({ push: pushMock, }); renderEditInterface(); HasCommand.mock.calls[0][0].commands.find(c => c.name === 'search').handler(); expect(pushMock).toHaveBeenCalledWith(ORGANIZATIONS_ROUTE); }); }); });
26.893333
84
0.644522
73f6168db598ca3156adc9439bc98592cc9029e6
489
js
JavaScript
build/webpack/webpack.common.js
ngocsangyem/static-blog
761eb2093566f4c3ab23d024936f102887bb6aa9
[ "MIT" ]
null
null
null
build/webpack/webpack.common.js
ngocsangyem/static-blog
761eb2093566f4c3ab23d024936f102887bb6aa9
[ "MIT" ]
null
null
null
build/webpack/webpack.common.js
ngocsangyem/static-blog
761eb2093566f4c3ab23d024936f102887bb6aa9
[ "MIT" ]
null
null
null
const { paths, config } = require('../utils'); const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin'); const WebpackCommonConfig = { target: 'web', module: { rules: [ { test: /\.(ts)$/, exclude: /(node_modules|bower_components)/, loader: 'awesome-typescript-loader', }, ], }, resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx'], alias: config.alias, plugins: [new TsconfigPathsPlugin()], }, }; module.exports = { WebpackCommonConfig };
19.56
69
0.619632
73f64ef4f83625390ca1ea227735178cd4ef9e02
1,364
js
JavaScript
src/dictionary/gnomish.js
alvarocastro/wow-lexicon
2efb05006bed98d1a6ae62e7d390c7792e1aa883
[ "MIT" ]
2
2019-12-01T14:19:58.000Z
2021-06-23T06:53:01.000Z
src/dictionary/gnomish.js
alvarocastro/wow-lexicon
2efb05006bed98d1a6ae62e7d390c7792e1aa883
[ "MIT" ]
46
2020-03-23T15:57:10.000Z
2022-02-10T11:42:12.000Z
src/dictionary/gnomish.js
alvarocastro/wow-lexicon
2efb05006bed98d1a6ae62e7d390c7792e1aa883
[ "MIT" ]
2
2021-01-06T09:03:52.000Z
2021-05-06T08:26:08.000Z
module.exports = { 1: ['a', 'c', 'd', 'e', 'f', 'g', 'i', 'o', 't'], 2: ['am', 'ga', 'ke', 'lo', 'ok', 'so', 'ti', 'um', 'va', 'we'], 3: ['bur', 'dun', 'fez', 'giz', 'gal', 'gar', 'her', 'mik', 'mor', 'mos', 'nid', 'rod', 'zah'], 4: ['buma', 'cost', 'dani', 'gear', 'gosh', 'grum', 'helm', 'hine', 'huge', 'lock', 'kahs', 'rand', 'riff', 'rune'], 5: ['algos', 'angor', 'dagem', 'frend', 'goten', 'haven', 'havis', 'mitta', 'modan', 'modor', 'nagin', 'tiras', 'thros', 'weird'], 6: ['danieb', 'drugan', 'dumssi', 'gizber', 'haldir', 'helmok', 'mergud', 'protos', 'revosh', 'rugosh', 'shermt', 'waldor'], 7: ['bergrim', 'costirm', 'ferdosr', 'ganrokh', 'geardum', 'godling', 'haidren', 'havagun', 'noxtyec', 'scrutin', 'sturome', 'thorneb'], 8: ['aldanoth', 'azregorn', 'bolthelm', 'botlikin', 'dimligar', 'gefrunon', 'godunmug', 'grumgizr', 'kahsgear', 'kahzregi', 'landivar', 'methrine', 'mikthros', 'misfaran', 'nandiger', 'thulmane'], 9: ['angordame', 'elodergim', 'elodmodor', 'naggirath', 'nockhavis'], 10: ['ahzodaugum', 'alegaskron', 'algosgoten', 'danavandar', 'dyrstagist', 'falhadrink', 'frendgalva', 'mosgodunan', 'mundgizber', 'naginbumat', 'sihnvulden', 'throsigear', 'vustrangin'], 11: ['ferdosmodan', 'gizbarlodun', 'haldjinagin', 'helmokheram', 'kahzhaldren', 'lockrevoshi', 'robuswaldir', 'skalfgizgar', 'thrunon’gol', 'thumanerand'] };
97.428571
197
0.577713
73f65affdce9a7f5d53d98b2d7c2275468e0035d
711
js
JavaScript
commands/unban.js
peopu/aku
446e6a9bf6b21b9bd65b39d8623b47289366c50f
[ "MIT" ]
1
2021-07-25T15:27:33.000Z
2021-07-25T15:27:33.000Z
commands/unban.js
peopu/aku
446e6a9bf6b21b9bd65b39d8623b47289366c50f
[ "MIT" ]
null
null
null
commands/unban.js
peopu/aku
446e6a9bf6b21b9bd65b39d8623b47289366c50f
[ "MIT" ]
null
null
null
exports.run = (client, message, args) => { const reason = args.slice(1).join(' '); client.unbanReason = reason; client.unbanAuth = message.author; const user = args[0]; const modlog = client.channels.find('name', 'mod-log'); if (!modlog) return message.reply('Nie moge znalesc kanalu mod-log'); if (reason.length < 1) return message.reply('Musisz dac powod'); if (!user) return message.reply('Nie podales ID uzytkownika,').catch(console.error); message.guild.unban(user); }; exports.conf = { enabled: true, guildOnly: false, aliases: [], permLevel: 2 }; exports.help = { name: 'unban', description: 'Unbanuje zbanowanego uzytkownika. PV:2', usage: 'unban [IDosoby] [powod]' };
28.44
86
0.673699
73f673f4888b4a8586ffba8df8c8ca521229099b
1,657
js
JavaScript
front-end/sentimentbot/src/Components/CreatorPage/austinModal.js
lsgitprojects/labs10-sentiment
8b64163b752b1dc87f0dca93ebeb76585ebc8473
[ "MIT" ]
5
2019-02-12T22:59:35.000Z
2020-03-12T04:16:03.000Z
front-end/sentimentbot/src/Components/CreatorPage/austinModal.js
lsgitprojects/labs10-sentiment
8b64163b752b1dc87f0dca93ebeb76585ebc8473
[ "MIT" ]
1
2019-03-28T17:20:24.000Z
2019-03-28T17:20:24.000Z
front-end/sentimentbot/src/Components/CreatorPage/austinModal.js
lsgitprojects/labs10-sentiment
8b64163b752b1dc87f0dca93ebeb76585ebc8473
[ "MIT" ]
4
2019-02-13T17:28:28.000Z
2019-04-03T00:05:05.000Z
import React from 'react'; import { Modal, ModalHeader, ModalBody, Button, ModalFooter } from 'reactstrap'; import Austin from "../PNG/AustinBot.png" class AustinModal extends React.Component { constructor(props) { super(props); this.state = { modal: false, }; this.toggle = this.toggle.bind(this); } toggle() { this.setState(prevState => ({ modal: !prevState.modal })); } render() { return ( <div> <Button color="secondary" onClick={this.toggle}>Meet Me!</Button> <Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}> <ModalHeader toggle={this.toggle}>Austin</ModalHeader> <ModalBody> <div className="austin-modal-container"> <p>Austin has a love for food, tech, edm, movies, and gaming. Favorite cities include Hong Kong and Seattle. He put blood, sweat and tears (okay, maybe no blood) into this application. Here's hoping you love it as much as he does!</p> <img src={Austin} width="300" height="300" alt="austin" className="austin-bot" /> <div className="austin-link-container"> <a href="https://www.instagram.com/abikblake/">Instagram</a> <a href="https://github.com/dyiar">Github</a> <a href="https://www.linkedin.com/in/austblake11/">LinkedIn</a> </div> </div> </ModalBody> <ModalFooter> <Button color="secondary" onClick={this.toggle}>Return</Button> </ModalFooter> </Modal> </div> ); } } export default AustinModal;
33.14
246
0.596258
73f705e4080fc7d3a94103ec9c54582c9de856d1
143
js
JavaScript
actions/playerstate.js
jamiehenson/trivia
6833caba2a25d21b552fd0bc35041d3a7df20456
[ "MIT" ]
null
null
null
actions/playerstate.js
jamiehenson/trivia
6833caba2a25d21b552fd0bc35041d3a7df20456
[ "MIT" ]
null
null
null
actions/playerstate.js
jamiehenson/trivia
6833caba2a25d21b552fd0bc35041d3a7df20456
[ "MIT" ]
null
null
null
var Reflux = require('reflux'); var PlayerActions = Reflux.createActions([ 'createNote', 'editNote' ]); module.exports = PlayerActions;
17.875
42
0.706294
73f977179848ce66f117c3d58a22744cce7f0d80
1,861
js
JavaScript
packages/ConferenceApp/src/content-single/ChildContentFeed/index.js
watermarkchurch/clc-conference-app
4a709b0bdd0908ade042cb03b7ce1aa9bf63a31d
[ "MIT" ]
1
2019-02-21T21:34:56.000Z
2019-02-21T21:34:56.000Z
packages/ConferenceApp/src/content-single/ChildContentFeed/index.js
watermarkchurch/clc-conference-app
4a709b0bdd0908ade042cb03b7ce1aa9bf63a31d
[ "MIT" ]
61
2019-03-05T02:43:20.000Z
2021-06-21T21:55:38.000Z
packages/ConferenceApp/src/content-single/ChildContentFeed/index.js
watermarkchurch/clc-conference-app
4a709b0bdd0908ade042cb03b7ce1aa9bf63a31d
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import { get } from 'lodash'; import PropTypes from 'prop-types'; import { withNavigation } from 'react-navigation'; import { Query } from 'react-apollo'; import { PaddedView, H4 } from '@apollosproject/ui-kit'; import ScheduleItem from '../../ui/ScheduleItem'; import getChildContent from './getChildContent'; class HorizontalContentFeed extends Component { static propTypes = { contentId: PropTypes.string, navigation: PropTypes.shape({ push: PropTypes.func, }), }; handleOnPressItem = (item) => { this.props.navigation.push('ContentSingle', { itemId: item.id, }); }; renderItem = (item) => ( <ScheduleItem {...item} startTime={null} endTime={null} key={item.id} onPress={() => this.handleOnPressItem(item)} /> ); renderFeed = ({ data, loading, error }) => { if (error) return null; const childContent = get( data, 'node.childContentItemsConnection.edges', [] ).map((edge) => edge.node); const content = childContent; return (content && content.length) || loading ? ( <React.Fragment> <PaddedView vertical={false}> <H4 padded isLoading={(!content || !content.length) && loading}> Sessions </H4> </PaddedView> {content.map(this.renderItem)} </React.Fragment> ) : null; }; render() { if (!this.props.contentId) return this.renderFeed({ loading: true }); return ( <Query query={getChildContent} fetchPolicy="cache-and-network" variables={{ itemId: this.props.contentId, showLabel: !this.props.contentId.includes('Breakouts'), }} > {this.renderFeed} </Query> ); } } export default withNavigation(HorizontalContentFeed);
24.168831
74
0.600752
73f9b9d90f11fcdc6555d7544da267596b1fec25
425
js
JavaScript
seeds/001_director.js
genacatharine/movieapp
bf5fa301462b6ab09da0a5729347acf1a5398ff5
[ "MIT" ]
null
null
null
seeds/001_director.js
genacatharine/movieapp
bf5fa301462b6ab09da0a5729347acf1a5398ff5
[ "MIT" ]
null
null
null
seeds/001_director.js
genacatharine/movieapp
bf5fa301462b6ab09da0a5729347acf1a5398ff5
[ "MIT" ]
null
null
null
exports.seed = function(knex, Promise) { // Deletes ALL existing entries return knex('director').del() .then(function () { // Inserts seed entries return knex('director').insert([ {id: 1, name: 'Steven Spielberg', nationality: 'American'}, {id: 2, name: 'Quentin Tarentino', nationality: 'American'}, {id: 3, name: 'James Cameron', nationality: 'Canadian'}, ]); }); };
28.333333
68
0.590588
73fa8ddaff5ce7ba311e0f23923c2225a927eedc
1,111
js
JavaScript
src/core/Context.js
rdad/PP.js
dea683d00718d5706cf6a37b9ba9fde071132889
[ "MIT" ]
19
2015-03-22T16:15:05.000Z
2021-11-06T18:21:36.000Z
src/core/Context.js
mcanthony/PP.js
dea683d00718d5706cf6a37b9ba9fde071132889
[ "MIT" ]
null
null
null
src/core/Context.js
mcanthony/PP.js
dea683d00718d5706cf6a37b9ba9fde071132889
[ "MIT" ]
1
2015-10-10T05:59:17.000Z
2015-10-10T05:59:17.000Z
PP.Context = function ( parameters ) { parameters = parameters || {}; this.dimension = (typeof parameters.dimension == 'undefined') ? PP.config.dimension : parameters.dimension; // --- scene this.scene = new THREE.Scene(); // --- camera this.camera = new THREE.Camera(); this.camera.projectionMatrix = THREE.Matrix4.makeOrtho( this.dimension.width / - 2, this.dimension.width / 2, this.dimension.height / 2, this.dimension.height / - 2, -10000, 10000 ); this.camera.position.z = PP.config.camera.z; // --- quad this.quad = new THREE.Mesh( new THREE.PlaneGeometry( 1, 1 ), new THREE.MeshBasicMaterial() ); this.quad.position.z = -500; this.quad.scale.set( this.dimension.width, this.dimension.height, 1 ); if(typeof parameters.quadReverse != 'undefined') { this.quad.doubleSided = true; this.quad.scale.y = - this.quad.scale.y; } this.scene.addObject( this.quad ); };
37.033333
194
0.555356
73fac78c3c6bd3bc9b95ca105cc86f25d041cbea
4,991
js
JavaScript
dist/models/precincts.js
hankthemason/knowyourcops.nyc
38656364fbc821fc76e139039916133240849f38
[ "MIT" ]
null
null
null
dist/models/precincts.js
hankthemason/knowyourcops.nyc
38656364fbc821fc76e139039916133240849f38
[ "MIT" ]
null
null
null
dist/models/precincts.js
hankthemason/knowyourcops.nyc
38656364fbc821fc76e139039916133240849f38
[ "MIT" ]
1
2021-07-07T16:04:09.000Z
2021-07-07T16:04:09.000Z
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.Precincts = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var Precincts = /*#__PURE__*/function () { function Precincts(db) { (0, _classCallCheck2.default)(this, Precincts); this.db = db; } (0, _createClass2.default)(Precincts, [{ key: "init", value: function () { var _init = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee() { return _regenerator.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return this.db.run("CREATE TABLE IF NOT EXISTS precincts (\n\t\t\t\tid INTEGER PRIMARY KEY\n\t\t\t\t);"); case 2: case "end": return _context.stop(); } } }, _callee, this); })); function init() { return _init.apply(this, arguments); } return init; }() }, { key: "create", value: function () { var _create = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee2(precinct) { var command, match, precinct_id; return _regenerator.default.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.prev = 0; if (!(precinct.precinct !== '')) { _context2.next = 4; break; } _context2.next = 4; return this.db.run("INSERT INTO precincts(id) VALUES('".concat(precinct.precinct, "')")); case 4: //step 1: look at command_at_incident and parse an int (precinct) from it (if it exists) command = precinct.command_at_incident; match = command.match(/(.*) (?:PCT)?(?:DET)?$/); precinct_id = match && match[1] ? parseInt(match[1]) || null : null; //step 2: check precinct table to see if a corresponding row exists yet; //if not, we need to make that row in the precincts table if (!precinct_id) { _context2.next = 10; break; } _context2.next = 10; return this.db.run("\n\t\t\t\tINSERT OR IGNORE INTO\n\t\t\t\t\tprecincts(id)\n\t\t\t\tVALUES\n\t\t\t\t\t(".concat(precinct_id, ")\n\t\t\t")); case 10: _context2.next = 19; break; case 12: _context2.prev = 12; _context2.t0 = _context2["catch"](0); if (!(_context2.t0 && !_context2.t0.message.match(/SQLITE_CONSTRAINT:.*/))) { _context2.next = 19; break; } console.log(_context2.t0.message); console.log('error in populating precincts'); console.log(precinct); throw _context2.t0.message; case 19: case "end": return _context2.stop(); } } }, _callee2, this, [[0, 12]]); })); function create(_x) { return _create.apply(this, arguments); } return create; }() }, { key: "read", value: function () { var _read = (0, _asyncToGenerator2.default)( /*#__PURE__*/_regenerator.default.mark(function _callee3() { var result; return _regenerator.default.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.prev = 0; _context3.next = 3; return this.db.all("\n\t\t\t\tSELECT \n\t\t\t\t\t*\n\t\t\t\tFROM\n\t\t\t\t\tprecincts"); case 3: result = _context3.sent; return _context3.abrupt("return", result); case 7: _context3.prev = 7; _context3.t0 = _context3["catch"](0); console.error(_context3.t0); case 10: case "end": return _context3.stop(); } } }, _callee3, this, [[0, 7]]); })); function read() { return _read.apply(this, arguments); } return read; }() }]); return Precincts; }(); exports.Precincts = Precincts;
32.2
158
0.528752
73fada316a24954faac2a57f3cfc86943e9e5405
2,116
js
JavaScript
app/components/geschaeft/DateField.js
barbalex/kapla
a427acd7d9d18c03f55920d583782638ec43d1b1
[ "MIT" ]
null
null
null
app/components/geschaeft/DateField.js
barbalex/kapla
a427acd7d9d18c03f55920d583782638ec43d1b1
[ "MIT" ]
null
null
null
app/components/geschaeft/DateField.js
barbalex/kapla
a427acd7d9d18c03f55920d583782638ec43d1b1
[ "MIT" ]
null
null
null
import React, { PropTypes } from 'react' import { FormGroup, InputGroup, FormControl, ControlLabel, Glyphicon, } from 'react-bootstrap' import moment from 'moment' import DateRangePicker from 'react-bootstrap-daterangepicker' import styles from './dateField.css' import getDateValidationStateDate from '../../src/getDateValidationStateDate' moment.locale('de') const DateField = ({ geschaeft, name, label, change, blur, onChangeDatePicker, tabIndex, }) => { /** * need to give addon no padding * and the originally addon's padding to the glyphicon * to make entire addon clickable * for opening calendar */ const datePickerAddonStyle = { padding: 0, } const datePickerCalendarStyle = { paddingTop: 6, paddingBottom: 6, paddingLeft: 12, paddingRight: 12, } return ( <FormGroup className={styles.field} validationState={getDateValidationStateDate(geschaeft[name])} > <ControlLabel> {label} </ControlLabel> <InputGroup> <FormControl type="text" value={geschaeft[name] || ''} name={name} onChange={change} onBlur={blur} bsSize="small" tabIndex={tabIndex} /> <InputGroup.Addon style={datePickerAddonStyle}> <DateRangePicker singleDatePicker drops="up" opens="left" onApply={onChangeDatePicker.bind(this, name)} className={styles.datePicker} > <Glyphicon glyph="calendar" style={datePickerCalendarStyle} /> </DateRangePicker> </InputGroup.Addon> </InputGroup> </FormGroup> ) } DateField.displayName = 'DateField' DateField.propTypes = { geschaeft: PropTypes.object.isRequired, name: PropTypes.string.isRequired, label: PropTypes.string.isRequired, change: PropTypes.func.isRequired, blur: PropTypes.func.isRequired, onChangeDatePicker: PropTypes.func.isRequired, tabIndex: PropTypes.number.isRequired, } export default DateField
23.252747
77
0.634688
73fd167635b4a2773bc4492bc1a66a8c4af198f9
440
js
JavaScript
day4/3.express/4.usetemplate.js
Crystal2030/nodestudy
5b79f6c68ccfbe773d992de2fc7f40ad1400106e
[ "MIT" ]
null
null
null
day4/3.express/4.usetemplate.js
Crystal2030/nodestudy
5b79f6c68ccfbe773d992de2fc7f40ad1400106e
[ "MIT" ]
null
null
null
day4/3.express/4.usetemplate.js
Crystal2030/nodestudy
5b79f6c68ccfbe773d992de2fc7f40ad1400106e
[ "MIT" ]
null
null
null
var express = require('express'); var path = require('path'); var app = express(); /** * 1.动态内容 当前时间 * 2.静态内容 当前tmpl.html * 3.动静结合 */ app.get('/',function(req,res){ }); //配置模版引擎 app.set('view engine','ejs'); app.set('views',path.resolve('views')); app.get('/', function(req, res){ res.render('index.ejs',{title:'HOME'}) }); app.get('/reg', function(req, res){ res.render('index',{title:'REGISTER'}) }); app.listen(3000);
15.714286
42
0.602273
73fd46486d923b16ed3af99c9318310ef2acc52f
3,661
js
JavaScript
__tests__/fsmUnsubscribe.js
dreibelt/node-mqttsngw-core
9b55c9edfaa14a05d063f4142cb2da69b8ca8884
[ "MIT" ]
3
2019-01-07T13:43:22.000Z
2020-02-04T04:51:12.000Z
__tests__/fsmUnsubscribe.js
dreibelt/node-mqttsngw-core
9b55c9edfaa14a05d063f4142cb2da69b8ca8884
[ "MIT" ]
3
2018-10-29T12:43:59.000Z
2019-02-13T17:59:15.000Z
__tests__/fsmUnsubscribe.js
dreibelt/node-mqttsngw-core
9b55c9edfaa14a05d063f4142cb2da69b8ca8884
[ "MIT" ]
2
2020-02-06T02:41:10.000Z
2021-02-13T21:02:13.000Z
const EventEmitter = require('eventemitter2'); jest.mock('edfsm'); const fsmUnsubscribe = require('../fsmUnsubscribe.js'); describe('state: init', () => { test('get topic from \'normal\' topic id type', () => { const CTX = { topicIdType: 'normal', topicName: 'testtopic' }; const fsm = fsmUnsubscribe().testState('init', CTX); expect(CTX.topic).toEqual('testtopic'); expect(fsm.next.mock.calls[0][0]).toEqual('brokerUnsubscribe'); }); test('get topic from \'short topic\' topic id type', () => { const CTX = { topicIdType: 'short topic', topicName: 'ab' }; const fsm = fsmUnsubscribe().testState('init', CTX); expect(CTX.topic).toEqual('ab'); expect(fsm.next.mock.calls[0][0]).toEqual('brokerUnsubscribe'); }); test('send negativ unsuback if topic cannot determined', () => { const CTX = { topicIdType: 'pre-defined', topicId: 123 }; const fsm = fsmUnsubscribe().testState('init', CTX); expect(fsm.next.mock.calls[0][0].message).toEqual('Rejected: invalid topic ID'); }); }); describe('state: brokerUnsubscribe', () => { test('send unsubscribe request to broker', () => { const CTX = { clientKey: '::1_12345', msgId: 123, topic: 'testtopic' }; const bus = new EventEmitter(); const req = jest.fn(); bus.on(['brokerUnsubscribe', CTX.clientKey, 'req'], req); fsmUnsubscribe(bus).testState('brokerUnsubscribe', CTX); expect(req.mock.calls[0][0]).toMatchObject({ clientKey: CTX.clientKey, msgId: CTX.msgId, topic: CTX.topic }); }); test('wait for subscribe response from broker', () => { const CTX = { clientKey: '::1_12345', msgId: 123 }; const bus = new EventEmitter(); const fsm = fsmUnsubscribe(bus).testState('brokerUnsubscribe', CTX); bus.emit(['brokerUnsubscribe', CTX.clientKey, 'res'], { clientKey: CTX.clientKey, msgId: 123, error: null }); expect(fsm.next.mock.calls[0][0]).toBe(null); }); test('ignore subscribe responses from broker for other msgIds', () => { const CTX = { clientKey: '::1_12345', msgId: 123 }; const bus = new EventEmitter(); const fsm = fsmUnsubscribe(bus).testState('brokerUnsubscribe', CTX); bus.emit(['brokerUnsubscribe', CTX.clientKey, 'res'], { clientKey: CTX.clientKey, msgId: 124, error: null }); expect(fsm.next.mock.calls.length).toEqual(0); }); test('handle failed desubscription', () => { const CTX = { clientKey: '::1_12345', msgId: 123 }; const bus = new EventEmitter(); const fsm = fsmUnsubscribe(bus).testState('brokerUnsubscribe', CTX); bus.emit(['brokerUnsubscribe', CTX.clientKey, 'res'], { clientKey: CTX.clientKey, msgId: 123, error: 'Subscription failed' }); expect(fsm.next.mock.calls[0][0].message).toEqual('Rejected: congestion'); }); }); describe('final', () => { test('if err is not null, send no unsuback', () => { const CTX = { clientKey: '::1_12345', msgId: 123 }; const ERR = new Error('Rejected: invalid topic ID'); const bus = new EventEmitter(); const ack = jest.fn(); bus.on(['snUnicastOutgress', CTX.clientKey, 'unsuback'], ack); fsmUnsubscribe(bus).testState('_final', CTX, ERR); expect(ack.mock.calls.length).toBe(0); }); test('send unsuback if everything went fine', () => { const CTX = { clientKey: '::1_12345', msgId: 123, topic: 'def', topics: ['abc', 'def'] }; const bus = new EventEmitter(); const ack = jest.fn(); bus.on(['snUnicastOutgress', CTX.clientKey, 'unsuback'], ack); fsmUnsubscribe(bus).testState('_final', CTX); expect(ack.mock.calls[0][0]).toMatchObject({ clientKey: CTX.clientKey, cmd: 'unsuback', msgId: CTX.msgId }); }); });
28.601563
82
0.640809
73fe36621426ea8420aa70e1efdb232232a0ea56
2,239
es6
JavaScript
spec/javascripts/angular_services/query/query_tab_spec.js.es6
PolRod/aleph
faf94b9831c1dcda642308e2b1a1ce88bf44fa0c
[ "MIT" ]
79
2016-06-02T01:20:52.000Z
2020-07-09T22:17:17.000Z
spec/javascripts/angular_services/query/query_tab_spec.js.es6
PolRod/aleph
faf94b9831c1dcda642308e2b1a1ce88bf44fa0c
[ "MIT" ]
70
2016-06-07T00:38:53.000Z
2021-09-13T13:38:10.000Z
spec/javascripts/angular_services/query/query_tab_spec.js.es6
PolRod/aleph
faf94b9831c1dcda642308e2b1a1ce88bf44fa0c
[ "MIT" ]
18
2016-06-07T02:58:56.000Z
2020-01-17T17:25:09.000Z
'use strict'; describe('QueryTab', () => { let QueryTab; let location; beforeEach(module('alephServices')); beforeEach(inject((_QueryTab_, $location) => { QueryTab = _QueryTab_; location = $location; })); it('the defaultTag by default is query', () => { expect(QueryTab.defaultTag).toBe('query'); }); describe('#getTab', () => { describe('when tab parameter is query, visualization, or results', () => { beforeEach(() => { spyOn(location, 'search').and.returnValue({ tab: 'results' }); }); it('returns the value from the tab parameter', () => { expect(QueryTab.getTab()).toBe('results'); }); }); describe('when tab parameter is invalid (non-existant or not query, visualization, or results)', () => { beforeEach(() => { spyOn(location, 'search').and.returnValue({ tab: undefined }); }); it('returns query tab', () => { expect(QueryTab.getTab()).toBe('query'); }); }); }); describe('#setTab', () => { beforeEach(() => { spyOn(location, 'search'); QueryTab.setTab('meh'); }); it('sets search on $location for tab', () => { expect(location.search).toHaveBeenCalledWith('tab', 'meh'); }); }); describe('#setActiveTabFromUrl', () => { beforeEach(() => { spyOn(QueryTab, '_initTabs').and.callThrough(); spyOn(QueryTab, 'getTab').and.returnValue('results'); QueryTab.setActiveTabFromUrl(); }); it('sets search on $location for tab', () => { expect(QueryTab._initTabs).toHaveBeenCalled(); expect(QueryTab.state.results.active).toBeTruthy(); expect(QueryTab.state.query.active).toBeFalsy(); expect(QueryTab.state.visualizations.active).toBeFalsy(); }); }); describe('#navigateToTab', () => { beforeEach(() => { spyOn(QueryTab, 'setTab'); QueryTab.navigateToTab('results'); }); it('sets search on $location for tab', () => { expect(QueryTab.state.results.active).toBeTruthy(); expect(QueryTab.state.query.active).toBeFalsy(); expect(QueryTab.state.visualizations.active).toBeFalsy(); expect(QueryTab.setTab).toHaveBeenCalledWith('results'); }); }); });
27.9875
108
0.591335
73ff338eb3a2b57eccfd9f00bddc338340e2c20a
1,419
js
JavaScript
src/custom_components/PageNav.js
diasdestarika/TestReact
13e55c4ce6d1e61e397020f963c36ac73f09aa52
[ "MIT" ]
null
null
null
src/custom_components/PageNav.js
diasdestarika/TestReact
13e55c4ce6d1e61e397020f963c36ac73f09aa52
[ "MIT" ]
6
2020-09-08T00:57:59.000Z
2022-02-18T23:44:00.000Z
src/custom_components/PageNav.js
djsp286/frontend_neogenesis
746d98604a72306e2b5e48bcf61764ce325095bb
[ "MIT" ]
null
null
null
import React from 'react'; import PropTypes from 'prop-types'; import { Button, ButtonGroup } from 'reactstrap'; const propTypes = { First: PropTypes.func, Back: PropTypes.func, Next: PropTypes.func, Last: PropTypes.func, Page: PropTypes.number, MaxPage: PropTypes.number }; class PageNav extends React.Component { constructor(props) { super(props); } First(e) { this.props.First(e); } Back(e) { this.props.Back(e); } Next(e) { this.props.Next(e); } Last(e) { this.props.Last(e); } render() { const {Page, MaxPage} = this.props; const AdjustedMaxPage = MaxPage < 1 ? 1 : MaxPage; const AdjustedPage = Page > MaxPage ? MaxPage : Page < 1 ? 1 : Page ; const isFirst = AdjustedPage <= 1; const isLast = AdjustedPage >= MaxPage; return ( <ButtonGroup style={{ alignSelf: 'center', alignItems: 'center'}}> <Button onClick={e => this.First(e)} disabled={isFirst}>«</Button> <Button onClick={e => this.Back(e)} disabled={isFirst}>‹</Button> <Button color="white" style={{fontSize: "10pt", width: "55px"}} disabled> {AdjustedPage} / {AdjustedMaxPage} </Button> <Button onClick={e => this.Next(e)} disabled={isLast}>›</Button> <Button onClick={e => this.Last(e)} disabled={isLast}>»</Button> </ButtonGroup> ); } } PageNav.propTypes = propTypes; export default PageNav;
24.894737
130
0.620155
73ffb807a51f7089e94e2f210e20610a42d6ab46
5,120
js
JavaScript
burger-builder/src/containers/Checkout/ContactData/ContactData.js
kburudi/React-001-Tutorial
fca7b68c0ba9e1011d6526495b1fc307ff97a13a
[ "MIT" ]
null
null
null
burger-builder/src/containers/Checkout/ContactData/ContactData.js
kburudi/React-001-Tutorial
fca7b68c0ba9e1011d6526495b1fc307ff97a13a
[ "MIT" ]
27
2020-09-05T02:08:44.000Z
2022-02-26T15:19:50.000Z
burger-builder/src/containers/Checkout/ContactData/ContactData.js
kburudi/React-001-Tutorial
fca7b68c0ba9e1011d6526495b1fc307ff97a13a
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import { connect } from 'react-redux'; import axios from '../../../axios-orders'; import ContactDataCss from './ContactData.css'; import Button from '../../../components/UI/Button/Button'; import Spinner from '../../../components/UI/Spinner/Spinner'; import Input from '../../../components/UI/Input/Input'; import withErrorHandler from '../../../hoc/withErrorHandler/withErrorHandler'; import { purchaseBurger } from '../../../store/actions/order.js'; class ContactData extends Component { state = { orderForm: { name: { elementType: 'input', elementConfig: { type: 'text', placeholder: 'Your Name' }, value: '', validation: { required: true }, valid: false, touched: false }, email: { elementType: 'input', elementConfig: { type: 'text', placeholder: 'Your Email' }, value: '', validation: { required: true }, valid: false, touched: false }, country: { elementType: 'input', elementConfig: { type: 'text', placeholder: 'Country' }, value: '', validation: { required: true }, valid: false, touched: false }, street: { elementType: 'input', elementConfig: { type: 'text', placeholder: 'Your Street' }, value: '', validation: { required: true }, valid: false, touched: false }, postalCode: { elementType: 'input', elementConfig: { type: 'text', placeholder: 'Postal Code' }, value: '', validation: { required: true, minLength: 3, maxLength: 6, }, valid: false, touched: false }, deliveryMethod: { elementType: 'select', elementConfig: { options: [ { value: 'fastest', displayValue: 'Fastest' }, { value: 'cheapest', displayValue: 'Cheapest' }, ] }, value: 'fastest', valid: true, validation: {} } }, formIsValid: false, } orderHandler = (e) => { e.preventDefault() const formData = {}; for (let formElId in this.state.orderForm) { formData[formElId] = this.state.orderForm[formElId].value; } const orderData = { ingredients: this.props.ingredients, price: this.props.price, orderData: formData, } this.props.onBurgerOrder(orderData); document.getElementById('contact-form').reset(); } inputChangedHandler = (e, inputId) => { const updatedOrderForm = { ...this.state.orderForm }; const updatedFormEl = { ...updatedOrderForm[inputId] }; updatedFormEl.value = e.target.value; updatedFormEl.touched = true updatedFormEl.valid = this.checkValid(updatedFormEl.value, updatedFormEl.validation); updatedOrderForm[inputId] = updatedFormEl; let formIsValid = true; for (let inputId in updatedOrderForm) { formIsValid = updatedOrderForm[inputId].valid && formIsValid; } this.setState({ orderForm: updatedOrderForm, formIsValid: formIsValid }); } checkValid = (value, rules) => { let isValid = true; if (rules.required) { isValid = value.trim() !== '' && isValid; } if (rules.minLength) { isValid = value.length >= rules.minLength && isValid; } if (rules.maxLength) { isValid = value.length <= rules.maxLength && isValid; } return isValid; } render() { const formElementsArray = []; for (let key in this.state.orderForm) { formElementsArray.push({ id: key, config: this.state.orderForm[key] }) } let form = ( <form id="contact-form"> {formElementsArray.map(el => { return <Input key={el.id} elementtype={el.config.elementType} elementconfig={el.config.elementConfig} value={el.config.value} changed={(e) => this.inputChangedHandler(e, el.id)} invalid={!el.config.valid} shouldValidate={el.config.validation} touched={el.config.touched} /> })} <Button btnType="Success" clicked={this.orderHandler} disabled={!this.state.formIsValid} > MAKE ORDER </Button> </form> ); if (this.props.loading) { form = <Spinner />; } return ( <div className={ContactDataCss.ContactData}> <h4> Enter your contact data...</h4> {form} </div> ); } }; const mapStateToProps = state => ({ price: state.burger.totalPrice, ingredients: state.burger.ingredients, loading: state.order.loading, }); const mapDispatchToProps = dispatch => ({ onBurgerOrder: orderData => dispatch(purchaseBurger(orderData)), }); export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(ContactData, axios));
25.858586
119
0.559375
360eddecc7a3b07201c08e9b2db8e76e2011b4ec
374
js
JavaScript
docs/doxygen/html/legendre__p_8hpp.js
CiaranWelsh/NumCpp
7bc37f2ea197624bf568446f991f4fd96de66864
[ "MIT" ]
2
2020-12-16T03:18:43.000Z
2020-12-16T03:18:46.000Z
docs/doxygen/html/legendre__p_8hpp.js
inteliter/NumCpp
370b6ea8852824c9dc270f86ae67e00d068bb7c6
[ "MIT" ]
null
null
null
docs/doxygen/html/legendre__p_8hpp.js
inteliter/NumCpp
370b6ea8852824c9dc270f86ae67e00d068bb7c6
[ "MIT" ]
1
2020-08-29T14:56:50.000Z
2020-08-29T14:56:50.000Z
var legendre__p_8hpp = [ [ "legendre_p", "legendre__p_8hpp.html#a4e15f397e7c9dc338e990eaf2c2f55f0", null ], [ "legendre_p", "legendre__p_8hpp.html#a0f49fd4ed2ad26ed5176ca69ee62013f", null ], [ "legendre_p", "legendre__p_8hpp.html#aa17c1920f8efa35e91af667b2eaf32cf", null ], [ "legendre_p", "legendre__p_8hpp.html#a7c8f219798eea097e85877892323ca8a", null ] ];
53.428571
86
0.76738
360eeb84fb4c3fb33783e0bc929d1efe4cde1abe
435
js
JavaScript
app/utils/File.js
jcbel/jcbel-weixin
ba0114260fbb2a18b520ee6a7f92ae8631a3631e
[ "MIT" ]
null
null
null
app/utils/File.js
jcbel/jcbel-weixin
ba0114260fbb2a18b520ee6a7f92ae8631a3631e
[ "MIT" ]
null
null
null
app/utils/File.js
jcbel/jcbel-weixin
ba0114260fbb2a18b520ee6a7f92ae8631a3631e
[ "MIT" ]
null
null
null
const fileOperate = { formatSize(size) { const units = ['Bytes', 'KB', 'MB', 'GB', 'TB']; let times = 0; let shrinkedSize = size; while (shrinkedSize >= 1000 && times < units.length - 1) { shrinkedSize /= 1024; times += 1; } shrinkedSize = shrinkedSize.toFixed(2); return `${shrinkedSize} ${units[times]}`; }, }; export default fileOperate;
21.75
66
0.517241
360f1607cf0cb2f7c2bef7461e2fe09a71271b48
1,598
js
JavaScript
events/welcome.js
Akuver/Akuver_bot
437dabb5e2b943943bbfde2b61a28ea0bca9a03f
[ "MIT" ]
null
null
null
events/welcome.js
Akuver/Akuver_bot
437dabb5e2b943943bbfde2b61a28ea0bca9a03f
[ "MIT" ]
null
null
null
events/welcome.js
Akuver/Akuver_bot
437dabb5e2b943943bbfde2b61a28ea0bca9a03f
[ "MIT" ]
1
2021-12-17T07:54:06.000Z
2021-12-17T07:54:06.000Z
const Canvas = require('canvas'); const { MessageAttachment } = require('discord.js'); const path = require('path'); const { welcome, rules } = require('../util/update'); module.exports = { name: 'guildMemberAdd', async execute(member, client) { const guildId = member.guild.id; if (typeof welcome[guildId.toString()] === 'undefined') return; const channelId = welcome[guildId.toString()]; const targetChannelId = rules[guildId.toString()]; const msg = `Welcome aboard <@${member.user.id}>! Please check out <#${targetChannelId}>`; const channel = member.guild.channels.cache.get(channelId); const canvas = Canvas.createCanvas(700, 250); const ctx = canvas.getContext('2d'); const background = await Canvas.loadImage( path.join(__dirname, '../util/background.png') ); let x = 0; let y = 0; ctx.drawImage(background, x, y); const pfp = await Canvas.loadImage( member.user.displayAvatarURL({ format: 'png', }) ); x = canvas.width / 2 - pfp.width / 2; y = 25; ctx.drawImage(pfp, x, y); ctx.fillStyle = '#ffffff'; ctx.font = '35px sans-serif'; let text = `Welcome ${member.user.tag}`; x = canvas.width / 2 - ctx.measureText(text).width / 2; ctx.fillText(text, x, 60 + pfp.height); ctx.font = '30px sans-serif'; text = `Member #${member.guild.memberCount}`; x = canvas.width / 2 - ctx.measureText(text).width / 2; ctx.fillText(text, x, 100 + pfp.height); const attachment = new MessageAttachment(canvas.toBuffer()); channel.send(msg, attachment); }, };
35.511111
94
0.635169
36105566e7b1ea90f1130c13f5d1d6f3f208a64a
108
js
JavaScript
src/container/Financial/Payments/components/index.js
erickrocha/freeman-web
05ee7218bb3fd0b625aafd0e6231f16045e06fe9
[ "MIT" ]
null
null
null
src/container/Financial/Payments/components/index.js
erickrocha/freeman-web
05ee7218bb3fd0b625aafd0e6231f16045e06fe9
[ "MIT" ]
null
null
null
src/container/Financial/Payments/components/index.js
erickrocha/freeman-web
05ee7218bb3fd0b625aafd0e6231f16045e06fe9
[ "MIT" ]
null
null
null
export { default as Payment } from './Payment'; export { default as PaymentSearch } from './PaymentSearch';
36
59
0.722222
3610f43ff46281a554c2ce3c8217c9a9ccbba131
12,021
js
JavaScript
src/index.js
javidhsueh/react-gradient-color-picker
2fc8c695b8e74dbbc1328f0729963572df875887
[ "MIT" ]
15
2016-01-07T03:21:33.000Z
2022-02-24T19:07:19.000Z
src/index.js
javidhsueh/react-gradient-color-picker
2fc8c695b8e74dbbc1328f0729963572df875887
[ "MIT" ]
2
2016-02-09T10:04:02.000Z
2016-10-04T11:02:59.000Z
src/index.js
javidhsueh/react-gradient-color-picker
2fc8c695b8e74dbbc1328f0729963572df875887
[ "MIT" ]
11
2016-01-03T15:26:48.000Z
2019-12-02T20:11:26.000Z
'use strict'; import _ from 'lodash'; import ColorPicker from 'react-colors-picker'; import d3 from 'd3'; import React from 'react'; const HandlerWidth = 4; const ColorPickerWidth = 16; const Width = 300; const Height = 15; const DefaultColorSpace = 'HSL'; const ColorSpaces = { 'HSL': d3.interpolateHsl, 'HCL': d3.interpolateHcl, 'Lab': d3.interpolateLab, 'RGB': d3.interpolateRgb }; const DefaultStops = [ { offset: 0.0, color: '#00f', opacity: 1.0 }, { offset: 0.5, color: '#0f0', opacity: 0.5 }, { offset: 1.0, color: '#f00', opacity: 1.0 } ]; const CompareOffset = function CompareOffset(a, b) { return a.offset - b.offset; }; const ColorPickerID = function ColorPickerID(containerID, idx) { return containerID + '_gc-cp_' + idx; } class ReactGradientColorPicker extends React.Component { constructor(props) { super(props); // TODO: how to get auto-expanded width var rootHeight = Height; var rootWidth = Width; if (this.props.width) { rootWidth = this.props.width; } this.containerID = _.uniqueId('gc-canvas_'); this.svg = null; var defaultStops = this.props.stops || DefaultStops; var stops = defaultStops.map((stop, idx) => { return { idx: idx, x: rootWidth * stop.offset, offset: stop.offset, color: stop.color, opacity: stop.opacity } }); var initColorSpace = DefaultColorSpace; if (this.props.colorSpace) { if (ColorSpaces.hasOwnProperty(this.props.colorSpace)) { initColorSpace = this.props.colorSpace } else { /* eslint-disable no-console */ console.error('Incorrect props: colorSpace should be one of [HSL,HCL,Lab,RGB]'); /* eslint-enable no-console */ } } // init state this.state = { rootWidth: rootWidth, rootHeight: rootHeight, colorSpace: initColorSpace, stops: stops }; } _addHandler(mouseX) { var offset = 1.0 * mouseX / this.state.rootWidth; var midColor = this.colorScale(offset); var newStop = { idx: this.state.stops.length, x: mouseX, offset: offset, color: midColor, opacity: 1.0 }; var newStops = this.state.stops.concat([newStop]); newStops.sort(CompareOffset); this.setState({ stops: newStops }); this._notifyChange(); } _removeHandler(idx) { const {stops: oldStops} = this.state; const stopIdx = _.findIndex(this.state.stops, {idx}); if (stopIdx !== -1) { this.setState({ stops: [ ...oldStops.slice(0, stopIdx), ...oldStops.slice(stopIdx + 1) ] }); } } _dragHandler(d, mouseX, colorPickerID) { // only update handler position but not state d.x = mouseX; d3.select(this).attr('x', mouseX); d3.select('#' + colorPickerID) .style('left', (d.x - ColorPickerWidth / 2) + 'px') .style('top', Height + 'px'); } _dragHandlerEnd(d) { // when the end of drag, update the state once. var newStops = _.cloneDeep(this.state.stops); var currentHandler = _.find(newStops, { 'idx': d.idx }); currentHandler.offset = 1.0 * d.x / this.state.rootWidth; currentHandler.x = d.x; this.setState({ stops: newStops }); this._notifyChange(); } _notifyChange() { if (this.props.onChange) { this.props.onChange(this.state.stops, this.colorScale); } } componentDidMount() { // TODO: get the auto-expanded comonent width var rootWidth = this.refs.root.offsetWidth; var rootHeight = this.state.rootHeight; if (this.props.width) { rootWidth = this.props.width; } var newStops = this.state.stops.map((stop) => { stop.x = stop.offset * rootWidth; return stop; }); // TODO: this is anti-pattern. should fix it soon. /* eslint-disable react/no-did-mount-set-state */ this.setState({ rootWidth: rootWidth, stops: newStops }); /* eslint-enable react/no-did-mount-set-state */ var self = this; // init canvas this.canvas = d3.select('#' + this.containerID) .append('canvas') .attr('width', rootWidth) .attr('height', 1) .style('width', rootWidth + 'px') .style('height', rootHeight + 'px'); this.svg = d3.select('#' + this.containerID) .append('svg') .attr('width', rootWidth) .attr('height', rootHeight); this.colorMap = this.svg.append('rect') .attr('id', 'gc-color-map') .attr('x', 0) .attr('y', 0) .attr('width', rootWidth) .attr('height', rootHeight) .attr('fill', 'rgba(0,0,0,0)') .on('click', function clickColorMap() { var mouseX = d3.mouse(this)[0]; self._addHandler(mouseX); }); } _refreshCanvas() { if (this.svg === null) { return; } var rootWidth = this.state.rootWidth; var rootHeight = this.state.rootHeight; // refresh canvas size this.canvas .attr('width', this.state.rootWidth) .attr('height', 1) .style('width', this.state.rootWidth + 'px') .style('height', this.state.rootHeight + 'px'); this.svg.attr('width', rootWidth) .attr('height', rootHeight); // refresh color scale var stops = this.state.stops.map(function iterator(s) { return { offset: s.offset, color: s.color, opacity: s.opacity }; }).sort(CompareOffset); var offsets = _.map(stops, 'offset'); var colors = _.map(stops, 'color'); var opacity = _.map(stops, 'opacity'); this.colorScale = d3.scale.linear() .domain(offsets) .range(colors) .interpolate(ColorSpaces[this.state.colorSpace]); this.opacityScale = d3.scale.linear() .domain(offsets) .range(opacity); var _localColorScale = this.colorScale; var _localOpacityScale = this.opacityScale; this.colorMap .attr('width', rootWidth) .attr('height', rootHeight); this.canvas.each(function renderCanvas() { var context = this.getContext('2d'), image = context.createImageData(rootWidth, 1); for (var i = 0, j = -1, c, a; i < rootWidth; ++i) { c = d3.rgb(_localColorScale(i * 1.0 / rootWidth)); a = _localOpacityScale(i * 1.0 / rootWidth); image.data[++j] = c.r; image.data[++j] = c.g; image.data[++j] = c.b; image.data[++j] = a*255; } context.putImageData(image, 0, 0); }) // refresh gradient var gradientID = this.containerID + '_gc-gradient'; this.gradient = this.svg.select('#' + gradientID) .attr('x2', rootWidth) .selectAll('stop') .data(this.state.stops); // enter stops this.gradient.enter() .append('stop') .attr('offset', function offsetAccessor(d) { return (d.offset * 100) + '%'; }) .attr('stop-color', function colorAccessor(d) { return d.color; }); // update existing stops this.gradient .attr('offset', (d) => (d.offset * 100).toString() + '%') .attr('stop-color', (d) => d.color); // remove non-exist stops this.gradient.exit().remove(); // refresh handlers this.handlers = this.svg.selectAll('.gc-handler') .data(this.state.stops); // enter new handlers var self = this; var dragCallback = function dragCallback(d) { var newX = d3.event.x; if (newX >= 0 && newX <= self.state.rootWidth) { self._dragHandler.call(this, d, newX, ColorPickerID(self.containerID, d.idx)); } } var drag = d3.behavior.drag() .origin(Object) .on('drag', dragCallback) .on('dragend', this._dragHandlerEnd.bind(this)); this.handlers.enter() .append('rect') .attr('class', 'gc-handler') .attr('x', function xPos(d) { return d.x - HandlerWidth / 2; }.bind(this)) .attr('y', '0') .attr('width', HandlerWidth) .attr('height', rootHeight) .call(drag); // update existing handlers this.handlers .attr('x', function xPos(d) { return d.x - HandlerWidth / 2; }.bind(this)); // remove non-exist handlers this.handlers.exit().remove(); // refresh the color pickers this.state.stops.forEach(function iterator(s) { d3.select('#' + ColorPickerID(this.containerID, s.idx)) .style('left', (s.x - ColorPickerWidth / 2) + 'px') .style('top', Height + 'px'); }.bind(this)); } render() { this._refreshCanvas(); var colorChangeCallback = function colorChangeCallback(color, opacity, idx) { var newStops = _.cloneDeep(this.state.stops); var currentHandler = _.find(newStops, { 'idx': idx }); currentHandler.color = color; currentHandler.opacity = 1.0 * opacity / 100; this.setState({ stops: newStops }); // notify change if (this.props.onChange) { this.props.onChange(this.state.stops, this.colorScale); } }.bind(this); var colorpickers = this.state.stops.map(function iterator(s) { let pickerId = ColorPickerID(this.containerID, s.idx); let removeCallback = () => this._removeHandler(s.idx); let callback = (c) => colorChangeCallback(c.color, c.alpha, s.idx); var style = { left: (s.x - ColorPickerWidth / 2) + 'px', top: Height + 'px' } return ( <div key={ pickerId } className = "gc-colorpicker" style = { style }> < div id = { pickerId } key = { pickerId } > < ColorPicker animation = "slide-up" color = { s.color } alpha = {s.opacity * 100} onChange = { callback } placement = "bottomLeft" / > < /div> <div className = "remove-btn" onClick = {removeCallback}> x </div> </div> ); }.bind(this)); return ( < div className = "gc-container" ref = "root" > { colorpickers } < div className = "gc-canvas" id = { this.containerID } > < /div> < /div> ); } // Publid API: getColorMap() { return this.colorScale; } getColorStops() { return this.state.stops; } } ReactGradientColorPicker.propTypes = { stops: React.PropTypes.arrayOf(React.PropTypes.object), colorSpace: React.PropTypes.string, onChange: React.PropTypes.func, width: React.PropTypes.number }; module.exports = ReactGradientColorPicker;
32.401617
96
0.510274
361148081afefa54a0a87ea8098fe3caa159d053
308
js
JavaScript
projects/projects/curso1/aulas/12-abas/abas.js
GlauberC/projetos-react-native
ce434d884053e20e89e91593ba9e58fd8796e7ed
[ "MIT" ]
null
null
null
projects/projects/curso1/aulas/12-abas/abas.js
GlauberC/projetos-react-native
ce434d884053e20e89e91593ba9e58fd8796e7ed
[ "MIT" ]
4
2021-05-10T04:48:57.000Z
2022-02-26T15:59:52.000Z
projects/projects/curso1/aulas/12-abas/abas.js
GlauberC/projetos-react-native
ce434d884053e20e89e91593ba9e58fd8796e7ed
[ "MIT" ]
null
null
null
import React, { Component } from 'react' import { Text, View, } from 'react-native' // npm install --save react-native-vector-icons import TabNabigator from './services/routes' export default class Abas extends Component{ render(){ return( <TabNabigator/> ) } }
18.117647
47
0.623377
3612962f90fd796e1da76c787d0294593a521ca7
4,349
js
JavaScript
verification_app/src/components/VerifyCertificate/index.js
varadeth/DIVOC
25c284c378ae797ba7c77a419969687619d02e22
[ "MIT" ]
null
null
null
verification_app/src/components/VerifyCertificate/index.js
varadeth/DIVOC
25c284c378ae797ba7c77a419969687619d02e22
[ "MIT" ]
null
null
null
verification_app/src/components/VerifyCertificate/index.js
varadeth/DIVOC
25c284c378ae797ba7c77a419969687619d02e22
[ "MIT" ]
1
2021-12-30T07:00:30.000Z
2021-12-30T07:00:30.000Z
import React, {useState, useEffect} from "react"; import "./index.css"; import VerifyCertificateImg from "../../assets/img/verify-certificate.png" import LoadingImg from "../../assets/img/loading-buffering.gif" import QRCodeImg from "../../assets/img/qr-code.svg" import {CertificateStatus} from "../CertificateStatus"; import {CustomButton} from "../CustomButton"; import QRScanner from "../QRScanner"; import JSZip from "jszip"; import {CERTIFICATE_FILE} from "../../constants"; import {useTranslation} from "react-i18next"; import config from "../../config" export const VerifyCertificate = () => { const [result, setResult] = useState(""); const [showScanner, setShowScanner] = useState(false); const [showTimeout, setShowTimeout] = useState(false); const [timerClocked, setTimerClocked] = useState(false); const {t} = useTranslation(); const handleScan = data => { if (data) { const zip = new JSZip(); zip.loadAsync(data).then((contents) => { return contents.files[CERTIFICATE_FILE].async('text') }).then(function (contents) { setResult(contents); }).catch(err => { setResult(data) } ); } }; const handleError = err => { console.error(err) }; useEffect(() => { if(timerClocked && result === '') { setShowTimeout(true); } }); const onScanWithQR = () => { setShowScanner(true); setTimerClocked(false); setTimeout(() => { setTimerClocked(true); }, config.CERTIFICATE_SCAN_TIMEOUT); }; const onTryAgain = () => { setShowTimeout(false); setShowScanner(false); setTimerClocked(false); }; return ( <div className="container-fluid verify-certificate-wrapper"> { (!result && !showTimeout) && <> {!showScanner && <> <img src={VerifyCertificateImg} className="banner-img" alt="banner-img"/> <h3 className="text-center">{t('verifyCertificate.title')}</h3> <CustomButton className="green-btn" onClick={() => onScanWithQR()}> <span>{t('verifyCertificate.scanWithQR')}</span> <img className="ml-3" src={QRCodeImg} alt={""}/> </CustomButton> </>} {showScanner && <> <QRScanner onError={handleError} onScan={handleScan}/> <span className="mt-2"><img style={{height: "20px"}} className="mr-1" src={LoadingImg} />Detecting QR code</span> <CustomButton className="green-btn text-uppercase" onClick={() => setShowScanner(false)}>{t('button.back')}</CustomButton> </> } </> } { result && <CertificateStatus certificateData={result} goBack={() => { setShowScanner(false); setShowTimeout(false); setTimerClocked(false); setResult(""); } }/> } { showTimeout && <> <h4 className="mt-5 text-center">{t('verifyCertificate.timeoutTitle')}</h4> <p className="font-weight-bold mt-5">{t('verifyCertificate.timeoutInfo')}</p> <ul className="mr-4"> <li className="pb-2">{t('verifyCertificate.timeoutInfoList.0')}</li> <li className="pb-2">{t('verifyCertificate.timeoutInfoList.1')}</li> <li className="pb-2">{t('verifyCertificate.timeoutInfoList.2')}</li> <li className="pb-2">{t('verifyCertificate.timeoutInfoList.3')}</li> </ul> <CustomButton className="green-btn" onClick={() => onTryAgain()}> <span>{t('verifyCertificate.tryAgain')}</span> </CustomButton> </> } </div> ) };
39.18018
146
0.493677
3612fed330f5861d052cd591ad0eb4eaf22b7936
2,193
js
JavaScript
src/extension/ecosystem/ExEntry/UI.js
silentbalanceyh/vertx-ui
e8024525a8cbd1df0640e52f4ffdaa15e5c3e35b
[ "Apache-2.0" ]
31
2017-12-12T08:11:07.000Z
2022-03-30T07:55:22.000Z
src/extension/ecosystem/ExEntry/UI.js
silentbalanceyh/vertx-ui
e8024525a8cbd1df0640e52f4ffdaa15e5c3e35b
[ "Apache-2.0" ]
8
2020-04-08T10:09:36.000Z
2020-08-01T06:21:50.000Z
src/extension/ecosystem/ExEntry/UI.js
silentbalanceyh/vertx-ui
e8024525a8cbd1df0640e52f4ffdaa15e5c3e35b
[ "Apache-2.0" ]
18
2017-12-18T05:07:05.000Z
2020-06-11T01:06:27.000Z
import React from 'react'; import Ux from "ux"; import Ex from 'ex'; /** * ## 「组件」`ExEntry` * * ```js * import { ExEntry } from 'ei'; * ``` * * ### 1. 生命周期 * * |Hoc高阶周期|Mount初始化|Update更新| * |---|---|---| * |Ok|x|x| * * ### 2. 运行时 * * > componentDidMount执行完成后。 * * #### 2.1. 容器属性 * * |属性名|类型|含义| * |:---|---|:---| * |$app|DataObject|应用程序基本数据。| * |$router|DataRouter|路由基本信息。| * |$collapsed|Boolean|是否展开左侧的主菜单。| * |fnApp|Function|关联`Ex.epicApp`函数,读取应用程序配置数据专用函数。| * |fnOut|Function|Redux专用函数,写状态树。| * |react|ReactComponent|顶层组件引用。| * |reference|ReactComponent|父类组件引用。| * * #### 2.1. 属性props * * |属性名|类型|含义| * |:---|---|:---| * |$options|Object|基础选项配置数据。| * |form|Object|Ant Form构造的专用表单变量。| * |rxLogin|Function|登录专用回调函数。| * * #### 2.2. 状态state * * |状态名|类型|含义| * |:---|---|:---| * |$op|Object|登录专用操作,主要会触发`$opLogin`函数。| * |$hoc|HocI18n|绑定好的资源文件,对应`cab/<LANG>/extension/ecosystem/ExEntry.json`资源文件。| * |$ready|Boolean|是否加载完成,此时已为`true`。| * |raft|Object|构造完成的表单配置数据`raftForm`结果。| * * * ### 3.核心点 * * #### 3.1.关于rxLogin回调 * * 标准的`$opLogin`方法执行流程如下: * * 1. `POST /oauth/login`登录系统拿到`clientSecret`密钥。 * 2. `POST /oauth/authorize`请求申请临时授权码。 * 3. `POST /oauth/token`使用临时授权码交换令牌`token`。 * 4. `GET /api/user`执行用户信息读取,不同用户读取到的信息结构会有所区别。 * 5. 将所有信息合并,然后调用`rxLogin`回调函数,该函数必须返回`Promise`,异步调用。 * 6. 执行最终三步。 * * #### 3.2.关于密码 * * 在调用`/oauth/login`方法时,密码会执行`MD5`加密,发送密文到后端。 * * #### 3.3.最终三步执行流程 * * 1. `Ux.storeUser`将数据存储到SessionStorage中。 * 2. `Ux.writeSubmit`方法将Redux树中的重复提交修正到false位置(提交完成)。 * 3. `Ux.toOriginal`方法执行原始路径重定向。 * 1. 如果有`target=xxx`则重定向到`target`中。 * 2. 如果没有`target`参数,则直接重定向到管理主界面`Z_ENTRY_ADMIN`页中。 * * > `Ux.storeUser`在整个流程中调用了两次,第一次是直接提取用户信息,第二次会将`rxLogin`以及用户数据合并到一起重写SessionStorage中存储的数据。 * * @memberOf module:web-component * @method ExEntry **/ @Ux.zero(Ux.rxEtat(require('./Cab.json')) .cab("ExEntry") .form().raft(1).raft(Ex.Jsx.Login) .bind(Ex.Op) .to() ) class Component extends React.PureComponent { render() { return Ex.yoRender(this, () => Ux.aiForm(this), Ex.parserOfColor("ExEntry").form({monitor: false})) } } export default Component;
22.84375
92
0.610123
36153a8d2acf7205570225b52614d6afa4f33439
4,715
js
JavaScript
ui/mm-react/src/containers/DecodeEditor.js
bvelt/mastermind
8f04f5d5bbe58a2e9c7c9363904f80017858f754
[ "MIT" ]
2
2019-05-10T10:46:32.000Z
2019-05-18T15:39:45.000Z
ui/mm-react/src/containers/DecodeEditor.js
bvelt/mastermind
8f04f5d5bbe58a2e9c7c9363904f80017858f754
[ "MIT" ]
null
null
null
ui/mm-react/src/containers/DecodeEditor.js
bvelt/mastermind
8f04f5d5bbe58a2e9c7c9363904f80017858f754
[ "MIT" ]
1
2019-07-08T20:47:14.000Z
2019-07-08T20:47:14.000Z
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import CodePegList from '../components/CodePegList'; import CodePeg from '../components/CodePeg'; import DecodeGrid from '../components/DecodeGrid'; import Button from '../components/Button'; import Assist from '../components/Assist'; import * as actions from '../actions/ActionCreators'; import './DecodeEditor.css'; class DecodeEditor extends React.Component { static propTypes = { code: PropTypes.array, possibleCodes: PropTypes.array, nextGuess: PropTypes.array, maximumGuessCount: PropTypes.number, length: PropTypes.number, prevGuesses: PropTypes.array, prevAnswers: PropTypes.array, onDecodeDone: PropTypes.func }; constructor(props) { super(props); this.handleSelect = this.handleSelect.bind(this); this.handleReset = this.handleReset.bind(this); this.handleRandom = this.handleRandom.bind(this); this.handleDelete = this.handleDelete.bind(this); this.handleCheck = this.handleCheck.bind(this); this.handleNewGame = this.handleNewGame.bind(this); } handleSelect(value) { const { nextGuess, length, dispatch } = this.props; if (nextGuess.length < length) { dispatch(actions.appendGuessToken(value)); } } handleDelete() { const { nextGuess, dispatch } = this.props; if (nextGuess.length > 0) { dispatch(actions.removeGuessToken()); } } handleReset() { const { nextGuess, dispatch } = this.props; if (nextGuess.length > 0) { dispatch(actions.resetGuess()); } } handleRandom() { const { dispatch } = this.props; dispatch(actions.randomGuess()); } handleCheck() { const { maximumGuessCount, prevGuesses, nextGuess, length, dispatch } = this.props; if (nextGuess.length === length && prevGuesses.length < maximumGuessCount) { dispatch(actions.checkGuess()); } } handleNewGame() { const { dispatch } = this.props; dispatch(actions.newGame()); } padRight(items, length, value) { const padded = Array.from(items); while (padded.length < length) { padded.push(value); } return padded; } render() { const { code, possibleCodes, maximumGuessCount, length, nextGuess, prevGuesses, prevAnswers, broken } = this.props; let guesses = Array.from(prevGuesses); let answers = Array.from(prevAnswers); const active = !broken && prevGuesses.length < maximumGuessCount; let message = "You broke the code!"; if (!active && !broken) { guesses.push(code); answers.push([4, 0]); message = "Bummer. You failed."; } else if (active) { guesses.push(this.padRight(nextGuess, length, CodePeg.defaultValue())); answers.push([0, 0]); } while (guesses.length < maximumGuessCount) { guesses.push(Array(length).fill(CodePeg.defaultValue())); answers.push([0, 0]); } let newGameButton = ''; if (!active) { newGameButton = ( <div className="gameover"> <div className="message"> <span className="emoji" role="img" aria-label="Face">{broken === true ? '😃' : '🙁'}</span> <span className="text">{message}</span> </div> <Button key={7} label="TRY AGAIN" onClick={this.handleNewGame}></Button> </div> ); } return ( <div className="decodeEditor"> <div className="c1"> <CodePegList key={1} values={[...CodePeg.colors().keys()]} isSelectable={active && nextGuess.length < length} onSelect={this.handleSelect} onCheck={this.handleCheck} onDelete={this.handleDelete} onRandom={this.handleRandom} onReset={this.handleReset}></CodePegList> <DecodeGrid key={6} remainingGuessCount={maximumGuessCount - prevGuesses.length} guesses={guesses} answers={answers}></DecodeGrid> {newGameButton} </div> <div className="c2"> <Assist possibleCodes={possibleCodes}></Assist> </div> </div> ); } } const mapStateToProps = state => { return { code: state.code, possibleCodes: state.possibleCodes, nextGuess: state.nextGuess, maximumGuessCount: state.settings.maximumGuessCount, length: state.settings.codeLength, prevGuesses: state.prevGuesses, prevAnswers: state.prevAnswers, broken: state.broken }; } export default connect(mapStateToProps)(DecodeEditor);
25.765027
82
0.614846
3615560f7da559b6178471d042abc12e38fd3199
370
js
JavaScript
src/containers/Preview.js
Akitsuyoshi/solo-mvp-desktop
87f3a4f4ad49b36cd0415eff252baf7e746f2f33
[ "MIT" ]
null
null
null
src/containers/Preview.js
Akitsuyoshi/solo-mvp-desktop
87f3a4f4ad49b36cd0415eff252baf7e746f2f33
[ "MIT" ]
10
2021-03-02T00:18:12.000Z
2022-03-25T18:48:35.000Z
src/containers/Preview.js
Akitsuyoshi/solo-mvp-desktop
87f3a4f4ad49b36cd0415eff252baf7e746f2f33
[ "MIT" ]
null
null
null
import { connect } from 'react-redux' import Preview from '../components/Preview' import { changeClick, } from '../actions' const mapStateToProps = state => ({ code: state.contents.code, }) const mapDispatchToProps = dispatch => ({ onClick: () => { dispatch(changeClick()) }, }) export default connect( mapStateToProps, mapDispatchToProps, )(Preview)
17.619048
43
0.681081
3616968cb633c5a9ce03764aef59b58566df2293
264
js
JavaScript
src/routes/pages/StyleGuide.js
nhunglele2492/lele-grapqhl
5fc7af127a69dd1cb38f4d313628a3fbfab11bca
[ "MIT" ]
null
null
null
src/routes/pages/StyleGuide.js
nhunglele2492/lele-grapqhl
5fc7af127a69dd1cb38f4d313628a3fbfab11bca
[ "MIT" ]
null
null
null
src/routes/pages/StyleGuide.js
nhunglele2492/lele-grapqhl
5fc7af127a69dd1cb38f4d313628a3fbfab11bca
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import DefaultLayout from '../layout/DefaultLayout'; class StyleGuide extends Component { render() { return ( <DefaultLayout> StyleGuide </DefaultLayout> ); } } export default StyleGuide;
17.6
52
0.655303
3616d99d479cf3fab3c070665b9cabbafa478310
4,106
js
JavaScript
artifact_evaluation/data/codeCoverage/fuzzilli_generate/148.js
weucode/COMFORT
0cfce5d70a58503f8ba3c3ff825abc24b79a1d2b
[ "Apache-2.0" ]
55
2021-03-05T06:42:22.000Z
2022-02-22T05:33:47.000Z
artifact_evaluation/data/codeCoverage/fuzzilli_generate/148.js
Delepha/COMFORT
a76ab2cc0069542b2bd75e4952c4709eef936124
[ "Apache-2.0" ]
null
null
null
artifact_evaluation/data/codeCoverage/fuzzilli_generate/148.js
Delepha/COMFORT
a76ab2cc0069542b2bd75e4952c4709eef936124
[ "Apache-2.0" ]
20
2021-04-14T15:17:05.000Z
2022-02-15T10:48:00.000Z
function main() { const v0 = "2"; // v0 = .string + .object(ofGroup: String, withProperties: ["constructor", "__proto__", "length"], withMethods: ["padEnd", "split", "charAt", "match", "lastIndexOf", "charCodeAt", "trim", "startsWith", "includes", "repeat", "search", "slice", "endsWith", "matchAll", "indexOf", "concat", "replace", "padStart", "substring", "codePointAt"]) function v1(v2,v3) { const v6 = [13.37,13.37,3697200800,13.37]; // v6 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"]) const v8 = [v6,1337,1337,1337]; // v8 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"]) const v10 = [v8,1337,1337,1337]; // v10 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"]) for (const v11 in v10) { const v14 = [13.37,13.37]; // v14 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"]) const v16 = [1337,1337,1337,1337]; // v16 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"]) const v17 = {__proto__:13.37,a:v16,b:1337,constructor:"6S7QrUljSC",d:1337,e:1337,length:v14}; // v17 = .object(ofGroup: Object, withProperties: ["d", "e", "length", "b", "a", "__proto__", "constructor"]) const v24 = Object(); // v24 = .object() const v26 = {__proto__:Object,constructor:v24,d:createGlobalObject,e:1,length:1337}; // v26 = .object(ofGroup: Object, withProperties: ["constructor", "__proto__", "length", "e"], withMethods: ["__proto__", "d"]) Object[1] = v17; const v30 = {get:Object,set:Object}; // v30 = .object(ofGroup: Object, withProperties: ["__proto__"], withMethods: ["get", "set"]) const v32 = Object.defineProperty(Object,3,v30); // v32 = .undefined } const v34 = [13.37,13.37]; // v34 = .object(ofGroup: Array, withProperties: ["length", "__proto__", "constructor"], withMethods: ["concat", "fill", "indexOf", "entries", "forEach", "find", "reverse", "slice", "flat", "reduce", "join", "findIndex", "reduceRight", "some", "copyWithin", "toString", "pop", "filter", "map", "splice", "keys", "unshift", "sort", "includes", "flatMap", "shift", "values", "every", "toLocaleString", "push", "lastIndexOf"]) } for (let v38 = 0; v38 < 100; v38 = v38 + 1) { const v39 = v1(v1,v1); // v39 = .unknown } } main();
108.052632
431
0.613249
3617b1d2789104077c0aec9b9e391cf68bc7a8e7
396
js
JavaScript
src/models/group.js
CS275-Icebreaker/Icebreaker
4d2efc1d5c1500e0d92f8604f0824d8dcee2e906
[ "MIT" ]
null
null
null
src/models/group.js
CS275-Icebreaker/Icebreaker
4d2efc1d5c1500e0d92f8604f0824d8dcee2e906
[ "MIT" ]
35
2018-03-02T23:02:05.000Z
2018-03-22T17:08:57.000Z
src/models/group.js
CS275-Icebreaker/Icebreaker
4d2efc1d5c1500e0d92f8604f0824d8dcee2e906
[ "MIT" ]
null
null
null
"use strict"; var mongoose = require("mongoose"); var GroupSchema = mongoose.Schema({ room_id: mongoose.Schema.Types.ObjectId, topic_id: mongoose.Schema.Types.ObjectId, stage: Number, action: String, timeline: [{ start: { type: Date }, end: { type: Date } }], members: [mongoose.Schema.Types.ObjectId] }); var Group = mongoose.model('Group', GroupSchema); module.exports = Group;
20.842105
49
0.69697
3617e0f7ad3b4fb072b36f2501fce1e9f63fc0a0
756
js
JavaScript
dialogs/welcome.js
cedextech/event-chatbot
50be6798346ee5db9bcc8ccc8255f5b3735dc665
[ "MIT" ]
null
null
null
dialogs/welcome.js
cedextech/event-chatbot
50be6798346ee5db9bcc8ccc8255f5b3735dc665
[ "MIT" ]
null
null
null
dialogs/welcome.js
cedextech/event-chatbot
50be6798346ee5db9bcc8ccc8255f5b3735dc665
[ "MIT" ]
null
null
null
var quickReplies = require('botbuilder-quickreplies'); var builder = require('botbuilder'); module.exports = function(bot) { bot.dialog('/GetStarted', [ function(session, args, next) { var message = new builder.Message(session) .text('Hello ' + session.message.user.name + ', welcome to DCB Bank Innovation Carnival.'); session.sendTyping(); quickReplyMessage = quickReplies.AddQuickReplies(session, message, [ new quickReplies.QuickReplyText('About Us', 'Event.About'), new quickReplies.QuickReplyText('Why Participate', 'Event.Participate') ]); session.send(quickReplyMessage); session.endDialog(); } ]); }
36
107
0.608466
3618385b0e43c33341448e8d8b4063f97173b84e
411
js
JavaScript
src/scripts/header-hide.js
AaronRankin/ivs-prototype
357e4a6159acf849608ea70ba305a379cc5d102d
[ "MIT" ]
null
null
null
src/scripts/header-hide.js
AaronRankin/ivs-prototype
357e4a6159acf849608ea70ba305a379cc5d102d
[ "MIT" ]
null
null
null
src/scripts/header-hide.js
AaronRankin/ivs-prototype
357e4a6159acf849608ea70ba305a379cc5d102d
[ "MIT" ]
null
null
null
var prevScrollpos = window.pageYOffset; window.onscroll = function() { var currentScrollPos = window.pageYOffset; if (70 > currentScrollPos) { document.getElementsByClassName("example").style.top = "0"; } else { document.getElementsByClassName("example").style.transition = "all 300ms" document.getElementsByClassName("example").style.top = "-100px"; } prevScrollpos = currentScrollPos; };
37.363636
77
0.729927
361863b13abd7475453c821aa90c9b9c82950f21
6,250
js
JavaScript
src/js/editors/ImageEditor.js
benallfree/bootstrap-richarea
097497694c3c45cdef7736df690951f2ca53395e
[ "MIT" ]
1
2017-01-03T20:21:28.000Z
2017-01-03T20:21:28.000Z
src/js/editors/ImageEditor.js
benallfree/bootstrap-richarea
097497694c3c45cdef7736df690951f2ca53395e
[ "MIT" ]
1
2019-11-10T20:44:35.000Z
2019-11-10T20:44:35.000Z
src/js/editors/ImageEditor.js
benallfree/bootstrap-richarea
097497694c3c45cdef7736df690951f2ca53395e
[ "MIT" ]
1
2017-07-10T09:54:17.000Z
2017-07-10T09:54:17.000Z
let BaseEditor = require('./BaseEditor'); require('jquery.actual'); require('jquery-migrate'); require('cropit'); class ImageEditor extends BaseEditor { static initField(field, layout, options) { let assetRoot = options.editors[this.slug].assetRoot || layout.assetRoot field.defaultValue.originalImage = assetRoot + field.defaultValue.originalImage; field.defaultValue.croppedImage = assetRoot + field.defaultValue.croppedImage; } static getVueData() { return { props: ['item', 'fieldName', 'config', 'layout'], template: ` <div> <div :data-field="fieldName" class="image-editor"> <input accept="image/gif,image/png,image/jpeg" class="cropit-image-input" type="file"></input> <img :src="layout.fields[fieldName].defaultValue.croppedImage" class="reference" style="width:100%; display: none"/> <div class="cropit-preview"></div> <input class="cropit-image-zoom-input" type="range"></input> </div> </div> `, data() { return { isCropperInitialized: false, $modal: null, $editor: null, $root: null, $referenceImage: null, $fileInput: null, shouldSave: false, }; }, computed: { field: function() { return this.item.data[this.fieldName]; } }, methods: { showBsModal: function() { if(this.isCropperInitialized) return; this.$editor.invisible(); }, shownBsModal: function() { this.shouldSave = false; if(this.isCropperInitialized) return; if(this.$referenceImage.get(0).naturalWidth==0 || this.$referenceImage.get(0).naturalHeight==0) { throw new TypeError(`Reference/placeholder image was not found ${this.$referenceImage.attr('src')}`); } let w = Math.floor(this.$referenceImage.actual('width')); let h = Math.floor(this.$referenceImage.actual('height')); this.$editor.cropit({ exportZoom: (this.$referenceImage.get(0).naturalWidth / w) || 1, imageBackground: false, imageBackgroundBorderWidth: 0, initialZoom: 'image', width: w, height: h, maxZoom: 5, onFileReadError: function() { console.log('onFileReadError', arguments); }, onImageError: this.onImageError, smallImage: 'allow', // Allow images that must be zoomed to fit onImageLoaded: this.onImageLoaded, onZoomChange: this.onZoomChange, onOffsetChange: this.onOffsetChange, }); this.$editor.cropit('imageSrc', this.field.originalImage); }, hideBsModal: function() { if(!this.config.editors.ImageEditor.uploadUrl) return; if(!this.shouldSave) return; $.post(this.config.editors.ImageEditor.uploadUrl, { data: this.$editor.cropit('export'), }, (data,status)=>{ console.log([data, status]); if(status=='success' && data.status=='success') { this.field.croppedImage = data.url; } }); }, onImageError: function() { this.$editor.cropit('imageSrc', ''); this.isCropperInitialized = true; this.$editor.visible(); this.$editor.cropit('offset', {x: 0, y: 0}); }, onImageLoaded: function() { if(!this.isCropperInitialized) { let zoom = this.field.zoom == null ? this.$referenceImage.actual('width') / this.$referenceImage.get(0).naturalWidth : this.field.zoom; this.$editor.cropit('zoom', zoom); this.$editor.cropit('offset', this.field.offset); this.isCropperInitialized = true; this.$editor.visible(); } else { this.shouldSave = true; let file = this.$fileInput.get(0).files[0]; let fr = new FileReader(); fr.onload = ()=>{ if(!this.config.editors.ImageEditor.uploadUrl) return; $.post(this.config.editors.ImageEditor.uploadUrl, { data: fr.result, }, (data,status)=>{ console.log([data, status]); if(status=='success' && data.status=='success') { this.field.originalImage = data.url; this.field.croppedImage = data.url; } }); } fr.readAsDataURL(file); this.field.croppedImage = this.$editor.cropit('export'); } }, onZoomChange: function() { if(!this.isCropperInitialized) return; this.shouldSave = true; this.field.zoom = this.$editor.cropit('zoom'); this.field.croppedImage = this.$editor.cropit('export'); }, onOffsetChange: function() { if(!this.isCropperInitialized) return; this.shouldSave = true; let o = this.$editor.cropit('offset'); this.field.offset = {x: Math.floor(o.x), y: Math.floor(o.y)}; this.field.croppedImage = this.$editor.cropit('export'); }, }, mounted: function() { console.log(`mount ${this.item.layoutId}:${this.fieldName}`); this.$root = $(this.$el); this.$modal = this.$root.closest('.modal'); this.$editor = this.$root.find('.image-editor'); this.$referenceImage = this.$editor.find('.reference'); this.$fileInput = this.$editor.find('[type=file]'); this.$modal.on('show.bs.modal', this.showBsModal); this.$modal.on('shown.bs.modal', this.shownBsModal); this.$modal.on('hide.bs.modal', this.hideBsModal); }, beforeDestroy: function() { console.log(`unmount ${this.item.layoutId}:${this.fieldName}`); this.$modal.off('show.bs.modal', this.showBsModal); this.$modal.off('shown.bs.modal', this.shownBsModal); this.$modal.off('hide.bs.modal', this.hideBsModal); }, }; } } ImageEditor.slug = 'ImageEditor'; module.exports = ImageEditor;
38.109756
147
0.55744
36199db54d629376762d3ea7ec9d520efbae229d
103
js
JavaScript
dist/string/addZero.js
iyolee/fetools
bd9b437926de511768cf76a0f8270e67a97c214a
[ "MIT" ]
9
2019-10-20T15:14:43.000Z
2022-03-21T03:04:41.000Z
dist/string/addZero.js
iyolee/fetools
bd9b437926de511768cf76a0f8270e67a97c214a
[ "MIT" ]
null
null
null
dist/string/addZero.js
iyolee/fetools
bd9b437926de511768cf76a0f8270e67a97c214a
[ "MIT" ]
2
2019-10-25T08:20:49.000Z
2021-04-01T02:42:58.000Z
export function $addZero(num) { return ("0" + num).slice(-2); } //# sourceMappingURL=addZero.js.map
25.75
35
0.660194
361a935a149f8cd5898514ff7828fcf7042c3448
2,815
js
JavaScript
app.js
jsrath/number-generator
26dc886107a8a6d3e42399cc4a53e14ff8f9361c
[ "MIT" ]
null
null
null
app.js
jsrath/number-generator
26dc886107a8a6d3e42399cc4a53e14ff8f9361c
[ "MIT" ]
null
null
null
app.js
jsrath/number-generator
26dc886107a8a6d3e42399cc4a53e14ff8f9361c
[ "MIT" ]
null
null
null
const config = { initialFlipNumbers: 3, minimumFlipNumbers: 1, maximumFlipNumbers: 10, }; let run = false; const digitInput = document.querySelector('.digit-input'); function toggleRotation() { run = !run; const board = document.querySelectorAll('.board'); board.forEach(flipNumber => { const rotateNumbers = setInterval(() => { if (!run) { clearInterval(rotateNumbers); } return (flipNumber.innerHTML = Math.floor(Math.random() * 10)); }, 100); }); } function addOrRemoveNumbers(difference) { const sign = Math.sign(difference); switch (sign) { case 1: addFlipNumbersToBoard(difference); break; case -1: removeFlipNumbersFromBoard(difference); break; default: return; } } function setBoardSize(inputNumber) { const isInputValid = validateInput(inputNumber); if (!isInputValid) { return alert(`Please enter a number between ${config.minimumFlipNumbers} and ${config.maximumFlipNumbers}!`); } checkWrapper(); const wrapper = document.querySelector('.wrapper'); const difference = inputNumber - wrapper.querySelectorAll('.board').length; addOrRemoveNumbers(difference) } function validateInput(input) { if (input < config.minimumFlipNumbers || input > config.maximumFlipNumbers || isNaN(input)) { return false; } return true; } function checkWrapper() { const wrapper = document.querySelector('.wrapper'); if (!wrapper) { const newWrapper = document.createElement('div'); newWrapper.classList.add('wrapper'); document.querySelector('.container').appendChild(newWrapper); } } function generateOneFlipNumber() { return `<div class="digit">0</div>`; } function addFlipNumbersToBoard(digits) { const wrapper = document.querySelector('.wrapper'); [...Array(digits)].forEach(() => { const div = document.createElement('div'); div.classList.add('board'); div.innerHTML = generateOneFlipNumber(); wrapper.appendChild(div); }); } function removeFlipNumbersFromBoard(digits) { [...Array(-digits)].forEach(() => { const elementToRemove = document.querySelector('.board'); elementToRemove.parentNode.removeChild(elementToRemove); }); } function initalizeBoard() { digitInput.value = config.initialFlipNumbers; setBoardSize(config.initialFlipNumbers); } function copyNumber() { const textToCopy = [...document.querySelectorAll('.board')].map(digit => digit.innerText).join(''); navigator.clipboard.writeText(textToCopy); } digitInput.addEventListener('input', () => setBoardSize(Number(event.target.value))); document.addEventListener('DOMContentLoaded', initalizeBoard); document.querySelector('.toggle').addEventListener('change', toggleRotation); document.querySelector('.copy-button').addEventListener('click', copyNumber);
27.330097
113
0.705861
361b1c3b83fb9679b2b274df43f8b227a97c06c6
327
js
JavaScript
tests/toy-test.js
zhiyand/npm-package-template
317cf78c4b9af523d49564b055350623137be905
[ "MIT" ]
null
null
null
tests/toy-test.js
zhiyand/npm-package-template
317cf78c4b9af523d49564b055350623137be905
[ "MIT" ]
null
null
null
tests/toy-test.js
zhiyand/npm-package-template
317cf78c4b9af523d49564b055350623137be905
[ "MIT" ]
null
null
null
import Toy from '../src/toy' import chai from 'chai' let expect = chai.expect describe('Tick', function () { it('exists', function () { let toy = new Toy() expect(toy).to.be.a('object') }) it('can be nudged', function () { let toy = new Toy() expect(toy.nudge()).to.equal('Don\'t touch me!') }) })
17.210526
52
0.577982
361b295ab9bb69c2a9346205407caa9586d204c6
1,822
js
JavaScript
example/src/Home.js
HakunaKp/React-Market-Analysis
65bea03c135a2c0ed669e44e40ef13dd4875dbf2
[ "MIT" ]
null
null
null
example/src/Home.js
HakunaKp/React-Market-Analysis
65bea03c135a2c0ed669e44e40ef13dd4875dbf2
[ "MIT" ]
null
null
null
example/src/Home.js
HakunaKp/React-Market-Analysis
65bea03c135a2c0ed669e44e40ef13dd4875dbf2
[ "MIT" ]
null
null
null
import React from 'react'; import { Link } from 'react-router-dom'; const Home = () => ( <> <div className='header'> <h1 className='title'>Nasdaq Stock Market Analysis</h1> <h2 className='subtitle'>OHLC & Technical Indicators - Visualized</h2> <div className='links'> <a className='btn btn-gh' href='https://github.com/HakunaKp/' > GitHub </a> <a className='btn btn-npm' href='https://alpaca.markets/' > Alpaca </a> <a className='btn btn-chartjs' href='https://www.chartjs.org' > Chart.js </a> </div> </div> <hr /> <div className='categories'> <div className='category'> <h3 className='title'>OHLC Charts</h3> <ul className='items'> <li className='entry'> <Link to='/grouped-bar'>Grouped OHLC Bar Chart</Link> </li> </ul> </div> <div className='category'> <h3 className='title'>Technical Indicators</h3> <ul className='items'> <li className='entry'> <Link to='/multi-axis-line'>Grouped SMA & RSI</Link> </li> <li className='entry'> <Link to='/multi'>Grouped OHLC Bars, SMA & RSI</Link> </li> </ul> </div> <div className='category'> <h3 className='title'>Trading Strategies</h3> <ul className='items'> <li className='entry'> <Link to='/momentum'>Momentum</Link> </li> </ul> </div> </div> <hr /> <div className='footer'> <h6> <a href='https://kunal-patil.ghost.io'> Kunal Patil </a> </h6> </div> </> ); export default Home;
25.305556
76
0.487377
361cfdc71f9918ab4725c900ce927d6f8a24eb35
6,061
js
JavaScript
client/src/components/ServiceModal/ServiceModal.js
Igorxp5/stackprior
a29ec676168f8e88b64dbf2aef35e9636a2d9c79
[ "MIT" ]
3
2020-10-28T00:46:18.000Z
2020-10-28T00:46:58.000Z
client/src/components/ServiceModal/ServiceModal.js
Igorxp5/stackprior
a29ec676168f8e88b64dbf2aef35e9636a2d9c79
[ "MIT" ]
1
2020-11-10T19:57:05.000Z
2020-11-30T12:05:13.000Z
client/src/components/ServiceModal/ServiceModal.js
Igorxp5/stackprior
a29ec676168f8e88b64dbf2aef35e9636a2d9c79
[ "MIT" ]
1
2020-12-08T23:36:37.000Z
2020-12-08T23:36:37.000Z
import React, { Component} from "react"; import axios from 'axios'; import 'bootstrap/dist/css/bootstrap.min.css'; import { Modal, Button, Form, InputGroup } from 'react-bootstrap'; import './ServiceModal.scss'; class ServiceModal extends Component { constructor(props) { super(props) this.state = { name: this.props.service.name, endpoint: this.props.service.endpoint, sub_endpoint: this.props.service['sub-endpoint'], priority: this.props.service.priority, strategy: this.props.service.strategy, servers: this.props.service.servers, host: "", port: "", by_priority: "", strategy_temp: "" } this.renderStrategy = this.renderStrategy.bind(this); this.checkStrategy = this.checkStrategy.bind(this); this.closeModal = this.closeModal.bind(this); } checkStrategy() { if (this.state.strategy === "ROUND-ROBIN") { this.setState({port: this.props.service.port}) } else if (this.state.strategy === "BY PRIORITY") { this.setState({port: this.props.service.port}); this.setState({by_priority: this.props.service.by_priority}) } } renderServiceEdit() { return ( <Form onSubmit={this.handleSubmit}> <InputGroup className="input"> <Form.Control value={this.state.name} name="name" onChange={(e) => this.setState({ name: e.target.value })} required/> </InputGroup> <InputGroup className="input"> <Form.Control value={this.state.endpoint} name="endpoint" onChange={(e) => this.setState({ endpoint: e.target.value })} required/> </InputGroup> <InputGroup className="input"> <Form.Control value={this.state.sub_endpoint} name="sub_endpoint" onChange={(e) => this.setState({ sub_endpoint: e.target.value })} required/> </InputGroup> <InputGroup className="input"> <Form.Control value={this.state.priority} name="priority" onChange={(e) => this.setState({ priority: e.target.value })} required/> </InputGroup> <InputGroup className="input"> <Form.Control as="select" custom defaultValue={this.state.strategy} onChange={(e) => this.setState({ temp: e.target.value })}> <option disabled>STRATEGY</option> {/* <option>DNS</option> */} <option>ROUND-ROBIN</option> {/* <option>BY PRIORITY</option> */} </Form.Control> <InputGroup> {this.checkQnt()} <Form.Control placeholder={""}/> <Form.Control placeholder={""}/> </InputGroup> </InputGroup> <button className="submit-button"type="submit">Edit</button> </Form> ); } checkQnt() { var count = 0 if (this.state.strategy_temp === "") { return ( this.state.servers.map((server) => this.renderStrategy(server, count++)) ) } } // checkChange() { if (this.state.strategy_temp === "") { console.log("test") return false; } else if (this.state.strategy_temp !== "") { return true; } } renderStrategy(server, i) { if (this.state.strategy === "DNS") { return( <Form className="server-form"> {console.log("test")} <Form.Control className="input-new" placeholder={server.host} onChange={(e) => this.setState({ host: e.target.value })} required/> </Form> ) } else if (this.state.strategy === "ROUND-ROBIN") { return( <Form className="server-form"> <Form.Control /> </Form> ) } else if (this.state.strategy === "BY PRIORITY" ) { return ( <Form className="server-form"> <Form.Control className="input-new" value={this.state.server} onChange={(e) => this.setState({ server: e.target.value })} required/> <Form.Control className="input-new" placeholder="BY PRIORITY" value={this.state.by_priority} onChange={(e) => this.setState({ by_priority: e.target.value })} required/> </Form> ); } } componentDidMount() { this.state.strategy_temp = this.state.strategy; this.checkStrategy(); } handleSubmit(event) { const {name, endpoint, sub_endpoint, priority, strategy, servers} = this.state; if (strategy === "DNS") { axios.put('http://localhost:3333/services/', { //to be defined name: name, endpoint: endpoint, sub_endpoint: sub_endpoint, priority: priority, strategy: strategy, servers: servers }).then( response => console.log("response", response.data)) } else if (strategy === "ROUND-ROBIN") { axios.put('http://localhost:3333/services', { //to be defined name: name, endpoint: endpoint, sub_endpoint: sub_endpoint, priority: priority, strategy: strategy, servers: servers }).then( response => console.log("response", response.data)) } else if (strategy === "BY PRIORITY") { axios.put('http://localhost:3333/services', { //to be defined name: name, endpoint: endpoint, sub_endpoint: sub_endpoint, priority: priority, strategy: strategy, servers: servers }).then( response => console.log("response", response.data)) } } closeModal() { return this.props.callbackParent(false); } render() { return ( <Modal show={true} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Header> <Modal.Title id="contained-modal-title-vcenter"> <span className="title">NEW SERVICE</span> </Modal.Title> <Button variant="light" onClick={this.closeModal} > X </Button> </Modal.Header> <section > {this.renderServiceEdit()} <div> </div> </section> </Modal> ); } } export default ServiceModal;
32.411765
178
0.580597
361d1e0ff673395e87f6594ae86e3873f3883a40
981
js
JavaScript
scripts/generate_graph.js
michaelmartins09/elevator-problem-apa
0dfc6cdbed9324e968ac7dcddb391bcb430fa1a7
[ "MIT" ]
null
null
null
scripts/generate_graph.js
michaelmartins09/elevator-problem-apa
0dfc6cdbed9324e968ac7dcddb391bcb430fa1a7
[ "MIT" ]
null
null
null
scripts/generate_graph.js
michaelmartins09/elevator-problem-apa
0dfc6cdbed9324e968ac7dcddb391bcb430fa1a7
[ "MIT" ]
null
null
null
const plotLib = require('nodeplotlib') const { lab } = require("./execute_lab") const generateLayout = () => { return { title: 'Comparação Brute force x Dynamic Programming', xaxis: { title: 'Quantidade de andares' }, yaxis: { title: 'Tempo de execução' } }; } const generateGraph = () => { const { bruteForce, progDynamic, caseSize } = lab const data = [ { y: Array.from({length: caseSize}, (_, index) => bruteForce[`experimento${index+1}`].time), x: Array.from({length: caseSize}, (_, index) => bruteForce[`experimento${index+1}`].lifts), type: 'line', name: 'Brute Force' }, { y: Array.from({length: caseSize}, (_, index) => progDynamic[`experimento${index+1}`].time), x: Array.from({length: caseSize}, (_, index) => progDynamic[`experimento${index+1}`].lifts), type: 'line', name: 'Dynamic Programming' }, ]; return data } plotLib.plot(generateGraph(), generateLayout(), [{}]);
28.852941
98
0.602446
361e1072932ce5e9c71a7d8a64d9698d25314d29
214
js
JavaScript
examples/with-react-router/src/Home.js
chanhong/razzle
e2b416c16baaae5927bbe087813e18aa2824eb61
[ "MIT" ]
10,101
2017-03-22T13:27:14.000Z
2022-03-31T02:52:32.000Z
examples/with-react-router/src/Home.js
chanhong/razzle
e2b416c16baaae5927bbe087813e18aa2824eb61
[ "MIT" ]
1,321
2017-03-23T13:38:43.000Z
2022-03-30T22:30:46.000Z
examples/with-react-router/src/Home.js
chanhong/razzle
e2b416c16baaae5927bbe087813e18aa2824eb61
[ "MIT" ]
1,044
2017-03-26T19:30:52.000Z
2022-03-29T07:33:36.000Z
import React from "react"; import { Link } from "react-router-dom"; const Home = () => { return ( <> <p>Welcome to Razzle.</p> <Link to="about">About</Link> </> ); }; export default Home;
15.285714
40
0.546729
361e5d8160d8055a3e785991f06a47dda036b566
1,073
js
JavaScript
src/learning/components/FlashcardFoldersToLearn.js
damianszwed/fishky-ui
907d9b9b128f6e43d2c77ecc35cb7a4b64995e13
[ "MIT" ]
null
null
null
src/learning/components/FlashcardFoldersToLearn.js
damianszwed/fishky-ui
907d9b9b128f6e43d2c77ecc35cb7a4b64995e13
[ "MIT" ]
21
2020-04-26T07:54:16.000Z
2022-03-08T21:52:04.000Z
src/learning/components/FlashcardFoldersToLearn.js
damianszwed/fishky-ui
907d9b9b128f6e43d2c77ecc35cb7a4b64995e13
[ "MIT" ]
null
null
null
import React from 'react' import PropTypes from 'prop-types' import {Link} from "react-router-dom"; const FlashcardFoldersToLearn = ({flashcardFolders, navbarText}) => { return ( <div> <nav className="navbar navbar-light bg-light mb-3 mt-3"> <span className="navbar-brand mb-0 h1">{navbarText}</span> </nav> {flashcardFolders.map(flashcardFolder => ( <Link to={`/learning/${flashcardFolder.id}`} className="btn btn-outline-primary btn-block d-flex justify-content-between" key={flashcardFolder.id}> <span className="mt-1">{flashcardFolder.name}</span> <span className="badge badge-primary badge-pill h6 mt-2">{flashcardFolder.flashcards.length}</span> </Link> ))} </div> ) }; FlashcardFoldersToLearn.propTypes = { flashcardFolders: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired })).isRequired, navbarText: PropTypes.string.isRequired }; export default FlashcardFoldersToLearn;
33.53125
109
0.666356
361f9359b054eea4351195daa42ad707a04c5a4a
2,055
js
JavaScript
index.js
Nymoth/pkapii
c8ee20ab7da7ec194648327d650e99ff27af6ff7
[ "MIT" ]
null
null
null
index.js
Nymoth/pkapii
c8ee20ab7da7ec194648327d650e99ff27af6ff7
[ "MIT" ]
null
null
null
index.js
Nymoth/pkapii
c8ee20ab7da7ec194648327d650e99ff27af6ff7
[ "MIT" ]
null
null
null
import express from 'express'; import cors from 'cors'; import { MongoClient } from 'mongodb'; import { localeToLangId } from './core/locale'; import { getType } from './core/types'; require('dotenv').config(); async function main() { const { MONGODB_USER, MONGODB_PASS, MONGODB_URI, MONGODB_DBNAME } = process.env; if (!MONGODB_USER || !MONGODB_PASS, !MONGODB_URI || !MONGODB_DBNAME) { console.error('missing config'); return; } const uri = MONGODB_URI .replace('__USER__', MONGODB_USER) .replace('__PASS__', MONGODB_PASS); const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, }); try { await client.connect(); const db = client.db(MONGODB_DBNAME); await serveApp(db); } catch (e) { console.error(e); } } async function serveApp(db) { const app = express(); app.use(cors()); app.get('/list', async (req, res) => { const locale = localeToLangId(req.query.locale); const limit = req.query.limit ? +req.query.limit : 0; const skip = req.query.skip ? +req.query.skip : 0; const species = db.collection('pokemon_species_names'); const aggregationPipeline = [{ $match: { local_language_id: locale } }]; if (skip > 0) aggregationPipeline.push({ $skip: skip }); if (limit > 0) aggregationPipeline.push({ $limit: limit }); aggregationPipeline.push({ $lookup: { from: 'pokemon_types', localField: 'pokemon_species_id', foreignField: 'pokemon_id', as: 'type_slots' } }); const result = await species .aggregate(aggregationPipeline) .map(r => ({ id: r.pokemon_species_id, name: r.name, types: r.type_slots.map(({ type_id }) => getType(type_id)), sprite: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${r.pokemon_species_id}.png` })) .toArray(); res.json(result); }); app.listen(process.env.PORT || 3000, () => { console.log('api up') }); } main().catch(console.error);
25.6875
118
0.632117
3621425c92a75f61fb758d70bd57846960e6b317
1,118
js
JavaScript
src/compiler/types.js
smartadserver/amphtml
ef873f0e7c5134c31558c3ded4b75d4f3228450f
[ "Apache-2.0" ]
null
null
null
src/compiler/types.js
smartadserver/amphtml
ef873f0e7c5134c31558c3ded4b75d4f3228450f
[ "Apache-2.0" ]
2
2018-01-30T14:10:11.000Z
2021-09-24T12:51:03.000Z
src/compiler/types.js
smartadserver/amphtml
ef873f0e7c5134c31558c3ded4b75d4f3228450f
[ "Apache-2.0" ]
null
null
null
/** * AMP Components must implement this "buildDom" function in order to be server-rendered. * * - It must perform all of the DOM manipulations necessary to render a component. * Note: this is a subset of the responsibilities of buildCallback. * - It must not perform any side effects, such as adding event listeners or assigning instance variables. * - It must not perform any of the operations involved with layoutCallback (loading). * * The return value is set to *, so that we may optionally return any DOM nodes * created during a client-side render. These nodes are often needed for ivars. * * @typedef {function(!Element):*} */ export let BuildDomDef; /** * See @ampproject/bento-compiler for the definition. * @typedef {*} */ export let TreeProtoDef; /** * Contains component versioning data via a map from tagName --> version. * * @typedef {Object<string, string>}} */ export let VersionsDef; /** * @typedef {{ * document: TreeProtoDef, * versions: VersionsDef * }} */ export let CompilerRequest; /** * @typedef {{ document: TreeProtoDef }} */ export let CompilerResponse;
27.268293
106
0.711091
3621b83fb4c9c6f70a51292253cce17f9f6bcd41
1,260
js
JavaScript
tests/specs/take.spec.js
nyinyithann/SeqJS
eaa5a46252d4e8fb447d85890308b306424e790f
[ "MIT" ]
null
null
null
tests/specs/take.spec.js
nyinyithann/SeqJS
eaa5a46252d4e8fb447d85890308b306424e790f
[ "MIT" ]
null
null
null
tests/specs/take.spec.js
nyinyithann/SeqJS
eaa5a46252d4e8fb447d85890308b306424e790f
[ "MIT" ]
null
null
null
import Seq from '../../src/main'; describe('take()', () => { test('take exists', () => { const seq = Seq.of(1, 2, 3, 4, 5); const taken = seq.take(2); expect([...taken]).toEqual([1, 2]); }); test('take more', () => { const seq = Seq.of(1, 2, 3, 4, 5); const taken = seq.take(100); expect([...taken]).toEqual([1, 2, 3, 4, 5]); }); test('take none', () => { const seq = Seq.of(1, 2, 3, 4, 5); const taken = seq.take(0); expect(taken.isEmpty()).toBe(true); expect([...seq]).toEqual([1, 2, 3, 4, 5]); }); test('take from empty seq should be fine.', () => { const seq = Seq.empty(); const taken = seq.take(10); expect(taken.isEmpty()).toBe(true); }); test('should throw error if count is a non-negative', () => { const seq = Seq.of(1, 2, 3, 4, 5); expect(() => seq.take(-1)).toThrow(TypeError); }); test('apply/call invocation', () => { const seq = Seq.of(1, 2, 3, 4, 5); const { take } = Seq.prototype; const taken = take.call(seq, 3); expect([...taken]).toEqual([1, 2, 3]); }); test('apply/call invocation on null context should throw error', () => { const { take } = Seq.prototype; expect(() => take.call(null, 1)).toThrow(TypeError); }); });
27.391304
74
0.527778
3621f5fc8f6bfd16d0c98eb2365bc6ef936347dc
446
js
JavaScript
platforms/ios/www/js/configured_dust.js
vantist/CWEPBU_Library
b5b34d1d28525bf0c3aaef014dfad3e14da4484d
[ "MIT" ]
1
2015-12-01T04:24:26.000Z
2015-12-01T04:24:26.000Z
www/js/configured_dust.js
vantist/CWEPBU_Library
b5b34d1d28525bf0c3aaef014dfad3e14da4484d
[ "MIT" ]
null
null
null
www/js/configured_dust.js
vantist/CWEPBU_Library
b5b34d1d28525bf0c3aaef014dfad3e14da4484d
[ "MIT" ]
null
null
null
/* globals define */ define(['jquery', 'dust', 'debug'], function ($, Dust, Debug) { 'use strict'; // disable cache Dust.config.cache = false; // dust override onload Dust.onLoad = function dustOnLoadEvent(template, callback) { $.get('templates/' + template + '.dust', function (data) { callback(undefined, data); }).fail(function (err) { Debug.error('dust load error'); callback(err, undefined); }); }; return Dust; });
21.238095
63
0.636771
36223a8021c0f79d8f8b67565893f2c1f8d4a2bb
730
js
JavaScript
gulpfile.js
AdrianToman1/uiBreadcrumbs
7071d4216397fb2589d0920d23161a13d84922f4
[ "MIT" ]
null
null
null
gulpfile.js
AdrianToman1/uiBreadcrumbs
7071d4216397fb2589d0920d23161a13d84922f4
[ "MIT" ]
22
2016-11-22T23:08:16.000Z
2017-01-19T01:47:45.000Z
gulpfile.js
AdrianToman1/Angular-UI-Breadcrumbs
7071d4216397fb2589d0920d23161a13d84922f4
[ "MIT" ]
null
null
null
var gulp = require('gulp'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), gutil = require('gulp-util'), eslint = require('gulp-eslint'), karma = require('karma'); gulp.task('lint', function(){ return gulp.src(['uiBreadcrumbs.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('test', function (done) { new karma.Server({ configFile: __dirname + '/karma.conf.js', singleRun: true }, done).start(); }); gulp.task('default', ['lint', 'test'], function(){ return gulp.src(['uiBreadcrumbs.js']) .on('error', console.log) .pipe(uglify().on('error', gutil.log)) .pipe(rename({ suffix: '.min' })) .pipe(gulp.dest('.')); });
25.172414
51
0.608219
362250b3fb576624038256ea835c7ab28f08bd66
45,074
js
JavaScript
scripts/weatherOverview.js
signag/snweather-ui
e13009b5104247867a13737341f36f8f426db548
[ "MIT" ]
null
null
null
scripts/weatherOverview.js
signag/snweather-ui
e13009b5104247867a13737341f36f8f426db548
[ "MIT" ]
null
null
null
scripts/weatherOverview.js
signag/snweather-ui
e13009b5104247867a13737341f36f8f426db548
[ "MIT" ]
null
null
null
/* ======================== Chart default parameters ======================== */ // -- Initial start and end date var tEnd = new Date(); var tStart = new Date(tEnd.getFullYear(), tEnd.getMonth(), 1); // // Temperature range for widgets var tempMin = -30; var tempMax = 40; // -- Content selection var includeMeasurement = true; var includeForecast = true; // -- Range const PeriodEnum = Object.freeze({ "week": 1, "month": 2, "year": 3, "free": 4}); var period = PeriodEnum.month; // At beginning of a month, show also the previous month if (tEnd.getDate() <= 10) { period = PeriodEnum.free; if (tEnd.getMonth() == 0) { tStart = new Date(tEnd.getFullYear() - 1, 11, 1); } else { tStart = new Date(tEnd.getFullYear(), tEnd.getMonth() - 1, 1); }; }; // // Path to i18n lacale JSON files relative to root var localesPath = "/locales"; // Supported languages var supportedLangs = ["de", "en"]; // Fallback language var fallbackLangs = ["de"]; // Order for language detection // The page does not provide the capability to change the language // When launched from index.html, the current language for this page is transferred // through query string. var lngDetectOrder = ['querystring', 'navigator', 'htmlTag', 'subdomain']; // i18next debug mode var i18nextDebug = false; // -- Comparison sets // These are used for the comparison selector on the page // and serve ase base for datafields for data adapter // and xSeriesGroups for the charts. // The first set is the reference set which cannot be unselected // It's period range determins the x-axis value range on the charts. // If additional sets are added, also related table rows in overview.html must be added! // Consistency of compSet data (e.g. week, tStart, tEnd) // under consideration of period will be assured during initialization var compSets = [{ select: true, year: tEnd.getFullYear(), month: tEnd.getMonth() + 1, week: 1, tStart: tStart, tEnd: tEnd, setName:'REF', setCol: '#000000' }, { select: false, year: tEnd.getFullYear() - 1, month: tEnd.getMonth() + 1, week: 1, tStart: tStart, tEnd: tEnd, setName: 'CO1', setCol: '#FF0000' }, { select: false, year: tEnd.getFullYear() - 2, month: tEnd.getMonth() + 1, week: 1, tStart: tStart, tEnd: tEnd, setName: 'CO2', setCol: '#0000FF' }, ] /* ======================= Conversion to timestamp ======================= */ Date.prototype.toDayTimestamp = function() { y = this.getFullYear(); m = this.getMonth() + 1; ms = m.toString(); if (ms.length < 2) { ms = '0' + ms }; d = this.getDate(); ds = d.toString(); if (ds.length < 2) { ds = '0' + ds }; ts = y + '-' + ms + '-' + ds return ts; }; /* ========================= Last day of month as date ========================= */ Date.prototype.lastDayInMonth = function() { var y = this.getFullYear(); var m = this.getMonth() + 1; var d = new Date(y, m, 1); d.setDate(d.getDate() - 1); return d; }; /* ======================================================== Return the ISO week number Taken from https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php ========================================================= */ Date.prototype.getWeekNumber = function(){ var d = new Date(Date.UTC(this.getFullYear(), this.getMonth(), this.getDate())); var dayNum = d.getUTCDay() || 7; d.setUTCDate(d.getUTCDate() + 4 - dayNum); var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); return Math.ceil((((d - yearStart) / 86400000) + 1)/7) } /* ======================================================== For a given date, get the ISO week number Taken from https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php Based on information at: http://www.merlyn.demon.co.uk/weekcalc.htm#WNR Algorithm is to find nearest thursday, it's year is the year of the week number. Then get weeks between that date and the first day of that year. Note that dates in one year can be weeks of previous or next year, overlap is up to 3 days. e.g. 2014/12/29 is Monday in week 1 of 2015 2012/1/1 is Sunday in week 52 of 2011 ========================================================= */ function getWeekNumber(d) { // Copy date so don't modify original d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate())); // Set to nearest Thursday: current date + 4 - current day number // Make Sunday's day number 7 d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7)); // Get first day of year var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1)); // Calculate full weeks to nearest Thursday var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7); // Return array of year and week number return [d.getUTCFullYear(), weekNo]; } /* ============================================================== Return the start of a week as date, given week number and year Taken from https://stackoverflow.com/questions/16590500/javascript-calculate-date-from-week-number ============================================================== */ function getStartOfWeek(y, w){ var simple = new Date(y, 0, 1 + (w - 1) * 7); var dow = simple.getDay(); var ISOweekStart = simple; if (dow <= 4) ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1); else ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay()); return ISOweekStart; } /* ============================================== Determine First day of week and return as date ============================================== */ function firstDayOfWeek(date) { d = new Date(date.getFullYear(), date.getMonth(), date.getDate()); var wd = d.getDay() || 7; if( wd !== 1 ) d.setHours(-24 * (wd - 1)); return d; } /* ======================== Initializing ======================== */ // -- Auto refresh var autoRefresh = false; var refreshRequired = false; var doNotRefresh = false; var ignoreEvents = false; for (var s = 0; s < compSets.length; s++) { compSets[s]['week'] = tEnd.getWeekNumber(); }; var cmpSets = new Array(); // -- parameters controlling the data adapter query var querydata = { 'start': tStart.toDayTimestamp() + ' 00:00:00', 'end' : tEnd.toDayTimestamp() + ' 23:59:59', period, PeriodEnum, compset: cmpSets, }; // -- Declare global chart configuration variables var sourceList; var datafields; var dataAdapter; var tSettings; var tSeriesGroups; var pSettings; var pSeriesGroups; var hSettings; var hSeriesGroups; // -- Declare tooltip format function for all charts // The intention is to show the specific time of measurement or forecast // for a series, rather than the time of the reference set var toolTipCustomFormatFn = function ( value, itemIndex, series, group, categoryValue, categoryAxis) { var tRef = categoryValue; var df = series["dataField"]; // Data field naming is e.g. fc_temperature_REF // Get set ID (e.g. "REF") var p = df.lastIndexOf("_"); var setId = df.substring(p + 1, df.length); var set = i18next.t("comparisonSet") + ": " + setId; df = df.substr(0, p); // Get forecast or measurement var isForecast = false; if (df.substr(0, 3) == "fc_") { isForecast = true; df = df.substring(3, df.length); } // Determine set-specific time var tSet = setSpecificDate(tRef, setId); var tSer = tSet.toLocaleString(i18next.language); var tDis = i18next.t("time") + ": " + tSer; // Set data type if (isForecast == true) { var dTyp = i18next.t("forecast"); } else { var dTyp = i18next.t("measurement"); }; // Set unit var unit = "??" if (df == "temperature") { unit = "°C"; } else if (df == "pressure") { unit = "hPa"; } else if (df == "humidity") { unit = "%" }; // Prepare display dTyp = dTyp + " " + i18next.t(df); var dat = dTyp + ": " + value + " " + unit return '<div style="text-align:left">' + set + '<br />' + tDis + '<br />' + dat; }; /* ===================================================== Determine set-specific date from given reference date ===================================================== */ function setSpecificDate(refDate, setId) { var sd = refDate; if (setId != compSets[0]["setName"]) { var y = sd.getFullYear var m = sd.getMonth(); var d = sd.getDate(); var wd = sd.getDay() || 7; var h = sd.getHours(); var mi = sd.getMinutes(); var s = sd.getSeconds(); var ms = sd.getMilliseconds(); var compSet = getComparisonSet(setId); if (compSet != null) { switch(period) { case PeriodEnum.year: // Set date is corresponding date in set year sd = new Date(compSet['year'], m, d, h, mi, s, ms); break; case PeriodEnum.month: // Set date is corresponding date in set month sd = new Date(compSet['year'], compSet['month'] - 1, d, h, mi, s, ms); break; case PeriodEnum.week: // Set date is corresponding week day in set week var ws = getStartOfWeek(compSet['year'], compSet['week']); sd = new Date(ws.getFullYear(), ws.getMonth(), ws.getDate(), h, mi, s, ms); sd.setDate(sd.getDate() + wd - 1); break; case PeriodEnum.free: // Set date is corresponding date in set year sd = new Date(compSet['year'], m, d, h, mi, s, ms); break; }; }; }; return sd; } /* =============================== Get comparison set given its ID =============================== */ function getComparisonSet(setId) { var set = null; for (var s = 0; s < compSets.length; s++) { if (compSets[s]['setName'] == setId) { set = compSets[s]; break; }; }; return set; } /* ======================= Localization ======================= */ function localize(initial) { var lng = i18next.language; // Localize header $('.snw-header').localize(); // Localize data $('.snw-data').localize(); // Localize buttons $("#refreshbutton" ).jqxButton({ value: i18next.t("refresh") }); } /* ====================================== Set up query data from comparison sets ====================================== */ function setupQueryData() { cmpSets = new Array(); var l = compSets.length; if (l > 1) { for (var i = 1; i < l; i++) { if (compSets[i]['select'] == true) { var s = compSets[i]['tStart'].toDayTimestamp() + ' 00:00:00'; var e = compSets[i]['tEnd'].toDayTimestamp() + ' 23:59:59'; cmpSets.push({ name: compSets[i]['setName'], start: s, end: e, }); }; }; }; querydata = { 'start': tStart.toDayTimestamp() + ' 00:00:00', 'end': tEnd.toDayTimestamp() + ' 23:59:59', period, PeriodEnum, compset: cmpSets, }; } /* ======================== Set up data adapter ======================== */ function setupDataAdapter() { setupQueryData(); var source = { datatype: "json", datafields: datafields, url: 'scripts/weatherOverviewData.php', data: querydata, async: false, }; dataAdapter = new $.jqx.dataAdapter(source, { autoBind: true, async: false, downloadComplete: function() {}, loadComplete: function() {}, loadError: function() {}, }); } /* ======================== Set up temperature chart ======================== */ function setupTemperatureChart() { tSettings = { title: '', description: '', showLegend: false, animationDuration: 500, showBorderLine: false, source: dataAdapter, colorScheme: 'scheme05', toolTipFormatFunction: toolTipCustomFormatFn, xAxis: { textRotationAngle: 90, valuesOnTicks: true, dataField: 'timestamp', type: 'date', baseUnit: 'day', unitInterval: 1, formatFunction: function(value) { return $.jqx.dataFormat.formatdate(value, 'dd.MM.yy'); }, showTickMarks: true, }, valueAxis: { displayValueAxis: true, description: '', axisSize: 'auto', unitInterval: 1, labels: { visible: true, step: 5 }, tickMarks: { visible: true, step: 1, color: '#000000' }, gridLines: { visible: true, step: 5, color: '#000000' }, minValue: tempMin, maxValue: tempMax, }, seriesGroups: tSeriesGroups, }; } /* ======================== Set up pressure chart ======================== */ function setupPressureChart() { pSettings = { title: '', description: '', showLegend: false, animationDuration: 500, showBorderLine: false, source: dataAdapter, colorScheme: 'scheme05', toolTipFormatFunction: toolTipCustomFormatFn, xAxis: { textRotationAngle: 90, valuesOnTicks: true, dataField: 'timestamp', type: 'date', baseUnit: 'day', unitInterval: 1, formatFunction: function(value) { return $.jqx.dataFormat.formatdate(value, 'dd.MM.yy'); }, showTickMarks: true, }, valueAxis: { displayValueAxis: true, description: '', axisSize: 'auto', tickMarks: { visible: true, step: 1, color: '#000000' }, unitInterval: 5, minValue: 950, maxValue: 1080 }, seriesGroups: pSeriesGroups, }; } /* ======================== Set up humidity chart ======================== */ function setupHumidityChart() { hSettings = { title: '', description: '', showLegend: false, animationDuration: 500, showBorderLine: false, source: dataAdapter, colorScheme: 'scheme05', toolTipFormatFunction: toolTipCustomFormatFn, xAxis: { textRotationAngle: 90, valuesOnTicks: true, dataField: 'timestamp', type: 'date', baseUnit: 'day', unitInterval: 1, formatFunction: function(value) { return $.jqx.dataFormat.formatdate(value, 'dd.MM.yy'); }, showTickMarks: true, }, valueAxis: { displayValueAxis: true, description: '', axisSize: 'auto', tickMarks: { visible: true, step: 1, color: '#000000' }, unitInterval: 10, minValue: 0, maxValue: 100 }, seriesGroups: hSeriesGroups, }; } /* ===================================================================== Initialize data fields datafields for dataAdapter and xSeriesGroups for the charts (x=t,p,h) are initialized simultaneously ===================================================================== */ function initializeDataFields() { // datafields datafields = new Array(); datafields.push({ name: 'timestamp', type: 'date' }) datafields.push({ name: 'year' }) datafields.push({ name: 'day_year' }) datafields.push({ name: 'month' }) datafields.push({ name: 'day_month' }) datafields.push({ name: 'week' }) datafields.push({ name: 'day_week' }) datafields.push({ name: 'hour' }) // series groups tSeriesGroups = new Array(); pSeriesGroups = new Array(); hSeriesGroups = new Array(); } /* ===================================================================== Add data fields for measurement data for specific data set datafields for dataAdapter and xSeriesGroups for the charts (x=t,p,h) are added simultaneously ===================================================================== */ function DataFieldsMeasurement(set, col) { // datafields for data source datafields.push({ name: 'temperature_' + set }); datafields.push({ name: 'humidity_' + set }); datafields.push({ name: 'pressure_' + set }); // Series groups temperature tSeriesGroups.push({ type: 'line', series: [{ dataField: 'temperature_' + set, lineColor: col, emptyPointsDisplay: 'skip', displayText: set + ': ' + i18next.t("measuredTemp"), }] }); // Series groups pressure pSeriesGroups.push({ type: 'line', series: [{ dataField: 'pressure_' + set, lineColor: col, emptyPointsDisplay: 'skip', displayText: set + ': ' + i18next.t("measuredPres"), }] }); // Series groups humidity hSeriesGroups.push({ type: 'line', series: [{ dataField: 'humidity_' + set, lineColor: col, emptyPointsDisplay: 'skip', displayText: set + ': ' + i18next.t("measuredHumi"), }] }); } /* ===================================================================== Add data fields for reference forecast data datafields for dataAdapter and xSeriesGroups for the charts (x=t,p,h) are added simultaneously ===================================================================== */ function DataFieldsForecast(set, col) { // datafields for data source datafields.push({ name: 'fc_temperature_' + set }); datafields.push({ name: 'fc_humidity_' + set }); datafields.push({ name: 'fc_pressure_' + set }); // Series groups temperature tSeriesGroups.push({ type: 'scatter', series: [{ dataField: 'fc_temperature_' + set, symbolType: 'circle', symbolSize: 1, lineColor: col, lineColorSymbol: col, emptyPointsDisplay: 'skip', displayText: set + ': ' + i18next.t('forecastTemp'), }] }); // Series groups pressure pSeriesGroups.push({ type: 'scatter', series: [{ dataField: 'fc_pressure_' + set, symbolType: 'circle', symbolSize: 1, lineColor: col, lineColorSymbol: col, emptyPointsDisplay: 'skip', displayText: set + ': ' + i18next.t('forecastPres'), }] }); // Series groups humidity hSeriesGroups.push({ type: 'scatter', series: [{ dataField: 'fc_humidity_' + set, symbolType: 'circle', symbolSize: 1, lineColor: col, lineColorSymbol: col, emptyPointsDisplay: 'skip', displayText: set + ': ' + i18next.t('forecastHumi'), }] }); } /* ============================================================== Configure data fields according to current configuration Fields for dataAdapter (datafields) and series groups for charts (xSeriesGroups) for the three chart types (x=t,p,h) are configured simultaneously. ============================================================== */ function configureDataFields() { // Initialize initializeDataFields(); // Add reference data set if (includeMeasurement == true) { DataFieldsMeasurement(compSets[0]['setName'], compSets[0]['setCol']); }; if (includeForecast == true) { DataFieldsForecast(compSets[0]['setName'], compSets[0]['setCol']); }; var nrSets = compSets.length; for (var s = 1; s < nrSets; s++) { if (compSets[s]['select'] == true) { if (includeMeasurement == true) { DataFieldsMeasurement(compSets[s]['setName'], compSets[s]['setCol']); } if (includeForecast == true) { DataFieldsForecast(compSets[s]['setName'], compSets[s]['setCol']); }; }; }; } /* ================== Refresh all charts ================== */ function refreshAll(force) { if ((doNotRefresh == false) && ((autoRefresh == true) || (force == true))) { // Refresh is done only if autoRefresh is activated or if forced // In addition the global doNotRefresh is used to avoid refresh // when multiple parameter change events are expected $("#progressbar").jqxProgressBar({ value: 0, width: 100, height: 25, max: 100, showText: false}); // Configure datafields for dataAdapter and xSeriesGroups for charts configureDataFields(); //set up the dataAdapter setupDataAdapter(); $("#progressbar").jqxProgressBar({ animationDuration: 0, value: 20 }); dataAdapter.dataBind(); $("#progressbar").jqxProgressBar({ animationDuration: 0, value: 40 }); // Set up and refresh the different charts setupTemperatureChart(); $('#tempFunc').jqxChart(tSettings); $("#progressbar").jqxProgressBar({ animationDuration: 0, value: 60 }); setupPressureChart(); $('#presFunc').jqxChart(pSettings); $("#progressbar").jqxProgressBar({ animationDuration: 0, value: 80 }); setupHumidityChart(); $('#humiFunc').jqxChart(hSettings); $("#progressbar").jqxProgressBar({ animationDuration: 0, value: 100 }); // Reset refresh indicator refreshRequired = false; // ... and disable the refresh button $("#refreshbutton").jqxButton({ disabled: true }); $("#progressbar").jqxProgressBar({ animationDuration: 0, value: 0 }); //$("#progressbar").jqxProgressBar('destroy'); } else { // Refresh is postponed // Therefore, set refresh indicator refreshRequired = true; // ... and enable the refresh button $("#refreshbutton").jqxButton({ disabled: false }); // Reset the doNotRefresh every time, a refresh has been postponed //doNotRefresh = false; } } /* ================================== Set up Selector for display period ================================== */ function setupPeriodSelector() { // Setup start selector $("#startinput").jqxDateTimeInput({ width: '120px', height: '25px' }); $('#startinput').jqxDateTimeInput({ culture: i18next.language }); $("#startinput").jqxDateTimeInput('setDate', tStart); $('#startinput').on('change', function(event) { if (ignoreEvents == false) { tStart = event.args.date; period = PeriodEnum.free; ignoreEvents = true; $("#periodFree").jqxRadioButton('check'); ignoreEvents = false; doNotRefresh = true; refreshComparisonSelectors(); doNotRefresh = false; refreshAll(false); }; }); // Setup end selector $("#endinput").jqxDateTimeInput({ width: '120px', height: '25px' }); $('#endinput').jqxDateTimeInput({ culture: i18next.language }); $("#endinput").jqxDateTimeInput('setDate', tEnd); $('#endinput').on('change', function(event) { if (ignoreEvents == false) { tEnd = event.args.date; period = PeriodEnum.free; ignoreEvents = true; $("#periodFree").jqxRadioButton('check'); ignoreEvents = false; doNotRefresh = true; refreshComparisonSelectors(); doNotRefresh = false; refreshAll(false); }; }); } /* =========================================== Set up content selector for measured values =========================================== */ function setupContentSelectorMeasurement() { //Checkboxes for content selection $("#selectMeasurement").jqxCheckBox({ width: 120, height: 25 }); if (includeMeasurement == true) { $("#selectMeasurement").jqxCheckBox('check'); } else { $("#selectMeasurement").jqxCheckBox('uncheck'); }; $("#selectMeasurement").bind('change', function(event) { var checked = event.args.checked; if (checked) { includeMeasurement = true; refreshAll(false); } else { includeMeasurement = false; refreshAll(false); }; }); } /* ==================================== Set up content selector for forecast ==================================== */ function setupContentSelectorForecast() { //Checkboxes for content selection $("#selectForecast").jqxCheckBox({ width: 120, height: 25 }); if (includeForecast == true) { $("#selectForecast").jqxCheckBox('check'); } else { $("#selectForecast").jqxCheckBox('uncheck'); }; $("#selectForecast").bind('change', function(event) { var checked = event.args.checked; if ((checked) && (ignoreEvents == false)) { includeForecast = true; refreshAll(false); } else { includeForecast = false; refreshAll(false); }; }); } /* ==================================================== Prepare compSet based on current configuration Adjust month, week, tStart, tEnd depending on period ==================================================== */ function prepareCompSet(ind) { var start; var end; var tNow = new Date(); switch(period) { case PeriodEnum.year: // Year is fix. adjust the others start = new Date(compSets[ind]['year'], 0, 1); end = new Date(compSets[ind]['year'], 11, 31); compSets[ind]['tStart'] = start; compSets[ind]['tEnd'] = end; compSets[ind]['week'] = end.getWeekNumber(); compSets[ind]['month'] = 12; break; case PeriodEnum.month: // Year and month are fixed. Adjust the others start = new Date(compSets[ind]['year'], compSets[ind]['month'] - 1, 1); end = start.lastDayInMonth(); compSets[ind]['tStart'] = start; compSets[ind]['tEnd'] = end; compSets[ind]['week'] = end.getWeekNumber(); break; case PeriodEnum.week: // Year and week are fixed. Adjust the others start = getStartOfWeek(compSets[ind]['year'], compSets[ind]['week']); if (start > tNow) { start = firstDayOfWeek(tNow); }; end = new Date(start.getFullYear(), start.getMonth(), start.getDate()); end.setDate(start.getDate() + 6); m = end.getMonth(); compSets[ind]['tStart'] = start; compSets[ind]['tEnd'] = end; compSets[ind]['week'] = end.getWeekNumber(); compSets[ind]['month'] = m + 1; break; case PeriodEnum.free: // Year is fixed. start and end from global if (ind == 0) { start = tStart; end = tEnd; } else { var m = tStart.getMonth(); var d = tStart.getDate(); start = new Date(compSets[ind]['year'], m, d); var m = tEnd.getMonth(); var d = tEnd.getDate(); end = new Date(compSets[ind]['year'], m, d); } compSets[ind]['tStart'] = start; compSets[ind]['tEnd'] = end; compSets[ind]['week'] = end.getWeekNumber(); break; }; } /* ======================================= Show additional inf for compSets ======================================= */ function showCompSetInfo(ind) { // Show set name var cbIdName = "#set" + ind + "name"; $(cbIdName).text(compSets[ind].setName); // Color var cbIdColor = "#set" + ind + "color"; $(cbIdColor).css("background-color", compSets[ind].setCol); } /* ======================================= Initialize all compSets ======================================= */ function prepareCompSets() { var nrSets = compSets.length; for (var s = 0; s < nrSets; s++ ) { prepareCompSet(s); showCompSetInfo(s); } } /* =================================================================== Set up individual comparison selector selection of year ind : Corresponding index of compSets ==================================================================== */ function refreshComparisonSelectorYear(ind) { var cbId = "#set" + ind + "year"; // Set value ignoreEvents = true; $(cbId).jqxNumberInput({ decimal: compSets[ind]['year']}); ignoreEvents = false; } /* =================================================================== Refresh individual comparison selector selection of month ind : Corresponding index of compSets ==================================================================== */ function refreshComparisonSelectorMonth(ind) { var cbId = "#set" + ind + "month"; // Set value ignoreEvents = true; $(cbId).jqxNumberInput({ decimal: compSets[ind]['month']}); ignoreEvents = false; // Disable depending on period selection if ((period == PeriodEnum.year) || (period == PeriodEnum.week) || (period == PeriodEnum.free)) { $(cbId).jqxNumberInput({ disabled: true }); } else { $(cbId).jqxNumberInput({ disabled: false }); }; } /* =================================================================== Refresh individual comparison selector selection of week ind : Corresponding index of compSets ==================================================================== */ function refreshComparisonSelectorWeek(ind) { var cbId = "#set" + ind + "week"; // Set value ignoreEvents = true; $(cbId).jqxNumberInput({ decimal: compSets[ind]['week']}); ignoreEvents = false; // Disable depending on period selection if ((period == PeriodEnum.year) || (period == PeriodEnum.month) || (period == PeriodEnum.free)) { $(cbId).jqxNumberInput({ disabled: true }); } else { $(cbId).jqxNumberInput({ disabled: false }); }; } /* =================================================================== Refresh individual comparison selector id : identifying part of jQuery selector (e.g. 'set1') ind : Corresponding index of compSets isRef : True if the selector is the reference (cannot be unselected) ==================================================================== */ function refreshComparisonSelector(ind) { // Year refreshComparisonSelectorYear(ind); // Month refreshComparisonSelectorMonth(ind); // Week refreshComparisonSelectorWeek(ind); } /* ======================================= Adjust compSet based on modified values ======================================= */ function adjustCompSet(ind) { // Prepare compSet data prepareCompSet(ind); // Adjust display values without firing change events refreshComparisonSelector(ind); if (ind == 0){ tStart = compSets[ind]['tStart']; tEnd = compSets[ind]['tEnd']; ignoreEvents = true; $("#startinput").jqxDateTimeInput('setDate', tStart); $("#endinput").jqxDateTimeInput('setDate', tEnd); ignoreEvents = false; refreshAll(false); } else { if (compSets[ind]['select'] == true) { // Do refresh only if comparison set is active refreshAll(false); }; }; } /* ============================ Refresh comparison selectors ============================ */ function refreshComparisonSelectors() { var nrSets = compSets.length; for (var ind = 0; ind < nrSets; ind++) { adjustCompSet(ind); }; } /* =================================================================== Set up individual comparison selector selection check box ind : Corresponding index of compSets ==================================================================== */ function setupComparisonSelectorSel(ind) { // Checkbox var cbId = "#set" + ind + "select"; $(cbId).jqxCheckBox({ width: 25, height: 25 }); if (compSets[ind]['select'] == true) { $(cbId).jqxCheckBox('check'); } else { $(cbId).jqxCheckBox('uncheck'); }; if (ind == 0) { $(cbId).jqxCheckBox({ disabled: true}); } else { $(cbId).jqxCheckBox({ disabled: false}); } $(cbId).bind('change', function(event) { var checked = event.args.checked; if ((checked) && (ignoreEvents == false)) { compSets[ind]['select'] = true; refreshAll(false); } else { compSets[ind]['select'] = false; refreshAll(false); }; }); } /* =================================================================== Set up individual comparison selector selection of year id : identifying part of jQuery selector (e.g. 'set1') ind : Corresponding index of compSets ==================================================================== */ function setupComparisonSelectorYear(ind) { // Checkbox var cbId = "#set" + ind + "year"; var settings = { width: '80px', height: '25px', decimalDigits: 0, groupSeparator: '', groupSize: 4, inputMode: 'simple', spinButtons: true, spinMode: 'simple', min: 2019, max: 2050, }; $(cbId).jqxNumberInput(settings); $(cbId).on('change', function(event) { if (ignoreEvents == false) { compSets[ind]['year'] = event.args.value; adjustCompSet(ind); }; }); } /* =================================================================== Set up individual comparison selector selection of month ind : Corresponding index of compSets ==================================================================== */ function setupComparisonSelectorMonth(ind) { // Checkbox var cbId = "#set" + ind + "month"; var settings = { width: '63px', height: '25px', decimalDigits: 0, groupSeparator: '', groupSize: 2, inputMode: 'simple', spinButtons: true, spinMode: 'simple', min: 1, max: 12, }; $(cbId).jqxNumberInput(settings); // Register change event $(cbId).on('change', function(event) { var cbId = "#set" + ind + "month"; if (($(cbId).jqxNumberInput('disabled') == false) && (ignoreEvents == false)) { // handle only user modifications var value = event.args.value; compSets[ind]['month'] = value; var fdm = new Date(compSets[ind]['year'], value - 1, 1); var ldm = fdm.lastDayInMonth(); compSets[ind]['week'] = ldm.getWeekNumber(); var cbIdw = "#set" + ind + "week"; ignoreEvents = true; $(cbIdw).jqxNumberInput({ decimal: compSets[ind]['week']}); ignoreEvents = false; adjustCompSet(ind); }; }); } /* =================================================================== Set up individual comparison selector selection of week id : identifying part of jQuery selector (e.g. 'set1') ind : Corresponding index of compSets ==================================================================== */ function setupComparisonSelectorWeek(ind) { // Checkbox var cbId = "#set" + ind + "week"; var settings = { width: '63px', height: '25px', decimalDigits: 0, groupSeparator: '', groupSize: 2, inputMode: 'simple', spinButtons: true, spinMode: 'simple', min: 1, max: 53, }; $(cbId).jqxNumberInput(settings); // Register change event $(cbId).on('change', function(event) { var cbId = "#set" + ind + "week"; if (($(cbId).jqxNumberInput('disabled') == false) && (ignoreEvents == false)) { // handle only user modifications var value = event.args.value; compSets[ind]['week'] = value; var ws = getStartOfWeek(compSets[ind]['year'], value); var we = new Date(ws.getFullYear(), ws.getMonth(), ws.getDate()); we.setDate(ws.getDate() + 6); compSets[ind]['month'] = we.getMonth() + 1; var cbIdm = "#set" + ind + "month"; ignoreEvents = true; $(cbIdm).jqxNumberInput({ decimal: compSets[ind]['month']}); ignoreEvents = false; adjustCompSet(ind); }; }); } /* =================================================================== Set up individual comparison selector id : identifying part of jQuery selector (e.g. 'set1') ind : Corresponding index of compSets isRef : True if the selector is the reference (cannot be unselected) ==================================================================== */ function setupComparisonSelector(ind) { // Checkbox setupComparisonSelectorSel(ind); // Year setupComparisonSelectorYear(ind); // Month setupComparisonSelectorMonth(ind); // Week setupComparisonSelectorWeek(ind); } /* =========================== Set up comparison selectors =========================== */ function setupComparisonSelectors() { var nrSets = compSets.length; for (var ind = 0; ind < nrSets; ind++) { setupComparisonSelector(ind); refreshComparisonSelector(ind); }; } /* ============================== Set up range selector for week ============================== */ function setupRangeSelectorWeek() { //Radio buttons for range selection $("#periodWeek").jqxRadioButton({ width: 120, height: 25 }); if (period == PeriodEnum.week) { $("#periodWeek").jqxRadioButton('check'); } $("#periodWeek").bind('change', function(event) { var checked = event.args.checked; if ((checked) && (ignoreEvents == false)) { period = PeriodEnum.week; // Starting from tEnd, determine beginning of week tStart = firstDayOfWeek(tEnd); // Refresh comparison selectors doNotRefresh = true; refreshComparisonSelectors(); doNotRefresh = false; refreshAll(false); }; }); } /* =============================== Set up range selector for month =============================== */ function setupRangeSelectorMonth() { //Radio buttons for range selection $("#periodMonth").jqxRadioButton({ width: 120, height: 25 }); if (period == PeriodEnum.month) { $("#periodMonth").jqxRadioButton('check'); } $("#periodMonth").bind('change', function(event) { var checked = event.args.checked; if ((checked) && (ignoreEvents == false)) { period = PeriodEnum.month; // Starting fro tEnd, determine beginning of month tStart = new Date(tEnd.getFullYear(), 0, 1); // Refresh comparison selectors doNotRefresh = true; refreshComparisonSelectors(); doNotRefresh = false; refreshAll(false); }; }); } /* ============================== Set up range selector for year ============================== */ function setupRangeSelectorYear() { //Radio buttons for range selection $("#periodYear").jqxRadioButton({ width: 120, height: 25 }); if (period == PeriodEnum.year) { $("#periodYear").jqxRadioButton('check'); } $("#periodYear").bind('change', function(event) { var checked = event.args.checked; if ((checked) && (ignoreEvents == false)) { period = PeriodEnum.year; // Starting from tEnd, determine beginning of month tStart = new Date(tEnd.getFullYear(), tEnd.getMonth(), 1); // Refresh comparison selectors doNotRefresh = true; refreshComparisonSelectors(); doNotRefresh = false; refreshAll(false); }; }); } /* ==================================== Set up range selector for free range ==================================== */ function setupRangeSelectorFree() { //Radio buttons for range selection $("#periodFree").jqxRadioButton({ width: 120, height: 25 }); if (period == PeriodEnum.free) { $("#periodFree").jqxRadioButton('check'); } $("#periodFree").bind('change', function(event) { var checked = event.args.checked; if ((checked) && (ignoreEvents == false)) { period = PeriodEnum.free; doNotRefresh = true; refreshComparisonSelectors(); doNotRefresh = false; refreshAll(false); }; }); } /* ================================= Set up check box for auto refresh ================================= */ function setupAutoRefresh() { //Checkbox $("#autoRefresh").jqxCheckBox({ width: 170, height: 25 }); if (autoRefresh == true) { $("#autoRefresh").jqxCheckBox('check'); } else { $("#autoRefresh").jqxCheckBox('uncheck'); }; $("#autoRefresh").bind('change', function(event) { var checked = event.args.checked; if ((checked) && (ignoreEvents == false)) { autoRefresh = true; if (refreshRequired == true) { refreshAll(false); } } else { autoRefresh = false; }; }); } /* ===================== Toggle refresh button ===================== */ function toggleRefreshButton() { if (refreshRequired == true) { $("#refreshbutton").jqxButton({ disabled: false }); } else { $("#refreshbutton").jqxButton({ disabled: true }); }; } /* ===================== Set up refresh button ===================== */ function setupRefreshButton() { $("#refreshbutton").jqxButton({ width : 100, height : 25, textPosition: 'center', }); toggleRefreshButton(); $('#refreshbutton').click(function() { refreshAll(true); $("#refreshbutton").jqxButton({ disabled: false }); }); } /* =================== Set up progress bar =================== */ function setupProgressBar() { $("#progressbar").jqxProgressBar({ width: 20, height: 25 }); } /* =================== Main =================== */ $(document).ready(function() { // // Localization var root = location.pathname.slice(0, location.pathname.indexOf('/', 1)); i18next.use(i18nextHttpBackend); i18next.use(i18nextBrowserLanguageDetector); i18next.init({ detection: { order : lngDetectOrder, }, supportedLngs: supportedLangs, fallbackLng : fallbackLangs, debug: i18nextDebug, backend: { loadPath : root + localesPath + '/snw_{{lng}}.json' }, }, function(err, t) { jqueryI18next.init(i18next, $); localize(true); // // Special handling for initial period // // Auto refresh checkbox and button setupAutoRefresh(); setupRefreshButton(); // Set selector for display period setupPeriodSelector(); // Set up selector for content types (measurement / forecast) setupContentSelectorMeasurement(); setupContentSelectorForecast(); // Set up radio buttons for selection of range type setupRangeSelectorWeek(); setupRangeSelectorMonth(); setupRangeSelectorYear(); setupRangeSelectorFree(); // Set up selectors for comparison data sets prepareCompSets(); setupComparisonSelectors(); // Configure data fields configureDataFields(); // Set up data adapter setupDataAdapter(); // Define and draw temperture chart setupTemperatureChart(); $('#tempFunc').jqxChart(tSettings); // Define and draw pressure chart setupPressureChart(); $('#presFunc').jqxChart(pSettings); // Define and draw humidity chart setupHumidityChart(); $('#humiFunc').jqxChart(hSettings); /* */ }); });
30.809296
96
0.512002
3622645678ed2a838c87c8d4fbacac4ddaafec67
871
js
JavaScript
src/global/mixins.js
stangerjm/smart-x-vue
d8ace7df0027f260f6b944b0d5cc4640465bfa51
[ "MIT" ]
1
2020-08-07T19:22:04.000Z
2020-08-07T19:22:04.000Z
src/global/mixins.js
stangerjm/smart-x-vue
d8ace7df0027f260f6b944b0d5cc4640465bfa51
[ "MIT" ]
null
null
null
src/global/mixins.js
stangerjm/smart-x-vue
d8ace7df0027f260f6b944b0d5cc4640465bfa51
[ "MIT" ]
null
null
null
import parseDateString from './mixins/parseDateString'; import createViewModel from './mixins/createViewModel'; import toTitleCase from './mixins/toTitleCase'; import getItemId from './mixins/getItemId'; import createLinkToRecord from './mixins/createLinkToRecord'; import getDataSortedByColumn from './mixins/getDataSortedByColumn'; import compare from './mixins/compare'; import getInputType from './mixins/getInputType'; import transformIntoFormModel from './mixins/transformIntoFormModel'; import formatDate from './mixins/formatDate'; import switchCase from './mixins/switchCase'; import generateRandomId from './mixins/generateRandomId'; export { parseDateString, createViewModel, toTitleCase, getItemId, createLinkToRecord, getDataSortedByColumn, compare, getInputType, transformIntoFormModel, formatDate, switchCase, generateRandomId, };
31.107143
69
0.799082
362272bb38f6b5f7f786c871de8d74c31dbd42f2
393
js
JavaScript
app/components/AddUser/messages.js
pauleonardo/demo-trans
a3d4e0e7ea2eee1f6af46d6cc4a6ccb47a7a78ba
[ "MIT" ]
1
2018-07-08T14:22:08.000Z
2018-07-08T14:22:08.000Z
app/components/AddUser/messages.js
pauleonardo/demo-trans
a3d4e0e7ea2eee1f6af46d6cc4a6ccb47a7a78ba
[ "MIT" ]
null
null
null
app/components/AddUser/messages.js
pauleonardo/demo-trans
a3d4e0e7ea2eee1f6af46d6cc4a6ccb47a7a78ba
[ "MIT" ]
null
null
null
/* * AddUser Messages * * This contains all the text for the AddUser component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.components.AddUser.header', defaultMessage: 'This is the AddUser component !', }, boxAdmin: { id: 'app.components.AddUser.boxAdmin', defaultMessage: 'Acciones de Administrador', }, });
21.833333
56
0.679389
36232b8801f88d38081f79883681d29c4486600f
1,304
js
JavaScript
angular2-rxjs-observable-data-services-master/angular2-rxjs-observable-data-services-master/src/server.js
MaxvandenHout/allcode
e965b8f7acd5f69938946a4d7c33c395ff52b81c
[ "Apache-2.0" ]
null
null
null
angular2-rxjs-observable-data-services-master/angular2-rxjs-observable-data-services-master/src/server.js
MaxvandenHout/allcode
e965b8f7acd5f69938946a4d7c33c395ff52b81c
[ "Apache-2.0" ]
null
null
null
angular2-rxjs-observable-data-services-master/angular2-rxjs-observable-data-services-master/src/server.js
MaxvandenHout/allcode
e965b8f7acd5f69938946a4d7c33c395ff52b81c
[ "Apache-2.0" ]
null
null
null
var express = require('express'); var bodyParser = require('body-parser'); var _ = require('lodash'); var httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer(); var app = express(); var todos = []; app.use(express.static('.')); app.use(bodyParser.json()); app.use(bodyParser.text()); app.route('/todo') .get((req, res) => { console.log(JSON.stringify(todos)); res.send(todos); }) .put((req, res) => { var json = req.body; var toggled = _.find(todos, (todo) => todo.id == json.id); toggled.completed = !toggled.completed; console.log(JSON.stringify(todos)); res.send(); }) .delete((req,res) => { console.log('removing todo with id = ' + req.query.id); todos = _.remove(todos,(todo) => todo.id != req.query.id ); console.log(JSON.stringify(todos)); res.send(); }) .post((req, res) => { todos.push(req.body); console.log(JSON.stringify(todos)); setTimeout(() => res.send(), 1000); }); app.all('/bundle.js', function (req, res) { proxy.web(req, res, { target: 'http://localhost:8081' }); }); var server = app.listen(8080, function() { console.log("Server running at http://localhost:" + server.address().port); });
27.166667
79
0.572853
36265a04885508303822af2ddd8c6b011572f603
6,115
js
JavaScript
solution/WebResources/dse_/Scripts/NewPattern/newPatternOnLoad.js
Ben-Fishin/Dynamics-365-CE-Client-Side-Scripting-Patterns
14fbddcaa15a29addb843f18558a81c08d9592ff
[ "MIT" ]
null
null
null
solution/WebResources/dse_/Scripts/NewPattern/newPatternOnLoad.js
Ben-Fishin/Dynamics-365-CE-Client-Side-Scripting-Patterns
14fbddcaa15a29addb843f18558a81c08d9592ff
[ "MIT" ]
null
null
null
solution/WebResources/dse_/Scripts/NewPattern/newPatternOnLoad.js
Ben-Fishin/Dynamics-365-CE-Client-Side-Scripting-Patterns
14fbddcaa15a29addb843f18558a81c08d9592ff
[ "MIT" ]
null
null
null
/* * This Sample Code is provided for the purpose of illustration only and is not intended to be used in a production environment. * THIS SAMPLE CODE AND ANY RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. We grant You * a nonexclusive, royalty-free right to use and modify the Sample Code and to reproduce and distribute the object code form of * the Sample Code, provided that You agree: (i) to not use Our name, logo, or trademarks to market Your software product in which * the Sample Code is embedded; (ii) to include a valid copyright notice on Your software product in which the Sample Code is * embedded; and (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and against any claims or lawsuits, * including attorneys? fees, that arise or result from the use or distribution of the Sample Code. * * Please note: None of the conditions outlined in the disclaimer above will supersede the terms and conditions contained within * the Premier Customer Services Description. * * Extended from CRM SDK References: */ var NewPatternForm = window.NewPatternForm || {}; /** * @function NewPatternForm.OnLoad * @description Configured in form properties to trigger on form load */ NewPatternForm.OnLoad = async function (executionContext) { "use strict" var formContext = executionContext.getFormContext(); //get the account lookup control from the formcontext var accountControl = formContext.getControl("dse_accountid"); //makes a non-UCI blocking block call to show "Auditor" Section based on some evaluation of values NewPatternForm.CheckIsAuditor(formContext); //Returns a Promise. determine if the current user is a member of the "Spark" owner team. Caches value in sessionStorage after first retrieval. Cache is used on subsequent calls var checkTeamMemberPromise = NewPatternForm.CheckTeamMember(accountControl); //Returns a Promise. Function checks "checkAccountCreditHold" config value and retrieves the related account "creditonhold". If account on credit hold a notification is displayed on the form var checkCreditHoldPromise = NewPatternForm.CheckCreditHold(formContext); //Resolve both promises in parallel. Then return out of onload return Promise.all([checkTeamMemberPromise, checkCreditHoldPromise]); } /** * @function NewPatternForm.CheckTeamMember * @description checks if user is a member of Spark Team and has Salesperson Role. Disables Related Account Lookup if both are not true */ NewPatternForm.CheckTeamMember = async function (accountControl) { "use strict"; //Makes Async call to determine if the "Spark Team" button feature is enabled. Caches value in sessionStorage after first retrieval. Cache is used on subsequent calls var isUserOnSparkTeam = await Spark30Common.UserIsTeamMember("Spark"); //determine if the current user has the "Salesperson" security role. Uses the roles collection(id, name) provided in the Model driven app scripting var isUserSalesperson = Spark30Common.UserHasRoleName("Salesperson"); //Disables the "Account" lookup field if the current user is not a "Spark" owner team and "Salesperson" security role if (isUserOnSparkTeam && isUserSalesperson) { accountControl.setDisabled(false); } else { accountControl.setDisabled(true); } } /** * @function NewPatternForm.CheckCreditHold * @description checks "checkAccountCreditHold" config value and retrieves the related account "creditonhold". If on credit hold a notification is displayed on the form */ NewPatternForm.CheckCreditHold = async function (formContext) { "use strict"; //get the "Account" lookup attribute value from the formContext var accountValue = formContext.getAttribute("dse_accountid").getValue() if (accountValue !== null) { //Returns Promise - determine if we should retrieve the Related Accounts "Credit Hold" value var checkAccountCreditHoldPromise = Spark30Common.GetConfigurationValue("checkAccountCreditHold"); //Returns Promise - retrieve the Related Account "Credit Hold" value var isAccountCreditHoldPromise = Spark30Common.IsCreditHoldAccount(accountValue[0].id); //Resolve both promises in parallel. const [checkAccountCreditHold, isAccountCreditHold] = await Promise.all([checkAccountCreditHoldPromise, isAccountCreditHoldPromise]); //display a form notification if the Related Accounts is on credit hold if (checkAccountCreditHold === "1") { if(isAccountCreditHold === true) { formContext.ui.setFormNotification("Related Account is on credit hold!", "WARNING", "accountCreditHoldNotification"); } else { formContext.ui.clearFormNotification("accountCreditHoldNotification"); } } } } /** * @function NewPatternForm.CheckIsAuditor * @description checks "checkAccountCreditHold" config value and retrieves the related account "creditonhold". If on credit hold a notification is displayed on the form * * Function method signature is not designated with async so it will not return a promise to block UCI */ NewPatternForm.CheckIsAuditor = function (formContext) { "use strict"; //Returns promise. Retrieve User Table custom column(dse_isauditor) indicating if the user is an Auditor. Caches value in sessionStorage after first retrieval. Cache is used on subsequent calls var isAuditorPromise = Spark30Common.UserIsAuditor(); //Async unhide the Audit section if the Users is an Auditor isAuditorPromise.then((CheckIsUserAuditor) => { var tabObj = formContext.ui.tabs.get("general_tab"); var sectionObj = tabObj.sections.get("audit_section"); if(CheckIsUserAuditor === true) { sectionObj.setVisible(true); } else { sectionObj.setVisible(false); } }); }
52.264957
197
0.741619
36290f783ad2aa41525109dde651396f2e369c0d
1,093
js
JavaScript
src/components/search-bar.js
pvsousalima/gitstats
c8911928d77b6940a5a903a9d07b4757d87c3bcd
[ "MIT" ]
null
null
null
src/components/search-bar.js
pvsousalima/gitstats
c8911928d77b6940a5a903a9d07b4757d87c3bcd
[ "MIT" ]
null
null
null
src/components/search-bar.js
pvsousalima/gitstats
c8911928d77b6940a5a903a9d07b4757d87c3bcd
[ "MIT" ]
null
null
null
import { h, Component } from 'preact'; export default class SearchBar extends Component { onInputChange(query) { this.props.updateState({query}); } onSortChange(order) { this.props.updateState({order}); } renderSearchContainer(order, searchItems) { return searchItems.map(orderid => <div className="search-order"> <input id={orderid} type="radio" name="order" value={orderid} checked={order == orderid} onChange={event => this.onSortChange(event.target.id)} /> <label className={`order-${orderid}`} htmlFor={orderid}></label> </div>); } render({query, order}) { return ( <div className="search-container"> <div className="search-bar-container"> <input className="search-bar" placeholder="Search..." value={query} onChange={event => this.onInputChange(event.target.value)} /> </div> <form className="search-order-container"> {this.renderSearchContainer(order, ['stars', 'forks', 'updated'])} </form> </div> ); } };
28.763158
152
0.602928
36299bc7461dd5c2015f698dc8a935a60f6d5808
1,090
js
JavaScript
src/states/Game.js
jacobscunn07/mmo-game
81a7312745034c9324e83e2c0c366f1020762fc8
[ "MIT" ]
null
null
null
src/states/Game.js
jacobscunn07/mmo-game
81a7312745034c9324e83e2c0c366f1020762fc8
[ "MIT" ]
null
null
null
src/states/Game.js
jacobscunn07/mmo-game
81a7312745034c9324e83e2c0c366f1020762fc8
[ "MIT" ]
null
null
null
/* globals __DEV__ */ import Phaser from 'phaser' import Mushroom from '../sprites/Mushroom' import Player from './../sprites/Player'; export default class extends Phaser.State { init() { } preload() { // this.load.spritesheet('clotharmor', './../../assets/images/clotharmor.png', 32, 32, 5); this.load.atlasJSONHash('miosprite', './../../assets/images/clotharmor.png', 'src/sprites/clotharmor.json'); } create() { this.cursors = game.input.keyboard.createCursorKeys(); this.test = new Player({ game: this.game, x: 200, y: 300 }); this.game.add.existing(this.test); this.test.animations.play('walkdown'); } render() { if (__DEV__) { this.game.debug.spriteInfo(this.test, 32, 32); } } update() { if (this.cursors.left.isDown) { this.test.walkLeft(); } else if (this.cursors.right.isDown) { this.test.walkRight(); } if (this.cursors.up.isDown) { this.test.walkUp(); } else if (this.cursors.down.isDown) { this.test.walkDown(); } } }
20.961538
112
0.591743
362b25e0a3f23a2934370a7993de44247955d27e
3,835
js
JavaScript
doc/themes/nilearn/static/doctools.js
SIMEXP/nilearn
4f51aea58f38689ca32c2edd748528d521e6cfb0
[ "BSD-2-Clause" ]
827
2015-01-30T23:11:42.000Z
2022-03-29T21:21:05.000Z
doc/themes/nilearn/static/doctools.js
SIMEXP/nilearn
4f51aea58f38689ca32c2edd748528d521e6cfb0
[ "BSD-2-Clause" ]
2,845
2015-01-04T22:14:41.000Z
2022-03-31T20:28:09.000Z
doc/themes/nilearn/static/doctools.js
SIMEXP/nilearn
4f51aea58f38689ca32c2edd748528d521e6cfb0
[ "BSD-2-Clause" ]
484
2015-02-03T10:58:19.000Z
2022-03-29T21:57:16.000Z
$u=_.noConflict();jQuery.urldecode=function(x){return decodeURIComponent(x).replace(/\+/g,' ')};jQuery.urlencode=encodeURIComponent;jQuery.getQueryParameters=function(s){if(typeof s=='undefined')s=document.location.search;var parts=s.substr(s.indexOf('?')+1).split('&');var result={};for(var i=0;i<parts.length;i++){var tmp=parts[i].split('=',2);var key=jQuery.urldecode(tmp[0]);var value=jQuery.urldecode(tmp[1]);if(key in result)result[key].push(value);else result[key]=[value]}return result};jQuery.fn.highlightText=function(text,className){function highlight(node){if(node.nodeType==3){var val=node.nodeValue;var pos=val.toLowerCase().indexOf(text);if(pos>=0&&!jQuery(node.parentNode).hasClass(className)){var span=document.createElement("span");span.className=className;span.appendChild(document.createTextNode(val.substr(pos,text.length)));node.parentNode.insertBefore(span,node.parentNode.insertBefore(document.createTextNode(val.substr(pos+text.length)),node.nextSibling));node.nodeValue=val.substr(0,pos)}}else if(!jQuery(node).is("button, select, textarea")){jQuery.each(node.childNodes,function(){highlight(this)})}}return this.each(function(){highlight(this)})};var Documentation={init:function(){this.fixFirefoxAnchorBug();this.highlightSearchWords();this.initIndexTable()},TRANSLATIONS:{},PLURAL_EXPR:function(n){return n==1?0:1},LOCALE:'unknown',gettext:function(string){var translated=Documentation.TRANSLATIONS[string];if(typeof translated=='undefined')return string;return(typeof translated=='string')?translated:translated[0]},ngettext:function(singular,plural,n){var translated=Documentation.TRANSLATIONS[singular];if(typeof translated=='undefined')return(n==1)?singular:plural;return translated[Documentation.PLURALEXPR(n)]},addTranslations:function(catalog){for(var key in catalog.messages)this.TRANSLATIONS[key]=catalog.messages[key];this.PLURAL_EXPR=new Function('n','return +('+catalog.plural_expr+')');this.LOCALE=catalog.locale},addContextElements:function(){$('div[id] > :header:first').each(function(){$('<a class="headerlink">\u00B6</a>').attr('href','#'+this.id).attr('title',_('Permalink to this headline')).appendTo(this)});$('dt[id]').each(function(){$('<a class="headerlink">\u00B6</a>').attr('href','#'+this.id).attr('title',_('Permalink to this definition')).appendTo(this)})},fixFirefoxAnchorBug:function(){if(document.location.hash&&$.browser.mozilla)window.setTimeout(function(){document.location.href+=''},10)},highlightSearchWords:function(){var params=$.getQueryParameters();var terms=(params.highlight)?params.highlight[0].split(/\s+/):[];if(terms.length){var body=$('div.body');window.setTimeout(function(){$.each(terms,function(){body.highlightText(this.toLowerCase(),'highlighted')})},10);$('<p class="highlight-link"><a href="javascript:Documentation.'+'hideSearchWords()">'+_('Hide Search Matches')+'</a></p>').appendTo($('#searchbox'))}},initIndexTable:function(){var togglers=$('img.toggler').click(function(){var src=$(this).attr('src');var idnum=$(this).attr('id').substr(7);$('tr.cg-'+idnum).toggle();if(src.substr(-9)=='minus.png')$(this).attr('src',src.substr(0,src.length-9)+'plus.png');else $(this).attr('src',src.substr(0,src.length-8)+'minus.png')}).css('display','');if(DOCUMENTATION_OPTIONS.COLLAPSE_INDEX){togglers.click()}},hideSearchWords:function(){$('#searchbox .highlight-link').fadeOut(300);$('span.highlighted').removeClass('highlighted')},makeURL:function(relativeURL){return DOCUMENTATION_OPTIONS.URL_ROOT+'/'+relativeURL},getCurrentURL:function(){var path=document.location.pathname;var parts=path.split(/\//);$.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//),function(){if(this=='..')parts.pop()});var url=parts.join('/');return path.substring(url.lastIndexOf('/')+1,path.length-1)}};_=Documentation.gettext;$(document).ready(function(){Documentation.init()});
1,917.5
3,834
0.752021
362be05f0c920ec5854da1ff5be92eded166f86b
695
js
JavaScript
app/WakandaAuthenticator.js
lucasventurasc/wakanda-statistic-receiver
3140cd578d6a0b2bd2e8f6c2191d9001ba95df01
[ "MIT" ]
null
null
null
app/WakandaAuthenticator.js
lucasventurasc/wakanda-statistic-receiver
3140cd578d6a0b2bd2e8f6c2191d9001ba95df01
[ "MIT" ]
null
null
null
app/WakandaAuthenticator.js
lucasventurasc/wakanda-statistic-receiver
3140cd578d6a0b2bd2e8f6c2191d9001ba95df01
[ "MIT" ]
null
null
null
'use strict'; var request = require('request'); class WakandaAuthenticator { authenticate(email, token, onSuccess, onError) { var options = { method: 'GET', url: 'https://wakanda-security.herokuapp.com/verifyToken?email=' + email + "&token=" + token }; request(options, function (error, response, body) { if (error) throw new Error(error); console.log(response.statusCode); if(response.statusCode === 200) { onSuccess.apply(this); } else { onError.call(this, response.statusCode); } }); } } module.exports = WakandaAuthenticator;
23.166667
104
0.552518
362ca214dddf5feabe115578676e7c4071f8ea1d
991
js
JavaScript
src/utils/fileUtils.js
glssn/boogi
b46d1d9b0843a40f09ab9c07e2b0e7a12b5fa0d8
[ "MIT" ]
117
2020-06-16T13:35:38.000Z
2022-02-15T04:27:55.000Z
src/utils/fileUtils.js
glssn/boogi
b46d1d9b0843a40f09ab9c07e2b0e7a12b5fa0d8
[ "MIT" ]
172
2020-06-13T17:43:45.000Z
2022-03-30T04:26:26.000Z
src/utils/fileUtils.js
glssn/boogi
b46d1d9b0843a40f09ab9c07e2b0e7a12b5fa0d8
[ "MIT" ]
47
2020-09-19T11:34:20.000Z
2022-02-14T01:02:11.000Z
const { readFileSync, close, open, utimes } = require('fs'); const yaml = require('js-yaml'); const path = require('path'); const touch = (path) => { return new Promise((resolve, reject) => { const time = new Date(); utimes(path, time, time, (err) => { if (err) { return open(path, 'w', (err, fd) => { if (err) return reject(err); close(fd, (err) => (err ? reject(err) : resolve(fd))); }); } resolve(); }); }); }; const readYamlOrJson = (path) => { try { if (path.endsWith('.yml') || path.endsWith('.yaml')) { const fileContents = readFileSync(path, 'utf8'); return yaml.safeLoad(fileContents); } else if (path.endsWith('.json')) { return require(path); } throw 'Config file must be either YAML or JSON'; } catch (err) { console.error(err); return {}; } }; const rootDir = () => path.dirname(require.main.filename); module.exports = { touch, readYamlOrJson, rootDir };
26.078947
64
0.563068
362ea3e8b815f12f793f203603c002899c502f60
144
js
JavaScript
src/element/id.js
symbo-ls/domql
9502f338e6bcd715cc3765bb8b43eb3a779b4906
[ "MIT" ]
10
2020-01-27T17:53:26.000Z
2022-01-19T15:48:05.000Z
src/element/id.js
symbo-ls/domql
9502f338e6bcd715cc3765bb8b43eb3a779b4906
[ "MIT" ]
41
2020-12-16T06:18:41.000Z
2022-02-14T07:06:04.000Z
src/element/id.js
symbo-ls/domql
9502f338e6bcd715cc3765bb8b43eb3a779b4906
[ "MIT" ]
3
2019-08-06T11:51:47.000Z
2021-11-30T05:19:29.000Z
'use strict' const createID = function * () { let index = 1 while (index < index + 1) { yield index++ } } export default createID()
13.090909
32
0.597222
362ec3f882ca1b6edce120b677a029d3a6acdd22
3,969
js
JavaScript
src/NetStackBeautifier.WebAPI/wwwroot/app.js
xiaomi7732/StackBeauty
7f59b19695c9efa3f96947fbdffe8a2bed13bd31
[ "MIT" ]
5
2022-03-04T01:02:22.000Z
2022-03-08T23:03:53.000Z
src/NetStackBeautifier.WebAPI/wwwroot/app.js
xiaomi7732/StackBeauty
7f59b19695c9efa3f96947fbdffe8a2bed13bd31
[ "MIT" ]
28
2022-03-04T05:03:47.000Z
2022-03-18T04:22:28.000Z
src/NetStackBeautifier.WebAPI/wwwroot/app.js
xiaomi7732/StackBeauty
7f59b19695c9efa3f96947fbdffe8a2bed13bd31
[ "MIT" ]
1
2022-03-04T19:03:22.000Z
2022-03-04T19:03:22.000Z
const backend = "" const parserPath = "/Beautified"; const divRenderPath = "/HtmlContent"; const btnBeautify = document.getElementById('btnBeautify'); const btnClearInput = document.getElementById('btnClearInput'); const resultDiv = document.getElementById('result'); const simpleCheckBox = document.getElementById('cbxRenderMode'); const cbxAutoSubmitExample = document.getElementById('cbxAutoSubmitExample'); const darkThemeButton = document.getElementById('themeDark'); const lightThemeButton = document.getElementById('themeLight'); const styleDiv = document.getElementById('themeStyleSheet'); const callstackInputTextArea = document.getElementById('callstackinput'); const btnExample1 = document.getElementById('btnExampleInput1'); const btnExample2 = document.getElementById('btnExampleInput2'); const btnExample3 = document.getElementById('btnExampleInput3'); const btnExample4 = document.getElementById('btnExampleInput4'); const btnExample5 = document.getElementById('btnExampleInput5'); const btnExamples = [btnExample1, btnExample2, btnExample3, btnExample4, btnExample5]; const onThemeChanged = (ev) => { const themeFileName = ev.target.value + ".css"; styleDiv.href = themeFileName; } btnBeautify.addEventListener("click", beautifyButtonClicked); btnClearInput.addEventListener('click', () => { callstackInputTextArea.value = ""; btnClearInput.disabled = true; btnBeautify.disabled = true; }); darkThemeButton.addEventListener("click", onThemeChanged); lightThemeButton.addEventListener("click", onThemeChanged); callstackInputTextArea.addEventListener('input', async (ev) => { btnClearInput.disabled = (ev.target.value === ""); btnBeautify.disabled = (ev.target.value === ""); if (cbxAutoSubmitExample.checked) { await beautifyButtonClicked(); } }); const exampleButtonCount = btnExamples.length; for (let i = 0; i < exampleButtonCount; i++) { btnExamples[i].addEventListener('click', () => inputExample(`example${i + 1}.txt`)); } async function inputExample(fileName) { const response = await fetch(fileName); callstackInputTextArea.value = await response.text(); btnClearInput.disabled = false; btnBeautify.disabled = false; if (cbxAutoSubmitExample.checked) { await beautifyButtonClicked(); } } async function beautifyButtonClicked() { const waitingSign = '...'; const callstackInput = callstackInputTextArea.value; resultDiv.innerHTML = waitingSign; const timeoutHandle = setTimeout((condition, ctrl) => { if (ctrl.innerHTML === condition) { const coldPrompt = 'The backend feels cold. Give me a few seconds to warm it up....'; ctrl.innerHTML = coldPrompt; } }, 1000, waitingSign, resultDiv); try { const jsonResult = await getBeautifiedAsync(callstackInput); if (!jsonResult || jsonResult.length === 0) { throw { title: "No content returned", }; } const divContent = await getDivContent(jsonResult); resultDiv.innerHTML = divContent; } catch (ex) { console.error(ex); resultDiv.innerHTML = `An error happened. Details: ${ex.title}`; } finally { clearTimeout(timeoutHandle); } } async function getBeautifiedAsync(data) { const response = await fetch(backend + parserPath, { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: data, }); if (response.ok) { return response.json(); } throw await response.json(); } async function getDivContent(data) { const response = await fetch(backend + divRenderPath + '?' + new URLSearchParams({ "RenderMode": simpleCheckBox.checked ? "Simple" : "Full", }), { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }); return response.text(); }
33.923077
97
0.682036
362fc9c62dadbea7fc753fb1faa1ae58f66835d0
465
js
JavaScript
__tests__/lib/pynths.js
perifinance/peri-finance-js
31e45637fcac6074ce9917bb63add632a0ed3e11
[ "MIT" ]
null
null
null
__tests__/lib/pynths.js
perifinance/peri-finance-js
31e45637fcac6074ce9917bb63add632a0ed3e11
[ "MIT" ]
null
null
null
__tests__/lib/pynths.js
perifinance/peri-finance-js
31e45637fcac6074ce9917bb63add632a0ed3e11
[ "MIT" ]
null
null
null
import ContractSettings from '../../src/contractSettings'; import pynths from '../../lib/pynths'; import * as peri from '@perifinance/peri-finance'; const { SUPPORTED_NETWORKS } = ContractSettings; describe('lib/pynths', () => { Object.entries(SUPPORTED_NETWORKS).forEach(([networkId, network]) => { test(`${network} has same pynths and those in PERI package`, () => { expect(pynths[networkId]).toEqual(peri.getPynths({ network })); }); }); });
33.214286
72
0.668817
362fe9efc2893ad1c5d53f5924883862a3bd9b33
355
js
JavaScript
src/Config/Images.js
yahongie2014/MainEXPO
99e503d2d0a0e303508b27d155b3c0a0ab3b061a
[ "MIT" ]
1
2022-02-19T22:23:52.000Z
2022-02-19T22:23:52.000Z
src/Config/Images.js
yahongie2014/MainEXPO
99e503d2d0a0e303508b27d155b3c0a0ab3b061a
[ "MIT" ]
null
null
null
src/Config/Images.js
yahongie2014/MainEXPO
99e503d2d0a0e303508b27d155b3c0a0ab3b061a
[ "MIT" ]
null
null
null
/** @format */ export default { imageHolder: require("../../assets/images/holder.png"), logo: require("../../assets/images/logo.png"), logoSpin: require("../../assets/images/logoSpin.png"), icons: { homeListing: "https://constellationhb.com/images/default-source/default-album/newhome_logo543189417cb3682fb0a7ff0000918585.png", }, };
29.583333
121
0.684507
36300eeb1ee57889bd8afeba971f9dc68427a39b
5,300
js
JavaScript
src/swuquery/swuquery-regex.js
sutton-signwriting/core
8e2c5bd073f6bdee0f0294153399c3bfcbce9e0e
[ "MIT" ]
1
2021-04-10T16:13:27.000Z
2021-04-10T16:13:27.000Z
src/swuquery/swuquery-regex.js
sutton-signwriting/core
8e2c5bd073f6bdee0f0294153399c3bfcbce9e0e
[ "MIT" ]
null
null
null
src/swuquery/swuquery-regex.js
sutton-signwriting/core
8e2c5bd073f6bdee0f0294153399c3bfcbce9e0e
[ "MIT" ]
null
null
null
import { re } from './swuquery-re'; import { re as reSWU } from '../swu/swu-re'; import { re as reStyle } from '../style/style-re'; import { range } from './swuquery-range'; import { symbolRanges } from './swuquery-symbol-ranges'; import { swu2coord, num2swu, swu2key, key2swu } from '../convert'; const regexRange = (symRange) => { from = swu2key(symRange.slice(1, 3)); to = swu2key(symRange.slice(-2)); from = key2swu(from.slice(0, 4) + '00'); to = key2swu(to.slice(0, 4) + '5f'); return range(from, to); } //needs rewritten, but it works /** * Function to transform an SWU query string to one or more regular expressions * @function swuquery.regex * @param {string} query - an SWU query string * @returns {string[]} an array of one or more regular expressions * @example * swuquery.regex('QA񀀒T') * * return [ * '(\uD836\uDC00\uD8C0\uDC12((?:(?:\uD8C0[\uDC01-\uDFFF])|(?:[\uD8C1-\uD8FC][\uDC00-\uDFFF])|(?:\uD8FD[\uDC00-\uDC80])))*)\uD836[\uDC01-\uDC04](?:\uD836[\uDC0C-\uDDFF]){2}((?:(?:\uD8C0[\uDC01-\uDFFF])|(?:[\uD8C1-\uD8FC][\uDC00-\uDFFF])|(?:\uD8FD[\uDC00-\uDC80]))(?:\uD836[\uDC0C-\uDDFF]){2})*' * ] */ const regex = (query) => { query = query.match(new RegExp(`^${re.full}`))[0]; if (!query) { return ''; } let matches; let matchesOr; let matched; let orList; let i; let j; let swu_pattern; let part; let from; let to; let coord; let re_range; let segment; let x; let y; let base; let fill; let rotate; let fuzz = 20; let re_sym = reSWU.symbol; let re_coord = reSWU.coord; let re_signbox = reSWU.box; let re_seq = reSWU.sort; let re_word = re_signbox + re_coord + '(' + re_sym + re_coord + ')*'; let re_sortable = '(' + re_seq + '(' + re_sym + ')+)'; let q_range = 'R' + re_sym + re_sym; let q_sym = re_sym + 'f?r?'; let q_coord = '(' + re_coord + ')?'; let q_var = '(V[0-9]+)'; let q_style = '(' + reStyle.full + ')?'; let q_sortable; if (query == 'Q') { return [reSWU.sign]; } if (query == 'Q-') { return [reSWU.sign + "(" + reStyle.full + ")?"]; } if (query == 'QT') { return [reSWU.sortable]; } if (query == 'QT-') { return [reSWU.sortable + "(" + reStyle.full + ")?"]; } let segments = []; let sym, key; let sortable = query.indexOf('T') + 1; if (sortable) { q_sortable = '(' + reSWU.sort; let qat = query.slice(0, sortable); query = query.replace(qat, ''); if (qat == 'QT') { q_sortable += '(' + re_sym + ')+)'; } else { matches = qat.match(new RegExp('(' + re.list + ')', 'g')); if (matches) { for (i = 0; i < matches.length; i += 1) { orList = []; matchesOr = matches[i].match(new RegExp('(' + re.symbol + '|' + re.range + ')', 'g')); if (matchesOr) { for (j = 0; j < matchesOr.length; j += 1) { matched = matchesOr[j].match(new RegExp(re.symbol)); if (matched) { orList.push(symbolRanges(matched[0])); } else { orList.push(regexRange(matchesOr[j])); } } if (orList.length==1){ q_sortable += orList[0]; } else { q_sortable += '(' + orList.join('|') + ')'; } } } q_sortable += '(' + reSWU.symbol + ')*)'; } } } //get the variance matches = query.match(new RegExp(q_var, 'g')); if (matches) { fuzz = matches.toString().slice(1) * 1; } //this gets all symbols and ranges with or without location matches = query.match(new RegExp(re.list + re.coord, 'g')); if (matches) { for (i = 0; i < matches.length; i += 1) { orList = []; matchesOr = matches[i].match(new RegExp('(' + re.symbol + '|' + re.range + ')', 'g')); if (matchesOr) { for (j = 0; j < matchesOr.length; j += 1) { matched = matchesOr[j].match(new RegExp(re.symbol)); if (matched) { orList.push(symbolRanges(matched[0])); } else { orList.push(regexRange(matchesOr[j])); } } if (orList.length==1){ segment = orList[0]; } else { segment = '(' + orList.join('|') + ')'; } } coord = matches[i].match(new RegExp(`${reSWU.coord}`)); if (coord) { coord = swu2coord(coord[0]); x = coord[0]; y = coord[1]; segment += range(num2swu(x - fuzz), num2swu(x + fuzz)); segment += range(num2swu(y - fuzz), num2swu(y + fuzz)); } else { segment += reSWU.coord; } // add to general swu word segment = re_word + segment + '(' + re_sym + re_coord + ')*'; if (sortable) { segment = q_sortable + segment; } else { segment = re_sortable + "?" + segment; } if (query.indexOf('-') > 0) { segment += q_style; } segments.push(segment); } } if (!segments.length) { if (query.indexOf('-') > 0) { segment += q_style; } segments.push(q_sortable + re_word); } return segments; } export { regex }
29.281768
297
0.503396
3630d7a46ae4048964a2edfcee5368dc3c7ee8ce
1,832
js
JavaScript
src/templates/all-workshops-page.js
yulanhenlp/emnlp2020-website
8a82b1103ee58467bfd4c50f4e5a9e257202e6e5
[ "MIT" ]
null
null
null
src/templates/all-workshops-page.js
yulanhenlp/emnlp2020-website
8a82b1103ee58467bfd4c50f4e5a9e257202e6e5
[ "MIT" ]
null
null
null
src/templates/all-workshops-page.js
yulanhenlp/emnlp2020-website
8a82b1103ee58467bfd4c50f4e5a9e257202e6e5
[ "MIT" ]
null
null
null
import React from "react"; import PropTypes from "prop-types"; import { graphql } from "gatsby"; import Layout from "../components/Layout"; import HTMLContent from "../components/Content"; import PageHelmet from "../components/PageHelmet"; import StandardPageTemplate from "../components/StandardPageTemplate"; import "../styles/all-events-page.scss"; const WorkshopListing = ({ title, summary, authors, url }) => ( <article className="event-listing"> <h3><a href={url}>{title}</a></h3> <div className="event-organizers">{authors}</div> <p className="event-summary">{summary}</p> </article> ); const AllWorkshops = ({ workshops }) => ( <section className="all-events"> {workshops.map(w => <WorkshopListing {...w} key={w.workshopNumber} />)} </section> ); const AllWorkshopsPage = ({ data }) => { const { markdownRemark: page, footerData, navbarData, site, allWorkshopsCsv } = data; const { workshops } = allWorkshopsCsv return ( <Layout footerData={footerData} navbarData={navbarData} site={site}> <PageHelmet page={page} /> <StandardPageTemplate page={{ ...page }}> <HTMLContent className="default-content" content={page.html} /> <AllWorkshops workshops={workshops}/> </StandardPageTemplate> </Layout> ); }; AllWorkshopsPage.propTypes = { data: PropTypes.object.isRequired, }; export default AllWorkshopsPage; export const allWorkshopsPageQuery = graphql` query WorkshopsPage($id: String!) { markdownRemark(id: { eq: $id }) { html frontmatter { title seo { browserTitle title description } } } allWorkshopsCsv { workshops: nodes { authors workshopNumber url title summary } } ...LayoutFragment } `;
25.802817
87
0.636463
3631d7053670e3693cab2d8a25f289510afe4386
1,389
js
JavaScript
src/model/users.js
FelStroz/linkAPI
b18c3f2ed9391d384c8eeaaed4aff1aba31ed25e
[ "MIT" ]
null
null
null
src/model/users.js
FelStroz/linkAPI
b18c3f2ed9391d384c8eeaaed4aff1aba31ed25e
[ "MIT" ]
null
null
null
src/model/users.js
FelStroz/linkAPI
b18c3f2ed9391d384c8eeaaed4aff1aba31ed25e
[ "MIT" ]
null
null
null
const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const UserSchema = new mongoose.Schema({ name: { type: String, required: true, minlength: 2, maxlength: 80, lowercase: true, }, password: { type: String, required: true, minlength: 6, maxlength: 20, }, creationDate: { type: Date, default: Date.now } }); UserSchema.index({ email: 1 }, { unique: true }); UserSchema.pre('save', function (next) { let user = this; bcrypt.hash(user.password, 12, function (e, hash) { if (e) return next(e); user.password = hash; next(); }); }); UserSchema.pre('findOneAndUpdate', function (next) { let user = this._update; if (user.name && user.name === "") return next(new Error('The name must not be empty')); if (user.email && user.email === "") return next(new Error('The email must not be empty')); if (user.password) { if (user.password.length < 6) return next(new Error('The password must be at least 6 characters')); bcrypt.hash(user.password, 12, function (e, hash) { if (e) return next(e); user.password = hash; next(); }); } else next(user); }); module.exports = mongoose.model('Users', UserSchema);
24.803571
107
0.546436
36329a87ffb42a2458b1cab7fac289383025c333
1,828
js
JavaScript
server/src/services/health/health.js
jasonmcaffee/drummachine
5472c6a63464791c20ea3a7e4a70a60dae0d2698
[ "MIT" ]
null
null
null
server/src/services/health/health.js
jasonmcaffee/drummachine
5472c6a63464791c20ea3a7e4a70a60dae0d2698
[ "MIT" ]
null
null
null
server/src/services/health/health.js
jasonmcaffee/drummachine
5472c6a63464791c20ea3a7e4a70a60dae0d2698
[ "MIT" ]
null
null
null
import {config} from 'config/config'; import * as os from 'os'; /** * Service responsible for gathering server and subsystem health/status. * e.g. ensuring we can connect to couchbase and various other dbs. * @type {{health, couchbaseStatus, serverStatus, osStatus}} */ export let service = { /** * Returns summary of system health, including db connectivity, os info, etc. * @returns {Promise.<{systemOverallStatus: *, serverStatus: *, osStatus: *}>} */ getHealth: async function () { let serverStatus = this.serverStatus; let osStatus = this.osStatus; let subsystemStatuses = [ serverStatus, osStatus ]; // iterate over each status and if one is not ok, the overall status will not be ok. let systemOverallStatus = subsystemStatuses.reduce((previous, current)=>{ return { ok: previous.ok && current.ok }; }); let status = { systemOverallStatus, serverStatus, osStatus }; return status; }, /** * returns server status along with config * @returns {{ok, config: *}} */ get serverStatus () { return { get ok () { return true; }, config: config }; }, /** * returns os info available to node's os module. * @returns {{ok: boolean, hostname: *, type, platform: *, arch: *, release: *, uptime: *, loadavg: *, totalmem: *, freemem: *, cpus: *, networkInterfaces: *}} */ get osStatus () { return { ok: true, hostname: os.hostname(), type: os.type(), platform: os.platform(), arch: os.arch(), release: os.release(), uptime: os.uptime(), loadavg: os.loadavg(), totalmem: os.totalmem(), freemem: os.freemem(), cpus: os.cpus(), networkInterfaces: os.networkInterfaces() }; } };
24.702703
161
0.59628
3635acb86b5de629330f40b41e6c8357e158829a
239
js
JavaScript
js/solid/cis-speech.js
reesretuta/dropshipping-icons
c4b4f40959b1e44abaacd86981b9a896b121f419
[ "CC-BY-4.0", "MIT" ]
null
null
null
js/solid/cis-speech.js
reesretuta/dropshipping-icons
c4b4f40959b1e44abaacd86981b9a896b121f419
[ "CC-BY-4.0", "MIT" ]
null
null
null
js/solid/cis-speech.js
reesretuta/dropshipping-icons
c4b4f40959b1e44abaacd86981b9a896b121f419
[ "CC-BY-4.0", "MIT" ]
null
null
null
export const cisSpeech = ["512 512"," <path fill='currentColor' d='M464,48H48A16,16,0,0,0,32,64V352a16,16,0,0,0,16,16h80V480h8L248,368H464a16,16,0,0,0,16-16V64A16,16,0,0,0,464,48ZM184,272H144V232h40Zm96,0H240V232h40Zm96,0H336V232h40Z'/>"]
239
239
0.769874
3635dfd18a0283fb1b0ecf27e3e96a3da99185af
904
js
JavaScript
honours_dissertation/project_code/study_planner/controllers/assets/button/component.js
m-f-1998/university
12ddd56227c09018c2998960be32330f292adef8
[ "Apache-2.0" ]
null
null
null
honours_dissertation/project_code/study_planner/controllers/assets/button/component.js
m-f-1998/university
12ddd56227c09018c2998960be32330f292adef8
[ "Apache-2.0" ]
null
null
null
honours_dissertation/project_code/study_planner/controllers/assets/button/component.js
m-f-1998/university
12ddd56227c09018c2998960be32330f292adef8
[ "Apache-2.0" ]
null
null
null
import React from "react"; import { Text, TouchableOpacity } from "react-native"; import Styles from "./styles.js"; /* ========================================== Title: Custom Button Description: Custom Button For Major And Minor Purposes ( Distinguishable By this.props ) ========================================== */ class Button extends React.Component { render () { const containerStyle = [ this.props.main ? { backgroundColor: "#6b41de" } : { backgroundColor: "white" }, Styles.container, this.props.disabled ? { opacity: 0.3 } : { opacity: 1 } ]; return ( <TouchableOpacity style={ containerStyle } onPress={ this.props.onPress } disabled={ this.props.disabled }> <Text style={ [ this.props.main ? Styles.textColor : { color: "black" }, Styles.text ] }>{ this.props.label }</Text> </TouchableOpacity> ); }; } export default Button;
32.285714
124
0.590708
363612088d98ce756b5dca30c9159c430d05fdee
803
js
JavaScript
_RegEx.spec.js
trujs/trujs
05d966195fb8f419386fff9242ffb6641656ba3a
[ "MIT" ]
1
2018-09-19T23:51:44.000Z
2018-09-19T23:51:44.000Z
_RegEx.spec.js
trujs/trujs
05d966195fb8f419386fff9242ffb6641656ba3a
[ "MIT" ]
3
2017-12-28T17:18:32.000Z
2017-12-29T01:56:21.000Z
_RegEx.spec.js
trujs/trujs
05d966195fb8f419386fff9242ffb6641656ba3a
[ "MIT" ]
2
2020-04-19T14:35:05.000Z
2020-04-21T02:16:01.000Z
/**[@test({ "title": "TruJS.RegEx: unit test" })]*/ function testRegEx1(arrange, act, assert, module) { var getMatches, patt, test, res; arrange(function () { getMatches = module(["TruJS._RegEx", []]).getMatches; patt = /<([^\/\s>]+)([^\/>]+)?[\/]?>/g; test = '<input data-point value ="{:input:}" class="input:1234px;"/><div></div><span class=\'test\'></span>'; }); act(function () { res = getMatches(patt, test); }); assert(function (test) { test('There should be 3 matches').value(res).hasMemberCountOf(3); test('The first match, 1st group should be').value(res, '[0][1]').equals('input'); test('The first match, 2nd group should be').value(res, '[0][2]').equals(' data-point value ="{:input:}" class="input:1234px;"'); }); }
36.5
135
0.56538
3636ce8412887833af1225f4b8d1b85e298012ea
675
js
JavaScript
src/testdata.js
danielchengml/d3-tree-node-native
a85ca75ee053f03f63df6770679b89c315c322de
[ "MIT" ]
null
null
null
src/testdata.js
danielchengml/d3-tree-node-native
a85ca75ee053f03f63df6770679b89c315c322de
[ "MIT" ]
null
null
null
src/testdata.js
danielchengml/d3-tree-node-native
a85ca75ee053f03f63df6770679b89c315c322de
[ "MIT" ]
null
null
null
const testdata = [ { name: "ProjectA", parent: "" }, { name: "ApplicationA", parent: "ProjectA" }, { name: "EnvironmentB", parent: "ProjectA" }, { name: "TierC", parent: "ApplicationA" }, { name: "TierD", parent: "ApplicationA" }, { name: "TierE", parent: "ApplicationA" }, { name: "ServiceF", parent: "EnvironmentB" }, { name: "ContainerG", parent: "EnvironmentB" }, { name: "ContainerH", parent: "TierE" }, { name: "ContainerH", parent: "TierE" }, { name: "ContainerH", parent: "TierE" }, { name: "ContainerH", parent: "TierE" }, { name: "ContainerH", parent: "TierE" }, { name: "ContainerH", parent: "TierE" } ]; module.exports = testdata;
30.681818
49
0.6
36384b86da82b3ffb5268a6b6ab9f16f6a958e37
8,495
js
JavaScript
src/components/JobFormLatest.js
rudravaram85/task1redux
6ab5be3ee3dfe0cac996f1b25debebd669682cd7
[ "MIT" ]
null
null
null
src/components/JobFormLatest.js
rudravaram85/task1redux
6ab5be3ee3dfe0cac996f1b25debebd669682cd7
[ "MIT" ]
null
null
null
src/components/JobFormLatest.js
rudravaram85/task1redux
6ab5be3ee3dfe0cac996f1b25debebd669682cd7
[ "MIT" ]
null
null
null
import React from 'react'; import { useHistory } from 'react-router-dom'; export default function JobForm( props) { const history = useHistory() //const {client,id,name,openings,created_on,candidates,interviews,status } =props.job; const handleRedirect = () => { history.push('/candidate'); }; return ( <div className="container py-4"> <ol className="breadcrumb mb-4"> <li className="breadcrumb-item"><a href="index.html">Dashboard</a></li> <li className="breadcrumb-item"><a href="HRMS_JobList.html">Jobs</a></li> <li className="breadcrumb-item active">Job Dashboard</li> </ol> <h4 className="font-weight-normal mb-3">Job Dashboard</h4> <div className="row"> <div className="col-md-9"> {/* Horizontal Steppers */} <div> <ul className="stepper stepper-horizontal"> <li className="completed"> <div className="step"> <span className="circle">1</span> <span className="label">New</span> </div> </li> <li className="active"> <div className="step"> <span className="circle">2</span> <span className="label">Active</span> </div> </li> <li> <div className="step"> <span className="circle">3</span> <span className="label">Closed</span> </div> </li> </ul> </div> {/* /.Horizontal Steppers */} </div> </div> <div className="row"> <div className="col-md-9"> <div className="card shadow-sm"> <div className="card-body"> <div className="d-flex justify-content-between align-items-center mb-4"> <h5 className="font-weight-normal mb-0">Job 1</h5> <div className="font-weight-normal mb-0 text-danger"> <svg width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-clock-history fa-lg mr-1" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" d="M8.515 1.019A7 7 0 0 0 8 1V0a8 8 0 0 1 .589.022l-.074.997zm2.004.45a7.003 7.003 0 0 0-.985-.299l.219-.976c.383.086.76.2 1.126.342l-.36.933zm1.37.71a7.01 7.01 0 0 0-.439-.27l.493-.87a8.025 8.025 0 0 1 .979.654l-.615.789a6.996 6.996 0 0 0-.418-.302zm1.834 1.79a6.99 6.99 0 0 0-.653-.796l.724-.69c.27.285.52.59.747.91l-.818.576zm.744 1.352a7.08 7.08 0 0 0-.214-.468l.893-.45a7.976 7.976 0 0 1 .45 1.088l-.95.313a7.023 7.023 0 0 0-.179-.483zm.53 2.507a6.991 6.991 0 0 0-.1-1.025l.985-.17c.067.386.106.778.116 1.17l-1 .025zm-.131 1.538c.033-.17.06-.339.081-.51l.993.123a7.957 7.957 0 0 1-.23 1.155l-.964-.267c.046-.165.086-.332.12-.501zm-.952 2.379c.184-.29.346-.594.486-.908l.914.405c-.16.36-.345.706-.555 1.038l-.845-.535zm-.964 1.205c.122-.122.239-.248.35-.378l.758.653a8.073 8.073 0 0 1-.401.432l-.707-.707z" /> <path fillRule="evenodd" d="M8 1a7 7 0 1 0 4.95 11.95l.707.707A8.001 8.001 0 1 1 8 0v1z" /> <path fillRule="evenodd" d="M7.5 3a.5.5 0 0 1 .5.5v5.21l3.248 1.856a.5.5 0 0 1-.496.868l-3.5-2A.5.5 0 0 1 7 9V3.5a.5.5 0 0 1 .5-.5z" /> </svg> 20 hrs Remaining </div> <div className="dropdown"> <button className="btn btn-flat dropdown-toggle dropdown-caret-hide py-0 px-1" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <svg width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-three-dots" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z" /> </svg> </button> <div className="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton"> <a className="dropdown-item" href="#">More Profiles</a> </div> </div> </div> <form> <div className="form-group row"> <label htmlFor className="col-sm-4 col-lg-2 col-form-label">Label</label> <div className="col-sm-8 col-lg-4"> <input type="text" readOnly className="form-control-plaintext" id defaultValue="Description" /> </div> <label htmlFor className="col-sm-4 col-lg-2 col-form-label">Label</label> <div className="col-sm-8 col-lg-4"> <input type="text" readOnly className="form-control-plaintext" id defaultValue="Description" /> </div> </div> <div className="form-group row"> <label htmlFor className="col-sm-4 col-lg-2 col-form-label">Label</label> <div className="col-sm-8 col-lg-4"> <input type="text" readOnly className="form-control-plaintext" id defaultValue="Description" /> </div> <label htmlFor className="col-sm-4 col-lg-2 col-form-label">Label</label> <div className="col-sm-8 col-lg-4"> <input type="text" readOnly className="form-control-plaintext" id defaultValue="Description" /> </div> </div> </form> </div> </div> </div> <div className="col-md-3"> <div className="card shadow-sm mt-3 mt-md-0"> <div className="card-body"> <h6 className="font-weight-normal mb-4">Work Flow</h6> <ul className="list-group list-group-flush small"> <li className="list-group-item px-0">Work Flow 1</li> <li className="list-group-item px-0">Work Flow 2</li> <li className="list-group-item px-0">Work Flow 3</li> </ul> </div> </div> </div> </div> <div className="row mt-3"> <div className="col-md-9"> <div className="card shadow-sm"> <div className="card-body"> <div className="d-flex justify-content-between align-items-center mb-4"> <h5 className="font-weight-normal mb-0">Pipeline/Candidates</h5> <div className="dropdown"> <button className="btn btn-flat dropdown-toggle dropdown-caret-hide py-0 px-1" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <svg width="1em" height="1em" viewBox="0 0 16 16" className="bi bi-three-dots" fill="currentColor" xmlns="http://www.w3.org/2000/svg"> <path fillRule="evenodd" d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z" /> </svg> </button> <div className="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton"> <a className="dropdown-item" href="#">More Profiles</a> </div> </div> </div> <div className="d-flex mt-3"> <button type="button" className="btn btn-outline-info" style={{minWidth: '9rem'}} onclick="window.location.href='HRMS_JobCandidates.html'"> <h6 className="mt-3">Pipeline</h6> <hr /> <h5 className>10</h5> </button> <button onClick={handleRedirect} type="button" className="btn btn-outline-success ml-3" style={{minWidth: '9rem'}} onclick="window.location.href='HRMS_JobCandidates.html'"> <h6 className="mt-3">Candidates</h6> <hr /> <h5 className>25</h5> </button> </div> </div> </div> </div> <div className="col-md-3"> <div className="card shadow-sm mt-3 mt-md-0"> <div className="card-body"> <h6 className="font-weight-normal mb-4">Job Activities</h6> <ul className="list-group list-group-flush small"> <li className="list-group-item px-0">Activity 1</li> <li className="list-group-item px-0">Activity 2</li> <li className="list-group-item px-0">Activity 3</li> </ul> </div> </div> </div> </div> </div> ); }
53.09375
856
0.547028