max_stars_repo_path
stringlengths
3
961
max_stars_repo_name
stringlengths
5
122
max_stars_count
int64
0
224k
id
stringlengths
1
8
content
stringlengths
2
1.07M
score
float64
-0.95
3.88
int_score
int64
0
4
client/src/pages/Login.js
al-moreno/MERN-eCommerce
0
3223
import React, { useState } from 'react'; import axios from "axios"; import './Signup.css'; function Login(props) { const [email, setEmail] = useState("") const [password, setPassword] = useState("") const signupFormHandler = (event) => { event.preventDefault(); if (email && password) { axios.post('/api/users/login', { email, password }) .then((response) => { const userData = response && response.data ? response.data : ''; //save the token and the user localStorage.setItem("user", JSON.stringify(userData)); props.history.push("/"); window.location.reload(); }).catch((err) => { alert(err.response.data); }) } }; return ( <main> <div className="col-1"> <form onSubmit={(e) => signupFormHandler(e)} className="card-body card"> <div> <h3> Login </h3> </div> <div className="row "> <label for="text" type="input" className="form-label">Email</label> <input type="email" onChange={(e) => setEmail(e.target.value)} className="form-control" id="email-login" /> </div> <div class="row "> <label for="exampleInputPassword1" className="form-label">Password</label> <input type="password" onChange={(e) => setPassword(e.target.value)} className="form-control" id="password-login" /> </div> <div class="row "> <label>Welcome Back</label > <input type="submit" value="Login" className=" " /> </div> </form> </div> </main> ); } export default Login;
1.679688
2
js/model/meta.js
jfseb/fdevsta_monmove
0
3231
/** * Functionality managing the match models * * @file */ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //import * as intf from 'constants'; var debug = require("debug"); var debuglog = debug('meta'); /** * the model path, may be controlled via environment variable */ var modelPath = process.env["ABOT_MODELPATH"] || "testmodel"; var separator = " -:- "; var validTypes = ["relation", "category", "domain"]; var AMeta = (function () { function AMeta(type, name) { if (validTypes.indexOf(type) < 0) { throw new Error("Illegal Type " + type); } this.name = name; this.type = type; } AMeta.prototype.toName = function () { return this.name; }; AMeta.prototype.toFullString = function () { return this.type + separator + this.name; }; AMeta.prototype.toType = function () { return this.type; }; return AMeta; }()); exports.AMeta = AMeta; function getStringArray(arr) { return arr.map(function (oMeta) { return oMeta.toName(); }); } exports.getStringArray = getStringArray; exports.RELATION_hasCategory = "hasCategory"; exports.RELATION_isCategoryOf = "isCategoryOf"; function parseAMeta(a) { var r = a.split(separator); if (!r || r.length !== 2) { throw new Error("cannot parse " + a + " as Meta"); } switch (r[0]) { case "category": return getMetaFactory().Category(r[1]); case "relation": return getMetaFactory().Relation(r[1]); case "domain": return getMetaFactory().Domain(r[1]); default: throw new Error("unknown meta type" + r[0]); } } function getMetaFactory() { return { Domain: function (a) { return new AMeta("domain", a); }, Category: function (a) { return new AMeta("category", a); }, Relation: function (a) { return new AMeta("relation", a); }, parseIMeta: parseAMeta }; } exports.getMetaFactory = getMetaFactory; //# sourceMappingURL=meta.js.map
1.648438
2
src/utils/status/host/index.js
pcbailey/web-ui-components
6
3239
export * from './constants'; export * from './hostStatus';
-0.230469
0
shared/settings/nav/settings-item.js
darwin/client
0
3247
// @flow import React from 'react' import type {SettingsItemProps} from './index' import {Badge, ClickableBox, Text, Icon} from '../../common-adapters' import * as Style from '../../styles' export default function SettingsItem(props: SettingsItemProps) { return ( <ClickableBox onClick={props.onClick} style={Style.collapseStyles([ styles.item, props.selected ? { borderLeftColor: Style.globalColors.blue, borderLeftStyle: 'solid', borderLeftWidth: 3, } : {}, ])} > {props.icon && ( <Icon type={props.icon} color={Style.globalColors.black_20} style={{marginRight: Style.globalMargins.small}} /> )} <Text type="BodySemibold" style={Style.collapseStyles([ props.selected ? styles.selectedText : styles.itemText, props.textColor ? {color: props.textColor} : {}, ])} > {props.text} </Text> {!!props.badgeNumber && props.badgeNumber > 0 && ( <Badge badgeNumber={props.badgeNumber} badgeStyle={styles.badge} /> )} </ClickableBox> ) } const styles = Style.styleSheetCreate({ badge: { marginLeft: 6, }, item: Style.platformStyles({ common: { ...Style.globalStyles.flexBoxRow, alignItems: 'center', paddingLeft: Style.globalMargins.small, paddingRight: Style.globalMargins.small, position: 'relative', }, isElectron: { height: 32, textTransform: 'uppercase', width: '100%', }, isMobile: { borderBottomColor: Style.globalColors.black_10, borderBottomWidth: Style.hairlineWidth, height: 56, }, }), itemText: Style.platformStyles({ isElectron: { color: Style.globalColors.black_50, }, isMobile: { color: Style.globalColors.black_75, }, }), selectedText: { color: Style.globalColors.black_75, }, })
1.492188
1
lib/db.js
jlleblanc/nodejs-joomla
26
3255
var MySQL = require('mysql'), config = require('./config'); var Db = module.exports; Db.connect = function (callback) { var host = config.configuration.host.split(':'); Db.client = MySQL.createClient({ user: config.configuration.user, password: <PASSWORD>, host: host[0], database: config.configuration.db, port: host[1] == undefined ? 3306 : host[1] }); }; Db.query = function (query_string, callback) { query_string = query_string.replace('#__', config.configuration.dbprefix); Db.client.query(query_string, function (error, results) { if (error) { console.log('MySQL query error, following query failed: ' + query_string + "\nWith this message: " + error); callback(); return; } callback(results); }); };
1.226563
1
client/app/components/Cards/Cards.js
Teenterror/cardsGame
0
3263
import React, { Component } from "react"; //Create two React components for stating a game and joining it: class Cards extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() {} render() { return ( <div> <h1>Cards Game</h1> </div> ); } } export default Cards;
1.679688
2
client-app/src/container/users/list/UsersList.js
code-en-design/econobis
4
3271
import React, { Component } from 'react'; import DataTable from '../../../components/dataTable/DataTable'; import DataTableHead from '../../../components/dataTable/DataTableHead'; import DataTableBody from '../../../components/dataTable/DataTableBody'; import DataTableHeadTitle from '../../../components/dataTable/DataTableHeadTitle'; import UsersListItem from './UsersListItem'; import { connect } from 'react-redux'; class UsersList extends Component { constructor(props) { super(props); } render() { let loadingText = ''; let loading = true; if (this.props.hasError) { loadingText = 'Fout bij het ophalen van gebruikers.'; } else if (this.props.isLoading) { loadingText = 'Gegevens aan het laden.'; } else if (this.props.users.length === 0) { loadingText = 'Geen gebruikers gevonden!'; } else { loading = false; } return ( <div> <DataTable> <DataTableHead> <tr className="thead-title"> <DataTableHeadTitle title={'Voornaam'} width={'30%'} /> <DataTableHeadTitle title={'Achternaam'} width={'25%'} /> <DataTableHeadTitle title={'E-mail'} width={'30%'} /> <DataTableHeadTitle title={'Status'} width={'10%'} /> <DataTableHeadTitle title={''} width={'5%'} /> </tr> </DataTableHead> <DataTableBody> {loading ? ( <tr> <td colSpan={11}>{loadingText}</td> </tr> ) : ( this.props.users.map(user => { return <UsersListItem key={user.id} {...user} />; }) )} </DataTableBody> </DataTable> </div> ); } } const mapStateToProps = state => { return { isLoading: state.loadingData.isLoading, hasError: state.loadingData.hasError, }; }; export default connect(mapStateToProps)(UsersList);
1.554688
2
server/models/index.js
chaldrich24/nft-hot-or-not
0
3279
const User = require('./User'); const Nft = require('./Nft'); module.exports = { User, Nft };
0.355469
0
src/NamedBackbone.js
youngseppa23/imvujs
8
3287
/*global IMVU:true*/ var IMVU = IMVU || {}; (function (root) { function MakeNamedBackboneConstructor(Constructor) { return IMVU.BaseClass.extend.call(Constructor, 'Named' + Constructor.name, { 'static extend': IMVU.BaseClass.extend, initialize: function () { var oldInitialize = this.initialize; this.initialize = function () {}; Constructor.apply(this, arguments); this.initialize = oldInitialize; } }); } IMVU.NamedView = MakeNamedBackboneConstructor(root.Backbone.View); IMVU.NamedModel = MakeNamedBackboneConstructor(root.Backbone.Model); IMVU.NamedCollection = MakeNamedBackboneConstructor(root.Backbone.Collection); }(this));
1.203125
1
src/index.js
guilhermesteves/callboy
2
3295
const { exec } = require('child_process') const { promisify } = require('util') const path = require('path') const fs = require('fs') const execPromise = promisify(exec) const mainPath = path.dirname(fs.realpathSync(__filename)) const soundPath = path.join(mainPath, './audios/callboy') const windowsScript = path.join(mainPath, './forWindows.jscript') const callboy = () => { const commandsForEachPlatform = { linux: `paplay ${soundPath}.ogg`, win32: `cscript /E:JScript /nologo "${windowsScript}" "${soundPath}.mp3"`, darwin: `afplay ${soundPath}.mp3`, } const platform = process.platform const codeToExecute = commandsForEachPlatform[platform] return execPromise(codeToExecute) } module.exports = callboy
1.421875
1
spec/javascripts/models/other_entry_spec.js
Modularfield/pageflow
1
3303
describe('OtherEntry', function() { describe('#getFileCollection', function() { it('returns file collection for entry by fileType', function() { var entry = new pageflow.OtherEntry({id: 34}); var imageFileType = support.factories.imageFileType(); var collection = entry.getFileCollection(imageFileType); expect(collection.url()).to.eq('/editor/entries/34/files/image_files'); }); }); });
1.023438
1
src/components/Angular.js
Kasilucky/coding-sastra
0
3311
import React from "react" import "./Global.css" import Sidebar from "./SideSearchbar"; import InstuctorVarma from "./InstructorVarma"; const Angular = () => ( <div> <section> <div className="container"> <div className="row"> <div className="col-lg-9"> <div className="single_course"> <div className="course_img"> <img src="https://www.encriss.com/wp-content/uploads/2019/04/angular-js.png" alt="course_img_big" /> <div className="enroll_btn"> <a href="https://docs.google.com/forms/d/e/1FAIpQLSds9Lhf8gwCJslxHRJ8ert0IWshl09tQHHX2qHFRsGi0tc7iQ/viewform" className="btn btn-default btn-sm" > Get Enroll </a> </div> </div> <div className="course_detail alert-warning"> <div className="course_title"> <h2>Nullam id varius nunc id varius nunc</h2> </div> <div className="countent_detail_meta"> <ul> <li> <div className="instructor"> <img src="http://mindandculture.org/wordpress6/wp-content/uploads/2018/07/Fotolia_188161178_XS-1.jpg" alt="user1" /> <div className="instructor_info"> <label>Teacher:</label> <h6><NAME></h6> </div> </div> </li> <li> <div className="course_student"> <label>Students: </label> <span> 352</span> </div> </li> <li> <div className="course_categories"> <label>Review: </label> <div className="rating_stars"> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star-half"></i> </div> </div> </li> </ul> </div> </div> <div className="course_tabs"> <ul className="nav nav-tabs" role="tablist"> <li className="nav-item"> <a className="nav-link active" id="overview-tab1" data-toggle="tab" href="#overview" role="tab" aria-controls="overview" aria-selected="true" > Overview </a> </li> <li className="nav-item"> <a className="nav-link" id="curriculum-tab1" data-toggle="tab" href="#curriculum" role="tab" aria-controls="curriculum" aria-selected="false" > curriculum </a> </li> <li className="nav-item"> <a className="nav-link" id="instructor-tab1" data-toggle="tab" href="#instructor" role="tab" aria-controls="instructor" aria-selected="false" > instructor </a> </li> </ul> <div className="tab-content"> <div className="tab-pane fade show active" id="overview" role="tabpanel" aria-labelledby="overview-tab1" > <div className="border radius_all_5 tab_box"> {" "} <p> Lorem Ipsu. is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> </div> </div> <div className="tab-pane fade" id="curriculum" role="tabpanel" aria-labelledby="curriculum-tab1" > <div id="accordion" className="accordion"> <div className="card"> <div className="card-header" id="heading-1-One"> <h6 className="mb-0"> {" "} <a data-toggle="collapse" href="#collapse-1-One" aria-expanded="true" aria-controls="collapse-1-One" > Leap into electronic typesetting{" "} <span className="item_meta duration">30 min</span> </a> </h6> </div> <div id="collapse-1-One" className="collapse show" aria-labelledby="heading-1-One" data-parent="#accordion" > <div className="card-body"> <p> Lorem Ipsu. is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> </div> </div> </div> <div className="card"> <div className="card-header" id="heading-1-Two"> <h6 className="mb-0"> {" "} <a className="collapsed" data-toggle="collapse" href="#collapse-1-Two" aria-expanded="false" aria-controls="collapse-1-Two" > Letraset sheets containing{" "} <span className="item_meta duration">30 min</span> </a>{" "} </h6> </div> <div id="collapse-1-Two" className="collapse" aria-labelledby="heading-1-Two" data-parent="#accordion" > <div className="card-body"> <p> Lorem Ipsu. is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> </div> </div> </div> <div className="card"> <div className="card-header" id="heading-1-Three"> <h6 className="mb-0"> {" "} <a className="collapsed" data-toggle="collapse" href="#collapse-1-Three" aria-expanded="false" aria-controls="collapse-1-Three" > took a galley of type{" "} <span className="item_meta duration">45 min</span> </a>{" "} </h6> </div> <div id="collapse-1-Three" className="collapse" aria-labelledby="heading-1-Three" data-parent="#accordion" > <div className="card-body"> <p> Lorem Ipsu. is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> </div> </div> </div> </div> </div> <div className="tab-pane fade" id="instructor" role="tabpanel" aria-labelledby="instructor-tab1" > <InstuctorVarma/> </div> </div> </div> <div className="row"> <div className="col-12"> <div className="medium_divider"></div> <div className="comment-title"> <h5>Related Courses</h5> </div> </div> </div> <div className="row"> <div className="col-md-6"> <div className="content_box radius_all_10 box_shadow1"> <div className="content_img radius_ltrt_10"> <a href="/"> <img src="assets/images/course_img1.jpg" alt="course_img1" /> </a> </div> <div className="content_desc"> <h4 className="content_title"> <a href="/">Nullam id varius nunc id varius nunc</a> </h4> <p> If you are going to use a passage of Lorem Ipsum you need to be sure anything embarrassing hidden in the middle of text. </p> <div className="courses_info"> <div className="rating_stars"> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star-half"></i> </div> <ul className="list_none content_meta"> <li> <a href="/"> <i className="ti-user"></i>31 </a> </li> <li> <a href="/"> <i className="ti-heart"></i>10 </a> </li> </ul> </div> </div> <div className="content_footer"> <div className="teacher"> <a href="/"> <img src="assets/images/user1.jpg" alt="user1" /> <span><NAME></span> </a> </div> </div> </div> </div> <div className="col-md-6"> <div className="content_box radius_all_10 box_shadow1"> <div className="content_img radius_ltrt_10"> <a href="/"> <img src="assets/images/course_img2.jpg" alt="course_img2" /> </a> </div> <div className="content_desc"> <h4 className="content_title"> <a href="/">Nullam id varius nunc id varius nunc</a> </h4> <p> If you are going to use a passage of Lorem Ipsum you need to be sure anything embarrassing hidden in the middle of text. </p> <div className="courses_info"> <div className="rating_stars"> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star"></i> <i className="ion-android-star-half"></i> </div> <ul className="list_none content_meta"> <li> <a href="/"> <i className="ti-user"></i>31 </a> </li> <li> <a href="/"> <i className="ti-heart"></i>10 </a> </li> </ul> </div> </div> <div className="content_footer"> <div className="teacher"> <a href="/"> <img src="assets/images/user2.jpg" alt="user2" /> <span>Dany Core</span> </a> </div> </div> </div> </div> </div> </div> </div> <Sidebar/> </div> </div> </section> </div> ) export default Angular
1.453125
1
third_party/closure_compiler/interfaces/language_settings_private_interface.js
zealoussnow/chromium
14,668
3319
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file was generated by: // ./tools/json_schema_compiler/compiler.py. /** @fileoverview Interface for languageSettingsPrivate that can be overriden. */ /** @interface */ function LanguageSettingsPrivate() {} LanguageSettingsPrivate.prototype = { /** * Gets languages available for translate, spell checking, input and locale. * @param {function(!Array<!chrome.languageSettingsPrivate.Language>): void} * callback */ getLanguageList: function(callback) {}, /** * Enables a language, adding it to the Accept-Language list (used to decide * which languages to translate, generate the Accept-Language header, etc.). * @param {string} languageCode */ enableLanguage: function(languageCode) {}, /** * Disables a language, removing it from the Accept-Language list. * @param {string} languageCode */ disableLanguage: function(languageCode) {}, /** * Enables or disables translation for a given language. * @param {string} languageCode * @param {boolean} enable */ setEnableTranslationForLanguage: function(languageCode, enable) {}, /** * Moves a language inside the language list. * @param {string} languageCode * @param {!chrome.languageSettingsPrivate.MoveType} moveType */ moveLanguage: function(languageCode, moveType) {}, /** * Gets languages that should always be automatically translated. * @param {function(!Array<string>): void} callback */ getAlwaysTranslateLanguages: function(callback) {}, /** * Sets whether a given language should always be automatically translated. * @param {string} languageCode * @param {boolean} alwaysTranslate */ setLanguageAlwaysTranslateState: function(languageCode, alwaysTranslate) {}, /** * Gets languages that should never be offered to translate. * @param {function(!Array<string>): void} callback */ getNeverTranslateLanguages: function(callback) {}, /** * Gets the current status of the chosen spell check dictionaries. * @param {function(!Array<!chrome.languageSettingsPrivate.SpellcheckDictionaryStatus>): void} * callback */ getSpellcheckDictionaryStatuses: function(callback) {}, /** * Gets the custom spell check words, in sorted order. * @param {function(!Array<string>): void} callback */ getSpellcheckWords: function(callback) {}, /** * Adds a word to the custom dictionary. * @param {string} word */ addSpellcheckWord: function(word) {}, /** * Removes a word from the custom dictionary. * @param {string} word */ removeSpellcheckWord: function(word) {}, /** * Gets the translate target language (in most cases, the display locale). * @param {function(string): void} callback */ getTranslateTargetLanguage: function(callback) {}, /** * Sets the translate target language given a language code. * @param {string} languageCode */ setTranslateTargetLanguage: function(languageCode) {}, /** * Gets all supported input methods, including third-party IMEs. Chrome OS * only. * @param {function(!chrome.languageSettingsPrivate.InputMethodLists): void} * callback */ getInputMethodLists: function(callback) {}, /** * Adds the input method to the current user's list of enabled input methods, * enabling the input method for the current user. Chrome OS only. * @param {string} inputMethodId */ addInputMethod: function(inputMethodId) {}, /** * Removes the input method from the current user's list of enabled input * methods, disabling the input method for the current user. Chrome OS only. * @param {string} inputMethodId */ removeInputMethod: function(inputMethodId) {}, /** * Tries to download the dictionary after a failed download. * @param {string} languageCode */ retryDownloadDictionary: function(languageCode) {}, }; /** * Called when the pref for the dictionaries used for spell checking changes or * the status of one of the spell check dictionaries changes. * @type {!ChromeEvent} */ LanguageSettingsPrivate.prototype.onSpellcheckDictionariesChanged; /** * Called when words are added to and/or removed from the custom spell check * dictionary. * @type {!ChromeEvent} */ LanguageSettingsPrivate.prototype.onCustomDictionaryChanged; /** * Called when an input method is added. * @type {!ChromeEvent} */ LanguageSettingsPrivate.prototype.onInputMethodAdded; /** * Called when an input method is removed. * @type {!ChromeEvent} */ LanguageSettingsPrivate.prototype.onInputMethodRemoved;
1.28125
1
eahub/base/static/scripts/cookieconsent/init.js
taymonbeal/eahub.org
36
3327
import { CookieConsent } from 'cookieconsent'; document.addEventListener('DOMContentLoaded', () => { cookieconsent.initialise({ "palette": { "popup": { "background": "#635274" }, "button": { "background": "#A7DBAB", "text": "white" } }, "content": { "href": "https://eahub.org/privacy-policy" } }) });
0.898438
1
assets/js/custom.js
JigneshMistry/hnetwork
1
3335
/* Name : Custom.Js * Description : Site Custom Function js file * Developer : JM * Verion : 01 */ var siteurl = 'http://localhost/hnetwork/'; var posturl = siteurl+'dashboard/getpost'; var subposturl = siteurl+'dashboard/ajaxpost'; jQuery( document ).ready(function() { /* image upload */ /*jQuery('#upload').click(function(){ //console.log("ok"); $.ajax({ url: "profile/do_upload", // Url to which the request is send type: "POST", // Type of request to be send, called as method data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values) contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData:false, // To send DOMDocument or non processed data file it is set to false success: function(data) // A function to be called if request succeeds { console.log(data); $('#loading').hide(); $("#message").html(data); } }); });*/ /* update account */ jQuery("#account-update").click(function(){ var first_name=jQuery('#first_name').val(); var last_name=jQuery('#last_name').val(); var phone=jQuery('#phone').val(); var address=jQuery('#address').val(); var state=jQuery('#state').val(); var country=jQuery('#country').val(); var pincode=jQuery('#pincode').val(); var dob=jQuery('#dob').val(); //console.log("hello"); if(first_name == "" || last_name == "" || phone == "" || address == "" || state == "" || country == "" || pincode == "" || dob == "") { jQuery("#ack").html("<p style='color:red;'>All Fields are mandatory</p>"); } else { jQuery.ajax({ type: "POST", url: siteurl+'settings/editaccountdata', data:{ 'first_name':first_name, 'last_name':last_name, 'phone':phone, 'address':address, 'state':state, 'country':country, 'pincode':pincode, 'dob':dob }, dataType:"json", success:function(ack){ if(ack == 1) { jQuery("#ack").html("<p style='color:blue;'>Account Updated Successfully</p>"); } else { jQuery("#ack").html("<p style='color:red;'>Account Not Updated.</p>"); } console.log(ack); } }); } //console.log(first_name+"||"+last_name+"||"+phone+"||"+state+"||"+country+"||"+pincode+"||"+dob); }); /* update account */ $("#uploadimage").on('submit',(function(e) { e.preventDefault(); $("#message").empty(); $('#loading').show(); $.ajax({ url: "profile/do_upload", // Url to which the request is send type: "POST", // Type of request to be send, called as method data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values) contentType: false, // The content type used when sending data to the server. cache: false, // To unable request pages to be cached processData:false, // To send DOMDocument or non processed data file it is set to false success: function(data) // A function to be called if request succeeds { $('#loading').hide(); $("#message").html(data); } }); })); $('input[type=file]').change(function(){ $(this).simpleUpload("/ajax/upload.php", { start: function(file){ //upload started $('#filename').html(file.name); $('#progress').html(""); $('#progressBar').width(0); }, progress: function(progress){ //received progress $('#progress').html("Progress: " + Math.round(progress) + "%"); $('#progressBar').width(progress + "%"); }, success: function(data){ //upload successful $('#progress').html("Success!<br>Data: " + JSON.stringify(data)); }, error: function(error){ //upload failed $('#progress').html("Failure!<br>" + error.name + ": " + error.message); } }); }); /* //image upload */ // Loading dashboard post jQuery('.loader').show(); setTimeout(function () { $.ajax({ url: posturl, type: "get", success: function (response) { //jQuery('.loader').hide(); jQuery(".se-pre-con").fadeOut("slow"); jQuery('.blogposts').append(response); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); }, 3000); jQuery('.nav li img.svg').each(function(){ var $img = jQuery(this); var imgID = $img.attr('id'); var imgClass = $img.attr('class'); var imgURL = $img.attr('src'); jQuery.get(imgURL, function(data) { // Get the SVG tag, ignore the rest var $svg = jQuery(data).find('svg'); // Add replaced image's ID to the new SVG if(typeof imgID !== 'undefined') { $svg = $svg.attr('id', imgID); } // Add replaced image's classes to the new SVG if(typeof imgClass !== 'undefined') { $svg = $svg.attr('class', imgClass+' replaced-svg'); } // Remove any invalid XML tags as per http://validator.w3.org $svg = $svg.removeAttr('xmlns:a'); // Replace image with new SVG $img.replaceWith($svg); }, 'xml'); }); jQuery('.newpost a').click(function(){ jQuery('.text_post').hide(); jQuery('.quote_post').hide(); jQuery('.photo_post').hide(); jQuery('.video_post').hide(); jQuery('.audio_post').hide(); var clickid = jQuery(this).attr('id'); jQuery('.postarea').find('.'+clickid).toggle(); }); //Close Event For Post Write Box jQuery('.closebtn').click(function(){ jQuery('.text_post').hide(); jQuery('.quote_post').hide(); jQuery('.photo_post').hide(); jQuery('.video_post').hide(); jQuery('.audio_post').hide(); clearall(); }); //Upload Photo Click jQuery('.photo_upload').click(function(){ //jQuery('#photo_upload input').open(); jQuery('#photo_up').trigger('click'); jQuery('#photo_upload').show(); jQuery("#first_up").hide(); jQuery("input[type=file]").on("change", function() { // $("[for=file]").html(this.files[0].name); jQuery("#preview").attr("src", URL.createObjectURL(this.files[0])); }); }); //From Web Photo, Video, Audio jQuery('.fromweb').click(function(){ jQuery('#photo_upload').show(); jQuery("#first_up").hide(); jQuery('.enter_url').show(); }); //Remove Picture Click Event jQuery('.del').click(function(){ jQuery("#preview").attr("src",''); jQuery("input[type=file]").val(''); jQuery('#photo_upload').hide(); jQuery("#first_up").show(); }); // Post the ajax with all post data jQuery('#post_text').click(function(){ var posttitle = jQuery("#newstatustitle").val(); var postdesc = jQuery("#newdesc").val(); var posttype = jQuery("#post_type").val(); if(posttitle!='') { // Value found in text box Ajax begin $.ajax({ url: subposturl, type: "post", data: {posttitle:posttitle,postdesc:postdesc,posttype:posttype} , success: function (response) { jQuery('.postarea .text_post').hide(); jQuery('.postarea .quote_post').hide(); jQuery('.postarea .photo_post').hide(); jQuery('.postarea .video_post').hide(); jQuery('.postarea .audio_post').hide(); jQuery('.post-forms-glass').hide(); jQuery('.post-forms-glass').removeClass('active'); jQuery('.post-forms-glass').css({'opacity':'0','display':'none'}); jQuery('.blogposts').prepend(response).show('slow'); jQuery("#newstatustitle").val(''); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); } }); //Quote post Ajax jQuery('#post_quote').click(function(){ var postdesc = jQuery("#newdesc").val(); var posttype = 2; var postquote = jQuery("#quote").val(); if(postquote!='') { // Value found in text box Ajax begin $.ajax({ url: subposturl, type: "post", data: {posttitle:postquote,postdesc:postdesc,posttype:posttype} , success: function (response) { jQuery('.postarea .text_post').hide(); jQuery('.postarea .quote_post').hide(); jQuery('.postarea .photo_post').hide(); jQuery('.postarea .video_post').hide(); jQuery('.postarea .audio_post').hide(); jQuery('.post-forms-glass').hide(); jQuery('.post-forms-glass').removeClass('active'); jQuery('.post-forms-glass').css({'opacity':'0','display':'none'}); jQuery('.blogposts').prepend(response).show('slow'); jQuery("#quote").val(''); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); } }); //Photo jQuery('#post_photo').click(function(){ var selectedphoto = jQuery("#photo_up").val(); //alert("testing"+selectedphoto) var postdesc = ""; var posttype = 3; var posttitle = ""; if(selectedphoto!='') { $('#photo_up').simpleUpload({ url: subposturl, trigger: '#post_photo', fields: { posttitle:posttitle,postdesc:postdesc,posttype:posttype }, success: function(data){ jQuery('.postarea .text_post').hide(); jQuery('.postarea .quote_post').hide(); jQuery('.postarea .photo_post').hide(); jQuery('.postarea .video_post').hide(); jQuery('.postarea .audio_post').hide(); jQuery('.post-forms-glass').hide(); jQuery('.post-forms-glass').removeClass('active'); jQuery('.post-forms-glass').css({'opacity':'0','display':'none'}); jQuery('#blog-wall').prepend(data).show('slow'); jQuery("#quote").val(''); } }); } }); //Video Post jQuery('#post_v').click(function(){ var pin = jQuery("#pin").val(); var wseep = jQuery("#wseep").val(); var idw = jQuery("#idw").val(); var typeattach2 = 2; var combowsee = 0; var posttitle = ''; var videourl = jQuery("#atach-value").val(); var videotitle = jQuery("#videotitle").val(); if(videourl!='') { // Value found in text box Ajax begin $.ajax({ url: subposturl, type: "post", data: {txttitle:videotitle,pin:pin,wseep:wseep,idw:idw,typeattach2:typeattach2,combowsee:combowsee,videourl:videourl} , success: function (response) { jQuery('.postarea .text_post').hide(); jQuery('.postarea .quote_post').hide(); jQuery('.postarea .photo_post').hide(); jQuery('.postarea .video_post').hide(); jQuery('.postarea .audio_post').hide(); jQuery('.post-forms-glass').hide(); jQuery('.post-forms-glass').removeClass('active'); jQuery('.post-forms-glass').css({'opacity':'0','display':'none'}); jQuery('#blog-wall').prepend(response).show('slow'); jQuery("#atach-value").val(''); jQuery("#videotitle").val(''); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); } }); //Audio Post jQuery('#post_audio').click(function(){ var pin = jQuery("#pin").val(); var wseep = jQuery("#wseep").val(); var idw = jQuery("#idw").val(); var typeattach3 = 3; var combowsee = 0; var posttitle = ''; var audiourl = jQuery("#audiourl").val(); var audiotitle = jQuery("#audiotitle").val(); if(audiourl!='') { // Value found in text box Ajax begin $.ajax({ url: subposturl, type: "post", data: {txttitle:audiotitle,pin:pin,wseep:wseep,idw:idw,typeattach3:typeattach3,combowsee:combowsee,videourl:audiourl} , success: function (response) { jQuery('.postarea .text_post').hide(); jQuery('.postarea .quote_post').hide(); jQuery('.postarea .photo_post').hide(); jQuery('.postarea .video_post').hide(); jQuery('.postarea .audio_post').hide(); jQuery('.post-forms-glass').hide(); jQuery('.post-forms-glass').removeClass('active'); jQuery('.post-forms-glass').css({'opacity':'0','display':'none'}); jQuery('#blog-wall').prepend(response).show('slow'); jQuery("#audiourl").val(''); jQuery("#audiotitle").val(''); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); } }); //Post Settings box $("#bsmenup_VmRcQkrhPKt").on("click",function(){ $('.submenuitem').hide(); positop = $("#bsmenup_VmRcQkrhPKt").position() $('#smnp_VmRcQkrhPKt').css('top',positop.top + 17); $('#smnp_VmRcQkrhPKt').show(); return false; }); }); //Delete function function postdelete(postid) { jQuery("#postdeletebox").modal('show'); jQuery("#yesdelete").click(function(){ jQuery.ajax({ url: siteurl+'dashboard/ajaxdelete', type: "post", data: {postid:postid} , success: function (response) { if(response == 1) { alert('Sorry due to some techinicle problem we can not delte this post'); }else { jQuery("#post_"+postid).slideUp(2000); jQuery("#postdeletebox").modal('hide'); } }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); }); } //Edit function function postedit(postid) { jQuery("#posteditbox").modal('show'); } //Report function function postreport(postid) { jQuery.ajax({ url: siteurl+'dashboard/ajaxreport', type: "post", data: {postid:postid} , success: function (response) { jQuery("#post_"+postid).slideUp(2000); }, error: function(jqXHR, textStatus, errorThrown) { console.log(textStatus, errorThrown); } }); } //Frendsuggestion function userfollow(userid,leaderid,clickid) { /* Add */ jQuery.ajax({ type:"post", dataType:"json", url:siteurl+'dashboard/follower', data:{ 'userid':userid, 'leaderid':leaderid, 'clickid':clickid }, success:function(res){ console.log(res); //console.log(res.uid); /*if(res == true) { //window.location.href=siteurl; //alert("follows "+res.cid+""); } */ } }); /* //Add */ //console.log("Hello "+ userid); jQuery("#"+clickid).slideUp(1000); } //Show img function on function showimg() { setTimeout(function () { var imgurl = jQuery('#from_url').val(); if(imgurl != '') { jQuery('.enter_url').hide(); jQuery("#preview").attr("src",imgurl); jQuery('.del').show(); } }, 1000); } function clearall() { jQuery("#newstatustitle").val(''); jQuery("#newdesc").html(''); jQuery("#quote").html(''); jQuery("#photo_up").val(''); jQuery("#from_url").val(''); jQuery("#preview").val(''); }
1.3125
1
src/liquidity-pool-stake.js
stellar-expert/liquidity-pool-utils
0
3343
import Bignumber from 'bignumber.js' import {stripTrailingZeros} from '@stellar-expert/formatter' /** * Estimate amounts of liquidity pool tokens based on the share of the pool * @param {Number|String|Bignumber} shares - Amount of pool shares that belong to the account * @param {Array<String|Number|Bignumber>} reserves - Total amount of tokens deposited to the pool * @param {Number|String|Bignumber} totalShares - Total pool shares * @return {Array<String>} */ export function estimateLiquidityPoolStakeValue(shares, reserves, totalShares) { if (!(shares > 0) || !(totalShares > 0)) return null return reserves.map(reserve => { const amount = new Bignumber(shares) .mul(new Bignumber(reserve)) .div(totalShares) .toFixed(7, Bignumber.ROUND_DOWN) return stripTrailingZeros(amount) }) }
1.921875
2
test/virtual-fs.js
shama/ix-head
1
3351
var fs = module.exports = {} var Readable = require('readable-stream/readable') var inherits = require('inherits') var data = { 'test/fixtures/twelve': 'one\ntwo\nthree\nfour\nfive\nsix\nseven\neight\nine\nten\neleven\ntwelve\n', 'test/fixtures/four': 'one\ntwo\nthree\nfour\n', } function VFile(filename) { Readable.call(this) this.filename = filename } inherits(VFile, Readable) VFile.prototype._read = function() { this.push(data[this.filename]) this.push(null) } fs.createReadStream = function(filename) { return new VFile(filename) }
1.03125
1
js/index.js
ZeroHang/proyecto-clases-UP-
0
3359
var usuarioGuardado = sessionStorage.getItem('usuarioLogueado'); if (usuarioGuardado) { usuarioGuardado = JSON.parse(usuarioGuardado); $('#login').text(usuarioGuardado.usuario); $('#login').parent().addClass('dropdown'); $('#login').addClass('dropdown-toggle'); $('#login').attr('href', '#'); $('#login').attr('data-toggle', 'dropdown'); $('#login').attr('aria-haspopup', 'true'); $('#login').attr('aria-expanded', 'false'); var div = document.createElement('div'); $(div).addClass('dropdown-menu', 'dropdown-menu-right'); $(div).attr('aria-labelledby', 'login'); $('<a class="dropdown-item" href="miperfil.html">Mi Perfil</a>').appendTo(div); $('<a class="dropdown-item" href="misordenes.html">Mis Ordenes</a>').appendTo(div); $('<a class="dropdown-item" href="javascript:void(0);" onclick="logout()">Logout</a>').appendTo(div); $('#login').parent().append(div); } traerProductosPrincipal();
0.820313
1
perun-apps/apps/alt-passwords/js/AlternativePassword.js
licehammer/perun
49
3367
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function entryPoint(user) { callPerun("attributesManager", "getAttribute", {user: user.id, attributeName: "urn:perun:user:attribute-def:def:login-namespace:einfra"}, function(login) { if (!login.value) { (staticMessager.newMessage("Can't set alternative passwords", "You don't have eInfra login", "danger")).draw(); return; } else { $("#passSubmit").removeAttr('disabled'); loadAlternativePasswords(user); } }); } $(document).ready(function() { $("#createAltPassword").submit(function(event) { event.preventDefault(); var loadImage = new LoadImage($('#createAltPassword'), "20px"); var password = <PASSWORD>); var description = $("#altPasswordDescription").val(); $("#altPasswordDescription").val(""); callPerunPost("usersManager", "createAlternativePassword", {user: user.id, description: description, loginNamespace: "einfra", password: password}, function() { loadAlternativePasswords(user); showPassword(description, password); (flowMessager.newMessage("Alternative password", "was created successfully", "success")).draw(); }, null, function() { loadImage.hide(); } ); }); }); function loadAlternativePasswords(user) { if (!user) { (flowMessager.newMessage("Alternative Passwords", "can't be loaded because user isn't loaded.", "danger")).draw(); return; } var loadImage = new LoadImage($('#altPasswordsTable'), "64px"); callPerun("attributesManager", "getAttribute", {user: user.id, attributeName: "urn:perun:user:attribute-def:def:altPasswords:einfra"}, function(altPasswords) { if (!altPasswords) { (flowMessager.newMessage("Alternative passwords", "can't be loaded.", "danger")).draw(); return; } fillAlternativePasswords(altPasswords); loadImage.hide(); //(flowMessager.newMessage("User data", "was loaded successfully.", "success")).draw(); }); } function fillAlternativePasswords(altPasswords) { if (!altPasswords) { (flowMessager.newMessage("Alternative Passwords", "can't be fill.", "danger")).draw(); return; } var altPasswordsTable = new PerunTable(); altPasswordsTable.addColumn({type: "number", title: "#"}); altPasswordsTable.addColumn({type: "text", title: "Description", name: "key"}); altPasswordsTable.addColumn({type: "button", title: "", btnText: "delete", btnType: "danger", btnName: "deleteAltPassword", btnId: "value"}); altPasswordsTable.setList(altPasswords.value); var tableHtml = altPasswordsTable.draw(); $("#altPasswordsTable").html(tableHtml); $("#altPasswordsTable button[id^='deleteAltPassword-']").click(function() { var loadImage = new LoadImage($('#altPasswordsTable'), "40px"); var passwordId = $(this).attr("id").split('-')[1]; callPerunPost("usersManager", "deleteAlternativePassword", {user: user.id, loginNamespace: "einfra", passwordId: <PASSWORD>}, function() { loadAlternativePasswords(user); loadImage.hide(); (flowMessager.newMessage("Alternative password", "was deleted successfully", "success")).draw(); }); }); } function randomPassword(length) { chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<PASSWORD>"; pass = ""; for (x = 0; x < length; x++) { i = Math.floor(Math.random() * chars.length); pass += chars.charAt(i); } return pass; } function showPassword(description, password) { $("#showPassword .description").text(description); $("#showPassword .password").html(splitStringToHtml(password, 4)); $("#showPassword").modal(); } $('#showPassword').on('hidden.bs.modal', function (e) { $("#showPassword .password").text("..."); }); function splitStringToHtml(string, number) { var splitHtml = "<span>"; for(var id in string) { if ((id % number === 0) && (id !== "0")) { splitHtml += "</span><span>"; } splitHtml += string[id]; } splitHtml += "</span>"; return splitHtml; }
1.289063
1
git-pull.js
SmilyBorg/bitburner-scripts
0
3375
let options; const argsSchema = [ ['github', 'SmilyBorg'], ['repository', 'bitburner-scripts'], ['branch', 'main'], ['download', []], // By default, all supported files in the repository will be downloaded. Override with just a subset of files here ['new-file', []], // If a repository listing fails, only files returned by ns.ls() will be downloaded. You can add additional files to seek out here. ['subfolder', ''], // Can be set to download to a sub-folder that is not part of the remote repository structure ['extension', ['.js', '.ns', '.txt', '.script']], // Files to download by extension ['omit-folder', ['/Temp/']], // Folders to omit ]; export function autocomplete(data, args) { data.flags(argsSchema); const lastFlag = args.length > 1 ? args[args.length - 2] : null; if (["--download", "--subfolder", "--omit-folder"].includes(lastFlag)) return data.scripts; return []; } /** @param {NS} ns * Will try to download a fresh version of every file on the current server. * You are responsible for: * - Backing up your save / scripts first (try `download *` in the terminal) * - Ensuring you have no local changes that you don't mind getting overwritten * TODO: Some way to list all files in the repository and/or download them all. **/ export async function main(ns) { options = ns.flags(argsSchema); if (options.subfolder && !options.subfolder.startsWith('/')) options.subfolder = '/' + options.subfolder; // Game requires folders to have a leading slash. Add one if it's missing. const baseUrl = `https://raw.githubusercontent.com/${options.github}/${options.repository}/${options.branch}/`; const filesToDownload = options['new-file'].concat(options.download.length > 0 ? options.download : await repositoryListing(ns)); for (const localFilePath of filesToDownload) { let fullLocalFilePath = pathJoin(options.subfolder, localFilePath); const remoteFilePath = baseUrl + localFilePath; ns.print(`Trying to update "${fullLocalFilePath}" from ${remoteFilePath} ...`); if (await ns.wget(`${remoteFilePath}?ts=${new Date().getTime()}`, fullLocalFilePath) && await rewriteFileForSubfolder(ns, fullLocalFilePath)) ns.tprint(`SUCCESS: Updated "${localFilePath}" to the latest from ${remoteFilePath}`); else ns.tprint(`WARNING: "${localFilePath}" was not updated. (Currently running or not located at ${remoteFilePath} )`) } } /** Joins all arguments as components in a path, e.g. pathJoin("foo", "bar", "/baz") = "foo/bar/baz" **/ function pathJoin(...args) { return args.filter(s => !!s).join('/').replace(/\/\/+/g, '/'); } /** @param {NS} ns * Rewrites a file with path substitions to handle downloading to a subfolder. **/ export async function rewriteFileForSubfolder(ns, path) { if (!options.subfolder || path.includes('git-pull.js')) return true; let contents = ns.read(path); // Replace subfolder reference in helpers.js getFilePath: contents = contents.replace(`const subfolder = ''`, `const subfolder = '${options.subfolder}/'`); // Replace any imports, which can't use getFilePath: contents = contents.replace(/from '(\.\/)?(.*)'/g, `from '${pathJoin(options.subfolder, '$2')}'`); await ns.write(path, contents, 'w'); return true; } /** @param {NS} ns * Gets a list of files to download, either from the github repository (if supported), or using a local directory listing **/ async function repositoryListing(ns, folder = '') { // Note: Limit of 60 free API requests per day, don't over-do it const listUrl = `https://api.github.com/repos/${options.github}/${options.repository}/contents/${folder}?ref=${options.branch}` let response = null; try { response = await fetch(listUrl); // Raw response // Expect an array of objects: [{path:"", type:"[file|dir]" },{...},...] response = await response.json(); // Deserialized // Sadly, we must recursively retrieve folders, which eats into our 60 free API requests per day. const folders = response.filter(f => f.type == "dir").map(f => f.path); let files = response.filter(f => f.type == "file").map(f => f.path) .filter(f => options.extension.some(ext => f.endsWith(ext))); ns.print(`The following files exist at ${listUrl}\n${files.join(", ")}`); for (const folder of folders) files = files.concat((await repositoryListing(ns, folder)) .map(f => `/${f}`)); // Game requires folders to have a leading slash return files; } catch (error) { if (folder !== '') throw error; // Propagate the error if this was a recursive call. ns.tprint(`WARNING: Failed to get a repository listing (GitHub API request limit of 60 reached?): ${listUrl}` + `\nResponse Contents (if available): ${JSON.stringify(response ?? '(N/A)')}\nError: ${String(error)}`); // Fallback, assume the user already has a copy of all files in the repo, and use it as a directory listing return ns.ls('home').filter(name => options.extension.some(ext => f.endsWith(ext)) && !options['omit-folder'].some(dir => name.startsWith(dir))); } }
1.710938
2
src/components/Todo/data.js
vUnAmp/gatsby-chess-dnd
0
3383
const initialData = { tasks: { 'task-1': { id: 'task-1', content: 'Take out the garbage' }, 'task-2': { id: 'task-2', content: 'Watch my favorite show' }, 'task-3': { id: 'task-3', content: 'Charge my phone' }, 'task-4': { id: 'task-4', content: 'Cook dinner' }, }, columns: { 'column-1': { id: 'column-1', title: 'To do', taskIds: ['task-1', 'task-2', 'task-3', 'task-4'], }, 'column-2': { id: 'column-2', title: 'In progress', taskIds: [], }, 'column-3': { id: 'column-3', title: 'Done', taskIds: [], }, }, // Facilitate reordering of the columns columnOrder: ['column-1', 'column-2', 'column-3'], } export default initialData
1.335938
1
public/de2d8f53-2e4c-4857-9ed2-98d6b6277260/projectzip/project/dgt/biz/phone_list.js
sandofsuro/react-web-dgt
0
3391
/** * 东管头村APP * @author nectar * Mon Jan 09 10:34:10 CST 2017 */ 'use strict'; import React, { Component, PropTypes } from 'react'; import { View, Text, TouchableHighlight, TouchableOpacity, StyleSheet, TextInput, Dimensions, Image, Alert, Platform, Navigator, ListView, RefreshControl } from 'react-native'; import AKCommunications from '../components/AKCommunications.js'; export default class PhoneList extends Component { constructor(props) { super(props); var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { refreshing: false, dataSource: ds.cloneWithRows([]), }; } componentWillMount() { client.getContacts(function(result) { if(result.success == true) { this.setState({ dataSource: this.state.dataSource.cloneWithRows(result.data), }); } else { console.log(result.err); } }.bind(this)); } _onRefresh() { this.setState({refreshing: true}); client.getContacts(function(result) { if(result.success == true) { this.setState({ refreshing: false, dataSource: this.state.dataSource.cloneWithRows(result.data), }); } else { console.log(result.err); } }.bind(this)); } dial(data) { AKCommunications.phonecall(data, true); } renderRow(rowData) { return ( <TouchableHighlight underlayColor={'#ccc'} onPress={() => {this.dial(rowData.number);}}> <View style={styles.row}> <Text style={styles.rowText} numberOfLines={1}>{rowData.name}</Text> <Image source={{uri: GLOBAL.WebRoot + 'web/img/home/[email protected]'}} style={styles.iconImage} /> </View> </TouchableHighlight> ); } renderScene(route, navigator) { return ( <View style={styles.container}> <ListView refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={this._onRefresh.bind(this)} /> } dataSource={this.state.dataSource} renderRow={this.renderRow.bind(this)} contentContainerStyle={styles.list} enableEmptySections = {true} /> </View> ); } renderNavTitle(route, navigator) { return ( <Text style={styles.navBarTitleText}> 电话黄页 </Text> ); } renderNavLeftButton(route, navigator) { var title = "返回"; return ( <TouchableOpacity onPress={() => this.props.navigator.pop()} style={styles.navBarLeftButton}> <Image source={{uri: GLOBAL.WebRoot + 'web/img/register/[email protected]'}} style={styles.backImage} /> <Text style={styles.navBarButtonText}> {title} </Text> </TouchableOpacity> ); } renderNavRightButton(route, navigator) { var title = ""; return ( <TouchableOpacity style={styles.navBarRightButton}> <Text style={styles.navBarButtonText}> {title} </Text> </TouchableOpacity> ); } render() { var bar = ( <Navigator.NavigationBar routeMapper={{ LeftButton:this.renderNavLeftButton.bind(this), RightButton:this.renderNavRightButton.bind(this), Title:this.renderNavTitle.bind(this), }} style={styles.navBar} /> ); return ( <Navigator style={styles.navigator} navigationBar={bar} renderScene={this.renderScene.bind(this)} initialRoute={{title:'电话黄页'}} /> ); } } const styles = StyleSheet.create({ container: { flex: 1, paddingTop:Platform.OS == 'ios' ? 74 : 68, backgroundColor: '#f5f5f5', justifyContent: 'flex-start', alignItems: 'center', }, navigator: { flex:1, justifyContent: 'center', alignItems: 'stretch', }, navBar: { backgroundColor: '#ff5558', justifyContent: 'center', }, navBarTitleText: { fontSize:20, fontWeight: '400', marginVertical: 12, width: 3 * (Dimensions.get('window').width) / 5, textAlign: 'center', color: '#ffffff', }, navBarButtonText: { fontSize:15, color: '#ffffff', }, navBarLeftButton: { flex: 1, flexDirection: 'row', paddingLeft: 10, alignItems: 'center', }, navBarRightButton: { paddingRight: 10, justifyContent: 'center', }, backImage: { width: 23 / 2, height: 41 / 2, marginRight: 5, }, list: { }, row: { height: 50, width: Dimensions.get('window').width, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', backgroundColor: 'white', borderBottomWidth: 1, borderBottomColor: '#e3e3e3', paddingLeft: 15, paddingRight: 15, }, rowText: { color: '#333', fontSize: 36 / 2, }, iconImage: { width: 28, height: 28, } });
1.695313
2
src/BreadCrumb/__stories__/BreadCrumb.stories.js
gurubamal/Stardust
15
3399
import React from 'react'; import { storiesOf } from '@storybook/react'; import { withKnobs, optionsKnob } from '@storybook/addon-knobs'; import withDocs from 'storybook-readme/with-docs'; import Wrapper from '../../Wrapper'; import BreadCrumb from '..'; import BreadCrumbReadme from '../README.md'; storiesOf('BreadCrumb', module) .addDecorator(withKnobs) .addDecorator(withDocs(BreadCrumbReadme)) // Show readme around story .addParameters({ readme: { includePropTables: [BreadCrumb], // won't work right now because of wrapped styled-comp https://github.com/tuchk4/storybook-readme/issues/177 }, }) .add('with customizable properties', () => { const paths = { path: 'path', to: 'to', the: 'the', current: 'current', page: 'page' }; const pathsToDisplay = optionsKnob( 'Paths to display', paths, Object.values(paths), { display: 'multi-select' }, 'State', ); return ( <Wrapper> <BreadCrumb> {pathsToDisplay.map(path => ( <BreadCrumb.Item key={path}>{path}</BreadCrumb.Item> ))} </BreadCrumb> </Wrapper> ); });
1.3125
1
src/visitors/heapRestore.js
txvnt/regenerator
0
3407
const t = require('babel-types'); function shallowCopy(object) { return object; } module.exports = { MemberExpression(path) { if ( path.node.object && path.node.property && path.node.object.name == 'delorean' && (path.node.property.name == 'insertTimepoint' || path.node.property.name == 'insertBreakpoint') ) { var snapshotCall = path.findParent((path) => path.isCallExpression()); var itIsInLoop = false; parent = path.context.parentPath; while (parent) { parent = parent.context.parentPath; if (parent) { if ( parent.node.type == 'ForStatement' || parent.node.type == 'DoWhileStatement' || parent.node.type == 'WhileStatement' ) { itIsInLoop = true; break; } } } let copy = 'ldDeepCopy'; if ( document.getElementsByClassName('swtich-options selected-switch')[0].innerHTML == 'Shallow Copy' ) copy = shallowCopy; //Stores all dependant variables in a temp global object. /* heap.dependencies.map(dependecy => { if (eval('typeof ' + dependecy.name.toString() + '!=\'undefined\'')) { tempValueStore[dependecy.name.toString()] = eval(dependecy.name.toString()); } else { tempValueStore[dependecy.name.toString()] = undefined; } }); */ snapshotCall.insertBefore( t.expressionStatement( t.callExpression( t.memberExpression( t.memberExpression(t.identifier('heap'), t.identifier('dependencies'), false), t.identifier('map'), false, ), [ t.arrowFunctionExpression( [t.identifier('dependecy')], t.blockStatement( [ t.ifStatement( t.callExpression(t.identifier('eval'), [ t.binaryExpression( '+', t.binaryExpression( '+', t.stringLiteral('typeof '), t.callExpression( t.memberExpression( t.memberExpression( t.identifier('dependecy'), t.identifier('name'), false, ), t.identifier('toString'), false, ), [], ), ), t.stringLiteral("!='undefined'"), ), ]), t.blockStatement([ t.expressionStatement( t.assignmentExpression( '=', t.memberExpression( t.identifier('tempValueStore'), t.callExpression( t.memberExpression( t.memberExpression( t.identifier('dependecy'), t.identifier('name'), false, ), t.identifier('toString'), false, ), [], ), true, ), t.callExpression(t.identifier('eval'), [ t.callExpression( t.memberExpression( t.memberExpression( t.identifier('dependecy'), t.identifier('name'), false, ), t.identifier('toString'), false, ), [], ), ]), ), ), ]), t.blockStatement([ t.expressionStatement( t.assignmentExpression( '=', t.memberExpression( t.identifier('tempValueStore'), t.callExpression( t.memberExpression( t.memberExpression( t.identifier('dependecy'), t.identifier('name'), false, ), t.identifier('toString'), false, ), [], ), true, ), t.identifier('undefined'), ), ), ]), ), ], [], ), ), ], ), ), ); // Restores variables when coming back form the future. /* if (fromTheFuture) { let snapshot = restoreHeap(startFrom); dependencies.map(key => { auxSnapshotValue = ldDeepCopy(snapshot[key.name]); if (typeof auxSnapshotValue == 'object') { updatedObj = updateProp(key.name, auxSnapshotValue); eval(key.name + ' = updatedObj'); } else { eval(key.name + ' = document.getElementById(\'input-' + key.name + '\').value || undefined || auxSnapshotValue;'); } }); fromTheFuture = false; } */ snapshotCall.insertAfter( t.ifStatement( t.identifier('fromTheFuture'), t.blockStatement( [ t.variableDeclaration('let', [ t.variableDeclarator( t.identifier('snapshot'), t.callExpression(t.identifier('restoreHeap'), [t.identifier('startFrom')]), ), ]), t.expressionStatement( t.callExpression( t.memberExpression(t.identifier('dependencies'), t.identifier('map'), false), [ t.arrowFunctionExpression( [t.identifier('key')], t.blockStatement([ t.ifStatement( t.binaryExpression( '!=', t.unaryExpression( 'typeof', t.memberExpression( t.identifier('snapshot'), t.memberExpression( t.identifier('key'), t.identifier('name'), false, ), true, ), true, ), t.stringLiteral('function'), ), t.expressionStatement( t.assignmentExpression( '=', t.identifier('auxSnapshotValue'), t.callExpression(t.identifier(copy), [ t.memberExpression( t.identifier('snapshot'), t.memberExpression( t.identifier('key'), t.identifier('name'), false, ), true, ), ]), ), ), t.expressionStatement( t.assignmentExpression( '=', t.identifier('auxSnapshotValue'), t.memberExpression( t.identifier('snapshot'), t.memberExpression( t.identifier('key'), t.identifier('name'), false, ), true, ), ), ), ), t.ifStatement( t.binaryExpression( '==', t.unaryExpression('typeof', t.identifier('auxSnapshotValue'), true), t.stringLiteral('object'), ), t.blockStatement( [ t.expressionStatement( t.assignmentExpression( '=', t.identifier('updatedObj'), t.callExpression(t.identifier('updateProp'), [ t.identifier('key.name'), t.identifier('auxSnapshotValue'), ]), ), ), t.expressionStatement( t.callExpression(t.identifier('eval'), [ t.binaryExpression( '+', t.memberExpression(t.identifier('key'), t.identifier('name')), t.stringLiteral(' = updatedObj'), ), ]), ), ], [], ), t.blockStatement( [ t.expressionStatement( t.callExpression(t.identifier('eval'), [ t.binaryExpression( '+', t.binaryExpression( '+', t.binaryExpression( '+', t.memberExpression( t.identifier('key'), t.identifier('name'), false, ), t.stringLiteral(" = document.getElementById('input-"), ), t.memberExpression( t.identifier('key'), t.identifier('name'), false, ), ), t.stringLiteral("').value || undefined || auxSnapshotValue;"), ), ]), ), ], [], ), ), ]), false, ), ], ), ), t.expressionStatement( t.assignmentExpression('=', t.identifier('fromTheFuture'), t.booleanLiteral(false)), ), ], [], ), null, ), ); } }, };
1.59375
2
js/utils/slugify.js
wdmih/Hillel-Project
0
3415
/// this code was taken from stackoverflow export default function slugify(string) { return string .toString() .toLowerCase() .trim() .replace(/&/g, '-and-') .replace(/[\s\W-]+/g, '-'); }
0.867188
1
test/widget-textarea.js
yaronn/blessed-patch-temp
1
3423
var blessed = require('../') , screen; screen = blessed.screen({ dump: __dirname + '/logs/textarea.log', fullUnicode: true }); var box = blessed.textarea({ parent: screen, // Possibly support: // align: 'center', style: { bg: 'blue' }, height: 'half', width: 'half', top: 'center', left: 'center', tags: true }); screen.render(); screen.key('q', function() { process.exit(0); }); screen.key('i', function() { box.readInput(function() {}); }); screen.key('e', function() { box.readEditor(function() {}); });
1.007813
1
components/__tests__/locale-chooser.js
andrew-codes/glamorous-website
105
3431
import React from 'react' import {mount} from 'enzyme' import {ThemeProvider} from 'glamorous' import GlobalStyles from '../../styles/global-styles' import LocaleChooser from '../locale-chooser' const {supportedLocales, fallbackLocale} = require('../../config.json') test('a closed locale-chooser', () => { setHost() const wrapper = mountLocaleChooser() testClosedState(wrapper) }) test('an open locale-chooser', () => { setHost() const wrapper = mountLocaleChooser() const toggle = wrapper.find('button') const selector = wrapper.find('ul') toggle.simulate('click') expect(toggle.getDOMNode().getAttribute('aria-expanded')).toEqual('true') expect(selector.getDOMNode().getAttribute('aria-hidden')).toEqual('false') expect( selector.childAt(0).find('a').getDOMNode() === document.activeElement, ).toBe(true) }) test('pressing the escape key closes the locale-selector', () => { setHost() const wrapper = mountLocaleChooser() const toggle = wrapper.find('button') toggle.simulate('click') document.dispatchEvent(new KeyboardEvent('keydown', {keyCode: 27})) testClosedState(wrapper) }) test('an outside click closes the locale-selector', () => { setHost() const wrapper = mountLocaleChooser() const toggle = wrapper.find('button') toggle.simulate('click') document.dispatchEvent(new Event('click')) testClosedState(wrapper) }) test('creates localization links', () => { supportedLocales.forEach(l => { setHost(l) testLocalizationLinks() }) }) function mountLocaleChooser() { return mount( <ThemeProvider theme={GlobalStyles}> <LocaleChooser /> </ThemeProvider>, ) } const host = 'glamorous.rocks' function setHost(lang = fallbackLocale) { process.env.LOCALE = lang // why can't we just do window.location.host = 'foo'? // https://github.com/facebook/jest/issues/890 Object.defineProperty(window.location, 'host', { writable: true, value: `${lang === fallbackLocale ? '' : `${lang}.`}${host}`, }) Object.defineProperty(window.location, 'protocol', { writable: true, value: 'https:', }) Object.defineProperty(window.location, 'pathname', { writable: true, value: '/', }) } function testClosedState(wrapper) { const toggle = wrapper.find('button') const selector = wrapper.find('ul') expect(toggle.getDOMNode().getAttribute('aria-expanded')).toEqual('false') expect(selector.getDOMNode().getAttribute('aria-hidden')).toEqual('true') } function testLocalizationLinks() { const wrapper = mountLocaleChooser() const links = wrapper.find('a') expect(links.length).toBe(supportedLocales.length + 1) supportedLocales.forEach((l, i) => { const prefix = l === fallbackLocale ? '' : `${l}.` expect(links.at(i).getDOMNode().getAttribute('href')).toEqual( `https://${prefix}${host}/`, ) }) expect( links.at(supportedLocales.length).getDOMNode().getAttribute('href'), ).toEqual( 'https://github.com/kentcdodds/glamorous-website/blob/master/other/CONTRIBUTING_DOCUMENTATION.md', ) }
1.554688
2
public/js/lang-en.8de533643027096faa7f.js
MegaMaid/MegaMaid
0
3439
webpackJsonp([2],{ /***/ 82: /***/ (function(module, exports) { eval("throw new Error(\"Module build failed: SyntaxError: Unexpected token } in JSON at position 4118\\n at JSON.parse (<anonymous>)\\n at Object.module.exports (/sites/megamaid.test/node_modules/json-loader/index.js:4:49)\");//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,<KEY>zLCJzb3VyY2VzIjpbXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IiIsImZpbGUiOiI4Mi5qcyIsInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///82\n"); /***/ }) });
1.195313
1
node_modules/css-vendor/tests/index.js
jlclementjr/material-dashboard
153
3447
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.supportedValue = exports.supportedProperty = exports.prefix = undefined; var _prefix = require('./prefix'); var _prefix2 = _interopRequireDefault(_prefix); var _supportedProperty = require('./supported-property'); var _supportedProperty2 = _interopRequireDefault(_supportedProperty); var _supportedValue = require('./supported-value'); var _supportedValue2 = _interopRequireDefault(_supportedValue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { prefix: _prefix2['default'], supportedProperty: _supportedProperty2['default'], supportedValue: _supportedValue2['default'] }; /** * CSS Vendor prefix detection and property feature testing. * * @copyright <NAME> 2015 * @website https://github.com/jsstyles/css-vendor * @license MIT */ exports.prefix = _prefix2['default']; exports.supportedProperty = _supportedProperty2['default']; exports.supportedValue = _supportedValue2['default'];
0.976563
1
packages/tools/f-vue-icons/icons/ReviewIcon.js
Preet-Sandhu/fozzie-components
13
3455
import _mergeJSXProps from "babel-helper-vue-jsx-merge-props"; export default { name: 'ReviewIcon', props: {}, functional: true, render: function render(h, ctx) { var attrs = ctx.data.attrs || {}; ctx.data.attrs = attrs; return h("svg", _mergeJSXProps([{ attrs: { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 16 16" }, "class": "c-ficon c-ficon--review" }, ctx.data]), [h("path", { attrs: { fill: "#333", d: "M7.432 6.16a.333.333 0 0 1-.25.183l-1.27.185.919.895a.333.333 0 0 1 .096.295L6.71 8.982l1.135-.597a.333.333 0 0 1 .31 0l1.135.597-.217-1.264a.333.333 0 0 1 .096-.295l.919-.895-1.27-.185a.333.333 0 0 1-.25-.182L8 5.01l-.568 1.15zm.27-2.05a.333.333 0 0 1 .597 0l.789 1.599 1.764.256c.273.04.382.376.185.57L9.76 7.777l.301 1.757a.333.333 0 0 1-.484.351L8 9.056l-1.577.83a.333.333 0 0 1-.484-.351l.3-1.757-1.276-1.244a.333.333 0 0 1 .185-.569l1.764-.256.79-1.599zm-4.23 7.953a3.853 3.853 0 0 1 2.195-.73H13a.333.333 0 0 0 .333-.333V3A.333.333 0 0 0 13 2.667H3A.333.333 0 0 0 2.667 3v9.867c.225-.303.496-.574.804-.804zM13 2a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H5.672a3.179 3.179 0 0 0-1.806.6 3.235 3.235 0 0 0-1.21 1.814c-.094.382-.656.313-.656-.08V3a1 1 0 0 1 1-1h10z" } })]); } };
1.015625
1
payload/gameOverride.js
jayden123sayshi/jayden
0
3463
window.gameFunctions = window.gameFunctions || {}; window.gameFunctions.gameOverride = function(){ this.override = true; // ZOOM var baseCameraTargetZoom = this[obfuscate.camera][obfuscate.targetZoom]; this[obfuscate.camera].__defineSetter__(obfuscate.targetZoom, function(val){ baseCameraTargetZoom = val; }); this[obfuscate.camera].__defineGetter__(obfuscate.targetZoom, function(){ if(window.gameVars && window.menu && window.menu.UserSetting.look.zoomEnabled) return window.gameVars.ZoomLevel; return baseCameraTargetZoom; }); var baseZoomFast = this[obfuscate.activePlayer].zoomFast; this[obfuscate.activePlayer].__defineSetter__("zoomFast", function(val){ baseZoomFast = val; }); this[obfuscate.activePlayer].__defineGetter__("zoomFast", function(){ if(window.menu && window.menu.UserSetting.look.zoomEnabled) return true; return baseZoomFast; }); // this[obfuscate.activePlayer][obfuscate.localData].inventory.soda = 1; // console.log(this[obfuscate.activePlayer][obfuscate.localData].inventory); // INPUT var inpt = this[obfuscate.input]; this[obfuscate.input].mouseButton = !1; this[obfuscate.input].mouseButtonOld = !1; this[obfuscate.input].rightMouseButton = !1; this[obfuscate.input].rightMouseButtonOld = !1 // console.log(inpt); var processInput = function(bind, down){ if(window.gameVars.Input.GlobalHookCallback) { if(bind.code == 27) { window.gameVars.Input.GlobalHookCallback.call(this, {code: 0, shift: false, ctrl: false, alt: false}); } else if(((bind.code == 16) || (bind.code == 17) || (bind.code == 18)) && (window.gameVars.Input.Keyboard.AnythingElsePressed == 0)) { if(down) return if(bind.code == 16) bind.shift = false; if(bind.code == 17) bind.ctrl = false; if(bind.code == 18) bind.alt = false; window.gameVars.Input.GlobalHookCallback.call(this, bind); } else if(down){ window.gameVars.Input.GlobalHookCallback.call(this, bind); } return; } // always pass Esc if(bind.code == 27) return keyboardEvent(27, down); var opt = window.menu.UserSetting.binds; if(checkBind(opt.autoAim, bind)) { window.gameVars.Input.Cheat.AutoAimPressed = down; }else if(checkBind(opt.switchMainWeapon, bind)) { window.gameVars.Input.Cheat.SwitchWeaponFirst = down; }else if(checkBind(opt.zoomIn, bind)) { window.gameVars.Input.Cheat.ZoomDelta += 1; }else if(checkBind(opt.zoomOut, bind)) { window.gameVars.Input.Cheat.ZoomDelta -= 1; }else if(checkBind(opt.displayNames, bind)) { window.gameVars.Input.Cheat.ShowNamesPressed = down; // }else if(checkBind(opt.streamerMode, bind)) { }else if(checkBind(opt.goUp, bind)) { keyboardEvent(87, down); }else if(checkBind(opt.goLeft, bind)) { keyboardEvent(65, down); }else if(checkBind(opt.goDown, bind)) { keyboardEvent(83, down); }else if(checkBind(opt.goRight, bind)) { keyboardEvent(68, down); }else if(checkBind(opt.shoot, bind)) { mouseButtonEvent(0, down); }else if(checkBind(opt.reload, bind)) { keyboardEvent(82, down); }else if(checkBind(opt.interact, bind)) { keyboardEvent(70, down); }else if(checkBind(opt.cancelAction, bind)) { keyboardEvent(88, down); }else if(checkBind(opt.teamPing, bind)) { triggerPing(down); }else if(checkBind(opt.emotes, bind)) { triggerEmote(down); }else if(checkBind(opt.toggleMap, bind)) { keyboardEvent(77, down); }else if(checkBind(opt.toggleMiniMap, bind)) { keyboardEvent(86, down); }else if(checkBind(opt.equipLast, bind)) { keyboardEvent(81, down); }else if(checkBind(opt.equipNext, bind)) { mouseWheelEvent(1); }else if(checkBind(opt.equipPrev, bind)) { mouseWheelEvent(-1); }else if(checkBind(opt.equipWeapon1, bind)) { keyboardEvent(49, down); }else if(checkBind(opt.equipWeapon2, bind)) { keyboardEvent(50, down); }else if(checkBind(opt.equipWeapon3, bind)) { keyboardEvent(51, down); }else if(checkBind(opt.equipWeapon4, bind)) { keyboardEvent(52, down); }else if(checkBind(opt.useMedical7, bind)) { keyboardEvent(55, down); }else if(checkBind(opt.useMedical8, bind)) { keyboardEvent(56, down); }else if(checkBind(opt.useMedical9, bind)) { keyboardEvent(57, down); }else if(checkBind(opt.useMedical0, bind)) { keyboardEvent(48, down); } } var checkBind = function(ref, bind){ try { return ref.code == bind.code && !(ref.shift && !bind.shift) && !(ref.ctrl && !bind.ctrl) && !(ref.alt && !bind.alt); } catch (err) { return false; } } document.addEventListener('mousedown', function(e) { // console.log(e.button); if((e.button == 2) || (window.gameVars.Input.GlobalHookCallback && (e.button == 0))){ processInput({code: e.button * -1 - 1, shift: e.shiftKey, ctrl: e.ctrlKey, alt: e.altKey}, true); } if(window.gameVars && window.gameVars.Menu) e.stopPropagation(); if(e.button == 0) { inpt.mouseButton = true; } if(e.button == 1) { e.preventDefault(); } }); document.addEventListener('mouseup', function(e) { if (e.button == 0) { inpt.mouseButton = false; } else if (e.button == 2) { processInput({code: e.button * -1 - 1, shift: e.shiftKey, ctrl: e.ctrlKey, alt: e.altKey}, false); } }); var keyboardEvent = function(code, down){ // console.log(down); down ? onKeyDownBase.call(inpt, {keyCode: code}) : onKeyUpBase.call(inpt, {keyCode: code}); } var mouseButtonEvent = function(buttonCode, down){ down ? onMouseDownBase.call(inpt, {button: buttonCode}) : onMouseUpBase.call(inpt, {button: buttonCode}); if(buttonCode == 0) { window.gameVars.Input.Cheat.FirePressed = down; } } var mouseWheelEvent = function(delta){ onMouseWheelBase.call(inpt, {deltaY: delta}); } var triggerEmote = function(down) { if(window.Pings && window.Pings.EmoteTrigger) window.Pings.EmoteTrigger(down) } var triggerPing = function(down) { if(window.Pings && window.Pings.PingTrigger) window.Pings.PingTrigger(down) } // keyboard var onKeyDownBase = function (e) { this.keys[e.keyCode] = !0, this.shiftKey |= e.shiftKey } // console.log(onKeyDownBase); this[obfuscate.input].onKeyDown = function(e){ // console.log("Key down!"); processInput({code: e.keyCode, shift: e.shiftKey, ctrl: e.ctrlKey, alt: e.altKey}, true); if(e.keyCode == 16) return window.gameVars.Input.Keyboard.ShiftPressed = true; if(e.keyCode == 17) return window.gameVars.Input.Keyboard.CtrlPressed = true; if(e.keyCode == 18) return window.gameVars.Input.Keyboard.AltPressed = true; window.gameVars.Input.Keyboard.AnythingElsePressed += 1; }; var onKeyUpBase = function (e) { delete this.keys[e.keyCode] }; this[obfuscate.input].onKeyUp = function(e){ processInput({code: e.keyCode, shift: e.shiftKey, ctrl: e.ctrlKey, alt: e.altKey}, false); if(e.keyCode == 16) return window.gameVars.Input.Keyboard.ShiftPressed = false; if(e.keyCode == 17) return window.gameVars.Input.Keyboard.CtrlPressed = false; if(e.keyCode == 18) return window.gameVars.Input.Keyboard.AltPressed = false; window.gameVars.Input.Keyboard.AnythingElsePressed -= 1; if(window.gameVars.Input.Keyboard.AnythingElsePressed < 0) window.gameVars.Input.Keyboard.AnythingElsePressed = 0; }; window.addEventListener("focus", function(event) { window.gameVars.Input.Keyboard.ShiftPressed = false; window.gameVars.Input.Keyboard.CtrlPressed = false; window.gameVars.Input.Keyboard.AltPressed = false; window.gameVars.Input.Keyboard.AnythingElsePressed = 0; }, false); // mouse var onMouseMoveBase = this[obfuscate.input].onMouseMove; this[obfuscate.input].onMouseMove = function(e){ if(window.gameVars){ window.gameVars.Input.Mouse.Pos.x = e.clientX; window.gameVars.Input.Mouse.Pos.y = e.clientY; if(window.gameVars.Input.Mouse.AimActive) { // e.clientX = window.gameVars.Input.Mouse.AimPos.x; // e.clientY = window.gameVars.Input.Mouse.AimPos.y; e = { clientX: window.gameVars.Input.Mouse.AimPos.x, clientY: window.gameVars.Input.Mouse.AimPos.y } } } onMouseMoveBase.call(inpt, e); }; var onMouseDownBase = function(e) { this.mouseButton = this.mouseButton || 0 === e.button, this.rightMouseButton = this.rightMouseButton || 2 === e.button }; // console.log(onMouseDownBase); onMouseDownBase = function(e){ processInput({code: e.button * -1 - 1, shift: e.shiftKey, ctrl: e.ctrlKey, alt: e.altKey}, true); }; var onMouseUpBase = function (e) { this.mouseButton = 0 !== e.button && this.mouseButton, this.rightMouseButton = 2 !== e.button && this.rightMouseButton }; onMouseUpBase = function(e){ processInput({code: e.button * -1 - 1, shift: e.shiftKey, ctrl: e.ctrlKey, alt: e.altKey}, false); }; var onMouseWheelBase = this[obfuscate.input].onMouseWheel; if (window.menu.UserSetting.look.zoomEnabled) { this[obfuscate.input].onMouseWheel = function(e){ e.stopPropagation(); if(window.gameVars && window.gameVars.Menu && !(window.gameVars.Input.GlobalHookCallback)) return; processInput({ code: e.deltaY < 0 ? -4 : -5, shift: window.gameVars.Input.Keyboard.ShiftPressed, ctrl: window.gameVars.Input.Keyboard.CtrlPressed, alt: window.gameVars.Input.Keyboard.AltPressed }, true); } } else { this[obfuscate.input].onMouseWheel = onMouseWheelBase; } var inputKeyPressedBase = this[obfuscate.input][obfuscate.keyPressed]; // console.log(inputKeyPressedBase); this[obfuscate.input][obfuscate.keyPressed] = function(e){ if(window.gameVars) { if(window.gameVars.Input.Cheat.RepeatInteraction && e == 70) return true; } return inputKeyPressedBase.call(inpt, e); }; var mousePressedFunc = function () { return !this.mouseButtonOld && this.mouseButton } var inputMousePressedBase = this[obfuscate.input][obfuscate.mouseDown]; this[obfuscate.input][obfuscate.mouseDown] = function(){ if(window.gameVars && window.gameVars.Input.Cheat.RepeatFire) return false; return inputMousePressedBase.call(inpt); }; var zHelper = function (e) { return void 0 !== this.keys[e] } var mouseDownFunc = function (e) { return this.keysOld[e] && !this.zHelper(e) } var inputMouseDownBase = this[obfuscate.input][obfuscate.mousePressed]; this[obfuscate.input][obfuscate.mousePressed] = function(){ if(window.gameVars && window.gameVars.Input.Cheat.RepeatFire) return true; return inputMouseDownBase.call(inpt); }; }
1.390625
1
tests/baselines/reference/sourceMap-Comment1.js
panagosg7/TypeScript-1.0.1.0
0
3471
//// [sourceMap-Comment1.ts] // Comment //// [sourceMap-Comment1.js] // Comment //# sourceMappingURL=sourceMap-Comment1.js.map
0.217773
0
test/helpers/sign.js
animocabrands/f1dt-ethereum-contracts
3
3479
function toEthSignedMessageHash(messageHex) { const messageBuffer = Buffer.from(messageHex.substring(2), 'hex'); const prefix = Buffer.from(`\u0019Ethereum Signed Message:\n${messageBuffer.length}`); return web3.utils.sha3(Buffer.concat([prefix, messageBuffer])); } function fixSignature(signature) { // in geth its always 27/28, in ganache its 0/1. Change to 27/28 to prevent // signature malleability if version is 0/1 // see https://github.com/ethereum/go-ethereum/blob/v1.8.23/internal/ethapi/api.go#L465 let v = parseInt(signature.slice(130, 132), 16); if (v < 27) { v += 27; } const vHex = v.toString(16); return signature.slice(0, 130) + vHex; } // signs message in node (ganache auto-applies "Ethereum Signed Message" prefix) async function signMessage(signer, messageHex = '0x') { return fixSignature(await web3.eth.sign(messageHex, signer)); } /** * Create a signer between a contract and a signer for a voucher of method, args, and redeemer * Note that `method` is the web3 method, not the truffle-contract method * @param contract TruffleContract * @param signer address * @param redeemer address * @param methodName string * @param methodArgs any[] */ const getSignFor = (contract, signer) => (redeemer, methodName, methodArgs = []) => { const parts = [contract.address, redeemer]; const REAL_SIGNATURE_SIZE = 2 * 65; // 65 bytes in hexadecimal string length const PADDED_SIGNATURE_SIZE = 2 * 96; // 96 bytes in hexadecimal string length const DUMMY_SIGNATURE = `0x${web3.utils.padLeft('', REAL_SIGNATURE_SIZE)}`; // if we have a method, add it to the parts that we're signing if (methodName) { if (methodArgs.length > 0) { parts.push( contract.contract.methods[methodName](...methodArgs.concat([DUMMY_SIGNATURE])) .encodeABI() .slice(0, -1 * PADDED_SIGNATURE_SIZE) ); } else { const abi = contract.abi.find((abi) => abi.name === methodName); parts.push(abi.signature); } } // return the signature of the "Ethereum Signed Message" hash of the hash of `parts` const messageHex = web3.utils.soliditySha3(...parts); return signMessage(signer, messageHex); }; module.exports = { signMessage, toEthSignedMessageHash, fixSignature, getSignFor, };
1.625
2
src/js/stocks/financialsAsReported.js
kaigong-iex/iexjs
53
3487
/* *************************************************************************** * * Copyright (c) 2021, the iexjs authors. * * This file is part of the iexjs library, distributed under the terms of * the Apache License 2.0. The full license can be found in the LICENSE file. * */ import { _raiseIfNotStr } from "../common"; import { Client } from "../client"; import { timeSeries } from "../timeseries"; /** * Get company's 10-Q statement * * @param {object} options `timeseries` options * @param {string} options.symbol company symbol * @param {object} standardOptions * @param {string} standardOptions.token Access token * @param {string} standardOptions.version API version * @param {string} standardOptions.filter https://iexcloud.io/docs/api/#filter-results * @param {string} standardOptions.format output format */ export const tenQ = (options, { token, version, filter, format } = {}) => { const { symbol } = options; _raiseIfNotStr(symbol); return timeSeries( { id: "REPORTED_FINANCIALS", key: symbol, subkey: "10-Q", ...(options || {}), }, { token, version, filter, format }, ); }; Client.prototype.tenQ = function (options, standardOptions) { return tenQ(options, { token: this._token, version: this._version, ...standardOptions, }); }; /** * Get company's 10-K statement * * @param {object} options `timeseries` options * @param {string} options.symbol company symbol * @param {object} standardOptions * @param {string} standardOptions.token Access token * @param {string} standardOptions.version API version * @param {string} standardOptions.filter https://iexcloud.io/docs/api/#filter-results * @param {string} standardOptions.format output format */ export const tenK = (options, { token, version, filter, format } = {}) => { const { symbol } = options; _raiseIfNotStr(symbol); return timeSeries( { id: "REPORTED_FINANCIALS", key: symbol, subkey: "10-K", ...(options || {}), }, { token, version, filter, format }, ); }; Client.prototype.tenK = function (options, standardOptions) { return tenK(options, { token: this._token, version: this._version, ...standardOptions, }); }; /** * Get company's 20-F statement * * @param {object} options `timeseries` options * @param {string} options.symbol company symbol * @param {object} standardOptions * @param {string} standardOptions.token Access token * @param {string} standardOptions.version API version * @param {string} standardOptions.filter https://iexcloud.io/docs/api/#filter-results * @param {string} standardOptions.format output format */ export const twentyF = (options, { token, version, filter, format } = {}) => { const { symbol } = options; _raiseIfNotStr(symbol); return timeSeries( { id: "REPORTED_FINANCIALS", key: symbol, subkey: "20-F", ...(options || {}), }, { token, version, filter, format }, ); }; Client.prototype.twentyF = function (options, standardOptions) { return twentyF(options, { token: this._token, version: this._version, ...standardOptions, }); }; /** * Get company's 40-F statement * * @param {object} options `timeseries` options * @param {string} options.symbol company symbol * @param {object} standardOptions * @param {string} standardOptions.token Access token * @param {string} standardOptions.version API version * @param {string} standardOptions.filter https://iexcloud.io/docs/api/#filter-results * @param {string} standardOptions.format output format */ export const fortyF = (options, { token, version, filter, format } = {}) => { const { symbol } = options; _raiseIfNotStr(symbol); return timeSeries( { id: "REPORTED_FINANCIALS", key: symbol, subkey: "40-F", ...(options || {}), }, { token, version, filter, format }, ); }; Client.prototype.fortyF = function (options, standardOptions) { return fortyF(options, { token: this._token, version: this._version, ...standardOptions, }); };
1.195313
1
src/components/Button/404-button.js
vinczun/terminal-app
0
3495
import React from 'react'; import { Link } from 'gatsby'; import '../../styles/404-button.scss'; const Button4 = () => ( <Link to='/' className='button-4' role='button'> Back to homepage </Link> ); export default Button4;
0.96875
1
src/remoteObject.js
davecoates/value-mirror
0
3503
// @flow import type { RemoteObjectId } from './types'; // Maintain a reference to an object while it is still needed (eg. not fully expanded) const objectById = new Map(); // Store object id by object so we can reuse ID's if same value is passed again const idByObject = new WeakMap(); let nextObjectId = 1; export function acquireObjectId(value:any) : RemoteObjectId { if (idByObject.has(value)) { return idByObject.get(value); } const objectId = nextObjectId++; objectById.set(objectId, value); idByObject.set(value, objectId); return objectId; } export function getObject(objectId: RemoteObjectId) : any { return objectById.get(objectId); } export function releaseObject(objectId: RemoteObjectId) : boolean { return objectById.delete(objectId); } export function getObjectId(value: any) : ?RemoteObjectId { return idByObject.get(value); }
1.976563
2
src/services/blocks/blocksListener.js
rsksmart/rsk-explorer-api
14
3511
import { createService, services, bootStrapService } from '../serviceFactory' import { ListenBlocks } from '../classes/ListenBlocks' const serviceConfig = services.LISTENER const executor = ({ create }) => { create.Emitter() } async function main () { try { const { log, db, initConfig } = await bootStrapService(serviceConfig) const { service, startService } = await createService(serviceConfig, executor, { log }) await startService() const listener = new ListenBlocks(db, { log, initConfig }, service) listener.start() } catch (err) { console.error(err) process.exit(9) } } main()
1.140625
1
server/controllers/ticketsController.js
Just5Coders/snapdesk
5
3519
/** * ************************************ * * @author Joshua * @date 2/21/20 * @description get tickets data from db middleware * * ************************************ */ // import access to database const db = require('../models/userModel'); const ticketsController = {}; ticketsController.getActiveTickets = (req, res, next) => { const getActiveTickets = ` SELECT t._id, t.snaps_given, t.message, t.status, t.timestamp, t.mentee_id, t.mentor_id, u2.name as mentee_name, t.topic FROM tickets t FULL OUTER JOIN users u ON u._id = t.mentor_id INNER JOIN users u2 ON u2._id = t.mentee_id WHERE t.status = 'active' OR status = 'pending' ORDER BY t._id `; db.query(getActiveTickets) .then(({ rows }) => { const formatTickets = rows.map(ticket => ({ messageInput: ticket.message, messageRating: ticket.snaps_given, messageId: ticket._id, menteeId: ticket.mentee_id, mentorName: ticket.mentor_name,//added menteeName: ticket.mentee_name,//added timestamp: ticket.timpestamp, status: ticket.status, mentorId: ticket.mentor_id || '', topic: ticket.topic, })) res.locals.activeTickets = formatTickets; return next(); }) .catch(err => next({ log: `Error in middleware ticketsController.addNewTicket: ${err}` })) } ticketsController.addTicket = (req, res, next) => { const { snaps_given, mentee_id, status, message, topic } = req.body; const addTicket = { text: ` INSERT INTO tickets (snaps_given, mentee_id, status, message, timestamp, topic) VALUES ($1, $2, $3, $4, NOW(), $5) RETURNING _id, timestamp, mentee_id, topic; `, values: [snaps_given, mentee_id, status, message, topic] } db.query(addTicket) .then(ticket => { res.locals.ticketId = ticket.rows[0]._id; res.locals.timestamp = ticket.rows[0].timestamp; res.locals.menteeId = ticket.rows[0].mentee_id; res.locals.topic = ticket.rows[0].topic; return next(); }) .catch(err => next({ log: `Error in middleware ticketsController.addNewTicket: ${err}` })) } ticketsController.updateTicketStatus = (req, res, next) => { const { status, ticketId } = req.body; const updateTicket = { text: ` UPDATE tickets SET status = $1 WHERE _id = $2; `, values: [status, ticketId] } db.query(updateTicket) .then(success => next()) .catch(err => next({ log: `Error in middleware ticketsController.updateTicket: ${err}` })); } ticketsController.cancelTicket = (req, res, next) => { const { status, messageId, mentorId } = req.body; const cancelTicket = { text: `UPDATE tickets SET status = $1, mentor_id = $3 WHERE _id = $2;`, values: [status, messageId, mentorId] }; db.query(cancelTicket) .then(data => { return next(); }) .catch(err => next({ log: `Error in middleware ticketsController.cancelTicket: ${err}` })); } ticketsController.acceptTicket = (req, res, next) => { const { status, ticketId, mentorId } = req.body; const acceptTicket = { text: ` UPDATE tickets SET status = $1, mentor_id = $3 WHERE _id = $2; `, values: [status, ticketId, mentorId], } db.query(acceptTicket) .then((response) => { return next(); }) .catch(err => { console.log('Error: ', err); return next(err) }); }; ticketsController.resolveTicket = (req, res, next) =>{ const { status, messageId, messageRating, feedback } = req.body; const resolveTicket = { text: `UPDATE tickets SET status = $1, snaps_given = $3, feedback = $4 WHERE _id = $2;`, values: [status, messageId, messageRating, feedback] } db.query(resolveTicket) .then((result) => { return next(); }) .catch(err =>{ console.log('Error: ', err); return next(err); }); }; module.exports = ticketsController;
1.523438
2
skillsquire/views/admin_views/controllers/resource.edit.controller.js
joryschmidt/hosted_jorys
0
3527
angular.module('admin') .controller('resourceEditCtrl', ['$http', '$scope', '$routeParams', '$location', function($http, $scope, $routeParams, $location) { $http.get('/skillsquire/admin/resource/' + $routeParams.id).then(function(res) { console.log('success'); $scope.resource = res.data; $scope.submit = function() { $http({method: 'PUT', url: '/skillsquire/admin/resource/edit/' + $routeParams.id, data: $scope.resource }).then(function(response) { // Having serious problems trying to get Angular to send resource.categories anything but an empty array, so this will have to do for now console.log('sent to mongo'); for (var cat in $scope.categories) { if ($scope.categories[cat] == true) { $http.put('/skillsquire/admin/resource/add_category/' + $routeParams.id, { cat: cat }).then(function() { console.log('Updated category'); }, function(err) { console.log(err); }); } else { $http.put('/skillquire/admin/resource/remove_category/' + $routeParams.id, { cat: cat }).then(function() { console.log('Removed category'); }, function(err) { console.log(err); }); } } }, function(response) { console.log(response.data); }); $location.path('/skillsquire/'); }; // This will add new categories to the database $scope.addNewCategory = function() { $http.put('/skillsquire/categories/add', { cat: $scope.newCat }).then(function(q) { console.log('Added category'); $scope.categories[$scope.newCat] = false; $scope.newCat = null; }, function(err) { console.log('Error: ', err); }); }; $http.get('/skillsquire/categories').then(function(q) { $scope.categories = {}; // this is so the in operator works in the next loop and we don't have to loop through the resource categories array for every checkbox var cat_object = {}; for (var i=0; i<$scope.resource.categories.length; i++) { cat_object[$scope.resource.categories[i]] = true; } var categories = q.data.categories; var len = categories.length; for (var i=0; i<len; i++) { $scope.categories[categories[i]] = categories[i] in cat_object; } }, function() { console.log('No cats :('); }); console.log($scope.resource); }); }]);
1.351563
1
src/ui/src/app/loading/Loading.js
PythonDataIntegrator/pythondataintegrator
14
3535
import React, { useState, useEffect } from "react"; import Backdrop from '@material-ui/core/Backdrop'; import CircularProgress from '@material-ui/core/CircularProgress'; import { makeStyles } from '@material-ui/core/styles'; import { useDispatch, useSelector } from 'react-redux'; import withReducer from 'app/store/withReducer'; import reducer from './store'; import { initialState } from './store/loadingSlice'; const useStyles = makeStyles(theme => ({ backdrop: { zIndex: theme.zIndex.drawer + 1, color: '#fff', }, })); const Loading = () => { const classes = useStyles(); // const openBackdrop = initialState.loading const openBackdrop = useSelector(({ loading }) => { return loading.loading.loading }); // const [openBackdrop, setOpenBackdrop] = React.useState(true); // const handleBackdropClose = () => { // setOpenBackdrop(false); // }; // const handleToggle = () => { // setOpenBackdrop(true); // }; return ( <div> <Backdrop className={classes.backdrop} open={openBackdrop} > <CircularProgress color="inherit" /> </Backdrop> </div> ) } export default withReducer('loading', reducer)(Loading);
1.492188
1
client/src/components/Landing/Landing.js
vivekmalva/audit-review-tool
0
3543
import React from 'react'; const Landing = () => { return ( <div style={{ textAlign: 'center' }}> <h1> Audit Review Tool </h1> <p>A project auditing tool</p> </div> ); }; export default Landing;
0.683594
1
11-21/demo02/src/pages/Page8/index.js
ZiCo11/React-demo
0
3551
import Page8 from './Page8'; export default Page8;
-0.08252
0
src/component/main/contact-form/index.js
sdmccoy/portfolio
0
3559
import React from 'react'; import {Link} from 'react-router-dom'; import './_contact-form.scss'; class ContactForm extends React.Component { constructor(props){ super(props); this.state = { }; } render(){ return( <div className='contact-container'> <h2 className='headline'> CONTACT </h2> <h4>Peruse, Connect, and Message!</h4> <div className='linkedin-container'> <Link to='https://www.linkedin.com/in/sdmccoy/' className='nav-icon' target='_blank'> <i className='fa fa-linkedin-square' aria-hidden='true'></i> </Link> </div> </div> ); } } export default ContactForm;
1.265625
1
test/tfs.js
yanmingsohu/nfs-cassandra-node
0
3567
module.exports = require('./test-base.js')(tfs_main); function tfs_main(driver) { var fs, hdid; var hdfs = require('fs'); var gid_uid = parseInt(10 * Math.random()) + 1; var mode = parseInt(0x777 * Math.random())+1; var now = Date.now(); var dir2remove_a= false; var append_buf = Math.random() > 0.5 ? '-' : '_'; var filecontent = new Buffer(4096*3 + 1); try { hdid = hdfs.readFileSync(__dirname + '/driver-id', {encoding:'UTF-8'}); hdid = hdid.trim(); } catch(e) { throw new Error('Run "tdriver.js" first.'); } for (var i=0,e=filecontent.length; i<e; ++i) { filecontent[i] = parseInt(Math.random() * 255); } function arrhas(arr, item) { for (var i=0,e=arr.length; i<e; ++i) { if (arr[i] == item) return true; } return false; } return { note : 'FS base', open_fs: function(test) { driver.open_fs(hdid, function(err, _fs) { fs = _fs; test.assert(err); test.assert(_fs != null, 'cannot get fs'); test.finish(); }); }, watch1: function(test) { test.wait('open_fs'); var w1 = fs.watch('/dir2', { recursive: true, persistent:true }, function(type, fname) { test.log(type, fname); }); w1.on('error', function(err) { test.assert(err); }); var w2 = fs.watch('/dir1/need-delete', function(type, fname) { test.log(type, fname); }); test.finish(); }, mkdir1 : function(test) { test.wait('open_fs', 'watch1'); fs.mkdir('/dir1', function(err) { if (err && err.code != 'EEXIST') test.assert(err); test.finish(); }); }, mkdir2 : function(test) { test.wait('mkdir1') fs.mkdir('/dir2', function(err) { if (err && err.code != 'EEXIST') test.assert(err); test.finish(); }); }, mkdir2a : function(test) { test.wait('mkdir2') fs.mkdir('/dir2/a', function(err) { if (err && err.code != 'EEXIST') test.assert(err); test.finish(); }); }, mkdir3 : function(test) { test.wait('mkdir2') fs.mkdir('/dir1/a', function(err) { if (err && err.code != 'EEXIST') test.assert(err); test.finish(); }); }, mkdir4 : function(test) { test.wait('mkdir3'); fs.mkdir('/dir1/b', function(err) { if (err && err.code != 'EEXIST') test.assert(err); test.finish(); }); }, list1: function(test) { test.wait('mkdir4'); fs.readdir('/', function(err, list) { test.assert(err); test.assert(arrhas(list, 'dir1'), list); test.assert(arrhas(list, 'dir2'), list); test.finish(); }); }, list2: function(test) { test.wait('mkdir4'); fs.readdir('/dir1', function(err, list) { test.assert(err); test.assert(arrhas(list, 'a'), list); test.assert(arrhas(list, 'b'), list); test.finish(); }); }, list3: function(test) { test.wait('mkdir2a'); fs.readdir('/dir2', function(err, list) { test.assert(err); if (dir2remove_a) { list.forEach(function(f) { test.assert(f != 'a', '/dir2/a not remove'); }); } test.finish(); }); }, rm_dir_fail: function(test) { test.wait('list2', 'mkdir2a'); fs.rmdir('/dir2', function(err) { test.assert(err != null, '非空文件夹不应该被删除'); test.finish(); }); }, rm_dir: function(test) { test.wait('list2', 'mkdir2a', 'rm_dir_fail'); fs.rmdir('/dir2/a', function(err) { test.assert(err); dir2remove_a = true; test.retest('list3'); test.finish(); }); }, 'update time': function(test) { test.wait('mkdir1'); fs.utimes('/dir1', now, now, function(err) { // test.log(now); test.assert(err); test.finish(); }); }, 'change-owner': function(test) { test.wait('mkdir1'); fs.chown('/dir1', gid_uid, gid_uid, function(err) { // test.log(gid_uid); test.assert(err); test.finish(); }); }, 'change-mode' : function(test) { test.wait('mkdir1'); fs.chmod('/dir1', mode, function(err) { // test.log(mode); test.assert(err); test.finish(); }); }, 'link-state' : function(test) { test.wait('mkdir1', 'update time', 'change-owner', 'change-mode'); fs.lstat('/dir1', function(err, stat) { test.assert(err); if (stat) { test.assert(stat.atime.getTime() == now, 'atime not change'); test.assert(stat.mtime.getTime() == now, 'mtime not change'); test.assert(stat.mode == mode, 'mode not change'); test.assert(stat.gid == gid_uid, 'gid not change'); test.assert(stat.uid == gid_uid, 'uid not change'); //test.log('/dir1', stat); } test.finish(); }); }, 'write-file': function(test) { test.wait('mkdir2'); fs.writeFile('/dir2/t.txt', filecontent, function(err, size, buffer) { test.assert(buffer != null, 'cannot get buffer:'); test.assert(size == buffer.length, 'cannot write file size: ' + size + '->' + buffer.length); test.assert(err); test.finish(); }); }, 'mkdir-for-rename': function(test) { test.wait('write-file'); fs.unlink('/rename-target/t.doc', function() { fs.rmdir('/rename-target', function() { fs.mkdir('/rename-target', function(err) { //test.assert(err); test.finish(); }); }) }); }, 'rename' : function(test) { test.wait('mkdir-for-rename'); fs.rename('/dir2/t.txt', '/rename-target/t.doc', function(err) { test.assert(err); test.finish(); }); }, 'read-file': function(test) { test.wait('rename'); fs.readFile('/rename-target/t.doc', function(err, buffer, size) { if (!err) { var showLen = 100; test.assert(size == buffer.length, 'size fail1 ' + buffer.length); test.assert(size == filecontent.length, 'size fail2 ' + filecontent.length); for (var i=0; i<size; ++i) { if (buffer[i] != filecontent[i]) { test.assert(false, 'file content fail at ' + i + '['+size+']'); test.log('src:', filecontent.slice(i-showLen, i+showLen)); test.log('fs: ', buffer.slice(i-showLen, i+showLen)); break; } } } test.assert(err); test.finish(); }); }, 'append' : function(test) { test.wait('mkdir2'); fs.appendFile('/dir2/append.txt', append_buf, function(err) { test.assert(err); test.finish(); }); }, 'read-append' : function(test) { test.wait('append'); fs.readFile('/dir2/append.txt', function(err, size, buffer) { if (buffer) { // test.log(size, buffer.slice(size-5, size).toString()); test.assert(buffer[buffer.length-1] == append_buf[0]); } test.assert(err); test.finish(); }); }, 'make-deled-txt' : function(test) { test.wait('mkdir1'); fs.writeFile('/dir1/need-delete', 'delete', function(err, size, buffer) { test.assert(err); test.finish(); }); }, 'remove-txt' : function(test) { test.wait('make-deled-txt'); fs.unlink('/dir1/need-delete', function(err) { test.assert(err); test.finish(); }); }, quit: function(test) { test.wait('change-mode', 'update time', 'list1', 'list2', 'read-append', 'rm_dir', 'change-owner', 'link-state', 'write-file', 'read-file', 'remove-txt', 'watch1'); fs.quit(function(err) { test.finish(); }); }, }; }
1.382813
1
test/web/crypto.spec.js
buttercup/app-env
2
3575
describe("crypto", function() { const { "app-env": { getSharedAppEnv } } = window; function arrayBuffersEqual(buf1, buf2) { if (buf1.byteLength != buf2.byteLength) return false; const dv1 = new Uint8Array(buf1); const dv2 = new Uint8Array(buf2); for (let i = 0; i <= buf1.byteLength; i += 1) { if (dv1[i] !== dv2[i]) return false; } return true; } describe("encryption", function() { it("can encrypt text", function() { const encrypt = getSharedAppEnv().getProperty("crypto/v1/encryptText"); const decrypt = getSharedAppEnv().getProperty("crypto/v1/decryptText"); return encrypt("test", "pass") .then(enc => decrypt(enc, "pass")) .then(res => { expect(res).to.equal("test"); }); }); it("can encrypt buffers", function() { const encrypt = getSharedAppEnv().getProperty("crypto/v1/encryptBuffer"); const decrypt = getSharedAppEnv().getProperty("crypto/v1/decryptBuffer"); const arr = new Uint8Array([0xff, 0x01, 0x45, 0xf5, 0x80, 0xac, 0xf4]); const buff = arr.buffer; return encrypt(arr, "pass") .then(enc => decrypt(enc, "pass")) .then(res => { expect(res).to.satisfy(buff2 => arrayBuffersEqual(buff2, buff)); }); }); }); });
1.757813
2
public/modules/product-brands/config/product-brands.client.routes.js
kruny1001/clippers
0
3583
'use strict'; //Setting up route angular.module('product-brands').config(['$stateProvider', function($stateProvider) { // Product brands state routing $stateProvider. state('listProductBrands', { url: '/product-brands', templateUrl: 'modules/product-brands/views/list-product-brands.client.view.html' }). state('createProductBrand', { url: '/product-brands/create', templateUrl: 'modules/product-brands/views/create-product-brand.client.view.html' }). state('viewProductBrand', { url: '/product-brands/:productBrandId', templateUrl: 'modules/product-brands/views/view-product-brand.client.view.html' }). state('editProductBrand', { url: '/product-brands/:productBrandId/edit', templateUrl: 'modules/product-brands/views/edit-product-brand.client.view.html' }); } ]);
1.117188
1
node_modules/handsontable/plugins/nestedRows/nestedRows.js
mingjieATuber/MandADemo
0
3591
"use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } require("core-js/modules/es.object.set-prototype-of.js"); require("core-js/modules/es.object.get-prototype-of.js"); require("core-js/modules/es.reflect.construct.js"); require("core-js/modules/es.reflect.get.js"); require("core-js/modules/es.object.get-own-property-descriptor.js"); require("core-js/modules/es.symbol.js"); require("core-js/modules/es.symbol.description.js"); require("core-js/modules/es.symbol.iterator.js"); require("core-js/modules/es.array.slice.js"); require("core-js/modules/es.function.name.js"); exports.__esModule = true; exports.NestedRows = exports.PLUGIN_PRIORITY = exports.PLUGIN_KEY = void 0; require("core-js/modules/es.array.iterator.js"); require("core-js/modules/es.object.to-string.js"); require("core-js/modules/es.string.iterator.js"); require("core-js/modules/es.weak-map.js"); require("core-js/modules/web.dom-collections.iterator.js"); require("core-js/modules/web.timers.js"); require("core-js/modules/es.array.from.js"); require("core-js/modules/es.array.reduce.js"); require("core-js/modules/web.dom-collections.for-each.js"); require("core-js/modules/es.set.js"); var _base = require("../base"); var _dataManager = _interopRequireDefault(require("./data/dataManager")); var _collapsing = _interopRequireDefault(require("./ui/collapsing")); var _headers = _interopRequireDefault(require("./ui/headers")); var _contextMenu = _interopRequireDefault(require("./ui/contextMenu")); var _console = require("../../helpers/console"); var _data = require("../../helpers/data"); var _translations = require("../../translations"); var _rowMoveController = _interopRequireDefault(require("./utils/rowMoveController")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } var PLUGIN_KEY = 'nestedRows'; exports.PLUGIN_KEY = PLUGIN_KEY; var PLUGIN_PRIORITY = 300; exports.PLUGIN_PRIORITY = PLUGIN_PRIORITY; var privatePool = new WeakMap(); /** * Error message for the wrong data type error. */ var WRONG_DATA_TYPE_ERROR = 'The Nested Rows plugin requires an Array of Objects as a dataset to be' + ' provided. The plugin has been disabled.'; /** * @plugin NestedRows * @class NestedRows * * @description * Plugin responsible for displaying and operating on data sources with nested structures. */ var NestedRows = /*#__PURE__*/function (_BasePlugin) { _inherits(NestedRows, _BasePlugin); var _super = _createSuper(NestedRows); function NestedRows(hotInstance) { var _this; _classCallCheck(this, NestedRows); _this = _super.call(this, hotInstance); /** * Reference to the DataManager instance. * * @private * @type {object} */ _this.dataManager = null; /** * Reference to the HeadersUI instance. * * @private * @type {object} */ _this.headersUI = null; /** * Map of skipped rows by plugin. * * @private * @type {null|TrimmingMap} */ _this.collapsedRowsMap = null; privatePool.set(_assertThisInitialized(_this), { movedToCollapsed: false, skipRender: null, skipCoreAPIModifiers: false }); return _this; } /** * Checks if the plugin is enabled in the handsontable settings. This method is executed in {@link Hooks#beforeInit} * hook and if it returns `true` than the {@link NestedRows#enablePlugin} method is called. * * @returns {boolean} */ _createClass(NestedRows, [{ key: "isEnabled", value: function isEnabled() { return !!this.hot.getSettings()[PLUGIN_KEY]; } /** * Enables the plugin functionality for this Handsontable instance. */ }, { key: "enablePlugin", value: function enablePlugin() { var _this2 = this; if (this.enabled) { return; } this.collapsedRowsMap = this.hot.rowIndexMapper.registerMap('nestedRows', new _translations.TrimmingMap()); this.dataManager = new _dataManager.default(this, this.hot); this.collapsingUI = new _collapsing.default(this, this.hot); this.headersUI = new _headers.default(this, this.hot); this.contextMenuUI = new _contextMenu.default(this, this.hot); this.rowMoveController = new _rowMoveController.default(this); this.addHook('afterInit', function () { return _this2.onAfterInit.apply(_this2, arguments); }); this.addHook('beforeRender', function () { return _this2.onBeforeRender.apply(_this2, arguments); }); this.addHook('modifyRowData', function () { return _this2.onModifyRowData.apply(_this2, arguments); }); this.addHook('modifySourceLength', function () { return _this2.onModifySourceLength.apply(_this2, arguments); }); this.addHook('beforeDataSplice', function () { return _this2.onBeforeDataSplice.apply(_this2, arguments); }); this.addHook('beforeDataFilter', function () { return _this2.onBeforeDataFilter.apply(_this2, arguments); }); this.addHook('afterContextMenuDefaultOptions', function () { return _this2.onAfterContextMenuDefaultOptions.apply(_this2, arguments); }); this.addHook('afterGetRowHeader', function () { return _this2.onAfterGetRowHeader.apply(_this2, arguments); }); this.addHook('beforeOnCellMouseDown', function () { return _this2.onBeforeOnCellMouseDown.apply(_this2, arguments); }); this.addHook('beforeRemoveRow', function () { return _this2.onBeforeRemoveRow.apply(_this2, arguments); }); this.addHook('afterRemoveRow', function () { return _this2.onAfterRemoveRow.apply(_this2, arguments); }); this.addHook('beforeAddChild', function () { return _this2.onBeforeAddChild.apply(_this2, arguments); }); this.addHook('afterAddChild', function () { return _this2.onAfterAddChild.apply(_this2, arguments); }); this.addHook('beforeDetachChild', function () { return _this2.onBeforeDetachChild.apply(_this2, arguments); }); this.addHook('afterDetachChild', function () { return _this2.onAfterDetachChild.apply(_this2, arguments); }); this.addHook('modifyRowHeaderWidth', function () { return _this2.onModifyRowHeaderWidth.apply(_this2, arguments); }); this.addHook('afterCreateRow', function () { return _this2.onAfterCreateRow.apply(_this2, arguments); }); this.addHook('beforeRowMove', function () { return _this2.onBeforeRowMove.apply(_this2, arguments); }); this.addHook('beforeLoadData', function (data) { return _this2.onBeforeLoadData(data); }); _get(_getPrototypeOf(NestedRows.prototype), "enablePlugin", this).call(this); } /** * Disables the plugin functionality for this Handsontable instance. */ }, { key: "disablePlugin", value: function disablePlugin() { this.hot.rowIndexMapper.unregisterMap('nestedRows'); _get(_getPrototypeOf(NestedRows.prototype), "disablePlugin", this).call(this); } /** * Updates the plugin state. This method is executed when {@link Core#updateSettings} is invoked. */ }, { key: "updatePlugin", value: function updatePlugin() { this.disablePlugin(); var vanillaSourceData = this.hot.getSourceData(); this.enablePlugin(); this.dataManager.updateWithData(vanillaSourceData); _get(_getPrototypeOf(NestedRows.prototype), "updatePlugin", this).call(this); } /** * `beforeRowMove` hook callback. * * @private * @param {Array} rows Array of visual row indexes to be moved. * @param {number} finalIndex Visual row index, being a start index for the moved rows. Points to where the elements * will be placed after the moving action. To check the visualization of the final index, please take a look at * [documentation](@/guides/rows/row-summary.md). * @param {undefined|number} dropIndex Visual row index, being a drop index for the moved rows. Points to where we * are going to drop the moved elements. To check visualization of drop index please take a look at * [documentation](@/guides/rows/row-summary.md). * @param {boolean} movePossible Indicates if it's possible to move rows to the desired position. * @fires Hooks#afterRowMove * @returns {boolean} */ }, { key: "onBeforeRowMove", value: function onBeforeRowMove(rows, finalIndex, dropIndex, movePossible) { return this.rowMoveController.onBeforeRowMove(rows, finalIndex, dropIndex, movePossible); } /** * Enable the modify hook skipping flag - allows retrieving the data from Handsontable without this plugin's * modifications. */ }, { key: "disableCoreAPIModifiers", value: function disableCoreAPIModifiers() { var priv = privatePool.get(this); priv.skipCoreAPIModifiers = true; } /** * Disable the modify hook skipping flag. */ }, { key: "enableCoreAPIModifiers", value: function enableCoreAPIModifiers() { var priv = privatePool.get(this); priv.skipCoreAPIModifiers = false; } /** * `beforeOnCellMousedown` hook callback. * * @private * @param {MouseEvent} event Mousedown event. * @param {object} coords Cell coords. * @param {HTMLElement} TD Clicked cell. */ }, { key: "onBeforeOnCellMouseDown", value: function onBeforeOnCellMouseDown(event, coords, TD) { this.collapsingUI.toggleState(event, coords, TD); } /** * The modifyRowData hook callback. * * @private * @param {number} row Visual row index. * @returns {boolean} */ }, { key: "onModifyRowData", value: function onModifyRowData(row) { var priv = privatePool.get(this); if (priv.skipCoreAPIModifiers) { return; } return this.dataManager.getDataObject(row); } /** * Modify the source data length to match the length of the nested structure. * * @private * @returns {number} */ }, { key: "onModifySourceLength", value: function onModifySourceLength() { var priv = privatePool.get(this); if (priv.skipCoreAPIModifiers) { return; } return this.dataManager.countAllRows(); } /** * @private * @param {number} index The index where the data was spliced. * @param {number} amount An amount of items to remove. * @param {object} element An element to add. * @returns {boolean} */ }, { key: "onBeforeDataSplice", value: function onBeforeDataSplice(index, amount, element) { var priv = privatePool.get(this); if (priv.skipCoreAPIModifiers || this.dataManager.isRowHighestLevel(index)) { return true; } this.dataManager.spliceData(index, amount, element); return false; } /** * Called before the source data filtering. Returning `false` stops the native filtering. * * @private * @param {number} index The index where the data filtering starts. * @param {number} amount An amount of rows which filtering applies to. * @param {number} physicalRows Physical row indexes. * @returns {boolean} */ }, { key: "onBeforeDataFilter", value: function onBeforeDataFilter(index, amount, physicalRows) { var priv = privatePool.get(this); this.collapsingUI.collapsedRowsStash.stash(); this.collapsingUI.collapsedRowsStash.trimStash(physicalRows[0], amount); this.collapsingUI.collapsedRowsStash.shiftStash(physicalRows[0], null, -1 * amount); this.dataManager.filterData(index, amount, physicalRows); priv.skipRender = true; return false; } /** * `afterContextMenuDefaultOptions` hook callback. * * @private * @param {object} defaultOptions The default context menu items order. * @returns {boolean} */ }, { key: "onAfterContextMenuDefaultOptions", value: function onAfterContextMenuDefaultOptions(defaultOptions) { return this.contextMenuUI.appendOptions(defaultOptions); } /** * `afterGetRowHeader` hook callback. * * @private * @param {number} row Row index. * @param {HTMLElement} TH Row header element. */ }, { key: "onAfterGetRowHeader", value: function onAfterGetRowHeader(row, TH) { this.headersUI.appendLevelIndicators(row, TH); } /** * `modifyRowHeaderWidth` hook callback. * * @private * @param {number} rowHeaderWidth The initial row header width(s). * @returns {number} */ }, { key: "onModifyRowHeaderWidth", value: function onModifyRowHeaderWidth(rowHeaderWidth) { return this.headersUI.rowHeaderWidthCache || rowHeaderWidth; } /** * `onAfterRemoveRow` hook callback. * * @private * @param {number} index Removed row. * @param {number} amount Amount of removed rows. * @param {Array} logicRows An array of the removed physical rows. * @param {string} source Source of action. */ }, { key: "onAfterRemoveRow", value: function onAfterRemoveRow(index, amount, logicRows, source) { var _this3 = this; if (source === this.pluginName) { return; } var priv = privatePool.get(this); setTimeout(function () { priv.skipRender = null; _this3.headersUI.updateRowHeaderWidth(); _this3.collapsingUI.collapsedRowsStash.applyStash(); }, 0); } /** * Callback for the `beforeRemoveRow` change list of removed physical indexes by reference. Removing parent node * has effect in removing children nodes. * * @private * @param {number} index Visual index of starter row. * @param {number} amount Amount of rows to be removed. * @param {Array} physicalRows List of physical indexes. */ }, { key: "onBeforeRemoveRow", value: function onBeforeRemoveRow(index, amount, physicalRows) { var _this4 = this; var modifiedPhysicalRows = Array.from(physicalRows.reduce(function (removedRows, physicalIndex) { if (_this4.dataManager.isParent(physicalIndex)) { var children = _this4.dataManager.getDataObject(physicalIndex).__children; // Preserve a parent in the list of removed rows. removedRows.add(physicalIndex); if (Array.isArray(children)) { // Add a children to the list of removed rows. children.forEach(function (child) { return removedRows.add(_this4.dataManager.getRowIndex(child)); }); } return removedRows; } // Don't modify list of removed rows when already checked element isn't a parent. return removedRows.add(physicalIndex); }, new Set())); // Modifying hook's argument by the reference. physicalRows.length = 0; physicalRows.push.apply(physicalRows, _toConsumableArray(modifiedPhysicalRows)); } /** * `beforeAddChild` hook callback. * * @private */ }, { key: "onBeforeAddChild", value: function onBeforeAddChild() { this.collapsingUI.collapsedRowsStash.stash(); } /** * `afterAddChild` hook callback. * * @private * @param {object} parent Parent element. * @param {object} element New child element. */ }, { key: "onAfterAddChild", value: function onAfterAddChild(parent, element) { this.collapsingUI.collapsedRowsStash.shiftStash(this.dataManager.getRowIndex(element)); this.collapsingUI.collapsedRowsStash.applyStash(); this.headersUI.updateRowHeaderWidth(); } /** * `beforeDetachChild` hook callback. * * @private */ }, { key: "onBeforeDetachChild", value: function onBeforeDetachChild() { this.collapsingUI.collapsedRowsStash.stash(); } /** * `afterDetachChild` hook callback. * * @private * @param {object} parent Parent element. * @param {object} element New child element. */ }, { key: "onAfterDetachChild", value: function onAfterDetachChild(parent, element) { this.collapsingUI.collapsedRowsStash.shiftStash(this.dataManager.getRowIndex(element), null, -1); this.collapsingUI.collapsedRowsStash.applyStash(); this.headersUI.updateRowHeaderWidth(); } /** * `afterCreateRow` hook callback. * * @private * @param {number} index Represents the visual index of first newly created row in the data source array. * @param {number} amount Number of newly created rows in the data source array. * @param {string} source String that identifies source of hook call. */ }, { key: "onAfterCreateRow", value: function onAfterCreateRow(index, amount, source) { if (source === this.pluginName) { return; } this.dataManager.updateWithData(this.dataManager.getRawSourceData()); } /** * `afterInit` hook callback. * * @private */ }, { key: "onAfterInit", value: function onAfterInit() { var deepestLevel = Math.max.apply(Math, _toConsumableArray(this.dataManager.cache.levels)); if (deepestLevel > 0) { this.headersUI.updateRowHeaderWidth(deepestLevel); } } /** * `beforeRender` hook callback. * * @param {boolean} force Indicates if the render call was trigered by a change of settings or data. * @param {object} skipRender An object, holder for skipRender functionality. * @private */ }, { key: "onBeforeRender", value: function onBeforeRender(force, skipRender) { var priv = privatePool.get(this); if (priv.skipRender) { skipRender.skipRender = true; } } /** * Destroys the plugin instance. */ }, { key: "destroy", value: function destroy() { _get(_getPrototypeOf(NestedRows.prototype), "destroy", this).call(this); } /** * `beforeLoadData` hook callback. * * @param {Array} data The source data. * @private */ }, { key: "onBeforeLoadData", value: function onBeforeLoadData(data) { if (!(0, _data.isArrayOfObjects)(data)) { (0, _console.error)(WRONG_DATA_TYPE_ERROR); this.disablePlugin(); return; } this.dataManager.setData(data); this.dataManager.rewriteCache(); } }], [{ key: "PLUGIN_KEY", get: function get() { return PLUGIN_KEY; } }, { key: "PLUGIN_PRIORITY", get: function get() { return PLUGIN_PRIORITY; } }]); return NestedRows; }(_base.BasePlugin); exports.NestedRows = NestedRows;
1.210938
1
demo-mobile/demo-elements/tabs/demo-tabs.js
openbap/obap-elements
11
3599
/* @license Copyright (c) 2021 <NAME>. All rights reserved. */ import { html, css, ObapElement } from '../../../src/obap-element/obap-element.js'; //import { subtitle } from '../../../src/obap-styles/obap-typography.js'; import '../../../src/obap-tabs/obap-tabs.js'; import '../../demo-mobile-app/demo-panel.js'; export class DemoTabs extends ObapElement { static get styles() { return [css` :host { display: block; height: 100%; width: 100%; max-width: 100%; padding: 8px; box-sizing: border-box; overflow: hidden; } :host([hidden]) { display: none !important; } :host([disabled]) { pointer-events: none; } obap-tabs { } demo-panel { margin-bottom: 8px; max-width: 100%; box-sizing: border-box; } demo-panel:last-of-type { margin-bottom: 0; } .container { height: 100%; display: flex; flex-direction: column; align-content: stretch; overflow-y: auto; } .temp { height: 64px; background: lightyellow; width: 1000px; } `]; } render() { return html` <div class="container"> <demo-panel label="Regular Tabs"> <obap-tabs selected-index="0"> <obap-tab>Tab 1</obap-tab> <obap-tab>Tab 2</obap-tab> <obap-tab>Tab 3</obap-tab> <obap-tab>Tab 4</obap-tab> <obap-tab>Tab 5</obap-tab> </obap-tabs> </demo-panel> <demo-panel label="Fill Tabs"> <obap-tabs fill selected-index="0"> <obap-tab>Tab 1</obap-tab> <obap-tab>Tab 2</obap-tab> <obap-tab>Tab 3</obap-tab> </obap-tabs> </demo-panel> <demo-panel label="Scrolling Tabs"> <obap-tabs scroll selected-index="0"> <obap-tab>Tab 1</obap-tab> <obap-tab>Tab 2</obap-tab> <obap-tab>Tab 3</obap-tab> <obap-tab>Tab 4</obap-tab> <obap-tab>Tab 5</obap-tab> <obap-tab>Tab 6</obap-tab> <obap-tab>Tab 7</obap-tab> <obap-tab>Tab 8</obap-tab> <obap-tab>Tab 9</obap-tab> <obap-tab>Tab 10</obap-tab> </obap-tabs> </demo-panel> <demo-panel label="Scrolling Tabs - No Buttons"> <obap-tabs scroll hide-scroll-buttons selected-index="0"> <obap-tab>Tab 1</obap-tab> <obap-tab>Tab 2</obap-tab> <obap-tab>Tab 3</obap-tab> <obap-tab>Tab 4</obap-tab> <obap-tab>Tab 5</obap-tab> <obap-tab>Tab 6</obap-tab> <obap-tab>Tab 7</obap-tab> <obap-tab>Tab 8</obap-tab> <obap-tab>Tab 9</obap-tab> <obap-tab>Tab 10</obap-tab> </obap-tabs> </demo-panel> </div> `; } } window.customElements.define('demo-tabs', DemoTabs);
1.414063
1
Project/resources/scripts/objects/skybox.js
mgrzeszczak/racing-3d
2
3607
app.objects.skybox = function(model,target){ this.model = model; this.worldMatrix = mat4.create(); this.workMatrix = mat4.create(); this.shader = app.shaderLoader.getStaticShader(); this.render = function(gl){ var shader = this.shader; var worldMatrixUniformLocation = gl.getUniformLocation(shader,app.names.SHADER_WORLD_MATRIX); mat4.identity(this.worldMatrix); mat4.fromScaling(this.worldMatrix,[50,50,50]); //mat4.fromTranslation(this.workMatrix,target.getPosition()); var translation = vec3.clone(app.getCamera().position); translation[1] = 0; mat4.fromTranslation(this.workMatrix,translation); mat4.multiply(this.worldMatrix,this.workMatrix,this.worldMatrix); gl.uniformMatrix4fv(worldMatrixUniformLocation,false,this.worldMatrix); this.model.render(gl,shader); }; };
1.390625
1
packages/bundler-utils/compiled/babel/preset-typescript.js
CJY0208/umi-next
474
3615
module.exports = require('./').presetTypescript();
0.306641
0
tests/setupImageSnapshots.js
tim-mccurrach/maths2Clipboard
3
3623
import { toMatchImageSnapshot } from "jest-image-snapshot"; expect.extend({ toMatchImageSnapshot });
0.439453
0
client/scripts/routes/home/HomeContainer.js
amitava82/product-manager
0
3631
/** * Created by amitava on 29/05/16. */ import React from 'react'; import {connect} from 'react-redux'; import autobind from 'autobind-decorator'; import {Link} from 'react-router'; import Helmet from 'react-helmet'; import Header from '../../components/Header'; @connect(state => state) export default class HomeContainer extends React.Component { render(){ return ( <div className="home-container"> <Helmet title="Home" /> <Header /> </div> ) } }
1.179688
1
solidity/test/CheckpointStore.js
surzm/contracts-solidity
200
3639
const { accounts, defaultSender, contract } = require('@openzeppelin/test-environment'); const { expectRevert, expectEvent, constants, BN, time } = require('@openzeppelin/test-helpers'); const { expect } = require('../../chai-local'); const { roles } = require('./helpers/Constants'); const { ZERO_ADDRESS } = constants; const { duration } = time; const { ROLE_OWNER, ROLE_SEEDER } = roles; const CheckpointStore = contract.fromArtifact('TestCheckpointStore'); describe('CheckpointStore', () => { const owner = defaultSender; const seeder = accounts[1]; const nonOwner = accounts[5]; const user = accounts[6]; const user2 = accounts[7]; let checkpointStore; let now = new BN(1000000000); beforeEach(async () => { checkpointStore = await CheckpointStore.new({ from: owner }); await checkpointStore.setTime(now); }); describe('construction', () => { it('should properly initialize roles', async () => { expect(await checkpointStore.getRoleMemberCount.call(ROLE_OWNER)).to.be.bignumber.equal(new BN(1)); expect(await checkpointStore.getRoleMemberCount.call(ROLE_SEEDER)).to.be.bignumber.equal(new BN(0)); expect(await checkpointStore.getRoleAdmin.call(ROLE_OWNER)).to.eql(ROLE_OWNER); expect(await checkpointStore.getRoleAdmin.call(ROLE_SEEDER)).to.eql(ROLE_OWNER); expect(await checkpointStore.hasRole.call(ROLE_OWNER, owner)).to.be.true(); expect(await checkpointStore.hasRole.call(ROLE_SEEDER, owner)).to.be.false(); }); }); describe('adding checkpoints', () => { const testCheckpoint = async (user) => { const res = await checkpointStore.addCheckpoint(user, { from: owner }); expectEvent(res, 'CheckpointUpdated', { _address: user, _time: now }); expect(await checkpointStore.checkpoint.call(user)).to.be.bignumber.equal(now); }; const testPastCheckpoint = async (user, time) => { const res = await checkpointStore.addPastCheckpoint(user, time, { from: seeder }); expectEvent(res, 'CheckpointUpdated', { _address: user, _time: time }); expect(await checkpointStore.checkpoint.call(user)).to.be.bignumber.equal(time); }; const testPastCheckpoints = async (users, times) => { const res = await checkpointStore.addPastCheckpoints(users, times, { from: seeder }); for (let i = 0; i < users.length; i++) { expectEvent(res, 'CheckpointUpdated', { _address: users[i], _time: times[i] }); expect(await checkpointStore.checkpoint.call(users[i])).to.be.bignumber.equal(times[i]); } }; context('owner', async () => { it('should allow an owner to add checkpoints', async () => { await testCheckpoint(user); now = now.add(duration.days(1)); await checkpointStore.setTime(now); await testCheckpoint(user); await testCheckpoint(user2); now = now.add(duration.days(5)); await checkpointStore.setTime(now); await testCheckpoint(user2); }); it('should revert when a non-owner attempts to add checkpoints', async () => { await expectRevert(checkpointStore.addCheckpoint(user, { from: nonOwner }), 'ERR_ACCESS_DENIED'); }); it('should revert when an owner attempts to add a checkpoint for the zero address user', async () => { await expectRevert(checkpointStore.addCheckpoint(ZERO_ADDRESS, { from: owner }), 'ERR_INVALID_ADDRESS'); }); it('should revert when an owner attempts to add checkpoints in an incorrect order', async () => { await testCheckpoint(user); now = now.sub(duration.days(1)); await checkpointStore.setTime(now); await expectRevert(checkpointStore.addCheckpoint(user, { from: owner }), 'ERR_WRONG_ORDER'); }); }); context('seeder', async () => { const nonSeeder = accounts[2]; beforeEach(async () => { await checkpointStore.grantRole(ROLE_SEEDER, seeder, { from: owner }); }); it('should allow a seeder to add past checkpoints', async () => { let past = now.sub(new BN(20000)); await testPastCheckpoint(user, past); past = past.add(new BN(1000)); await testPastCheckpoint(user, past); past = past.add(new BN(5000)); await testPastCheckpoint(user2, past); }); it('should allow a seeder to batch add past checkpoints', async () => { const past = now.sub(new BN(20000)); await testPastCheckpoints([user, user2], [past, past.add(new BN(1000))]); }); it('should revert when a seeder attempts to add past checkpoints in an incorrect order', async () => { let past = now.sub(new BN(1)); await testPastCheckpoint(user, past); past = past.sub(new BN(1000)); await expectRevert(checkpointStore.addPastCheckpoint(user, past, { from: seeder }), 'ERR_WRONG_ORDER'); await expectRevert( checkpointStore.addPastCheckpoints([user], [past], { from: seeder }), 'ERR_WRONG_ORDER' ); }); it('should revert when a non-seeder attempts to add past checkpoints', async () => { const past = now.sub(new BN(1)); await expectRevert( checkpointStore.addPastCheckpoint(user, past, { from: nonSeeder }), 'ERR_ACCESS_DENIED' ); await expectRevert( checkpointStore.addPastCheckpoints([user], [past], { from: nonSeeder }), 'ERR_ACCESS_DENIED' ); }); it('should revert when a seeder attempts to add a past checkpoint for the zero address user', async () => { const past = now.sub(new BN(1)); await expectRevert( checkpointStore.addPastCheckpoint(ZERO_ADDRESS, past, { from: seeder }), 'ERR_INVALID_ADDRESS' ); await expectRevert( checkpointStore.addPastCheckpoints([ZERO_ADDRESS], [past], { from: seeder }), 'ERR_INVALID_ADDRESS' ); }); it('should revert when a seeder attempts to add a future checkpoint', async () => { await expectRevert(checkpointStore.addPastCheckpoint(user, now, { from: seeder }), 'ERR_INVALID_TIME'); await expectRevert( checkpointStore.addPastCheckpoints([user, user], [now, now], { from: seeder }), 'ERR_INVALID_TIME' ); const future = now.add(new BN(100)); await expectRevert( checkpointStore.addPastCheckpoint(user, future, { from: seeder }), 'ERR_INVALID_TIME' ); await expectRevert( checkpointStore.addPastCheckpoints([user, user], [now.sub(duration.seconds(1)), future], { from: seeder }), 'ERR_INVALID_TIME' ); }); it('should revert when a seeder attempts to add batch checkpoints in an invalid length', async () => { await expectRevert( checkpointStore.addPastCheckpoints([user], [now, now], { from: seeder }), 'ERR_INVALID_LENGTH' ); await expectRevert( checkpointStore.addPastCheckpoints([user, user], [now], { from: seeder }), 'ERR_INVALID_LENGTH' ); }); }); }); });
1.640625
2
src/Page/PageNotFound/index.js
navgurukul/nightingale
0
3647
import React from 'react'; import { NavLink } from "react-router-dom"; import './style.css' const PageNotFound= ()=>{ return( <div className='pageNotFoundContainer'> <h3> 404 Page Not Found.</h3> <p><NavLink to="/">Go to the Home page</NavLink></p> </div> ) } export default PageNotFound
1.148438
1
docs/reference/cmsis-plus/search/classes_6.js
micro-os-plus/web-preview
0
3655
var searchData= [ ['file',['file',['../classos_1_1posix_1_1file.html',1,'os::posix']]], ['file_5fdescriptors_5fmanager',['file_descriptors_manager',['../classos_1_1posix_1_1file__descriptors__manager.html',1,'os::posix']]], ['file_5fimpl',['file_impl',['../classos_1_1posix_1_1file__impl.html',1,'os::posix']]], ['file_5fimplementable',['file_implementable',['../classos_1_1posix_1_1file__implementable.html',1,'os::posix']]], ['file_5flockable',['file_lockable',['../classos_1_1posix_1_1file__lockable.html',1,'os::posix']]], ['file_5fsystem',['file_system',['../classos_1_1posix_1_1file__system.html',1,'os::posix']]], ['file_5fsystem_5fimpl',['file_system_impl',['../classos_1_1posix_1_1file__system__impl.html',1,'os::posix']]], ['file_5fsystem_5fimplementable',['file_system_implementable',['../classos_1_1posix_1_1file__system__implementable.html',1,'os::posix']]], ['file_5fsystem_5flockable',['file_system_lockable',['../classos_1_1posix_1_1file__system__lockable.html',1,'os::posix']]], ['first_5ffit_5ftop',['first_fit_top',['../classos_1_1memory_1_1first__fit__top.html',1,'os::memory']]], ['first_5ffit_5ftop_5fallocated',['first_fit_top_allocated',['../classos_1_1memory_1_1first__fit__top__allocated.html',1,'os::memory']]], ['first_5ffit_5ftop_5finclusive',['first_fit_top_inclusive',['../classos_1_1memory_1_1first__fit__top__inclusive.html',1,'os::memory']]] ];
0.194336
0
src/export-travel.js
yongjun21/scrapping-LTA
1
3663
import PouchDB from 'pouchdb' import fs from 'fs' const db = new PouchDB( 'https://daburu.cloudant.com/lta-travel-time', { auth: { username: process.env.CLOUDANT_TRAVEL_KEY, password: process.env.CLOUDANT_TRAVEL_PASSWORD } } ) db.allDocs({include_docs: true}) .then((docs) => docs.rows.map((row) => row.doc)) .then((docs) => { fs.writeFileSync('R/travel.json', JSON.stringify(docs)) }) .catch(console.error)
1.046875
1
index.js
ruuvi/ruuvi.endpoints.js
3
3671
/*jshint node: true, esversion: 6 */ "use strict"; var parser = require('./parser.js'); var endpoints = require('./endpoints.js'); /** * Takes UINT8_T array with 11 bytes as input * Request Ruuvi Standard Message Object as output, * usage: * let message = parseRuuviStandardMessage(buffer); * message.source_endpoint * message.destination_endpoint * message.type * message.payload.sample_rate * message.payload.transmission_rate * // and so on. Payload fields are dependent on type. * * Supports Ruuvi Broadcast types, such as manufacturer specific data RAW formats 0x03 and 0x05 (TODO) * * Returns object with key-value pairs for data, for example data.source, data.destination, * data.type, data.val1, data.val2, data.val3 and data.val4 **/ var parse = function(serialBuffer){ return parser(serialBuffer); }; /** * Takes Ruuvi Standard Message * and returns 11-byte long UINT8 array represenstation. */ var create = function(message){ console.log("TODO: handle: " + message); }; /** * Returns object with key-value pairs of endpoints */ var getEndpoints = function(){ return endpoints.getEndpoints(); }; /** * Returns object with key-value pairs of DSP functions */ var getDSPFunctions = function(){ return endpoints.getDSPFunctions(); }; module.exports = { parse: parse, create: create, getEndpoints: getEndpoints, getDSPFunctions: getDSPFunctions, };
1.484375
1
src/components/footer/footer.styles.js
younessdev9/gatsby-portfolio
1
3679
import styled from "styled-components" const StyledFooter = styled.footer` border-top: 2px solid #3333; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; padding: 1rem; background-color: #298880; color: #333333; .social-footer { width: 33%; } h4 { font-size: 1.6rem; font-weight: 500; color: #f5f5f5; .gatsby-logo { width: 1.6rem; height: 1.6rem; margin-top: 0.7rem; margin-right: 0.3rem; font-style: normal; font-weight: normal; font-size: 1.3rem; transition: all 0.5s ease-out; transform: translateY(22%); &:hover { transform: scale(1.6) rotate(360deg); } } span { font-weight: bold; } } @media only screen and (max-width: ${({ theme }) => theme.laptop}) { justify-content: center; max-width: 96%; h4 { margin: 1.3rem; } } /* MobileM 387px and less */ @media only screen and (max-width: ${({ theme }) => theme.mobileM}) { .social-media { display: none; } } ` export default StyledFooter
1.09375
1
src/components/ChallengePane/ChallengeFilterSubnav/ButtonFilter.js
reichg/maproulette3
78
3687
import React from 'react' import classNames from 'classnames' import SvgSymbol from '../../SvgSymbol/SvgSymbol' const ButtonFilter = props => ( <span className="mr-block mr-text-left mr-font-normal"> <span className="mr-block mr-text-left mr-mb-1 mr-text-xs mr-uppercase mr-text-white"> {props.type} </span> <span className="mr-flex mr-items-center mr-text-green-lighter mr-cursor-pointer" onClick={props.onClick}> <span className={classNames( "mr-w-24 mr-mr-2 mr-overflow-hidden mr-whitespace-no-wrap mr-overflow-ellipsis", props.selectionClassName)} > {props.selection} </span> <SvgSymbol sym="icon-cheveron-down" viewBox="0 0 20 20" className="mr-fill-current mr-w-5 mr-h-5" /> </span> </span> ) export default ButtonFilter
1.007813
1
modules/deviceapiv2/server/controllers/main.server.controller.js
AtrixTV/backoffice-administration
0
3695
'use strict' var path = require('path'), db = require(path.resolve('./config/lib/sequelize')), response = require(path.resolve("./config/responses.js")), models = db.models, fs = require('fs'), qr = require('qr-image'), download = require('download-file'), winston = require(path.resolve('./config/lib/winston')); var authentication = require(path.resolve('./modules/deviceapiv2/server/controllers/authentication.server.controller.js')); var push_functions = require(path.resolve('./custom_functions/push_messages')); /** * @api {post} /apiv2/main/device_menu /apiv2/main/device_menu * @apiName DeviceMenu * @apiGroup DeviceAPI * * @apiUse body_auth * @apiDescription Returns list of menu items available for this user and device * * Use this token for testing purposes * * auth=<KEY> */ exports.device_menu = function(req, res) { var thisresponse = new response.OK(); var get_guest_menus = (req.auth_obj.username === 'guest' && req.app.locals.backendsettings[req.thisuser.company_id].allow_guest_login === true) ? true: false; models.device_menu.findAll({ attributes: ['id', 'title', 'url', 'icon_url', [db.sequelize.fn('concat', req.app.locals.backendsettings[req.thisuser.company_id].assets_url, db.sequelize.col('icon_url')), 'icon'], 'menu_code', 'position', [db.sequelize.fn('concat', "", db.sequelize.col('menu_code')), 'menucode']], where: {appid: {$like: '%'+req.auth_obj.appid+'%' }, isavailable:true, is_guest_menu: get_guest_menus, company_id: req.thisuser.company_id}, order: [[ 'position', 'ASC' ]] }).then(function (result) { for(var i=0; i<result.length; i++){ result[i].icon_url = req.app.locals.backendsettings[req.thisuser.company_id].assets_url+result[i].icon_url; } response.send_res(req, res, result, 200, 1, 'OK_DESCRIPTION', 'OK_DATA', 'private,max-age=86400'); }).catch(function(error) { winston.error("Getting a list of menus failed with error: ", error); response.send_res(req, res, [], 706, -1, 'DATABASE_ERROR_DESCRIPTION', 'DATABASE_ERROR_DATA', 'no-store'); }); }; /** DEVICE MENU GET * @api {get} /apiv2/main/device_menu Get Device Main Menu * @apiVersion 0.2.0 * @apiName GetDeviceMenu * @apiGroup Main Menu * * @apiHeader {String} auth Users unique access-key. * @apiDescription Get Main Menu object for the running application. */ exports.device_menu_get = function(req, res) { var get_guest_menus = (req.auth_obj.username === 'guest' && req.app.locals.backendsettings[req.thisuser.company_id].allow_guest_login === true) ? true: false; models.device_menu.findAll({ attributes: ['id', 'title', 'url', 'icon_url', [db.sequelize.fn('concat', req.app.locals.backendsettings[req.thisuser.company_id].assets_url, db.sequelize.col('icon_url')), 'icon'], 'menu_code', 'position', ['menu_code','menucode']], where: {appid: {$like: '%'+req.auth_obj.appid+'%' }, isavailable:true, is_guest_menu: get_guest_menus, company_id: req.thisuser.company_id}, order: [[ 'position', 'ASC' ]] }).then(function (result) { for(var i=0; i<result.length; i++){ result[i].icon_url = req.app.locals.backendsettings[req.thisuser.company_id].assets_url+result[i].icon_url; } response.send_res_get(req, res, result, 200, 1, 'OK_DESCRIPTION', 'OK_DATA', 'private,max-age=86400'); }).catch(function(error) { winston.error("Getting a list of menus failed with error: ", error); response.send_res_get(req, res, [], 706, -1, 'DATABASE_ERROR_DESCRIPTION', 'DATABASE_ERROR_DATA', 'no-store'); }); }; /** GET DEVICE MENU WITH TWO LEVELS - LEVEL ONE * @api {get} /apiv2/main/device_menu_levelone Get DeviceMenu level One * @apiVersion 0.2.0 * @apiName GetDeviceMenuLevelOne * @apiGroup Main Menu * * @apiHeader {String} auth Users unique access-key. * @apiDescription Get Main Menu object for the running application. */ exports.get_devicemenu_levelone = function(req, res) { var get_guest_menus = (req.auth_obj.username === 'guest' && req.app.locals.backendsettings[req.thisuser.company_id].allow_guest_login === true) ? true: false; models.device_menu.findAll({ attributes: ['id', 'title', 'url', [db.sequelize.fn('concat', req.app.locals.backendsettings[req.thisuser.company_id].assets_url, db.sequelize.col('icon_url')), 'icon'], [db.sequelize.fn('concat', req.app.locals.backendsettings[req.thisuser.company_id].assets_url, db.sequelize.col('icon_url')), 'icon_url'], 'menu_code', 'position','parent_id','menu_description', ['menu_code','menucode']], where: {appid: {$like: '%'+req.auth_obj.appid+'%' }, isavailable:true, is_guest_menu: get_guest_menus, company_id: req.thisuser.company_id}, order: [[ 'position', 'ASC' ]] }).then(function (result) { for(var i=0; i<result.length; i++){ result[i].dataValues.menucode = 0; result[i].dataValues.menu_code = 0; result[i].dataValues.parent_id = 0; } response.send_res_get(req, res, result, 200, 1, 'OK_DESCRIPTION', 'OK_DATA', 'private,max-age=86400'); }).catch(function(error) { winston.error("Getting a list of level one menus failed with error: ", error); response.send_res_get(req, res, [], 706, -1, 'DATABASE_ERROR_DESCRIPTION', 'DATABASE_ERROR_DATA', 'no-store'); }); }; /** GET DEVICE MENU WITH TWO LEVELS - LEVEL TWO * @api {get} /apiv2/main/device_menu_leveltwo Get DeviceMenu level Two * @apiVersion 0.2.0 * @apiName GetDeviceMenuLevelTwo * @apiGroup Main Menu * * @apiHeader {String} auth Users unique access-key. * @apiDescription Get Main Menu object for the running application. */ exports.get_devicemenu_leveltwo = function(req, res) { models.device_menu_level2.findAll({ attributes: ['id', 'title', 'url', [db.sequelize.fn('concat', req.app.locals.backendsettings[req.thisuser.company_id].assets_url, db.sequelize.col('icon_url')), 'icon'], [db.sequelize.fn('concat', req.app.locals.backendsettings[req.thisuser.company_id].assets_url, db.sequelize.col('icon_url')), 'icon_url'], 'menu_code', 'position','parent_id','menu_description', ['menu_code','menucode']], where: {appid: {$like: '%'+req.auth_obj.appid+'%' }, isavailable:true, company_id: req.thisuser.company_id}, order: [[ 'position', 'ASC' ]] }).then(function (result) { response.send_res_get(req, res, result, 200, 1, 'OK_DESCRIPTION', 'OK_DATA', 'private,max-age=86400'); }).catch(function(error) { winston.error("Getting a list of second level menus failed with error: ", error); response.send_res_get(req, res, [], 706, -1, 'DATABASE_ERROR_DESCRIPTION', 'DATABASE_ERROR_DATA', 'no-store'); }); }; exports.get_weather_widget = function(req, res) { if (fs.existsSync('public/weather_widget/index.html')) { var url= req.app.locals.backendsettings[1].assets_url; var file = '/weather_widget/index.html'; var response_Array = { "widget_url": url+file }; return res.send(response_Array); }else { return res.status(404).send({ message: 'Image Not Found' }); } }; exports.get_welcomeMessage = function(req, res) { models.customer_data.findOne({ attributes:['firstname','lastname'], where: {id: req.thisuser.customer_id } }).then(function(customer_data_result) { models.html_content.findOne({ where: {name: 'welcomeMessage' } }).then(function(html_content_result) { var html; if(!html_content_result){ html = 'Welcome'; }else { var content_from_ui = html_content_result.content; html = content_from_ui.replace(new RegExp('{{fullname}}', 'gi'),customer_data_result.firstname+' '+customer_data_result.lastname); } var response_Array = [{ "welcomeMessage": html }]; // response.set('Content-Type', 'text/html'); response.send_res_get(req, res, response_Array, 200, 1, 'OK_DESCRIPTION', 'OK_DATA', 'private,max-age=86400'); return null; }).catch(function(error){ winston.error("Html Content failed with error", error); response.send_res(req, res, [], 706, -1, 'DATABASE_ERROR_DESCRIPTION', 'DATABASE_ERROR_DATA', 'no-store'); }); return false; }).catch(function(error){ winston.error("Quering for the client's personal info failed with error: ", error); response.send_res(req, res, [], 706, -1, 'DATABASE_ERROR_DESCRIPTION', 'DATABASE_ERROR_DATA', 'no-store'); }); }; exports.get_qrCode = function(req, res) { if (!req.body.googleid) { return res.send({error: {code: 400, message: 'googleid parameter null'}}); } else { if (!fs.existsSync('./public/files/qrcode/')){ fs.mkdirSync('./public/files/qrcode/'); } var url = req.app.locals.backendsettings[1].assets_url; var d = new Date(); var qr_png = qr.image(url+'/apiv2/htmlContent/remotedeviceloginform?googleid='+req.body.googleid, { type: 'png', margin: 1, size: 5 }); qr_png.pipe(fs.createWriteStream('./public/files/qrcode/'+d.getTime()+'qrcode.png')); var qrcode_image_fullpath = qr_png._readableState.pipes.path.slice(8); var qrcode_url = url + qrcode_image_fullpath; response.send_res_get(req, res, qrcode_url, 200, 1, 'OK_DESCRIPTION', 'OK_DATA', 'private,max-age=86400'); } }; exports.getloginform = function(req, res) { res.set('Content-Type', 'text/html'); res.render(path.resolve('modules/deviceapiv2/server/templates/qrcode'), { googleid: req.query.googleid }); return null; }; exports.qr_login = function(req, res) { var login_params = { "username" : req.body.username, "password" : <PASSWORD> }; var push_obj = new push_functions.ACTION_PUSH('Action', 'Performing an action', 5, 'login_user', login_params); push_functions.send_notification(req.body.googleid, req.app.locals.backendsettings[1].firebase_key, req.body.username, push_obj, 60, false, false, function(result){}); res.status(200).send({message: 'Message sent'}); };
1.320313
1
index.js
Artpej/cluboeno
0
3703
var trendarticle = new Vue({ el: '#trendarticle', data: { articles : [ { title : 'Short Blog Title', publisheddate : '12th August 2018', summation : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do', img : 'https://picsum.photos/500/500/?random=1' }, { title : 'Short Blog Title', publisheddate : '12th August 2018', summation : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do', img : 'https://picsum.photos/500/500/?random=2' }, { title : 'Short Blog Title', publisheddate : '12th August 2018', summation : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do', img : 'https://picsum.photos/500/500/?random=3' }, { title : 'Short Blog Title', publisheddate : '12th August 2018', summation : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do', img : 'https://picsum.photos/500/500/?random=4' }, { title : 'Short Blog Title', publisheddate : '12th August 2018', summation : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do', img : 'https://picsum.photos/500/500/?random=5' } ] } }) var lastarticle = new Vue({ el: '#lastarticle', data: { articles : [ { title : 'Fusce facilisis tempus magna ac dignissim 1', publisheddate : '12th August 2018', text : 'Vivamus sed consequat urna. Fusce vitae urna sed ante placerat iaculis. Suspendisse potenti. Pellentesque quis fringilla libero. In hac habitasse platea dictumst. Ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo', img : 'https://picsum.photos/800/300/?random=1' }, { title : 'Fusce facilisis tempus magna ac dignissim 2' , publisheddate : '12th August 2018', text : 'Vivamus sed consequat urna. Fusce vitae urna sed ante placerat iaculis. Suspendisse potenti. Pellentesque quis fringilla libero. In hac habitasse platea dictumst. Ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo', img : 'https://picsum.photos/800/300/?random=2' }, { title : 'Fusce facilisis tempus magna ac dignissim 3', publisheddate : '12th August 2018', text : 'Vivamus sed consequat urna. Fusce vitae urna sed ante placerat iaculis. Suspendisse potenti. Pellentesque quis fringilla libero. In hac habitasse platea dictumst. Ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo', img : 'https://picsum.photos/800/300/?random=3' }, { title : 'Fusce facilisis tempus magna ac dignissim 4', publisheddate : '12th August 2018', text : 'Vivamus sed consequat urna. Fusce vitae urna sed ante placerat iaculis. Suspendisse potenti. Pellentesque quis fringilla libero. In hac habitasse platea dictumst. Ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo', img : 'https://picsum.photos/800/300/?random=4' }, { title : 'Fusce facilisis tempus magna ac dignissim 5', publisheddate : '12th August 2018', text : 'Vivamus sed consequat urna. Fusce vitae urna sed ante placerat iaculis. Suspendisse potenti. Pellentesque quis fringilla libero. In hac habitasse platea dictumst. Ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo', img : 'https://picsum.photos/800/300/?random=5' } ] } })
1.070313
1
nodeServer/node_modules/ipfs-http-server/cjs/src/api/resources/pin.js
mark146/usedmoa
0
3711
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var joi = require('../../utils/joi.js'); var Boom = require('@hapi/boom'); var map = require('it-map'); var itPipe = require('it-pipe'); var streamResponse = require('../../utils/stream-response.js'); var all = require('it-all'); var reduce = require('it-reduce'); function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } var Boom__default = /*#__PURE__*/_interopDefaultLegacy(Boom); var map__default = /*#__PURE__*/_interopDefaultLegacy(map); var all__default = /*#__PURE__*/_interopDefaultLegacy(all); var reduce__default = /*#__PURE__*/_interopDefaultLegacy(reduce); function toPin(type, cid, metadata) { const output = { Type: type }; if (cid) { output.Cid = cid; } if (metadata) { output.Metadata = metadata; } return output; } const lsResource = { options: { validate: { options: { allowUnknown: true, stripUnknown: true }, query: joi.object().keys({ paths: joi.array().single().items(joi.ipfsPath()), recursive: joi.boolean().default(true), cidBase: joi.string().default('base58btc'), type: joi.string().valid('all', 'direct', 'indirect', 'recursive').default('all'), stream: joi.boolean().default(false), timeout: joi.timeout() }).rename('cid-base', 'cidBase', { override: true, ignoreUndefined: true }).rename('arg', 'paths', { override: true, ignoreUndefined: true }) } }, async handler(request, h) { const { app: {signal}, server: { app: {ipfs} }, query: {paths, type, cidBase, stream, timeout} } = request; const source = ipfs.pin.ls({ paths, type, signal, timeout }); const base = await ipfs.bases.getBase(cidBase); if (!stream) { const res = await itPipe.pipe(source, function collectKeys(source) { const init = { Keys: {} }; return reduce__default['default'](source, (res, {type, cid, metadata}) => { res.Keys[cid.toString(base.encoder)] = toPin(type, undefined, metadata); return res; }, init); }); return h.response(res); } return streamResponse.streamResponse(request, h, () => itPipe.pipe(source, async function* transform(source) { yield* map__default['default'](source, ({type, cid, metadata}) => toPin(type, cid.toString(base.encoder), metadata)); })); } }; const addResource = { options: { validate: { options: { allowUnknown: true, stripUnknown: true }, query: joi.object().keys({ cids: joi.array().single().items(joi.cid()).min(1).required(), recursive: joi.boolean().default(true), cidBase: joi.string().default('base58btc'), timeout: joi.timeout(), metadata: joi.json() }).rename('cid-base', 'cidBase', { override: true, ignoreUndefined: true }).rename('arg', 'cids', { override: true, ignoreUndefined: true }) } }, async handler(request, h) { const { app: {signal}, server: { app: {ipfs} }, query: {cids, recursive, cidBase, timeout, metadata} } = request; let result; try { result = await all__default['default'](ipfs.pin.addAll(cids.map(cid => ({ cid, recursive, metadata })), { signal, timeout })); } catch (err) { if (err.code === 'ERR_BAD_PATH') { throw Boom__default['default'].boomify(err, { statusCode: 400 }); } if (err.message.includes('already pinned recursively')) { throw Boom__default['default'].boomify(err, { statusCode: 400 }); } throw Boom__default['default'].boomify(err, { message: 'Failed to add pin' }); } const base = await ipfs.bases.getBase(cidBase); return h.response({ Pins: result.map(cid => cid.toString(base.encoder)) }); } }; const rmResource = { options: { validate: { options: { allowUnknown: true, stripUnknown: true }, query: joi.object().keys({ cids: joi.array().single().items(joi.cid()).min(1).required(), recursive: joi.boolean().default(true), cidBase: joi.string().default('base58btc'), timeout: joi.timeout() }).rename('cid-base', 'cidBase', { override: true, ignoreUndefined: true }).rename('arg', 'cids', { override: true, ignoreUndefined: true }) } }, async handler(request, h) { const { app: {signal}, server: { app: {ipfs} }, query: {cids, recursive, cidBase, timeout} } = request; let result; try { result = await all__default['default'](ipfs.pin.rmAll(cids.map(cid => ({ cid, recursive })), { signal, timeout })); } catch (err) { if (err.code === 'ERR_BAD_PATH') { throw Boom__default['default'].boomify(err, { statusCode: 400 }); } throw Boom__default['default'].boomify(err, { message: 'Failed to remove pin' }); } const base = await ipfs.bases.getBase(cidBase); return h.response({ Pins: result.map(cid => cid.toString(base.encoder)) }); } }; exports.addResource = addResource; exports.lsResource = lsResource; exports.rmResource = rmResource;
1.304688
1
src/components/ReactHumanBody/Colon.js
YasminTeles/MegahackWomen
2
3719
import React, { Component } from 'react'; import Tooltip from '@material-ui/core/Tooltip'; class Colon extends Component { render() { const {onClick, fillColor} = this.props return ( <Tooltip title="Colon" placement="right"> <path id="colon" className="colon" fill={fillColor} onClick={onClick} fillOpacity="0.5" stroke="#787878" strokeWidth="0.5" d="M279.948,288.077l-0.987-4.124 l0.662-2.406v-6.873l0.325-3.093l-0.325-1.375v-6.874l-0.33-1.375v-5.154l-0.332-1.375l-0.993-2.406l-0.993-1.717l-0.662-0.688 l-1.988-0.688h-1.981l-1.656,0.688h-2.317l-2.313,2.063l-1.985,1.03l-2.316,1.718l-1.985,1.719l-0.994,1.375l-3.313,1.718 l-1.651,1.718l-0.663,1.031l-2.315,1.375l-1.656,1.718l-0.329,0.345l-0.993,0.344l-6.628,2.75l-2.316,0.344l-3.313,1.375h-1.986 l-2.318-0.688l-2.318-0.343l-1.986-1.03L225,268.491l-2-0.344l-1.656-0.688l-1.986-0.344l-2.315-1.031l-2.319-0.688l-1.324-0.687 l-1.653-0.687l-1.324-0.688l-1.656-1.375l-1.657-1.031l-1.32-0.687l-1.657-0.688l-3.646,0.344H198.5l-1.656,1.031l-1.656,1.03 l-2.316,2.062l-0.662,2.063l-1.323,2.063l-1.325,1.031l-1.324,2.748l-1.984,4.813l-0.331,2.749l-2.649,4.124l-0.993,2.406 l-0.331,3.437l-0.33,4.124l-0.993,3.093v5.156l0.662,2.062l0.331,2.406l0.662,4.469l0.993,3.779l2.317,4.469l3.979,2.405 l3.313,1.375h3.646l3.313-1.03l-0.009-3.095l0.33-2.062l-0.66-3.096l-0.331-1.718l-0.993-2.062v-3.438l-1.656-3.093l-0.663-1.031 l-0.662-4.123l0.662-2.404v-3.438l0.663-1.375v-2.405l2.649-2.063v-2.063l0.661-1.031l0.33-3.092l1.324-1.375l0.663-2.406 l-0.785-0.977l3.771,0.977l1.655,2.062l3.313,0.345l1.986,0.688l2.979,1.03h3.313l2.979,1.375l2.98,1.031h1.325l2.646,0.344 l2.98,1.031l2.979,0.344h3.646l1.322-0.344l2.979-1.375h3.313l1.984-2.063h2.648l1.653-1.031h1.654l2.649-1.375l3.313-0.344 l1.985-2.406l2.979-0.688l2.648-2.405l1.983-0.345l-0.658,2.063l0.99,2.406l-0.99,2.406v4.123l0.658,1.719l-0.658,2.406v2.748 l-0.993,1.375l0.329,2.406l-0.993,2.406l0.332,2.406v1.718l-0.993,1.718l-1.323,1.031v2.406l-1.658,1.718v1.718l-1.652,2.406 l-0.661,2.406l-1.654,1.718l-1.986,1.718l-0.66,2.063h-2.317l-0.661,1.718l-2.317,0.343h-2.315l-2.646,1.718H239.9l-1.654,1.718 l-1.655,0.688h-4.971l-1.656,0.687l-1.987,0.347l-0.993,1.718h-2.315l-2.318,1.031l-0.331,2.404l-0.102,0.13 c-0.239,2.772-0.256,6.608,0.665,9.534c4.396-0.555,8.8-0.787,13.218-0.863c0.131-0.386,0.308-0.764,0.521-1.123l-0.392-0.115 l-0.661-1.718l4.313-1.72l1.319-1.029l1.323-0.346l2.318-0.687l1.322-2.063l2.649-0.346h1.655l2.314-0.343l3.313-1.031l2.316-0.343 l2.317-0.344l1.656-2.406h2.646l1.656-2.063l1.323-1.375l2.646-3.438v-1.031l0.994-0.687v-1.375l2.319-2.406v-1.375l2.315-2.749 l0.329-3.093l1.987-2.749l0.993-2.063l-0.33-2.404l0.993-2.405l-0.331-4.468v-3.094L279.948,288.077z"/> </Tooltip> ) } } export default Colon
1.4375
1
config/utils.js
leslieSie/webpack-simple-framework
3
3727
let path = require("path"); let fs = require("fs"); let mkdirp = require("mkdirp"); const colors = require("colors"); const jsonfile = require('jsonfile'); // generate file address let absPath = function(dir) { return path.join(__dirname, "../", dir); }; // judge the file is exist let fileExist = function(absPath) { return fs.existsSync(absPath); }; // create new directory,if the directory exist that the function return the string which is 'the directory is exist' let dirCreate = function(absPath, fn) { let directoryIsExist = fileExist(absPath); if (directoryIsExist) { console.log("要创建的文件目录已经存在".red); return { status: "exist" }; } else { mkdirp(absPath, err => { if (err) { console.log(err.red); return { status: "error" }; } if (dataType(fn) == "Function") { fn(); } }); return { status: "success" }; } }; //judge the data type let dataType = function(data) { let tmpType = Object.prototype.toString.call(data); let sliceString = tmpType.slice(1, tmpType.length - 1); return sliceString.split(" ").reverse()[0]; }; // get file name and directory name from absolute path let getFileMsg = function(absPath) { let basename = path.basename(absPath); let dirname = path.dirname(absPath); return { filename: basename, dirname: dirname }; }; let createFileCoreModule = function(specifiedPath) { return new Promise((resolve, reject) => { fs.stat(specifiedPath, (err, stats) => { if (err) { resolve(); return false; } if (stats.isDirectory()) { reject({ msg: "传入的路径不能为目录路径" }); } if (stats.isFile()) { reject({ msg: `路径为${specifiedPath}的文件已经存在` }); } }); }) .then(data => { let fileMsgs = getFileMsg(specifiedPath); mkdirp(fileMsgs.dirname, err => { if (err) { console.log("文件创建失败".red); return false; } fs.writeFileSync( path.join(fileMsgs.dirname, fileMsgs.filename), {}, err => { if (err) { console.log(err.red); return false; } } ); }); return { status: true, } }) .catch(errObj => { console.log(errObj.msg.red); return { status: false, info: errObj.msg }; }); }; // create file on specified path,If the path mean directory,will return error message.If the path whitch is exist file,return a message to tell developer the file is exist.otherwise,create files depend on specifiedPath param.create succes run cb params.by the way,fn must Function type. let createFiles = async function(specifiedPaths, cb) { let statistic = 0; switch (dataType(specifiedPaths)) { case "String": await createFileCoreModule(specifiedPaths); cb(); break; case "Array": let status = specifiedPaths.forEach(async itemPath => { await createFileCoreModule(itemPath); statistic++; if (Object.is(statistic, specifiedPaths.length)) { cb(); } }); break; case "Undefined": console.log("创建的路径不能为空!".red); break; } }; let delFilesCoreModule = function(absPaths, params, cb) { let isExist = fileExist(absPaths); if (isExist) { fs.unlinkSync(absPaths); console.log("文件删除成功!".green); if (dataType(params) == "Object" && params.autoClear == true) { let files = fs.readdirSync(getFileMsg(absPaths).dirname); if (files.length == 0) { fs.rmdir(getFileMsg(absPaths).dirname, err => { console.log("空文件夹删除".green); }); } } cb(); } else { console.log('文件删除路径不存在'); return false; } }; // delete file let deleteFiles = function(absPaths, params, cb) { switch (dataType(absPaths)) { case "String": delFilesCoreModule(absPaths, params, cb); break; case "Array": absPaths.forEach(async path => { delFilesCoreModule(path, params, cb); }); break; } }; //read message from file let readFromFile = function(absPath = "", params, cb) { if (fileExist(absPath)) { let fileMsg = fs.readFileSync(absPath, 'utf8'); if (Object.is('Object', dataType(params))) { switch (params.type) { case 'json': jsonfile.readFile(absPath, (err, obj) => { if (err == undefined) { cb(err, obj); } }); break; default: break; } } else { cb(fileMsg); } } }; //store to file,only support message write to single file // writeMsg not type undefined,null,NaN let store2File = function(absPath = "", writeMsg, writeParams) { let dealStr = ""; if (Object.is(dataType(writeParams), 'Object') && writeParams.parseType) { switch (writeParams.parseType) { case 'json': jsonfile.writeFile(absPath, writeMsg) .then(res => { console.log(res); }) break; default: break; } } else { dealStr = writeMsg.toString(); } /* switch (dataType(writeMsg)) { case "Object": case "Array": dealStr = JSON.stringify(writeMsg); break; case 'Function': dealStr = writeMsg.toString(); break; default: dealStr = writeMsg; break; } */ const buf = Buffer.from(dealStr, "utf8"); if (fileExist(absPath) && !fs.statSync(absPath).isDirectory()) { let writeSteam = fs.createWriteStream(absPath); writeSteam.write(buf, "utf8"); writeSteam.end(); writeSteam.on("finish", () => { console.log("文件写入成功".green); }); writeSteam.on("error", () => { console.log("文件写入错误".red); }); } else { console.log("指定的路径文件不存在".red); } }; const global_exclude = [/node_modules/, absPath("build")]; module.exports = { absPath, fileExist, dirCreate, global_exclude, dataType, createFiles, deleteFiles, store2File, getFileMsg, readFromFile };
2.109375
2
lib/Drivers/DDL/postgres.js
interlock/node-orm2
0
3735
var ErrorCodes = require("../../ErrorCodes"); exports.drop = function (driver, opts, cb) { var i, queries = [], pending; queries.push("DROP TABLE IF EXISTS " + driver.query.escapeId(opts.table)); for (i = 0; i < opts.many_associations.length; i++) { queries.push("DROP TABLE IF EXISTS " + driver.query.escapeId(opts.many_associations[i].mergeTable)); } pending = queries.length; for (i = 0; i < queries.length; i++) { driver.execQuery(queries[i], function (err) { if (--pending === 0) { return cb(err); } }); } }; exports.sync = function (driver, opts, cb) { var tables = []; var subqueries = []; var typequeries = []; var definitions = []; var k, i, pending, prop; var primary_keys = opts.id.map(function (k) { return driver.query.escapeId(k); }); var keys = []; for (k in opts.allProperties) { prop = opts.allProperties[k]; definitions.push(buildColumnDefinition(driver, opts.table, k, prop)); if (prop.type == "enum") { typequeries.push( "CREATE TYPE " + driver.query.escapeId("enum_" + opts.table + "_" + k) + " AS ENUM (" + prop.values.map(driver.query.escapeVal.bind(driver)) + ")" ); } } for (k in opts.allProperties) { prop = opts.allProperties[k]; if (prop.unique === true) { definitions.push("UNIQUE (" + driver.query.escapeId(k) + ")"); } else if (prop.index) { definitions.push("INDEX (" + driver.query.escapeId(k) + ")"); } } definitions.push("PRIMARY KEY (" + primary_keys.join(", ") + ")"); tables.push({ name : opts.table, query : "CREATE TABLE " + driver.query.escapeId(opts.table) + " (" + definitions.join(", ") + ")", typequeries: typequeries, subqueries : subqueries }); for (i = 0; i < opts.one_associations.length; i++) { if (opts.one_associations[i].extension) continue; if (opts.one_associations[i].reversed) continue; for (k in opts.one_associations[i].field) { tables[tables.length - 1].subqueries.push( "CREATE INDEX ON " + driver.query.escapeId(opts.table) + " (" + driver.query.escapeId(k) + ")" ); } } for (i = 0; i < opts.indexes.length; i++) { tables[tables.length - 1].subqueries.push( "CREATE INDEX ON " + driver.query.escapeId(opts.table) + " (" + opts.indexes[i].split(/[,;]+/).map(function (el) { return driver.query.escapeId(el); }).join(", ") + ")" ); } for (i = 0; i < opts.many_associations.length; i++) { definitions = []; typequeries = []; for (k in opts.many_associations[i].mergeId) { definitions.push(buildColumnDefinition(driver, opts.many_associations[i].mergeTable, k, opts.many_associations[i].mergeId[k])); } for (k in opts.many_associations[i].mergeAssocId) { definitions.push(buildColumnDefinition(driver, opts.many_associations[i].mergeTable, k, opts.many_associations[i].mergeAssocId[k])); } for (k in opts.many_associations[i].props) { definitions.push(buildColumnDefinition(driver, opts.many_associations[i].mergeTable, k, opts.many_associations[i].props[k])); if (opts.many_associations[i].props[k].type == "enum") { typequeries.push( "CREATE TYPE " + driver.query.escapeId("enum_" + opts.many_associations[i].mergeTable + "_" + k) + " AS ENUM (" + opts.many_associations[i].props[k].values.map(driver.query.escapeVal.bind(driver)) + ")" ); } } var index = null; for (k in opts.many_associations[i].mergeId) { if (index == null) index = driver.query.escapeId(k); else index += ", " + driver.query.escapeId(k); } for (k in opts.many_associations[i].mergeAssocId) { if (index == null) index = driver.query.escapeId(k); else index += ", " + driver.query.escapeId(k); } tables.push({ name : opts.many_associations[i].mergeTable, query : "CREATE TABLE IF NOT EXISTS " + driver.query.escapeId(opts.many_associations[i].mergeTable) + " (" + definitions.join(", ") + ")", typequeries: typequeries, subqueries : [] }); tables[tables.length - 1].subqueries.push( "CREATE INDEX ON " + driver.query.escapeId(opts.many_associations[i].mergeTable) + " (" + index + ")" ); } pending = tables.length; for (i = 0; i < tables.length; i++) { createTableSchema(driver, tables[i], function (err) { if (--pending === 0) { // this will bring trouble in the future... // some errors are not avoided (like ENUM types already defined, etc..) return cb(err); } }); } }; function createTableSchema(driver, table, cb) { var pending = table.typequeries.length; var createTable = function () { driver.execQuery(table.query, function (err) { if (err || table.subqueries.length === 0) { return cb(err); } var pending = table.subqueries.length; for (var i = 0; i < table.subqueries.length; i++) { driver.execQuery(table.subqueries[i], function (err) { if (--pending === 0) { return cb(); } }); } }); }; if (pending === 0) { return createTable(); } for (var i = 0; i < table.typequeries.length; i++) { driver.execQuery(table.typequeries[i], function (err) { if (--pending === 0) { return createTable(); } }); } } var colTypes = { integer: { 2: 'SMALLINT', 4: 'INTEGER', 8: 'BIGINT' }, floating: { 4: 'REAL', 8: 'DOUBLE PRECISION' } }; function buildColumnDefinition(driver, table, name, prop) { var def = driver.query.escapeId(name); var customType; switch (prop.type) { case "text": if (prop.big === true) { def += " TEXT"; } else { def += " VARCHAR(" + Math.max(parseInt(prop.size, 10) || 255, 1) + ")"; } break; case "serial": def += " SERIAL"; break; case "number": if (prop.rational === false) { def += " " + colTypes.integer[prop.size || 4]; } else { def += " " + colTypes.floating[prop.size || 4]; } break; case "boolean": def += " BOOLEAN"; break; case "date": if (prop.time === false) { def += " DATE"; } else { def += " TIMESTAMP WITHOUT TIME ZONE"; } break; case "binary": case "object": def += " BYTEA"; break; case "enum": def += " " + driver.query.escapeId("enum_" + table + "_" + name); break; case "point": def += " POINT"; break; default: customType = driver.customTypes[prop.type]; if (customType) { def += " " + customType.datastoreType(prop); } else { throw ErrorCodes.generateError(ErrorCodes.NO_SUPPORT, "Unknown property type: '" + prop.type + "'", { property : prop }); } } if (prop.required === true) { def += " NOT NULL"; } if (prop.hasOwnProperty("defaultValue")) { def += " DEFAULT " + driver.query.escapeVal(prop.defaultValue); } return def; }
1.273438
1
src/Components/App.js
MaxBrockbank/Birres_with_Redux
0
3743
import React from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; import Header from './Header'; import Control from './Control'; import './../App.css'; import { Container } from 'react-bootstrap'; function App() { return ( <React.Fragment> <Container> <div className="pageAdjust"> <Header /> <Control /> </div> </Container> </React.Fragment> ); } export default App;
0.890625
1
cli/tests/tla3/timeout_loop.js
Preta-Crowz/deno
63,166
3751
export const foo = "foo"; export function delay(ms) { return new Promise((res) => setTimeout(() => { res(); }, ms) ); } let i = 0; async function timeoutLoop() { await delay(1000); console.log("timeout loop", i); i++; if (i > 5) { return; } timeoutLoop(); } timeoutLoop();
1.328125
1
src/utils/http.js
1224374619/Yinlinkrc-A
0
3759
// "use strict"; // import Vue from 'vue'; // import axios from "axios"; // import queryString from 'querystring' // // application/x-www-from-urlencode mime // // axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; // // axios.defaults.transformRequest = [function (data) { // // return queryString.stringify(data) // // }] // let config = { // //判断当前开发环境,切换代理配置 // baseURL: process.env.NODE_ENV === 'production' ? '/consumertest/' : '/api/', // timeout: 60 * 1000, // Timeout // withCredentials: true, // Check cross-site Access-Control // }; // const _axios = axios.create(config); // const instance= axios.create({ // baseURL: process.env.NODE_ENV === 'production' ? '/consumertest/' : '/api/', // headers:{'Content-Type':'application/x-www-form-urlencoded'}, // transformRequest:[ (data) => queryString.stringify(data)] // }) // Vue.prototype.$_http=instance; // _axios.interceptors.response.use(response => { // return response; // }, error => { // // logger and notification; // // Notification.error({ // // title: '错误', // // message: error.message // // }); // return Promise.reject(error); // }); // Plugin.install = function (Vue, options) { // Vue.axios = _axios; // window.axios = _axios; // Object.defineProperties(Vue.prototype, { // http: { // get() { // return _axios; // } // }, // $http: { // get() { // return _axios; // } // }, // }); // }; // Vue.use(Plugin) // export default _axios;
1.40625
1
server/db/seeds/comment.js
Aduda-Boaz/wikonnect
2
3767
exports.seed = function (knex) { // Deletes ALL existing entries return knex('comments').del() .then(function () { return knex('comments').insert([ { chapter_id: 'chapter1', comment: 'chapter1', creator_id: 'user1' }, { chapter_id: 'chapter1', comment: 'chapter1', creator_id: 'user1' }, { chapter_id: 'chapter2', comment: 'chapter2', creator_id: 'user2' }, { chapter_id: 'chapter2', comment: 'chapter2', creator_id: 'user3' } ]); }); };
0.90625
1
searchapp/node_modules/@appbaseio/reactivesearch/lib/appbase-js/node_modules/sha.js/sha1.js
lucmski/twint-docker
0
3775
'use strict'; /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright <NAME> 2000 - 2002. * Other contributors: <NAME>, <NAME>, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ var inherits = require('inherits'); var Hash = require('./hash'); var Buffer = require('safe-buffer').Buffer; var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0]; var W = new Array(80); function Sha1() { this.init(); this._w = W; Hash.call(this, 64, 56); } inherits(Sha1, Hash); Sha1.prototype.init = function () { this._a = 0x67452301; this._b = 0xefcdab89; this._c = 0x98badcfe; this._d = 0x10325476; this._e = 0xc3d2e1f0; return this; }; function rotl1(num) { return num << 1 | num >>> 31; } function rotl5(num) { return num << 5 | num >>> 27; } function rotl30(num) { return num << 30 | num >>> 2; } function ft(s, b, c, d) { if (s === 0) return b & c | ~b & d; if (s === 2) return b & c | b & d | c & d; return b ^ c ^ d; } Sha1.prototype._update = function (M) { var W = this._w; var a = this._a | 0; var b = this._b | 0; var c = this._c | 0; var d = this._d | 0; var e = this._e | 0; for (var i = 0; i < 16; ++i) { W[i] = M.readInt32BE(i * 4); }for (; i < 80; ++i) { W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]); }for (var j = 0; j < 80; ++j) { var s = ~~(j / 20); var t = rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s] | 0; e = d; d = c; c = rotl30(b); b = a; a = t; } this._a = a + this._a | 0; this._b = b + this._b | 0; this._c = c + this._c | 0; this._d = d + this._d | 0; this._e = e + this._e | 0; }; Sha1.prototype._hash = function () { var H = Buffer.allocUnsafe(20); H.writeInt32BE(this._a | 0, 0); H.writeInt32BE(this._b | 0, 4); H.writeInt32BE(this._c | 0, 8); H.writeInt32BE(this._d | 0, 12); H.writeInt32BE(this._e | 0, 16); return H; }; module.exports = Sha1;
2.453125
2
components/backButton.js
wchesley/FinalProject
0
3783
import React, { Component } from 'react' import { View, Text, Switch, StyleSheet } from 'react-native' import {NavigationActions} from 'react-navigation'; import { Icon } from 'react-native-elements' export class BackButton extends React.Component { render() { return ( <Icon name='backspace' //returns undefined? onPress={() => NavigationActions.navigate.goBack()} //same with this: // onPress={() => this.props.navigate.navigation.goBack()} /> ); } } export default BackButton
1.101563
1
src/SignaturePad.js
markrawls/react-signature-pad-wrapper
0
3791
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import SigPad from 'signature_pad'; import { debounce } from 'throttle-debounce'; /** * @class * @classdesc Signature pad component. * @extends {PureComponent} */ class SignaturePad extends PureComponent { static displayName = 'react-signature-pad-wrapper'; static propTypes = { width: PropTypes.number, height: PropTypes.number, options: PropTypes.object, redrawOnResize: PropTypes.bool.isRequired, debounceInterval: PropTypes.number.isRequired, canvasProps: PropTypes.object, }; static defaultProps = { redrawOnResize: false, debounceInterval: 150, }; /** * Create a new signature pad. * * @param {Object} props */ constructor(props) { super(props); this.state = { canvasWidth: 0, canvasHeight: 0 }; this._callResizeHandler = debounce(this.props.debounceInterval, this.handleResize.bind(this)); } /** * Initialise the signature pad once the canvas element is rendered. * * @return {void} */ componentDidMount() { if (this._canvas) { if (!this.props.width || !this.props.height) { this._canvas.style.width = '100%'; } this.scaleCanvas(); if (!this.props.width || !this.props.height) { window.addEventListener('resize', this._callResizeHandler); } this._signaturePad = new SigPad(this._canvas, this.props.options); } } /** * Remove the resize event listener and switch the signature pad off on * unmount. * * @return {void} */ componentWillUnmount() { if (!this.props.width || !this.props.height) { window.removeEventListener('resize', this._callResizeHandler); } this._signaturePad.off(); } /** * Get the original signature_pad instance. * * @return {SignaturePad} */ get instance() { return this._signaturePad; } /** * Get the canvas ref. * * @return {Object} */ get canvas() { return this._canvas; } /** * Set the radius of a single dot. * * @param {(number|Function)} dotSize * @return {void} */ set dotSize(dotSize) { this._signaturePad.dotSize = dotSize; } /** * Get the radius of a single dot. * * @return {number} */ get dotSize() { return this._signaturePad.dotSize; } /** * Set the minimum width of a line. * * @param {number} minWidth * @return {void} */ set minWidth(minWidth) { this._signaturePad.minWidth = minWidth; } /** * Get the minimum width of a line. * * @return {number} */ get minWidth() { return this._signaturePad.minWidth; } /** * Get the maximum width of a line. * * @param {number} maxWidth * @return {void} */ set maxWidth(maxWidth) { this._signaturePad.maxWidth = maxWidth; } /** * Get the maximum width of a line. * * @return {number} */ get maxWidth() { return this._signaturePad.maxWidth; } /** * Set the throttle for drawing the next point at most once every x ms. * * @param {number} throttle * @return {void} */ set throttle(throttle) { this._signaturePad.throttle = throttle; } /** * Get the throttle for drawing the next point at most once every x ms. * * @return {number} */ get throttle() { return this._signaturePad.throttle; } /** * Set the color used to clear the background. * * @param {string} color * @return {void} */ set backgroundColor(color) { this._signaturePad.backgroundColor = color; } /** * Get the color used to clear the background. * * @return {string} */ get backgroundColor() { return this._signaturePad.backgroundColor; } /** * Set the color used to draw the lines. * * @param {string} color * @return {void} */ set penColor(color) { this._signaturePad.penColor = color; } /** * Get the color used to draw the lines. * * @return {string} */ get penColor() { return this._signaturePad.penColor; } /** * Set weight used to modify new velocity based on the previous velocity. * * @param {number} weight * @return {void} */ set velocityFilterWeight(weight) { this._signaturePad.velocityFilterWeight = weight; } /** * Get weight used to modify new velocity based on the previous velocity. * * @return {number} */ get velocityFilterWeight() { return this._signaturePad.velocityFilterWeight; } /** * Set callback that will be triggered on stroke begin. * * @param {Function} fn * @return {void} */ set onBegin(fn) { if (!(fn && typeof fn === 'function')) { throw new Error('Invalid argument passed to onBegin()'); } this._signaturePad.onBegin = fn; } /** * Set callback that will be triggered on stroke end. * * @param {Function} fn * @return {void} */ set onEnd(fn) { if (!(fn && typeof fn === 'function')) { throw new Error('Invalid argument passed to onEnd()'); } this._signaturePad.onEnd = fn; } /** * Determine if the canvas is empty. * * @return {Boolean} */ isEmpty() { return this._signaturePad.isEmpty(); } /** * Clear the canvas. * * @return {void} */ clear() { this._signaturePad.clear(); } /** * Draw a signature from a data URL. * * @param {string} base64String * @return {void} */ fromDataURL(base64String) { this._signaturePad.fromDataURL(base64String); } /** * Get the signature data as a data URL. * * @param {string} mime * @return {string} */ toDataURL(mime) { return this._signaturePad.toDataURL(mime); } /** * Draw a signature from an array of point groups. * * @param {Array} data * @return {void} */ fromData(data) { this._signaturePad.fromData(data); } /** * Get the signature pad data an array of point groups. * * @return {Array} */ toData() { return this._signaturePad.toData(); } /** * Turn the signature pad off. * * @return {void} */ off() { this._signaturePad.off(); } /** * Turn the signature pad on. * * @return {void} */ on() { this._signaturePad.on(); } /** * Handle a resize event. * * @return {void} */ handleResize() { this.scaleCanvas(); } /** * Scale the canvas. * * @return {void} */ scaleCanvas() { const ratio = Math.max(window.devicePixelRatio || 1, 1); const width = (this.props.width || this._canvas.offsetWidth) * ratio; const height = (this.props.height || this._canvas.offsetHeight) * ratio; // Avoid needlessly setting height/width if dimensions haven't changed const { canvasWidth, canvasHeight } = this.state; if (width === canvasWidth && height === canvasHeight) return; let data; if (this.props.redrawOnResize && this._signaturePad) { data = this._signaturePad.toDataURL(); } this._canvas.width = width; this._canvas.height = height; this.setState({ canvasWidth: width, canvasHeight: height }); const ctx = this._canvas.getContext('2d'); ctx.scale(ratio, ratio); if (this.props.redrawOnResize && this._signaturePad) { this._signaturePad.fromDataURL(data); } else if (this._signaturePad) { this._signaturePad.clear(); } } /** * Render the signature pad component. * * @return {ReactElement} */ render() { const { canvasProps } = this.props; return <canvas ref={(ref) => (this._canvas = ref)} {...canvasProps} />; } } export default SignaturePad;
1.523438
2
dist/skylark-ace/mode/protobuf.js
skylark-integration/skylark-ace
0
3799
/** * skylark-ace - A version of ace v1.4.3 that ported to running on skylarkjs. * @author Hudaokeji Co.,Ltd * @version v0.9.0 * @link www.skylarkjs.org * @license MIT */ define(function(require,exports,module){"use strict";var t=require("../lib/oop"),i=require("./c_cpp").Mode,o=require("./protobuf_highlight_rules").ProtobufHighlightRules,e=require("./folding/cstyle").FoldMode,l=function(){i.call(this),this.foldingRules=new e,this.HighlightRules=o};t.inherits(l,i),function(){this.lineCommentStart="//",this.blockComment={start:"/*",end:"*/"},this.$id="ace/mode/protobuf"}.call(l.prototype),exports.Mode=l}); //# sourceMappingURL=../sourcemaps/mode/protobuf.js.map
1.117188
1
redux/locDuck.js
Carnabanegro/RN-RickAndMortyApp
0
3815
import ApolloClient, { gql } from 'apollo-boost'; import {updateLocationCurrentSearchAction} from './searchDuck'; //constant let initialData={ fetching: false, array: [],//array of locations nextPage: 1, error:false, errorMessage:"" } let client = new ApolloClient({ uri:"https://rickandmortyapi.com/graphql" }) let GET_LOCATIONS = "GET_LOCATIONS" let GET_LOCATIONS_SUCCESS = "GET_LOCATIONS_SUCCESS" let GET_LOCATIONS_ERROR = "GET_LOCATIONS_ERROR" let REMOVE_LOCATIONS = "REMOVE_LOCATIONS" let UPDATE_PAGE_LOC = "UPDATE_PAGE_LOC" export default function reducer(state=initialData, action){ switch(action.type){ case REMOVE_LOCATIONS: return {...state, array: [], nextPage:1, error:false, errorMessage:""} case GET_LOCATIONS: return{ ...state, fetching: true } case UPDATE_PAGE_LOC: return {...state, nextPage: action.payload} case GET_LOCATIONS_ERROR: return{ ...state,array: [], fetching:false, error: action.payload.error, errorMessage:action.payload.errorMessage} case GET_LOCATIONS_SUCCESS: return{ ...state, array: [...state.array,action.payload].flat() , fetching:false } default: return state } } //aux //action (thunks) export const removeLocationsAction = () => (dispatch, getState) =>{ updateLocationCurrentSearchAction("") dispatch({ type: REMOVE_LOCATIONS, }) } export let getLocationsAction = (value,select) => (dispatch,getState) => { let searchValue = value; let searchSelect = select; let query if (searchSelect === "name"){ query = gql`query ($page:Int,$search:String){ locations(page:$page,filter:{name:$search}){ info{ pages next prev } results{ id name type dimension residents{ name image } } } } ` }else{ query = gql`query ($page:Int,$search:String){ locations(page:$page,filter:{type:$search}){ info{ pages next prev } results{ id name type dimension residents{ name image } } } } ` } dispatch({ type: GET_LOCATIONS, }) let {nextPage} = getState().locations console.log(nextPage) return client.query({ query, variables: { search: searchValue, page:nextPage } }) .then(({ data}) => { dispatch({ type: GET_LOCATIONS_SUCCESS, payload: data.locations.results }) dispatch({ type: UPDATE_PAGE_LOC, payload: data.locations.info.next }) }) .catch(error =>{ dispatch({ type: GET_LOCATIONS_ERROR, payload:{ error:true, errorMessage:`Error! ${error}` } }) return }) }
1.796875
2
test/spec/handlers/index.js
bubkoo/random-json-from-template
1
3823
'use strict'; require('./number.spec.js'); require('./string.spec.js'); require('./boolean.spec.js'); require('./array.spec.js'); require('./object.spec.js'); require('./function.spec.js');
0.519531
1
docs/app/pods/components/transition-log-table/component.js
tomriley/ember-animated
0
3831
import Component from '@ember/component'; import { A } from '@ember/array'; import { action } from '@ember/object'; function printSprites(context) { return { inserted: context._insertedSprites.map((s) => s.owner.value.message), kept: context._keptSprites.map((s) => s.owner.value.message), removed: context._removedSprites.map((s) => s.owner.value.message), }; } export default Component.extend({ tagName: '', init() { this._super(); this.messages = A(); }, logTransition: action(function (context) { this.messages.pushObject(printSprites(context)); }), }); export const extensions = { init() { this._super(); this.transition = this.transition.bind(this); }, transition: function (context) { this.logTransition(context); return this._super(context); }, };
1.34375
1
client/app/lib/components/redux-form/SingleFileInput/__test__/BadgePreview.test.js
my-references/coursemology2
123
3839
import React from 'react'; import PropTypes from 'prop-types'; import { mount } from 'enzyme'; import BadgePreview from '../BadgePreview'; describe('<SingleFileInput />', () => { it('renders with url and name', () => { const badgePreview = mount( <BadgePreview originalName="bar" originalUrl="foo" />, { context: { intl, muiTheme }, // eslint-disable-line no-undef childContextTypes: { intl: intlShape, muiTheme: PropTypes.object, }, }, ); const avatar = badgePreview.find('Avatar').first(); expect(badgePreview.find('.file-name').text().includes('bar')).toEqual( true, ); expect(avatar.prop('src')).toEqual('foo'); expect(avatar.prop('icon')).toBeUndefined(); }); it('renders a placeholder when no url is provided', () => { const badgePreview = mount(<BadgePreview />, { context: { intl, muiTheme }, // eslint-disable-line no-undef childContextTypes: { intl: intlShape, muiTheme: PropTypes.object, }, }); const avatar = badgePreview.find('Avatar').first(); // SvgIcon is the element of the placeholder 'InsertDriveFileIcon' expect(avatar.find('SvgIcon').length).toBe(1); // No img element is rendered expect(avatar.find('img').length).toBe(0); }); });
1.476563
1
scripts/modules/Manager.js
ektabhagat22/parity
41
3847
var Manager = (function() { // Doesn't need to be interacted with, only mediates at a high level return { }; }()); // Add the mediator to the module mediator.installTo(Manager); // Loads the cookies when the story is finally loaded Manager.subscribe('loader_story_loaded', function() { mediator.publish('cookie_data_load'); }); // Sets bookmark for the story at the level loaded by the CookieDataManager Manager.subscribe('cookie_data_load_complete', function(saveObject) { mediator.publish('story_set_bookmark_at_level', saveObject); });
1.101563
1
Chapter 06/temperature_notifications/temperature_notifications.js
PacktPublishing/Building-Smart-Homes-with-Raspberry-Pi-Zero
26
3855
// Required modules var request = require('request'); var sensorLib = require('node-dht-sensor'); // IFTTT data var key = "key"; var eventName = 'data'; // Temperature sensor GPIO var sensorPin = 18; // Counter between two notifications var interval = 60 * 1000; // 1 minute var sensor = { initialize: function () { return sensorLib.initialize(11, sensorPin); }, read: function () { // Read var readout = sensorLib.read(); temperature = readout.temperature.toFixed(2); humidity = readout.humidity.toFixed(2); console.log('Current temperature: ' + temperature); console.log('Current humidity: ' + humidity); // Send event logIFTTT(temperature, humidity); // Repeat setTimeout(function () { sensor.read(); }, interval); } }; // Init sensor if (sensor.initialize()) { sensor.read(); } else { console.warn('Failed to initialize sensor'); } // Make request function logIFTTT(temperature, humidity) { // Send alert to IFTTT console.log("Sending message to IFTTT"); var url = 'https://maker.ifttt.com/trigger/' + eventName + '/with/key/' + key; url += '?value1=' + temperature + '&value2=' + humidity; request(url, function (error, response, body) { if (!error && response.statusCode == 200) { console.log("Data sent to IFTTT"); } }); }
1.820313
2
packages/react-frontend/src/websocket/reducer.js
ZechyW/cs-toolkit
1
3863
import { createReducer } from "redux-starter-kit"; import { open, close, subscribeAcknowledge, subscribeRequest } from "./actions"; /** * Handles WebSocket-related actions. * Action types are defined by the `redux-websocket-bridge` library. */ const initialState = { connected: false, subscriptions: {} }; const wsReducer = createReducer(initialState, { [open]: (state) => { state.connected = true; }, [close]: (state) => { state.connected = false; state.subscriptions = {}; }, [subscribeRequest]: (state, action) => { // If we have already started a subscription request to a model/instance, // we don't want other components to keep resending subscription // requests even if we haven't received a response yet. const model = action.payload.model; const id = action.payload.id; const subscriptionId = id ? `${model}:${id}` : `${model}`; state.subscriptions[subscriptionId] = "pending"; }, [subscribeAcknowledge]: (state, action) => { // Subscriptions may be to entire models, or specific model instances. const model = action.payload.model; const id = action.payload.id; const subscriptionId = id ? `${model}:${id}` : `${model}`; state.subscriptions[subscriptionId] = true; } }); export default wsReducer;
1.460938
1
components/channel_members_dropdown/index.js
sourabhlk/mattermost-webapp
0
3871
// Copyright (c) 2017 Mattermost, Inc. All Rights Reserved. // See License.txt for license information. import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {getChannelStats} from 'mattermost-redux/actions/channels'; import {haveIChannelPermission} from 'mattermost-redux/selectors/entities/roles'; import {getLicense} from 'mattermost-redux/selectors/entities/general'; import {Permissions} from 'mattermost-redux/constants'; import {canManageMembers} from 'utils/channel_utils.jsx'; import ChannelMembersDropdown from './channel_members_dropdown.jsx'; function mapStateToProps(state, ownProps) { const canChangeMemberRoles = haveIChannelPermission( state, { channel: ownProps.channel.id, team: ownProps.channel.team_id, permission: Permissions.MANAGE_CHANNEL_ROLES, } ); const license = getLicense(state); const isLicensed = license.IsLicensed === 'true'; const canRemoveMember = canManageMembers(ownProps.channel); return { isLicensed, canChangeMemberRoles, canRemoveMember, }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ getChannelStats, }, dispatch), }; } export default connect(mapStateToProps, mapDispatchToProps)(ChannelMembersDropdown);
1.3125
1
src/redux/timer/timerSelectors.js
RomanPidlisnychyi/timer
0
3879
import { createSelector } from '@reduxjs/toolkit'; import getTimeFormat from '../../common/getTimeFormat'; const getTime = state => state.time; const getSetIntervalId = state => state.setIntervalId; // const getSeconds = state => state.time; // const getMinutes = state => state; // const getHours = state => state; const getCurrentFormatByType = createSelector( [getTime, (state, timeType) => timeType], (time, timeType) => getTimeFormat(time, timeType) ); const timerSelectors = { getTime, getSetIntervalId, getCurrentFormatByType, }; export default timerSelectors;
1.273438
1
client/src/pages/Chatroom.js
girordo/EduSmart
21
3887
import React, { useEffect, useState } from "react"; import { Link, useHistory, useLocation } from "react-router-dom"; import { ChatRoomIcon } from "../assets/icons"; import Card from "../components/Card"; import ChatWindow from "./ChatWindow"; const Chatroom = ({ socket }) => { const location = useLocation(); console.log(socket); const [username, setUsername] = useState(""); const [showChat, setShowChat] = useState(false); const [room, setRoom] = useState(""); const history = useHistory(); const joinRoomstudent = () => { console.log("sds"); if (username !== "") { socket.emit("join_room", "student"); setShowChat(true); } else { alert("username is must !"); } }; const joinRoomteacher = () => { if (username !== "") { socket.emit("join_room", "teacher"); setShowChat(true); } else { alert("username is must !"); } }; useEffect(() => { if (location.state) setUsername(location.state.username); }, [username]); return ( <> <div className="w-full chatroom"> <div className="text-3xl text-white font-extralight m mt-8 text-center"> Chatroom </div> {!showChat ? ( <div className="flex justify-center items-center lg:justify-around lg:flex-row flex-col mt-16"> <div onClick={() => { joinRoomteacher(); setRoom("teacher"); }} className="my-5 w-5/6 "> <Card title="Teacher" /> </div> <div onClick={() => { joinRoomstudent(); setRoom("student"); }} className="my-5 w-5/6"> <Card title="Student" /> </div> </div> ) : ( <ChatWindow socket={socket} username={username} room={room} /> )} </div> </> ); }; export default Chatroom;
1.625
2
src/modules/App/index.js
ivo7690/Rangewell
205
3895
export Html from './Html' export default from './App'
-0.140625
0
api/node_modules/jsonwebtoken/index.js
hwj900702/MyBlog
1
3903
var jws = require('jws'); module.exports.decode = function (jwt) { return jws.decode(jwt).payload; }; module.exports.sign = function(payload, secretOrPrivateKey, options) { options = options || {}; var header = {typ: 'JWT', alg: options.algorithm || 'HS256'}; payload.iat = Math.round(Date.now() / 1000); if (options.expiresInMinutes) { var ms = options.expiresInMinutes * 60; payload.exp = payload.iat + ms; } if (options.audience) payload.aud = options.audience; if (options.issuer) payload.iss = options.issuer; if (options.subject) payload.sub = options.subject; var signed = jws.sign({header: header, payload: payload, secret: secretOrPrivateKey}); return signed; }; module.exports.verify = function(jwtString, secretOrPublicKey, options, callback) { if ((typeof options === 'function') && !callback) callback = options; if (!options) options = {}; var parts = jwtString.split('.'); if (parts.length < 3) return callback(new Error('jwt malformed')); if (parts[2].trim() === '' && secretOrPublicKey) return callback(new Error('jwt signature is required')); var valid; try { valid = jws.verify(jwtString, secretOrPublicKey); } catch (e) { return callback(e); } if (!valid) return callback(new Error('invalid signature')); var payload = this.decode(jwtString); if (payload.exp) { if (Math.round(Date.now()) / 1000 >= payload.exp) return callback(new Error('jwt expired')); } if (options.audience) { if (payload.aud !== options.audience) return callback(new Error('jwt audience invalid. expected: ' + payload.aud)); } if (options.issuer) { if (payload.iss !== options.issuer) return callback(new Error('jwt issuer invalid. expected: ' + payload.iss)); } callback(null, payload); };
1.414063
1
src/core_plugins/elasticsearch/lib/migrate_config.js
snide/kibana
0
3911
import upgrade from './upgrade_config'; import { SavedObjectsClient } from '../../../server/saved_objects'; export default async function (server, { mappings }) { const config = server.config(); const { callWithInternalUser } = server.plugins.elasticsearch.getCluster('admin'); const savedObjectsClient = new SavedObjectsClient(config.get('kibana.index'), mappings, callWithInternalUser); const { saved_objects: configSavedObjects } = await savedObjectsClient.find({ type: 'config', page: 1, perPage: 1000, sortField: 'buildNum', sortOrder: 'desc' }); return await upgrade(server, savedObjectsClient)(configSavedObjects); }
0.808594
1
test/performance-mark.js
BryanCrotaz/qunit
1
3919
QUnit.module( "urlParams performance mark module", function() { QUnit.test( "shouldn't fail if performance marks are cleared ", function( assert ) { performance.clearMarks(); assert.true( true ); } ); } );
0.867188
1
docs/reference/html/search/functions_f.js
FFCoder/Reddit.NET
493
3927
var searchData= [ ['qacommentsismonitored_3837',['QACommentsIsMonitored',['../class_reddit_1_1_controllers_1_1_comments.html#a1e4dabfccf0e0a32654d7255e0aeda17',1,'Reddit::Controllers::Comments']]], ['qareplies_3838',['QAReplies',['../class_reddit_tests_1_1_controller_tests_1_1_comment_tests.html#a85af18903f36acaa320e36b784464ee9',1,'RedditTests.ControllerTests.CommentTests.QAReplies()'],['../class_reddit_tests_1_1_controller_tests_1_1_post_tests.html#ace45a52ef29e998858da206e03584c1f',1,'RedditTests.ControllerTests.PostTests.QAReplies()']]] ];
0.000423
0
server/api/orders.js
gshop-jelly-toves/grace-shopper
0
3935
const router = require('express').Router() const { User, JellyOrder, Order, Jelly } = require('../db/models') const cartSession = require('./cartSession') // see /server/middlewares/user const { requireLogin, requireSeller, requireAdmin, requiredev } = require('../middlewares') module.exports = router //GET all orders for the session user ID router.get('/', requireLogin, async (req, res, next) => { try { const orders = await Order.findAll({ where: { userId: req.user.id } }) res.json(orders) } catch (e) { next(e) } }) //ADMIN ONLY //GET all orders router.get('/all', requireAdmin, async (req, res, next) => { try { const orders = await Order.findAll({ include: [{all: true }] }) res.json(orders) } catch (e) { next(e) } }) // include: [{model: JellyOrder}] router.get('/:orderId', requireAdmin, async (req, res, next) => { try { const order = await JellyOrder.findAll({ where: { orderId: req.params.orderId }, include: [{all: true }] }) res.json(order) } catch (e) { next(e) } }) router.put('/:orderId', requireAdmin, async (req, res, next) => { try { const order = await Order.findOne({ where: { id: req.params.orderId } }) order.update({ status: req.body.newOrderType }) res.json(order) } catch (e) { next(e) } })
1.414063
1
src/store/user/actions.js
thombruce/railgun
0
3943
import router from '@/router' import { gun, user } from '@/gun' const actions = { login ({ commit }, { username, password }) { commit('clearErrors') user.auth(username, password, (ack) => { if (!ack.err) router.push({ name: 'Documents' }) }) }, create ({ commit, dispatch }, { username, password }) { commit('clearErrors') gun.get('~@' + username).once((data) => { if (!data) { user.create(username, password, (ack) => { if (!ack.err) dispatch('login', { username, password }) }) } else { commit('addError', { username: 'User already exists' }) } }) }, update ({ commit }, { username, password, newPassword }) { commit('clearErrors') user.auth(username, password, (ack) => { if (!ack.err) router.push({ name: 'Documents' }) }, { change: newPassword }) }, logout ({ commit, dispatch }) { commit('clearErrors') user.leave() if (!user._.sea) { dispatch('documents/empty', null, { root: true }) router.push({ name: 'Login' }) } } } export default actions
1.414063
1
datefact.js
FabricLabs/doorman-datefact
0
3951
module.exports = function (Doorman) { return { commands: [ 'datefact' ], 'datefact': { usage: '<Question>', description: 'Gives a Random Date Fact.', process: (msg, suffix, isEdit, cb) => { request('http://numbersapi.com/random/date?json', function (err, res, body) { try { if (err) throw err; var data = JSON.parse(body); if (data && data.text) { cb({ embed: { color: Doorman.Config.discord.defaultEmbedColor, title: 'Date Fact', description: data.text } }, msg); } } catch (err) { var msgTxt = `command date_fact failed :disappointed_relieved:`; if (Doorman.Config.debug) { msgTxt += `\n${err.stack}`; Doorman.logError(err); } cb(msgTxt, msg); } }); } } } }
1.203125
1
js/starperu/star.js
CARLOSLUISGUTIERREZRAMOS/siststar
0
3959
$(function () { $('.date-calendar').datepicker({ language: "es", format: "dd/mm/yyyy", autoclose: true, todayHighlight: true }); cargarFechasActuales(); cargarListadoCarousel(); }); function cargarFechasActuales() { var y=new Date(); var today=devuelveDia(y.getDate())+'/'+devuelveMes(y.getMonth())+'/'+y.getFullYear(); $("input[name=desde]").datepicker('update',today); $("input[name=hasta]").datepicker('update',today); } function devuelveMes(mes) { var m=mes+1; m=m.toString(); if (m.length==1) { m='0'+m; } return m; } function devuelveDia(dia) { var d=dia.toString(); if (d.length==1) { d='0'+d; } return d; } $(document).on('click','#modal_starperu .btn-success',function (arg) { var form=$("#form-datos"); var formData = new FormData(form[0]); var tipo=$("#tipo").val(); var id = $(this).data('id') ? $(this).data('id') : 'n'; var button =$(this); var btncancelar=$("#modal_starperu .btn-danger"); button.html('<i class="fa fa-refresh fa-lg fa-spin"></i> Procesando'); button.attr('disabled',true); btncancelar.attr('disabled',true); $.ajax({ url: URLs+'starperu/Star/GuardarRegistro', data: formData, type: 'POST', contentType: false, processData: false, success: function(resultado) { button.html('<span class="fa fa-plus"></span> Agregar'); btncancelar.attr('disabled',false); button.attr('disabled',false); var data=JSON.parse(resultado); if (data.error_msg!=undefined) { mostrarMsgError(data.error_msg,1); } else{ if (tipo==1) { var length=objstar.length+1; data.id=length; objstar.unshift(data);//inserta en la primera posicion // objstar.push(data);//inserta en la ultima posicion } else{ if (id!='n') { data.id=objstar[id].id; objstar[id]=data; } // id != 'n' ? (objstar[id]=data) : ''; } enviarDataObjeto(); cargarListadoCarousel(); resetearFormulario(); $("#modal_starperu").modal('hide'); } } }); }); function enviarDataObjeto() { var json_tring=JSON.stringify(objstar).replace('#',''); $.ajax({ // url: URLs+'starperu/Star/ModificarObjetoJson', url:'https://www.starperu.com/es/server.php', data: 'objstar='+json_tring, type: 'GET', success: function(resultado) { } }); } function cargarListadoCarousel() { var tbody=$("#tbl_imagenes tbody"); tbody.empty(); $.each(objstar,function (index,element) { var tr; tr='<tr>'; tr+='<td>'+ '<img src="'+element.imagen+'" width="150">'+ '</td>'; tr+='<td>'+ '<span>'+(element.banner==1?element.desde:'-')+'</span><br>'+ '<span>'+(element.banner==1?element.inicio:'-')+'</span>'+ '</td>'; tr+='<td>'+ '<span>'+(element.banner==1?element.hasta:'-')+'</span><br>'+ '<span>'+(element.banner==1?element.fin:'-')+'</span>'+ '</td>'; tr+='<td>'+ (element.link ? ('<a href="https://www.starperu.com/es/'+element.link+'.'+element.extension+'" target="_blank">'+element.link+'</a>') : 'Sin direccionamiento')+ '</td>'; tr+='<td>'+ '<span class="label label-danger">'+element.prioridad+'</span><br>'+ '</td>'; tr+='<td>'+ '<input type="checkbox" class="checkbox-check" value="'+index+'|'+element.estado+'" '+(element.estado==1? 'checked' : '')+' title="'+(element.estado==1?'Publicado' : 'Por publicar')+'">'+ '</td>'; tr+='<td>'+ '<button class="btn btn-sm btn-success editar-carousel" title="Editar Carousel" id="'+index+'">'+ '<span class="fa fa-edit fa-lg"></span>'+ '</button>'+ // '<button class="btn btn-sm btn-danger eliminar-carousel" title="Eliminar Carousel" id="'+index+'" style="margin-left: 5px">'+ // '<span class="fa fa-trash fa-lg"></span>'+ // '</button>'+ (element.id!=1 ?('<button class="btn btn-sm btn-danger eliminar-carousel" title="Eliminar Carousel" id="'+index+'" style="margin-left: 5px">'+ '<span class="fa fa-trash fa-lg"></span>'+ '</button>') : '')+ '</td>'; tr+='</tr>'; tbody.append(tr); }); } function validarFormulario() { var form=$("#modal_starperu .panel-body"); var b=0; var tipo=$("input[name=tipo]").val(); $.each(form.find('input,select'),function (index,input) { var element=$(input); if (element.attr('data-req')==1) { if (element.val()!="") { b++; } } }); if (tipo==1) { return b==5 ? true : false; } else{ return b>=4 ? true : false; } } function disableBotonAgregar() { var button=$("#modal_starperu .btn-success"); if (!validarFormulario()) { button.attr('disabled',true); } else{ button.attr('disabled',false); } } function resetearFormulario() { var form=$("#form-datos"); var frame=$(".table-imagen"); var msg=$(".mensajes-error .col-md-12"); var button=$("#modal_starperu .btn-success"); form[0].reset(); frame.html(''); frame.addClass('hide'); msg.empty(); button.html('<span class="fa fa-plus"></span> Agregar'); button.data('id',''); $("#tipo").val(1); $("select[name=banner]").val(1).trigger('change'); cargarFechasActuales(); } $(document).on('click','.btn-agregar-nuevo',function (arg) { resetearFormulario(); disableBotonAgregar(); $("#modal_starperu").modal({backdrop: 'static', keyboard: false}); }); $(document).on('keyup change','.input-key',function (e) { var input=$(this); disableBotonAgregar(); if (input.attr('data-req')==1) { if (this.value!="") { input.parent().removeClass("has-error"); } } }); $(document).on('click','.editar-carousel',function (arg) { resetearFormulario(); var id=this.id; var objeto=objstar[id]; var frame=$(".table-imagen"); var button=$("#modal_starperu .btn-success"); $("select[name=banner]").val(objeto.banner).trigger('change'); $("input[name=desde]").datepicker('update',objeto.desde); $("input[name=hasta]").datepicker('update',objeto.hasta); $("input[name=inicio]").val(objeto.inicio); $("input[name=fin]").val(objeto.fin); $("input[name=link]").val(objeto.link); $("input[name=url_img]").val(objeto.imagen); $("select[name=promocion]").val(objeto.promocion); $("select[name=estado]").val(objeto.estado); $("select[name=extension]").val(objeto.extension); $("select[name=prioridad]").val(objeto.prioridad); $("input[name=tipo]").val(2); $("input[name=estado_img]").val(2); frame.html('<br><div class="col-md-12"><img src="'+objeto.imagen+'" width="100%" style="height: 300px;"></div>'); frame.removeClass('hide'); disableBotonAgregar(); button.data('id',id); button.html('<span class="fa fa-save"></span> Guardar Cambios'); $("#modal_starperu").modal({backdrop: 'static', keyboard: false}); }); $(document).on('click','.eliminar-carousel',function (arg) { var id=this.id; $("#modal_eliminar_registro .btn-success").data('id',id); $("#modal_eliminar_registro").modal({backdrop: 'static', keyboard: false}); }); $(document).on('click','#modal_eliminar_registro .btn-success',function (arg) { var id=$(this).data('id'); var url_img=objstar[id].imagen; var formData='url_img='+url_img+'&tipo='+2; var button=$(this); button.html('<i class="fa fa-refresh fa-lg fa-spin"></i> Procesando'); $.ajax({ url: URLs+'starperu/Star/EliminarRegistroImagen', data: formData, type: 'POST', success: function(resultado) { button.html('<i class="fa fa-trash"></i> Sí, entendido'); if (resultado=='ok') { objstar.splice(id,1); enviarDataObjeto(); cargarListadoCarousel(); $("#modal_eliminar_registro").modal('hide'); } } }); }); $(document).on('change','select[name=promocion]',function (arg) { if (this.value==1) { $("input[name=link]").val('promociones'); $("select[name=extension]").val('html'); } else{ $("input[name=link]").val(''); } }); $(document).on('change','select[name=banner]',function (arg) { if (this.value==1) { $(".fechas").removeClass('hide'); } else{ $(".fechas").addClass('hide'); } }); $(document).on('click','.checkbox-check',function (arg) { var val=this.value.split('|'); var estado; if (val[1]==1) { this.value=val[0]+'|'+0; estado=0; } else{ this.value=val[0]+'|'+1; estado=1; } objstar[val[0]].estado=estado; enviarDataObjeto(); }); function archivoFile(evt) { var files = evt.target.files; // FileList object var frame=$(".table-imagen"); var tipo = $("input[name=tipo]").val(); if (files.length==0) { frame.html(''); $("#imagen").val(''); disableBotonAgregar(); $("input[name=estado_img]").val(2); tipo == 1 ? mostrarMsgError('Seleccione una imagen.',3) : ''; } else{ if (files[0].type =="image/jpeg" || files[0].type =="image/png" || files[0].type =="image/jpeg") { imgfile_url=URL.createObjectURL(files[0]); frame.html('<br><div class="col-md-12"><img src="'+imgfile_url +'" width="100%" style="height: 300px;"></div>'); frame.removeClass('hide'); disableBotonAgregar(); $("input[name=estado_img]").val(1); } else{ $("#imagen").val(''); frame.addClass('hide'); mostrarMsgError('No se aceptan archivos solo imagenes en formato PNG,JPG y JPEG.',1); disableBotonAgregar(); $("input[name=estado_img]").val(2); } } } $("#imagen").change(function(event) { archivoFile(event); }); function mostrarMsgError(msg,estado) { var frame=$(".mensajes-error .col-md-12"); var color; if (estado==1) { color='d23b2994'; //error->rojo } else if (estado==2) { color='8BC34A '; //success->verde } else if (estado ==3) { color='FF9800'; //warning->naranja } frame.html('<div class="alert alert-warning alert-dismissible" role="alert" style="background-color: #'+color+' !important; border-color: #'+color+'">'+ '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'+ '<span aria-hidden="true">&times;</span>'+ '</button>'+ '<strong>Alerta!</strong> '+msg+ '</div>'); }
0.984375
1
GCanvas/js/src/context-webgl/Shader.js
nicholasalx/GCanvas
2,076
3967
import {getTransferedObjectUUID} from './classUtils'; const name = 'WebGLShader'; function uuid(id) { return getTransferedObjectUUID(name, id); } export default class WebGLShader { className = name; constructor(id, type) { this.id = id; this.type = type; } static uuid = uuid; uuid() { return uuid(this.id); } }
1.054688
1
public/js/init_editor.js
OsalaV/OBA-Web
0
3975
$(document).ready(function() { $('.savbtn').click(function() { if($("#descr").length){$("#descr").empty();} $('#descr').html($('#editor').html()); }); }); $(function() { function initToolbarBootstrapBindings() { var fonts = ['sans-serif', 'Sans', 'Arial', 'Arial Black', 'Courier', 'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', 'Lucida Sans', 'Tahoma', 'Times', 'Times New Roman', 'Verdana' ], fontTarget = $('[title=Font]').siblings('.dropdown-menu'); $.each(fonts, function(idx, fontName) { fontTarget.append($('<li><a data-edit="fontName ' + fontName + '" style="font-family:\'' + fontName + '\'">' + fontName + '</a></li>')); }); $('a[title]').tooltip({ container: 'body' }); $('.dropdown-menu input').click(function() { return false; }) .change(function() { $(this).parent('.dropdown-menu').siblings('.dropdown-toggle').dropdown('toggle'); }) .keydown('esc', function() { this.value = ''; $(this).change(); }); $('[data-role=magic-overlay]').each(function() { var overlay = $(this), target = $(overlay.data('target')); overlay.css('opacity', 0).css('position', 'absolute').offset(target.offset()).width(target.outerWidth()).height(target.outerHeight()); }); if ("onwebkitspeechchange" in document.createElement("input")) { var editorOffset = $('#editor').offset(); $('#voiceBtn').css('position', 'absolute').offset({ top: editorOffset.top, left: editorOffset.left + $('#editor').innerWidth() - 35 }); } else { $('#voiceBtn').hide(); } }; function showErrorAlert(reason, detail) { var msg = ''; if (reason === 'unsupported-file-type') { msg = "Unsupported format " + detail; } else { console.log("error uploading file", reason, detail); } $('<div class="alert"> <button type="button" class="close" data-dismiss="alert">&times;</button>' + '<strong>File upload error</strong> ' + msg + ' </div>').prependTo('#alerts'); }; initToolbarBootstrapBindings(); $('#editor').wysiwyg({ fileUploadError: showErrorAlert }); window.prettyPrint && prettyPrint(); });
0.898438
1
09_JS_Advanced/JavaScript/WebContent/20_OldExams/20161113_exam.js
akkirilov/ProgrammingFundamentalsHomeworks
0
3983
// 01. Add / Remove Towns function attachEvents() { $('#btnDelete').on('click', function() { $('#towns option:selected').remove(); }); $('#btnAdd').on('click', function() { let newItem = $('#newItem'); if (newItem.val() == '') { return; } $('#towns').append($('<option>').text(newItem.val())); newItem.val(''); }); } // 02. Add / Swap / Shift Left / Right in List //Tests in p20_20161113_02_tests.js function createList() { let data = []; return { add: function (item) { data.push(item) }, shiftLeft: function () { if (data.length > 1) { let first = data.shift(); data.push(first); } }, shiftRight: function () { if (data.length > 1) { let last = data.pop(); data.unshift(last); } }, swap: function (index1, index2) { if (!Number.isInteger(index1) || index1 < 0 || index1 >= data.length || !Number.isInteger(index2) || index2 < 0 || index2 >= data.length || index1 === index2) { return false; } let temp = data[index1]; data[index1] = data[index2]; data[index2] = temp; return true; }, toString: function () { return data.join(", "); } }; } // 03. Mail Box class MailBox { constructor() { this.messages = []; } get messageCount() { return this.messages.length; } addMessage(subject, text) { this.messages.push({subject: subject, text: text}); return this; } deleteAllMessages() { this.messages = []; } findBySubject(substr) { return this.messages.filter(x => x.subject.includes(substr)); } toString() { if (this.messages.length === 0) { return '* (empty mailbox)'; } return this.messages.map(x => '* [' + x.subject + '] ' + x.text).join('\n'); } } // 04. Cards function cardDeckBuilder(selector) { let validFaces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']; let validSuits = {C: '\u2663', S: '\u2660', D: '\u2666', H: '\u2665'} let el = $(selector); function createCard(face, suit) { if (validFaces.indexOf(face) < 0 || validSuits[suit] === undefined) { return undefined; } return face + ' ' + validSuits[suit]; } function reverseOrder() { let cards = el.children('.card'); el.append(cards.get().reverse()); } return { addCard: function (face, suit) { let card = createCard(face, suit); if (card !== undefined) { let newCard = $('<div>').addClass('card').text(card); newCard.on('click', reverseOrder); el.append(newCard); } } } } module.exports = { createList };
1.679688
2
gulpfile.js
hackclub/shipit
6
3991
const gulp = require("gulp"); const autoPrefixer = require("gulp-autoprefixer"); const cleanCSS = require("gulp-clean-css"); const concat = require("gulp-concat"); const sass = require("gulp-sass"); const pump = require("pump"); // Change to another module with ES6 support const composer = require("gulp-uglify/composer"); const uglify = composer(require("uglify-es"), console); const SASS_PATHS = [ "asset/sass/**/*.scss" ]; gulp.task("default", ["watch"]); gulp.task("build", ["build-css"]); gulp.task("build-css", cb => { pump([ gulp.src(SASS_PATHS), sass(), autoPrefixer(), cleanCSS({ compatibility: "ie8", rebase: false }), concat("shipit.min.css"), gulp.dest("asset/dist/") ], cb); }); gulp.task("watch", ["watch-css"]); gulp.task("watch-css", () => gulp.watch(SASS_PATHS, ["build-css"]));
1.070313
1
examples/HierarchicalKey.js
AKCore/arcadecore
0
3999
var run = function() { bitcore = typeof(bitcore) === 'undefined' ? require('../monacore') : bitcore; var HierarchicalKey = bitcore.HierarchicalKey; var Address = bitcore.Address; var networks = bitcore.networks; var coinUtil = bitcore.util; var crypto = require('crypto'); console.log('HierarchicalKey: Hierarchical Deterministic Wallets (BIP32)'); console.log('https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki\n'); console.log('1) Make new hkey from randomly generated new seed'); var randomBytes = crypto.randomBytes(32); var hkey = HierarchicalKey.seed(randomBytes); console.log('master extended private key: ' + hkey.extendedPrivateKeyString()); console.log('master extended public key: ' + hkey.extendedPublicKeyString()); console.log('m/0/3/5 extended private key: ' + hkey.derive('m/0/3/5').extendedPrivateKeyString()); console.log('m/0/3/5 extended public key: ' + hkey.derive('m/0/3/5').extendedPublicKeyString()); console.log(); console.log('2) Make new hkey from known seed'); var knownBytes = coinUtil.sha256('do not use this password as a brain wallet'); var hkey = HierarchicalKey.seed(knownBytes); console.log('master extended private key: ' + hkey.extendedPrivateKeyString()); console.log('master extended public key: ' + hkey.extendedPublicKeyString()); console.log('m/0/3/5 extended private key: ' + hkey.derive('m/0/3/5').extendedPrivateKeyString()); console.log('m/0/3/5 extended public key: ' + hkey.derive('m/0/3/5').extendedPublicKeyString()); console.log(); console.log('3) Make new hkey from known master private key'); var knownMasterPrivateKey = '<KEY>'; var hkey = new HierarchicalKey(knownMasterPrivateKey); console.log('master extended private key: ' + hkey.extendedPrivateKeyString()); console.log('master extended public key: ' + hkey.extendedPublicKeyString()); console.log('m/0/3/5 extended private key: ' + hkey.derive('m/0/3/5').extendedPrivateKeyString()); console.log('m/0/3/5 extended public key: ' + hkey.derive('m/0/3/5').extendedPublicKeyString()); console.log(); console.log('4) Make new hkey from known master public key'); var knownMasterPublicKey = '<KEY>'; var hkey = new HierarchicalKey(knownMasterPublicKey); console.log('master extended private key: cannot derive'); console.log('master extended public key: ' + hkey.extendedPublicKeyString()); console.log('m/0/3/5 extended private key: cannot derive'); console.log('m/0/3/5 extended public key: ' + hkey.derive('m/0/3/5').extendedPublicKeyString()); console.log(); console.log('5) Make new hkey from known derived public key'); var knownPublicKey = '<KEY>'; var hkey = new HierarchicalKey(knownPublicKey); console.log('master extended private key: cannot derive'); console.log('master extended public key: ' + hkey.extendedPublicKeyString()); console.log('m/0/3/5 extended private key: cannot derive'); console.log('m/0/3/5 extended public key: ' + hkey.derive('m/0/3/5').extendedPublicKeyString()); console.log(); console.log('6) Make a bunch of new addresses from known public key'); var knownPublicKey = '<KEY>'; var hkey = new HierarchicalKey(knownPublicKey); console.log('m/0 address: ' + Address.fromPubKey(hkey.derive('m/0').eckey.public).toString()); //console.log('m/1 extended public key: ' + hkey.derive('m/1').extendedPublicKeyString()); console.log('m/1 address: ' + Address.fromPubKey(hkey.derive('m/1').eckey.public).toString()); //console.log('m/2 extended public key: ' + hkey.derive('m/2').extendedPublicKeyString()); console.log('m/2 address: ' + Address.fromPubKey(hkey.derive('m/2').eckey.public).toString()); //console.log('m/3 extended public key: ' + hkey.derive('m/3').extendedPublicKeyString()); console.log('m/3 address: ' + Address.fromPubKey(hkey.derive('m/3').eckey.public).toString()); console.log('...'); //console.log('m/100 extended public key: ' + hkey.derive('m/100').extendedPublicKeyString()); console.log('m/100 address: ' + Address.fromPubKey(hkey.derive('m/100').eckey.public).toString()); console.log(); }; // This is just for browser & mocha compatibility if (typeof module !== 'undefined') { module.exports.run = run; if (require.main === module) { run(); } } else { run(); }
1.507813
2
packages/plugins/typescript/vue-urql/dist/index.js
shiwano/graphql-code-generator
0
4007
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } const graphql = require('graphql'); const visitorPluginCommon = require('@graphql-codegen/visitor-plugin-common'); const autoBind = _interopDefault(require('auto-bind')); const changeCaseAll = require('change-case-all'); const path = require('path'); class UrqlVisitor extends visitorPluginCommon.ClientSideBaseVisitor { constructor(schema, fragments, rawConfig) { super(schema, fragments, rawConfig, { withComposition: visitorPluginCommon.getConfigValue(rawConfig.withComposition, true), urqlImportFrom: visitorPluginCommon.getConfigValue(rawConfig.urqlImportFrom, '@urql/vue'), }); autoBind(this); } getImports() { const baseImports = super.getImports(); const imports = []; const hasOperations = this._collectedOperations.length > 0; if (!hasOperations) { return baseImports; } if (this.config.withComposition) { imports.push(`import * as Urql from '${this.config.urqlImportFrom}';`); } imports.push(visitorPluginCommon.OMIT_TYPE); return [...baseImports, ...imports]; } _buildCompositionFn(node, operationType, documentVariableName, operationResultType, operationVariablesTypes) { var _a, _b; const operationName = this.convertName((_b = (_a = node.name) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : '', { suffix: this.config.omitOperationSuffix ? '' : changeCaseAll.pascalCase(operationType), useTypesPrefix: false, }); if (operationType === 'Mutation') { return ` export function use${operationName}() { return Urql.use${operationType}<${operationResultType}, ${operationVariablesTypes}>(${documentVariableName}); };`; } if (operationType === 'Subscription') { return ` export function use${operationName}<R = ${operationResultType}>(options: Omit<Urql.Use${operationType}Args<never, ${operationVariablesTypes}>, 'query'> = {}, handler?: Urql.SubscriptionHandlerArg<${operationResultType}, R>) { return Urql.use${operationType}<${operationResultType}, R, ${operationVariablesTypes}>({ query: ${documentVariableName}, ...options }, handler); };`; } return ` export function use${operationName}(options: Omit<Urql.Use${operationType}Args<never, ${operationVariablesTypes}>, 'query'> = {}) { return Urql.use${operationType}<${operationResultType}>({ query: ${documentVariableName}, ...options }); };`; } buildOperation(node, documentVariableName, operationType, operationResultType, operationVariablesTypes) { const composition = this.config.withComposition ? this._buildCompositionFn(node, operationType, documentVariableName, operationResultType, operationVariablesTypes) : null; return [composition].filter(a => a).join('\n'); } } const plugin = (schema, documents, config) => { const allAst = graphql.concatAST(documents.map(v => v.document)); const allFragments = [ ...allAst.definitions.filter(d => d.kind === graphql.Kind.FRAGMENT_DEFINITION).map(fragmentDef => ({ node: fragmentDef, name: fragmentDef.name.value, onType: fragmentDef.typeCondition.name.value, isExternal: false, })), ...(config.externalFragments || []), ]; const visitor = new UrqlVisitor(schema, allFragments, config); const visitorResult = graphql.visit(allAst, { leave: visitor }); return { prepend: visitor.getImports(), content: [visitor.fragments, ...visitorResult.definitions.filter(t => typeof t === 'string')].join('\n'), }; }; const validate = async (schema, documents, config, outputFile) => { if (path.extname(outputFile) !== '.ts') { throw new Error(`Plugin "typescript-vue-urql" requires extension to be ".ts"!`); } }; exports.UrqlVisitor = UrqlVisitor; exports.plugin = plugin; exports.validate = validate;
1.289063
1
etc/config.js
sillelien/docker-usergrid-server
1
4015
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var Usergrid = Usergrid || {}; Usergrid.showNotifcations = true; // used only if hostname does not match a real server name Usergrid.overrideUrl = '${USERGRID_URL}/api'; Usergrid.options = { client:{ requiresDeveloperKey:false // apiKey:'123456' }, showAutoRefresh:true, autoUpdateTimer:61, //seconds menuItems:[ {path:'#!/org-overview', active:true,pic:'&#128362;',title:'Org Administration'}, {path:'#!/app-overview/summary',pic:'&#59214;',title:'App Overview'}, {path:'#!/users',pic:'&#128100;',title:'Users'}, {path:'#!/groups',pic:'&#128101;',title:'Groups'}, {path:'#!/roles',pic:'&#59170;',title:'Roles'}, {path:'#!/data',pic:'&#128248;',title:'Data'}, {path:'#!/activities',pic:'&#59194;',title:'Activities'}, {path:'#!/shell',pic:'&#9000;',title:'Shell'} ] }; Usergrid.regex = { appNameRegex: new RegExp("^[0-9a-zA-Z.-]{3,25}$"), usernameRegex: new RegExp("^[0-9a-zA-Z@\.\_-]{4,25}$"), nameRegex: new RegExp("^([0-9a-zA-Z@#$%^&!?;:.,'\"~*-:+_\[\\](){}/\\ |]{3,60})+$"), roleNameRegex: new RegExp("^([0-9a-zA-Z./-]{3,25})+$"), emailRegex: new RegExp("^(([0-9a-zA-Z]+[_\+.-]?)+@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$"), passwordRegex: /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, pathRegex: new RegExp("^/[a-zA-Z0-9\.\*_\$\{\}~-]+(\/[a-zA-Z0-9\.\*_\$\{\}~-]+)*$"), titleRegex: new RegExp("[a-zA-Z0-9.!-?]+[\/]?"), urlRegex: new RegExp("^(http?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$"), zipRegex: new RegExp("^[0-9]{5}(?:-[0-9]{4})?$"), countryRegex: new RegExp("^[A-Za-z ]{3,100}$"), stateRegex: new RegExp("^[A-Za-z ]{2,100}$"), collectionNameRegex: new RegExp("^[0-9a-zA-Z_.]{3,25}$"), appNameRegexDescription: "This field only allows : A-Z, a-z, 0-9, dot, and dash and must be between 3-25 characters.", usernameRegexDescription: "This field only allows : A-Z, a-z, 0-9, dot, underscore and dash. Must be between 4 and 15 characters.", nameRegexDescription: "Please enter a valid name. Must be betwee 3 and 60 characters.", roleNameRegexDescription: "Role only allows : /, a-z, 0-9, dot, and dash. Must be between 3 and 25 characters.", emailRegexDescription: "Please enter a valid email.", passwordRegexDescription: "Password must contain at least 1 upper and lower case letter, one number or special character and be at least 8 characters.", pathRegexDescription: "Path must begin with a slash, path only allows: /, a-z, 0-9, dot, and dash, paths of the format: /path/ or /path//path are not allowed", titleRegexDescription: "Please enter a valid title.", urlRegexDescription: "Please enter a valid url", zipRegexDescription: "Please enter a valid zip code.", countryRegexDescription: "Sorry only alphabetical characters or spaces are allowed. Must be between 3-100 characters.", stateRegexDescription: "Sorry only alphabetical characters or spaces are allowed. Must be between 2-100 characters.", collectionNameRegexDescription: "Collection name only allows : a-z A-Z 0-9. Must be between 3-25 characters." };
1
1
web/bundles/applicationbootstrap/js/forms/jquery.inputmask/Gruntfile.js
sidczak/development
1
4023
module.exports = function (grunt) { function createBanner(fileName) { return '/*!\n' + '* ' + fileName + '\n' + '* http://github.com/RobinHerbots/jquery.inputmask\n' + '* Copyright (c) 2010 - <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>\n' + '* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)\n' + '* Version: <%= pkg.version %>\n' + '*/\n'; } function createUglifyConfig(path) { var uglifyConfig = {}; var srcFiles = grunt.file.expand(path + "/*.js"); for (var srcNdx in srcFiles) { var dstFile = srcFiles[srcNdx].replace("js/", ""); wrapAMDLoader(srcFiles[srcNdx], "build/" + dstFile, dstFile.indexOf("extension") == -1 ? ["jquery"] : ["jquery", "./jquery.inputmask"]); uglifyConfig[dstFile] = { dest: 'dist/inputmask/' + dstFile, src: "build/" + dstFile, options: { banner: createBanner(dstFile), beautify: true, mangle: false, preserveComments: "some" } }; } srcFiles = grunt.file.expand(path + "/*.extensions.js"); srcFiles.splice(0, 0, "js/jquery.inputmask.js"); uglifyConfig["inputmaskbundle"] = { files: { 'dist/<%= pkg.name %>.bundle.js': srcFiles }, options: { banner: createBanner('<%= pkg.name %>.bundle'), beautify: true, mangle: false, preserveComments: "some" } } uglifyConfig["inputmaskbundlemin"] = { files: { 'dist/<%= pkg.name %>.bundle.min.js': srcFiles }, options: { banner: createBanner('<%= pkg.name %>.bundle'), preserveComments: "some" } } return uglifyConfig; } function wrapAMDLoader(src, dst, dependencies) { function stripClosureExecution() { return srcFile.replace(new RegExp("\\(jQuery\\).*$"), ""); } var srcFile = grunt.file.read(src), dstContent = "(function (factory) {" + "if (typeof define === 'function' && define.amd) {" + "define(" + JSON.stringify(dependencies) + ", factory);" + "} else {" + "factory(jQuery);" + "}}\n" + stripClosureExecution() + ");"; grunt.file.write(dst, dstContent); } // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: createUglifyConfig("js"), clean: ["dist"], qunit: { files: ['qunit/qunit.html'] }, bump: { options: { files: ['package.json', 'bower.json', 'jquery.inputmask.jquery.json'], updateConfigs: ['pkg'], commit: false, createTag: false, push: false } }, release: { options: { bump: false, commitMessage: 'jquery.inputmask <%= version %>' } }, nugetpack: { dist: { src: function () { return process.platform === "linux" ? 'nuget/jquery.inputmask.linux.nuspec' : 'nuget/jquery.inputmask.nuspec'; }(), dest: 'dist/', options: { version: '<%= pkg.version %>' } } }, nugetpush: { dist: { src: 'dist/jQuery.InputMask.<%= pkg.version %>.nupkg' } }, shell: { options: { stderr: false }, gitcommitchanges: { command: ['git add .', 'git reset -- package.json', 'git commit -m "jquery.inputmask <%= pkg.version %>"' ].join('&&') } } }); // Load the plugin that provides the tasks. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-qunit'); grunt.loadNpmTasks('grunt-bump'); grunt.loadNpmTasks('grunt-release'); grunt.loadNpmTasks('grunt-nuget'); grunt.loadNpmTasks('grunt-shell'); grunt.registerTask('publish:patch', ['clean', 'bump:patch', 'uglify', 'shell:gitcommitchanges', 'release', 'nugetpack', 'nugetpush']); grunt.registerTask('publish:minor', ['clean', 'bump:minor', 'uglify', 'shell:gitcommitchanges', 'release', 'nugetpack', 'nugetpush']); grunt.registerTask('publish:major', ['clean', 'bump:major', 'uglify', 'shell:gitcommitchanges', 'release', 'nugetpack', 'nugetpush']); // Default task(s). grunt.registerTask('default', ['clean', 'uglify']); };
1.375
1