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
|
---|---|---|---|---|---|---|
dist/transformers/transformer/dictionary.transformer.js | anowrot/Kakunin | 0 | 2415 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createDictionaryTransformer = undefined;
var _dictionaries = require('../../dictionaries');
class DictionaryTransformer {
constructor(dictionaries) {
this.dictionaries = dictionaries;
}
isSatisfiedBy(prefix) {
return 'd:' === prefix;
}
transform(value) {
const splittedValue = value.split(':');
return this.dictionaries.getMappedValue(splittedValue[0], splittedValue[1]);
}
}
const createDictionaryTransformer = exports.createDictionaryTransformer = (dicts = _dictionaries.dictionaries) => new DictionaryTransformer(dicts); | 1.125 | 1 |
wxgh-jssdk/config.js | xuedingmiaojun/koa-demo | 0 | 2423 | module.exports = {
grant_type: 'client_credential',
appid: 'wx36963a5a84d5ca4d',
secret: '',
noncestr: 'Wm3WZYTPz0wzccnW',
accessTokenUrl: 'https://api.weixin.qq.com/cgi-bin/token',
ticketUrl: 'https://api.weixin.qq.com/cgi-bin/ticket/getticket',
cache_duration: 1000 * 60 * 60 * 24,
};
| 0.710938 | 1 |
src/jquery/jquery/plugins/jquery.layout.js | kosmas58/compass-jquery-plugin | 3 | 2431 | /*
* jquery.layout 1.2.0
*
* Copyright (c) 2008
* <NAME> (http://www.fabrizioballiano.net)
* <NAME> (http://allpro.net)
*
* Dual licensed under the GPL (http://www.gnu.org/licenses/gpl.html)
* and MIT (http://www.opensource.org/licenses/mit-license.php) licenses.
*
* $Date: 2008-12-27 02:17:22 +0100 (sab, 27 dic 2008) $
* $Rev: 203 $
*
* NOTE: For best code readability, view this with a fixed-space font and tabs equal to 4-chars
*/
(function($) {
$.fn.layout = function (opts) {
/*
* ###########################
* WIDGET CONFIG & OPTIONS
* ###########################
*/
// DEFAULTS for options
var
prefix = "ui-layout-" // prefix for ALL selectors and classNames
, defaults = { // misc default values
paneClass: prefix + "pane" // ui-layout-pane
, resizerClass: prefix + "resizer" // ui-layout-resizer
, togglerClass: prefix + "toggler" // ui-layout-toggler
, togglerInnerClass: prefix + "" // ui-layout-open / ui-layout-closed
, buttonClass: prefix + "button" // ui-layout-button
, contentSelector: "." + prefix + "content"// ui-layout-content
, contentIgnoreSelector: "." + prefix + "ignore" // ui-layout-mask
}
;
// DEFAULT PANEL OPTIONS - CHANGE IF DESIRED
var options = {
name: "" // FUTURE REFERENCE - not used right now
, scrollToBookmarkOnLoad: true // after creating a layout, scroll to bookmark in URL (.../page.htm#myBookmark)
, defaults: { // default options for 'all panes' - will be overridden by 'per-pane settings'
applyDefaultStyles: false // apply basic styles directly to resizers & buttons? If not, then stylesheet must handle it
, closable: true // pane can open & close
, resizable: true // when open, pane can be resized
, slidable: true // when closed, pane can 'slide' open over other panes - closes on mouse-out
//, paneSelector: [ ] // MUST be pane-specific!
, contentSelector: defaults.contentSelector // INNER div/element to auto-size so only it scrolls, not the entire pane!
, contentIgnoreSelector: defaults.contentIgnoreSelector // elem(s) to 'ignore' when measuring 'content'
, paneClass: defaults.paneClass // border-Pane - default: 'ui-layout-pane'
, resizerClass: defaults.resizerClass // Resizer Bar - default: 'ui-layout-resizer'
, togglerClass: defaults.togglerClass // Toggler Button - default: 'ui-layout-toggler'
, buttonClass: defaults.buttonClass // CUSTOM Buttons - default: 'ui-layout-button-toggle/-open/-close/-pin'
, resizerDragOpacity: 1 // option for ui.draggable
//, resizerCursor: "" // MUST be pane-specific - cursor when over resizer-bar
, maskIframesOnResize: true // true = all iframes OR = iframe-selector(s) - adds masking-div during resizing/dragging
//, size: 100 // inital size of pane - defaults are set 'per pane'
, minSize: 0 // when manually resizing a pane
, maxSize: 0 // ditto, 0 = no limit
, spacing_open: 6 // space between pane and adjacent panes - when pane is 'open'
, spacing_closed: 6 // ditto - when pane is 'closed'
, togglerLength_open: 50 // Length = WIDTH of toggler button on north/south edges - HEIGHT on east/west edges
, togglerLength_closed: 50 // 100% OR -1 means 'full height/width of resizer bar' - 0 means 'hidden'
, togglerAlign_open: "center" // top/left, bottom/right, center, OR...
, togglerAlign_closed: "center" // 1 => nn = offset from top/left, -1 => -nn == offset from bottom/right
, togglerTip_open: "Close" // Toggler tool-tip (title)
, togglerTip_closed: "Open" // ditto
, resizerTip: "Resize" // Resizer tool-tip (title)
, sliderTip: "Slide Open" // resizer-bar triggers 'sliding' when pane is closed
, sliderCursor: "pointer" // cursor when resizer-bar will trigger 'sliding'
, slideTrigger_open: "click" // click, dblclick, mouseover
, slideTrigger_close: "mouseout" // click, mouseout
, hideTogglerOnSlide: false // when pane is slid-open, should the toggler show?
, togglerContent_open: "" // text or HTML to put INSIDE the toggler
, togglerContent_closed: "" // ditto
, showOverflowOnHover: false // will bind allowOverflow() utility to pane.onMouseOver
, enableCursorHotkey: true // enabled 'cursor' hotkeys
//, customHotkey: "" // MUST be pane-specific - EITHER a charCode OR a character
, customHotkeyModifier: "SHIFT" // either 'SHIFT', 'CTRL' or 'CTRL+SHIFT' - NOT 'ALT'
// NOTE: fxSss_open & fxSss_close options (eg: fxName_open) are auto-generated if not passed
, fxName: "slide" // ('none' or blank), slide, drop, scale
, fxSpeed: null // slow, normal, fast, 200, nnn - if passed, will OVERRIDE fxSettings.duration
, fxSettings: {} // can be passed, eg: { easing: "easeOutBounce", duration: 1500 }
, initClosed: false // true = init pane as 'closed'
, initHidden: false // true = init pane as 'hidden' - no resizer or spacing
/* callback options do not have to be set - listed here for reference only
, onshow_start: "" // CALLBACK when pane STARTS to Show - BEFORE onopen/onhide_start
, onshow_end: "" // CALLBACK when pane ENDS being Shown - AFTER onopen/onhide_end
, onhide_start: "" // CALLBACK when pane STARTS to Close - BEFORE onclose_start
, onhide_end: "" // CALLBACK when pane ENDS being Closed - AFTER onclose_end
, onopen_start: "" // CALLBACK when pane STARTS to Open
, onopen_end: "" // CALLBACK when pane ENDS being Opened
, onclose_start: "" // CALLBACK when pane STARTS to Close
, onclose_end: "" // CALLBACK when pane ENDS being Closed
, onresize_start: "" // CALLBACK when pane STARTS to be ***MANUALLY*** Resized
, onresize_end: "" // CALLBACK when pane ENDS being Resized ***FOR ANY REASON***
*/
}
, north: {
paneSelector: "." + prefix + "north" // default = .ui-layout-north
, size: "auto"
, resizerCursor: "n-resize"
}
, south: {
paneSelector: "." + prefix + "south" // default = .ui-layout-south
, size: "auto"
, resizerCursor: "s-resize"
}
, east: {
paneSelector: "." + prefix + "east" // default = .ui-layout-east
, size: 200
, resizerCursor: "e-resize"
}
, west: {
paneSelector: "." + prefix + "west" // default = .ui-layout-west
, size: 200
, resizerCursor: "w-resize"
}
, center: {
paneSelector: "." + prefix + "center" // default = .ui-layout-center
}
};
var effects = { // LIST *PREDEFINED EFFECTS* HERE, even if effect has no settings
slide: {
all: { duration: "fast" } // eg: duration: 1000, easing: "easeOutBounce"
, north: { direction: "up" }
, south: { direction: "down" }
, east: { direction: "right"}
, west: { direction: "left" }
}
, drop: {
all: { duration: "slow" } // eg: duration: 1000, easing: "easeOutQuint"
, north: { direction: "up" }
, south: { direction: "down" }
, east: { direction: "right"}
, west: { direction: "left" }
}
, scale: {
all: { duration: "fast" }
}
};
// STATIC, INTERNAL CONFIG - DO NOT CHANGE THIS!
var config = {
allPanes: "north,south,east,west,center"
, borderPanes: "north,south,east,west"
, zIndex: { // set z-index values here
resizer_normal: 1 // normal z-index for resizer-bars
, pane_normal: 2 // normal z-index for panes
, mask: 4 // overlay div used to mask pane(s) during resizing
, sliding: 100 // applied to both the pane and its resizer when a pane is 'slid open'
, resizing: 10000 // applied to the CLONED resizer-bar when being 'dragged'
, animation: 10000 // applied to the pane when being animated - not applied to the resizer
}
, resizers: {
cssReq: {
position: "absolute"
, padding: 0
, margin: 0
, fontSize: "1px"
, textAlign: "left" // to counter-act "center" alignment!
, overflow: "hidden" // keep toggler button from overflowing
, zIndex: 1
}
, cssDef: { // DEFAULT CSS - applied if: options.PANE.applyDefaultStyles=true
background: "#DDD"
, border: "none"
}
}
, togglers: {
cssReq: {
position: "absolute"
, display: "block"
, padding: 0
, margin: 0
, overflow: "hidden"
, textAlign: "center"
, fontSize: "1px"
, cursor: "pointer"
, zIndex: 1
}
, cssDef: { // DEFAULT CSS - applied if: options.PANE.applyDefaultStyles=true
background: "#AAA"
}
}
, content: {
cssReq: {
overflow: "auto"
}
, cssDef: {}
}
, defaults: { // defaults for ALL panes - overridden by 'per-pane settings' below
cssReq: {
position: "absolute"
, margin: 0
, zIndex: 2
}
, cssDef: {
padding: "10px"
, background: "#FFF"
, border: "1px solid #BBB"
, overflow: "auto"
}
}
, north: {
edge: "top"
, sizeType: "height"
, dir: "horz"
, cssReq: {
top: 0
, bottom: "auto"
, left: 0
, right: 0
, width: "auto"
// height: DYNAMIC
}
}
, south: {
edge: "bottom"
, sizeType: "height"
, dir: "horz"
, cssReq: {
top: "auto"
, bottom: 0
, left: 0
, right: 0
, width: "auto"
// height: DYNAMIC
}
}
, east: {
edge: "right"
, sizeType: "width"
, dir: "vert"
, cssReq: {
left: "auto"
, right: 0
, top: "auto" // DYNAMIC
, bottom: "auto" // DYNAMIC
, height: "auto"
// width: DYNAMIC
}
}
, west: {
edge: "left"
, sizeType: "width"
, dir: "vert"
, cssReq: {
left: 0
, right: "auto"
, top: "auto" // DYNAMIC
, bottom: "auto" // DYNAMIC
, height: "auto"
// width: DYNAMIC
}
}
, center: {
dir: "center"
, cssReq: {
left: "auto" // DYNAMIC
, right: "auto" // DYNAMIC
, top: "auto" // DYNAMIC
, bottom: "auto" // DYNAMIC
, height: "auto"
, width: "auto"
}
}
};
// DYNAMIC DATA
var state = {
// generate random 'ID#' to identify layout - used to create global namespace for timers
id: Math.floor(Math.random() * 10000)
, container: {}
, north: {}
, south: {}
, east: {}
, west: {}
, center: {}
};
var
altEdge = {
top: "bottom"
, bottom: "top"
, left: "right"
, right: "left"
}
, altSide = {
north: "south"
, south: "north"
, east: "west"
, west: "east"
}
;
/*
* ###########################
* INTERNAL HELPER FUNCTIONS
* ###########################
*/
/*
* isStr
*
* Returns true if passed param is EITHER a simple string OR a 'string object' - otherwise returns false
*/
var isStr = function (o) {
if (typeof o == "string")
return true;
else if (typeof o == "object") {
try {
var match = o.constructor.toString().match(/string/i);
return (match !== null);
} catch (e) {
}
}
return false;
};
/*
* str
*
* Returns a simple string if the passed param is EITHER a simple string OR a 'string object',
* else returns the original object
*/
var str = function (o) {
if (typeof o == "string" || isStr(o)) return $.trim(o); // trim converts 'String object' to a simple string
else return o;
};
/*
* min / max
*
* Alias for Math.min/.max to simplify coding
*/
var min = function (x, y) {
return Math.min(x, y);
};
var max = function (x, y) {
return Math.max(x, y);
};
/*
* transformData
*
* Processes the options passed in and transforms them into the format used by layout()
* Missing keys are added, and converts the data if passed in 'flat-format' (no sub-keys)
* In flat-format, pane-specific-settings are prefixed like: north__optName (2-underscores)
* To update effects, options MUST use nested-keys format, with an effects key
*
* @callers initOptions()
* @params JSON d Data/options passed by user - may be a single level or nested levels
* @returns JSON Creates a data struture that perfectly matches 'options', ready to be imported
*/
var transformData = function (d) {
var json = { defaults:{fxSettings:{}}, north:{fxSettings:{}}, south:{fxSettings:{}}, east:{fxSettings:{}}, west:{fxSettings:{}}, center:{fxSettings:{}} };
d = d || {};
if (d.effects || d.defaults || d.north || d.south || d.west || d.east || d.center)
json = $.extend(json, d); // already in json format - add to base keys
else
// convert 'flat' to 'nest-keys' format - also handles 'empty' user-options
$.each(d, function (key, val) {
a = key.split("__");
json[ a[1] ? a[0] : "defaults" ][ a[1] ? a[1] : a[0] ] = val;
});
return json;
};
/*
* setFlowCallback
*
* Set an INTERNAL callback to avoid simultaneous animation
* Runs only if needed and only if all callbacks are not 'already set'!
*
* @param String action Either 'open' or 'close'
* @pane String pane A valid border-pane name, eg 'west'
* @pane Boolean param Extra param for callback (optional)
*/
var setFlowCallback = function (action, pane, param) {
var
cb = action + "," + pane + "," + (param ? 1 : 0)
, cP, cbPane
;
$.each(c.borderPanes.split(","), function (i, p) {
if (c[p].isMoving) {
bindCallback(p); // TRY to bind a callback
return false; // BREAK
}
});
function bindCallback(p, test) {
cP = c[p];
if (!cP.doCallback) {
cP.doCallback = true;
cP.callback = cb;
}
else { // try to 'chain' this callback
cpPane = cP.callback.split(",")[1]; // 2nd param is 'pane'
if (cpPane != p && cpPane != pane) // callback target NOT 'itself' and NOT 'this pane'
bindCallback(cpPane, true); // RECURSE
}
}
};
/*
* execFlowCallback
*
* RUN the INTERNAL callback for this pane - if one exists
*
* @param String action Either 'open' or 'close'
* @pane String pane A valid border-pane name, eg 'west'
* @pane Boolean param Extra param for callback (optional)
*/
var execFlowCallback = function (pane) {
var cP = c[pane];
// RESET flow-control flaGs
c.isLayoutBusy = false;
delete cP.isMoving;
if (!cP.doCallback || !cP.callback) return;
cP.doCallback = false; // RESET logic flag
// EXECUTE the callback
var
cb = cP.callback.split(",")
, param = (cb[2] > 0 ? true : false)
;
if (cb[0] == "open")
open(cb[1], param);
else if (cb[0] == "close")
close(cb[1], param);
if (!cP.doCallback) cP.callback = null; // RESET - unless callback above enabled it again!
};
/*
* execUserCallback
*
* Executes a Callback function after a trigger event, like resize, open or close
*
* @param String pane This is passed only so we can pass the 'pane object' to the callback
* @param String v_fn Accepts a function name, OR a comma-delimited array: [0]=function name, [1]=argument
*/
var execUserCallback = function (pane, v_fn) {
if (!v_fn) return;
var fn;
try {
if (typeof v_fn == "function")
fn = v_fn;
else if (typeof v_fn != "string")
return;
else if (v_fn.indexOf(",") > 0) {
// function name cannot contain a comma, so must be a function name AND a 'name' parameter
var
args = v_fn.split(",")
, fn = eval(args[0])
;
if (typeof fn == "function" && args.length > 1)
return fn(args[1]); // pass the argument parsed from 'list'
}
else // just the name of an external function?
fn = eval(v_fn);
if (typeof fn == "function")
// pass data: pane-name, pane-element, pane-state, pane-options, and layout-name
return fn(pane, $Ps[pane], $.extend({}, state[pane]), $.extend({}, options[pane]), options.name);
}
catch (ex) {
}
};
/*
* cssNum
*
* Returns the 'current CSS value' for an element - returns 0 if property does not exist
*
* @callers Called by many methods
* @param jQuery $Elem Must pass a jQuery object - first element is processed
* @param String property The name of the CSS property, eg: top, width, etc.
* @returns Variant Usually is used to get an integer value for position (top, left) or size (height, width)
*/
var cssNum = function ($E, prop) {
var
val = 0
, hidden = false
, visibility = ""
;
if (!$.browser.msie) { // IE CAN read dimensions of 'hidden' elements - FF CANNOT
if ($.curCSS($E[0], "display", true) == "none") {
hidden = true;
visibility = $.curCSS($E[0], "visibility", true); // SAVE current setting
$E.css({ display: "block", visibility: "hidden" }); // show element 'invisibly' so we can measure it
}
}
val = parseInt($.curCSS($E[0], prop, true), 10) || 0;
if (hidden) { // WAS hidden, so put back the way it was
$E.css({ display: "none" });
if (visibility && visibility != "hidden")
$E.css({ visibility: visibility }); // reset 'visibility'
}
return val;
};
/*
* cssW / cssH / cssSize
*
* Contains logic to check boxModel & browser, and return the correct width/height for the current browser/doctype
*
* @callers initPanes(), sizeMidPanes(), initHandles(), sizeHandles()
* @param Variant elem Can accept a 'pane' (east, west, etc) OR a DOM object OR a jQuery object
* @param Integer outerWidth/outerHeight (optional) Can pass a width, allowing calculations BEFORE element is resized
* @returns Integer Returns the innerHeight of the elem by subtracting padding and borders
*
* @TODO May need to add additional logic to handle more browser/doctype variations?
*/
var cssW = function (e, outerWidth) {
var $E;
if (isStr(e)) {
e = str(e);
$E = $Ps[e];
}
else
$E = $(e);
// a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed
if (outerWidth <= 0)
return 0;
else if (!(outerWidth > 0))
outerWidth = isStr(e) ? getPaneSize(e) : $E.outerWidth();
if (!$.boxModel)
return outerWidth;
else // strip border and padding size from outerWidth to get CSS Width
return outerWidth
- cssNum($E, "paddingLeft")
- cssNum($E, "paddingRight")
- ($.curCSS($E[0], "borderLeftStyle", true) == "none" ? 0 : cssNum($E, "borderLeftWidth"))
- ($.curCSS($E[0], "borderRightStyle", true) == "none" ? 0 : cssNum($E, "borderRightWidth"))
;
};
var cssH = function (e, outerHeight) {
var $E;
if (isStr(e)) {
e = str(e);
$E = $Ps[e];
}
else
$E = $(e);
// a 'calculated' outerHeight can be passed so borders and/or padding are removed if needed
if (outerHeight <= 0)
return 0;
else if (!(outerHeight > 0))
outerHeight = (isStr(e)) ? getPaneSize(e) : $E.outerHeight();
if (!$.boxModel)
return outerHeight;
else // strip border and padding size from outerHeight to get CSS Height
return outerHeight
- cssNum($E, "paddingTop")
- cssNum($E, "paddingBottom")
- ($.curCSS($E[0], "borderTopStyle", true) == "none" ? 0 : cssNum($E, "borderTopWidth"))
- ($.curCSS($E[0], "borderBottomStyle", true) == "none" ? 0 : cssNum($E, "borderBottomWidth"))
;
};
var cssSize = function (pane, outerSize) {
if (c[pane].dir == "horz") // pane = north or south
return cssH(pane, outerSize);
else // pane = east or west
return cssW(pane, outerSize);
};
/*
* getPaneSize
*
* Calculates the current 'size' (width or height) of a border-pane - optionally with 'pane spacing' added
*
* @returns Integer Returns EITHER Width for east/west panes OR Height for north/south panes - adjusted for boxModel & browser
*/
var getPaneSize = function (pane, inclSpace) {
var
$P = $Ps[pane]
, o = options[pane]
, s = state[pane]
, oSp = (inclSpace ? o.spacing_open : 0)
, cSp = (inclSpace ? o.spacing_closed : 0)
;
if (!$P || s.isHidden)
return 0;
else if (s.isClosed || (s.isSliding && inclSpace))
return cSp;
else if (c[pane].dir == "horz")
return $P.outerHeight() + oSp;
else // dir == "vert"
return $P.outerWidth() + oSp;
};
var setPaneMinMaxSizes = function (pane) {
var
d = cDims
, edge = c[pane].edge
, dir = c[pane].dir
, o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $altPane = $Ps[ altSide[pane] ]
, paneSpacing = o.spacing_open
, altPaneSpacing = options[ altSide[pane] ].spacing_open
, altPaneSize = (!$altPane ? 0 : (dir == "horz" ? $altPane.outerHeight() : $altPane.outerWidth()))
, containerSize = (dir == "horz" ? d.innerHeight : d.innerWidth)
// limitSize prevents this pane from 'overlapping' opposite pane - even if opposite pane is currently closed
, limitSize = containerSize - paneSpacing - altPaneSize - altPaneSpacing
, minSize = s.minSize || 0
, maxSize = Math.min(s.maxSize || 9999, limitSize)
, minPos, maxPos // used to set resizing limits
;
switch (pane) {
case "north":
minPos = d.offsetTop + minSize;
maxPos = d.offsetTop + maxSize;
break;
case "west":
minPos = d.offsetLeft + minSize;
maxPos = d.offsetLeft + maxSize;
break;
case "south":
minPos = d.offsetTop + d.innerHeight - maxSize;
maxPos = d.offsetTop + d.innerHeight - minSize;
break;
case "east":
minPos = d.offsetLeft + d.innerWidth - maxSize;
maxPos = d.offsetLeft + d.innerWidth - minSize;
break;
}
// save data to pane-state
$.extend(s, { minSize: minSize, maxSize: maxSize, minPosition: minPos, maxPosition: maxPos });
};
/*
* getPaneDims
*
* Returns data for setting the size/position of center pane. Date is also used to set Height for east/west panes
*
* @returns JSON Returns a hash of all dimensions: top, bottom, left, right, (outer) width and (outer) height
*/
var getPaneDims = function () {
var d = {
top: getPaneSize("north", true) // true = include 'spacing' value for p
, bottom: getPaneSize("south", true)
, left: getPaneSize("west", true)
, right: getPaneSize("east", true)
, width: 0
, height: 0
};
d.width = cDims.innerWidth - left - right;
d.height = cDims.innerHeight - bottom - top;
// now add the 'container border/padding' to get final positions - relative to the container
d.top += cDims.top;
d.bottom += cDims.bottom;
d.left += cDims.left;
d.right += cDims.right;
return d;
};
/*
* getElemDims
*
* Returns data for setting size of an element (container or a pane).
*
* @callers create(), onWindowResize() for container, plus others for pane
* @returns JSON Returns a hash of all dimensions: top, bottom, left, right, outerWidth, innerHeight, etc
*/
var getElemDims = function ($E) {
var
d = {} // dimensions hash
, e, b, p // edge, border, padding
;
$.each("Left,Right,Top,Bottom".split(","), function () {
e = str(this);
b = d["border" + e] = cssNum($E, "border" + e + "Width");
p = d["padding" + e] = cssNum($E, "padding" + e);
d["offset" + e] = b + p; // total offset of content from outer edge
// if BOX MODEL, then 'position' = PADDING (ignore borderWidth)
if ($E == $Container)
d[e.toLowerCase()] = ($.boxModel ? p : 0);
});
d.innerWidth = d.outerWidth = $E.outerWidth();
d.innerHeight = d.outerHeight = $E.outerHeight();
if ($.boxModel) {
d.innerWidth -= (d.offsetLeft + d.offsetRight);
d.innerHeight -= (d.offsetTop + d.offsetBottom);
}
return d;
};
var setTimer = function (pane, action, fn, ms) {
var
Layout = window.layout = window.layout || {}
, Timers = Layout.timers = Layout.timers || {}
, name = "layout_" + state.id + "_" + pane + "_" + action // UNIQUE NAME for every layout-pane-action
;
if (Timers[name]) return; // timer already set!
else Timers[name] = setTimeout(fn, ms);
};
var clearTimer = function (pane, action) {
var
Layout = window.layout = window.layout || {}
, Timers = Layout.timers = Layout.timers || {}
, name = "layout_" + state.id + "_" + pane + "_" + action // UNIQUE NAME for every layout-pane-action
;
if (Timers[name]) {
clearTimeout(Timers[name]);
delete Timers[name];
return true;
}
else
return false;
};
/*
* ###########################
* INITIALIZATION METHODS
* ###########################
*/
/*
* create
*
* Initialize the layout - called automatically whenever an instance of layout is created
*
* @callers NEVER explicity called
* @returns An object pointer to the instance created
*/
var create = function () {
// initialize config/options
initOptions();
// initialize all objects
initContainer(); // set CSS as needed and init state.container dimensions
initPanes(); // size & position all panes
initHandles(); // create and position all resize bars & togglers buttons
initResizable(); // activate resizing on all panes where resizable=true
sizeContent("all"); // AFTER panes & handles have been initialized, size 'content' divs
if (options.scrollToBookmarkOnLoad)
if (self.location.hash) replace(self.location.hash); // scrollTo Bookmark
// bind hotkey function - keyDown - if required
initHotkeys();
// bind resizeAll() for 'this layout instance' to window.resize event
$(window).resize(function () {
var timerID = "timerLayout_" + state.id;
if (window[timerID]) clearTimeout(window[timerID]);
window[timerID] = null;
if (true || $.browser.msie) // use a delay for IE because the resize event fires repeatly
window[timerID] = setTimeout(resizeAll, 100);
else // most other browsers have a built-in delay before firing the resize event
resizeAll(); // resize all layout elements NOW!
});
};
/*
* initContainer
*
* Validate and initialize container CSS and events
*
* @callers create()
*/
var initContainer = function () {
try { // format html/body if this is a full page layout
if ($Container[0].tagName == "BODY") {
$("html").css({
height: "100%"
, overflow: "hidden"
});
$("body").css({
position: "relative"
, height: "100%"
, overflow: "hidden"
, margin: 0
, padding: 0 // TODO: test whether body-padding could be handled?
, border: "none" // a body-border creates problems because it cannot be measured!
});
}
else { // set required CSS - overflow and position
var
CSS = { overflow: "hidden" } // make sure container will not 'scroll'
, p = $Container.css("position")
, h = $Container.css("height")
;
// if this is a NESTED layout, then outer-pane ALREADY has position and height
if (!$Container.hasClass("ui-layout-pane")) {
if (!p || "fixed,absolute,relative".indexOf(p) < 0)
CSS.position = "relative"; // container MUST have a 'position'
if (!h || h == "auto")
CSS.height = "100%"; // container MUST have a 'height'
}
$Container.css(CSS);
}
} catch (ex) {
}
// get layout-container dimensions (updated when necessary)
cDims = state.container = getElemDims($Container); // update data-pointer too
};
/*
* initHotkeys
*
* Bind layout hotkeys - if options enabled
*
* @callers create()
*/
var initHotkeys = function () {
// bind keyDown to capture hotkeys, if option enabled for ANY pane
$.each(c.borderPanes.split(","), function (i, pane) {
var o = options[pane];
if (o.enableCursorHotkey || o.customHotkey) {
$(document).keydown(keyDown); // only need to bind this ONCE
return false; // BREAK - binding was done
}
});
};
/*
* initOptions
*
* Build final CONFIG and OPTIONS data
*
* @callers create()
*/
var initOptions = function () {
// simplify logic by making sure passed 'opts' var has basic keys
opts = transformData(opts);
// update default effects, if case user passed key
if (opts.effects) {
$.extend(effects, opts.effects);
delete opts.effects;
}
// see if any 'global options' were specified
$.each("name,scrollToBookmarkOnLoad".split(","), function (idx, key) {
if (opts[key] !== undefined)
options[key] = opts[key];
else if (opts.defaults[key] !== undefined) {
options[key] = opts.defaults[key];
delete opts.defaults[key];
}
});
// remove any 'defaults' that MUST be set 'per-pane'
$.each("paneSelector,resizerCursor,customHotkey".split(","),
function (idx, key) {
delete opts.defaults[key];
} // is OK if key does not exist
);
// now update options.defaults
$.extend(options.defaults, opts.defaults);
// make sure required sub-keys exist
//if (typeof options.defaults.fxSettings != "object") options.defaults.fxSettings = {};
// merge all config & options for the 'center' pane
c.center = $.extend(true, {}, c.defaults, c.center);
$.extend(options.center, opts.center);
// Most 'default options' do not apply to 'center', so add only those that DO
var o_Center = $.extend(true, {}, options.defaults, opts.defaults, options.center); // TEMP data
$.each("paneClass,contentSelector,contentIgnoreSelector,applyDefaultStyles,showOverflowOnHover".split(","),
function (idx, key) {
options.center[key] = o_Center[key];
}
);
var defs = options.defaults;
// create a COMPLETE set of options for EACH border-pane
$.each(c.borderPanes.split(","), function(i, pane) {
// apply 'pane-defaults' to CONFIG.PANE
c[pane] = $.extend(true, {}, c.defaults, c[pane]);
// apply 'pane-defaults' + user-options to OPTIONS.PANE
o = options[pane] = $.extend(true, {}, options.defaults, options[pane], opts.defaults, opts[pane]);
// make sure we have base-classes
if (!o.paneClass) o.paneClass = defaults.paneClass;
if (!o.resizerClass) o.resizerClass = defaults.resizerClass;
if (!o.togglerClass) o.togglerClass = defaults.togglerClass;
// create FINAL fx options for each pane, ie: options.PANE.fxName/fxSpeed/fxSettings[_open|_close]
$.each(["_open","_close",""], function (i, n) {
var
sName = "fxName" + n
, sSpeed = "fxSpeed" + n
, sSettings = "fxSettings" + n
;
// recalculate fxName according to specificity rules
o[sName] =
opts[pane][sName] // opts.west.fxName_open
|| opts[pane].fxName // opts.west.fxName
|| opts.defaults[sName] // opts.defaults.fxName_open
|| opts.defaults.fxName // opts.defaults.fxName
|| o[sName] // options.west.fxName_open
|| o.fxName // options.west.fxName
|| defs[sName] // options.defaults.fxName_open
|| defs.fxName // options.defaults.fxName
|| "none"
;
// validate fxName to be sure is a valid effect
var fxName = o[sName];
if (fxName == "none" || !$.effects || !$.effects[fxName] || (!effects[fxName] && !o[sSettings] && !o.fxSettings))
fxName = o[sName] = "none"; // effect not loaded, OR undefined FX AND fxSettings not passed
// set vars for effects subkeys to simplify logic
var
fx = effects[fxName] || {} // effects.slide
, fx_all = fx.all || {} // effects.slide.all
, fx_pane = fx[pane] || {} // effects.slide.west
;
// RECREATE the fxSettings[_open|_close] keys using specificity rules
o[sSettings] = $.extend(
{}
, fx_all // effects.slide.all
, fx_pane // effects.slide.west
, defs.fxSettings || {} // options.defaults.fxSettings
, defs[sSettings] || {} // options.defaults.fxSettings_open
, o.fxSettings // options.west.fxSettings
, o[sSettings] // options.west.fxSettings_open
, opts.defaults.fxSettings // opts.defaults.fxSettings
, opts.defaults[sSettings] || {} // opts.defaults.fxSettings_open
, opts[pane].fxSettings // opts.west.fxSettings
, opts[pane][sSettings] || {} // opts.west.fxSettings_open
);
// recalculate fxSpeed according to specificity rules
o[sSpeed] =
opts[pane][sSpeed] // opts.west.fxSpeed_open
|| opts[pane].fxSpeed // opts.west.fxSpeed (pane-default)
|| opts.defaults[sSpeed] // opts.defaults.fxSpeed_open
|| opts.defaults.fxSpeed // opts.defaults.fxSpeed
|| o[sSpeed] // options.west.fxSpeed_open
|| o[sSettings].duration // options.west.fxSettings_open.duration
|| o.fxSpeed // options.west.fxSpeed
|| o.fxSettings.duration // options.west.fxSettings.duration
|| defs.fxSpeed // options.defaults.fxSpeed
|| defs.fxSettings.duration// options.defaults.fxSettings.duration
|| fx_pane.duration // effects.slide.west.duration
|| fx_all.duration // effects.slide.all.duration
|| "normal" // DEFAULT
;
// DEBUG: if (pane=="east") debugData( $.extend({}, {speed: o[sSpeed], fxSettings_duration: o[sSettings].duration}, o[sSettings]), pane+"."+sName+" = "+fxName );
});
});
};
/*
* initPanes
*
* Initialize module objects, styling, size and position for all panes
*
* @callers create()
*/
var initPanes = function () {
// NOTE: do north & south FIRST so we can measure their height - do center LAST
$.each(c.allPanes.split(","), function() {
var
pane = str(this)
, o = options[pane]
, s = state[pane]
, fx = s.fx
, dir = c[pane].dir
// if o.size is not > 0, then we will use MEASURE the pane and use that as it's 'size'
, size = o.size == "auto" || isNaN(o.size) ? 0 : o.size
, minSize = o.minSize || 1
, maxSize = o.maxSize || 9999
, spacing = o.spacing_open || 0
, sel = o.paneSelector
, isIE6 = ($.browser.msie && $.browser.version < 7)
, CSS = {}
, $P, $C
;
$Cs[pane] = false; // init
if (sel.substr(0, 1) === "#") // ID selector
// NOTE: elements selected 'by ID' DO NOT have to be 'children'
$P = $Ps[pane] = $Container.find(sel + ":first");
else { // class or other selector
$P = $Ps[pane] = $Container.children(sel + ":first");
// look for the pane nested inside a 'form' element
if (!$P.length) $P = $Ps[pane] = $Container.children("form:first").children(sel + ":first");
}
if (!$P.length) {
$Ps[pane] = false; // logic
return true; // SKIP to next
}
// add basic classes & attributes
$P
.attr("pane", pane)// add pane-identifier
.addClass(o.paneClass + " " + o.paneClass + "-" + pane) // default = "ui-layout-pane ui-layout-pane-west" - may be a dupe of 'paneSelector'
;
// init pane-logic vars, etc.
if (pane != "center") {
s.isClosed = false; // true = pane is closed
s.isSliding = false; // true = pane is currently open by 'sliding' over adjacent panes
s.isResizing = false; // true = pane is in process of being resized
s.isHidden = false; // true = pane is hidden - no spacing, resizer or toggler is visible!
s.noRoom = false; // true = pane 'automatically' hidden due to insufficient room - will unhide automatically
// create special keys for internal use
c[pane].pins = []; // used to track and sync 'pin-buttons' for border-panes
}
CSS = $.extend({ visibility: "visible", display: "block" }, c.defaults.cssReq, c[pane].cssReq);
if (o.applyDefaultStyles) $.extend(CSS, c.defaults.cssDef, c[pane].cssDef); // cosmetic defaults
$P.css(CSS); // add base-css BEFORE 'measuring' to calc size & position
CSS = {}; // reset var
// set css-position to account for container borders & padding
switch (pane) {
case "north":
CSS.top = cDims.top;
CSS.left = cDims.left;
CSS.right = cDims.right;
break;
case "south":
CSS.bottom = cDims.bottom;
CSS.left = cDims.left;
CSS.right = cDims.right;
break;
case "west":
CSS.left = cDims.left; // top, bottom & height set by sizeMidPanes()
break;
case "east":
CSS.right = cDims.right; // ditto
break;
case "center": // top, left, width & height set by sizeMidPanes()
}
if (dir == "horz") { // north or south pane
if (size === 0 || size == "auto") {
$P.css({ height: "auto" });
size = $P.outerHeight();
}
size = max(size, minSize);
size = min(size, maxSize);
size = min(size, cDims.innerHeight - spacing);
CSS.height = max(1, cssH(pane, size));
s.size = size; // update state
// make sure minSize is sufficient to avoid errors
s.maxSize = maxSize; // init value
s.minSize = max(minSize, size - CSS.height + 1); // = pane.outerHeight when css.height = 1px
// handle IE6
//if (isIE6) CSS.width = cssW($P, cDims.innerWidth);
$P.css(CSS); // apply size & position
}
else if (dir == "vert") { // east or west pane
if (size === 0 || size == "auto") {
$P.css({ width: "auto", "float": "left" }); // float = FORCE pane to auto-size
size = $P.outerWidth();
$P.css({ "float": "none" }); // RESET
}
size = max(size, minSize);
size = min(size, maxSize);
size = min(size, cDims.innerWidth - spacing);
CSS.width = max(1, cssW(pane, size));
s.size = size; // update state
s.maxSize = maxSize; // init value
// make sure minSize is sufficient to avoid errors
s.minSize = max(minSize, size - CSS.width + 1); // = pane.outerWidth when css.width = 1px
$P.css(CSS); // apply size - top, bottom & height set by sizeMidPanes
sizeMidPanes(pane, null, true); // true = onInit
}
else if (pane == "center") {
$P.css(CSS); // top, left, width & height set by sizeMidPanes...
sizeMidPanes("center", null, true); // true = onInit
}
// close or hide the pane if specified in settings
if (o.initClosed && o.closable) {
$P.hide().addClass("closed");
s.isClosed = true;
}
else if (o.initHidden || o.initClosed) {
hide(pane, true); // will be completely invisible - no resizer or spacing
s.isHidden = true;
}
else
$P.addClass("open");
// check option for auto-handling of pop-ups & drop-downs
if (o.showOverflowOnHover)
$P.hover(allowOverflow, resetOverflow);
/*
* see if this pane has a 'content element' that we need to auto-size
*/
if (o.contentSelector) {
$C = $Cs[pane] = $P.children(o.contentSelector + ":first"); // match 1-element only
if (!$C.length) {
$Cs[pane] = false;
return true; // SKIP to next
}
$C.css(c.content.cssReq);
if (o.applyDefaultStyles) $C.css(c.content.cssDef); // cosmetic defaults
// NO PANE-SCROLLING when there is a content-div
$P.css({ overflow: "hidden" });
}
});
};
/*
* initHandles
*
* Initialize module objects, styling, size and position for all resize bars and toggler buttons
*
* @callers create()
*/
var initHandles = function () {
// create toggler DIVs for each pane, and set object pointers for them, eg: $R.north = north toggler DIV
$.each(c.borderPanes.split(","), function() {
var
pane = str(this)
, o = options[pane]
, s = state[pane]
, rClass = o.resizerClass
, tClass = o.togglerClass
, $P = $Ps[pane]
;
$Rs[pane] = false; // INIT
$Ts[pane] = false;
if (!$P || (!o.closable && !o.resizable)) return; // pane does not exist - skip
var
edge = c[pane].edge
, isOpen = $P.is(":visible")
, spacing = (isOpen ? o.spacing_open : o.spacing_closed)
, _pane = "-" + pane // used for classNames
, _state = (isOpen ? "-open" : "-closed") // used for classNames
, $R, $T
;
// INIT RESIZER BAR
$R = $Rs[pane] = $("<span></span>");
if (isOpen && o.resizable) {
}
// this is handled by initResizable
else if (!isOpen && o.slidable)
$R.attr("title", o.sliderTip).css("cursor", o.sliderCursor);
$R
// if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "paneLeft-resizer"
.attr("id", (o.paneSelector.substr(0, 1) == "#" ? o.paneSelector.substr(1) + "-resizer" : ""))
.attr("resizer", pane)// so we can read this from the resizer
.css(c.resizers.cssReq)// add base/required styles
// POSITION of resizer bar - allow for container border & padding
.css(edge, cDims[edge] + getPaneSize(pane))
// ADD CLASSNAMES - eg: class="resizer resizer-west resizer-open"
.addClass(rClass + " " + rClass + _pane + " " + rClass + _state + " " + rClass + _pane + _state)
.appendTo($Container) // append DIV to container
;
// ADD VISUAL STYLES
if (o.applyDefaultStyles)
$R.css(c.resizers.cssDef);
if (o.closable) {
// INIT COLLAPSER BUTTON
$T = $Ts[pane] = $("<div></div>");
$T
// if paneSelector is an ID, then create a matching ID for the resizer, eg: "#paneLeft" => "paneLeft-toggler"
.attr("id", (o.paneSelector.substr(0, 1) == "#" ? o.paneSelector.substr(1) + "-toggler" : ""))
.css(c.togglers.cssReq)// add base/required styles
.attr("title", (isOpen ? o.togglerTip_open : o.togglerTip_closed))
.click(function(evt) {
toggle(pane);
evt.stopPropagation();
})
.mouseover(function(evt) {
evt.stopPropagation();
})// prevent resizer event
// ADD CLASSNAMES - eg: class="toggler toggler-west toggler-west-open"
.addClass(tClass + " " + tClass + _pane + " " + tClass + _state + " " + tClass + _pane + _state)
.appendTo($R) // append SPAN to resizer DIV
;
// ADD INNER-SPANS TO TOGGLER
if (o.togglerContent_open) // ui-layout-open
$("<span>" + o.togglerContent_open + "</span>")
.addClass("content content-open")
.css("display", s.isClosed ? "none" : "block")
.appendTo($T)
;
if (o.togglerContent_closed) // ui-layout-closed
$("<span>" + o.togglerContent_closed + "</span>")
.addClass("content content-closed")
.css("display", s.isClosed ? "block" : "none")
.appendTo($T)
;
// ADD BASIC VISUAL STYLES
if (o.applyDefaultStyles)
$T.css(c.togglers.cssDef);
if (!isOpen) bindStartSlidingEvent(pane, true); // will enable if state.PANE.isSliding = true
}
});
// SET ALL HANDLE SIZES & LENGTHS
sizeHandles("all", true); // true = onInit
};
/*
* initResizable
*
* Add resize-bars to all panes that specify it in options
*
* @dependancies $.fn.resizable - will abort if not found
* @callers create()
*/
var initResizable = function () {
var
draggingAvailable = (typeof $.fn.draggable == "function")
, minPosition, maxPosition, edge // set in start()
;
$.each(c.borderPanes.split(","), function() {
var
pane = str(this)
, o = options[pane]
, s = state[pane]
;
if (!draggingAvailable || !$Ps[pane] || !o.resizable) {
o.resizable = false;
return true; // skip to next
}
var
rClass = o.resizerClass
// 'drag' classes are applied to the ORIGINAL resizer-bar while dragging is in process
, dragClass = rClass + "-drag" // resizer-drag
, dragPaneClass = rClass + "-" + pane + "-drag" // resizer-north-drag
// 'dragging' class is applied to the CLONED resizer-bar while it is being dragged
, draggingClass = rClass + "-dragging" // resizer-dragging
, draggingPaneClass = rClass + "-" + pane + "-dragging" // resizer-north-dragging
, draggingClassSet = false // logic var
, $P = $Ps[pane]
, $R = $Rs[pane]
;
if (!s.isClosed)
$R
.attr("title", o.resizerTip)
.css("cursor", o.resizerCursor) // n-resize, s-resize, etc
;
$R.draggable({
containment: $Container[0] // limit resizing to layout container
, axis: (c[pane].dir == "horz" ? "y" : "x") // limit resizing to horz or vert axis
, delay: 200
, distance: 1
// basic format for helper - style it using class: .ui-draggable-dragging
, helper: "clone"
, opacity: o.resizerDragOpacity
//, iframeFix: o.draggableIframeFix // TODO: consider using when bug is fixed
, zIndex: c.zIndex.resizing
, start: function (e, ui) {
// onresize_start callback - will CANCEL hide if returns false
// TODO: CONFIRM that dragging can be cancelled like this???
if (false === execUserCallback(pane, o.onresize_start)) return false;
s.isResizing = true; // prevent pane from closing while resizing
clearTimer(pane, "closeSlider"); // just in case already triggered
$R.addClass(dragClass + " " + dragPaneClass); // add drag classes
draggingClassSet = false; // reset logic var - see drag()
// SET RESIZING LIMITS - used in drag()
var resizerWidth = (pane == "east" || pane == "south" ? o.spacing_open : 0);
setPaneMinMaxSizes(pane); // update pane-state
s.minPosition -= resizerWidth;
s.maxPosition -= resizerWidth;
edge = (c[pane].dir == "horz" ? "top" : "left");
// MASK PANES WITH IFRAMES OR OTHER TROUBLESOME ELEMENTS
$(o.maskIframesOnResize === true ? "iframe" : o.maskIframesOnResize).each(function() {
$('<div class="ui-layout-mask"/>')
.css({
background: "#fff"
, opacity: "0.001"
, zIndex: 9
, position: "absolute"
, width: this.offsetWidth + "px"
, height: this.offsetHeight + "px"
})
.css($(this).offset())// top & left
.appendTo(this.parentNode) // put div INSIDE pane to avoid zIndex issues
;
});
}
, drag: function (e, ui) {
if (!draggingClassSet) { // can only add classes after clone has been added to the DOM
$(".ui-draggable-dragging")
.addClass(draggingClass + " " + draggingPaneClass)// add dragging classes
.children().css("visibility", "hidden") // hide toggler inside dragged resizer-bar
;
draggingClassSet = true;
// draggable bug!? RE-SET zIndex to prevent E/W resize-bar showing through N/S pane!
if (s.isSliding) $Ps[pane].css("zIndex", c.zIndex.sliding);
}
// CONTAIN RESIZER-BAR TO RESIZING LIMITS
if (ui.position[edge] < s.minPosition) ui.position[edge] = s.minPosition;
else if (ui.position[edge] > s.maxPosition) ui.position[edge] = s.maxPosition;
}
, stop: function (e, ui) {
var
dragPos = ui.position
, resizerPos
, newSize
;
$R.removeClass(dragClass + " " + dragPaneClass); // remove drag classes
switch (pane) {
case "north":
resizerPos = dragPos.top;
break;
case "west":
resizerPos = dragPos.left;
break;
case "south":
resizerPos = cDims.outerHeight - dragPos.top - $R.outerHeight();
break;
case "east":
resizerPos = cDims.outerWidth - dragPos.left - $R.outerWidth();
break;
}
// remove container margin from resizer position to get the pane size
newSize = resizerPos - cDims[ c[pane].edge ];
sizePane(pane, newSize);
// UN-MASK PANES MASKED IN drag.start
$("div.ui-layout-mask").remove(); // Remove iframe masks
s.isResizing = false;
}
});
});
};
/*
* ###########################
* ACTION METHODS
* ###########################
*/
/*
* hide / show
*
* Completely 'hides' a pane, including its spacing - as if it does not exist
* The pane is not actually 'removed' from the source, so can use 'show' to un-hide it
*
* @param String pane The pane being hidden, ie: north, south, east, or west
*/
var hide = function (pane, onInit) {
var
o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
;
if (!$P || s.isHidden) return; // pane does not exist OR is already hidden
// onhide_start callback - will CANCEL hide if returns false
if (false === execUserCallback(pane, o.onhide_start)) return;
s.isSliding = false; // just in case
// now hide the elements
if ($R) $R.hide(); // hide resizer-bar
if (onInit || s.isClosed) {
s.isClosed = true; // to trigger open-animation on show()
s.isHidden = true;
$P.hide(); // no animation when loading page
sizeMidPanes(c[pane].dir == "horz" ? "all" : "center");
execUserCallback(pane, o.onhide_end || o.onhide);
}
else {
s.isHiding = true; // used by onclose
close(pane, false); // adjust all panes to fit
//s.isHidden = true; - will be set by close - if not cancelled
}
};
var show = function (pane, openPane) {
var
o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
;
if (!$P || !s.isHidden) return; // pane does not exist OR is not hidden
// onhide_start callback - will CANCEL hide if returns false
if (false === execUserCallback(pane, o.onshow_start)) return;
s.isSliding = false; // just in case
s.isShowing = true; // used by onopen/onclose
//s.isHidden = false; - will be set by open/close - if not cancelled
// now show the elements
if ($R && o.spacing_open > 0) $R.show();
if (openPane === false)
close(pane, true); // true = force
else
open(pane); // adjust all panes to fit
};
/*
* toggle
*
* Toggles a pane open/closed by calling either open or close
*
* @param String pane The pane being toggled, ie: north, south, east, or west
*/
var toggle = function (pane) {
var s = state[pane];
if (s.isHidden)
show(pane); // will call 'open' after unhiding it
else if (s.isClosed)
open(pane);
else
close(pane);
};
/*
* close
*
* Close the specified pane (animation optional), and resize all other panes as needed
*
* @param String pane The pane being closed, ie: north, south, east, or west
*/
var close = function (pane, force, noAnimation) {
var
$P = $Ps[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
, o = options[pane]
, s = state[pane]
, doFX = !noAnimation && !s.isClosed && (o.fxName_close != "none")
, edge = c[pane].edge
, rClass = o.resizerClass
, tClass = o.togglerClass
, _pane = "-" + pane // used for classNames
, _open = "-open"
, _sliding = "-sliding"
, _closed = "-closed"
// transfer logic vars to temp vars
, isShowing = s.isShowing
, isHiding = s.isHiding
;
// now clear the logic vars
delete s.isShowing;
delete s.isHiding;
if (!$P || (!o.resizable && !o.closable)) return; // invalid request
else if (!force && s.isClosed && !isShowing) return; // already closed
if (c.isLayoutBusy) { // layout is 'busy' - probably with an animation
setFlowCallback("close", pane, force); // set a callback for this action, if possible
return; // ABORT
}
// onclose_start callback - will CANCEL hide if returns false
// SKIP if just 'showing' a hidden pane as 'closed'
if (!isShowing && false === execUserCallback(pane, o.onclose_start)) return;
// SET flow-control flags
c[pane].isMoving = true;
c.isLayoutBusy = true;
s.isClosed = true;
// update isHidden BEFORE sizing panes
if (isHiding) s.isHidden = true;
else if (isShowing) s.isHidden = false;
// sync any 'pin buttons'
syncPinBtns(pane, false);
// resize panes adjacent to this one
if (!s.isSliding) sizeMidPanes(c[pane].dir == "horz" ? "all" : "center");
// if this pane has a resizer bar, move it now
if ($R) {
$R
.css(edge, cDims[edge])// move the resizer bar
.removeClass(rClass + _open + " " + rClass + _pane + _open)
.removeClass(rClass + _sliding + " " + rClass + _pane + _sliding)
.addClass(rClass + _closed + " " + rClass + _pane + _closed)
;
// DISABLE 'resizing' when closed - do this BEFORE bindStartSlidingEvent
if (o.resizable)
$R
.draggable("disable")
.css("cursor", "default")
.attr("title", "")
;
// if pane has a toggler button, adjust that too
if ($T) {
$T
.removeClass(tClass + _open + " " + tClass + _pane + _open)
.addClass(tClass + _closed + " " + tClass + _pane + _closed)
.attr("title", o.togglerTip_closed) // may be blank
;
}
sizeHandles(); // resize 'length' and position togglers for adjacent panes
}
// ANIMATE 'CLOSE' - if no animation, then was ALREADY shown above
if (doFX) {
lockPaneForFX(pane, true); // need to set left/top so animation will work
$P.hide(o.fxName_close, o.fxSettings_close, o.fxSpeed_close, function () {
lockPaneForFX(pane, false); // undo
if (!s.isClosed) return; // pane was opened before animation finished!
close_2();
});
}
else {
$P.hide(); // just hide pane NOW
close_2();
}
// SUBROUTINE
function close_2() {
bindStartSlidingEvent(pane, true); // will enable if state.PANE.isSliding = true
// onclose callback - UNLESS just 'showing' a hidden pane as 'closed'
if (!isShowing) execUserCallback(pane, o.onclose_end || o.onclose);
// onhide OR onshow callback
if (isShowing) execUserCallback(pane, o.onshow_end || o.onshow);
if (isHiding) execUserCallback(pane, o.onhide_end || o.onhide);
// internal flow-control callback
execFlowCallback(pane);
}
};
/*
* open
*
* Open the specified pane (animation optional), and resize all other panes as needed
*
* @param String pane The pane being opened, ie: north, south, east, or west
*/
var open = function (pane, slide, noAnimation) {
var
$P = $Ps[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
, o = options[pane]
, s = state[pane]
, doFX = !noAnimation && s.isClosed && (o.fxName_open != "none")
, edge = c[pane].edge
, rClass = o.resizerClass
, tClass = o.togglerClass
, _pane = "-" + pane // used for classNames
, _open = "-open"
, _closed = "-closed"
, _sliding = "-sliding"
// transfer logic var to temp var
, isShowing = s.isShowing
;
// now clear the logic var
delete s.isShowing;
if (!$P || (!o.resizable && !o.closable)) return; // invalid request
else if (!s.isClosed && !s.isSliding) return; // already open
// pane can ALSO be unhidden by just calling show(), so handle this scenario
if (s.isHidden && !isShowing) {
show(pane, true);
return;
}
if (c.isLayoutBusy) { // layout is 'busy' - probably with an animation
setFlowCallback("open", pane, slide); // set a callback for this action, if possible
return; // ABORT
}
// onopen_start callback - will CANCEL hide if returns false
if (false === execUserCallback(pane, o.onopen_start)) return;
// SET flow-control flags
c[pane].isMoving = true;
c.isLayoutBusy = true;
// 'PIN PANE' - stop sliding
if (s.isSliding && !slide) // !slide = 'open pane normally' - NOT sliding
bindStopSlidingEvents(pane, false); // will set isSliding=false
s.isClosed = false;
// update isHidden BEFORE sizing panes
if (isShowing) s.isHidden = false;
// Container size may have changed - shrink the pane if now 'too big'
setPaneMinMaxSizes(pane); // update pane-state
if (s.size > s.maxSize) // pane is too big! resize it before opening
$P.css(c[pane].sizeType, max(1, cssSize(pane, s.maxSize)));
bindStartSlidingEvent(pane, false); // remove trigger event from resizer-bar
if (doFX) { // ANIMATE
lockPaneForFX(pane, true); // need to set left/top so animation will work
$P.show(o.fxName_open, o.fxSettings_open, o.fxSpeed_open, function() {
lockPaneForFX(pane, false); // undo
if (s.isClosed) return; // pane was closed before animation finished!
open_2(); // continue
});
}
else {// no animation
$P.show(); // just show pane and...
open_2(); // continue
}
// SUBROUTINE
function open_2() {
// NOTE: if isSliding, then other panes are NOT 'resized'
if (!s.isSliding) // resize all panes adjacent to this one
sizeMidPanes(c[pane].dir == "vert" ? "center" : "all");
// if this pane has a toggler, move it now
if ($R) {
$R
.css(edge, cDims[edge] + getPaneSize(pane))// move the toggler
.removeClass(rClass + _closed + " " + rClass + _pane + _closed)
.addClass(rClass + _open + " " + rClass + _pane + _open)
.addClass(!s.isSliding ? "" : rClass + _sliding + " " + rClass + _pane + _sliding)
;
if (o.resizable)
$R
.draggable("enable")
.css("cursor", o.resizerCursor)
.attr("title", o.resizerTip)
;
else
$R.css("cursor", "default"); // n-resize, s-resize, etc
// if pane also has a toggler button, adjust that too
if ($T) {
$T
.removeClass(tClass + _closed + " " + tClass + _pane + _closed)
.addClass(tClass + _open + " " + tClass + _pane + _open)
.attr("title", o.togglerTip_open) // may be blank
;
}
sizeHandles("all"); // resize resizer & toggler sizes for all panes
}
// resize content every time pane opens - to be sure
sizeContent(pane);
// sync any 'pin buttons'
syncPinBtns(pane, !s.isSliding);
// onopen callback
execUserCallback(pane, o.onopen_end || o.onopen);
// onshow callback
if (isShowing) execUserCallback(pane, o.onshow_end || o.onshow);
// internal flow-control callback
execFlowCallback(pane);
}
};
/*
* lockPaneForFX
*
* Must set left/top on East/South panes so animation will work properly
*
* @param String pane The pane to lock, 'east' or 'south' - any other is ignored!
* @param Boolean doLock true = set left/top, false = remove
*/
var lockPaneForFX = function (pane, doLock) {
var $P = $Ps[pane];
if (doLock) {
$P.css({ zIndex: c.zIndex.animation }); // overlay all elements during animation
if (pane == "south")
$P.css({ top: cDims.top + cDims.innerHeight - $P.outerHeight() });
else if (pane == "east")
$P.css({ left: cDims.left + cDims.innerWidth - $P.outerWidth() });
}
else {
if (!state[pane].isSliding) $P.css({ zIndex: c.zIndex.pane_normal });
if (pane == "south")
$P.css({ top: "auto" });
else if (pane == "east")
$P.css({ left: "auto" });
}
};
/*
* bindStartSlidingEvent
*
* Toggle sliding functionality of a specific pane on/off by adding removing 'slide open' trigger
*
* @callers open(), close()
* @param String pane The pane to enable/disable, 'north', 'south', etc.
* @param Boolean enable Enable or Disable sliding?
*/
var bindStartSlidingEvent = function (pane, enable) {
var
o = options[pane]
, $R = $Rs[pane]
, trigger = o.slideTrigger_open
;
if (!$R || !o.slidable) return;
// make sure we have a valid event
if (trigger != "click" && trigger != "dblclick" && trigger != "mouseover") trigger = "click";
$R
// add or remove trigger event
[enable ? "bind" : "unbind"](trigger, slideOpen)
// set the appropriate cursor & title/tip
.css("cursor", (enable ? o.sliderCursor : "default"))
.attr("title", (enable ? o.sliderTip : ""))
;
};
/*
* bindStopSlidingEvents
*
* Add or remove 'mouseout' events to 'slide close' when pane is 'sliding' open or closed
* Also increases zIndex when pane is sliding open
* See bindStartSlidingEvent for code to control 'slide open'
*
* @callers slideOpen(), slideClosed()
* @param String pane The pane to process, 'north', 'south', etc.
* @param Boolean isOpen Is pane open or closed?
*/
var bindStopSlidingEvents = function (pane, enable) {
var
o = options[pane]
, s = state[pane]
, trigger = o.slideTrigger_close
, action = (enable ? "bind" : "unbind") // can't make 'unbind' work! - see disabled code below
, $P = $Ps[pane]
, $R = $Rs[pane]
;
s.isSliding = enable; // logic
clearTimer(pane, "closeSlider"); // just in case
// raise z-index when sliding
$P.css({ zIndex: (enable ? c.zIndex.sliding : c.zIndex.pane_normal) });
$R.css({ zIndex: (enable ? c.zIndex.sliding : c.zIndex.resizer_normal) });
// make sure we have a valid event
if (trigger != "click" && trigger != "mouseout") trigger = "mouseout";
// when trigger is 'mouseout', must cancel timer when mouse moves between 'pane' and 'resizer'
if (enable) { // BIND trigger events
$P.bind(trigger, slideClosed);
$R.bind(trigger, slideClosed);
if (trigger = "mouseout") {
$P.bind("mouseover", cancelMouseOut);
$R.bind("mouseover", cancelMouseOut);
}
}
else { // UNBIND trigger events
// TODO: why does unbind of a 'single function' not work reliably?
//$P[action](trigger, slideClosed );
$P.unbind(trigger);
$R.unbind(trigger);
if (trigger = "mouseout") {
//$P[action]("mouseover", cancelMouseOut );
$P.unbind("mouseover");
$R.unbind("mouseover");
clearTimer(pane, "closeSlider");
}
}
// SUBROUTINE for mouseout timer clearing
function cancelMouseOut(evt) {
clearTimer(pane, "closeSlider");
evt.stopPropagation();
}
};
var slideOpen = function () {
var pane = $(this).attr("resizer"); // attr added by initHandles
if (state[pane].isClosed) { // skip if already open!
bindStopSlidingEvents(pane, true); // pane is opening, so BIND trigger events to close it
open(pane, true); // true = slide - ie, called from here!
}
};
var slideClosed = function () {
var
$E = $(this)
, pane = $E.attr("pane") || $E.attr("resizer")
, o = options[pane]
, s = state[pane]
;
if (s.isClosed || s.isResizing)
return; // skip if already closed OR in process of resizing
else if (o.slideTrigger_close == "click")
close_NOW(); // close immediately onClick
else // trigger = mouseout - use a delay
setTimer(pane, "closeSlider", close_NOW, 300); // .3 sec delay
// SUBROUTINE for timed close
function close_NOW() {
bindStopSlidingEvents(pane, false); // pane is being closed, so UNBIND trigger events
if (!s.isClosed) close(pane); // skip if already closed!
}
};
/*
* sizePane
*
* @callers initResizable.stop()
* @param String pane The pane being resized - usually west or east, but potentially north or south
* @param Integer newSize The new size for this pane - will be validated
*/
var sizePane = function (pane, size) {
// TODO: accept "auto" as size, and size-to-fit pane content
var
edge = c[pane].edge
, dir = c[pane].dir
, o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
;
// calculate 'current' min/max sizes
setPaneMinMaxSizes(pane); // update pane-state
// compare/update calculated min/max to user-options
s.minSize = max(s.minSize, o.minSize);
if (o.maxSize > 0) s.maxSize = min(s.maxSize, o.maxSize);
// validate passed size
size = max(size, s.minSize);
size = min(size, s.maxSize);
s.size = size; // update state
// move the resizer bar and resize the pane
$R.css(edge, size + cDims[edge]);
$P.css(c[pane].sizeType, max(1, cssSize(pane, size)));
// resize all the adjacent panes, and adjust their toggler buttons
if (!s.isSliding) sizeMidPanes(dir == "horz" ? "all" : "center");
sizeHandles();
sizeContent(pane);
execUserCallback(pane, o.onresize_end || o.onresize);
};
/*
* sizeMidPanes
*
* @callers create(), open(), close(), onWindowResize()
*/
var sizeMidPanes = function (panes, overrideDims, onInit) {
if (!panes || panes == "all") panes = "east,west,center";
var d = getPaneDims();
if (overrideDims) $.extend(d, overrideDims);
$.each(panes.split(","), function() {
if (!$Ps[this]) return; // NO PANE - skip
var
pane = str(this)
, o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
, hasRoom = true
, CSS = {}
;
if (pane == "center") {
d = getPaneDims(); // REFRESH Dims because may have just 'unhidden' East or West pane after a 'resize'
CSS = $.extend({}, d); // COPY ALL of the paneDims
CSS.width = max(1, cssW(pane, CSS.width));
CSS.height = max(1, cssH(pane, CSS.height));
hasRoom = (CSS.width > 1 && CSS.height > 1);
/*
* Extra CSS for IE6 or IE7 in Quirks-mode - add 'width' to NORTH/SOUTH panes
* Normally these panes have only 'left' & 'right' positions so pane auto-sizes
*/
if ($.browser.msie && (!$.boxModel || $.browser.version < 7)) {
if ($Ps.north) $Ps.north.css({ width: cssW($Ps.north, cDims.innerWidth) });
if ($Ps.south) $Ps.south.css({ width: cssW($Ps.south, cDims.innerWidth) });
}
}
else { // for east and west, set only the height
CSS.top = d.top;
CSS.bottom = d.bottom;
CSS.height = max(1, cssH(pane, d.height));
hasRoom = (CSS.height > 1);
}
if (hasRoom) {
$P.css(CSS);
if (s.noRoom) {
s.noRoom = false;
if (s.isHidden) return;
else show(pane, !s.isClosed);
/* OLD CODE - keep until sure line above works right!
if (!s.isClosed) $P.show(); // in case was previously hidden due to NOT hasRoom
if ($R) $R.show();
*/
}
if (!onInit) {
sizeContent(pane);
execUserCallback(pane, o.onresize_end || o.onresize);
}
}
else if (!s.noRoom) { // no room for pane, so just hide it (if not already)
s.noRoom = true; // update state
if (s.isHidden) return;
if (onInit) { // skip onhide callback and other logic onLoad
$P.hide();
if ($R) $R.hide();
}
else hide(pane);
}
});
};
var sizeContent = function (panes) {
if (!panes || panes == "all") panes = c.allPanes;
$.each(panes.split(","), function() {
if (!$Cs[this]) return; // NO CONTENT - skip
var
pane = str(this)
, ignore = options[pane].contentIgnoreSelector
, $P = $Ps[pane]
, $C = $Cs[pane]
, e_C = $C[0] // DOM element
, height = cssH($P); // init to pane.innerHeight
;
$P.children().each(function() {
if (this == e_C) return; // Content elem - skip
var $E = $(this);
if (!ignore || !$E.is(ignore))
height -= $E.outerHeight();
});
if (height > 0)
height = cssH($C, height);
if (height < 1)
$C.hide(); // no room for content!
else
$C.css({ height: height }).show();
});
};
/*
* sizeHandles
*
* Called every time a pane is opened, closed, or resized to slide the togglers to 'center' and adjust their length if necessary
*
* @callers initHandles(), open(), close(), resizeAll()
*/
var sizeHandles = function (panes, onInit) {
if (!panes || panes == "all") panes = c.borderPanes;
$.each(panes.split(","), function() {
var
pane = str(this)
, o = options[pane]
, s = state[pane]
, $P = $Ps[pane]
, $R = $Rs[pane]
, $T = $Ts[pane]
;
if (!$P || !$R || (!o.resizable && !o.closable)) return; // skip
var
dir = c[pane].dir
, _state = (s.isClosed ? "_closed" : "_open")
, spacing = o["spacing" + _state]
, togAlign = o["togglerAlign" + _state]
, togLen = o["togglerLength" + _state]
, paneLen
, offset
, CSS = {}
;
if (spacing == 0) {
$R.hide();
return;
}
else if (!s.noRoom && !s.isHidden) // skip if resizer was hidden for any reason
$R.show(); // in case was previously hidden
// Resizer Bar is ALWAYS same width/height of pane it is attached to
if (dir == "horz") { // north/south
paneLen = $P.outerWidth();
$R.css({
width: max(1, cssW($R, paneLen)) // account for borders & padding
, height: max(1, cssH($R, spacing)) // ditto
, left: cssNum($P, "left")
});
}
else { // east/west
paneLen = $P.outerHeight();
$R.css({
height: max(1, cssH($R, paneLen)) // account for borders & padding
, width: max(1, cssW($R, spacing)) // ditto
, top: cDims.top + getPaneSize("north", true)
//, top: cssNum($Ps["center"], "top")
});
}
if ($T) {
if (togLen == 0 || (s.isSliding && o.hideTogglerOnSlide)) {
$T.hide(); // always HIDE the toggler when 'sliding'
return;
}
else
$T.show(); // in case was previously hidden
if (!(togLen > 0) || togLen == "100%" || togLen > paneLen) {
togLen = paneLen;
offset = 0;
}
else { // calculate 'offset' based on options.PANE.togglerAlign_open/closed
if (typeof togAlign == "string") {
switch (togAlign) {
case "top":
case "left":
offset = 0;
break;
case "bottom":
case "right":
offset = paneLen - togLen;
break;
case "middle":
case "center":
default:
offset = Math.floor((paneLen - togLen) / 2); // 'default' catches typos
}
}
else { // togAlign = number
var x = parseInt(togAlign); //
if (togAlign >= 0) offset = x;
else offset = paneLen - togLen + x; // NOTE: x is negative!
}
}
var
$TC_o = (o.togglerContent_open ? $T.children(".content-open") : false)
, $TC_c = (o.togglerContent_closed ? $T.children(".content-closed") : false)
, $TC = (s.isClosed ? $TC_c : $TC_o)
;
if ($TC_o) $TC_o.css("display", s.isClosed ? "none" : "block");
if ($TC_c) $TC_c.css("display", s.isClosed ? "block" : "none");
if (dir == "horz") { // north/south
var width = cssW($T, togLen);
$T.css({
width: max(0, width) // account for borders & padding
, height: max(1, cssH($T, spacing)) // ditto
, left: offset // TODO: VERIFY that toggler positions correctly for ALL values
});
if ($TC) // CENTER the toggler content SPAN
$TC.css("marginLeft", Math.floor((width - $TC.outerWidth()) / 2)); // could be negative
}
else { // east/west
var height = cssH($T, togLen);
$T.css({
height: max(0, height) // account for borders & padding
, width: max(1, cssW($T, spacing)) // ditto
, top: offset // POSITION the toggler
});
if ($TC) // CENTER the toggler content SPAN
$TC.css("marginTop", Math.floor((height - $TC.outerHeight()) / 2)); // could be negative
}
}
// DONE measuring and sizing this resizer/toggler, so can be 'hidden' now
if (onInit && o.initHidden) {
$R.hide();
if ($T) $T.hide();
}
});
};
/*
* resizeAll
*
* @callers window.onresize(), callbacks or custom code
*/
var resizeAll = function () {
var
oldW = cDims.innerWidth
, oldH = cDims.innerHeight
;
cDims = state.container = getElemDims($Container); // UPDATE container dimensions
var
checkH = (cDims.innerHeight < oldH)
, checkW = (cDims.innerWidth < oldW)
, s, dir
;
if (checkH || checkW)
// NOTE special order for sizing: S-N-E-W
$.each(["south","north","east","west"], function(i, pane) {
s = state[pane];
dir = c[pane].dir;
if (!s.isClosed && ((checkH && dir == "horz") || (checkW && dir == "vert"))) {
setPaneMinMaxSizes(pane); // update pane-state
// shrink pane if 'too big' to fit
if (s.size > s.maxSize)
sizePane(pane, s.maxSize);
}
});
sizeMidPanes("all");
sizeHandles("all"); // reposition the toggler elements
};
/*
* keyDown
*
* Capture keys when enableCursorHotkey - toggle pane if hotkey pressed
*
* @callers document.keydown()
*/
function keyDown(evt) {
if (!evt) return true;
var code = evt.keyCode;
if (code < 33) return true; // ignore special keys: ENTER, TAB, etc
var
PANE = {
38: "north" // Up Cursor
, 40: "south" // Down Cursor
, 37: "west" // Left Cursor
, 39: "east" // Right Cursor
}
, isCursorKey = (code >= 37 && code <= 40)
, ALT = evt.altKey // no worky!
, SHIFT = evt.shiftKey
, CTRL = evt.ctrlKey
, pane = false
, s, o, k, m, el
;
if (!CTRL && !SHIFT)
return true; // no modifier key - abort
else if (isCursorKey && options[PANE[code]].enableCursorHotkey) // valid cursor-hotkey
pane = PANE[code];
else // check to see if this matches a custom-hotkey
$.each(c.borderPanes.split(","), function(i, p) { // loop each pane to check its hotkey
o = options[p];
k = o.customHotkey;
m = o.customHotkeyModifier; // if missing or invalid, treated as "CTRL+SHIFT"
if ((SHIFT && m == "SHIFT") || (CTRL && m == "CTRL") || (CTRL && SHIFT)) { // Modifier matches
if (k && code == (isNaN(k) || k <= 9 ? k.toUpperCase().charCodeAt(0) : k)) { // Key matches
pane = p;
return false; // BREAK
}
}
});
if (!pane) return true; // no hotkey - abort
// validate pane
o = options[pane]; // get pane options
s = state[pane]; // get pane options
if (!o.enableCursorHotkey || s.isHidden || !$Ps[pane]) return true;
// see if user is in a 'form field' because may be 'selecting text'!
el = evt.target || evt.srcElement;
if (el && SHIFT && isCursorKey && (el.tagName == "TEXTAREA" || (el.tagName == "INPUT" && (code == 37 || code == 39))))
return true; // allow text-selection
// SYNTAX NOTES
// use "returnValue=false" to abort keystroke but NOT abort function - can run another command afterwards
// use "return false" to abort keystroke AND abort function
toggle(pane);
evt.stopPropagation();
evt.returnValue = false; // CANCEL key
return false;
}
;
/*
* ###########################
* UTILITY METHODS
* called externally only
* ###########################
*/
function allowOverflow(elem) {
if (this && this.tagName) elem = this; // BOUND to element
var $P;
if (typeof elem == "string")
$P = $Ps[elem];
else {
if ($(elem).attr("pane")) $P = $(elem);
else $P = $(elem).parents("div[pane]:first");
}
if (!$P.length) return; // INVALID
var
pane = $P.attr("pane")
, s = state[pane]
;
// if pane is already raised, then reset it before doing it again!
// this would happen if allowOverflow is attached to BOTH the pane and an element
if (s.cssSaved)
resetOverflow(pane); // reset previous CSS before continuing
// if pane is raised by sliding or resizing, or it's closed, then abort
if (s.isSliding || s.isResizing || s.isClosed) {
s.cssSaved = false;
return;
}
var
newCSS = { zIndex: (c.zIndex.pane_normal + 1) }
, curCSS = {}
, of = $P.css("overflow")
, ofX = $P.css("overflowX")
, ofY = $P.css("overflowY")
;
// determine which, if any, overflow settings need to be changed
if (of != "visible") {
curCSS.overflow = of;
newCSS.overflow = "visible";
}
if (ofX && ofX != "visible" && ofX != "auto") {
curCSS.overflowX = ofX;
newCSS.overflowX = "visible";
}
if (ofY && ofY != "visible" && ofY != "auto") {
curCSS.overflowY = ofX;
newCSS.overflowY = "visible";
}
// save the current overflow settings - even if blank!
s.cssSaved = curCSS;
// apply new CSS to raise zIndex and, if necessary, make overflow 'visible'
$P.css(newCSS);
// make sure the zIndex of all other panes is normal
$.each(c.allPanes.split(","), function(i, p) {
if (p != pane) resetOverflow(p);
});
}
;
function resetOverflow(elem) {
if (this && this.tagName) elem = this; // BOUND to element
var $P;
if (typeof elem == "string")
$P = $Ps[elem];
else {
if ($(elem).hasClass("ui-layout-pane")) $P = $(elem);
else $P = $(elem).parents("div[pane]:first");
}
if (!$P.length) return; // INVALID
var
pane = $P.attr("pane")
, s = state[pane]
, CSS = s.cssSaved || {}
;
// reset the zIndex
if (!s.isSliding && !s.isResizing)
$P.css("zIndex", c.zIndex.pane_normal);
// reset Overflow - if necessary
$P.css(CSS);
// clear var
s.cssSaved = false;
}
;
/*
* getBtn
*
* Helper function to validate params received by addButton utilities
*
* @param String selector jQuery selector for button, eg: ".ui-layout-north .toggle-button"
* @param String pane Name of the pane the button is for: 'north', 'south', etc.
* @returns If both params valid, the element matching 'selector' in a jQuery wrapper - otherwise 'false'
*/
function getBtn(selector, pane, action) {
var
$E = $(selector)
, err = "Error Adding Button \n\nInvalid "
;
if (!$E.length) // element not found
alert(err + "selector: " + selector);
else if (c.borderPanes.indexOf(pane) == -1) // invalid 'pane' sepecified
alert(err + "pane: " + pane);
else { // VALID
var btn = options[pane].buttonClass + "-" + action;
$E.addClass(btn + " " + btn + "-" + pane);
return $E;
}
return false; // INVALID
}
;
/*
* addToggleBtn
*
* Add a custom Toggler button for a pane
*
* @param String selector jQuery selector for button, eg: ".ui-layout-north .toggle-button"
* @param String pane Name of the pane the button is for: 'north', 'south', etc.
*/
function addToggleBtn(selector, pane) {
var $E = getBtn(selector, pane, "toggle");
if ($E)
$E
.attr("title", state[pane].isClosed ? "Open" : "Close")
.click(function (evt) {
toggle(pane);
evt.stopPropagation();
})
;
}
;
/*
* addOpenBtn
*
* Add a custom Open button for a pane
*
* @param String selector jQuery selector for button, eg: ".ui-layout-north .open-button"
* @param String pane Name of the pane the button is for: 'north', 'south', etc.
*/
function addOpenBtn(selector, pane) {
var $E = getBtn(selector, pane, "open");
if ($E)
$E
.attr("title", "Open")
.click(function (evt) {
open(pane);
evt.stopPropagation();
})
;
}
;
/*
* addCloseBtn
*
* Add a custom Close button for a pane
*
* @param String selector jQuery selector for button, eg: ".ui-layout-north .close-button"
* @param String pane Name of the pane the button is for: 'north', 'south', etc.
*/
function addCloseBtn(selector, pane) {
var $E = getBtn(selector, pane, "close");
if ($E)
$E
.attr("title", "Close")
.click(function (evt) {
close(pane);
evt.stopPropagation();
})
;
}
;
/*
* addPinBtn
*
* Add a custom Pin button for a pane
*
* Four classes are added to the element, based on the paneClass for the associated pane...
* Assuming the default paneClass and the pin is 'up', these classes are added for a west-pane pin:
* - ui-layout-pane-pin
* - ui-layout-pane-west-pin
* - ui-layout-pane-pin-up
* - ui-layout-pane-west-pin-up
*
* @param String selector jQuery selector for button, eg: ".ui-layout-north .ui-layout-pin"
* @param String pane Name of the pane the pin is for: 'north', 'south', etc.
*/
function addPinBtn(selector, pane) {
var $E = getBtn(selector, pane, "pin");
if ($E) {
var s = state[pane];
$E.click(function (evt) {
setPinState($(this), pane, (s.isSliding || s.isClosed));
if (s.isSliding || s.isClosed) open(pane); // change from sliding to open
else close(pane); // slide-closed
evt.stopPropagation();
});
// add up/down pin attributes and classes
setPinState($E, pane, (!s.isClosed && !s.isSliding));
// add this pin to the pane data so we can 'sync it' automatically
// PANE.pins key is an array so we can store multiple pins for each pane
c[pane].pins.push(selector); // just save the selector string
}
}
;
/*
* syncPinBtns
*
* INTERNAL function to sync 'pin buttons' when pane is opened or closed
* Unpinned means the pane is 'sliding' - ie, over-top of the adjacent panes
*
* @callers open(), close()
* @params pane These are the params returned to callbacks by layout()
* @params doPin True means set the pin 'down', False means 'up'
*/
function syncPinBtns(pane, doPin) {
$.each(c[pane].pins, function (i, selector) {
setPinState($(selector), pane, doPin);
});
}
;
/*
* setPinState
*
* Change the class of the pin button to make it look 'up' or 'down'
*
* @callers addPinBtn(), syncPinBtns()
* @param Element $Pin The pin-span element in a jQuery wrapper
* @param Boolean doPin True = set the pin 'down', False = set it 'up'
* @param String pinClass The root classname for pins - will add '-up' or '-down' suffix
*/
function setPinState($Pin, pane, doPin) {
var updown = $Pin.attr("pin");
if (updown && doPin == (updown == "down")) return; // already in correct state
var
root = options[pane].buttonClass
, class1 = root + "-pin"
, class2 = class1 + "-" + pane
, UP1 = class1 + "-up"
, UP2 = class2 + "-up"
, DN1 = class1 + "-down"
, DN2 = class2 + "-down"
;
$Pin
.attr("pin", doPin ? "down" : "up")// logic
.attr("title", doPin ? "Un-Pin" : "Pin")
.removeClass(doPin ? UP1 : DN1)
.removeClass(doPin ? UP2 : DN2)
.addClass(doPin ? DN1 : UP1)
.addClass(doPin ? DN2 : UP2)
;
}
;
/*
* ###########################
* CREATE/RETURN BORDER-LAYOUT
* ###########################
*/
// init global vars
var
$Container = $(this).css({ overflow: "hidden" }) // Container elem
, $Ps = {} // Panes x4 - set in initPanes()
, $Cs = {} // Content x4 - set in initPanes()
, $Rs = {} // Resizers x4 - set in initHandles()
, $Ts = {} // Togglers x4 - set in initHandles()
// object aliases
, c = config // alias for config hash
, cDims = state.container // alias for easy access to 'container dimensions'
;
// create the border layout NOW
create();
// return object pointers to expose data & option Properties, and primary action Methods
return {
options: options // property - options hash
, state: state // property - dimensions hash
, panes: $Ps // property - object pointers for ALL panes: panes.north, panes.center
, toggle: toggle // method - pass a 'pane' ("north", "west", etc)
, open: open // method - ditto
, close: close // method - ditto
, hide: hide // method - ditto
, show: show // method - ditto
, resizeContent: sizeContent // method - ditto
, sizePane: sizePane // method - pass a 'pane' AND a 'size' in pixels
, resizeAll: resizeAll // method - no parameters
, addToggleBtn: addToggleBtn // utility - pass element selector and 'pane'
, addOpenBtn: addOpenBtn // utility - ditto
, addCloseBtn: addCloseBtn // utility - ditto
, addPinBtn: addPinBtn // utility - ditto
, allowOverflow: allowOverflow // utility - pass calling element
, resetOverflow: resetOverflow // utility - ditto
, cssWidth: cssW
, cssHeight: cssH
};
}
})(jQuery); | 1.234375 | 1 |
benchmark/scope/async_local_storage.js | vecerek/dd-trace-js | 1 | 2439 | 'use strict'
const { AsyncResource } = require('async_hooks')
const proxyquire = require('proxyquire')
const platform = require('../../packages/dd-trace/src/platform')
const node = require('../../packages/dd-trace/src/platform/node')
const benchmark = require('../benchmark')
platform.use(node)
const suite = benchmark('scope (AsyncLocalStorage)')
const spanStub = require('../stubs/span')
const Scope = proxyquire('../../packages/dd-trace/src/scope/async_local_storage', {
'../platform': platform
})
const scope = new Scope({
experimental: {}
})
function activateResource (name) {
return scope.activate(spanStub, () => {
return new AsyncResource(name, {
requireManualDestroy: true
})
})
}
suite
.add('Scope#activate', {
fn () {
const resource = activateResource('test')
resource.runInAsyncScope(() => {})
resource.emitDestroy()
}
})
.add('Scope#activate (nested)', {
fn () {
const outer = activateResource('outer')
let middle
let inner
outer.runInAsyncScope(() => {
middle = activateResource('middle')
})
outer.emitDestroy()
middle.runInAsyncScope(() => {
inner = activateResource('middle')
})
middle.emitDestroy()
inner.runInAsyncScope(() => {})
inner.emitDestroy()
}
})
.add('Scope#activate (async)', {
defer: true,
fn (deferred) {
scope.activate(spanStub, () => {
queueMicrotask(() => {
deferred.resolve()
})
})
}
})
.add('Scope#activate (promise)', {
defer: true,
fn (deferred) {
scope.activate(spanStub, () => {
Promise.resolve().then(() => {
deferred.resolve()
})
})
}
})
.add('Scope#activate (async/await)', {
defer: true,
async fn (deferred) {
await scope.activate(spanStub, () => {
return Promise.resolve()
})
deferred.resolve()
}
})
.add('Scope#active', {
fn () {
scope.active()
}
})
suite.run()
| 1.359375 | 1 |
src/CommandManager.js | kevelbreh/bottie-commands | 0 | 2447 | const Command = require("./Command");
/*
TODO: Define a prefix (or list of prefixes)
TODO: Prefix handling when a message is consumed.
*/
class CommandManager {
constructor(options = {}) {
this.commands = []
// Add a command for displaying information on help.
if (options.allow_help == true) {
}
// Add a command for querying the usage of a specific command.
if (options.allow_usage == true) {
}
}
register(pattern, fn) {
var cmd = new Command(pattern, fn);
this.commands.push(cmd);
return cmd;
}
register_command(cmd) {
this.commands.push(cmd)
return cmd;
}
consume(message, context={}) {
this.commands.forEach(item => {
var matches = item.re.exec(message);
if (!matches) return;
item.fn(matches.slice(1, matches.length), context);
});
}
}
module.exports = CommandManager;
| 1.828125 | 2 |
src/core_modules/capture-core/components/Pages/NewEvent/epics/newEvent.epics.js | karolinelien/capture-app | 0 | 2455 | // @flow
import { push } from 'connected-react-router';
import {
actionTypes as editEventSelectorActionTypes,
} from '../../EditEvent/EditEventSelector/EditEventSelector.actions';
import {
actionTypes as viewEventSelectorActionTypes,
} from '../../ViewEvent/ViewEventSelector/ViewEventSelector.actions';
import { actionTypes as mainPageSelectorActionTypes } from '../../MainPage/MainPageSelector/MainPageSelector.actions';
const getArguments = (programId: string, orgUnitId: string) => {
const argArray = [];
if (programId) {
argArray.push(`programId=${programId}`);
}
if (orgUnitId) {
argArray.push(`orgUnitId=${orgUnitId}`);
}
return argArray.join('&');
};
export const openNewEventPageLocationChangeEpic = (action$: InputObservable, store: ReduxStore) =>
// $FlowSuppress
action$.ofType(
editEventSelectorActionTypes.OPEN_NEW_EVENT,
viewEventSelectorActionTypes.OPEN_NEW_EVENT,
mainPageSelectorActionTypes.OPEN_NEW_EVENT,
)
.map(() => {
const state = store.getState();
const { programId, orgUnitId } = state.currentSelections;
const args = getArguments(programId, orgUnitId);
return push(`/newEvent/${args}`);
});
| 1.335938 | 1 |
test/unit/util.js | pepsipu/rctf | 0 | 2463 | const test = require('ava')
const util = require('../../dist/server/util')
test('get score static', t => {
const score = util.scores.getScore('static', 100, 100, 20)
t.is(score, 100)
})
test('get score dynamic', t => {
const score = util.scores.getScore('dynamic', 100, 500, 20)
t.is(score, 484)
})
| 1.164063 | 1 |
temperature/temperature.js | iluque95/m365dashboard_api | 0 | 2471 | module.exports = (temperatureModel) => {
class Temperature {
async create(params) {
return new Promise(async (resolve, reject) => {
try {
// validacion: if (!params.km) throw new Error('El km es obligatorio')
//params.creationDate = this.formatDate(params.creationDate)
let model = new temperatureModel(params)
let response = await model.save()
resolve(response)
} catch (e) {
reject(e)
}
})
}
async get() {
return new Promise(async (resolve, reject) => {
try {
let list = await temperatureModel.find()
resolve(list)
} catch (e) {
reject(e)
}
})
}
async get_by_id(id) {
return new Promise(async (resolve, reject) => {
try {
let list
if (id.length == 24)
list = await temperatureModel.findById(id)
else
list = await temperatureModel.findOne({ serial: id })
} catch (e) {
reject(e)
}
})
}
formatDate(date) {
return new Date(date)
}
async update(id, params) {
return new Promise(async (resolve, reject) => {
try {
let list
if (id.length == 24)
list = await temperatureModel.findByIdAndUpdate(id, params)
else
list = await temperatureModel.findOneAndUpdate({ serial: id }, params)
resolve(doc)
} catch (e) {
reject(e)
}
})
}
async delete(id) {
return new Promise(async (resolve, reject) => {
try {
if (id.length == 24)
doc = await temperatureModel.findByIdAndDelete(id)
else
doc = await temperatureModel.findOneAndDelete({ serial: id })
resolve(doc)
} catch (e) {
reject(e)
}
})
}
}
return new Temperature()
} | 1.609375 | 2 |
src/context/ThemeContext.js | mrcMesen/CoffeeShop_RN_SysCo | 0 | 2479 | import React, { createContext, useState } from "react";
export const ThemeContext = createContext();
const ThemeLight = {
palette: {
primary: "#239b56",
secondary: "#7e5109",
ligth: "#DBC2AF",
cancel: "#e70012",
},
};
export const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState(ThemeLight);
return (
<ThemeContext.Provider
value={{
theme,
}}
>
{children}
</ThemeContext.Provider>
);
};
| 1.304688 | 1 |
examples/example_0.js | madhums/LeafletPlayback | 0 | 2487 | $(function() {
// Setup leaflet map
var map = new L.Map('map');
var basemapLayer = new L.TileLayer('https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=<KEY>');
let json = window.trekker.filter(d => d.time).map(d => ({
time: d.time * 1000,
lat: Number(d.lat),
lng: Number(d.lng)
}))
// Center map and default zoom level
map.setView([json[0].lat, json[0].lng], 17);
// Adds the background layer to the map
map.addLayer(basemapLayer);
// =====================================================
// =============== Playback ============================
// =====================================================
// Playback options
var playbackOptions = {
playControl: true,
dateControl: true,
sliderControl: true
};
let coordinates = json.map(coord => [coord.lng, coord.lat]);
let times = json.map(coord => coord.time);
const data = {
"type": "Feature",
"geometry": {
"type": "MultiPoint",
"coordinates": coordinates
},
"properties": {
"time": times
}
}
// Initialize playback
var playback = new L.Playback(map, data, null, playbackOptions);
});
| 1.726563 | 2 |
src/resources/1_0_2/profiles/enrollmentrequest/query.js | rafmos/graphql-fhir | 0 | 2495 | // Schemas
const EnrollmentRequestSchema = require('../../schemas/enrollmentrequest.schema');
const BundleSchema = require('../../schemas/bundle.schema');
// Arguments
const EnrollmentRequestArgs = require('../../parameters/enrollmentrequest.parameters');
const CommonArgs = require('../../parameters/common.parameters');
// Resolvers
const {
enrollmentrequestResolver,
enrollmentrequestListResolver,
enrollmentrequestInstanceResolver
} = require('./resolver');
// Scope Utilities
const {
scopeInvariant
} = require('../../../../utils/scope.utils');
let scopeOptions = {
name: 'EnrollmentRequest',
action: 'read',
version: '1_0_2'
};
/**
* @name exports.EnrollmentRequestQuery
* @summary EnrollmentRequest Query.
*/
module.exports.EnrollmentRequestQuery = {
args: Object.assign({}, CommonArgs, EnrollmentRequestArgs),
description: 'Query for a single EnrollmentRequest',
resolve: scopeInvariant(scopeOptions, enrollmentrequestResolver),
type: EnrollmentRequestSchema
};
/**
* @name exports.EnrollmentRequestListQuery
* @summary EnrollmentRequestList Query.
*/
module.exports.EnrollmentRequestListQuery = {
args: Object.assign({}, CommonArgs, EnrollmentRequestArgs),
description: 'Query for multiple EnrollmentRequests',
resolve: scopeInvariant(scopeOptions, enrollmentrequestListResolver),
type: BundleSchema
};
/**
* @name exports.EnrollmentRequestInstanceQuery
* @summary EnrollmentRequestInstance Query.
*/
module.exports.EnrollmentRequestInstanceQuery = {
description: 'Get information about a single EnrollmentRequest',
resolve: scopeInvariant(scopeOptions, enrollmentrequestInstanceResolver),
type: EnrollmentRequestSchema
};
| 1.15625 | 1 |
test/browserEnv.js | pengge/wgis.leaflet.geosearch.vue2 | 544 | 2503 | /* eslint-disable no-undef, @typescript-eslint/no-var-requires */
const browserEnv = require('browser-env');
browserEnv();
const fetch = require('node-fetch');
window.fetch = global.fetch = fetch;
const leaflet = require('leaflet');
window.L = global.L = leaflet;
| 0.789063 | 1 |
demos/scheme-explorer/index.js | calvinomiguel/node-sketch | 298 | 2511 | const ns = require('../../');
ns.read('demo.sketch').then(sketch => sketch.saveDir('demo'));
| 0.726563 | 1 |
src/constants.js | onelive-dev/luxon-business-days | 24 | 2519 | export const MONTH = {
january: 1,
may: 5,
september: 9,
october: 10,
november: 11,
};
export const ONE_WEEK = 7;
| 0.310547 | 0 |
js/modules/camera.js | flagpatch/pixi-raycast | 1 | 2527 | function Camera(x, y) {
this.position = {x: x, y: y};
this.direction = {x: -1, y: 0};
this.plane = {x: 0, y:1};
}
Camera.prototype.update = function (dt) {
}
module.exports = Camera; | 0.984375 | 1 |
issues/issues-router.js | Co-make-bw/back-end | 0 | 2535 | const router = require('express').Router();
const Issues = require('./issues-model');
router.get('/', (req, res) => {
Issues.get()
.then(issues => {
res.status(200).json(issues)
})
.catch(err => {
console.log(err)
res.status(500).json({message: 'Failed to get issues' })
})
})
router.get('/:id', (req, res) => {
const {id} = req.params;
Issues.getById(id)
.then(issue => {
if(issue) {
res.status(200).json(issue)
} else {
res.status(404).json({ message: 'Failed to find issue with given ID' })
}
})
.catch(err => {
console.log(err)
res.status(500).json({message: 'Failed to get issue' })
})
})
module.exports = router; | 1.242188 | 1 |
lib/engine.js | think-in-universe/aurora.js | 0 | 2543 | /* This is free and unencumbered software released into the public domain. */
import { AccountID, Address } from './account.js';
import { BlockProxy, parseBlockID, } from './block.js';
import { NETWORKS } from './config.js';
import { KeyStore } from './key_store.js';
import { Err, Ok } from './prelude.js';
import { SubmitResult, FunctionCallArgs, GetStorageAtArgs, InitCallArgs, NewCallArgs, ViewCallArgs, FungibleTokenMetadata, TransactionStatus, WrappedSubmitResult, } from './schema.js';
import { TransactionID } from './transaction.js';
import { base58ToBytes } from './utils.js';
import { defaultAbiCoder } from '@ethersproject/abi';
import { arrayify as parseHexString } from '@ethersproject/bytes';
import { parse as parseRawTransaction } from '@ethersproject/transactions';
import { toBigIntBE, toBufferBE } from 'bigint-buffer';
import { Buffer } from 'buffer';
import BN from 'bn.js';
import * as NEAR from 'near-api-js';
export { getAddress as parseAddress } from '@ethersproject/address';
export { arrayify as parseHexString } from '@ethersproject/bytes';
export class AddressState {
constructor(address, nonce = BigInt(0), balance = BigInt(0), code, storage = new Map()) {
this.address = address;
this.nonce = nonce;
this.balance = balance;
this.code = code;
this.storage = storage;
}
}
export var EngineStorageKeyPrefix;
(function (EngineStorageKeyPrefix) {
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Config"] = 0] = "Config";
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Nonce"] = 1] = "Nonce";
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Balance"] = 2] = "Balance";
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Code"] = 3] = "Code";
EngineStorageKeyPrefix[EngineStorageKeyPrefix["Storage"] = 4] = "Storage";
})(EngineStorageKeyPrefix || (EngineStorageKeyPrefix = {}));
export class EngineState {
constructor(storage = new Map()) {
this.storage = storage;
}
}
const DEFAULT_NETWORK_ID = 'local';
export class Engine {
constructor(near, keyStore, signer, networkID, contractID) {
this.near = near;
this.keyStore = keyStore;
this.signer = signer;
this.networkID = networkID;
this.contractID = contractID;
}
static async connect(options, env) {
const networkID = options.network || (env && env.NEAR_ENV) || DEFAULT_NETWORK_ID;
const network = NETWORKS.get(networkID); // TODO: error handling
const contractID = AccountID.parse(options.contract || (env && env.AURORA_ENGINE) || network.contractID).unwrap();
const signerID = AccountID.parse(options.signer || (env && env.NEAR_MASTER_ACCOUNT)).unwrap(); // TODO: error handling
const keyStore = KeyStore.load(networkID, env);
const near = new NEAR.Near({
deps: { keyStore },
networkId: networkID,
nodeUrl: options.endpoint || (env && env.NEAR_URL) || network.nearEndpoint,
});
const signer = await near.account(signerID.toString());
return new Engine(near, keyStore, signer, networkID, contractID);
}
async install(contractCode) {
const contractAccount = (await this.getAccount()).unwrap();
const result = await contractAccount.deployContract(contractCode);
return Ok(TransactionID.fromHex(result.transaction.hash));
}
async upgrade(contractCode) {
return await this.install(contractCode);
}
async initialize(options) {
const newArgs = new NewCallArgs(parseHexString(defaultAbiCoder.encode(['uint256'], [options.chain || 0])), options.owner || '', options.bridgeProver || '', new BN(options.upgradeDelay || 0));
const default_ft_metadata = FungibleTokenMetadata.default();
const given_ft_metadata = options.metadata || default_ft_metadata;
const ft_metadata = new FungibleTokenMetadata(given_ft_metadata.spec || default_ft_metadata.spec, given_ft_metadata.name || default_ft_metadata.name, given_ft_metadata.symbol || default_ft_metadata.symbol, given_ft_metadata.icon || default_ft_metadata.icon, given_ft_metadata.reference || default_ft_metadata.reference, given_ft_metadata.reference_hash || default_ft_metadata.reference_hash, given_ft_metadata.decimals || default_ft_metadata.decimals);
// default values are the testnet values
const connectorArgs = new InitCallArgs(options.prover || 'prover.ropsten.testnet', options.ethCustodian || '9006a6D7d08A388Eeea0112cc1b6b6B15a4289AF', ft_metadata);
// TODO: this should be able to be a single transaction with multiple actions,
// but there doesn't seem to be a good way to do that in `near-api-js` presently.
const tx = await this.promiseAndThen(this.callMutativeFunction('new', newArgs.encode()), (_) => this.callMutativeFunction('new_eth_connector', connectorArgs.encode()));
return tx.map(({ id }) => id);
}
// Like Result.andThen, but wrapped up in Promises
async promiseAndThen(p, f) {
const r = await p;
if (r.isOk()) {
const t = r.unwrap();
return await f(t);
}
else {
return Err(r.unwrapErr());
}
}
async getAccount() {
return Ok(await this.near.account(this.contractID.toString()));
}
async getBlockHash() {
const contractAccount = (await this.getAccount()).unwrap();
const state = (await contractAccount.state());
return Ok(state.block_hash);
}
async getBlockHeight() {
const contractAccount = (await this.getAccount()).unwrap();
const state = (await contractAccount.state());
return Ok(state.block_height);
}
async getBlockInfo() {
return Ok({
hash: '',
coinbase: Address.zero(),
timestamp: 0,
number: 0,
difficulty: 0,
gasLimit: 0,
});
}
async getBlockTransactionCount(blockID) {
try {
const provider = this.near.connection.provider;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const block = (await provider.block(parseBlockID(blockID)));
const chunk_mask = block.header.chunk_mask;
const requests = block.chunks
.filter((_, index) => chunk_mask[index])
.map(async (chunkHeader) => {
if (chunkHeader.tx_root == '11111111111111111111111111111111') {
return 0; // no transactions in this chunk
}
else {
const chunk = await provider.chunk(chunkHeader.chunk_hash);
return chunk.transactions.length;
}
});
const counts = (await Promise.all(requests));
return Ok(counts.reduce((a, b) => a + b, 0));
}
catch (error) {
//console.error('Engine#getBlockTransactionCount', error);
return Err(error.message);
}
}
async getBlock(blockID, options) {
const provider = this.near.connection.provider;
return await BlockProxy.fetch(provider, blockID, options);
}
async hasBlock(blockID) {
const provider = this.near.connection.provider;
return await BlockProxy.lookup(provider, blockID);
}
async getCoinbase() {
return Ok(Address.zero()); // TODO
}
async getVersion(options) {
return (await this.callFunction('get_version', undefined, options)).map((output) => output.toString());
}
async getOwner(options) {
return (await this.callFunction('get_owner', undefined, options)).andThen((output) => AccountID.parse(output.toString()));
}
async getBridgeProvider(options) {
return (await this.callFunction('get_bridge_provider', undefined, options)).andThen((output) => AccountID.parse(output.toString()));
}
async getChainID(options) {
const result = await this.callFunction('get_chain_id', undefined, options);
return result.map(toBigIntBE);
}
// TODO: getUpgradeIndex()
// TODO: stageUpgrade()
// TODO: deployUpgrade()
async deployCode(bytecode) {
const args = parseHexString(bytecode);
const outcome = await this.callMutativeFunction('deploy_code', args);
return outcome.map(({ output }) => {
const result = SubmitResult.decode(Buffer.from(output));
return Address.parse(Buffer.from(result.output().unwrap()).toString('hex')).unwrap();
});
}
async call(contract, input) {
const args = new FunctionCallArgs(contract.toBytes(), this.prepareInput(input));
return (await this.callMutativeFunction('call', args.encode())).map(({ output }) => output);
}
async submit(input) {
try {
const inputBytes = this.prepareInput(input);
try {
const rawTransaction = parseRawTransaction(inputBytes); // throws Error
if (rawTransaction.gasLimit.toBigInt() < 21000n) {
// See: https://github.com/aurora-is-near/aurora-relayer/issues/17
return Err('ERR_INTRINSIC_GAS');
}
}
catch (error) {
//console.error(error); // DEBUG
return Err('ERR_INVALID_TX');
}
return (await this.callMutativeFunction('submit', inputBytes)).map(({ output, gasBurned, tx }) => {
return new WrappedSubmitResult(SubmitResult.decode(Buffer.from(output)), gasBurned, tx);
});
}
catch (error) {
//console.error(error); // DEBUG
return Err(error.message);
}
}
// TODO: metaCall()
async view(sender, address, amount, input, options) {
const args = new ViewCallArgs(sender.toBytes(), address.toBytes(), toBufferBE(BigInt(amount), 32), this.prepareInput(input));
const result = await this.callFunction('view', args.encode(), options);
return result.map((output) => {
const status = TransactionStatus.decode(output);
if (status.success !== undefined)
return status.success.output;
else if (status.revert !== undefined)
return status.revert.output;
else if (status.outOfGas !== undefined)
return Err(status.outOfGas);
else if (status.outOfFund !== undefined)
return Err(status.outOfFund);
else if (status.outOfOffset !== undefined)
return Err(status.outOfOffset);
else if (status.callTooDeep !== undefined)
return Err(status.callTooDeep);
else
return Err('Failed to retrieve data from the contract');
});
}
async getCode(address, options) {
const args = address.toBytes();
if (typeof options === 'object' && options.block) {
options.block = (options.block + 1);
}
return await this.callFunction('get_code', args, options);
}
async getBalance(address, options) {
const args = address.toBytes();
const result = await this.callFunction('get_balance', args, options);
return result.map(toBigIntBE);
}
async getNonce(address, options) {
const args = address.toBytes();
const result = await this.callFunction('get_nonce', args, options);
return result.map(toBigIntBE);
}
async getStorageAt(address, key, options) {
const args = new GetStorageAtArgs(address.toBytes(), parseHexString(defaultAbiCoder.encode(['uint256'], [key])));
const result = await this.callFunction('get_storage_at', args.encode(), options);
return result.map(toBigIntBE);
}
async getAuroraErc20Address(nep141, options) {
const args = Buffer.from(nep141.id, 'utf-8');
const result = await this.callFunction('get_erc20_from_nep141', args, options);
return result.map((output) => {
return Address.parse(output.toString('hex')).unwrap();
});
}
async getNEP141Account(erc20, options) {
const args = erc20.toBytes();
const result = await this.callFunction('get_nep141_from_erc20', args, options);
return result.map((output) => {
return AccountID.parse(output.toString('utf-8')).unwrap();
});
}
// TODO: beginChain()
// TODO: beginBlock()
async getStorage() {
const result = new Map();
const contractAccount = (await this.getAccount()).unwrap();
const records = await contractAccount.viewState('', { finality: 'final' });
for (const record of records) {
const record_type = record.key[0];
if (record_type == EngineStorageKeyPrefix.Config)
continue; // skip EVM metadata
const key = record_type == EngineStorageKeyPrefix.Storage
? record.key.subarray(1, 21)
: record.key.subarray(1);
const address = Buffer.from(key).toString('hex');
if (!result.has(address)) {
result.set(address, new AddressState(Address.parse(address).unwrap()));
}
const state = result.get(address);
switch (record_type) {
case EngineStorageKeyPrefix.Config:
break; // unreachable
case EngineStorageKeyPrefix.Nonce:
state.nonce = toBigIntBE(record.value);
break;
case EngineStorageKeyPrefix.Balance:
state.balance = toBigIntBE(record.value);
break;
case EngineStorageKeyPrefix.Code:
state.code = record.value;
break;
case EngineStorageKeyPrefix.Storage: {
state.storage.set(toBigIntBE(record.key.subarray(21)), toBigIntBE(record.value));
break;
}
}
}
return Ok(result);
}
async callFunction(methodName, args, options) {
const result = await this.signer.connection.provider.query({
request_type: 'call_function',
account_id: this.contractID.toString(),
method_name: methodName,
args_base64: this.prepareInput(args).toString('base64'),
finality: options?.block === undefined || options?.block === null
? 'final'
: undefined,
block_id: options?.block !== undefined && options?.block !== null
? options.block
: undefined,
});
if (result.logs && result.logs.length > 0)
console.debug(result.logs); // TODO
return Ok(Buffer.from(result.result));
}
async callMutativeFunction(methodName, args) {
this.keyStore.reKey();
const gas = new BN('300000000000000'); // TODO?
try {
const result = await this.signer.functionCall(this.contractID.toString(), methodName, this.prepareInput(args), gas);
if (typeof result.status === 'object' &&
typeof result.status.SuccessValue === 'string') {
const transactionId = result?.transaction_outcome?.id;
return Ok({
id: TransactionID.fromHex(result.transaction.hash),
output: Buffer.from(result.status.SuccessValue, 'base64'),
tx: transactionId,
gasBurned: await this.transactionGasBurned(transactionId),
});
}
return Err(result.toString()); // FIXME: unreachable?
}
catch (error) {
//assert(error instanceof ServerTransactionError);
switch (error?.type) {
case 'FunctionCallError': {
const transactionId = error?.transaction_outcome?.id;
const details = {
tx: transactionId,
gasBurned: await this.transactionGasBurned(transactionId),
};
const errorKind = error?.kind?.ExecutionError;
if (errorKind) {
const errorCode = errorKind.replace('Smart contract panicked: ', '');
return Err(this.errorWithDetails(errorCode, details));
}
return Err(this.errorWithDetails(error.message, details));
}
case 'MethodNotFound':
return Err(error.message);
default:
console.debug(error);
return Err(error.toString());
}
}
}
prepareInput(args) {
if (typeof args === 'undefined')
return Buffer.alloc(0);
if (typeof args === 'string')
return Buffer.from(parseHexString(args));
return Buffer.from(args);
}
errorWithDetails(message, details) {
return `${message}|${JSON.stringify(details)}`;
}
async transactionGasBurned(id) {
try {
const transactionStatus = await this.near.connection.provider.txStatus(base58ToBytes(id), this.contractID.toString());
const receiptsGasBurned = transactionStatus.receipts_outcome.reduce((sum, value) => sum + value.outcome.gas_burnt, 0);
const transactionGasBurned = transactionStatus.transaction_outcome.outcome.gas_burnt || 0;
return receiptsGasBurned + transactionGasBurned;
}
catch (error) {
return 0;
}
}
}
| 1.257813 | 1 |
src/account/login.js | ytt123/gitchat_dianshan | 0 | 2551 | 'use strict';
import React from 'react';
import {
StyleSheet,
View,
Text,
TouchableOpacity,
TouchableWithoutFeedback,
Image,
TextInput
} from 'react-native';
import px from '../utils/px'
import TopHeader from '../component/header'
import toast from '../utils/toast'
import { NavigationActions } from 'react-navigation';
export default class extends React.Component {
constructor(props) {
super(props);
this.state = {
valid: false,
isRegShow: 0,
tel: '',
sent: false
};
this.isPass = true;
}
render() {
return <View style={styles.container}>
{/*顶部组件*/}
<TopHeader title='登录' navigation={this.props.navigation} />
{/*Logo*/}
<Image
source={{ uri: require('../images/logo_new') }}
style={{ width: px(220), height: px(130), marginTop: px(170), marginLeft: px(50), marginBottom: px(80) }} />
{/*手机号输入框*/}
<View style={[styles.input, { marginBottom: px(12) }]}>
<TextInput style={styles.inputTxt}
placeholder='请输入手机号' placeholderTextColor="#b2b3b5"
maxlength={11} keyboardType="numeric"
clearButtonMode='while-editing'
onChangeText={(v) => this.setState({ tel: v })}
underlineColorAndroid="transparent" />
</View>
{/*短信验证码*/}
<View style={[styles.input, { marginBottom: px(62) }]}>
<TextInput style={styles.inputTxt}
placeholder='请输入验证码' placeholderTextColor="#b2b3b5"
maxLength={10} keyboardType="numeric"
onChangeText={(v) => this.setState({ code: v })}
underlineColorAndroid="transparent" />
<Text allowFontScaling={false} style={this.state.sent ? styles.sent : styles.send}
onPress={() => this.sendCode()}>
{this.state.sent ?
`重新获取${this.state.timeout}S` :
`获取验证码`
}
</Text>
</View>
{/*登录按钮*/}
<TouchableOpacity activeOpacity={0.8} onPress={() => this.submit()}>
<View style={[styles.btn, { backgroundColor: '#d0648f' }]}>
<Text allowFontScaling={false} style={{ fontSize: px(30), color: '#fff' }}>
登录</Text>
</View>
</TouchableOpacity>
{/*微信登录*/}
<View style={{ position: 'absolute', bottom: px(80) }}>
<TouchableOpacity style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center' }}
activeOpacity={0.8}
onPress={() => this.loginWeChat()}>
<Image source={{ uri: require('../images/icon-wechat') }} style={{ width: px(38), height: px(38), marginRight: px(13) }} />
<Text allowFontScaling={false} style={{ color: '#679d5e', fontSize: px(28) }}>微信登录</Text>
</TouchableOpacity>
</View>
</View>
}
//发送验证码
sendCode() {
if (this.state.sent) {
return;
}
if (!this.state.tel || this.state.tel.length != 11) {
toast('请输入正确的手机号');
return;
}
this.startTimer();
}
//倒计时
startTimer() {
this.setState({
'sent': Date.now(),
'timeout': 60
});
this.timer = setInterval(() => {
let elapsed = Math.ceil((Date.now() - this.state.sent) / 1000);
if (elapsed > 60) {
this.setState({
'sent': null,
'timeout': null
});
clearInterval(this.timer);
delete this.timer;
} else {
this.setState({
'timeout': 60 - elapsed
});
}
}, 100);
}
//调起微信登录
loginWeChat() {
}
//短信登录
submit() {
toast('登录成功');
this.goTabPage();
}
goTabPage() {
this.props.navigation.dispatch(NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Tabs' })
]
}))
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center'
},
'input': {
width: px(580),
height: px(80),
borderBottomWidth: px(1),
borderBottomColor: '#e5e5e5',
paddingLeft: px(12),
paddingRight: px(12),
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'center'
},
'inputTxt': {
fontSize: px(26),
color: '#252426',
flex: 1
},
'send': {
color: '#d0648f',
fontSize: px(26),
marginLeft: px(30)
},
'sent': {
color: '#b2b5b5',
fontSize: px(26),
marginLeft: px(30)
},
'btn': {
width: px(580),
height: px(80),
alignItems: 'center',
justifyContent: 'center',
borderRadius: px(40)
},
}) | 1.578125 | 2 |
app/components/tab-bar-item.js | AriasBros/ember-material | 0 | 2559 | export { default } from 'ember-material/components/tab-bar-item'; | 0.333984 | 0 |
posts-server/src/index.js | kevinvoduy/discor | 0 | 2567 | import http from 'http';
import SocketIO from 'socket.io';
import App from './config/express';
// dynamo: prod
// import './config/dynamo';
// mongodb: dev
import './config/mongo';
// if (process.env.NODE_ENV !== 'production') {
// require('babel-register');
// require('babel-polyfill');
// }
const app = App.express;
const server = http.Server(app);
const io = SocketIO(server);
const PORT = process.env.PORT || 3030;
io.on('connection', socket => {
console.log('Client Connected');
socket.on('new__post', post => {
console.log('posts - broadcasting new post');
socket.broadcast.emit('new__posts', post);
});
});
server.listen(PORT, err => {
if (err) throw new Error;
else console.log('successfully connected to posts server:', PORT);
});
export default app; | 1.070313 | 1 |
client/src/pages/About.js | cmarshman/shoestring | 5 | 2575 | import React from 'react';
import Navbar from '../components/navbar';
import AppScreens from './../images/AppScreens/user-wallet.png';
import TheTeam from './../components/TheTeam';
import Playstore from './../components/Playstore';
function About() {
return (
<>
<Navbar />
<br />
<br />
<div className="tile is-ancestor">
<div className="tile is vertical is-10 is-clearfix columns" id="tile">
<div className="column">
<div className="column is-pulled-right">
<img id="appscreens" src={AppScreens} alt="appscreens" />
</div>
</div>
<div className="column is-three-fifths">
<p className="title">Meet the Team</p>
<br />
<TheTeam />
<br />
<p className="subtitle"><strong>Download our app</strong></p>
<div className="columns">
<Playstore />
</div>
</div>
</div>
</div>
<br />
</>
);
}
export default About; | 0.828125 | 1 |
client/src/js/actions/fuelSavingsActions.js | ziyadparekh/relay-services | 0 | 2583 | import * as types from 'constants/ActionTypes';
export function saveFuelSavings(settings) {
return { type: types.SAVE_FUEL_SAVINGS, settings };
}
export function calculateFuelSavings(settings, fieldName, value) {
return { type: types.CALCULATE_FUEL_SAVINGS, settings, fieldName, value };
} | 0.667969 | 1 |
__test__/test_helpers.js | gracecarey/Spoke | 2 | 2591 | import {createLoaders, r} from '../src/server/models/'
import { sleep } from '../src/workers/lib'
export async function setupTest() {
createLoaders()
let i = 0
while (i++ < 4) {
const results = [await r.knex.schema.hasTable('assignment'),
await r.knex.schema.hasTable('campaign'),
await r.knex.schema.hasTable('campaign_contact'),
await r.knex.schema.hasTable('canned_response'),
await r.knex.schema.hasTable('interaction_step'),
await r.knex.schema.hasTable('invite'),
await r.knex.schema.hasTable('job_request'),
await r.knex.schema.hasTable('log'),
await r.knex.schema.hasTable('message'),
await r.knex.schema.hasTable('migrations'),
await r.knex.schema.hasTable('opt_out'),
await r.knex.schema.hasTable('organization'),
await r.knex.schema.hasTable('pending_message_part'),
await r.knex.schema.hasTable('question_response'),
await r.knex.schema.hasTable('user'),
await r.knex.schema.hasTable('user_cell'),
await r.knex.schema.hasTable('user_organization'),
await r.knex.schema.hasTable('zip_code')]
if (results.some((element) => !element)) {
await sleep(i * 1000)
}
else {
break
}
}
}
export async function cleanupTest() {
// Drop tables in an order that drops foreign keys before dependencies
await r.knex.schema.dropTableIfExists('log')
await r.knex.schema.dropTableIfExists('zip_code')
await r.knex.schema.dropTableIfExists('message')
await r.knex.schema.dropTableIfExists('user_cell')
await r.knex.schema.dropTableIfExists('user_organization')
await r.knex.schema.dropTableIfExists('canned_response')
await r.knex.schema.dropTableIfExists('invite')
await r.knex.schema.dropTableIfExists('job_request')
await r.knex.schema.dropTableIfExists('migrations')
await r.knex.schema.dropTableIfExists('opt_out')
await r.knex.schema.dropTableIfExists('question_response')
await r.knex.schema.dropTableIfExists('interaction_step')
await r.knex.schema.dropTableIfExists('campaign_contact')
await r.knex.schema.dropTableIfExists('assignment')
await r.knex.schema.dropTableIfExists('campaign')
await r.knex.schema.dropTableIfExists('organization')
await r.knex.schema.dropTableIfExists('pending_message_part')
await r.knex.schema.dropTableIfExists('user')
}
export function getContext(context) {
return {
...context,
req: {},
loaders: createLoaders(),
}
}
| 1.320313 | 1 |
src/App.js | larissapissurno/tech-list | 0 | 2599 | import React from 'react';
import './App.css';
import TechList from './components/TechList';
function App() {
return <TechList />
}
export default App; | 0.419922 | 0 |
src/js/herocalc/hero/heroOptionsArray.js | devilesk/hero-calculator | 9 | 2607 | var HeroOption = require("./HeroOption");
var heroOptionsArray = {};
var init = function (heroData) {
heroOptionsArray.items = [];
for (var h in heroData) {
heroOptionsArray.items.push(new HeroOption(h.replace('npc_dota_hero_', ''), heroData[h].displayname));
}
return heroOptionsArray.items;
}
heroOptionsArray.init = init;
module.exports = heroOptionsArray; | 0.914063 | 1 |
MobileClient/components/SendPage.js | ramon54321/popcornproject | 1 | 2623 | import React, { Component } from "react";
import { Text, View, TextInput, StyleSheet, Alert } from "react-native";
import Tabs from "./Tabs";
import Main from "./Main";
import { StackNavigator } from "react-navigation";
import { getTransactionByCode, confirmTransaction } from "../api";
import { connect } from "react-redux";
import actions from "../redux/actions";
class SendPage extends Component {
constructor(props) {
super(props);
this.state = {
values: [null, null, null, null],
text: "",
user: "",
coins: "",
hash: ""
};
this.showAlert = this.showAlert.bind(this);
}
inputs = [];
confirmRequest = async () => {
const response = await confirmTransaction(this.state.hash);
if (response.success) {
this.setState({
text: "You sent brownies!",
values: [null, null, null, null]
});
} else {
this.setState({
text: "Something went wrong!"
});
}
};
showAlert() {
Alert.alert(
"Confirmation window",
`Do you want send ${this.state.coins}$ to ${this.state.user}`,
[
{
text: "Cancel",
onPress: () => console.log("Cancel Pressed"),
style: "cancel"
},
{ text: "OK", onPress: this.confirmRequest }
]
);
}
handleTextInputChange = (value, index) => {
if (!value) return;
const currentValues = [...this.state.values];
currentValues[index] = value;
this.setState(
{
values: currentValues
},
async () => {
if (index !== 3) {
this.inputs[index + 1].focus();
} else {
this.inputs[index].blur();
console.log(currentValues);
const code = currentValues.reduce((string, input) => {
return string + input;
}, "");
const response = await getTransactionByCode(code);
console.log(response);
if (response.request) {
this.setState({
text: `Send ${response.request.amount}$ to ${
response.request.userid
} `,
user: response.request.userid,
coins: response.request.amount,
hash: code
});
} else {
this.setState({
text: `The code is wrong! `
});
}
}
}
);
};
render() {
return (
<View style={styles.mainView}>
<Text style={styles.balance}>{`${this.props.balance} $`}</Text>
<View style={styles.view1}>
<View style={styles.inputContainer}>
<TextInput
editable={true}
ref={ref => this.inputs.push(ref)}
maxLength={1}
onChangeText={code => this.handleTextInputChange(code, 0)}
style={styles.input}
value={this.state.values[0]}
/>
<TextInput
editable={true}
ref={ref => this.inputs.push(ref)}
maxLength={1}
onChangeText={code => this.handleTextInputChange(code, 1)}
style={styles.input}
value={this.state.values[1]}
/>
<TextInput
editable={true}
ref={ref => this.inputs.push(ref)}
maxLength={1}
onChangeText={code => this.handleTextInputChange(code, 2)}
style={styles.input}
value={this.state.values[2]}
/>
<TextInput
editable={true}
ref={ref => this.inputs.push(ref)}
maxLength={1}
onChangeText={code => this.handleTextInputChange(code, 3)}
style={styles.input}
value={this.state.values[3]}
/>
</View>
<Text style={styles.text}>{this.state.text}</Text>
</View>
<Tabs
names={["Back", "Confirm"]}
pages={["Back", this.showAlert]}
navigation={this.props.navigation}
/>
</View>
);
}
}
const mapStateToProps = store => ({
user: store.user,
balance: store.balance,
requests: store.requests
});
export default connect(mapStateToProps)(SendPage);
const styles = StyleSheet.create({
text: {
color: "#663300",
fontSize: 35,
fontWeight: "bold"
},
view1: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
mainView: {
flex: 1,
flexDirection: "column",
justifyContent: "space-between",
alignItems: "center"
},
balance: {
color: "#663300",
fontSize: 50,
fontWeight: "bold",
alignSelf: "flex-end"
},
input: {
borderColor: "#000000",
borderWidth: 1,
width: 70,
height: 70,
padding: 10,
margin: 5,
borderRadius: 4,
fontSize: 50,
textAlign: "center"
},
inputContainer: {
height: 80,
flexDirection: "row"
}
});
| 1.882813 | 2 |
lib/aggregation/reporting/src/test/lib/summarizer-test.js | wanglw/cf-abacus | 98 | 2631 | 'use strict';
const summarizer = require('../../lib/summarizer.js');
/* eslint-disable no-unused-expressions */
describe('summarizer', () => {
const summarizeFnErrMsg = 'SummarizeFn error';
let sandbox;
let summaryFunction;
beforeEach(() => {
sandbox = sinon.createSandbox();
summaryFunction = sandbox.stub().throws(new Error(summarizeFnErrMsg));
});
afterEach(() => {
sandbox.restore();
sandbox.reset();
});
describe('summarizeWindowElement', () => {
context('when summary function errors', () => {
const windowElement = {};
it('returns summary 0', () => {
expect(
summarizer.summarizeWindowElement(
sandbox.any,
windowElement,
summaryFunction,
sandbox.any,
sandbox.any
)
).to.deep.equal({
summary: 0
});
});
});
});
describe('summarizeMetric', () => {
context('when summary function errors', () => {
let chargePlanMetric;
beforeEach(() => {
chargePlanMetric = summarizer.summarizeMetric(sandbox.any, sandbox.any, summaryFunction);
});
it('throws', (done) => {
chargePlanMetric({ metric: 'metric' }, (err) => {
expect(err).to.exist;
expect(err.message).to.equal(summarizeFnErrMsg);
done();
});
});
});
});
});
| 1.304688 | 1 |
alldata.js | kmcarter2025/Bandbank1 | 0 | 2639 | function AllData(){
const ctx = React.useContext(UserContext);
const userAccounts = ctx.users;
return (
<div>
{userAccounts.map(function(user, i){
return (
<table className="ui celled table">
<thead bgcolor="success">
<tr>
<th>Email</th>
<th>Name</th>
<th>Password</th>
</tr>
</thead>
<tbody>
<tr key={i}>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.password}</td>
</tr>
</tbody>
</table>)
})}
</div>
);
};
| 1.390625 | 1 |
src/views/GalleryPage/GalleryPage.js | antarikshray/websiterudra | 0 | 2647 | import React, { useState, useCallback, useEffect } from "react";
import DelayLink from 'react-delay-link';
// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";
import Gallery from 'react-photo-gallery';
import Carousel, { Modal, ModalGateway } from "react-images";
import photos from "../GalleryPage/components/photo";
import Home from "@material-ui/icons/Home";
const useStyles = makeStyles({
container: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
},
navBar: {
position: 'fixed',
top: '0px',
left: '0px',
height: '6vh',
width: '100vw',
backgroundColor: 'white',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-around'
},
mainCard: {
marginTop: '8vh',
width: '92vw'
},
title: {
fontSize: '2em',
color: '#fc4267'
},
brand: {
fontFamily: 'nordi',
fontSize: '2em',
color: '#fc4267',
},
load1: {
position: 'fixed',
height: '120vh',
width: '50vw',
backgroundColor: '#bababa',
zIndex: '1000000',
transition: '2s ease-in-out',
},
load2: {
position: 'fixed',
height: '120vh',
width: '50vw',
backgroundColor: '#bababa',
zIndex: '1000000',
transition: '2s ease-in-out',
},
load3: {
position: 'fixed',
height: '120vh',
marginLeft: '50vw',
width: '50vw',
backgroundColor: '#454545',
zIndex: '1000000',
transition: '2s ease-in-out',
},
});
export default function GalleryPage(props) {
const classes = useStyles();
const [currentImage, setCurrentImage] = useState(0);
const [viewerIsOpen, setViewerIsOpen] = useState(false);
const openLightbox = useCallback((event, { photo, index }) => {
setCurrentImage(index);
setViewerIsOpen(true);
}, []);
const closeLightbox = () => {
setCurrentImage(0);
setViewerIsOpen(false);
};
useEffect(() => {
setTimeout(function () {
document.getElementById('load1').style.width = '0px';
document.getElementById('load2').style.height = '0px';
}, 2000);
setTimeout(function () {
document.getElementById('load3').style.height = '0px';
}, 3000);
});
return (
<div>
<div id="load1" className={classes.load1}>
</div>
<div id="load2" className={classes.load2}>
</div>
<div id="load3" className={classes.load3}>
</div>
<div className={classes.navBar}>
<DelayLink delay={1800} to="/" clickAction={() => {
document.getElementById('load1').style.width = '50vw';
document.getElementById('load2').style.height = '120vh';
setTimeout(function () {
document.getElementById('load3').style.height = '120vh';
}, 500);
}}>
<Home style={{ fontSize: '2em', color: "#fc4267" }} />
</DelayLink>
<div className={classes.title}>
Gallery
</div>
<DelayLink delay={1800} to="/" clickAction={() => {
document.getElementById('load1').style.width = '50vw';
document.getElementById('load2').style.height = '120vh';
setTimeout(function () {
document.getElementById('load3').style.height = '120vh';
}, 500);
}}>
<div className={classes.brand}>
rudra
</div>
</DelayLink>
</div>
<div className={classes.container}>
<div className={classes.mainCard}>
<Gallery margin={7} photos={photos} onClick={openLightbox} />
<ModalGateway>
{viewerIsOpen ? (
<Modal onClose={closeLightbox}>
<Carousel
currentIndex={currentImage}
views={photos.map(x => ({
...x,
srcset: x.srcSet,
caption: x.title
}))}
/>
</Modal>
) : null}
</ModalGateway>
</div>
</div>
</div >
);
}
| 1.390625 | 1 |
node_modules/polyfill-library/polyfills/__dist/console.markTimeline/min.js | vladermakov12345/Test1 | 1 | 2655 | console.markTimeline=function(){}; | 0.365234 | 0 |
src/EChart/echartTheme.js | liuderchi/mcs-ui | 5 | 2663 | // @flow
import { type Theme } from '../utils/type.flow';
import theme, { fontFamily } from '../utils/theme';
const {
color: {
grayLight,
grayBase,
grayDark,
warning,
primary,
success,
black,
white,
},
}: Theme = theme;
const axisCommon = {
axisLine: {
lineStyle: {
color: grayBase,
},
},
axisTick: {
show: false,
},
axisLabel: {
textStyle: {
fontSize: 12,
color: grayDark,
},
interval: 0,
},
splitLine: {
show: false,
},
splitArea: {
show: false,
},
nameGap: 15,
nameTextStyle: {
color: grayDark,
},
};
export default {
// Note: Global font style
textStyle: {
color: black,
fontSize: 14,
fontFamily,
},
// Note: SVG container padding
grid: {
left: '8%',
right: '3%',
},
color: [warning, primary, success],
legend: {
textStyle: {
padding: [2, 0, 0, 0],
},
itemHeight: 14,
itemWidth: 14,
itemGap: 10,
inactiveColor: grayBase,
x: 'right',
padding: [0, 15, 0, 0],
},
dataZoom: {
showDataShadow: true,
height: 20,
handleSize: '100%',
backgroundColor: '#F2F2F2',
dataBackground: {
lineStyle: {
color: grayDark,
opacity: 0.2,
},
areaStyle: {
color: grayBase,
opacity: 0.2,
},
},
fillerColor: 'rgba(53, 54, 48, 0.05)',
handleColor: 'rgba(53, 54, 48, 0.2)',
borderColor: grayBase,
textStyle: {
color: grayDark,
},
},
tooltip: {
trigger: 'axis',
backgroundColor: grayLight,
borderWidth: 1,
borderColor: grayBase,
padding: 10,
textStyle: {
color: black,
},
axisPointer: {
type: 'line',
lineStyle: {
color: grayBase,
},
label: {
backgroundColor: grayDark,
color: white,
margin: 5,
},
},
extraCssText:
'box-shadow: 0 1px 5px 0 rgba(0, 0, 0, 0.2); border-radius: 3px;',
},
timeAxis: axisCommon,
logAxis: axisCommon,
valueAxis: axisCommon,
categoryAxis: axisCommon,
};
| 1.023438 | 1 |
tests/lib/all.js | shuckster/eslint-plugin-big-number-rules | 3 | 2671 | const path = require('path')
const RuleTester = require('eslint').RuleTester
const {
baseEslintSettings,
configsPath,
getExampleEslintConfigsForOtherLibs,
loadJsonFile,
bigNumberRules,
filter,
map,
flow,
tryCatch
} = require('./common')
const suites = [
require('./arithmetic'),
require('./assignment'),
require('./is-nan'),
require('./math'),
require('./number'),
require('./parse-float'),
require('./rounding')
]
let errorCode = 0
function main() {
loadJsonFile(path.join(configsPath, 'default.json'))
.then(testAllSuitesAgainstEslintConfig)
.then(logWhenDoneWith())
.then(runTestSuitesAgainstCustomEslintConfigs)
.finally(() => {
console.log(new Date().toTimeString())
process.exit(errorCode)
})
}
function testAllSuitesAgainstEslintConfig(customEslintSettings) {
const eslintSettings = {
...baseEslintSettings,
...customEslintSettings
}
const ruleTester = new RuleTester(eslintSettings)
const config = bigNumberRules(eslintSettings)
const suitesOpts = suites
.map(({ makeTest }) => makeTest(config))
.map(({ invalidTests: invalid, validTests: valid, ...rest }) => ({
testCases: { valid, invalid },
...rest
}))
const ruleTestersToRun = suitesOpts.map(opts =>
runRuleTester({ ruleTester, config, ...opts })
)
return Promise.allSettled(ruleTestersToRun)
.then(filter(result => result.status === 'rejected'))
.then(map(result => result.reason))
.then(errors => {
if (errors.length) {
errorCode = 1
}
errors.forEach(console.error)
})
}
function runRuleTester({ ruleTester, config, name, rule, testCases }) {
return new Promise((resolve, reject) =>
tryCatch(() => ruleTester.run(name, rule, testCases)).fold(
flow(
error => [error, config.construct, name, JSON.stringify(rule, null, 2)],
([$1, $2, $3, $4]) => `${$1}\n\\_ ${$2} // ${$3}\nrule: ${$4}\n`,
reject
),
resolve
)
)
}
function runTestSuitesAgainstCustomEslintConfigs() {
return getExampleEslintConfigsForOtherLibs().then(runTestsAgainstAll)
function runTestsAgainstAll(configs) {
return Promise.all(configs.map(runTestsAgainstThis))
}
function runTestsAgainstThis(config) {
return testAllSuitesAgainstEslintConfig(config).finally(
logWhenDoneWith(config)
)
}
}
function logWhenDoneWith(config) {
const { construct = 'DEFAULT' } = config?.settings['big-number-rules'] || {}
const message = `Tests finished using: ${construct}`
return () => console.log(message)
}
main()
| 1.359375 | 1 |
Doc/html/html/structs_mail_node__t.js | VKM96/MailBox | 0 | 2679 | var structs_mail_node__t =
[
[ "msg", "structs_mail_node__t.html#adc525266dacc05e195c3b72d140b6b05", null ],
[ "next", "structs_mail_node__t.html#a67cb14019eb48bc46327bcafa0cff740", null ]
]; | 0.048828 | 0 |
src/pages/kidok.js | hansvertriest/Orbit-DevStudio | 0 | 2687 | import React from "react"
import { Helmet } from "react-helmet"
import Layout from "../components/layout"
import img0 from '../images/screenshots/connus-banner.png'
import img1 from '../images/screenshots/connus-1.png'
import img2 from '../images/screenshots/connus-2.png'
import img3 from '../images/screenshots/connus-3.png'
const IndexPage = () => (
<Layout>
<Helmet>
<meta charSet="utf-8" />
<title>Orbit DevStudio | KidOk-kit</title>
<meta name="description" content="Datavisualisatie voor Vlugmoor UGent."/>
<meta name="keywords" content="web, development, webdesign, website, freelance, app, application, datavisualisatie, data" />
<meta name="author" content="<NAME>" />
</Helmet>
<div className="project-container">
<div className="container">
<a href="/#projects">Terug naar overzicht</a>
<h1>Mijn projecten</h1>
<h2>KidOk-kit</h2>
</div>
<div className="container">
<div className="row">
<div className="col-12 col-md-6">
<h3>Project</h3>
<p>Open Poortje is een opvang voor kinderen die om eender welke reden thuis niet meer terecht kunnen. Zij gebruiken de KidOk-kit: een papieren bundel fiches die worden ingevuld samen met het kind om zijn/haar proces in Open Poortje op te volgen. Onze briefing was het ontwikkelen van een digitale versie van de KidOk-kit met een focus op animatie en interactiviteit. Design door <NAME>, <NAME> en <NAME>. Animatie door Stijn Stevens. Front-end door <NAME>, <NAME> en <NAME>. Backend door Hans Vertriest.</p>
</div>
<div className="col-12 col-md-6">
<h3>Technologieën</h3>
<p>ReactJS, Express, Mongoose, MongoDB</p>
<h3>Eigen inbreng</h3>
<p>Backend en integratie ervan in de frontend</p>
</div>
<div className="col-12 col-md-6">
<iframe width="560" height="315" src="https://www.youtube.com/embed/Sr36fT4X8Yw" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</div>
</div>
</div>
</Layout>
)
export default IndexPage
| 1.234375 | 1 |
test/helpers/config-test.js | sznowicki/ubbthreads-cherrypick-exporter | 0 | 2695 | const chai = require('chai');
const should = chai.should();
const config = require('../../app/helpers/config');
describe('Mysql config test', function() {
it('Should give all required properties for mysql', function() {
const keyToCheck = [
'host',
'dbname',
'username',
'password',
'prefix'
];
keyToCheck.forEach(val => {
config.getSetting(`mysql.${val}`).should.be.a('string');
});
});
}); | 1.328125 | 1 |
src/test.js | CrystalAngelLee/vue-webpack-demo | 0 | 2703 | export default () => {
const element = document.createElement("h2");
element.textContent = "Hello world";
element.addEventListener("click", () => {
alert("Hello webpack");
});
return element;
};
| 0.910156 | 1 |
04/js/app.js | liuxuanhai/react-book-examples | 811 | 2711 | import ReactDOM from 'react-dom';
import React from 'react';
import CommentBox from './components/CommentBox';
import '../css/style.css';
ReactDOM.render(<CommentBox />, document.getElementById('root'));
| 0.75 | 1 |
lib/relue/math/generators.js | jeremyagray/relue | 0 | 2719 | 'use strict';
const nt = require('./number-theory.js');
/**
* Generates the sequence of perfect cubes.
*
* @generator
* @name cubes
* @memberof math
* @api public
*
* @param {number} n - The first perfect cube.
* @yields {number} The next perfect cube.
*
* @example
* const generator = relue.math.cubes();
*
* // Returns next perfect cube.
* console.log(generator.next().value);
*/
exports.cubes = function*(n=0) {
while (true) {
yield n * n * n;
n++;
}
};
/**
* Generates the sequence of even numbers.
*
* @generator
* @name evens
* @memberof math
* @api public
*
* @yields {number} The next even number, beginning at 0.
*
* @example
* const generator = relue.math.evens();
*
* // Returns next even number.
* console.log(generator.next().value);
*/
exports.evens = function*() {
let n = 0;
while (true) {
yield n;
n += 2;
}
};
/**
* Generates the sequence of odd numbers.
*
* @generator
* @name odds
* @memberof math
* @api public
*
* @yields {number} The next odd number, beginning at 1.
*
* @example
* const generator = relue.math.odds();
*
* // Returns next odd number.
* console.log(generator.next().value);
*/
exports.odds = function*() {
let n = 1;
while (true) {
yield n;
n += 2;
}
};
/**
* Generates the Fibonacci sequence.
*
* @generator
* @name fibonaccis
* @memberof math
* @api public
*
* @yields {number} The next Fibonacci number.
*
* @example
* const generator = relue.math.fibonaccis();
*
* // Returns next Fibonacci number.
* console.log(generator.next().value);
*/
exports.fibonaccis = function*() {
let a = 0;
let b = 1;
let tmp = 0;
while (true) {
yield a;
tmp = a;
a = b;
b = b + tmp;
}
};
/**
* Generates the hailstone sequence for n.
*
* @generator
* @name hailstone
* @memberof math
* @api public
*
* @param {number} n - The starting number of the hailstone sequence.
* @yields {number} The next number in the hailstone sequence for n.
*
* @example
* const generator = relue.math.hailstone(27);
*
* // Prints 82.
* console.log(generator.next().value);
*/
exports.hailstone = function*(n) {
if (n === undefined
|| n === null
|| typeof n === 'boolean'
|| typeof n === 'string'
|| Number.isNaN(n)) {
return null;
}
let m = n;
// First time.
if (m < 1) {
return 0;
} else if (m === 1) {
return m;
} else {
yield m;
}
// Sequence generation.
while (true) {
if (m === 1) {
return m;
} else if (m % 2 === 0) {
m = m / 2;
} else {
m = 3 * m + 1;
}
yield m;
}
};
/**
* Generates the pentagonal sequence.
*
* @generator
* @name pentagonal
* @memberof math
* @api public
*
* @yields {number} n - The next number in the pentagonal sequence.
*
* @example
* const generator = relue.math.pentagonal();
*
* // Prints 1, 2, 5, 7, 12, 15, 20, ...
* console.log(generator.next().value);
*/
exports.pentagonal = function*() {
let k = 1;
while (true) {
yield (k * (3 * k - 1) / 2);
k = -k;
yield (k * (3 * k - 1) / 2);
k = -k;
k++;
}
};
/**
* Generates prime numbers.
*
* @generator
* @name primes
* @memberof math
* @api public
*
* @param {number} [n=2] - The number to start searching for primes.
* @yields {number} The next prime number.
*
* @example
* const generator = relue.math.primes();
*
* // Returns next prime.
* console.log(generator.next().value);
*/
exports.primes = function*(n=2) {
let i = n;
while (true) {
if (nt.isPrime(i)) {
yield i;
}
i++;
}
};
/**
* Generates the sequence of perfect squares.
*
* @generator
* @name squares
* @memberof math
* @api public
*
* @param {number} n - The first perfect square.
* @yields {number} The next perfect square.
*
* @example
* const generator = relue.math.squares();
*
* // Returns next perfect square.
* console.log(generator.next().value);
*/
exports.squares = function*(n=0) {
while (true) {
yield n * n;
n++;
}
};
| 2.734375 | 3 |
test/transaction/input/publickey.js | POPChainFoundation/bitcore-lib-pch | 4 | 2727 | 'use strict';
var should = require('chai').should();
var bitcore = require('../../..');
var Transaction = bitcore.Transaction;
var PrivateKey = bitcore.PrivateKey;
describe('PublicKeyInput', function() {
var utxo = {
txid: '7f3b688cb224ed83e12d9454145c26ac913687086a0a62f2ae0bc10934a4030f',
vout: 0,
address: 'yjA6k167XHU4FqZbFWpSLTe5ivngfiJhKc',
scriptPubKey: '2103c9594cb2ebfebcb0cfd29eacd40ba012606a197beef76f0269ed8c101e56ceddac',
amount: 50,
confirmations: 104,
spendable: true
};
var privateKey = PrivateKey.fromWIF('<KEY>');
var address = privateKey.toAddress();
utxo.address.should.equal(address.toString());
var destKey = new PrivateKey();
it('will correctly sign a publickey out transaction', function() {
var tx = new Transaction();
tx.from(utxo);
tx.to(destKey.toAddress(), 10000);
tx.sign(privateKey);
tx.inputs[0].script.toBuffer().length.should.be.above(0);
});
it('count can count missing signatures', function() {
var tx = new Transaction();
tx.from(utxo);
tx.to(destKey.toAddress(), 10000);
var input = tx.inputs[0];
input.isFullySigned().should.equal(false);
tx.sign(privateKey);
input.isFullySigned().should.equal(true);
});
it('it\'s size can be estimated', function() {
var tx = new Transaction();
tx.from(utxo);
tx.to(destKey.toAddress(), 10000);
var input = tx.inputs[0];
input._estimateSize().should.equal(73);
});
it('it\'s signature can be removed', function() {
var tx = new Transaction();
tx.from(utxo);
tx.to(destKey.toAddress(), 10000);
var input = tx.inputs[0];
tx.sign(privateKey);
input.isFullySigned().should.equal(true);
input.clearSignatures();
input.isFullySigned().should.equal(false);
});
it('returns an empty array if private key mismatches', function() {
var tx = new Transaction();
tx.from(utxo);
tx.to(destKey.toAddress(), 10000);
var input = tx.inputs[0];
var signatures = input.getSignatures(tx, new PrivateKey(), 0);
signatures.length.should.equal(0);
});
});
| 1.648438 | 2 |
Community/iot_device_registration/js/iotdeviceregistration_page.js | TMAers/gateway-workflows | 0 | 2735 | // Copyright 2019 BlueCat Networks. All rights reserved.
$(document).ready(function()
{
$("#file").prop("disabled", false);
$("#submit").prop("disabled", false);
});
| 0.322266 | 0 |
resources/assets/js/partials/order.js | JanTrnavsky/da-test-webapp | 0 | 2743 | module.exports = {
init: function (app, webSection) {
if (webSection != 'orders') {
return;
}
this.ares.init(app);
},
ares: {
init: function () {
$('input#ico').change(this.icoFilled.bind(this));
},
icoFilled: function (e) {
var t = $(e.target);
if (t.val() == '') {
return;
}
if (t.val().match(/^[0-9]{4,8}$/) == null) {
toastr.error(CzechitasApp.config('orders.notFoundMsg'));
return;
}
var url = CzechitasApp.config('orders.aresUrl');
if (!url) {
console.log('Missing route for ARES');
return;
}
this.inputsDisabled(true);
$.ajax({
type: 'POST',
url: url,
data: { ico: t.val() },
success: this.dataReceived.bind(this),
error: this.dataError.bind(this),
complete: this.inputsDisabled.bind(this, false),
});
},
dataReceived: function (data) {
$('#address').val(data.address);
$('#client').val(data.company);
toastr.success(CzechitasApp.config('orders.successMsg'));
},
dataError: function (jqXHR) {
toastr.error(CzechitasApp.config(jqXHR.status == 404 ? 'orders.notFoundMsg' : 'orders.errorMsg'));
},
inputsDisabled: function (disable) {
var placeholder = disable ? CzechitasApp.config('orders.ares_searching') : '';
$('#address, #client').prop('disabled', disable).attr('placeholder', placeholder);
},
},
};
| 1.242188 | 1 |
new-bootcamp-prep-assessments-master/final_evaluation/final_eval/problems/1_word_sandwich.js | skullbaselab/instructor_documents | 0 | 2751 | /**************************************************************************************
Write a function `wordSandwich(outerWord, innerWord)` that takes in two strings and
returns a string representing a word sandwich. See the examples below.
Examples:
wordSandwich('bread', 'cheese'); // => 'BREADcheeseBREAD'
wordSandwich('BREAD', 'CHEESE'); // => 'BREADcheeseBREAD'
wordSandwich('HeLLo', 'worLD'); // => 'HELLOworldHELLO'
Difficulty: Easy
*************************************************************************************/
function wordSandwich(outerWord, innerWord) {
}
/******************** DO NOT MODIFY ANYTHING UNDER THIS LINE *************************/
module.exports = wordSandwich;
| 2.328125 | 2 |
js/controller/ColorService.js | Vincent-0x00/BunkersCharacterDesigner | 0 | 2759 | "use strict";
import {getColors, getColorsList} from "../data/DataHandler.js";
import {ViewController} from "../view/ViewController.js";
/**
* controller for colors
* @author <NAME>
*/
export class ColorService {
constructor() {
}
/**
* shows the color options for a type
* @param type
*/
populateColors(type) {
let viewController = new ViewController();
let colorsList = getColorsList(
document.querySelector("input[name='species']:checked").value,
document.querySelector("input[name='subspecies']:checked").value,
document.querySelector("input[name='variant']:checked").value,
type
);
let selection = "";
let count = colorsList.length;
for (let i = 0; i < count; i++) {
let color = colorsList[i];
let hexCode = "#fefefe";
if (Array.isArray(color)) {
color = color[0];
}
if (typeof color === 'object' && color[0] !== null) {
if (color.select !== null)
hexCode = color.select;
} else
hexCode = color;
selection += viewController.buildHeart(type, i, hexCode);
}
document.getElementById(type).innerHTML = selection;
document.querySelector("input[name='" + type + "']").checked = true;
}
/**
* the user changed the color for skin, ears or eyes
*/
changeColors() {
let style = ".skins0 {fill:none; stroke:#000; stroke-width:2px;} " +
".skins1,.skins2,.skins3,.ears0,.ears1,.ears2,.ears3 {fill:none;}";
let mask = "";
let defs = "";
let types = ["skins", "ears", "eyes"];
for (const type in types) {
let fieldId = types[type];
let colors = getColors(
document.querySelector("input[name='species']:checked").value,
document.querySelector("input[name='subspecies']:checked").value,
document.querySelector("input[name='variant']:checked").value,
fieldId,
document.querySelector("input[name='" + fieldId + "']:checked").value
);
if (!Array.isArray(colors)) {
colors = [colors, "none", "none"];
}
let data = colors[0];
if (data == null || typeof data !== "object") {
style += this.colorValues(colors, fieldId);
} else {
let keys = Object.keys(data);
for (let j = 0; j < keys.length; j++) {
if (keys[j] === "style") {
style += data.style;
} else if (keys[j] === "mask") {
mask += data.mask;
} else {
defs += data.defs;
}
}
}
}
let styles = "<style id='svgStyle'>" + style + "</style>";
document.getElementById("svgDefs").innerHTML = styles + defs;
}
/**
* get the colors from an array of hex values
* @param colors
* @param fieldId
* @returns {string}
*/
colorValues(colors, fieldId) {
let style = "";
for (let i = 0; i < 4; i++) {
let data;
if (i < colors.length) {
data = colors[i];
} else {
data = "none";
}
style += "." + fieldId + i + "{fill: " + data + "} ";
}
return style;
}
} | 1.78125 | 2 |
js/routes.js | wuliupo/simple-vue | 0 | 2767 | ~function () {
window.SIMPLE_VUE = window.SIMPLE_VUE || {};
var loader = window.SIMPLE_VUE.loader;
var common = {name: 'page-common', template: '<router-view class="page-common">Loading...</router-view>'}
window.SIMPLE_VUE.routes = [{
path: '/',
name: '',
redirect: '/home',
},
{
path: '/home',
component: loader,
name: 'home',
meta: {
nav: '首页',
html: 'pages/home/home.html',
js: 'pages/home/home.js',
css: 'pages/home/home.css'
}
},
{
path: '/todo',
component: loader,
name: 'todo',
meta: {
nav: 'TODO',
vue: 'pages/todo.vue'
}
},
{
path: '/about',
component: loader,
name: 'about',
meta: {
nav: '关于',
html: 'pages/about/about.html',
css: 'pages/about/about.css'
}
},
{
path: '/post',
component: common,
name: '',
meta: {
nav: '日志'
},
children: [
{
path: '',
component: loader,
name: 'post-list',
meta: {
nav: '日志列表',
html: 'pages/post/post-list.html',
js: 'pages/post/post-list.js',
css: 'pages/post/post.css'
}
},
{
path: ':id',
component: loader,
name: 'post-detail',
meta: {
nav: '日志正文',
html: 'pages/post/post-detail.html',
js: 'pages/post/post-detail.js',
css: 'pages/post/post.css'
}
}
]
},
{
path: '/404',
component: loader,
name: '404',
meta: {
html: 'pages/404.html'
}
},
{
path: '*',
redirect: {
path: '/404'
}
}
];
}();
| 1.0625 | 1 |
website/src/components/TeaserFlow/B.js | moulik-deepsource/react-flow | 0 | 2775 | import React, { useState, useEffect } from 'react';
import styled from '@emotion/styled';
import ReactFlow, {
Handle,
ReactFlowProvider,
Background,
Controls,
} from 'react-flow-renderer';
import TeaserFlow from 'components/TeaserFlow';
import { baseColors } from 'themes';
const NodeWrapper = styled.div`
background: ${(p) => p.theme.colors.silverLighten30};
padding: 8px 10px;
font-size: 12px;
border-radius: 4px;
input {
font-size: 12px;
border: 1px solid ${(p) => p.theme.colors.violetLighten60};
width: 100%;
border-radius: 2px;
max-width: 100px;
}
.react-flow__handle {
background: ${(p) => p.theme.colors.violetLighten60};
}
`;
const InputLabel = styled.div`
color: ${(p) => p.theme.colors.violetLighten60};
`;
const InputNode = ({ id, data }) => {
return (
<NodeWrapper>
<InputLabel>{data.label}:</InputLabel>
<input
className="nodrag"
value={data.value}
onChange={(event) => data.onChange(event, id)}
/>
<Handle type="source" position="bottom" />
</NodeWrapper>
);
};
const ResultNode = ({ data }) => {
return (
<NodeWrapper>
<div>{data.value}</div>
<Handle type="target" position="top" id="a" style={{ left: '40%' }} />
<Handle type="target" position="top" id="b" style={{ left: '60%' }} />
</NodeWrapper>
);
};
const nodeTypes = {
nameinput: InputNode,
result: ResultNode,
};
const onLoad = (rf) => setTimeout(() => rf.fitView({ padding: 0.1 }), 1);
const findNodeById = (id) => (n) => n.id === id;
export default () => {
const [elements, setElements] = useState([]);
useEffect(() => {
const onChange = (event, id) => {
setElements((els) => {
const nextElements = els.map((e) => {
if (e.id !== id) {
return e;
}
const value = event.target.value;
return {
...e,
data: {
...e.data,
value,
},
};
});
const forname = nextElements.find(findNodeById('1')).data.value;
const lastname = nextElements.find(findNodeById('2')).data.value;
const result = `${forname} ${lastname}`;
const resultNode = nextElements.find((n) => n.type === 'result');
resultNode.data = {
...resultNode.data,
value: !forname && !lastname ? '*please enter a name*' : result,
};
return nextElements;
});
};
const initialElements = [
{
id: '1',
type: 'nameinput',
position: {
x: 0,
y: 200,
},
data: {
label: 'Forename',
value: 'React',
onChange,
},
},
{
id: '2',
type: 'nameinput',
position: {
x: 400,
y: 200,
},
data: {
label: 'Lastname',
value: 'Flow',
onChange,
},
},
{
id: '3',
type: 'result',
position: {
x: 200,
y: 400,
},
data: {
value: 'React Flow',
},
},
{
id: 'e1',
source: '1',
target: '3__a',
animated: true,
},
{
id: 'e2',
source: '2',
target: '3__b',
animated: true,
},
];
setElements(initialElements);
}, []);
return (
<TeaserFlow
title="Customizable"
description="You can create your own node and edge types or just pass a custom style. You can implement custom UIs inside your nodes and add functionality to your edges."
textPosition="right"
fitView
isDark
>
<ReactFlowProvider>
<ReactFlow
elements={elements}
nodeTypes={nodeTypes}
onLoad={onLoad}
zoomOnScroll={false}
>
<Background color={baseColors.silverDarken60} gap={15} />
<Controls showInteractive={false} />
</ReactFlow>
</ReactFlowProvider>
</TeaserFlow>
);
};
| 1.804688 | 2 |
src/store/mutations/structs.js | opensparkl/sse_dc_editor | 0 | 2783 | /**
* Copyright 2018 SPARKL Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Vue from 'vue'
import _ from 'lodash'
import Tree from '../../util/tree'
import Type from '../../util/type'
import store from '../index'
var createMissingService = function (nodes, rootId, op) {
var service = {
tag: 'service',
attr: {
name: op.attr.service
}
}
var services = Tree.searchUp(nodes, op.attr.id, service, {limit: 1})
if (services.length === 0) {
service = Vue.util.extend(service, {
parent_id: rootId,
is_ghost: true
})
store.commit('createStruct', service)
return true
}
return false
}
var mutations = {
createStruct (state, payload) {
var nodes = state.nodes
var node = Tree.create(nodes, payload, {append: true})
if (payload.hasOwnProperty('$position')) {
Tree.parent(nodes, node, node.parent_id, {
position: payload.$position
})
}
},
updateStruct (state, {id, partial}) {
var node = state.nodes[id]
if (node) {
_.merge(node, partial)
Vue.set(state.nodes, id, node)
}
},
moveStruct (state, {id, to, at}) {
if (to) {
const node = state.nodes[id]
const parentId = node.parent_id
const type = Type.is(node)
Tree.parent(state.nodes, id, to, {position: at})
if (type === 'operation' && node.attr.service) {
createMissingService(state.nodes, state.rootId, node)
}
if (type === 'service') {
const serviceName = node.attr.name
const operations = []
Tree.traverse(state.nodes, parentId, (child, params) => {
const type = Type.is(child)
if (type === 'operation' && child.attr.service === serviceName) {
operations.push(child)
return window.TRAVERSE.CONTINUE
}
/* If service with such name exists, stop traversion in the
child folders
*/
if (type === 'service' && child.attr.name === serviceName) {
return window.TRAVERSE.STOP_BRANCH
}
})
for (let i = 0; i < operations.length; i++) {
const op = operations[i]
/*
Create a service if it is not an ancestor of the operations.
Also there is no need to iterate futher, because service is
created in the root
*/
if (!Tree.isAncestorOf(state.nodes, node, op)) {
var created = createMissingService(state.nodes, state.rootId, op)
console.log('Created referenced service for ' + op.attr.name)
if (created) {
break
}
}
}
}
if (type === 'field') {
const operations = []
const fieldId = node.attr.id
const fieldName = node.attr.name
Tree.traverse(state.nodes, parentId, (child, params) => {
var childType = Type.is(child)
if (childType === 'field' && child.attr.name === fieldName) {
return window.TRAVERSE.STOP_BRANCH
}
if (childType === 'operation' && child.attr.fields) {
var index = child.attr.fields.indexOf(fieldId)
if (index !== -1) {
/* Caching operation object and index in "fields" array */
operations.push({
index: index,
op: child
})
}
}
})
var field = null
for (let i = 0; i < operations.length; i++) {
const {op, index} = operations[i]
const isAncestor = Tree.isAncestorOf(state.nodes, fieldId, op)
if (!isAncestor) {
if (!field) {
field = Tree.create(state.nodes, {
tag: 'field',
attr: {
name: fieldName
},
is_ghost: true,
parent_id: state.rootId
}, {append: true})
}
op.attr.fields.splice(index, 1, field.attr.id)
}
}
}
} else {
console.error('Please, specifiy the target for ' + id)
}
},
deleteStruct (state, id) {
Tree.remove(state.nodes, id)
if (state.selectedId === id && !state.nodes[id]) {
state.selectedId = null
}
},
selectStruct (state, id) {
if (state.selectedId) {
store.commit('unselectStruct')
}
state.selectedId = id
},
unselectStruct (state) {
if (state.selectedId) {
var selected = state.nodes[state.selectedId]
var isOperation = Type.is(selected.tag) === 'operation'
if (isOperation && selected.attr.service) {
createMissingService(state.nodes, state.rootId, selected)
}
state.selectedId = null
}
}
}
export default mutations
| 1.742188 | 2 |
assets/javascripts/discourse/components/count-i18n.js.es6 | vndee/unescohackathon-xixforum | 2 | 2791 | import { bufferedRender } from "discourse-common/lib/buffered-render";
export default Ember.Component.extend(
bufferedRender({
tagName: "span",
rerenderTriggers: ["count", "suffix"],
buildBuffer(buffer) {
buffer.push(
I18n.t(this.get("key") + (this.get("suffix") || ""), {
count: this.get("count")
})
);
}
})
);
| 1.226563 | 1 |
src/components/SearchBox/SearchBox.js | KutieKat/github-emojis-cheatsheet | 0 | 2799 | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { updateKeyword, resetKeyword, filterEmojis } from '../../store/ActionCreators';
import './SearchBox.css';
class SearchBox extends Component {
handleResetKeyword() {
this.props.dispatch(resetKeyword());
this.props.dispatch(filterEmojis());
}
handleChangeKeyword(e) {
this.props.dispatch(updateKeyword(e.target.value));
this.props.dispatch(filterEmojis());
}
render() {
let removeButton = null;
if(this.props.keyword != '') {
removeButton = <button className="btn" onClick={ () => this.handleResetKeyword() }><i className="fas fa-times-circle btn-remove"></i></button>;
}
return (
<header className="search-box">
<input
type="text"
placeholder={ 'Search ' + this.props.filteredEmojis.length + ' emojis for...' }
value={ this.props.keyword }
onChange={ (e) => this.handleChangeKeyword(e) } />
{ removeButton }
</header>
);
}
}
function mapStateToProps(state) {
return {
keyword: state.keyword,
filteredEmojis: state.filteredEmojis
}
}
export default connect(mapStateToProps)(SearchBox); | 1.59375 | 2 |
rockfish_client/rockfish_client_android/Rockfish/app/src/main/assets/rockfish_client_web.js | devsunset/rockfish | 5 | 2807 | /*■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■*/
/* filename : rockfish_client_web.js
/* author : devsunset (<EMAIL>)
/* desc : rockfish client web (ajax module)
/*■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■*/
// PARAMETER 평문 설정
var ROCKFISH_PARAMETER_PLAIN = "ROCKFISH_PARAMETER_PLAIN";
// PARAMETER 암호화 설정
var ROCKFISH_PARAMETER_ENCRYPT = "ROCKFISH_PARAMETER_ENCRYPT";
// RSA 암호화 공개 키 ■■■ TO-DO set up 한 공개 key 값 으로 치환 필요
var ROCKFISH_RSA_PUBLIC_KEY_VALUE = '-----BEGIN PUBLIC KEY-----';
ROCKFISH_RSA_PUBLIC_KEY_VALUE+='<KEY>';
ROCKFISH_RSA_PUBLIC_KEY_VALUE+='<KEY>';
ROCKFISH_RSA_PUBLIC_KEY_VALUE+='<KEY>';
ROCKFISH_RSA_PUBLIC_KEY_VALUE+='<KEY>';
ROCKFISH_RSA_PUBLIC_KEY_VALUE+='<KEY>';
ROCKFISH_RSA_PUBLIC_KEY_VALUE+='<KEY>';
ROCKFISH_RSA_PUBLIC_KEY_VALUE+='<KEY>';
ROCKFISH_RSA_PUBLIC_KEY_VALUE+='-----END PUBLIC KEY-----';
var ROCKFISH_RSA_JSENCRYPT = new JSEncrypt();
ROCKFISH_RSA_JSENCRYPT.setPublicKey(ROCKFISH_RSA_PUBLIC_KEY_VALUE);
/**
* <pre>
* rockfish ajax Common call function
* </pre>
* @param service : 호출 service target
* @param data : 호출 parameter
* @param encdata : 암호화 설정 값
* ROCKFISH_PARAMETER_PLAIN (전체 평문)
* ROCKFISH_PARAMETER_ENCRYPT (전체 암호화)
* Array() field value (암호화 하고자 하는 field)
* @param callback : success callback 함수
* @param errorcallback : error callback 함수
* @param loadingbar : 공통으로 progress bar 등을 사용하는 경우 호출 Action에 따라 표시 유무 설정
* @param async : 동기화 여부 설정 기본은 true
* @param attachField : 첨부파일 Array Field
* @param attachFile : 첨부파일 Array Object
* @param downolad : 다운로드 호출 설정
*
* ■■■ TO-DO 표시 항목에 대해서는 사용자가 요건에 맞게 정의 하여 사용 ■■■
*
*/
function rockfishAjax(service, data, encdata, callback, errorcallback, loadingbar, async, attachField , attachFile, downolad){
if(service === undefined || service === null || service.trim() == ""){
alert("error : service value is empty");
return;
}
// TO-DO ROCKFISH URL (http,https - https://localhost:9999)
// HTTPS 사용시 self-sign에 따른 오류 발생 - 공인 인증서 사용하면 HTTPS 사용 가능
//var url = "https://localhost:9999/rockfishController";
//var url = "http://localhost:8888/rockfishController";
//var downloadurl = "http://localhost:8888/rockfishDownloadController";
// TEST용 (서버 IP 동적 설정)
var url = "http://"+$("#IPPORT").val()+"/rockfishController";
var downloadurl = "http://"+$("#IPPORT").val()+"/rockfishDownloadController";
var rockfishSendType = "G"; // G : General M : Multipart D : Download
if(typeof async === undefined){
async = true;
}
if(typeof downolad === undefined){
downolad = false;
}
var paramData = null;
var encryptParameter = "";
if(ROCKFISH_PARAMETER_PLAIN === encdata){
paramData = data;
}else if (ROCKFISH_PARAMETER_ENCRYPT === encdata){
if(data !== null && data !== undefined){
for(var fidx = 0;fidx <data.length;fidx++){
encryptParameter += data[fidx].name +"|^|";
data[fidx].value = rockfishRsaEncrypt(data[fidx].value);
}
paramData = data;
}
}else{
if( Object.prototype.toString.call( encdata ) === '[object Array]' ) {
if(encdata !==null && encdata.length > 0){
for(var fidx = 0;fidx <data.length;fidx++){
if($.inArray(data[fidx].name, encdata) != -1){
encryptParameter += data[fidx].name +"|^|";
data[fidx].value = rockfishRsaEncrypt(data[fidx].value);
}
}
paramData = data;
}else{
paramData = data;
}
}else{
paramData = data;
}
}
if(attachField !== null && typeof attachField !== 'undefined'
&& attachFile !== null && typeof attachFile !== 'undefined'
&& attachField.length == attachFile.length){
rockfishSendType = "M";
if (window.File && window.FileList && window.Blob && window.FileReader && window.FormData) {
var formData = new FormData();
if(paramData !=null && paramData.length > 0){
for(var fidx = 0;fidx <paramData.length;fidx++){
formData.append(paramData[fidx].name,paramData[fidx].value);
}
}
for(var fileIdx = 0 ;fileIdx < attachFile.length; fileIdx++){
if( Object.prototype.toString.call(attachFile[fileIdx]) === '[object File]' ){
formData.append(attachField[fileIdx],attachFile[fileIdx]);
}else{
alert("object is not file object");
return;
}
}
paramData = formData;
} else {
alert("browser doesn't supports File API");
return;
}
}
if(downolad){
rockfishSendType = "D";
}
if(rockfishSendType == "G"){
$.ajax({
type : "POST",
url : url,
async : async,
cache : false,
data : paramData,
crossDomain : true,
contentType: "application/json; charset=utf-8",
success : function(response, status, request) {
callback(response);
},
beforeSend: function(xhr) {
/* ROCKFISH CUSTMOMER HEADER*/
xhr.setRequestHeader("rockfish_session_key", rockfishGetStorge("rockfish_session_key"));
xhr.setRequestHeader("rockfish_access_id", rockfishGetStorge("rockfish_access_id"));
xhr.setRequestHeader("rockfish_ip", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_mac", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_phone", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_device", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_imei", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_os", "BROWSER");
xhr.setRequestHeader("rockfish_os_version", rockfishBrowserType());
xhr.setRequestHeader("rockfish_os_version_desc", navigator.userAgent);
xhr.setRequestHeader("rockfish_target_service", service);
xhr.setRequestHeader("rockfish_client_app", "Rockfish"); // TO-DO Client App
xhr.setRequestHeader("rockfish_client_app_version", "1.0"); // TO-DO Client App Version
xhr.setRequestHeader("rockfish_send_type", "G");
xhr.setRequestHeader("rockfish_encrypt_parameter", encryptParameter);
// TO-DO COMMON PROGRESS START (EX : PROGRESSING BAR LOADING) loadingbar true : false
},
complete: function() {
// TO-DO COMMON PROGRESS END (EX : PROGRESSING BAR CLOASE) loadingbar true : false
},
error : function(request, status, error) {
if(errorcallback !== null && typeof errorcallback !== "undefined"){
errorcallback(status,error);
}else{
// TO-DO customer define
var errorMsg = 'status(code) : ' + request.status + '\n';
errorMsg += 'statusText : ' + request.statusText + '\n';
errorMsg += 'responseText : ' + request.responseText + '\n';
errorMsg += 'textStatus : ' + status + '\n';
errorMsg += 'errorThrown : ' + error;
alert(errorMsg);
}
}
});
}else if(rockfishSendType == "M"){
$.ajax({
type : "POST",
url : url,
async : async,
cache : false,
processData : false,
data : paramData,
crossDomain : true,
contentType: false,
success : function(response, status, request) {
callback(response);
},
beforeSend: function(xhr) {
/* ROCKFISH CUSTMOMER HEADER*/
xhr.setRequestHeader("rockfish_session_key", rockfishGetStorge("rockfish_session_key"));
xhr.setRequestHeader("rockfish_access_id", rockfishGetStorge("rockfish_access_id"));
xhr.setRequestHeader("rockfish_ip", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_mac", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_phone", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_device", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_imei", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_os", "BROWSER");
xhr.setRequestHeader("rockfish_os_version", rockfishBrowserType());
xhr.setRequestHeader("rockfish_os_version_desc", navigator.userAgent);
xhr.setRequestHeader("rockfish_target_service", service);
xhr.setRequestHeader("rockfish_client_app", "Rockfish"); // TO-DO Client App
xhr.setRequestHeader("rockfish_client_app_version", "1.0"); // TO-DO Client App Version
xhr.setRequestHeader("rockfish_send_type", "M");
xhr.setRequestHeader("rockfish_encrypt_parameter", encryptParameter);
// TO-DO COMMON PROGRESS START (EX : PROGRESSING BAR LOADING) loadingbar true : false
},
complete: function() {
// TO-DO COMMON PROGRESS END (EX : PROGRESSING BAR CLOASE) loadingbar true : false
},
error : function(request, status, error) {
if(errorcallback !== null && typeof errorcallback !== "undefined"){
errorcallback(status,error);
}else{
// TO-DO customer define
var errorMsg = 'status(code) : ' + request.status + '\n';
errorMsg += 'statusText : ' + request.statusText + '\n';
errorMsg += 'responseText : ' + request.responseText + '\n';
errorMsg += 'textStatus : ' + status + '\n';
errorMsg += 'errorThrown : ' + error;
alert(errorMsg);
}
}
});
}else{
$.ajax({
type : "POST",
url : url,
async : async,
cache : false,
data : paramData,
crossDomain : true,
success : function(response, status, request) {
rockfishAjaxDownload(downloadurl,response.ROCKFISH_RESULT_JSON);
/*
var contTypeDisposition = request.getResponseHeader ("Content-Disposition");
if (contTypeDisposition && contTypeDisposition.indexOf("=") !== -1) {
var filename = contTypeDisposition.substring(contTypeDisposition.indexOf("=")+1,contTypeDisposition.length);
var blob = new Blob([response], {type: "octet/stream"});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=filename;
link.click();
}
*/
},
beforeSend: function(xhr) {
/* ROCKFISH CUSTMOMER HEADER*/
xhr.setRequestHeader("rockfish_session_key", rockfishGetStorge("rockfish_session_key"));
xhr.setRequestHeader("rockfish_access_id", rockfishGetStorge("rockfish_access_id"));
xhr.setRequestHeader("rockfish_ip", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_mac", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_phone", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_device", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_imei", rockfishRsaEncrypt("")); // Ignore Web Client
xhr.setRequestHeader("rockfish_os", "BROWSER");
xhr.setRequestHeader("rockfish_os_version", rockfishBrowserType());
xhr.setRequestHeader("rockfish_os_version_desc", navigator.userAgent);
xhr.setRequestHeader("rockfish_target_service", service);
xhr.setRequestHeader("rockfish_client_app", "Rockfish"); // TO-DO Client App
xhr.setRequestHeader("rockfish_client_app_version", "1.0"); // TO-DO Client App Version
xhr.setRequestHeader("rockfish_send_type", "D");
xhr.setRequestHeader("rockfish_encrypt_parameter", encryptParameter);
// TO-DO COMMON PROGRESS START (EX : PROGRESSING BAR LOADING) loadingbar true : false
},
complete: function() {
// TO-DO COMMON PROGRESS END (EX : PROGRESSING BAR CLOASE) loadingbar true : false
},
error : function(request, status, error) {
if(errorcallback !== null && typeof errorcallback !== "undefined"){
errorcallback(status,error);
}else{
// TO-DO customer define
var errorMsg = 'status(code) : ' + request.status + '\n';
errorMsg += 'statusText : ' + request.statusText + '\n';
errorMsg += 'responseText : ' + request.responseText + '\n';
errorMsg += 'textStatus : ' + status + '\n';
errorMsg += 'errorThrown : ' + error;
alert(errorMsg);
}
}
});
}
};
/**
* <pre>
* rsa encrypt
* </pre>
* @param toEncrypt : encrypt value
*
*/
function rockfishRsaEncrypt(toEncrypt){
if(toEncrypt === null || toEncrypt === "" || toEncrypt === undefined){
return "";
}else{
return ROCKFISH_RSA_JSENCRYPT.encrypt(toEncrypt);
}
}
/**
* <pre>
* set localStorge
* </pre>
* @param cName : storge key
* @param cValue : storge value
*
*/
function rockfishSetStorge(cName, cValue){
if( ('localStorage' in window) && window['localStorage'] !== null) {
localStorage.setItem(cName, cValue);
}else{
alert("현재 브라우저는 WebStorage를 지원하지 않습니다")
}
}
/**
* <pre>
* set localStorge
* </pre>
* @param cName : storge key
* @param cValue : storge value
*
*/
function rockfishSetEncryptStorge(cName, cValue){
if( ('localStorage' in window) && window['localStorage'] !== null) {
localStorage.setItem(cName, rockfishRsaEncrypt(cValue));
}else{
alert("현재 브라우저는 WebStorage를 지원하지 않습니다")
}
}
/**
* <pre>
* localStorge clear
* </pre>
*
*/
function rockfishClearStorge(){
if( ('localStorage' in window) && window['localStorage'] !== null) {
localStorage.clear();
}else{
alert("현재 브라우저는 WebStorage를 지원하지 않습니다")
}
}
/**
* <pre>
* get localStorge
* </pre>
* @param cName : storge key
*
*/
function rockfishGetStorge(cName) {
if( ('localStorage' in window) && window['localStorage'] !== null) {
if(localStorage.getItem(cName) == null){
return "";
}else{
return localStorage.getItem(cName);
}
}else{
alert("현재 브라우저는 WebStorage를 지원하지 않습니다")
return "";
}
}
/**
* <pre>
* get browser type
* </pre>
*/
function rockfishBrowserType(){
var agent = navigator.userAgent.toLowerCase();
var name = navigator.appName;
var browser = "Etc";
// MS 계열 브라우저를 구분하기 위함.
if(name === 'Microsoft Internet Explorer' || agent.indexOf('trident') > -1 || agent.indexOf('edge/') > -1) {
browser = 'ie';
if(name === 'Microsoft Internet Explorer') { // IE old version (IE 10 or Lower)
agent = /msie ([0-9]{1,}[\.0-9]{0,})/.exec(agent);
browser += parseInt(agent[1]);
} else { // IE 11+
if(agent.indexOf('trident') > -1) { // IE 11
browser += 11;
} else if(agent.indexOf('edge/') > -1) { // Edge
browser = 'edge';
}
}
} else if(agent.indexOf('safari') > -1) { // Chrome or Safari
if(agent.indexOf('opr') > -1) { // Opera
browser = 'opera';
} else if(agent.indexOf('chrome') > -1) { // Chrome
browser = 'chrome';
} else { // Safari
browser = 'safari';
}
} else if(agent.indexOf('firefox') > -1) { // Firefox
browser = 'firefox';
}
return browser;
}
/**
* <pre>
* download action
* </pre>
* @param url : download url
* @param data : json object
*
*/
function rockfishAjaxDownload(url, data) {
//To-Do (개선 필요)
location.href = url+"?ROCKFISH_TEMP_FILE="+encodeURIComponent(rockfishRsaEncrypt(data.ROCKFISH_TEMP_FILE))+"&ROCKFISH_REAL_FILE="+encodeURIComponent(rockfishRsaEncrypt(data.ROCKFISH_REAL_FILE));
/*
var agent = navigator.userAgent.toLowerCase();
if ( (navigator.appName == 'Netscape' && navigator.userAgent.search('Trident') != -1) || (agent.indexOf("msie") != -1) ) {
var url= url+"?ROCKFISH_TEMP_FILE="+encodeURIComponent(rockfishRsaEncrypt(data.ROCKFISH_TEMP_FILE))+"&ROCKFISH_REAL_FILE="+encodeURIComponent(rockfishRsaEncrypt(data.ROCKFISH_REAL_FILE));
var $form = $('<form></form>');
$form.attr('action', url);
$form.attr('method', 'POST');
$form.attr('target', '_blank');
$form.appendTo('body');
$form.submit();
}else{
var $iframe;
var iframe_doc;
var iframe_html;
if (($iframe = $('#download_iframe')).length === 0) {
$iframe = $("<iframe id='download_iframe'" +
" style='display: none' src='about:blank'></iframe>"
).appendTo("body");
}
iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
if (iframe_doc.document) {
iframe_doc = iframe_doc.document;
}
iframe_html = "<html><head></head><body><form method='POST' action='" + url +"'>";
Object.keys(data).forEach(function(key){
iframe_html += "<input type='hidden' name='"+key+"' value='"+rockfishRsaEncrypt(data[key])+"'>";
});
iframe_html +="</form></body></html>";
iframe_doc.open();
iframe_doc.write(iframe_html);
$(iframe_doc).find('form').submit();
}
*/
} | 1.007813 | 1 |
src/renderers/shaders/ShaderLib/linedashed_frag.js | 3dseals/Bonnie3D | 0 | 2815 | export default String('\n\
uniform vec3 diffuse;\n\
uniform float opacity;\n\
\n\
uniform float dashSize;\n\
uniform float totalSize;\n\
\n\
varying float vLineDistance;\n\
\n\
#include <common>\n\
#include <color_pars_fragment>\n\
#include <fog_pars_fragment>\n\
#include <logdepthbuf_pars_fragment>\n\
#include <clipping_planes_pars_fragment>\n\
\n\
void main() {\n\
\n\
#include <clipping_planes_fragment>\n\
\n\
if ( mod( vLineDistance, totalSize ) > dashSize ) {\n\
\n\
discard;\n\
\n\
}\n\
\n\
vec3 outgoingLight = vec3( 0.0 );\n\
vec4 diffuseColor = vec4( diffuse, opacity );\n\
\n\
#include <logdepthbuf_fragment>\n\
#include <color_fragment>\n\
\n\
outgoingLight = diffuseColor.rgb; // simple shader\n\
\n\
gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\
\n\
#include <premultiplied_alpha_fragment>\n\
#include <tonemapping_fragment>\n\
#include <encodings_fragment>\n\
#include <fog_fragment>\n\
\n\
}\n\
').replace( /[ \t]*\/\/.*\n/g, '' ).replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' ).replace( /\n{2,}/g, '\n' ); | 1.15625 | 1 |
rre-server/src/main/resources/static/code_templates.js | irwinmx-lng-con/rated-ranking-evaluator | 148 | 2823 | /**
* This is a controller
*
*/
(function () {
angular.module('App').controller('FeatureController', FeatureController);
FeatureController.$inject = ['$scope', 'logger', 'resolvedValue'];
function FeatureController($scope, logger, resolvedValue) {
var vm = this;
// Scope vars
vm.variable = 'value';
// Methods
vm.aMethod = aMethod;
activate();
////////////
/**
* controller activation
*/
function activate() {
logger.log('FeatureController', 'starting');
vm.variable = resolvedValue.data;
}
/**
* This is a method
* @param param
*/
function aMethod(param) {
vm.variable = param;
}
/**
* Watch a variable with $watch
*/
$scope.$watch('vm.variable', watchVariable);
function watchVariable(newValue) {
logger.log('FeatureController', 'variable=' + newValue);
}
}
})();
/**
* This is a service, preferably it should be stateless but it's not mandatory
*
*/
(function () {
angular.module('App').factory('SimpleService', SimpleService);
SimpleService.$inject = ['logger'];
function SimpleService(logger) {
var aVar; // A variable internal to the service
init();
return {
aMethod: aMethod,
anotherMethod: anotherMethod
};
////////////
/**
* Init
*/
function init() {
}
/**
* A simple method
*/
function aMethod(v) {
aVar = v;
}
/**
* Another simple method
*/
function anotherMethod() {
return aVar;
}
}
})();
/**
*
* This shared model is used among various collaborating controllers to share data
* It's a lightweight object useful to hold shareable data
*
*/
(function () {
angular.module('App').service('sharedModel', sharedModel);
sharedModel.$inject = [];
function sharedModel() {
var _this = this;
// Properties
_this.aVar = null;
_this.anotherVar = '';
}
})();
/**
* This is a router config
*
*/
(function () {
angular.module('App').config(config);
config.$inject = ['$routeProvider'];
function config($routeProvider) {
$routeProvider.when('/path/:id', {
controller: 'FeatureController',
controllerAs: 'vm',
templateUrl: 'views/theview.html',
resolve: {
resolvedValue: ['$route', 'AService', function ($route, AService) {
return AService.get($route.current.params.id);
}]
}
});
}
})();
/**
* This is a typical server-side API HTTP invocation.
* Please notice the function returns the promise object coming from $http service invocation.
* We prefer letting callers decide what to do with the promise.
*
* Ideally, this should be better placed in a service, as controllers and directives should not perform API calls directly.
* @param params A JSON object representing the parameters to send
* @returns {HttpPromise}
*/
function apiCallExample(params) {
return $http({
method: 'GET', // Or POST, PUT, DELETE, etc.
url: theUrl,
data: params
});
}
| 2.015625 | 2 |
public/admin/assets/plugins/bootstrap-timepicker/Gruntfile.js | enuenan/enan | 185 | 2831 | module.exports = function(grunt) {
'use strict';
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-jasmine');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-exec');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
project: 'bootstrap-timepicker',
version: '0.2.3'
},
exec: {
dump: {
command: 'grunt jshint; grunt uglify; grunt exec:deleteAssets; grunt less:production;'
},
copyAssets: {
command: 'git checkout gh-pages -q; git checkout master css/bootstrap-timepicker.min.css; git checkout master js/bootstrap-timepicker.min.js;'
},
deleteAssets: {
command: 'rm -rf css/bootstrap-timepicker.css; rm -rf css/bootstrap-timepicker.min.css; rm -rf js/bootstrap-timepicker.min.js;'
}
},
jasmine: {
build: {
src : ['spec/js/libs/jquery/jquery.min.js', 'spec/js/libs/bootstrap/js/bootstrap.min.js', 'spec/js/libs/autotype/index.js', 'js/bootstrap-timepicker.js'],
options: {
specs : 'spec/js/*Spec.js',
helpers : 'spec/js/helpers/*.js',
timeout : 100
}
}
},
jshint: {
options: {
browser: true,
camelcase: true,
curly: true,
eqeqeq: true,
eqnull: true,
immed: true,
indent: 2,
latedef: true,
newcap: true,
noarg: true,
quotmark: true,
sub: true,
strict: true,
trailing: true,
undef: true,
unused: true,
white: false,
globals: {
jQuery: true,
$: true,
expect: true,
it: true,
beforeEach: true,
afterEach: true,
describe: true,
loadFixtures: true,
console: true,
module: true
}
},
files: ['js/bootstrap-timepicker.js', 'Gruntfile.js', 'package.json', 'spec/js/*Spec.js']
},
less: {
development: {
options: {
paths: ['css']
},
files: {
'css/bootstrap-timepicker.css': 'less/*.less'
}
},
production: {
options: {
paths: ['css'],
yuicompress: true
},
files: {
'css/bootstrap-timepicker.min.css': ['less/*.less']
}
}
},
uglify: {
options: {
banner: '/*! <%= meta.project %> v<%= meta.version %> \n' +
'* http://jdewit.github.com/bootstrap-timepicker \n' +
'* Copyright (c) <%= grunt.template.today("yyyy") %> <NAME> \n' +
'* MIT License \n' +
'*/'
},
build: {
src: ['<banner:meta.banner>','js/<%= pkg.name %>.js'],
dest: 'js/<%= pkg.name %>.min.js'
}
}
});
grunt.registerTask('default', ['jasmine','jshint','uglify','less:production']);
grunt.registerTask('test', ['jasmine','lint']);
grunt.registerTask('copy', ['exec:copyAssets']);
};
| 0.996094 | 1 |
app/components/message_attachments/attachment_title.js | DigasNikas/mattermost-mobile | 1 | 2839 | // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import React, {PureComponent} from 'react';
import {Alert, Text, View} from 'react-native';
import {intlShape} from 'react-intl';
import PropTypes from 'prop-types';
import Markdown from '@components/markdown';
import {makeStyleSheetFromTheme} from '@utils/theme';
import {tryOpenURL} from '@utils/url';
export default class AttachmentTitle extends PureComponent {
static propTypes = {
link: PropTypes.string,
theme: PropTypes.object.isRequired,
value: PropTypes.string,
};
static contextTypes = {
intl: intlShape.isRequired,
};
openLink = () => {
const {link} = this.props;
const {intl} = this.context;
if (link) {
const onError = () => {
Alert.alert(
intl.formatMessage({
id: 'mobile.link.error.title',
defaultMessage: 'Error',
}),
intl.formatMessage({
id: 'mobile.link.error.text',
defaultMessage: 'Unable to open the link.',
}),
);
};
tryOpenURL(link, onError);
}
};
render() {
const {
link,
value,
theme,
} = this.props;
if (!value) {
return null;
}
const style = getStyleSheet(theme);
let title;
if (link) {
title = (
<Text
style={[style.title, Boolean(link) && style.link]}
onPress={this.openLink}
>
{value}
</Text>
);
} else {
title = (
<Markdown
isEdited={false}
isReplyPost={false}
disableHashtags={true}
disableAtMentions={true}
disableChannelLink={true}
disableGallery={true}
autolinkedUrlSchemes={[]}
mentionKeys={[]}
theme={theme}
value={value}
baseTextStyle={style.title}
textStyles={{link: style.link}}
/>
);
}
return (
<View style={style.container}>
{title}
</View>
);
}
}
const getStyleSheet = makeStyleSheetFromTheme((theme) => {
return {
container: {
marginTop: 3,
flex: 1,
flexDirection: 'row',
},
title: {
color: theme.centerChannelColor,
fontWeight: '600',
marginBottom: 5,
fontSize: 14,
lineHeight: 20,
},
link: {
color: theme.linkColor,
},
};
});
| 1.625 | 2 |
src/components/Profile/Challenges/index.js | arslansajid/rank-page | 0 | 2847 | import React, {useState, useEffect} from "react";
import { Typography, Grid } from "@material-ui/core";
import { makeStyles } from '@material-ui/core/styles';
import PostCard from "../../PostCard";
import { connect } from "react-redux";
import LoadingSpinner from "../../Common/LoadingSpinner"
import {getChallenges} from "./actions"
const Challenges = (props) => {
const classes = useStyles();
const [challenges, setChallenges] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const { user, userId } = props;
useEffect(() => {
if(!!userId) {
getChallenges({ 'user_id': userId })
.then((res) => {
console.log('res', res)
setChallenges(res.data.data.users_own_challenges)
setIsLoading(false);
})
.catch((err) => {
console.log('err', err);
setIsLoading(false);
})
} else if (!!user) {
getChallenges({ 'user_id': user.id })
.then((res) => {
console.log('res', res)
setChallenges(res.data.data.users_own_challenges)
setIsLoading(false);
})
.catch((err) => {
console.log('err', err);
setIsLoading(false);
})
}
}, [user])
return (
<>
{
isLoading && (
<LoadingSpinner
loading={isLoading}
text="Fetching Challenges..."
size="large"
/>
)
}
{challenges.length
?
challenges.map((challenge, index) => {
return (
<Grid key={index}>
<PostCard post={challenge} />
</Grid>
)
})
:
"No Pools Present"
}
</>
)
}
const useStyles = makeStyles((theme) => ({
moreText: {
margin: theme.spacing(6, 0, 6, 0),
textAlign: 'center'
}
})
)
function mapStateToProps(state) {
return {
user: state.user,
};
}
export default connect(mapStateToProps)(Challenges);
| 1.734375 | 2 |
src/reducers/BusinessOwnerReducer.js | StampsCard/stamps-card-app | 0 | 2855 | import {
MY_CUSTOMERS_FETCH_SUCCESS,
LAST_PURCHASES_FETCH_SUCCESS,
BUSINESS_STAMPS_CARDS_FETCH_SUCCESS,
STAMP_PRICE_CHANGED,
TOTAL_STAMPS_CHANGED,
DISCOUNT_CHANGED,
STAMPS_CARD_CREATION_FAIL,
STAMPS_CARD_CREATION_SUCCESS,
STAMPS_CARD_CREATION_STARTS
} from '../actions/types';
const INITIAL_STATE = {
error: '',
loading: false,
stampsCard: null,
stampPrice: '',
totalStamps: '',
discount: '',
showToast: false
};
export default(state = INITIAL_STATE, action) => {
switch (action.type) {
case MY_CUSTOMERS_FETCH_SUCCESS:
return { myCustomers: action.payload.myCustomers };
case LAST_PURCHASES_FETCH_SUCCESS:
return { lastPurchases: action.payload.lastPurchases };
case BUSINESS_STAMPS_CARDS_FETCH_SUCCESS:
return { stampsCards: action.payload.stampsCards };
case STAMP_PRICE_CHANGED:
return {
...state,
loading: true,
error: '',
showToast: false,
stampPrice: action.payload
};
case TOTAL_STAMPS_CHANGED:
return {
...state,
loading: true,
error: '',
showToast: false,
totalStamps: action.payload
};
case DISCOUNT_CHANGED:
return {
...state,
loading: true,
error: '',
showToast: false,
discount: action.payload
};
case STAMPS_CARD_CREATION_STARTS:
return {
...state,
loading: true,
error: '',
showToast: false
};
case STAMPS_CARD_CREATION_FAIL:
return {
...state,
error: 'The stamps card could not be created.',
loading: false,
showToast: true
};
case STAMPS_CARD_CREATION_SUCCESS:
return {
...state,
stampsCard: action.payload,
loading: false,
error: '',
showToast: false
};
default:
return state;
}
};
| 1.242188 | 1 |
src/angular-zxcvbn.js | GabLeRoux/angular-zxcvbn | 52 | 2863 | (function () {
'use strict';
angular.module('zxcvbn', [])
.directive('zxcvbn', function () {
return {
scope: {
password: '=',
extras: '=?',
data: '=?'
},
restrict: 'E',
template: '{{ display.crack_times_display }}',
link: function (scope, element, attrs) {
scope.$watch('password', function (newVal) {
if (angular.isString(newVal)) {
if (scope.extras)
scope.timeToCrack = zxcvbn(newVal, scope.extras);
else
scope.timeToCrack = zxcvbn(newVal);
if (('data' in attrs) && scope.timeToCrack)
scope.data = angular.copy(scope.timeToCrack);
scope.display = angular.copy(scope.timeToCrack);
}
});
}
};
});
})();
| 0.835938 | 1 |
controllers/admin/uploadRepositoryBuild.js | aytch/stampede-server | 0 | 2871 | const yaml = require("js-yaml");
/**
* path this handler will serve
*/
function path() {
return "/admin/uploadRepositoryBuild";
}
/**
* http method this handler will serve
*/
function method() {
return "post";
}
/**
* if the route requires admin
*/
function requiresAdmin() {
return true;
}
/**
* handle index
* @param {*} req
* @param {*} res
* @param {*} dependencies
*/
async function handle(req, res, dependencies) {
const owner = req.body.owner;
const repository = req.body.repository;
let repositoryAdminURL =
"/admin/repositoryAdmin?owner=" + owner + "&repository=" + repository;
if (req.files != null) {
const uploadData = req.files.uploadFile;
try {
const buildInfo = yaml.safeLoad(uploadData.data);
if (buildInfo != null) {
await dependencies.cache.repositoryBuilds.updateRepositoryBuild(
owner,
repository,
buildInfo
);
}
} catch (e) {
repositoryAdminURL += "&uploadError=Invalid build file";
}
}
res.writeHead(301, {
Location: repositoryAdminURL,
});
res.end();
}
module.exports.path = path;
module.exports.method = method;
module.exports.requiresAdmin = requiresAdmin;
module.exports.handle = handle;
| 1.414063 | 1 |
packages/scalable-form-editor/src/popover/baseConfig/index.js | baiheinet/scalable-form-platform | 121 | 2879 | /**
* 表单基本信息浮层(目前是标题和描述)
* @props: visible(popover是否显示) formData(当前的配置数据) formDataChangeHandler(数据变换处理回调方法) visibleChangeHandler(popover的onVisibleChange处理器)
*/
import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {Popover} from 'antd';
import XForm from 'scalable-form-antd';
import './index.less';
import {getMessageId} from '../../i18n/localeMessages';
export default class BaseFormConfigPopover extends PureComponent {
static propTypes = {
messages: PropTypes.object.isRequired,
popupContainer: PropTypes.func.isRequired,
children: PropTypes.element.isRequired,
visible: PropTypes.bool.isRequired,
formData: PropTypes.shape({
formTitle: PropTypes.string,
formDesc: PropTypes.string
}).isRequired,
formDataChangeHandler: PropTypes.func.isRequired,
visibleChangeHandler: PropTypes.func.isRequired
};
constructor(props) {
super(props);
this.renderPopoverContent = this.renderPopoverContent.bind(this);
}
renderPopoverContent() {
const {messages, formData, formDataChangeHandler} = this.props;
return (
<div className="base-config-wrapper">
<p className="popover-title">{messages[getMessageId('xformBaseConfigPopoverTitle')]}</p>
<XForm
formItemLayout={{
labelCol: {span: 3},
wrapperCol: {span: 21}
}}
alignType="vertical"
onChange={(formData) => {
formDataChangeHandler(formData);
}}
jsonSchema={{
type: 'object',
title: '',
properties: {
formTitle: {
title: messages[getMessageId('xformBaseConfigFormTitleLabel')],
type: 'string',
maxLength: 20
},
formDesc: {
title: messages[getMessageId('xformBaseConfigFormDescLabel')],
type: 'string',
maxLength: 200
}
}
}}
uiSchema={{
formTitle: {
'ui:options': {
placeholder: messages[getMessageId('xformBaseConfigFormTitlePlaceholder')]
}
},
formDesc: {
'ui:widget': 'textarea',
'ui:options': {
placeholder: messages[getMessageId('xformBaseConfigFormDescPlaceholder')]
}
}
}}
formData={{...formData}}
/>
</div>
);
}
render() {
const {children, visible, visibleChangeHandler, popupContainer} = this.props;
return (
<Popover
title=""
content={this.renderPopoverContent()}
visible={visible}
onVisibleChange={visibleChangeHandler}
trigger="click"
placement="bottomLeft"
overlayClassName="app-xform-builder-base-config-popover"
getPopupContainer={popupContainer}
>
{children}
</Popover>
);
}
}
| 1.453125 | 1 |
node_modules/@react-stately/numberfield/dist/module.js | SlipFil/DeleteBG | 0 | 2887 | import {useControlledState as $vhjCi$useControlledState, clamp as $vhjCi$clamp, snapValueToStep as $vhjCi$snapValueToStep} from "@react-stately/utils";
import {NumberFormatter as $vhjCi$NumberFormatter, NumberParser as $vhjCi$NumberParser} from "@internationalized/number";
import {useState as $vhjCi$useState, useMemo as $vhjCi$useMemo, useCallback as $vhjCi$useCallback, useRef as $vhjCi$useRef} from "react";
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
var $de67e98908f0c6ee$exports = {};
$parcel$export($de67e98908f0c6ee$exports, "useNumberFieldState", () => $de67e98908f0c6ee$export$7f629e9dc1ecf37c);
function $de67e98908f0c6ee$export$7f629e9dc1ecf37c(props) {
let { minValue: minValue , maxValue: maxValue , step: step , formatOptions: formatOptions , value: value1 , defaultValue: defaultValue , onChange: onChange , locale: locale , isDisabled: isDisabled , isReadOnly: isReadOnly } = props;
let [numberValue, setNumberValue] = $vhjCi$useControlledState(value1, isNaN(defaultValue) ? NaN : defaultValue, onChange);
let [inputValue, setInputValue] = $vhjCi$useState(()=>isNaN(numberValue) ? '' : new $vhjCi$NumberFormatter(locale, formatOptions).format(numberValue)
);
let numberParser = $vhjCi$useMemo(()=>new $vhjCi$NumberParser(locale, formatOptions)
, [
locale,
formatOptions
]);
let numberingSystem = $vhjCi$useMemo(()=>numberParser.getNumberingSystem(inputValue)
, [
numberParser,
inputValue
]);
let formatter = $vhjCi$useMemo(()=>new $vhjCi$NumberFormatter(locale, {
...formatOptions,
numberingSystem: numberingSystem
})
, [
locale,
formatOptions,
numberingSystem
]);
let intlOptions = $vhjCi$useMemo(()=>formatter.resolvedOptions()
, [
formatter
]);
let format = $vhjCi$useCallback((value)=>isNaN(value) ? '' : formatter.format(value)
, [
formatter
]);
let clampStep = !isNaN(step) ? step : 1;
if (intlOptions.style === 'percent' && isNaN(step)) clampStep = 0.01;
// Update the input value when the number value or format options change. This is done
// in a useEffect so that the controlled behavior is correct and we only update the
// textfield after prop changes.
let prevValue = $vhjCi$useRef(numberValue);
let prevLocale = $vhjCi$useRef(locale);
let prevFormatOptions = $vhjCi$useRef(formatOptions);
if (!Object.is(numberValue, prevValue.current) || locale !== prevLocale.current || formatOptions !== prevFormatOptions.current) {
setInputValue(format(numberValue));
prevValue.current = numberValue;
prevLocale.current = locale;
prevFormatOptions.current = formatOptions;
}
// Store last parsed value in a ref so it can be used by increment/decrement below
let parsedValue = $vhjCi$useMemo(()=>numberParser.parse(inputValue)
, [
numberParser,
inputValue
]);
let parsed = $vhjCi$useRef(0);
parsed.current = parsedValue;
let commit = ()=>{
// Set to empty state if input value is empty
if (!inputValue.length) {
setNumberValue(NaN);
setInputValue(value1 === undefined ? '' : format(numberValue));
return;
}
// if it failed to parse, then reset input to formatted version of current number
if (isNaN(parsed.current)) {
setInputValue(format(numberValue));
return;
}
// Clamp to min and max, round to the nearest step, and round to specified number of digits
let clampedValue;
if (isNaN(step)) clampedValue = $vhjCi$clamp(parsed.current, minValue, maxValue);
else clampedValue = $vhjCi$snapValueToStep(parsed.current, minValue, maxValue, step);
clampedValue = numberParser.parse(format(clampedValue));
setNumberValue(clampedValue);
// in a controlled state, the numberValue won't change, so we won't go back to our old input without help
setInputValue(format(value1 === undefined ? clampedValue : numberValue));
};
let safeNextStep = (operation, minMax)=>{
let prev = parsed.current;
if (isNaN(prev)) {
// if the input is empty, start from the min/max value when incrementing/decrementing,
// or zero if there is no min/max value defined.
let newValue = isNaN(minMax) ? 0 : minMax;
return $vhjCi$snapValueToStep(newValue, minValue, maxValue, clampStep);
} else {
// otherwise, first snap the current value to the nearest step. if it moves in the direction
// we're going, use that value, otherwise add the step and snap that value.
let newValue = $vhjCi$snapValueToStep(prev, minValue, maxValue, clampStep);
if (operation === '+' && newValue > prev || operation === '-' && newValue < prev) return newValue;
return $vhjCi$snapValueToStep($de67e98908f0c6ee$var$handleDecimalOperation(operation, prev, clampStep), minValue, maxValue, clampStep);
}
};
let increment = ()=>{
let newValue = safeNextStep('+', minValue);
// if we've arrived at the same value that was previously in the state, the
// input value should be updated to match
// ex type 4, press increment, highlight the number in the input, type 4 again, press increment
// you'd be at 5, then incrementing to 5 again, so no re-render would happen and 4 would be left in the input
if (newValue === numberValue) setInputValue(format(newValue));
setNumberValue(newValue);
};
let decrement = ()=>{
let newValue = safeNextStep('-', maxValue);
if (newValue === numberValue) setInputValue(format(newValue));
setNumberValue(newValue);
};
let incrementToMax = ()=>{
if (maxValue != null) setNumberValue($vhjCi$snapValueToStep(maxValue, minValue, maxValue, clampStep));
};
let decrementToMin = ()=>{
if (minValue != null) setNumberValue(minValue);
};
let canIncrement = $vhjCi$useMemo(()=>!isDisabled && !isReadOnly && (isNaN(parsedValue) || isNaN(maxValue) || $vhjCi$snapValueToStep(parsedValue, minValue, maxValue, clampStep) > parsedValue || $de67e98908f0c6ee$var$handleDecimalOperation('+', parsedValue, clampStep) <= maxValue)
, [
isDisabled,
isReadOnly,
minValue,
maxValue,
clampStep,
parsedValue
]);
let canDecrement = $vhjCi$useMemo(()=>!isDisabled && !isReadOnly && (isNaN(parsedValue) || isNaN(minValue) || $vhjCi$snapValueToStep(parsedValue, minValue, maxValue, clampStep) < parsedValue || $de67e98908f0c6ee$var$handleDecimalOperation('-', parsedValue, clampStep) >= minValue)
, [
isDisabled,
isReadOnly,
minValue,
maxValue,
clampStep,
parsedValue
]);
let validate = (value)=>numberParser.isValidPartialNumber(value, minValue, maxValue)
;
return {
validate: validate,
increment: increment,
incrementToMax: incrementToMax,
decrement: decrement,
decrementToMin: decrementToMin,
canIncrement: canIncrement,
canDecrement: canDecrement,
minValue: minValue,
maxValue: maxValue,
numberValue: parsedValue,
setInputValue: setInputValue,
inputValue: inputValue,
commit: commit
};
}
function $de67e98908f0c6ee$var$handleDecimalOperation(operator, value1, value2) {
let result = operator === '+' ? value1 + value2 : value1 - value2;
// Check if we have decimals
if (value1 % 1 !== 0 || value2 % 1 !== 0) {
const value1Decimal = value1.toString().split('.');
const value2Decimal = value2.toString().split('.');
const value1DecimalLength = value1Decimal[1] && value1Decimal[1].length || 0;
const value2DecimalLength = value2Decimal[1] && value2Decimal[1].length || 0;
const multiplier = Math.pow(10, Math.max(value1DecimalLength, value2DecimalLength));
// Transform the decimals to integers based on the precision
value1 = Math.round(value1 * multiplier);
value2 = Math.round(value2 * multiplier);
// Perform the operation on integers values to make sure we don't get a fancy decimal value
result = operator === '+' ? value1 + value2 : value1 - value2;
// Transform the integer result back to decimal
result /= multiplier;
}
return result;
}
export {$de67e98908f0c6ee$export$7f629e9dc1ecf37c as useNumberFieldState};
//# sourceMappingURL=module.js.map
| 1.5 | 2 |
public/assets/js/main.js | pkbox/webserver | 0 | 2895 | /*
Snapshot by TEMPLATED
templated.co @templatedco
Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
*/
(function($) {
skel.breakpoints({
xlarge: '(max-width: 1680px)',
large: '(max-width: 1280px)',
medium: '(max-width: 980px)',
small: '(max-width: 736px)',
xsmall: '(max-width: 480px)'
});
$(function() {
var $window = $(window),
$body = $('body');
// Disable animations/transitions until the page has loaded.
$body.addClass('is-loading');
$window.on('load', function() {
window.setTimeout(function() {
$body.removeClass('is-loading');
}, 100);
});
// Fix: Placeholder polyfill.
$('form').placeholder();
// Prioritize "important" elements on medium.
skel.on('+medium -medium', function() {
$.prioritize(
'.important\\28 medium\\29',
skel.breakpoint('medium').active
);
});
// Scrolly.
$('.scrolly').scrolly();
// Gallery.
$('.gallery').each(function() {
var $gallery = $(this),
$content = $gallery.find('.content');
// // Poptrox.
// $content.poptrox({
// usePopupCaption: true
// });
// Tabs.
$gallery.each( function() {
var $this = $(this),
$tabs = $this.find('.tabs a'),
$media = $this.find('.media');
$tabs.on('click', function(e) {
var $this = $(this),
tag = $this.data('tag');
// Prevent default.
e.preventDefault();
// Remove active class from all tabs.
$tabs.removeClass('active');
// Reapply active class to current tab.
$this.addClass('active');
// Hide media that do not have the same class as the clicked tab.
$media
.fadeOut('fast')
.each(function() {
var $this = $(this);
if ($this.hasClass(tag))
$this
.fadeOut('fast')
.delay(200)
.queue(function(next) {
$this.fadeIn();
next();
});
});
});
});
});
});
})(jQuery);
| 1.085938 | 1 |
webpack.dev.js | TrueMoein/TruePlayer | 1 | 2903 | const { merge } = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const common = require('./webpack.common.js');
module.exports = merge(common, {
entry: {
playground: './playground/app.ts',
},
plugins: [
new HtmlWebpackPlugin({
title: 'TruePlayer...',
template: './playground/index.html',
favicon: './playground/favicon.png',
}),
],
devtool: 'inline-source-map',
});
| 0.828125 | 1 |
test/dir_test.js | realglobe-Inc/the-templates | 0 | 2911 | /**
* Test case for dir.
* Runs with mocha.
*/
'use strict'
const dir = require('../lib/dir.js')
const assert = require('assert')
const coz = require('coz')
describe('dir', function () {
this.timeout(3000)
before(async () => {
})
after(async () => {
})
it('Dir', async () => {
const bud = dir({
dirname: __dirname,
name: 'foo',
description: 'hoge',
default: 'dddd'
})
bud.path = `${__dirname}/../tmp/testing-dir/index.mjs`
bud.mkdirp = true
await coz.render(bud)
})
it('CJS', async () => {
const bud = dir({
dirname: __dirname,
name: 'foo',
description: 'hoge',
default: 'dir_test',
cjs: true
})
bud.path = `${__dirname}/../tmp/testing-dir/index.js`
bud.mkdirp = true
await coz.render(bud)
})
})
/* global describe, before, after, it */
| 1.375 | 1 |
src/localization/tr/index.js | Didr/regexlearn.com | 0 | 2919 | import general from "./general.json";
import landing from "./landing.json";
import cheatsheet from "./cheatsheet.json";
import learn from "./learn.json";
const messages = {
...general,
...landing,
...cheatsheet,
...learn
}
export default messages; | 0.296875 | 0 |
lib/rest/api/V2010.js | akreddy403/twilio-node | 4 | 2927 | 'use strict';
/* jshint ignore:start */
/**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
/* jshint ignore:end */
var _ = require('lodash'); /* jshint ignore:line */
var AccountContext = require('./v2010/account').AccountContext;
var AccountList = require('./v2010/account').AccountList;
var Version = require('../../base/Version'); /* jshint ignore:line */
/* jshint ignore:start */
/**
* Initialize the V2010 version of Api
*
* @property {Twilio.Api.V2010.AccountList} accounts - accounts resource
* @property {Twilio.Api.V2010.AccountContext} account - account resource
* @property {Twilio.Api.V2010.AccountContext.AddressList} addresses -
* addresses resource
* @property {Twilio.Api.V2010.AccountContext.ApplicationList} applications -
* applications resource
* @property {Twilio.Api.V2010.AccountContext.AuthorizedConnectAppList} authorizedConnectApps -
* authorizedConnectApps resource
* @property {Twilio.Api.V2010.AccountContext.AvailablePhoneNumberCountryList} availablePhoneNumbers -
* availablePhoneNumbers resource
* @property {Twilio.Api.V2010.AccountContext.BalanceList} balance -
* balance resource
* @property {Twilio.Api.V2010.AccountContext.CallList} calls - calls resource
* @property {Twilio.Api.V2010.AccountContext.ConferenceList} conferences -
* conferences resource
* @property {Twilio.Api.V2010.AccountContext.ConnectAppList} connectApps -
* connectApps resource
* @property {Twilio.Api.V2010.AccountContext.IncomingPhoneNumberList} incomingPhoneNumbers -
* incomingPhoneNumbers resource
* @property {Twilio.Api.V2010.AccountContext.KeyList} keys - keys resource
* @property {Twilio.Api.V2010.AccountContext.MessageList} messages -
* messages resource
* @property {Twilio.Api.V2010.AccountContext.NewKeyList} newKeys -
* newKeys resource
* @property {Twilio.Api.V2010.AccountContext.NewSigningKeyList} newSigningKeys -
* newSigningKeys resource
* @property {Twilio.Api.V2010.AccountContext.NotificationList} notifications -
* notifications resource
* @property {Twilio.Api.V2010.AccountContext.OutgoingCallerIdList} outgoingCallerIds -
* outgoingCallerIds resource
* @property {Twilio.Api.V2010.AccountContext.QueueList} queues - queues resource
* @property {Twilio.Api.V2010.AccountContext.RecordingList} recordings -
* recordings resource
* @property {Twilio.Api.V2010.AccountContext.SigningKeyList} signingKeys -
* signingKeys resource
* @property {Twilio.Api.V2010.AccountContext.SipList} sip - sip resource
* @property {Twilio.Api.V2010.AccountContext.ShortCodeList} shortCodes -
* shortCodes resource
* @property {Twilio.Api.V2010.AccountContext.TokenList} tokens - tokens resource
* @property {Twilio.Api.V2010.AccountContext.TranscriptionList} transcriptions -
* transcriptions resource
* @property {Twilio.Api.V2010.AccountContext.UsageList} usage - usage resource
* @property {Twilio.Api.V2010.AccountContext.ValidationRequestList} validationRequests -
* validationRequests resource
*
* @param {Twilio.Api} domain - The twilio domain
*/
/* jshint ignore:end */
function V2010(domain) {
Version.prototype.constructor.call(this, domain, '2010-04-01');
// Resources
this._accounts = undefined;
this._account = undefined;
}
_.extend(V2010.prototype, Version.prototype);
V2010.prototype.constructor = V2010;
Object.defineProperty(V2010.prototype,
'accounts', {
get: function() {
this._accounts = this._accounts || new AccountList(this);
return this._accounts;
}
});
Object.defineProperty(V2010.prototype,
'account', {
get: function() {
if (!this._account) {
this._account = new AccountContext(this, this._domain.twilio.accountSid);
}
return this._account;
},
set: function(accountContext) {
this._account = accountContext;
}
});
Object.defineProperty(V2010.prototype,
'addresses', {
get: function() {
return this.account.addresses;
}
});
Object.defineProperty(V2010.prototype,
'applications', {
get: function() {
return this.account.applications;
}
});
Object.defineProperty(V2010.prototype,
'authorizedConnectApps', {
get: function() {
return this.account.authorizedConnectApps;
}
});
Object.defineProperty(V2010.prototype,
'availablePhoneNumbers', {
get: function() {
return this.account.availablePhoneNumbers;
}
});
Object.defineProperty(V2010.prototype,
'balance', {
get: function() {
return this.account.balance;
}
});
Object.defineProperty(V2010.prototype,
'calls', {
get: function() {
return this.account.calls;
}
});
Object.defineProperty(V2010.prototype,
'conferences', {
get: function() {
return this.account.conferences;
}
});
Object.defineProperty(V2010.prototype,
'connectApps', {
get: function() {
return this.account.connectApps;
}
});
Object.defineProperty(V2010.prototype,
'incomingPhoneNumbers', {
get: function() {
return this.account.incomingPhoneNumbers;
}
});
Object.defineProperty(V2010.prototype,
'keys', {
get: function() {
return this.account.keys;
}
});
Object.defineProperty(V2010.prototype,
'messages', {
get: function() {
return this.account.messages;
}
});
Object.defineProperty(V2010.prototype,
'newKeys', {
get: function() {
return this.account.newKeys;
}
});
Object.defineProperty(V2010.prototype,
'newSigningKeys', {
get: function() {
return this.account.newSigningKeys;
}
});
Object.defineProperty(V2010.prototype,
'notifications', {
get: function() {
return this.account.notifications;
}
});
Object.defineProperty(V2010.prototype,
'outgoingCallerIds', {
get: function() {
return this.account.outgoingCallerIds;
}
});
Object.defineProperty(V2010.prototype,
'queues', {
get: function() {
return this.account.queues;
}
});
Object.defineProperty(V2010.prototype,
'recordings', {
get: function() {
return this.account.recordings;
}
});
Object.defineProperty(V2010.prototype,
'signingKeys', {
get: function() {
return this.account.signingKeys;
}
});
Object.defineProperty(V2010.prototype,
'sip', {
get: function() {
return this.account.sip;
}
});
Object.defineProperty(V2010.prototype,
'shortCodes', {
get: function() {
return this.account.shortCodes;
}
});
Object.defineProperty(V2010.prototype,
'tokens', {
get: function() {
return this.account.tokens;
}
});
Object.defineProperty(V2010.prototype,
'transcriptions', {
get: function() {
return this.account.transcriptions;
}
});
Object.defineProperty(V2010.prototype,
'usage', {
get: function() {
return this.account.usage;
}
});
Object.defineProperty(V2010.prototype,
'validationRequests', {
get: function() {
return this.account.validationRequests;
}
});
module.exports = V2010;
| 1 | 1 |
KRD_MZ_ItemSort.js | kuroudo119/RPGMZ_Plugin | 0 | 2935 | /*:
* @target MZ
* @plugindesc アイテム・スキル一覧ソート
* @url https://twitter.com/kuroudo119/
* @url https://github.com/kuroudo119/RPGMZ-Plugin
* @author kuroudo119 (くろうど)
*
* @help
# KRD_MZ_ItemSort.js
アイテム・スキル一覧ソート
## 権利表記
(c) 2021 kuroudo119 (くろうど)
## 利用規約
このプラグインはMITライセンスです。
https://github.com/kuroudo119/RPGMZ-Plugin/blob/master/LICENSE
## 仕様
### アイテム・スキルの並び順
使用可能時、ダメージタイプ、範囲の順。
### 武器の並び順
武器タイプ順。
### 防具の並び順
装備タイプ、防具タイプの順。
## 更新履歴
- ver.0.0.1 (2021/02/23) 非公開版完成
- ver.0.1.0 (2022/03/08) 武器防具タイプソートに変更
- ver.0.2.0 (2022/03/10) 範囲・使用可能時でのソートに変更
- ver.1.0.0 (2022/03/17) 公開
*
*
*/
(() => {
"use strict";
//--------------------------------------
// アイテムリストのソート
const KRD_Window_ItemList_makeItemList = Window_ItemList.prototype.makeItemList;
Window_ItemList.prototype.makeItemList = function() {
KRD_Window_ItemList_makeItemList.apply(this, arguments);
if (this._data && this._data.length > 0) {
if (DataManager.isItem(this._data[0])) {
this._data.sort(compareItems);
} else if (DataManager.isWeapon(this._data[0])) {
this._data.sort(compareWeapons);
} else if (DataManager.isArmor(this._data[0])) {
this._data.sort(compareArmors);
}
}
};
const compareItems = function(a, b) {
if (!a || !b) {
return 0;
}
if (a.occasion === b.occasion) {
if (a.damage.type === b.damage.type) {
return forSortScope(a.scope) - forSortScope(b.scope);
} else {
return forSortDamageType(a.damage.type) - forSortDamageType(b.damage.type);
}
} else {
return forSortOccasion(a.occasion) - forSortOccasion(b.occasion);
}
};
const forSortOccasion = function(base) {
return base === 1 || base === 3 ? base + 100 : base;
}
const forSortScope = function(base) {
const isForOpponent = [1, 2, 3, 4, 5, 6, 14];
const isForFriend = [7, 8, 9, 10, 11, 12, 13, 14];
if (isForFriend.includes(base)) {
return base;
} else if (isForOpponent.includes(base)) {
return base + 100;
}
return base;
}
const forSortDamageType = function(base) {
return base === 3 || base === 4 ? base : base + 100;
};
const compareWeapons = function(a, b) {
if (!a || !b) {
return 0;
}
return a.wtypeId - b.wtypeId;
};
const compareArmors = function(a, b) {
if (!a || !b) {
return 0;
}
if (a.etypeId === b.etypeId) {
return a.atypeId - b.atypeId;
} else {
return a.etypeId - b.etypeId;
}
};
//--------------------------------------
// スキルリストのソート
const KRD_Window_SkillList_makeItemList = Window_SkillList.prototype.makeItemList;
Window_SkillList.prototype.makeItemList = function() {
KRD_Window_SkillList_makeItemList.apply(this, arguments);
if (this._data && this._data.length > 0) {
this._data.sort(compareSkills);
}
};
const compareSkills = function(a, b) {
return compareItems(a, b);
};
//--------------------------------------
})();
| 1.507813 | 2 |
doc/html/search/functions_4.js | servodevelop/uart-servo-lib-arduino | 0 | 2943 | var searchData=
[
['spin',['spin',['../class_u_a_r_t_servo.html#a26bde11d848366a45a6b8adfe846ef6a',1,'UARTServo']]],
['stop',['stop',['../class_u_a_r_t_servo.html#aad804d5e1994fffd3ed07d8f579d7289',1,'UARTServo']]]
];
| 0.029053 | 0 |
bin/help.js | ntindall/npm-shrinkwrap | 1 | 2951 | var path = require('path');
var fs = require('graceful-fs');
var msee = require('msee');
var template = require('string-template');
function printHelp(opts) {
opts = opts || {};
var loc = path.join(__dirname, 'usage.md');
var content = fs.readFileSync(loc, 'utf8');
content = template(content, {
cmd: opts.cmd || 'npm-shrinkwrap'
});
if (opts.h) {
content = content.split('##')[0];
}
var text = msee.parse(content, {
paragraphStart: '\n'
});
return console.log(text);
}
module.exports = printHelp;
| 1.164063 | 1 |
tests/charts/updateChart.test.js | seatsio/seatsio-js | 10 | 2959 | const testUtils = require('../testUtils.js')
test('should update chart name', async () => {
const { client, user } = await testUtils.createTestUserAndClient()
const categories = [{ key: 1, label: 'Category 1', color: '#aaaaaa', accessible: false }]
const chart = await client.charts.create(null, null, categories)
await client.charts.update(chart.key, 'aChart')
const retrievedChart = await client.charts.retrievePublishedVersion(chart.key)
expect(retrievedChart.name).toBe('aChart')
expect(retrievedChart.categories.list).toEqual(categories)
})
test('should update chart categories', async () => {
const { client, user } = await testUtils.createTestUserAndClient()
const chart = await client.charts.create('aChart')
const categories = [{ key: 1, label: 'Category 1', color: '#aaaaaa', accessible: false }, { key: 2, label: 'Category 2', color: '#bbbbbb', accessible: true }]
await client.charts.update(chart.key, null, categories)
const retrievedChart = await client.charts.retrievePublishedVersion(chart.key)
expect(retrievedChart.name).toBe('aChart')
expect(retrievedChart.categories.list).toEqual(categories)
})
| 1.40625 | 1 |
config/routes.js | aleksandar9999a/cubicle | 0 | 2967 | const mainCotroller = require('./../controllers/main.controller');
const authCotroller = require('./../controllers/auth');
const { auth } = require('./../utils');
module.exports = (app) => {
app.post('/create/accessory', auth(), mainCotroller.postAccessories);
app.get('/create/accessory', auth(), mainCotroller.getAccessories);
app.post('/attach/accessory/:id', auth(), mainCotroller.postAttachAccessory);
app.get('/attach/accessory/:id', auth(), mainCotroller.getAttachAccessory);
app.get('/details/:id', auth(false), mainCotroller.details);
app.post('/create', auth(), mainCotroller.postCreate);
app.get('/create', auth(), mainCotroller.getCreate);
app.post('/edit/:id', auth(), mainCotroller.postEdit);
app.get('/edit/:id', auth(), mainCotroller.getEdit);
app.post('/delete/:id', auth(), mainCotroller.postDelete);
app.get('/delete/:id', auth(), mainCotroller.getDelete);
app.get('/about', auth(false), mainCotroller.about);
app.post('/login', auth(false), authCotroller.postLogin);
app.get('/login', auth(false), authCotroller.getLogin);
app.post('/register', auth(false), authCotroller.postRegister);
app.get('/register', auth(false), authCotroller.getRegister);
app.get('/logout', authCotroller.logout);
app.get('/404', auth(false), mainCotroller.notFound);
app.post('/', auth(false), mainCotroller.postIndex);
app.get('/', auth(false), mainCotroller.getIndex);
}; | 1.070313 | 1 |
lib/actions/SuccessActionCreators.js | vasanthk2/Mortar-JS | 17 | 2975 | var AppDispatcher = require('../dispatcher/AppDispatcher');
var AppActionConstants = require('../constants/AppActionConstants');
var ActionTypes = AppActionConstants.ActionTypes.alerts;
module.exports = {
success: function (status, message) {
AppDispatcher.dispatch({
type : ActionTypes.ALERT_SUCCESS,
message : message,
actionOrError : status
});
}
};
| 1.015625 | 1 |
src/utils/rgbToHsl.js | emresandikci/esducad-ui | 0 | 2983 | import hexToRgba from './hexToRgba';
const rgbToHsl = (hex, lightness) => {
const c255 = 255;
let min,
max,
i,
l,
s,
maxcolor,
h,
rgb = [];
let color;
let { r, g, b } = hexToRgba(hex);
rgb[0] = r / c255;
rgb[1] = g / c255;
rgb[2] = b / c255;
min = rgb[0];
max = rgb[0];
maxcolor = 0;
for (i = 0; i < rgb.length - 1; i++) {
if (rgb[i + 1] <= min) {
min = rgb[i + 1];
}
if (rgb[i + 1] >= max) {
max = rgb[i + 1];
maxcolor = i + 1;
}
}
if (maxcolor == 0) {
h = (rgb[1] - rgb[2]) / (max - min);
}
if (maxcolor == 1) {
h = 2 + (rgb[2] - rgb[0]) / (max - min);
}
if (maxcolor == 2) {
h = 4 + (rgb[0] - rgb[1]) / (max - min);
}
if (isNaN(h)) {
h = 0;
}
h = h * 60;
if (h < 0) {
h = h + 360;
}
l = (min + max) / 2;
if (min == max) {
s = 0;
} else {
if (l < 0.5) {
s = (max - min) / (max + min);
} else {
s = (max - min) / (2 - max - min);
}
}
h = Number(h.toFixed(0));
s = Number(s.toFixed(2)) * 100;
l = Number(l.toFixed(2)) * 100;
if (lightness) l += lightness;
color = { h, s, l, all: `hsl(${h}, ${s}%, ${l}%)` };
return color;
};
export default rgbToHsl;
| 2.03125 | 2 |
codelab-final-state/functions/index.js | mgechev/emulators-codelab | 0 | 2991 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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.
const admin = require('firebase-admin');
const functions = require('firebase-functions');
const db = admin.initializeApp().firestore();
// Recalculates the total cost of a cart; triggered when there's a change
// to any items in a cart.
exports.calculateCart = functions
.firestore.document("carts/{cartId}/items/{itemId}")
.onWrite(async (change, context) => {
let totalPrice = 0;
let itemCount = 0;
try {
const cartRef = db.collection("carts").doc(context.params.cartId);
const itemsSnap = await cartRef.collection("items").get();
itemsSnap.docs.forEach(item => {
const itemData = item.data();
if (itemData.price) {
// If not specified, the quantity is 1
const quantity = (itemData.quantity) ? itemData.quantity : 1;
itemCount += quantity;
totalPrice += (itemData.price * quantity);
}
});
console.log("Cart total successfully recalculated: ", totalPrice);
return await cartRef.update({
totalPrice,
itemCount
});
} catch(err) {
if (itemCount === 0) {
return;
}
console.error("Cart could not be recalculated. ", err);
}
});
| 2.03125 | 2 |
app/screens/Send/index.js | Groestlcoin/shocknet-wallet | 0 | 2999 | /**
* @format
*/
import React, { Component } from 'react'
import {
// Clipboard,
StyleSheet,
Text,
View,
ScrollView,
ImageBackground,
Dimensions,
ActivityIndicator,
Image,
TouchableOpacity,
Switch,
} from 'react-native'
import Logger from 'react-native-file-log'
// @ts-ignore
import { Dropdown } from 'react-native-material-dropdown'
// @ts-ignore
import SwipeVerify from 'react-native-swipe-verify'
import Ionicons from 'react-native-vector-icons/Ionicons'
import { connect } from 'react-redux'
import Big from 'big.js'
import wavesBG from '../../assets/images/shock-bg.png'
import Nav from '../../components/Nav'
import InputGroup from '../../components/InputGroup'
import ContactsSearch from '../../components/Search/ContactsSearch'
import Suggestion from '../../components/Search/Suggestion'
import QRScanner from '../QRScanner'
import BitcoinAccepted from '../../assets/images/bitcoin-accepted.png'
import * as CSS from '../../res/css'
import * as Wallet from '../../services/wallet'
import * as API from '../../services/contact-api/index'
import { selectContact, resetSelectedContact } from '../../actions/ChatActions'
import {
resetInvoice,
decodePaymentRequest,
} from '../../actions/InvoiceActions'
import { WALLET_OVERVIEW } from '../WalletOverview'
export const SEND_SCREEN = 'SEND_SCREEN'
/**
* @typedef {import('react-navigation').NavigationScreenProp<{}, {}>} Navigation
*/
/**
* @typedef {import('../../actions/ChatActions').Contact | import('../../actions/ChatActions').BTCAddress} ContactTypes
*/
/**
* @typedef {({ type: 'error', error: Error }|undefined)} DecodeResponse
*/
/**
* @typedef {object} Props
* @prop {(Navigation)=} navigation
* @prop {import('../../../reducers/ChatReducer').State} chat
* @prop {import('../../../reducers/InvoiceReducer').State} invoice
* @prop {(contact: ContactTypes) => ContactTypes} selectContact
* @prop {() => void} resetSelectedContact
* @prop {() => void} resetInvoice
* @prop {(invoice: string) => Promise<DecodeResponse>} decodePaymentRequest
*/
/**
* @typedef {object} State
* @prop {string} description
* @prop {string} unitSelected
* @prop {string} amount
* @prop {string} contactsSearch
* @prop {boolean} sending
* @prop {boolean} paymentSuccessful
* @prop {boolean} scanningQR
* @prop {boolean} sendAll
* @prop {Error|null} error
*/
/**
* @augments React.Component<Props, State, never>
*/
class SendScreen extends Component {
state = {
description: '',
unitSelected: 'gros',
amount: '0',
contactsSearch: '',
paymentSuccessful: false,
scanningQR: false,
sending: false,
sendAll: false,
error: null,
}
amountOptionList = React.createRef()
componentDidMount() {
this.resetSearchState()
}
/**
* @param {keyof State} key
* @returns {(value: any) => void}
*/
onChange = key => value => {
/**
* @type {Pick<State, keyof State>}
*/
// @ts-ignore TODO: fix typing
const updatedState = {
[key]: value,
}
this.setState(updatedState)
}
isFilled = () => {
const { amount, sendAll } = this.state
const { paymentRequest } = this.props.invoice
const { selectedContact } = this.props.chat
return (
((selectedContact?.address?.length > 0 ||
selectedContact?.type === 'contact') &&
parseFloat(amount) > 0) ||
(selectedContact?.type === 'btc' && sendAll) ||
!!paymentRequest
)
}
sendBTCRequest = async () => {
try {
const { selectedContact } = this.props.chat
const { amount, sendAll } = this.state
if (!selectedContact.address) {
return
}
this.setState({
sending: true,
})
const transactionId = await Wallet.sendCoins({
addr: selectedContact.address,
amount: sendAll ? parseInt(amount, 10) : undefined,
send_all: sendAll,
})
Logger.log('New Transaction ID:', transactionId)
this.setState({
sending: false,
})
if (this.props.navigation) {
this.props.navigation.goBack()
}
} catch (e) {
Logger.log(e)
this.setState({
sending: false,
error: e.message,
})
}
}
payLightningInvoice = async () => {
try {
const { invoice, navigation } = this.props
const { amount } = this.state
this.setState({
sending: true,
})
await Wallet.CAUTION_payInvoice({
amt:
invoice.paymentRequest && invoice.amount && Big(invoice.amount).gt(0)
? undefined
: parseInt(amount, 10),
payreq: invoice.paymentRequest,
})
this.setState({
sending: false,
paymentSuccessful: true,
})
setTimeout(() => {
if (navigation) {
navigation.navigate(WALLET_OVERVIEW)
}
}, 500)
} catch (err) {
this.setState({
sending: false,
error: err,
})
}
}
sendPayment = async () => {
try {
const { chat } = this.props
const { amount, description } = this.state
const { selectedContact } = chat
await API.Actions.sendPayment(selectedContact.pk, amount, description)
return true
} catch (err) {
this.setState({
sending: false,
error: err,
})
return false
}
}
resetSearchState = () => {
const { resetSelectedContact, resetInvoice } = this.props
resetSelectedContact()
resetInvoice()
this.setState({
contactsSearch: '',
})
}
renderContactsSearch = () => {
const { chat, invoice } = this.props
const { contactsSearch } = this.state
if (invoice.paymentRequest) {
return (
<Suggestion
name={invoice.paymentRequest}
onPress={this.resetSearchState}
type="invoice"
style={styles.suggestion}
/>
)
}
if (!chat.selectedContact) {
return (
<ContactsSearch
onChange={this.onChange('contactsSearch')}
onError={this.onChange('error')}
enabledFeatures={['btc', 'invoice', 'contacts']}
placeholder="Enter invoice or address..."
value={contactsSearch}
style={styles.contactsSearch}
/>
)
}
if (chat.selectedContact.type === 'btc') {
return (
<Suggestion
name={chat.selectedContact.address}
onPress={this.resetSearchState}
type="btc"
style={styles.suggestion}
/>
)
}
return (
<Suggestion
name={chat.selectedContact.displayName}
avatar={chat.selectedContact.avatar}
onPress={this.resetSearchState}
style={styles.suggestion}
/>
)
}
getErrorMessage = () => {
const { error } = this.state
if (!error) {
return null
}
// @ts-ignore Typescript is being crazy here
if (error.message) {
// @ts-ignore
return error.message
}
return error
}
toggleQRScreen = () => {
const { scanningQR } = this.state
this.setState({
scanningQR: !scanningQR,
})
}
/**
* @param {string} address
*/
sanitizeAddress = address =>
address.replace(/(.*):/, '').replace(/\?(.*)/, '')
/**
* @param {string} value
*/
isBTCAddress = value => {
const sanitizedAddress = this.sanitizeAddress(value)
const btcTest = /^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$/.test(sanitizedAddress)
const bech32Test = /^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,90}$/.test(
sanitizedAddress,
)
return btcTest || bech32Test
}
/**
* @param {string} value
*/
isLightningInvoice = value =>
/^(ln(tb|bc))[0-9][a-z0-9]{180,7089}$/.test(value.toLowerCase())
/**
* @param {string} data
*/
sanitizeQR = data => data.replace(/((lightning:)|(http(s)?:\/\/))/gi, '')
onQRRead = async (data = '') => {
this.resetSearchState()
const { decodePaymentRequest, selectContact } = this.props
const sanitizedQR = this.sanitizeQR(data)
Logger.log('QR Value:', sanitizedQR)
Logger.log('Lightning Invoice?', this.isLightningInvoice(sanitizedQR))
Logger.log('GRS Address?', this.isBTCAddress(sanitizedQR))
this.onChange('error')('')
if (this.isLightningInvoice(sanitizedQR)) {
const data = await decodePaymentRequest(sanitizedQR)
if (data && data.type === 'error') {
this.onChange('error')(data.error.message)
}
} else if (this.isBTCAddress(sanitizedQR)) {
selectContact({ address: this.sanitizeAddress(sanitizedQR), type: 'btc' })
} else {
this.onChange('error')('Invalid QR Code')
}
this.toggleQRScreen()
}
onSwipe = async () => {
try {
const { invoice, chat } = this.props
if (chat.selectedContact?.type === 'contact') {
await this.sendPayment()
return true
}
if (invoice.paymentRequest) {
await this.payLightningInvoice()
return true
}
await this.sendBTCRequest()
return true
} catch (err) {
return false
}
}
render() {
const {
description,
unitSelected,
amount,
sending,
error,
paymentSuccessful,
scanningQR,
sendAll,
} = this.state
const { navigation, invoice, chat } = this.props
const { width, height } = Dimensions.get('window')
const editable =
!!(
invoice.paymentRequest &&
invoice.amount &&
Big(invoice.amount).eq(0)
) || !invoice.paymentRequest
if (scanningQR) {
return (
<View style={CSS.styles.flex}>
<QRScanner
onQRSuccess={this.onQRRead}
toggleQRScreen={this.toggleQRScreen}
type="send"
/>
</View>
)
}
return (
<ImageBackground
source={wavesBG}
resizeMode="cover"
style={styles.container}
>
<Nav backButton title="Send" navigation={navigation} />
<View
style={[
styles.sendContainer,
{
width: width - 50,
maxHeight: height - 200,
},
]}
>
<ScrollView>
<View style={styles.scrollInnerContent}>
{error ? (
<View style={styles.errorRow}>
<Text style={styles.errorText}>{this.getErrorMessage()}</Text>
</View>
) : null}
<TouchableOpacity
style={styles.scanBtn}
onPress={this.toggleQRScreen}
>
<Text style={styles.scanBtnText}>SCAN QR</Text>
<Ionicons name="md-qr-scanner" color="gray" size={24} />
</TouchableOpacity>
{this.renderContactsSearch()}
{invoice.paymentRequest ? (
<InputGroup
label="Destination"
value={invoice.recipientAddress}
style={styles.destinationInput}
inputStyle={styles.destinationInput}
disabled
/>
) : null}
<View style={styles.amountContainer}>
<InputGroup
label="Enter Amount"
value={!editable ? invoice.amount : amount}
onChange={this.onChange('amount')}
style={styles.amountInput}
disabled={!editable}
type="numeric"
/>
<Dropdown
data={[
{
value: 'gros',
},
{
value: 'GRS',
},
]}
disabled={!editable}
onChangeText={this.onChange('unitSelected')}
containerStyle={styles.amountSelect}
value={invoice.paymentRequest ? 'gros' : unitSelected}
lineWidth={0}
inputContainerStyle={styles.amountSelectInput}
rippleOpacity={0}
pickerStyle={styles.amountPicker}
dropdownOffset={{ top: 8, left: 0 }}
rippleInsets={{ top: 8, bottom: 0, right: 0, left: 0 }}
/>
</View>
{chat.selectedContact?.type === 'btc' ? (
<View style={styles.toggleContainer}>
<Text style={styles.toggleTitle}>Send All</Text>
<Switch
value={sendAll}
onValueChange={this.onChange('sendAll')}
/>
</View>
) : null}
<InputGroup
label="Description"
value={
invoice.paymentRequest ? invoice.description : description
}
multiline
onChange={this.onChange('description')}
inputStyle={styles.descInput}
disabled={!!invoice.paymentRequest}
/>
{sending ? (
<View
style={[
styles.sendingOverlay,
{
width: width - 50,
height: height - 194,
},
]}
>
<ActivityIndicator color={CSS.Colors.FUN_BLUE} size="large" />
<Text style={styles.sendingText}>Sending Transaction...</Text>
</View>
) : null}
{paymentSuccessful ? (
<View
style={[
styles.sendingOverlay,
{
width: width - 50,
height: height - 194,
},
]}
>
<Ionicons
name="md-checkmark-circle-outline"
size={60}
color={CSS.Colors.FUN_BLUE}
/>
<Text style={styles.sendingText}>
Transaction sent successfully!
</Text>
</View>
) : null}
</View>
</ScrollView>
</View>
<View style={styles.sendSwipeContainer}>
{this.isFilled() ? (
<SwipeVerify
width="100%"
buttonSize={60}
height={50}
style={styles.swipeBtn}
buttonColor={CSS.Colors.BACKGROUND_WHITE}
borderColor={CSS.Colors.TRANSPARENT}
backgroundColor={CSS.Colors.BACKGROUND_WHITE}
textColor="#37474F"
borderRadius={100}
swipeColor={CSS.Colors.GOLD}
icon={
<Image
source={BitcoinAccepted}
resizeMethod="resize"
resizeMode="contain"
style={styles.btcIcon}
/>
}
disabled={!this.isFilled()}
onVerified={this.onSwipe}
>
<Text style={styles.swipeBtnText}>SLIDE TO SEND</Text>
</SwipeVerify>
) : null}
</View>
</ImageBackground>
)
}
}
/** @param {{ invoice: import('../../../reducers/InvoiceReducer').State, chat: import('../../../reducers/ChatReducer').State }} state */
const mapStateToProps = ({ chat, invoice }) => ({ chat, invoice })
const mapDispatchToProps = {
selectContact,
resetSelectedContact,
resetInvoice,
decodePaymentRequest,
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(SendScreen)
const styles = StyleSheet.create({
container: {
height: 170,
flex: 1,
justifyContent: 'flex-start',
alignItems: 'center',
},
contactsSearch: { marginBottom: 20 },
sendContainer: {
marginTop: 5,
backgroundColor: CSS.Colors.BACKGROUND_WHITE,
height: 'auto',
borderRadius: 40,
overflow: 'hidden',
},
scrollInnerContent: {
height: '100%',
width: '100%',
paddingVertical: 23,
paddingHorizontal: 35,
paddingBottom: 0,
},
destinationInput: {
marginBottom: 10,
},
suggestion: { marginVertical: 10 },
sendingOverlay: {
position: 'absolute',
left: 0,
top: 0,
right: 0,
width: '100%',
height: '100%',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: CSS.Colors.BACKGROUND_WHITE_TRANSPARENT95,
elevation: 10,
zIndex: 1000,
},
sendingText: {
color: CSS.Colors.TEXT_GRAY,
fontSize: 14,
fontFamily: 'Montserrat-700',
marginTop: 10,
},
errorRow: {
width: '100%',
paddingVertical: 5,
paddingHorizontal: 15,
borderRadius: 100,
backgroundColor: CSS.Colors.BACKGROUND_RED,
alignItems: 'center',
marginBottom: 10,
},
errorText: {
fontFamily: 'Montserrat-700',
color: CSS.Colors.TEXT_WHITE,
textAlign: 'center',
},
scanBtn: {
width: '100%',
flexDirection: 'row',
backgroundColor: CSS.Colors.BACKGROUND_WHITE,
paddingVertical: 10,
alignItems: 'center',
justifyContent: 'center',
borderRadius: 30,
marginBottom: 30,
elevation: 10,
},
scanBtnText: {
color: CSS.Colors.GRAY,
fontSize: 14,
fontFamily: 'Montserrat-700',
marginRight: 10,
},
amountContainer: {
width: '100%',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-end',
marginBottom: 20,
},
amountInput: {
width: '60%',
marginBottom: 0,
},
amountSelect: {
width: '35%',
marginBottom: 0,
height: 45,
},
amountSelectInput: {
borderBottomColor: CSS.Colors.TRANSPARENT,
elevation: 4,
paddingHorizontal: 15,
borderRadius: 100,
height: 45,
alignItems: 'center',
backgroundColor: CSS.Colors.BACKGROUND_WHITE,
},
amountPicker: { borderRadius: 15 },
toggleContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
},
toggleTitle: {
fontFamily: 'Montserrat-700',
},
sendSwipeContainer: {
width: '100%',
height: 70,
paddingHorizontal: 35,
justifyContent: 'center',
marginTop: 10,
},
swipeBtn: {
marginBottom: 10,
},
btcIcon: {
height: 30,
},
swipeBtnText: {
fontSize: 12,
fontFamily: 'Montserrat-700',
color: CSS.Colors.TEXT_GRAY,
},
descInput: {
height: 90,
borderRadius: 15,
textAlignVertical: 'top',
},
})
| 1.265625 | 1 |
static/js/hotjar.js | LBHackney-IT/education-evidence-upload-tool | 2 | 3007 | (function(h, o, t, j, a, r) {
h.hj =
h.hj ||
function() {
(h.hj.q = h.hj.q || []).push(arguments);
};
h._hjSettings = { hjid: 1958227, hjsv: 6 };
a = o.getElementsByTagName('head')[0];
r = o.createElement('script');
r.async = 1;
r.src = t + h._hjSettings.hjid + j + h._hjSettings.hjsv;
a.appendChild(r);
})(window, document, 'https://static.hotjar.com/c/hotjar-', '.js?sv=');
| 0.597656 | 1 |
public/admin/vendors/Chart.js/src/scales/scale.logarithmic.js | shayzism/Laravel-VegStore | 18 | 3015 | "use strict";
module.exports = function(Chart) {
var helpers = Chart.helpers;
var defaultConfig = {
position: "left",
// label settings
ticks: {
callback: function(value, index, arr) {
var remain = value / (Math.pow(10, Math.floor(helpers.log10(value))));
if (remain === 1 || remain === 2 || remain === 5 || index === 0 || index === arr.length - 1) {
return value.toExponential();
} else {
return '';
}
}
}
};
var LogarithmicScale = Chart.Scale.extend({
determineDataLimits: function() {
var me = this;
var opts = me.options;
var tickOpts = opts.ticks;
var chart = me.chart;
var data = chart.data;
var datasets = data.datasets;
var getValueOrDefault = helpers.getValueOrDefault;
var isHorizontal = me.isHorizontal();
function IDMatches(meta) {
return isHorizontal ? meta.xAxisID === me.id : meta.yAxisID === me.id;
}
// Calculate Range
me.min = null;
me.max = null;
if (opts.stacked) {
var valuesPerType = {};
helpers.each(datasets, function(dataset, datasetIndex) {
var meta = chart.getDatasetMeta(datasetIndex);
if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
if (valuesPerType[meta.type] === undefined) {
valuesPerType[meta.type] = [];
}
helpers.each(dataset.data, function(rawValue, index) {
var values = valuesPerType[meta.type];
var value = +me.getRightValue(rawValue);
if (isNaN(value) || meta.data[index].hidden) {
return;
}
values[index] = values[index] || 0;
if (opts.relativePoints) {
values[index] = 100;
} else {
// Don't need to split positive and negative since the log scale can't handle a 0 crossing
values[index] += value;
}
});
}
});
helpers.each(valuesPerType, function(valuesForType) {
var minVal = helpers.min(valuesForType);
var maxVal = helpers.max(valuesForType);
me.min = me.min === null ? minVal : Math.min(me.min, minVal);
me.max = me.max === null ? maxVal : Math.max(me.max, maxVal);
});
} else {
helpers.each(datasets, function(dataset, datasetIndex) {
var meta = chart.getDatasetMeta(datasetIndex);
if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) {
helpers.each(dataset.data, function(rawValue, index) {
var value = +me.getRightValue(rawValue);
if (isNaN(value) || meta.data[index].hidden) {
return;
}
if (me.min === null) {
me.min = value;
} else if (value < me.min) {
me.min = value;
}
if (me.max === null) {
me.max = value;
} else if (value > me.max) {
me.max = value;
}
});
}
});
}
me.min = getValueOrDefault(tickOpts.min, me.min);
me.max = getValueOrDefault(tickOpts.max, me.max);
if (me.min === me.max) {
if (me.min !== 0 && me.min !== null) {
me.min = Math.pow(10, Math.floor(helpers.log10(me.min)) - 1);
me.max = Math.pow(10, Math.floor(helpers.log10(me.max)) + 1);
} else {
me.min = 1;
me.max = 10;
}
}
},
buildTicks: function() {
var me = this;
var opts = me.options;
var tickOpts = opts.ticks;
var getValueOrDefault = helpers.getValueOrDefault;
// Reset the ticks array. Later on, we will draw a grid line at these positions
// The array simply contains the numerical value of the spots where ticks will be
var ticks = me.ticks = [];
// Figure out what the max number of ticks we can support it is based on the size of
// the axis area. For now, we say that the minimum tick spacing in pixels must be 50
// We also limit the maximum number of ticks to 11 which gives a nice 10 squares on
// the graph
var tickVal = getValueOrDefault(tickOpts.min, Math.pow(10, Math.floor(helpers.log10(me.min))));
while (tickVal < me.max) {
ticks.push(tickVal);
var exp = Math.floor(helpers.log10(tickVal));
var significand = Math.floor(tickVal / Math.pow(10, exp)) + 1;
if (significand === 10) {
significand = 1;
++exp;
}
tickVal = significand * Math.pow(10, exp);
}
var lastTick = getValueOrDefault(tickOpts.max, tickVal);
ticks.push(lastTick);
if (!me.isHorizontal()) {
// We are in a vertical orientation. The top value is the highest. So reverse the array
ticks.reverse();
}
// At this point, we need to update our max and min given the tick values since we have expanded the
// range of the scale
me.max = helpers.max(ticks);
me.min = helpers.min(ticks);
if (tickOpts.reverse) {
ticks.reverse();
me.start = me.max;
me.end = me.min;
} else {
me.start = me.min;
me.end = me.max;
}
},
convertTicksToLabels: function() {
this.tickValues = this.ticks.slice();
Chart.Scale.prototype.convertTicksToLabels.call(this);
},
// Get the correct tooltip label
getLabelForIndex: function(index, datasetIndex) {
return +this.getRightValue(this.chart.data.datasets[datasetIndex].data[index]);
},
getPixelForTick: function(index, includeOffset) {
return this.getPixelForValue(this.tickValues[index], null, null, includeOffset);
},
getPixelForValue: function(value, index, datasetIndex, includeOffset) {
var me = this;
var innerDimension;
var pixel;
var start = me.start;
var newVal = +me.getRightValue(value);
var range = helpers.log10(me.end) - helpers.log10(start);
var paddingTop = me.paddingTop;
var paddingBottom = me.paddingBottom;
var paddingLeft = me.paddingLeft;
if (me.isHorizontal()) {
if (newVal === 0) {
pixel = me.left + paddingLeft;
} else {
innerDimension = me.width - (paddingLeft + me.paddingRight);
pixel = me.left + (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start)));
pixel += paddingLeft;
}
} else {
// Bottom - top since pixels increase downard on a screen
if (newVal === 0) {
pixel = me.top + paddingTop;
} else {
innerDimension = me.height - (paddingTop + paddingBottom);
pixel = (me.bottom - paddingBottom) - (innerDimension / range * (helpers.log10(newVal) - helpers.log10(start)));
}
}
return pixel;
},
getValueForPixel: function(pixel) {
var me = this;
var offset;
var range = helpers.log10(me.end) - helpers.log10(me.start);
var value;
var innerDimension;
if (me.isHorizontal()) {
innerDimension = me.width - (me.paddingLeft + me.paddingRight);
value = me.start * Math.pow(10, (pixel - me.left - me.paddingLeft) * range / innerDimension);
} else {
innerDimension = me.height - (me.paddingTop + me.paddingBottom);
value = Math.pow(10, (me.bottom - me.paddingBottom - pixel) * range / innerDimension) / me.start;
}
return value;
}
});
Chart.scaleService.registerScaleType("logarithmic", LogarithmicScale, defaultConfig);
}; | 1.625 | 2 |
app/containers/SettingsList.js | fakob/MoviePrint_v004 | 88 | 3023 | // @flow
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import Slider, { Handle, createSliderWithTooltip } from 'rc-slider';
import Tooltip from 'rc-tooltip';
import { SketchPicker } from 'react-color';
import throttle from 'lodash/throttle';
import { Checkboard } from 'react-color/lib/components/common';
import {
Accordion,
Button,
Icon,
Label,
Radio,
Dropdown,
Container,
Statistic,
Divider,
Checkbox,
Grid,
List,
Message,
Popup,
Input,
} from 'semantic-ui-react';
import styles from './Settings.css';
import stylesPop from '../components/Popup.css';
import { frameCountToMinutes, getCustomFileName, limitRange, sanitizeString, typeInTextarea } from '../utils/utils';
import {
CACHED_FRAMES_SIZE_OPTIONS,
COLOR_PALETTE_PICO_EIGHT,
DEFAULT_ALLTHUMBS_NAME,
DEFAULT_FRAMEINFO_BACKGROUND_COLOR,
DEFAULT_FRAMEINFO_COLOR,
DEFAULT_FRAMEINFO_MARGIN,
DEFAULT_FRAMEINFO_POSITION,
DEFAULT_FRAMEINFO_SCALE,
DEFAULT_MOVIE_HEIGHT,
DEFAULT_MOVIE_WIDTH,
DEFAULT_MOVIEPRINT_BACKGROUND_COLOR,
DEFAULT_MOVIEPRINT_NAME,
DEFAULT_SHOW_FACERECT,
DEFAULT_SINGLETHUMB_NAME,
DEFAULT_OUTPUT_JPG_QUALITY,
DEFAULT_THUMB_FORMAT,
DEFAULT_THUMB_JPG_QUALITY,
FACE_CONFIDENCE_THRESHOLD,
FACE_SIZE_THRESHOLD,
FACE_UNIQUENESS_THRESHOLD,
FRAMEINFO_POSITION_OPTIONS,
MENU_FOOTER_HEIGHT,
MENU_HEADER_HEIGHT,
MOVIEPRINT_WIDTH_HEIGHT,
MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT,
OUTPUT_FORMAT_OPTIONS,
OUTPUT_FORMAT,
PAPER_LAYOUT_OPTIONS,
SHEET_TYPE,
SHOT_DETECTION_METHOD_OPTIONS,
THUMB_SELECTION,
} from '../utils/constants';
import getScaleValueObject from '../utils/getScaleValueObject';
const SliderWithTooltip = createSliderWithTooltip(Slider);
const handle = props => {
const { value, dragging, index, ...restProps } = props;
return (
<Tooltip prefixCls="rc-slider-tooltip" overlay={value} visible placement="top" key={index}>
<Handle value={value} {...restProps} />
</Tooltip>
);
};
const getOutputSizeOptions = (
baseSizeArray,
file = {
width: DEFAULT_MOVIE_WIDTH,
height: DEFAULT_MOVIE_HEIGHT,
},
columnCountTemp,
thumbCountTemp,
settings,
visibilitySettings,
sceneArray,
secondsPerRowTemp,
isGridView,
) => {
const newScaleValueObject = getScaleValueObject(
file,
settings,
visibilitySettings,
columnCountTemp,
thumbCountTemp,
4096,
undefined,
1,
undefined,
undefined,
sceneArray,
secondsPerRowTemp,
);
// set base size options
const moviePrintSize = MOVIEPRINT_WIDTH_HEIGHT.map(item => {
const otherDim = isGridView
? Math.round(item * newScaleValueObject.moviePrintAspectRatioInv)
: Math.round(item / newScaleValueObject.timelineMoviePrintAspectRatioInv);
return {
value: item,
otherdim: otherDim,
text: isGridView ? `${item}px (×${otherDim}px)` : `${otherDim}px (×${item}px)`,
'data-tid': `${item}-option`,
};
});
// add max option
if (
isGridView
? newScaleValueObject.moviePrintAspectRatioInv > 1
: newScaleValueObject.timelineMoviePrintAspectRatioInv < 1
) {
const maxDim = isGridView
? Math.round(MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT / newScaleValueObject.moviePrintAspectRatioInv)
: Math.round(MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT * newScaleValueObject.timelineMoviePrintAspectRatioInv);
// to avoid duplicates due to rounding
if (maxDim !== MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT) {
moviePrintSize.push({
value: maxDim,
otherdim: MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT,
text: isGridView
? `${maxDim}px (×${MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT}px)`
: `${MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT}px (×${maxDim}px)`,
'data-tid': `other-max-option`,
});
}
}
// filter options
const moviePrintSizeArray = moviePrintSize.filter(item => {
const useOtherDim = isGridView
? newScaleValueObject.moviePrintAspectRatioInv > 1
: newScaleValueObject.timelineMoviePrintAspectRatioInv < 1;
return useOtherDim
? item.otherdim <= MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT
: item.value <= MOVIEPRINT_WIDTH_HEIGHT_SIZE_LIMIT;
});
// console.log(moviePrintSizeArray);
return moviePrintSizeArray;
};
class SettingsList extends Component {
constructor(props) {
super(props);
this.state = {
changeSceneCount: false,
showSliders: true,
displayColorPicker: {
moviePrintBackgroundColor: false,
frameninfoBackgroundColor: false,
frameinfoColor: false,
},
previewMoviePrintName: DEFAULT_MOVIEPRINT_NAME,
previewSingleThumbName: DEFAULT_SINGLETHUMB_NAME,
previewAllThumbsName: DEFAULT_ALLTHUMBS_NAME,
focusReference: undefined,
activeIndex: -1,
};
this.onChangeDefaultMoviePrintNameThrottled = throttle(
value => this.props.onChangeDefaultMoviePrintName(value),
1000,
{ leading: false },
);
this.onChangeDefaultMoviePrintNameThrottled = this.onChangeDefaultMoviePrintNameThrottled.bind(this);
this.onChangeDefaultSingleThumbNameThrottled = throttle(
value => this.props.onChangeDefaultSingleThumbName(value),
1000,
{ leading: false },
);
this.onChangeDefaultSingleThumbNameThrottled = this.onChangeDefaultSingleThumbNameThrottled.bind(this);
this.onChangeDefaultAllThumbsNameThrottled = throttle(
value => this.props.onChangeDefaultAllThumbsName(value),
1000,
{ leading: false },
);
this.onChangeDefaultAllThumbsNameThrottled = this.onChangeDefaultAllThumbsNameThrottled.bind(this);
// this.onToggleSliders = this.onToggleSliders.bind(this);
this.onGetPreviewCustomFileName = this.onGetPreviewCustomFileName.bind(this);
this.onShowSliders = this.onShowSliders.bind(this);
this.onChangeSceneCount = this.onChangeSceneCount.bind(this);
this.onChangePaperAspectRatio = this.onChangePaperAspectRatio.bind(this);
this.onChangeShowPaperPreview = this.onChangeShowPaperPreview.bind(this);
this.onChangeOutputPathFromMovie = this.onChangeOutputPathFromMovie.bind(this);
this.onChangeTimelineViewFlow = this.onChangeTimelineViewFlow.bind(this);
this.onChangeDetectInOutPoint = this.onChangeDetectInOutPoint.bind(this);
this.onChangeReCapture = this.onChangeReCapture.bind(this);
this.onChangeShowHeader = this.onChangeShowHeader.bind(this);
this.onChangeShowPathInHeader = this.onChangeShowPathInHeader.bind(this);
this.onChangeShowDetailsInHeader = this.onChangeShowDetailsInHeader.bind(this);
this.onChangeShowTimelineInHeader = this.onChangeShowTimelineInHeader.bind(this);
this.onChangeRoundedCorners = this.onChangeRoundedCorners.bind(this);
this.onChangeShowHiddenThumbs = this.onChangeShowHiddenThumbs.bind(this);
this.onChangeThumbInfo = this.onChangeThumbInfo.bind(this);
this.onChangeOutputFormat = this.onChangeOutputFormat.bind(this);
this.onChangeThumbFormat = this.onChangeThumbFormat.bind(this);
this.onChangeFrameinfoPosition = this.onChangeFrameinfoPosition.bind(this);
this.onChangeCachedFramesSize = this.onChangeCachedFramesSize.bind(this);
this.onChangeOverwrite = this.onChangeOverwrite.bind(this);
this.onChangeIncludeIndividual = this.onChangeIncludeIndividual.bind(this);
this.onChangeEmbedFrameNumbers = this.onChangeEmbedFrameNumbers.bind(this);
this.onChangeEmbedFilePath = this.onChangeEmbedFilePath.bind(this);
this.onChangeOpenFileExplorerAfterSaving = this.onChangeOpenFileExplorerAfterSaving.bind(this);
this.onChangeThumbnailScale = this.onChangeThumbnailScale.bind(this);
this.onChangeMoviePrintWidth = this.onChangeMoviePrintWidth.bind(this);
this.onChangeShotDetectionMethod = this.onChangeShotDetectionMethod.bind(this);
this.onSubmitDefaultMoviePrintName = this.onSubmitDefaultMoviePrintName.bind(this);
this.onSubmitDefaultSingleThumbName = this.onSubmitDefaultSingleThumbName.bind(this);
this.setFocusReference = this.setFocusReference.bind(this);
this.addAttributeIntoInput = this.addAttributeIntoInput.bind(this);
this.onSubmitDefaultAllThumbsName = this.onSubmitDefaultAllThumbsName.bind(this);
this.onChangeColumnCountViaInput = this.onChangeColumnCountViaInput.bind(this);
this.onChangeColumnCountViaInputAndApply = this.onChangeColumnCountViaInputAndApply.bind(this);
this.onChangeRowViaInput = this.onChangeRowViaInput.bind(this);
this.onChangeTimelineViewSecondsPerRowViaInput = this.onChangeTimelineViewSecondsPerRowViaInput.bind(this);
this.handleClick = this.handleClick.bind(this);
}
componentDidUpdate(prevProps) {
const { file, sheetName, settings } = this.props;
if (
file !== undefined &&
prevProps.file !== undefined &&
prevProps.file.name !== undefined &&
file.name !== undefined
) {
if (file.name !== prevProps.file.name || sheetName !== prevProps.sheetName) {
const {
defaultMoviePrintName = DEFAULT_MOVIEPRINT_NAME,
defaultSingleThumbName = DEFAULT_SINGLETHUMB_NAME,
defaultAllThumbsName = DEFAULT_ALLTHUMBS_NAME,
} = settings;
this.setState({
previewMoviePrintName: this.onGetPreviewCustomFileName(defaultMoviePrintName),
previewSingleThumbName: this.onGetPreviewCustomFileName(defaultSingleThumbName),
previewAllThumbsName: this.onGetPreviewCustomFileName(defaultAllThumbsName),
});
}
}
}
// onToggleSliders = () => {
// this.setState(state => ({
// showSliders: !state.showSliders
// }));
// }
handleClick = (e, titleProps) => {
const { index } = titleProps;
const { activeIndex } = this.state;
const newIndex = activeIndex === index ? -1 : index;
this.setState({ activeIndex: newIndex });
};
onGetPreviewCustomFileName = (customFileName, props = this.props) => {
const { file, settings, sheetName } = props;
const previewName = getCustomFileName(file !== undefined ? file.name : '', sheetName, `000000`, customFileName);
return previewName;
};
onShowSliders = (e, { checked }) => {
this.setState({
showSliders: !checked,
});
};
setFocusReference = e => {
const ref = e.target;
this.setState({
focusReference: ref,
});
};
addAttributeIntoInput = attribute => {
const { focusReference } = this.state;
if (focusReference !== undefined) {
// console.log(focusReference);
const newText = typeInTextarea(focusReference, attribute);
const previewName = this.onGetPreviewCustomFileName(newText);
switch (focusReference.name) {
case 'defaultMoviePrintNameInput':
this.setState({
previewMoviePrintName: previewName,
});
break;
case 'defaultSingleThumbNameInput':
this.setState({
previewSingleThumbName: previewName,
});
break;
case 'defaultAllThumbsNameInput':
this.setState({
previewAllThumbsName: previewName,
});
break;
default:
}
}
};
onSubmitDefaultMoviePrintName = e => {
const value = sanitizeString(e.target.value);
const previewMoviePrintName = this.onGetPreviewCustomFileName(value);
this.setState({
previewMoviePrintName,
});
this.onChangeDefaultMoviePrintNameThrottled(value);
};
onSubmitDefaultSingleThumbName = e => {
const value = sanitizeString(e.target.value);
const previewSingleThumbName = this.onGetPreviewCustomFileName(value);
this.setState({
previewSingleThumbName,
});
this.onChangeDefaultSingleThumbNameThrottled(value);
};
onSubmitDefaultAllThumbsName = e => {
const value = sanitizeString(e.target.value);
const previewAllThumbsName = this.onGetPreviewCustomFileName(value);
this.setState({
previewAllThumbsName,
});
this.onChangeDefaultAllThumbsNameThrottled(value);
};
onChangeColumnCountViaInput = e => {
if (e.key === 'Enter') {
const value = limitRange(Math.floor(e.target.value), 1, 100);
this.props.onChangeColumn(value);
}
};
onChangeColumnCountViaInputAndApply = e => {
if (e.key === 'Enter') {
const value = limitRange(Math.floor(e.target.value), 1, 100);
this.props.onChangeColumnAndApply(value);
}
};
onChangeRowViaInput = e => {
if (e.key === 'Enter') {
const value = limitRange(Math.floor(e.target.value), 1, 100);
this.props.onChangeRow(value);
}
};
onChangeTimelineViewSecondsPerRowViaInput = e => {
if (e.key === 'Enter') {
const value = limitRange(Math.floor(e.target.value), 1, 20000); // 1 second to 5 hours
this.props.onChangeTimelineViewSecondsPerRow(value);
}
};
onChangeSceneCount = (e, { checked }) => {
this.setState({ changeSceneCount: checked });
};
onChangeTimelineViewFlow = (e, { checked }) => {
this.props.onTimelineViewFlowClick(checked);
};
onChangeShowPaperPreview = (e, { checked }) => {
this.props.onShowPaperPreviewClick(checked);
};
onChangeOutputPathFromMovie = (e, { checked }) => {
this.props.onOutputPathFromMovieClick(checked);
};
onChangePaperAspectRatio = (e, { value }) => {
this.props.onPaperAspectRatioClick(value);
};
onChangeDetectInOutPoint = (e, { checked }) => {
this.props.onDetectInOutPointClick(checked);
};
onChangeReCapture = (e, { checked }) => {
this.props.onReCaptureClick(checked);
};
onChangeShowHeader = (e, { checked }) => {
this.props.onToggleHeaderClick(checked);
};
onChangeShowPathInHeader = (e, { checked }) => {
this.props.onShowPathInHeaderClick(checked);
};
onChangeShowFaceRect = (e, { checked }) => {
this.props.onChangeShowFaceRectClick(checked);
};
onChangeShowDetailsInHeader = (e, { checked }) => {
this.props.onShowDetailsInHeaderClick(checked);
};
onChangeShowTimelineInHeader = (e, { checked }) => {
this.props.onShowTimelineInHeaderClick(checked);
};
onChangeRoundedCorners = (e, { checked }) => {
this.props.onRoundedCornersClick(checked);
};
onChangeShowHiddenThumbs = (e, { checked }) => {
this.props.onShowHiddenThumbsClick(checked);
};
onChangeThumbInfo = (e, { value }) => {
this.props.onThumbInfoClick(value);
};
onChangeOutputFormat = (e, { value }) => {
this.props.onOutputFormatClick(value);
};
onChangeThumbFormat = (e, { value }) => {
this.props.onThumbFormatClick(value);
};
onChangeFrameinfoPosition = (e, { value }) => {
this.props.onFrameinfoPositionClick(value);
};
onChangeCachedFramesSize = (e, { value }) => {
this.props.onCachedFramesSizeClick(value);
};
onChangeOverwrite = (e, { checked }) => {
this.props.onOverwriteClick(checked);
};
onChangeIncludeIndividual = (e, { checked }) => {
this.props.onIncludeIndividualClick(checked);
};
onChangeEmbedFrameNumbers = (e, { checked }) => {
this.props.onEmbedFrameNumbersClick(checked);
};
onChangeEmbedFilePath = (e, { checked }) => {
this.props.onEmbedFilePathClick(checked);
};
onChangeOpenFileExplorerAfterSaving = (e, { checked }) => {
this.props.onOpenFileExplorerAfterSavingClick(checked);
};
onChangeThumbnailScale = (e, { value }) => {
this.props.onThumbnailScaleClick(value);
};
onChangeMoviePrintWidth = (e, { value }) => {
this.props.onMoviePrintWidthClick(value);
};
onChangeShotDetectionMethod = (e, { value }) => {
this.props.onShotDetectionMethodClick(value);
};
colorPickerHandleClick = (e, id) => {
e.stopPropagation();
this.setState({
displayColorPicker: {
...this.state.displayColorPicker,
[id]: !this.state.displayColorPicker[id],
},
});
};
colorPickerHandleClose = (e, id) => {
e.stopPropagation();
this.setState({
displayColorPicker: {
...this.state.displayColorPicker,
[id]: false,
},
});
};
colorPickerHandleChange = (colorLocation, color) => {
console.log(colorLocation);
console.log(color);
this.props.onMoviePrintBackgroundColorClick(colorLocation, color.rgb);
};
render() {
const {
columnCountTemp,
file,
fileScanRunning,
isGridView,
onApplyNewGridClick,
onChangeColumn,
onChangeColumnAndApply,
onChangeMargin,
onChangeOutputJpgQuality,
onChangeThumbJpgQuality,
onChangeFaceSizeThreshold,
onChangeFaceConfidenceThreshold,
onChangeFrameinfoMargin,
onChangeFrameinfoScale,
onChangeMinDisplaySceneLength,
onChangeOutputPathClick,
onChangeRow,
onChangeSceneDetectionThreshold,
onChangeTimelineViewWidthScale,
onToggleDetectionChart,
reCapture,
recaptureAllFrames,
rowCountTemp,
sceneArray,
secondsPerRowTemp,
settings,
sheetType,
sheetName,
showChart,
thumbCount,
thumbCountTemp,
visibilitySettings,
} = this.props;
const {
activeIndex,
displayColorPicker,
focusReference,
outputSizeOptions,
previewMoviePrintName,
previewSingleThumbName,
previewAllThumbsName,
showSliders,
} = this.state;
const {
defaultCachedFramesSize = 0,
defaultDetectInOutPoint,
defaultEmbedFilePath,
defaultEmbedFrameNumbers,
defaultShowFaceRect = DEFAULT_SHOW_FACERECT,
defaultFaceSizeThreshold = FACE_SIZE_THRESHOLD,
defaultFaceConfidenceThreshold = FACE_CONFIDENCE_THRESHOLD,
defaultFaceUniquenessThreshold = FACE_UNIQUENESS_THRESHOLD,
defaultFrameinfoBackgroundColor = DEFAULT_FRAMEINFO_BACKGROUND_COLOR,
defaultFrameinfoColor = DEFAULT_FRAMEINFO_COLOR,
defaultFrameinfoPosition = DEFAULT_FRAMEINFO_POSITION,
defaultFrameinfoScale = DEFAULT_FRAMEINFO_SCALE,
defaultFrameinfoMargin = DEFAULT_FRAMEINFO_MARGIN,
defaultMarginRatio,
defaultOutputJpgQuality = DEFAULT_OUTPUT_JPG_QUALITY,
defaultThumbJpgQuality = DEFAULT_THUMB_JPG_QUALITY,
defaultMarginSliderFactor,
defaultMoviePrintBackgroundColor = DEFAULT_MOVIEPRINT_BACKGROUND_COLOR,
defaultMoviePrintWidth,
defaultOpenFileExplorerAfterSaving,
defaultOutputFormat,
defaultThumbFormat = DEFAULT_THUMB_FORMAT,
defaultOutputPath,
defaultOutputPathFromMovie,
defaultPaperAspectRatioInv,
defaultRoundedCorners,
defaultSaveOptionIncludeIndividual,
defaultSaveOptionOverwrite,
defaultSceneDetectionThreshold,
defaultShotDetectionMethod,
defaultShowDetailsInHeader,
defaultShowHeader,
defaultShowPaperPreview,
defaultShowPathInHeader,
defaultShowTimelineInHeader,
defaultThumbInfo,
defaultTimelineViewFlow,
defaultTimelineViewMinDisplaySceneLengthInFrames,
defaultTimelineViewWidthScale,
defaultMoviePrintName = DEFAULT_MOVIEPRINT_NAME,
defaultSingleThumbName = DEFAULT_SINGLETHUMB_NAME,
defaultAllThumbsName = DEFAULT_ALLTHUMBS_NAME,
} = settings;
const fileFps = file !== undefined ? file.fps : 25;
const minutes = file !== undefined ? frameCountToMinutes(file.frameCount, fileFps) : undefined;
const minutesRounded = Math.round(minutes);
const cutsPerMinuteRounded = Math.round((thumbCountTemp - 1) / minutes);
const frameNumberOrTimecode = ['[FN]', '[TC]'];
const defaultSingleThumbNameContainsFrameNumberOrTimeCode = frameNumberOrTimecode.some(item =>
defaultSingleThumbName.includes(item),
);
const defaultAllThumbsNameContainsFrameNumberOrTimeCode = frameNumberOrTimecode.some(item =>
defaultAllThumbsName.includes(item),
);
const moviePrintBackgroundColorDependentOnFormat =
defaultOutputFormat === OUTPUT_FORMAT.JPG // set alpha only for PNG
? {
r: defaultMoviePrintBackgroundColor.r,
g: defaultMoviePrintBackgroundColor.g,
b: defaultMoviePrintBackgroundColor.b,
}
: defaultMoviePrintBackgroundColor;
const moviePrintBackgroundColorDependentOnFormatString =
defaultOutputFormat === OUTPUT_FORMAT.JPG // set alpha only for PNG
? `rgb(${defaultMoviePrintBackgroundColor.r}, ${defaultMoviePrintBackgroundColor.g}, ${defaultMoviePrintBackgroundColor.b})`
: `rgba(${defaultMoviePrintBackgroundColor.r}, ${defaultMoviePrintBackgroundColor.g}, ${defaultMoviePrintBackgroundColor.b}, ${defaultMoviePrintBackgroundColor.a})`;
const frameninfoBackgroundColorString = `rgba(${defaultFrameinfoBackgroundColor.r}, ${defaultFrameinfoBackgroundColor.g}, ${defaultFrameinfoBackgroundColor.b}, ${defaultFrameinfoBackgroundColor.a})`;
const frameinfoColorString = `rgba(${defaultFrameinfoColor.r}, ${defaultFrameinfoColor.g}, ${defaultFrameinfoColor.b}, ${defaultFrameinfoColor.a})`;
return (
<Container
style={{
marginBottom: `${MENU_HEADER_HEIGHT + MENU_FOOTER_HEIGHT}px`,
}}
>
<Grid padded inverted>
{!isGridView && (
<Grid.Row>
<Grid.Column width={16}>
<Statistic inverted size="tiny">
<Statistic.Value>{thumbCountTemp}</Statistic.Value>
<Statistic.Label>{thumbCountTemp === 1 ? 'Shot' : 'Shots'}</Statistic.Label>
</Statistic>
<Statistic inverted size="tiny">
<Statistic.Value>/</Statistic.Value>
</Statistic>
<Statistic inverted size="tiny">
<Statistic.Value>~{minutesRounded}</Statistic.Value>
<Statistic.Label>{minutesRounded === 1 ? 'Minute' : 'Minutes'}</Statistic.Label>
</Statistic>
<Statistic inverted size="tiny">
<Statistic.Value>≈</Statistic.Value>
</Statistic>
<Statistic inverted size="tiny">
<Statistic.Value>{cutsPerMinuteRounded}</Statistic.Value>
<Statistic.Label>cut/min</Statistic.Label>
</Statistic>
</Grid.Column>
</Grid.Row>
)}
{isGridView && (
<Grid.Row>
<Grid.Column width={16}>
<Statistic inverted size="tiny">
<Statistic.Value>{columnCountTemp}</Statistic.Value>
<Statistic.Label>{columnCountTemp === 1 ? 'Column' : 'Columns'}</Statistic.Label>
</Statistic>
<Statistic inverted size="tiny">
<Statistic.Value>×</Statistic.Value>
</Statistic>
<Statistic inverted size="tiny">
<Statistic.Value>{rowCountTemp}</Statistic.Value>
<Statistic.Label>{rowCountTemp === 1 ? 'Row' : 'Rows'}</Statistic.Label>
</Statistic>
<Statistic inverted size="tiny">
<Statistic.Value>{columnCountTemp * rowCountTemp === thumbCountTemp ? '=' : '≈'}</Statistic.Value>
</Statistic>
<Statistic inverted size="tiny" color={reCapture ? 'orange' : undefined}>
<Statistic.Value>{thumbCountTemp}</Statistic.Value>
<Statistic.Label>{reCapture ? 'Count' : 'Count'}</Statistic.Label>
</Statistic>
</Grid.Column>
</Grid.Row>
)}
{isGridView && (
<Grid.Row>
<Grid.Column width={4}>Columns</Grid.Column>
<Grid.Column width={12}>
{showSliders && (
<SliderWithTooltip
data-tid="columnCountSlider"
className={styles.slider}
min={1}
max={20}
defaultValue={columnCountTemp}
value={columnCountTemp}
marks={{
1: '1',
20: '20',
}}
handle={handle}
onChange={
sheetType === SHEET_TYPE.INTERVAL && reCapture && isGridView
? onChangeColumn
: onChangeColumnAndApply
}
/>
)}
{!showSliders && (
<Input
type="number"
data-tid="columnCountInput"
className={styles.input}
defaultValue={columnCountTemp}
onKeyDown={
reCapture && isGridView
? this.onChangeColumnCountViaInput
: this.onChangeColumnCountViaInputAndApply
}
/>
)}
</Grid.Column>
</Grid.Row>
)}
{sheetType === SHEET_TYPE.INTERVAL && isGridView && reCapture && (
<Grid.Row>
<Grid.Column width={4}>Rows</Grid.Column>
<Grid.Column width={12}>
{showSliders && (
<SliderWithTooltip
data-tid="rowCountSlider"
disabled={!reCapture}
className={styles.slider}
min={1}
max={20}
defaultValue={rowCountTemp}
value={rowCountTemp}
{...(reCapture ? {} : { value: rowCountTemp })}
marks={{
1: '1',
20: '20',
}}
handle={handle}
onChange={onChangeRow}
/>
)}
{!showSliders && (
<Input
type="number"
data-tid="rowCountInput"
className={styles.input}
defaultValue={rowCountTemp}
onKeyDown={this.onChangeRowViaInput}
/>
)}
</Grid.Column>
</Grid.Row>
)}
{!isGridView && (
<>
<Grid.Row>
<Grid.Column width={4}>Minutes per row</Grid.Column>
<Grid.Column width={12}>
{showSliders && (
<SliderWithTooltip
data-tid="minutesPerRowSlider"
className={styles.slider}
min={10}
max={1800}
defaultValue={secondsPerRowTemp}
value={secondsPerRowTemp}
marks={{
10: '0.1',
60: '1',
300: '5',
600: '10',
1200: '20',
1800: '30',
}}
handle={handle}
onChange={this.props.onChangeTimelineViewSecondsPerRow}
/>
)}
{!showSliders && (
<Input
type="number"
data-tid="minutesPerRowInput"
className={styles.input}
label={{ basic: true, content: 'sec' }}
labelPosition="right"
defaultValue={secondsPerRowTemp}
onKeyDown={this.onChangeTimelineViewSecondsPerRowViaInput}
/>
)}
</Grid.Column>
</Grid.Row>
{sheetType === SHEET_TYPE.SCENES && (
<Grid.Row>
<Grid.Column width={4}></Grid.Column>
<Grid.Column width={12}>
<Checkbox
data-tid="changeTimelineViewFlow"
label={<label className={styles.label}>Natural flow</label>}
checked={defaultTimelineViewFlow}
onChange={this.onChangeTimelineViewFlow}
/>
</Grid.Column>
</Grid.Row>
)}
{sheetType === SHEET_TYPE.SCENES && (
<Grid.Row>
<Grid.Column width={4}>Count</Grid.Column>
<Grid.Column width={12}>
<Checkbox
data-tid="changeSceneCountCheckbox"
label={<label className={styles.label}>Change scene count</label>}
checked={this.state.changeSceneCount}
onChange={this.onChangeSceneCount}
/>
</Grid.Column>
</Grid.Row>
)}
{sheetType === SHEET_TYPE.SCENES && this.state.changeSceneCount && (
<>
<Grid.Row>
<Grid.Column width={4}>Shot detection threshold</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
// data-tid='sceneDetectionThresholdSlider'
className={styles.slider}
min={3}
max={40}
defaultValue={defaultSceneDetectionThreshold}
marks={{
3: '3',
15: '15',
30: '30',
}}
handle={handle}
onChange={onChangeSceneDetectionThreshold}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}></Grid.Column>
<Grid.Column width={12}>
<Popup
trigger={
<Button
data-tid="runSceneDetectionBtn"
fluid
color="orange"
loading={fileScanRunning}
disabled={fileScanRunning}
onClick={() =>
this.props.runSceneDetection(
file.id,
file.path,
file.useRatio,
defaultSceneDetectionThreshold,
)
}
>
Add new MoviePrint
</Button>
}
mouseEnterDelay={1000}
on={['hover']}
position="bottom center"
className={stylesPop.popup}
content="Run shot detection with new threshold"
/>
</Grid.Column>
</Grid.Row>
</>
)}
</>
)}
{sheetType === SHEET_TYPE.INTERVAL && isGridView && (
<Grid.Row>
<Grid.Column width={4}>Count</Grid.Column>
<Grid.Column width={12}>
<Checkbox
data-tid="changeThumbCountCheckbox"
label={<label className={styles.label}>Change thumb count</label>}
checked={reCapture}
onChange={this.onChangeReCapture}
/>
</Grid.Column>
</Grid.Row>
)}
{sheetType === SHEET_TYPE.INTERVAL && isGridView && thumbCount !== thumbCountTemp && (
<Grid.Row>
<Grid.Column width={4} />
<Grid.Column width={12}>
<Message data-tid="applyNewGridMessage" color="orange" size="mini">
Applying a new grid will overwrite your previously selected thumbs. Don't worry, this can be
undone.
</Message>
</Grid.Column>
</Grid.Row>
)}
{sheetType === SHEET_TYPE.INTERVAL && isGridView && (
<Grid.Row>
<Grid.Column width={4} />
<Grid.Column width={12}>
<Popup
trigger={
<Button
data-tid="applyNewGridBtn"
fluid
color="orange"
disabled={thumbCount === thumbCountTemp}
onClick={onApplyNewGridClick}
>
Apply
</Button>
}
mouseEnterDelay={1000}
on={['hover']}
position="bottom center"
className={stylesPop.popup}
content="Apply new grid for MoviePrint"
/>
</Grid.Column>
</Grid.Row>
)}
<Grid.Row>
<Grid.Column width={16}>
<Accordion inverted className={styles.accordion}>
<Accordion.Title active={activeIndex === 0} index={0} onClick={this.handleClick}>
<Icon name="dropdown" />
Guide layout
</Accordion.Title>
<Accordion.Content active={activeIndex === 0}>
<Grid padded inverted>
<Grid.Row>
<Grid.Column width={4} textAlign="right" verticalAlign="middle">
<Checkbox
data-tid="showPaperPreviewCheckbox"
checked={defaultShowPaperPreview}
onChange={this.onChangeShowPaperPreview}
/>
</Grid.Column>
<Grid.Column width={12}>
<Dropdown
data-tid="paperLayoutOptionsDropdown"
placeholder="Select..."
selection
disabled={!defaultShowPaperPreview}
options={PAPER_LAYOUT_OPTIONS}
defaultValue={defaultPaperAspectRatioInv}
onChange={this.onChangePaperAspectRatio}
/>
</Grid.Column>
</Grid.Row>
</Grid>
</Accordion.Content>
<Accordion.Title active={activeIndex === 1} index={1} onClick={this.handleClick}>
<Icon name="dropdown" />
Styling
</Accordion.Title>
<Accordion.Content active={activeIndex === 1}>
<Grid padded inverted>
<Grid.Row>
<Grid.Column width={4}>Grid margin</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
// data-tid='marginSlider'
className={styles.slider}
min={0}
max={20}
defaultValue={defaultMarginRatio * defaultMarginSliderFactor}
marks={{
0: '0',
20: '20',
}}
handle={handle}
onChange={onChangeMargin}
/>
</Grid.Column>
</Grid.Row>
{!isGridView && (
<Grid.Row>
<Grid.Column width={4}>Scene width ratio</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
data-tid="sceneWidthRatioSlider"
className={styles.slider}
min={0}
max={100}
defaultValue={defaultTimelineViewWidthScale}
marks={{
0: '-10',
50: '0',
100: '+10',
}}
handle={handle}
onChange={onChangeTimelineViewWidthScale}
/>
</Grid.Column>
</Grid.Row>
)}
{!isGridView && (
<Grid.Row>
<Grid.Column width={4}>Min scene width</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
data-tid="minSceneWidthSlider"
className={styles.slider}
min={0}
max={10}
defaultValue={Math.round(
defaultTimelineViewMinDisplaySceneLengthInFrames / (fileFps * 1.0),
)}
marks={{
0: '0',
10: '10',
}}
handle={handle}
onChange={onChangeMinDisplaySceneLength}
/>
</Grid.Column>
</Grid.Row>
)}
<Grid.Row>
<Grid.Column width={4}>Options</Grid.Column>
<Grid.Column width={12}>
<List>
{isGridView && (
<>
<List.Item>
<Checkbox
data-tid="showHeaderCheckbox"
label={<label className={styles.label}>Show header</label>}
checked={defaultShowHeader}
onChange={this.onChangeShowHeader}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="showFilePathCheckbox"
className={styles.subCheckbox}
label={<label className={styles.label}>Show file path</label>}
disabled={!defaultShowHeader}
checked={defaultShowPathInHeader}
onChange={this.onChangeShowPathInHeader}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="showFileDetailsCheckbox"
className={styles.subCheckbox}
label={<label className={styles.label}>Show file details</label>}
disabled={!defaultShowHeader}
checked={defaultShowDetailsInHeader}
onChange={this.onChangeShowDetailsInHeader}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="showTimelineCheckbox"
className={styles.subCheckbox}
label={<label className={styles.label}>Show timeline</label>}
disabled={!defaultShowHeader}
checked={defaultShowTimelineInHeader}
onChange={this.onChangeShowTimelineInHeader}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="roundedCornersCheckbox"
label={<label className={styles.label}>Rounded corners</label>}
checked={defaultRoundedCorners}
onChange={this.onChangeRoundedCorners}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="showHiddenThumbsCheckbox"
label={<label className={styles.label}>Show hidden thumbs</label>}
checked={visibilitySettings.visibilityFilter === THUMB_SELECTION.ALL_THUMBS}
onChange={this.onChangeShowHiddenThumbs}
/>
</List.Item>
</>
)}
</List>
</Grid.Column>
</Grid.Row>
<Divider inverted />
<Grid.Row>
<Grid.Column width={4}>Frame info</Grid.Column>
<Grid.Column width={12}>
<List>
<List.Item>
<Radio
data-tid="showFramesRadioBtn"
label={<label className={styles.label}>Show frames</label>}
name="radioGroup"
value="frames"
checked={defaultThumbInfo === 'frames'}
onChange={this.onChangeThumbInfo}
/>
</List.Item>
<List.Item>
<Radio
data-tid="showTimecodeRadioBtn"
label={<label className={styles.label}>Show timecode</label>}
name="radioGroup"
value="timecode"
checked={defaultThumbInfo === 'timecode'}
onChange={this.onChangeThumbInfo}
/>
</List.Item>
<List.Item>
<Radio
data-tid="hideInfoRadioBtn"
label={<label className={styles.label}>Hide info</label>}
name="radioGroup"
value="hideInfo"
checked={defaultThumbInfo === 'hideInfo'}
onChange={this.onChangeThumbInfo}
/>
</List.Item>
</List>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Font color</Grid.Column>
<Grid.Column width={12}>
<div>
<div
className={styles.colorPickerSwatch}
onClick={e => this.colorPickerHandleClick(e, 'frameinfoColor')}
>
<Checkboard />
<div
className={`${styles.colorPickerColor} ${styles.colorPickerText}`}
style={{
backgroundColor: frameninfoBackgroundColorString,
color: frameinfoColorString,
}}
>
00:00:00:00
</div>
</div>
{displayColorPicker.frameinfoColor ? (
<div
className={styles.colorPickerPopover}
// onMouseLeave={(e) => this.colorPickerHandleClose(e, 'frameinfoColor')}
>
<div
className={styles.colorPickerCover}
onClick={e => this.colorPickerHandleClose(e, 'frameinfoColor')}
/>
<SketchPicker
color={defaultFrameinfoColor}
onChange={color => this.colorPickerHandleChange('frameinfoColor', color)}
presetColors={COLOR_PALETTE_PICO_EIGHT}
/>
</div>
) : null}
</div>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Background color</Grid.Column>
<Grid.Column width={12}>
<div>
<div
className={styles.colorPickerSwatch}
onClick={e => this.colorPickerHandleClick(e, 'frameninfoBackgroundColor')}
>
<Checkboard />
<div
className={styles.colorPickerColor}
style={{
backgroundColor: frameninfoBackgroundColorString,
}}
/>
</div>
{displayColorPicker.frameninfoBackgroundColor ? (
<div
className={styles.colorPickerPopover}
// onMouseLeave={(e) => this.colorPickerHandleClose(e, 'frameninfoBackgroundColor')}
>
<div
className={styles.colorPickerCover}
onClick={e => this.colorPickerHandleClose(e, 'frameninfoBackgroundColor')}
/>
<SketchPicker
color={defaultFrameinfoBackgroundColor}
onChange={color => this.colorPickerHandleChange('frameninfoBackgroundColor', color)}
presetColors={COLOR_PALETTE_PICO_EIGHT}
/>
</div>
) : null}
</div>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Position</Grid.Column>
<Grid.Column width={12}>
<Dropdown
data-tid="changeFrameinfoPositionDropdown"
placeholder="Select..."
selection
options={FRAMEINFO_POSITION_OPTIONS}
defaultValue={defaultFrameinfoPosition}
onChange={this.onChangeFrameinfoPosition}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Size</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
data-tid="frameinfoScaleSlider"
className={styles.slider}
min={1}
max={100}
defaultValue={defaultFrameinfoScale}
marks={{
1: '1',
10: '10',
100: '100',
}}
handle={handle}
onChange={onChangeFrameinfoScale}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Margin</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
data-tid="frameinfoMarginSlider"
className={styles.slider}
min={0}
max={50}
defaultValue={defaultFrameinfoMargin}
marks={{
0: '0',
50: '50',
}}
handle={handle}
onChange={onChangeFrameinfoMargin}
/>
</Grid.Column>
</Grid.Row>
</Grid>
</Accordion.Content>
<Accordion.Title active={activeIndex === 2} index={2} onClick={this.handleClick}>
<Icon name="dropdown" />
Output
</Accordion.Title>
<Accordion.Content active={activeIndex === 2}>
<Grid padded inverted>
<Grid.Row>
<Grid.Column width={4}>File path</Grid.Column>
<Grid.Column width={12}>
<List>
<List.Item>
<div
style={{
wordWrap: 'break-word',
opacity: defaultOutputPathFromMovie ? '0.5' : '1.0',
}}
>
{defaultOutputPath}
</div>
</List.Item>
<List.Item>
<Button
data-tid="changeOutputPathBtn"
onClick={onChangeOutputPathClick}
disabled={defaultOutputPathFromMovie}
>
Change...
</Button>
</List.Item>
<List.Item>
<Checkbox
data-tid="showPaperPreviewCheckbox"
label={<label className={styles.label}>Same as movie file</label>}
style={{
marginTop: '8px',
}}
checked={defaultOutputPathFromMovie}
onChange={this.onChangeOutputPathFromMovie}
/>
</List.Item>
</List>
</Grid.Column>
</Grid.Row>
<Divider inverted />
<Grid.Row>
<Grid.Column width={16}>
<h4>MoviePrint</h4>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Size</Grid.Column>
<Grid.Column width={12}>
<Dropdown
data-tid="changeMoviePrintWidthDropdown"
placeholder="Select..."
selection
options={getOutputSizeOptions(
MOVIEPRINT_WIDTH_HEIGHT,
file,
columnCountTemp,
thumbCountTemp,
settings,
visibilitySettings,
sceneArray,
secondsPerRowTemp,
isGridView,
)}
defaultValue={defaultMoviePrintWidth}
onChange={this.onChangeMoviePrintWidth}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Format</Grid.Column>
<Grid.Column width={12}>
<Dropdown
data-tid="changeOutputFormatDropdown"
placeholder="Select..."
selection
options={OUTPUT_FORMAT_OPTIONS}
defaultValue={defaultOutputFormat}
onChange={this.onChangeOutputFormat}
/>
</Grid.Column>
</Grid.Row>
{defaultOutputFormat === OUTPUT_FORMAT.JPG && (
<Grid.Row>
<Grid.Column width={4}>JPG quality</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
data-tid="outputJpgQualitySlider"
className={styles.slider}
min={0}
max={100}
defaultValue={defaultOutputJpgQuality}
marks={{
0: '0',
80: '80',
100: '100',
}}
handle={handle}
onChange={onChangeOutputJpgQuality}
/>
</Grid.Column>
</Grid.Row>
)}
<Grid.Row>
<Grid.Column width={4}>Background color</Grid.Column>
<Grid.Column width={12}>
<div>
<div
className={styles.colorPickerSwatch}
onClick={e => this.colorPickerHandleClick(e, 'moviePrintBackgroundColor')}
>
<Checkboard />
<div
className={styles.colorPickerColor}
style={{
backgroundColor: moviePrintBackgroundColorDependentOnFormatString,
}}
/>
</div>
{displayColorPicker.moviePrintBackgroundColor ? (
<div
className={styles.colorPickerPopover}
// onMouseLeave={(e) => this.colorPickerHandleClose(e, 'moviePrintBackgroundColor')}
>
<div
className={styles.colorPickerCover}
onClick={e => this.colorPickerHandleClose(e, 'moviePrintBackgroundColor')}
/>
<SketchPicker
color={moviePrintBackgroundColorDependentOnFormat}
onChange={color => this.colorPickerHandleChange('moviePrintBackgroundColor', color)}
disableAlpha={defaultOutputFormat === OUTPUT_FORMAT.JPG}
presetColors={COLOR_PALETTE_PICO_EIGHT}
/>
</div>
) : null}
</div>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Save options</Grid.Column>
<Grid.Column width={12}>
<List>
<List.Item>
<Checkbox
data-tid="overwriteExistingCheckbox"
label={<label className={styles.label}>Overwrite existing</label>}
checked={defaultSaveOptionOverwrite}
onChange={this.onChangeOverwrite}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="includeIndividualFramesCheckbox"
label={<label className={styles.label}>Include individual thumbs</label>}
checked={defaultSaveOptionIncludeIndividual}
onChange={this.onChangeIncludeIndividual}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="embedFrameNumbersCheckbox"
label={<label className={styles.label}>Embed frameNumbers (only PNG)</label>}
checked={defaultEmbedFrameNumbers}
onChange={this.onChangeEmbedFrameNumbers}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="embedFilePathCheckbox"
label={<label className={styles.label}>Embed filePath (only PNG)</label>}
checked={defaultEmbedFilePath}
onChange={this.onChangeEmbedFilePath}
/>
</List.Item>
<List.Item>
<Checkbox
data-tid="embedFilePathCheckbox"
label={<label className={styles.label}>Open File Explorer after saving</label>}
checked={defaultOpenFileExplorerAfterSaving}
onChange={this.onChangeOpenFileExplorerAfterSaving}
/>
</List.Item>
</List>
</Grid.Column>
</Grid.Row>
<Divider inverted />
<Grid.Row>
<Grid.Column width={16}>
<h4>Thumbs</h4>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Format</Grid.Column>
<Grid.Column width={12}>
<Dropdown
data-tid="changeThumbFormatDropdown"
placeholder="Select..."
selection
options={OUTPUT_FORMAT_OPTIONS}
defaultValue={defaultThumbFormat}
onChange={this.onChangeThumbFormat}
/>
</Grid.Column>
</Grid.Row>
{defaultThumbFormat === OUTPUT_FORMAT.JPG && (
<Grid.Row>
<Grid.Column width={4}>JPG quality</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
data-tid="thumbJpgQualitySlider"
className={styles.slider}
min={0}
max={100}
defaultValue={defaultThumbJpgQuality}
marks={{
0: '0',
95: '95',
100: '100',
}}
handle={handle}
onChange={onChangeThumbJpgQuality}
/>
</Grid.Column>
</Grid.Row>
)}
</Grid>
</Accordion.Content>
<Accordion.Title active={activeIndex === 3} index={3} onClick={this.handleClick}>
<Icon name="dropdown" />
Naming scheme
</Accordion.Title>
<Accordion.Content active={activeIndex === 3}>
<Grid padded inverted>
<Grid.Row>
<Grid.Column width={16}>
<label>File name when saving a MoviePrint</label>
<Input
// ref={this.inputDefaultMoviePrintName}
data-tid="defaultMoviePrintNameInput"
name="defaultMoviePrintNameInput" // needed for addAttributeIntoInput
fluid
placeholder="MoviePrint name"
defaultValue={defaultMoviePrintName}
onFocus={this.setFocusReference}
onBlur={this.onSubmitDefaultMoviePrintName}
onKeyUp={this.onSubmitDefaultMoviePrintName}
/>
<Label className={styles.previewCustomName}>
{previewMoviePrintName}.{defaultOutputFormat}
</Label>
<Divider hidden className={styles.smallDivider} />
<label>File name of thumb when saving a single thumb</label>
<Input
// ref={this.inputDefaultSingleThumbName}
data-tid="defaultSingleThumbNameInput"
name="defaultSingleThumbNameInput" // needed for addAttributeIntoInput
fluid
placeholder="Name when saving a single thumb"
defaultValue={defaultSingleThumbName}
onFocus={this.setFocusReference}
onBlur={this.onSubmitDefaultSingleThumbName}
onKeyUp={this.onSubmitDefaultSingleThumbName}
/>
<Label
className={styles.previewCustomName}
color={defaultSingleThumbNameContainsFrameNumberOrTimeCode ? undefined : 'orange'}
pointing={defaultSingleThumbNameContainsFrameNumberOrTimeCode ? undefined : true}
>
{defaultSingleThumbNameContainsFrameNumberOrTimeCode
? undefined
: 'The framenumber attribute is missing. This can lead to the thumb being overwritten. | '}
{previewSingleThumbName}.jpg
</Label>
<Divider hidden className={styles.smallDivider} />
<label>
File name of thumbs when <em>Include individual thumbs</em> is selected
</label>
<Input
// ref={this.inputDefaultAllThumbsName}
data-tid="defaultAllThumbsNameInput"
name="defaultAllThumbsNameInput" // needed for addAttributeIntoInput
fluid
placeholder="Name when including individual thumbs"
defaultValue={defaultAllThumbsName}
onFocus={this.setFocusReference}
onBlur={this.onSubmitDefaultAllThumbsName}
onKeyUp={this.onSubmitDefaultAllThumbsName}
/>
<Label
className={styles.previewCustomName}
color={defaultAllThumbsNameContainsFrameNumberOrTimeCode ? undefined : 'orange'}
pointing={defaultAllThumbsNameContainsFrameNumberOrTimeCode ? undefined : true}
>
{defaultAllThumbsNameContainsFrameNumberOrTimeCode
? undefined
: 'The framenumber attribute is missing. This can lead to the thumb being overwritten. | '}
{previewAllThumbsName}.jpg
</Label>
<h6>Available attributes</h6>
<Button
data-tid="addAttribute[MN]IntoInputButton"
className={styles.attributeButton}
onClick={() => this.addAttributeIntoInput('[MN]')}
disabled={focusReference === undefined}
size="mini"
>
[MN] Movie name
</Button>
<Button
data-tid="addAttribute[ME]IntoInputButton"
className={styles.attributeButton}
onClick={() => this.addAttributeIntoInput('[ME]')}
disabled={focusReference === undefined}
size="mini"
>
[ME] Movie extension
</Button>
<Button
data-tid="addAttribute[MPN]IntoInputButton"
className={styles.attributeButton}
onClick={() => this.addAttributeIntoInput('[MPN]')}
disabled={focusReference === undefined}
size="mini"
>
[MPN] MoviePrint name
</Button>
<Button
data-tid="addAttribute[FN]IntoInputButton"
className={styles.attributeButton}
onClick={() => this.addAttributeIntoInput('[FN]')}
disabled={focusReference === undefined}
size="mini"
>
[FN] Frame number
</Button>
<Button
data-tid="addAttribute[TC]IntoInputButton"
className={styles.attributeButton}
onClick={() => this.addAttributeIntoInput('[TC]')}
disabled={focusReference === undefined}
size="mini"
>
[TC] Timecode
</Button>
</Grid.Column>
</Grid.Row>
</Grid>
</Accordion.Content>
<Accordion.Title active={activeIndex === 4} index={4} onClick={this.handleClick}>
<Icon name="dropdown" />
Face detection
</Accordion.Title>
<Accordion.Content active={activeIndex === 4}>
<Grid padded inverted>
<Grid.Row>
<Grid.Column width={4}>Face confidence threshold</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
data-tid="faceConfidenceThresholdSlider"
className={styles.slider}
min={0}
max={100}
defaultValue={defaultFaceConfidenceThreshold}
marks={{
0: '0',
50: '50',
100: '100',
}}
handle={handle}
onChange={onChangeFaceConfidenceThreshold}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Face size threshold</Grid.Column>
<Grid.Column width={12}>
<SliderWithTooltip
data-tid="faceSizeThresholdSlider"
className={styles.slider}
min={0}
max={100}
defaultValue={defaultFaceSizeThreshold}
marks={{
0: '0',
50: '50',
100: '100',
}}
handle={handle}
onChange={onChangeFaceSizeThreshold}
/>
<br />
<em>Changes take effect on next face scan.</em>
</Grid.Column>
</Grid.Row>
</Grid>
</Accordion.Content>
<Accordion.Title active={activeIndex === 5} index={5} onClick={this.handleClick}>
<Icon name="dropdown" />
Frame cache
</Accordion.Title>
<Accordion.Content active={activeIndex === 5}>
<Grid padded inverted>
<Grid.Row>
<Grid.Column width={4}>Max size</Grid.Column>
<Grid.Column width={12}>
<Dropdown
data-tid="changeCachedFramesSizeDropdown"
placeholder="Select..."
selection
options={CACHED_FRAMES_SIZE_OPTIONS}
defaultValue={defaultCachedFramesSize}
onChange={this.onChangeCachedFramesSize}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4} />
<Grid.Column width={12}>
<Popup
trigger={
<Button data-tid="updateFrameCacheBtn" onClick={recaptureAllFrames}>
Update frame cache
</Button>
}
mouseEnterDelay={1000}
on={['hover']}
position="bottom center"
className={stylesPop.popup}
content="Recapture all frames and store it in the frame cache (uses max size)"
/>
</Grid.Column>
</Grid.Row>
</Grid>
</Accordion.Content>
<Accordion.Title active={activeIndex === 6} index={6} onClick={this.handleClick}>
<Icon name="dropdown" />
Experimental
</Accordion.Title>
<Accordion.Content active={activeIndex === 6}>
<Grid padded inverted>
<Grid.Row>
<Grid.Column width={4}>Shot detection method</Grid.Column>
<Grid.Column width={12}>
<Dropdown
data-tid="shotDetectionMethodOptionsDropdown"
placeholder="Select..."
selection
options={SHOT_DETECTION_METHOD_OPTIONS}
defaultValue={defaultShotDetectionMethod}
onChange={this.onChangeShotDetectionMethod}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Detection chart</Grid.Column>
<Grid.Column width={12}>
<Popup
trigger={
<Button
data-tid="showDetectionChartBtn"
// fluid
onClick={onToggleDetectionChart}
>
{showChart ? 'Hide detection chart' : 'Show detection chart'}
</Button>
}
mouseEnterDelay={1000}
on={['hover']}
position="bottom center"
className={stylesPop.popup}
content="Show detection chart with mean and difference values per frame"
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Import options</Grid.Column>
<Grid.Column width={12}>
<Checkbox
data-tid="automaticDetectionInOutPointCheckbox"
label={<label className={styles.label}>Automatic detection of In and Outpoint</label>}
checked={defaultDetectInOutPoint}
onChange={this.onChangeDetectInOutPoint}
/>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column width={4}>Expert</Grid.Column>
<Grid.Column width={12}>
<Checkbox
data-tid="showSlidersCheckbox"
label={<label className={styles.label}>Show input field instead of slider</label>}
checked={!this.state.showSliders}
onChange={this.onShowSliders}
/>
</Grid.Column>
</Grid.Row>
</Grid>
</Accordion.Content>
</Accordion>
</Grid.Column>
</Grid.Row>
</Grid>
</Container>
);
}
}
SettingsList.contextTypes = {
store: PropTypes.object,
};
export default SettingsList;
| 1.515625 | 2 |
src/__tests__/Button.js | hichroma/priceline-design-system | 0 | 3031 | import React from 'react'
import renderer from 'react-test-renderer'
import { Button, theme } from '..'
describe('Button', () => {
test('renders', () => {
const json = renderer.create(<Button />).toJSON()
expect(json).toMatchSnapshot()
})
test('size small sets height and font-size', () => {
const json = renderer.create(<Button size="small" />).toJSON()
expect(json).toMatchSnapshot()
expect(json).toHaveStyleRule('height', '32px')
expect(json).toHaveStyleRule('font-size', '12px')
expect(json).toHaveStyleRule('background-color', theme.colors.blue)
expect(json).toHaveStyleRule('color', theme.colors.white)
})
test('size medium sets height and font-size', () => {
const json = renderer.create(<Button size="medium" />).toJSON()
expect(json).toMatchSnapshot()
expect(json).toHaveStyleRule('height', '40px')
expect(json).toHaveStyleRule('font-size', '14px')
})
test('size large sets height and font-size', () => {
const json = renderer.create(<Button size="large" />).toJSON()
expect(json).toMatchSnapshot()
expect(json).toHaveStyleRule('height', '48px')
expect(json).toHaveStyleRule('font-size', '16px')
})
test('fullWidth prop sets width to 100%', () => {
const json = renderer.create(<Button fullWidth />).toJSON()
expect(json).toMatchSnapshot()
expect(json).toHaveStyleRule('width', '100%')
})
test('disabled prop sets', () => {
const json = renderer.create(<Button disabled />).toJSON()
expect(json).toMatchSnapshot()
expect(json).toHaveStyleRule('background-color', theme.colors.blue)
})
test('without disabled prop sets', () => {
const json = renderer.create(<Button />).toJSON()
expect(json).toMatchSnapshot()
expect(json).toHaveStyleRule('background-color', theme.colors.darkBlue, {
modifier: ':hover'
})
})
})
| 1.554688 | 2 |
src/index.js | davidroyer/v-editor | 0 | 3039 | // import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import VEditor from './VEditor.vue'
export default VEditor
| 0.457031 | 0 |
node_modules/replace-in-file/lib/replace-in-file.js | kube-HPC/load-version | 1 | 3047 | 'use strict';
/**
* Dependencies
*/
const chalk = require('chalk');
const parseConfig = require('./helpers/parse-config');
const getPathsSync = require('./helpers/get-paths-sync');
const getPathsAsync = require('./helpers/get-paths-async');
const replaceSync = require('./helpers/replace-sync');
const replaceAsync = require('./helpers/replace-async');
/**
* Replace in file helper
*/
function replaceInFile(config, cb) {
//Parse config
try {
config = parseConfig(config);
}
catch (error) {
if (cb) {
return cb(error, null);
}
return Promise.reject(error);
}
//Get config
const {
files, from, to, encoding, ignore, allowEmptyPaths, disableGlobs,
dry, verbose, glob,
} = config;
//Dry run?
//istanbul ignore if: No need to test console logs
if (dry && verbose) {
console.log(chalk.yellow('Dry run, not making actual changes'));
}
//Find paths
return getPathsAsync(files, ignore, disableGlobs, allowEmptyPaths, glob)
//Make replacements
.then(paths => Promise.all(paths.map(file => {
return replaceAsync(file, from, to, encoding, dry);
})))
//Convert results to array of changed files
.then(results => {
return results
.filter(result => result.hasChanged)
.map(result => result.file);
})
//Success handler
.then(changedFiles => {
if (cb) {
cb(null, changedFiles);
}
return changedFiles;
})
//Error handler
.catch(error => {
if (cb) {
cb(error);
}
else {
throw error;
}
});
}
/**
* Sync API
*/
replaceInFile.sync = function(config) {
//Parse config
config = parseConfig(config);
//Get config, paths, and initialize changed files
const {
files, from, to, encoding, ignore, disableGlobs, dry, verbose, glob,
} = config;
const paths = getPathsSync(files, ignore, disableGlobs, glob);
const changedFiles = [];
//Dry run?
//istanbul ignore if: No need to test console logs
if (dry && verbose) {
console.log(chalk.yellow('Dry run, not making any changes'));
}
//Process synchronously
paths.forEach(path => {
if (replaceSync(path, from, to, encoding, dry)) {
changedFiles.push(path);
}
});
//Return changed files
return changedFiles;
};
//Export
module.exports = replaceInFile;
| 1.492188 | 1 |
packages/1985/05/31/index.js | antonmedv/year | 7 | 3055 | module.exports = new Date(1985, 4, 31)
| 0.030518 | 0 |
wildcard-js/two.js | snowpackjs/export-map-test | 0 | 3063 | // ./wildcard-ext/two.js
| -0.068848 | 0 |
src/main/webapp/mock/BillMock.js | alvin198761/erp_laozhang | 0 | 3071 | /*开票信息模拟数据},作者:唐植超,日期:2018-11-27 14:04:59*/
'use strict';
var Mock = require('mockjs')
var Random = Mock.Random;
module.exports = {
'POST /api/bill/queryPage': function (req, res, next) {
var data = Mock.mock({
'content|10': [{
id: "@integer(100,200)",//主键
vendor_id: "@integer(100,200)",//供应商
bank: "@word(5,10)",// 开户行
account: "@word(5,10)",// 账号
taxpayer_no: "@word(5,10)",// 纳税人识别号
remark: "@word(5,10)",// 备注
}],
'number': '@integer(100,200)',
'size': 10,
'totalElements': 500,
});
setTimeout(function () {
res.json(data);
}, 500);
},
'POST /api/bill/update': function (req, res, next) {
setTimeout(function () {
res.json({});
}, 500);
},
'POST /api/bill/save': function (req, res, next) {
setTimeout(function () {
res.json({});
}, 500);
},
'POST /api/bill/queryList': function (req, res, next) {
var data = Mock.mock({
'content|10': [{
id: "@integer(100,200)",//主键
vendor_id: "@integer(100,200)",//供应商
bank: "@word(5,10)",// 开户行
account: "@word(5,10)",// 账号
taxpayer_no: "@word(5,10)",// 纳税人识别号
remark: "@word(5,10)",// 备注
}]
});
setTimeout(function () {
res.json(data.content);
}, 500);
},
'POST /api/bill/delete': function (req, res, next) {
setTimeout(function () {
res.json({});
}, 500);
},
} | 1.507813 | 2 |
src/components/Projects/AddProjectForm.js | lilian-n/defect-tracker-frontend | 0 | 3079 | import React from "react";
import { useDispatch } from "react-redux";
import { useAuth0 } from "@auth0/auth0-react";
import { useForm, Controller } from "react-hook-form";
import {
Form,
FormText,
Modal,
ModalHeader,
ModalBody,
ModalFooter,
Button,
FormGroup,
Label,
Input
} from "reactstrap";
import DateTimePicker from "react-widgets/lib/DateTimePicker"
import { addProject } from "../../redux-store/projectSlice";
const AddProjectForm = ({ open, setOpen }) => {
// set default values for react hook form
const defaultValues = {
projectTitle: "",
projectDescription: "",
projectStartDate: new Date(),
projectTargetEndDate: null
}
const dispatch = useDispatch();
const { getAccessTokenSilently } = useAuth0();
const { register, errors, handleSubmit, control } = useForm({ defaultValues });
function handleClose() {
setOpen(false);
}
async function onSubmit(data) {
const token = await getAccessTokenSilently();
const newValues = {
token,
title: data.projectTitle,
description: data.projectDescription,
startDate: data.projectStartDate,
targetEndDate: data.projectTargetEndDate
}
dispatch(addProject(newValues))
setOpen(false);
}
return (
<Modal isOpen={open} toggle={handleClose} backdrop="static">
<Form onSubmit={handleSubmit(onSubmit)}>
<ModalHeader toggle={handleClose}>Add a new project</ModalHeader>
<ModalBody>
<FormGroup>
<Label for="projectTitle">Project Title</Label>
<Input
type="text"
name="projectTitle"
innerRef={register({ required: true })}
/>
<FormText color="muted">
Required
</FormText>
<p style={{ color: "red" }}>{errors.projectTitle && "Project title is required."}</p>
</FormGroup>
<FormGroup>
<Label for="projectDescription">Project Description</Label>
<Input
type="text"
name="projectDescription"
id="projectDescription"
innerRef={register({ required: true })}
/>
<FormText color="muted">
Required
</FormText>
<p style={{ color: "red" }}>{errors.projectDescription && "Project description is required."}</p>
</FormGroup>
<FormGroup>
<Label for="projectStartDate">Project Start Date</Label>
<Controller
name="projectStartDate"
control={control}
register={register({ required: true })}
rules={{ required: true }}
render={props =>
<DateTimePicker
onChange={(e) => props.onChange(e)}
value={props.value}
format="MM/DD/YYYY"
time={false}
/>
}
/>
<FormText color="muted">
Required
</FormText>
<p style={{ color: "red" }}>{errors.projectStartDate && "Project start date is required."}</p>
</FormGroup>
<FormGroup>
<Label for="projectTargetEndDate">Project Target End Date</Label>
<Controller
name="projectTargetEndDate"
control={control}
register={register({ required: true })}
rules={{ required: true }}
render={props =>
<DateTimePicker
onChange={(e) => props.onChange(e)}
value={props.value}
format="MM/DD/YYYY"
time={false}
/>
}
/>
<FormText color="muted">
Required
</FormText>
<p style={{ color: "red" }}>{errors.projectTargetEndDate && "Project target end date is required."}</p>
</FormGroup>
</ModalBody>
<ModalFooter>
<Button color="danger" onClick={handleClose}>Cancel</Button>
<Button color="info" type="submit">Submit</Button>
</ModalFooter>
</Form>
</Modal>
);
}
export default AddProjectForm; | 1.554688 | 2 |
test/destroy.test.js | cafreeman/ember-cli-typescript-blueprint-polyfill | 0 | 3087 | /* eslint jest/expect-expect: ["error", { "assertFunctionNames": ["expect", "assertFilesExist", "assertFilesNotExist"] }] */
const { Project } = require('fixturify-project');
const path = require('path');
const execa = require('execa');
const fs = require('fs-extra');
const ROOT = process.cwd();
const EmberCLITargets = ['ember-cli-3-24', 'ember-cli-3-28', 'ember-cli'];
// const EmberCLITargets = ['ember-cli'];
describe('ember destroy', () => {
let fixturifyProject;
EmberCLITargets.forEach((target) => {
describe(`ember-cli: ${target}`, function () {
const cliBinPath = require.resolve(`${target}/bin/ember`);
function ember(args) {
return execa(cliBinPath, args);
}
beforeEach(() => {
fixturifyProject = new Project('best-ever', '0.0.0', {
files: {},
});
fixturifyProject.linkDevDependency('ember-cli', {
baseDir: __dirname,
resolveName: target,
});
addAddon('my-addon', '1.0.0', (addon) => {
addon.files.blueprints = {
'my-blueprint': {
'index.js': `
const typescriptBlueprintPolyfill = require('ember-cli-typescript-blueprint-polyfill');
module.exports = {
shouldTransformTypeScript: true,
init() {
this._super && this._super.init.apply(this, arguments);
typescriptBlueprintPolyfill(this);
}
}
`,
files: {
app: {
'my-blueprints': {
'__name__.ts': `export default function <%= camelizedModuleName %>(a: string, b: number): string {
return a + b;
}
`,
},
},
},
},
};
});
});
afterEach(() => {
process.chdir(ROOT);
fixturifyProject.dispose();
});
function addAddon(name, version, callback = () => {}) {
let addon = fixturifyProject.addDevDependency(name, version, {
files: {
'index.js': `module.exports = { name: require("./package").name };`,
},
});
addon.pkg.keywords.push('ember-addon');
addon.pkg['ember-addon'] = {};
addon.linkDependency('ember-cli-typescript-blueprint-polyfill', {
target: path.join(__dirname, '..'),
});
callback(addon);
}
function assertFilesExist(files) {
files.forEach((file) => {
expect(fs.pathExistsSync(file)).toBe(true);
});
}
async function assertFilesNotExist(files) {
files.forEach((file) => {
expect(fs.pathExistsSync(file)).toBe(false);
});
}
describe('with flags', () => {
beforeEach(() => {
fixturifyProject.writeSync();
process.chdir(fixturifyProject.baseDir);
});
test('it deletes JS files generated from typescript blueprints and transformed', async () => {
const files = ['app/my-blueprints/foo.js'];
await ember(['generate', 'my-blueprint', 'foo']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo']);
assertFilesNotExist(files);
});
it('deletes TS files generated from typescript blueprints with --typescript', async function () {
const files = ['app/my-blueprints/foo.ts'];
await ember(['generate', 'my-blueprint', 'foo', '--typescript']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo']);
assertFilesNotExist(files);
});
it('deletes TS files generated from typescript blueprints when --typescript is passed', async function () {
const files = ['app/my-blueprints/foo.ts'];
await ember(['generate', 'my-blueprint', 'foo', '--typescript']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo', '--typescript']);
assertFilesNotExist(files);
});
it('does not delete anything if --typescript is passed and there are no TS files', async function () {
const files = ['app/my-blueprints/foo.js'];
await ember(['generate', 'my-blueprint', 'foo']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo', '--typescript']);
assertFilesExist(files);
});
it('does not delete anything if --no-typescript is passed and there are no JS files', async function () {
const files = ['app/my-blueprints/foo.ts'];
await ember(['generate', 'my-blueprint', 'foo', '--typescript']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo', '--no-typescript']);
assertFilesExist(files);
});
describe('when JS and TS files are present', function () {
it('deletes the TS file when --typescript is passed', async function () {
const files = [
'app/my-blueprints/foo.ts',
'app/my-blueprints/foo.js',
];
const [tsFile, jsFile] = files;
await ember(['generate', 'my-blueprint', 'foo']);
await ember(['generate', 'my-blueprint', 'foo', '--typescript']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo', '--typescript']);
assertFilesNotExist([tsFile]);
assertFilesExist([jsFile]);
});
it('deletes the JS file when --no-typescript flag is passed', async function () {
const files = [
'app/my-blueprints/foo.ts',
'app/my-blueprints/foo.js',
];
const [tsFile, jsFile] = files;
await ember(['generate', 'my-blueprint', 'foo']);
await ember(['generate', 'my-blueprint', 'foo', '--typescript']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo', '--no-typescript']);
assertFilesExist([tsFile]);
assertFilesNotExist([jsFile]);
});
it('deletes both files when no flags are passed', async function () {
const files = [
'app/my-blueprints/foo.ts',
'app/my-blueprints/foo.js',
];
await ember(['generate', 'my-blueprint', 'foo']);
await ember(['generate', 'my-blueprint', 'foo', '--typescript']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo']);
assertFilesNotExist(files);
});
});
});
describe('with project config', () => {
it('deletes TS files generated from typescript blueprints in a typescript project', async function () {
const files = ['app/my-blueprints/foo.ts'];
fixturifyProject.files['.ember-cli'] = JSON.stringify({
isTypeScriptProject: true,
});
fixturifyProject.writeSync();
process.chdir(fixturifyProject.baseDir);
await ember(['generate', 'my-blueprint', 'foo']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo']);
assertFilesNotExist(files);
});
it('deletes TS files generated from typescript blueprints when {typescript: true} is present in .ember-cli', async function () {
const files = ['app/my-blueprints/foo.ts'];
fixturifyProject.files['.ember-cli'] = JSON.stringify({
typescript: true,
});
fixturifyProject.writeSync();
process.chdir(fixturifyProject.baseDir);
await ember(['generate', 'my-blueprint', 'foo']);
assertFilesExist(files);
await ember(['destroy', 'my-blueprint', 'foo']);
assertFilesNotExist(files);
});
});
});
});
});
| 1.289063 | 1 |
src/components/icons/solid/VenusMars.js | MythicalFish/mythical.fish | 2 | 3095 | import React from 'react'
const VenusMars = props => (
<svg
fill='currentColor'
viewBox='0 0 576 512'
width='1em'
height='1em'
{...props}
>
<path d='M564 0h-79c-10.7 0-16 12.9-8.5 20.5l16.9 16.9-48.7 48.7C422.5 72.1 396.2 64 368 64c-33.7 0-64.6 11.6-89.2 30.9 14 16.7 25 36 32.1 57.1 14.5-14.8 34.7-24 57.1-24 44.1 0 80 35.9 80 80s-35.9 80-80 80c-22.3 0-42.6-9.2-57.1-24-7.1 21.1-18 40.4-32.1 57.1 24.5 19.4 55.5 30.9 89.2 30.9 79.5 0 144-64.5 144-144 0-28.2-8.1-54.5-22.1-76.7l48.7-48.7 16.9 16.9c2.4 2.4 5.4 3.5 8.4 3.5 6.2 0 12.1-4.8 12.1-12V12c0-6.6-5.4-12-12-12zM144 64C64.5 64 0 128.5 0 208c0 68.5 47.9 125.9 112 140.4V400H76c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h36v36c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12v-36h36c6.6 0 12-5.4 12-12v-40c0-6.6-5.4-12-12-12h-36v-51.6c64.1-14.6 112-71.9 112-140.4 0-79.5-64.5-144-144-144zm0 224c-44.1 0-80-35.9-80-80s35.9-80 80-80 80 35.9 80 80-35.9 80-80 80z' />
</svg>
)
export default VenusMars
| 1.484375 | 1 |
src/v1/endpoints/items/index.js | ekpo-d/cp-api-javascript-client | 1 | 3103 | import express from 'express';
import validate from 'is-express-schema-valid';
import Item from '../../models/Item';
import errors from '../../../utils/errors';
import validateAccessToken from '../../../middleware/validateAccessToken';
import validateUserRole from '../../../middleware/validateUserRole';
import { itemSchema } from './schemas';
export default function () {
var router = express.Router();
router.post('/',
validateAccessToken,
validateUserRole('artist'),
validate(itemSchema),
createItem,
returnItem
);
router.get('/:id',
validateAccessToken,
findItemById,
returnItem
);
router.put('/:id',
validateAccessToken,
validateUserRole('artist'),
validate(itemSchema),
findItemById,
updateItem,
returnItem
);
router.delete('/:id',
validateAccessToken,
validateUserRole('artist'),
findItemById,
deleteItem
);
async function createItem (req, res, next) {
try {
const itemData = Object.assign({}, req.body, {owner: req.email});
req.item = await Item.create(itemData);
next();
} catch (err) {
next(err);
}
}
async function findItemById (req, res, next) {
try {
req.item = await Item.findById(req.params.id);
if (!req.item) {
return next(new errors.NotFound('Item not found'));
}
next();
} catch (err) {
next(err);
}
}
async function updateItem (req, res, next) {
try {
req.item = await Item.update(req.item, req.body);
next();
} catch (err) {
next(err);
}
}
async function deleteItem (req, res, next) {
try {
await Item.remove(req.params.id);
res.sendStatus(204);
} catch (err) {
next(err);
}
}
function returnItem (req, res) {
res.json(Item.transformResponse(req.item));
}
return router;
}
| 1.59375 | 2 |
node_modules/@patternfly/react-tokens/dist/esm/c_notification_badge_m_read_after_BorderColor.js | jeffpuzzo/jp-rosa-react-form-wizard | 0 | 3111 | export const c_notification_badge_m_read_after_BorderColor = {
"name": "--pf-c-notification-badge--m-read--after--BorderColor",
"value": "transparent",
"var": "var(--pf-c-notification-badge--m-read--after--BorderColor)"
};
export default c_notification_badge_m_read_after_BorderColor; | 0.333984 | 0 |
forms-flow-web/src/components/ServiceFlow/constants/taskConstants.js | gitter-badger/forms-flow-ai | 0 | 3119 | export const sortingList = [
{sortBy:"created",label:"Created", sortOrder:"asc"},
{sortBy:"priority",label:"Priority", sortOrder:"asc"},
{sortBy:"dueDate",label:"Due date", sortOrder:"asc"},
{sortBy:"assignee",label:"Assignee", sortOrder:"asc"},
{sortBy:"name",label:"Task name", sortOrder:"asc"},
{sortBy:"followUpDate",label:"Follow-up date", sortOrder:"asc"},
];
export const searchData = [
{"label": "Task Variables", "compares": [">", ">=", "=","!=", "<", "<="]},
{"label": "Process Variables", "compares": [">", ">=", "=","!=", "<", "<="]},
{"label": "Process Definition Name", "compares": ["like", "="], "values": ["processDefinitionNameLike", "processDefinitionName"]},
{"label": "Assignee", "compares": ["like", "="], "values": ["assigneeLike", "assignee"]},
{"label":"Candidate Group", "compares": ["="], "values": ["candidateGroup"]},
{"label":"Candidate User", "compares": ["="], "values": ["candidateUser"]},
{"label":"Name", "compares": ["like", "="], "values": ["nameLike", "name"]},
{"label": "Description","compares": ["like", "="], "values": ["descriptionLike", "description"] },
{"label":"Priority", "compares": ["="], "values": ["priority"]},
{"label":"Due Date", "compares": ["before", "after"], "values": ["due"]},
{"label":"Follow up Date", "compares": ["before", "after"], "values": ["followUp"]},
{"label":"Created", "compares": ["before", "after"], "values": ["created"]},
]
export const Filter_Search_Types = {
VARIABLES:"variables",
STRING:"string",
DATE:"date",
NORMAL:"normal"
}
export const FILTER_OPERATOR_TYPES = {
EQUAL:"=",
LIKE:"like",
BEFORE:"before",
AFTER:"after"
}
//TODO update to further constants
export const FILTER_COMPARE_OPTIONS = {
[Filter_Search_Types.VARIABLES]:[">", ">=", FILTER_OPERATOR_TYPES.EQUAL ,"!=", "<", "<=",FILTER_OPERATOR_TYPES.LIKE],
[Filter_Search_Types.DATE]:[FILTER_OPERATOR_TYPES.BEFORE, FILTER_OPERATOR_TYPES.AFTER],
[Filter_Search_Types.STRING]:[FILTER_OPERATOR_TYPES.EQUAL,FILTER_OPERATOR_TYPES.LIKE],
[Filter_Search_Types.NORMAL]:[FILTER_OPERATOR_TYPES.EQUAL]
};
export const taskFilters = [
{label:"Process Variables",key:"processVariables", operator:FILTER_OPERATOR_TYPES.EQUAL, type:Filter_Search_Types.VARIABLES, value:"", name:""},
{label:"Task Variables", key:"taskVariables",operator:FILTER_OPERATOR_TYPES.EQUAL, type:Filter_Search_Types.VARIABLES, value:"", name:""},
{label:"Process Definition Name",key:"processDefinitionName", operator:FILTER_OPERATOR_TYPES.LIKE, type:Filter_Search_Types.STRING, value:"" },
{label:"Assignee",key:"assignee",operator:FILTER_OPERATOR_TYPES.LIKE, type:Filter_Search_Types.STRING,value:"", },
{label:"Candidate Group",key:"candidateGroup",operator:FILTER_OPERATOR_TYPES.EQUAL,type:Filter_Search_Types.NORMAL, value:""},
{label:"Candidate User",key:"candidateUser",operator:FILTER_OPERATOR_TYPES.EQUAL,type:Filter_Search_Types.NORMAL, value:""},
{label:"Name",key:"name",operator:FILTER_OPERATOR_TYPES.LIKE,type:Filter_Search_Types.STRING,value:""},
{label:"Description",key:"description",operator:FILTER_OPERATOR_TYPES.LIKE,type:Filter_Search_Types.STRING, value:""},
{label:"Priority",key:"priority",operator:FILTER_OPERATOR_TYPES.EQUAL,type:Filter_Search_Types.NORMAL, value:""},
{label:"Due Date",key:"due",operator:FILTER_OPERATOR_TYPES.BEFORE, type:Filter_Search_Types.DATE, value:""},
{label:"Follow up Date",key:"followUp",operator:FILTER_OPERATOR_TYPES.BEFORE, type:Filter_Search_Types.DATE, value:""},
{label:"Created",key:"created",operator:FILTER_OPERATOR_TYPES.BEFORE,type:Filter_Search_Types.DATE, value:"" },
];
export const ALL_TASKS="All tasks"
export const QUERY_TYPES= {ANY:"ANY",ALL:"ALL"};
| 0.914063 | 1 |
LightTemperatureSensor/lib/STM32 B_LUX_D_V32/CMSIS/Documentation/Core/html/search/groups_64.js | zhangxinhui02/ArduinoProjects | 1 | 3127 | var searchData=
[
['debug_20access',['Debug Access',['../group___i_t_m___debug__gr.html',1,'']]]
];
| -0.373047 | 0 |
src/shared/configure-store.js | graymur/rcn.io | 47 | 3135 | import { createStore, applyMiddleware, compose } from 'redux'
import rootReducer from 'shared/reducers/reducer.js'
import createSagaMiddleware from 'redux-saga'
import rootSaga from 'shared/sagas/root'
import { browserHistory } from 'react-router'
import { routerMiddleware as createRouterMiddleware } from 'react-router-redux'
const routingMiddlewhare = createRouterMiddleware(browserHistory)
const sagaMiddleware = createSagaMiddleware()
const middlewares = [
sagaMiddleware,
// used to process routing actions like push() and replace() (navigaiton with redux actions)
// it's not required for routing to work with redux if actions are not used
routingMiddlewhare
]
// use logging middleware only in dev mode
if (process.env.NODE_ENV === 'development') {
const createLogger = require('redux-logger')
const logger = createLogger({
diff: false, //diff it adds like 1s overhead for 300-400 events
timestamp: false,
duration: true,
collapsed: true,
colors: {
title: (action) => '#EEE',
prevState: (state) => '#9e9e9e',
action: (action) => 'yellowgreen',
nextState: (state) => '#98AFC7'
}
})
middlewares.push(logger)
// const reactPerfMiddleware = require('shared/middlewares/react-perf-middleware').default
// middlewares.push(reactPerfMiddleware)
}
const configureStore = (initialState) => {
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(...middlewares), //logger must be last middleware,
// server-side safe enabling of Redux Dev tools
typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f
)
)
sagaMiddleware.run(rootSaga)
//according to https://github.com/reactjs/react-redux/releases/tag/v2.0.0
if (module.hot) {
// Enable Webpack hot module replacement for reducers
module.hot.accept('shared/reducers/reducer.js', () => {
const nextRootReducer = require('shared/reducers/reducer.js').default
store.replaceReducer(nextRootReducer)
})
}
return store
}
export default configureStore
| 1.46875 | 1 |
src/index.js | sergiirocks/babel-plugin-transform-ui5 | 2 | 3143 | import template from 'babel-template';
import Path from 'path';
const buildDefine = template(`
VARS;
sap.ui.define(MODULE_NAME, [SOURCES], FACTORY);
`);
const buildFactory = template(`
(function (PARAMS) {
BODY;
})
`);
exports.default = function({ types: t }) {
const ui5ModuleVisitor = {
Program: {
enter: (path, state) => {
const filePath = Path.resolve(path.hub.file.opts.filename);
const sourceRootPath = getSourceRoot(path);
let relativeFilePath = null;
let relativeFilePathWithoutExtension = null;
let namespace = null;
if (filePath.startsWith(sourceRootPath)) {
relativeFilePath = Path.relative(sourceRootPath, filePath);
relativeFilePathWithoutExtension =
Path.dirname(relativeFilePath) + Path.sep + Path.basename(relativeFilePath, Path.extname(relativeFilePath));
relativeFilePathWithoutExtension = relativeFilePathWithoutExtension.replace(/\\/g, '/');
const parts = relativeFilePath.split(Path.sep);
if (parts.length <= 1) {
namespace = relativeFilePath;
} else {
parts.pop();
namespace = parts.join('.');
}
}
if (!path.state) {
path.state = {};
}
path.state.ui5 = {
filePath,
relativeFilePath,
relativeFilePathWithoutExtension,
namespace,
className: null,
fullClassName: null,
superClassName: null,
imports: [],
staticMembers: [],
returnValue: false
};
},
exit(path) {
const state = path.state.ui5;
const hasUi5 = state.returnValue || state.imports.length;
if (hasUi5) {
const { node } = path;
const factoryBody = state.imports.map(i => {
if (i.isLib) {
i.path.remove();
}
return t.assignmentExpression('=', t.identifier(i.name), i.tmpName);
});
if (state.returnValue) {
factoryBody.push(t.returnStatement(state.returnValue));
}
const factory = buildFactory({
PARAMS: state.imports.map(i => i.tmpName),
BODY: factoryBody
});
let factoryInsertIndex = 0;
for (let i = 0, target = node.body; i < target.length; i++) {
if (target[i].type !== 'ImportDeclaration') {
factoryInsertIndex = i + 1;
break;
}
}
const define = buildDefine({
VARS: state.imports
.map(i => t.identifier(i.name))
.map(i => t.variableDeclaration('var', [t.variableDeclarator(i)])),
MODULE_NAME: t.stringLiteral(state.relativeFilePathWithoutExtension),
SOURCES: state.imports.map(i => t.stringLiteral(i.src)),
FACTORY: factory
});
node.body.splice(factoryInsertIndex, 0, ...define);
}
}
},
ImportDeclaration: (path, { opts }) => {
const state = path.state.ui5;
const node = path.node;
const sourceRootPath = getSourceRoot(path);
let name = null;
let srcRaw = node.source.value;
let srcPath = null;
if (srcRaw.startsWith('./') || srcRaw.startsWith('../')) {
srcPath = Path.normalize(Path.resolve(Path.dirname(state.filePath), srcRaw));
srcRaw = Path.relative(sourceRootPath, srcPath);
}
const srcNormalized = Path.normalize(srcRaw);
const src = srcNormalized.replace(/\\/g, '/');
if (node.specifiers && node.specifiers.length === 1) {
name = node.specifiers[0].local.name;
} else {
const parts = srcNormalized.split(Path.sep);
name = parts[parts.length - 1];
}
if (node.leadingComments) {
state.leadingComments = node.leadingComments;
}
const testLibs = opts.libs || ['^sap/'];
const isLibRE = testLibs.length && new RegExp(`(${testLibs.join('|')})`);
const isLib = isLibRE.test(src);
const testSrc = (opts.libs || ['^sap/']).concat(opts.files || []);
const isUi5SrcRE = testSrc.length && new RegExp(`(${testSrc.join('|')})`);
const isUi5Src = isUi5SrcRE.test(src);
if (isLib || isUi5Src) {
const tmpName = path.scope.generateUidIdentifierBasedOnNode(t.identifier(name));
const imp = {
path,
name,
tmpName,
isLib,
isUi5Src,
src
};
state.imports.push(imp);
}
},
ExportDeclaration: path => {
const state = path.state.ui5;
if (!path.node.declaration) {
return;
}
const id = path.node.declaration.id;
const leadingComments = path.node.leadingComments;
if (path.node.declaration.type === 'ClassDeclaration') {
state.returnValue = transformClass(path.node.declaration, state);
path.remove();
}
return;
const defineCallArgs = [
t.stringLiteral(state.relativeFilePathWithoutExtension),
t.arrayExpression(state.imports.map(i => t.stringLiteral(i.src))),
t.functionExpression(
null,
state.imports.map(i => t.identifier(i.name)),
t.blockStatement([
t.expressionStatement(t.stringLiteral('use strict')),
t.returnStatement(transformClass(path.node.declaration, program, state))
])
)
];
const defineCall = t.callExpression(t.identifier('sap.ui.define'), defineCallArgs);
if (state.leadingComments) {
defineCall.leadingComments = state.leadingComments;
}
path.replaceWith(defineCall);
// Add static members
for (let key in state.staticMembers) {
const id = t.identifier(state.fullClassName + '.' + key);
const statement = t.expressionStatement(t.assignmentExpression('=', id, state.staticMembers[key]));
path.insertAfter(statement);
}
},
CallExpression(path) {
const state = path.state.ui5;
const node = path.node;
if (node.callee.type === 'Super') {
if (!state.superClassName) {
this.errorWithNode("The keyword 'super' can only used in a derrived class.");
}
const identifier = t.identifier(state.superClassName + '.apply');
let args = t.arrayExpression(node.arguments);
if (
node.arguments.length === 1 &&
node.arguments[0].type === 'Identifier' &&
node.arguments[0].name === 'arguments'
) {
args = t.identifier('arguments');
}
path.replaceWith(t.callExpression(identifier, [t.identifier('this'), args]));
} else if (node.callee.object && node.callee.object.type === 'Super') {
if (!state.superClassName) {
this.errorWithNode("The keyword 'super' can only used in a derrived class.");
}
const identifier = t.identifier(
state.superClassName + '.prototype' + '.' + node.callee.property.name + '.apply'
);
path.replaceWith(t.callExpression(identifier, [t.identifier('this'), t.arrayExpression(node.arguments)]));
}
}
};
function transformClass(node, state) {
if (node.type !== 'ClassDeclaration') {
return node;
} else {
resolveClass(node, state);
const props = [];
node.body.body.forEach(member => {
if (member.type === 'ClassMethod') {
const func = t.functionExpression(null, member.params, member.body);
if (!member.static) {
func.generator = member.generator;
func.async = member.async;
props.push(t.objectProperty(member.key, func));
} else {
func.body.body.unshift(t.expressionStatement(t.stringLiteral('use strict')));
state.staticMembers[member.key.name] = func;
}
} else if (member.type == 'ClassProperty') {
if (!member.static) {
props.push(t.objectProperty(member.key, member.value));
} else {
state.staticMembers[member.key.name] = member.value;
}
}
});
const bodyJSON = t.objectExpression(props);
const extendCallArgs = [t.stringLiteral(state.fullClassName), bodyJSON];
const extendCall = t.callExpression(t.identifier(state.superClassName + '.extend'), extendCallArgs);
return extendCall;
}
}
function resolveClass(node, state) {
state.className = node.id.name;
state.superClassName = node.superClass.name;
if (state.namespace) {
state.fullClassName = state.namespace + '.' + state.className;
} else {
state.fullClassName = state.className;
}
}
function getSourceRoot(path) {
let sourceRootPath = null;
if (path.hub.file.opts.sourceRoot) {
sourceRootPath = Path.resolve(path.hub.file.opts.sourceRoot);
} else {
sourceRootPath = Path.resolve('.' + Path.sep);
}
return sourceRootPath;
}
return {
name: 'transform-ui5',
visitor: ui5ModuleVisitor
};
};
module.exports = exports.default;
| 1.390625 | 1 |
frontend/src/components/UserTable.js | Lekesoldat/BACkup | 0 | 3151 | import React from 'react';
import { navigate } from '@reach/router';
import styled from 'styled-components';
import useRequest from '../hooks/useRequest';
const Table = styled.table`
border: 1px solid black;
border-collapse: collapse;
`;
const Row = styled.tr`
&:hover {
background-color: #e4e4e4;
cursor: pointer;
}
`;
const Th = styled.th`
border: 1px solid black;
padding: 1rem;
`;
const Td = styled.td`
text-align: center;
border: 1px solid black;
padding: 1rem;
`;
// A component for dynamically rendering users.
const UserTable = ({ data }) => {
const { request: startSession } = useRequest({
lazy: true,
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
}
});
return (
<>
<Table>
<thead>
<tr>
<Th>Name</Th>
<Th>Weight</Th>
<Th>Gender</Th>
<Th>Total Sessions</Th>
<Th>Total Drinks</Th>
<Th>Average</Th>
</tr>
</thead>
<tbody>
{data.map(u => {
return (
<Row
key={u.id}
onClick={async () => {
// Start a new drinking session when selecting the user.
await startSession({
path: `/api/users/${u.id}/session`
});
// Navigate to the tracker when the session is created.
await navigate(`/tracker/${u.id}`);
}}
>
<Td>{u.name}</Td>
<Td>{u.weight}</Td>
<Td>{u.gender}</Td>
<Td>{u.sessions.length}</Td>
<Td>
{u.sessions.reduce(
(prev, curr) => prev + curr.drinks.length,
0
)}
</Td>
<Td>
{!u.sessions.length
? 0
: Math.round(
u.sessions.reduce(
(prev, curr) => prev + curr.drinks.length,
0
) / u.sessions.length
)}
</Td>
</Row>
);
})}
</tbody>
</Table>
</>
);
};
export default UserTable;
| 1.84375 | 2 |
lib/helpers/assert.js | joriewong/factory-web | 0 | 3159 | "use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertFbiPaths = exports.assertFactoryTemplate = void 0;
const assert_1 = __importDefault(require("assert"));
const assertFactoryTemplate = (factory) => {
const assertFailLog = 'fbi factory.template field must one of "micro-main", "micro-react", "micro-vue", "react", "vue"';
const assertIsOk = factory &&
factory.template &&
['micro-main', 'micro-react', 'micro-vue', 'react', 'vue'].includes(factory.template);
assert_1.default(assertIsOk, assertFailLog);
};
exports.assertFactoryTemplate = assertFactoryTemplate;
const assertFbiPaths = () => {
const assertFailLog = '';
const assertIsOk = true;
assert_1.default(assertIsOk, assertFailLog);
};
exports.assertFbiPaths = assertFbiPaths;
| 1.257813 | 1 |
Documentation/html/search/all_0.js | AntoineHX/OMPL_Planning | 0 | 3167 | var searchData=
[
['checking_5fbox',['Checking_Box',['../struct_checking___box.html',1,'']]],
['checkpath',['checkPath',['../class_o_m_p_l___planner.html#a3e94f89db54c6b2c302b46ea2140d56b',1,'OMPL_Planner']]],
['controller',['Controller',['../classcontroller__turtlebot_1_1_controller.html',1,'controller_turtlebot']]],
['controller',['Controller',['../classcontroller__quadrotor_1_1_controller.html',1,'controller_quadrotor']]]
];
| 0.289063 | 0 |
assets/js/shortcodes/shortcodes.js | iamacceptable/evedant | 0 | 3175 | // Document ready actions for shortcodes
jQuery(document).ready(function(){
"use strict";
setTimeout(themerex_animation_shortcodes, 600);
});
// Animation
function themerex_animation_shortcodes() {
jQuery('[data-animation^="animated"]:not(.animated)').each(function() {
"use strict";
if (jQuery(this).offset().top < jQuery(window).scrollTop() + jQuery(window).height())
jQuery(this).addClass(jQuery(this).data('animation'));
});
}
// Shortcodes init
function themerex_init_shortcodes(container) {
// Accordion
if (container.find('.sc_accordion:not(.inited)').length > 0) {
container.find(".sc_accordion:not(.inited)").each(function () {
"use strict";
var init = jQuery(this).data('active');
if (isNaN(init)) init = 0;
else init = Math.max(0, init);
jQuery(this)
.addClass('inited')
.accordion({
active: init,
heightStyle: "content",
header: "> .sc_accordion_item > .sc_accordion_title",
create: function (event, ui) {
themerex_init_shortcodes(ui.panel);
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(ui.panel);
ui.header.each(function () {
jQuery(this).parent().addClass('sc_active');
});
},
activate: function (event, ui) {
themerex_init_shortcodes(ui.newPanel);
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(ui.newPanel);
ui.newHeader.each(function () {
jQuery(this).parent().addClass('sc_active');
});
ui.oldHeader.each(function () {
jQuery(this).parent().removeClass('sc_active');
});
}
});
});
}
// Contact form
if (container.find('.sc_contact_form:not(.inited) form').length > 0) {
container.find(".sc_contact_form:not(.inited) form")
.addClass('inited')
.submit(function(e) {
"use strict";
themerex_contact_form_validate(jQuery(this));
e.preventDefault();
return false;
});
}
//Countdown
if (container.find('.sc_countdown:not(.inited)').length > 0) {
container.find('.sc_countdown:not(.inited)')
.each(function () {
"use strict";
jQuery(this).addClass('inited');
var id = jQuery(this).attr('id');
var curDate = new Date();
var curDateTimeStr = curDate.getFullYear()+'-'+(curDate.getMonth()<9 ? '0' : '')+(curDate.getMonth()+1)+'-'+(curDate.getDate()<10 ? '0' : '')+curDate.getDate()
+' '+(curDate.getHours()<10 ? '0' : '')+curDate.getHours()+':'+(curDate.getMinutes()<10 ? '0' : '')+curDate.getMinutes()+':'+(curDate.getSeconds()<10 ? '0' : '')+curDate.getSeconds();
var interval = 1; //jQuery(this).data('interval');
var endDateStr = jQuery(this).data('date');
var endDateParts = endDateStr.split('-');
var endTimeStr = jQuery(this).data('time');
var endTimeParts = endTimeStr.split(':');
if (endTimeParts.length < 3) endTimeParts[2] = '00';
var endDateTimeStr = endDateStr+' '+endTimeStr;
if (curDateTimeStr < endDateTimeStr) {
jQuery(this).find('.sc_countdown_placeholder').countdown({
until: new Date(endDateParts[0], endDateParts[1]-1, endDateParts[2], endTimeParts[0], endTimeParts[1], endTimeParts[2]),
tickInterval: interval,
onTick: themerex_countdown
});
} else {
jQuery(this).find('.sc_countdown_placeholder').countdown({
since: new Date(endDateParts[0], endDateParts[1]-1, endDateParts[2], endTimeParts[0], endTimeParts[1], endTimeParts[2]),
tickInterval: interval,
onTick: themerex_countdown
});
}
});
}
// Emailer form
if (container.find('.sc_emailer:not(.inited)').length > 0) {
container.find(".sc_emailer:not(.inited)")
.addClass('inited')
.find('.sc_emailer_button')
.click(function(e) {
"use strict";
var form = jQuery(this).parents('form');
var parent = jQuery(this).parents('.sc_emailer');
if (parent.hasClass('sc_emailer_opened')) {
if (form.length>0 && form.find('input').val()!='') {
var group = jQuery(this).data('group');
var email = form.find('input').val();
var regexp = new RegExp(THEMEREX_GLOBALS['email_mask']);
if (!regexp.test(email)) {
form.find('input').get(0).focus();
themerex_message_warning(THEMEREX_GLOBALS['strings']['email_not_valid']);
} else {
jQuery.post(THEMEREX_GLOBALS['ajax_url'], {
action: 'emailer_submit',
nonce: THEMEREX_GLOBALS['ajax_nonce'],
group: group,
email: email
}).done(function(response) {
var rez = JSON.parse(response);
if (rez.error === '') {
themerex_message_info(THEMEREX_GLOBALS['strings']['email_confirm'].replace('%s', email));
form.find('input').val('');
} else {
themerex_message_warning(rez.error);
}
});
}
} else
form.get(0).submit();
} else {
parent.addClass('sc_emailer_opened');
}
e.preventDefault();
return false;
});
}
// Googlemap init
if (container.find('.sc_googlemap:not(.inited)').length > 0) {
container.find('.sc_googlemap:not(.inited)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
var map = jQuery(this).addClass('inited');
var map_address = map.data('address');
var map_latlng = map.data('latlng');
var map_id = map.attr('id');
var map_zoom = map.data('zoom');
var map_style = map.data('style');
var map_descr = map.data('description');
var map_title = map.data('title');
var map_point = map.data('point');
themerex_googlemap_init( jQuery('#'+map_id).get(0), {address: map_address , latlng: map_latlng, style: map_style, zoom: map_zoom, description: map_descr, title: map_title, point: map_point});
});
}
// Infoboxes
if (container.find('.sc_infobox.sc_infobox_closeable:not(.inited)').length > 0) {
container.find('.sc_infobox.sc_infobox_closeable:not(.inited)')
.addClass('inited')
.click(function () {
jQuery(this).slideUp();
});
}
// Popup links
if (container.find('.popup_link:not(.inited)').length > 0) {
container.find('.popup_link:not(.inited)')
.addClass('inited')
.magnificPopup({
type: 'inline',
removalDelay: 500,
midClick: true,
callbacks: {
beforeOpen: function () {
this.st.mainClass = 'mfp-zoom-in';
},
open: function() {},
close: function() {}
}
});
}
// Search form
if (container.find('.search_wrap:not(.inited)').length > 0) {
container.find('.search_wrap:not(.inited)').each(function() {
jQuery(this).addClass('inited');
jQuery(this).find('.search_icon').click(function(e) {
"use strict";
var search_wrap = jQuery(this).parent();
if (!search_wrap.hasClass('search_fixed')) {
if (search_wrap.hasClass('search_opened')) {
search_wrap.find('.search_form_wrap').animate({'width': 'hide'}, 200, function() {
if (search_wrap.parents('.menu_main_wrap').length > 0)
search_wrap.parents('.menu_main_wrap').removeClass('search_opened');
});
search_wrap.find('.search_results').fadeOut();
search_wrap.removeClass('search_opened');
} else {
search_wrap.find('.search_form_wrap').animate({'width': 'show'}, 200, function() {
jQuery(this).parents('.search_wrap').addClass('search_opened');
jQuery(this).find('input').get(0).focus();
});
if (search_wrap.parents('.menu_main_wrap').length > 0)
search_wrap.parents('.menu_main_wrap').addClass('search_opened');
}
} else {
search_wrap.find('.search_field').val('');
search_wrap.find('.search_results').fadeOut();
}
e.preventDefault();
return false;
});
jQuery(this).find('.search_results_close').click(function(e) {
"use strict";
jQuery(this).parent().fadeOut();
e.preventDefault();
return false;
});
jQuery(this).on('click', '.search_submit,.search_more', function(e) {
"use strict";
if (jQuery(this).parents('.search_wrap').find('.search_field').val() != '')
jQuery(this).parents('.search_wrap').find('.search_form_wrap form').get(0).submit();
e.preventDefault();
return false;
});
if (jQuery(this).hasClass('search_ajax')) {
var ajax_timer = null;
jQuery(this).find('.search_field').keyup(function(e) {
"use strict";
var search_field = jQuery(this);
var s = search_field.val();
if (ajax_timer) {
clearTimeout(ajax_timer);
ajax_timer = null;
}
if (s.length >= THEMEREX_GLOBALS['ajax_search_min_length']) {
ajax_timer = setTimeout(function() {
jQuery.post(THEMEREX_GLOBALS['ajax_url'], {
action: 'ajax_search',
nonce: THEMEREX_GLOBALS['ajax_nonce'],
text: s
}).done(function(response) {
clearTimeout(ajax_timer);
ajax_timer = null;
var rez = JSON.parse(response);
if (rez.error === '') {
search_field.parents('.search_ajax').find('.search_results_content').empty().append(rez.data);
search_field.parents('.search_ajax').find('.search_results').fadeIn();
} else {
themerex_message_warning(THEMEREX_GLOBALS['strings']['search_error']);
}
});
}, THEMEREX_GLOBALS['ajax_search_delay']);
}
});
}
});
}
// Section Pan init
if (container.find('.sc_pan:not(.inited_pan)').length > 0) {
container.find('.sc_pan:not(.inited_pan)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
var pan = jQuery(this).addClass('inited_pan');
var cont = pan.parent();
cont.mousemove(function(e) {
"use strict";
var anim = {};
var tm = 0;
var pw = pan.width(), ph = pan.height();
var cw = cont.width(), ch = cont.height();
var coff = cont.offset();
if (pan.hasClass('sc_pan_vertical'))
pan.css('top', -Math.floor((e.pageY - coff.top) / ch * (ph-ch)));
if (pan.hasClass('sc_pan_horizontal'))
pan.css('left', -Math.floor((e.pageX - coff.left) / cw * (pw-cw)));
});
cont.mouseout(function(e) {
pan.css({'left': 0, 'top': 0});
});
});
}
//Scroll
if (container.find('.sc_scroll:not(.inited)').length > 0) {
container.find('.sc_scroll:not(.inited)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
THEMEREX_GLOBALS['scroll_init_counter'] = 0;
themerex_init_scroll_area(jQuery(this));
});
}
// Swiper Slider
if (container.find('.sc_slider_swiper:not(.inited)').length > 0) {
container.find('.sc_slider_swiper:not(.inited)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
//if (jQuery(this).parents('.isotope_wrap:not(.inited)').length > 0) return;
jQuery(this).addClass('inited');
themerex_slider_autoheight(jQuery(this));
if (jQuery(this).parents('.sc_slider_pagination_area').length > 0) {
jQuery(this).parents('.sc_slider_pagination_area').find('.sc_slider_pagination .post_item').eq(0).addClass('active');
}
var id = jQuery(this).attr('id');
if (id == undefined) {
id = 'swiper_'+Math.random();
id = id.replace('.', '');
jQuery(this).attr('id', id);
}
jQuery(this).addClass(id);
jQuery(this).find('.slides .swiper-slide').css('position', 'relative');
if (THEMEREX_GLOBALS['swipers'] === undefined) THEMEREX_GLOBALS['swipers'] = {};
THEMEREX_GLOBALS['swipers'][id] = new Swiper('.'+id, {
calculateHeight: !jQuery(this).hasClass('sc_slider_height_fixed'),
resizeReInit: true,
autoResize: true,
loop: true,
grabCursor: true,
pagination: jQuery(this).hasClass('sc_slider_pagination') ? '#'+id+' .sc_slider_pagination_wrap' : false,
paginationClickable: true,
autoplay: jQuery(this).hasClass('sc_slider_noautoplay') ? false : (isNaN(jQuery(this).data('interval')) ? 7000 : jQuery(this).data('interval')),
autoplayDisableOnInteraction: false,
initialSlide: 0,
speed: 600,
// Autoheight on start
onFirstInit: function (slider){
var cont = jQuery(slider.container);
if (!cont.hasClass('sc_slider_height_auto')) return;
var li = cont.find('.swiper-slide').eq(1);
var h = li.data('height_auto');
if (h > 0) {
var pt = parseInt(li.css('paddingTop')), pb = parseInt(li.css('paddingBottom'));
li.height(h);
cont.height(h + (isNaN(pt) ? 0 : pt) + (isNaN(pb) ? 0 : pb));
cont.find('.swiper-wrapper').height(h + (isNaN(pt) ? 0 : pt) + (isNaN(pb) ? 0 : pb));
}
},
// Autoheight on slide change
onSlideChangeStart: function (slider){
var cont = jQuery(slider.container);
if (!cont.hasClass('sc_slider_height_auto')) return;
var idx = slider.activeIndex;
var li = cont.find('.swiper-slide').eq(idx);
var h = li.data('height_auto');
if (h > 0) {
var pt = parseInt(li.css('paddingTop')), pb = parseInt(li.css('paddingBottom'));
li.height(h);
cont.height(h + (isNaN(pt) ? 0 : pt) + (isNaN(pb) ? 0 : pb));
cont.find('.swiper-wrapper').height(h + (isNaN(pt) ? 0 : pt) + (isNaN(pb) ? 0 : pb));
}
},
// Change current item in 'full' or 'over' pagination wrap
onSlideChangeEnd: function (slider, dir) {
var cont = jQuery(slider.container);
if (cont.parents('.sc_slider_pagination_area').length > 0) {
var li = cont.parents('.sc_slider_pagination_area').find('.sc_slider_pagination .post_item');
var idx = slider.activeIndex > li.length ? 0 : slider.activeIndex-1;
themerex_change_active_pagination_in_slider(cont, idx);
}
}
});
jQuery(this).data('settings', {mode: 'horizontal'}); // VC hook
var curSlide = jQuery(this).find('.slides').data('current-slide');
if (curSlide > 0)
THEMEREX_GLOBALS['swipers'][id].swipeTo(curSlide-1);
themerex_prepare_slider_navi(jQuery(this));
});
}
//Skills init
if (container.find('.sc_skills_item:not(.inited)').length > 0) {
themerex_init_skills(container);
jQuery(window).scroll(function () { themerex_init_skills(container); });
}
//Skills type='arc' init
if (container.find('.sc_skills_arc:not(.inited)').length > 0) {
themerex_init_skills_arc(container);
jQuery(window).scroll(function () { themerex_init_skills_arc(container); });
}
// Tabs
if (container.find('.sc_tabs:not(.inited),.tabs_area:not(.inited)').length > 0) {
container.find('.sc_tabs:not(.inited),.tabs_area:not(.inited)').each(function () {
var init = jQuery(this).data('active');
if (isNaN(init)) init = 0;
else init = Math.max(0, init);
jQuery(this)
.addClass('inited')
.tabs({
active: init,
show: {
effect: 'fadeIn',
duration: 300
},
hide: {
effect: 'fadeOut',
duration: 300
},
create: function (event, ui) {
themerex_init_shortcodes(ui.panel);
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(ui.panel);
},
activate: function (event, ui) {
themerex_init_shortcodes(ui.newPanel);
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(ui.newPanel);
}
});
});
}
// Toggles
if (container.find('.sc_toggles .sc_toggles_title:not(.inited)').length > 0) {
container.find('.sc_toggles .sc_toggles_title:not(.inited)')
.addClass('inited')
.click(function () {
jQuery(this).toggleClass('ui-state-active').parent().toggleClass('sc_active');
jQuery(this).parent().find('.sc_toggles_content').slideToggle(300, function () {
themerex_init_shortcodes(jQuery(this).parent().find('.sc_toggles_content'));
if (window.themerex_init_hidden_elements) themerex_init_hidden_elements(jQuery(this).parent().find('.sc_toggles_content'));
});
});
}
//Zoom
if (container.find('.sc_zoom:not(.inited)').length > 0) {
container.find('.sc_zoom:not(.inited)')
.each(function () {
"use strict";
if (jQuery(this).parents('div:hidden,article:hidden').length > 0) return;
jQuery(this).addClass('inited');
jQuery(this).find('img').elevateZoom({
zoomType: "lens",
lensShape: "round",
lensSize: 200,
lensBorderSize: 4,
lensBorderColour: '#ccc'
});
});
}
}
// Scrolled areas
function themerex_init_scroll_area(obj) {
// Wait for images loading
if (!themerex_check_images_complete(obj) && THEMEREX_GLOBALS['scroll_init_counter']++ < 30) {
setTimeout(function() { themerex_init_scroll_area(obj); }, 200);
return;
}
// Start init scroll area
obj.addClass('inited');
var id = obj.attr('id');
if (id == undefined) {
id = 'scroll_'+Math.random();
id = id.replace('.', '');
obj.attr('id', id);
}
obj.addClass(id);
var bar = obj.find('#'+id+'_bar');
if (bar.length > 0 && !bar.hasClass(id+'_bar')) {
bar.addClass(id+'_bar');
}
// Init Swiper with scroll plugin
if (THEMEREX_GLOBALS['swipers'] === undefined) THEMEREX_GLOBALS['swipers'] = {};
THEMEREX_GLOBALS['swipers'][id] = new Swiper('.'+id, {
calculateHeight: false,
resizeReInit: true,
autoResize: true,
freeMode: true,
freeModeFluid: true,
grabCursor: true,
noSwiping: obj.hasClass('scroll-no-swiping'),
mode: obj.hasClass('sc_scroll_vertical') ? 'vertical' : 'horizontal',
slidesPerView: obj.hasClass('sc_scroll') ? 'auto' : 1,
mousewheelControl: true,
mousewheelAccelerator: 4, // Accelerate mouse wheel in Firefox 4+
scrollContainer: obj.hasClass('sc_scroll_vertical'),
scrollbar: {
container: '.'+id+'_bar',
hide: true,
draggable: true
}
})
obj.data('settings', {mode: 'horizontal'});
themerex_prepare_slider_navi(obj);
}
// Slider navigation
function themerex_prepare_slider_navi(slider) {
// Prev / Next
var navi = slider.find('> .sc_slider_controls_wrap, > .sc_scroll_controls_wrap');
if (navi.length == 0) navi = slider.siblings('.sc_slider_controls_wrap,.sc_scroll_controls_wrap');
if (navi.length > 0) {
navi.find('.sc_slider_prev,.sc_scroll_prev').click(function(e){
var swiper = jQuery(this).parents('.swiper-slider-container');
if (swiper.length == 0) swiper = jQuery(this).parents('.sc_slider_controls_wrap,.sc_scroll_controls_wrap').siblings('.swiper-slider-container');
var id = swiper.attr('id');
THEMEREX_GLOBALS['swipers'][id].swipePrev();
e.preventDefault();
return false;
});
navi.find('.sc_slider_next,.sc_scroll_next').click(function(e){
var swiper = jQuery(this).parents('.swiper-slider-container');
if (swiper.length == 0) swiper = jQuery(this).parents('.sc_slider_controls_wrap,.sc_scroll_controls_wrap').siblings('.swiper-slider-container');
var id = swiper.attr('id');
THEMEREX_GLOBALS['swipers'][id].swipeNext();
e.preventDefault();
return false;
});
}
// Pagination
navi = slider.siblings('.sc_slider_pagination');
if (navi.length > 0) {
navi.find('.post_item').click(function(e){
var swiper = jQuery(this).parents('.sc_slider_pagination_area').find('.swiper-slider-container');
var id = swiper.attr('id');
THEMEREX_GLOBALS['swipers'][id].swipeTo(jQuery(this).index());
e.preventDefault();
return false;
});
}
}
function themerex_change_active_pagination_in_slider(slider, idx) {
var pg = slider.parents('.sc_slider_pagination_area').find('.sc_slider_pagination');
if (pg.length==0) return;
pg.find('.post_item').removeClass('active').eq(idx).addClass('active');
var h = pg.height();
var off = pg.find('.active').offset().top - pg.offset().top;
var off2 = pg.find('.sc_scroll_wrapper').offset().top - pg.offset().top;
var h2 = pg.find('.active').height();
if (off < 0) {
pg.find('.sc_scroll_wrapper').css({'transform': 'translate3d(0px, 0px, 0px)', 'transition-duration': '0.3s'});
} else if (h <= off+h2) {
pg.find('.sc_scroll_wrapper').css({'transform': 'translate3d(0px, -'+(Math.abs(off2)+off-h/4)+'px, 0px)', 'transition-duration': '0.3s'});
}
}
// Sliders: Autoheight
function themerex_slider_autoheight(slider) {
if (slider.hasClass('.sc_slider_height_auto')) {
slider.find('.swiper-slide').each(function() {
if (jQuery(this).data('height_auto') == undefined) {
jQuery(this).attr('data-height_auto', jQuery(this).height());
}
});
}
}
// Skills init
function themerex_init_skills(container) {
if (arguments.length==0) var container = jQuery('body');
var scrollPosition = jQuery(window).scrollTop() + jQuery(window).height();
container.find('.sc_skills_item:not(.inited)').each(function () {
var skillsItem = jQuery(this);
var scrollSkills = skillsItem.offset().top;
if (scrollPosition > scrollSkills) {
skillsItem.addClass('inited');
var skills = skillsItem.parents('.sc_skills').eq(0);
var type = skills.data('type');
var total = (type=='pie' && skills.hasClass('sc_skills_compact_on')) ? skillsItem.find('.sc_skills_data .pie') : skillsItem.find('.sc_skills_total').eq(0);
var start = parseInt(total.data('start'));
var stop = parseInt(total.data('stop'));
var maximum = parseInt(total.data('max'));
var startPercent = Math.round(start/maximum*100);
var stopPercent = Math.round(stop/maximum*100);
var ed = total.data('ed');
var duration = parseInt(total.data('duration'));
var speed = parseInt(total.data('speed'));
var step = parseInt(total.data('step'));
if (type == 'bar') {
var dir = skills.data('dir');
var count = skillsItem.find('.sc_skills_count').eq(0);
if (dir=='horizontal')
count.css('width', startPercent + '%').animate({ width: stopPercent + '%' }, duration);
else if (dir=='vertical')
count.css('height', startPercent + '%').animate({ height: stopPercent + '%' }, duration);
themerex_animate_skills_counter(start, stop, speed-(dir!='unknown' ? 5 : 0), step, ed, total);
} else if (type == 'counter') {
themerex_animate_skills_counter(start, stop, speed - 5, step, ed, total);
} else if (type == 'pie') {
var steps = parseInt(total.data('steps'));
var bg_color = total.data('bg_color');
var border_color = total.data('border_color');
var cutout = parseInt(total.data('cutout'));
var easing = total.data('easing');
var options = {
segmentShowStroke: true,
segmentStrokeColor: border_color,
segmentStrokeWidth: 1,
percentageInnerCutout : cutout,
animationSteps: steps,
animationEasing: easing,
animateRotate: true,
animateScale: false,
};
var pieData = [];
total.each(function() {
var color = jQuery(this).data('color');
var stop = parseInt(jQuery(this).data('stop'));
var stopPercent = Math.round(stop/maximum*100);
pieData.push({
value: stopPercent,
color: color
});
});
if (total.length == 1) {
themerex_animate_skills_counter(start, stop, Math.round(1500/steps), step, ed, total);
pieData.push({
value: 100-stopPercent,
color: bg_color
});
}
var canvas = skillsItem.find('canvas');
canvas.attr({width: skillsItem.width(), height: skillsItem.width()}).css({width: skillsItem.width(), height: skillsItem.height()});
new Chart(canvas.get(0).getContext("2d")).Doughnut(pieData, options);
}
}
});
}
// Skills counter animation
function themerex_animate_skills_counter(start, stop, speed, step, ed, total) {
start = Math.min(stop, start + step);
total.text(start+ed);
if (start < stop) {
setTimeout(function () {
themerex_animate_skills_counter(start, stop, speed, step, ed, total);
}, speed);
}
}
// Skills arc init
function themerex_init_skills_arc(container) {
if (arguments.length==0) var container = jQuery('body');
container.find('.sc_skills_arc:not(.inited)').each(function () {
var arc = jQuery(this);
arc.addClass('inited');
var items = arc.find('.sc_skills_data .arc');
var canvas = arc.find('.sc_skills_arc_canvas').eq(0);
var legend = arc.find('.sc_skills_legend').eq(0);
var w = Math.round(arc.width() - legend.width());
var c = Math.floor(w/2);
var o = {
random: function(l, u){
return Math.floor((Math.random()*(u-l+1))+l);
},
diagram: function(){
var r = Raphael(canvas.attr('id'), w, w),
rad = hover = Math.round(w/2/items.length),
step = Math.round(((w-20)/2-rad)/items.length),
stroke = Math.round(w/9/items.length),
speed = 400;
r.circle(c, c, Math.round(w/2)).attr({ stroke: 'none', fill: THEMEREX_GLOBALS['theme_skin_bg'] ? THEMEREX_GLOBALS['theme_skin_bg'] : '#ffffff' });
var title = r.text(c, c, arc.data('subtitle')).attr({
font: 'lighter '+Math.round(rad*0.7)+'px "'+THEMEREX_GLOBALS['theme_font']+'"',
fill: '#888888'
}).toFront();
rad -= Math.round(step/2);
r.customAttributes.arc = function(value, color, rad){
var v = 3.6 * value,
alpha = v == 360 ? 359.99 : v,
rand = o.random(91, 240),
a = (rand-alpha) * Math.PI/180,
b = rand * Math.PI/180,
sx = c + rad * Math.cos(b),
sy = c - rad * Math.sin(b),
x = c + rad * Math.cos(a),
y = c - rad * Math.sin(a),
path = [['M', sx, sy], ['A', rad, rad, 0, +(alpha > 180), 1, x, y]];
return { path: path, stroke: color }
}
items.each(function(i){
var t = jQuery(this),
color = t.find('.color').val(),
value = t.find('.percent').val(),
text = t.find('.text').text();
rad += step;
var z = r.path().attr({ arc: [value, color, rad], 'stroke-width': stroke });
z.mouseover(function(){
this.animate({ 'stroke-width': hover, opacity: .75 }, 1000, 'elastic');
if (Raphael.type != 'VML') //solves IE problem
this.toFront();
title.stop().animate({ opacity: 0 }, speed, '>', function(){
this.attr({ text: (text ? text + '\n' : '') + value + '%' }).animate({ opacity: 1 }, speed, '<');
});
}).mouseout(function(){
this.stop().animate({ 'stroke-width': stroke, opacity: 1 }, speed*4, 'elastic');
title.stop().animate({ opacity: 0 }, speed, '>', function(){
title.attr({ text: arc.data('subtitle') }).animate({ opacity: 1 }, speed, '<');
});
});
});
}
}
o.diagram();
});
}
// Countdown update
function themerex_countdown(dt) {
var counter = jQuery(this).parent();
for (var i=3; i<dt.length; i++) {
var v = (dt[i]<10 ? '0' : '') + dt[i];
counter.find('.sc_countdown_item').eq(i-3).find('.sc_countdown_digits span').addClass('hide');
for (var ch=v.length-1; ch>=0; ch--) {
counter.find('.sc_countdown_item').eq(i-3).find('.sc_countdown_digits span').eq(ch+(i==3 && v.length<3 ? 1 : 0)).removeClass('hide').text(v.substr(ch, 1));
}
}
} | 1.328125 | 1 |
backend/src/server.js | lulukc/projeto_gostack | 0 | 3183 | import app from './app';
const port = 3003;
app.listen(port, () => {
console.log(`Servidor rodando na porta ${port}`);
});
| 0.621094 | 1 |
chrome/phraseapp.js | Vadorequest/PhraseApp-AutoTranslate | 1 | 3191 | // Name of the pck.
PHRASE_APP_PCK = 'PhraseApp';
// Create our own pck to avoid gobals that could interfere with the website.
window[PHRASE_APP_PCK] = {};
// Create shortcut.
holdsport = window[PHRASE_APP_PCK];
// True will display debug messages.
holdsport.DEBUG = false;
holdsport.dev = function(callback){
if(holdsport.DEBUG && callback){
callback();
}
return holdsport.DEBUG;
}
// Auto running once DOM loaded.
$(function(){
var consoleDev = function(content){
holdsport.dev(function(){
console.log(content);
});
}
consoleDev("PhraseApp AutoTranslate processing");
var translationSuggested = $('.translation-suggest');
consoleDev("There are "+translationSuggested.length+" translations detected to to!");
if(translationSuggested.length > 0){
// We are running in a page where we can autoload suggested translations.
for(var i in translationSuggested){
// If the object is clickable, just click on it!
if(translationSuggested[i].click){
translationSuggested[i].click();
consoleDev("Starting auto translate phrase "+i);
}
}
}
}); | 1.085938 | 1 |
src/pages/LoginPage/MessageLoginFormComponent.js | WhiteRobe/hypethron | 2 | 3199 | import React from 'react';
import {Row, Col} from 'antd';
import 'antd/es/style/index.css' // col & row
import 'antd/es/grid/style/index.css' // col & row
class MessageLoginFormComponent extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
return (
<Row style={{minHeight: '473.5px'}}>
<Col span={5}> </Col>
<Col span={14} style={{textAlign: 'center'}}>
短信登录暂未制作
</Col>
<Col span={5}> </Col>
</Row>
)
}
}
export default MessageLoginFormComponent; | 1.046875 | 1 |
public/script/main.js | Diegooliveyra/dashboard-road-to-dev | 1 | 3207 | import menuMobile from "./menu-mobile.js";
import navCourses from "./nav-cousers.js";
import contador from './contador.js'
import dropMenu from './dropMenu.js'
menuMobile();
navCourses();
contador();
dropMenu(); | 0.208008 | 0 |
glossary/index.js | designstem/projects | 1 | 3215 | import { fachwerk } from "https://designstem.github.io/fachwerk/fachwerk.js";
fachwerk({ type: 'document', editor: 'none', menu: 'none' }) | 0.320313 | 0 |