<commit_before>    /*
     *
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor l    icense agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     *
     *   http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing,
     * software distributed under the License is distributed on an
     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     * KIND, either express or implied.  See the License for the
     * specific language governing permissions and limitations
     * under the License.
     *
     */

    var argscheck = require('cordova/argscheck'),
        channel = require('cordova/channel'),
        utils = require('cordova/utils'),
        exec = require('cordova/exec'),
        cordova = require('cordova');

    channel.createSticky('onCordovaInfoReady');
    // Tell cordova channel to wait on the CordovaInfoReady event
    channel.waitForInitialization('onCordovaInfoReady');

    /**
     * This represents the mobile printer, and provides properties for inspecting the model, version, UUID of the
     * phone, etc.
     * @constructor
     */
    function zebra() {
        var me = this;
        channel.onCordovaReady.subscribe(function() {
            channel.onCordovaInfoReady.fire();
        });

    }

    /**
     * Get printer info
     *
     * @param {Function} successCallback The function to call when the heading data is available
     * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
     */
    zebra.prototype.scan = function(successCallback, errorCallback) {
        exec(successCallback, errorCallback, "Zebra", "scan", []);
    };

    zebra.prototype.write = function(serialNumber,data,successCallback, errorCallback) {
        exec(successCallback, errorCallback, "Zebra", "write", [serialNumber,data]);
    };

    module.exports = new zebra();
<commit_msg>Actualizando index del plugin <commit_after>    /*
     *
     * Licensed to the Apache Software Foundation (ASF) under one
     * or more contributor l    icense agreements.  See the NOTICE file
     * distributed with this work for additional information
     * regarding copyright ownership.  The ASF licenses this file
     * to you under the Apache License, Version 2.0 (the
     * "License"); you may not use this file except in compliance
     * with the License.  You may obtain a copy of the License at
     *
     *   http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing,
     * software distributed under the License is distributed on an
     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     * KIND, either express or implied.  See the License for the
     * specific language governing permissions and limitations
     * under the License.
     *
     */

    var argscheck = require('cordova/argscheck'),
        channel = require('cordova/channel'),
        utils = require('cordova/utils'),
        exec = require('cordova/exec'),
        cordova = require('cordova');

    channel.createSticky('onCordovaZebraPrinterReady');
    // Tell cordova channel to wait on the CordovaInfoReady event
    channel.waitForInitialization('onCordovaZebraPrinterReady');

    /**
     * This represents the mobile printer, and provides properties for inspecting the model, version, UUID of the
     * phone, etc.
     * @constructor
     */
    function Zebra() {
        var me = this;
        channel.onCordovaReady.subscribe(function() {
            channel.onCordovaZebraPrinterReady.fire();
        });

    }

    /**
     * Get printer info
     *
     * @param {Function} successCallback The function to call when the heading data is available
     * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
     */
    Zebra.prototype.scan = function(successCallback, errorCallback) {
        exec(successCallback, errorCallback, "Zebra", "scan", []);
    };

    Zebra.prototype.write = function(serialNumber,data,successCallback, errorCallback) {
        exec(successCallback, errorCallback, "Zebra", "write", [serialNumber,data]);
    };

    module.exports = new Zebra();
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/

'use strict';

/*
* The original C++ code and copyright notice are from the [Boost library]{@link http://www.boost.org/doc/libs/1_62_0/boost/math/special_functions/beta.hpp}.
*
* The implementation has been modified for JavaScript.
*/

/*
* (C) Copyright John Maddock 2006.
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
*/

// MODULES //

var lanczosSumExpGScaled = require( '@stdlib/math/base/special/gamma-lanczos-sum-expg-scaled' );
var expm1 = require( '@stdlib/math/base/special/expm1' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var pow = require( '@stdlib/math/base/special/pow' );
var max = require( '@stdlib/math/base/special/max' );
var min = require( '@stdlib/math/base/special/min' );
var ln = require( '@stdlib/math/base/special/ln' );
var MAX_LN = require( '@stdlib/constants/math/float64-max-ln' );
var MIN_LN = require( '@stdlib/constants/math/float64-min-ln' );
var G = require( '@stdlib/constants/math/float64-gamma-lanczos-g' );
var E = require( '@stdlib/constants/math/float64-e' );

// MAIN //

/**
* Computes the leading power terms in the incomplete beta function.
*
* When normalized,
*
* ```tex
* \frac{ x^a y^b }{ \operatorname{Beta}(a,b) }
* ```
*
* and otherwise
*
* ```tex
* x^a y^b
* ```
*
* ## Notes
*
* -   Almost all of the error in the incomplete beta comes from this function, particularly when \\( a \\) and \\( b \\) are large. Computing large powers are _hard_ though, and using logarithms just leads to horrendous cancellation errors.
*
* -   For \\( l1 * l2 > 0 \\) or \\( \operatorname{min}( a, b ) < 1 \\), the two power terms both go in the same direction (towards zero or towards infinity). In this case if either term overflows or underflows, then the product of the two must do so also. Alternatively, if one exponent is less than one, then we can't productively use it to eliminate overflow or underflow from the other term.  Problems with spurious overflow/underflow can't be ruled out in this case, but it is _very_ unlikely since one of the power terms will evaluate to a number close to 1.
*
* -   If \\( \max( \abs(l1), \abs(l2) ) < 0.5 \\), both exponents are near one and both the exponents are greater than one, and, further, these two power terms tend in opposite directions (one toward zero, the other toward infinity), so we have to combine the terms to avoid any risk of overflow or underflow. We do this by moving one power term inside the other, we have:
*
*     ```tex
*     (1 + l_1)^a \cdot (1 + l_2)^b \\
*     = ((1 + l_1) \cdot (1 + l_2)^(b/a))^a \\
*     = (1 + l_1 + l_3 + l_1*l_3)^a
*     ```
*
*     and
*
*     ```tex
*     l_3 = (1 + l_2)^(b/a) - 1 \\
*     = \exp((b/a) * \ln(1 + l_2)) - 1
*     ```
*
*     The tricky bit is deciding which term to move inside. By preference we move the larger term inside, so that the size of the largest exponent is reduced.  However, that can only be done as long as l3 (see above) is also small.
*
* @private
* @param {NonNegativeNumber} a - function parameter
* @param {NonNegativeNumber} b - function parameter
* @param {Probability} x - function parameter
* @param {Probability} y - probability equal to `1-x`
* @param {boolean} normalized - boolean indicating whether to evaluate the power terms of the regularized or non-regularized incomplete beta function
* @returns {number} power terms
*/
function ibetaPowerTerms( a, b, x, y, normalized ) {
	var result;
	var smallA;
	var ratio;
	var agh;
	var bgh;
	var cgh;
	var l1;
	var l2;
	var l3;
	var p1;
	var b1;
	var b2;
	var c;
	var l;

	if ( !normalized ) {
		// Can we do better here?
		return pow( x, a ) * pow( y, b );
	}
	c = a + b;

	// Combine power terms with Lanczos approximation:
	agh = a + G - 0.5;
	bgh = b + G - 0.5;
	cgh = c + G - 0.5;
	result = lanczosSumExpGScaled( c );
	result /= lanczosSumExpGScaled( a ) * lanczosSumExpGScaled( b );

	// Combine with the leftover terms from the Lanczos approximation:
	result *= sqrt( bgh / E );
	result *= sqrt( agh / cgh );

	// `l1` and `l2` are the base of the exponents minus one:
	l1 = ( ( x * b ) - ( y * agh ) ) / agh;
	l2 = ( ( y * a ) - ( x * bgh ) ) / bgh;
	if ( min( abs(l1), abs(l2) ) < 0.2 ) {
		// When the base of the exponent is very near 1 we get really gross errors unless extra care is taken:
		if ( l1 * l2 > 0 || min( a, b ) < 1 ) {
			if ( abs(l1) < 0.1 ) {
				result *= exp( a * log1p( l1 ) );
			} else {
				result *= pow( ( x*cgh ) / agh, a );
			}
			if ( abs(l2) < 0.1 ) {
				result *= exp( b * log1p( l2 ) );
			} else {
				result *= pow((y * cgh) / bgh, b);
			}
		}
		else if ( max( abs(l1), abs(l2) ) < 0.5 ) {
			smallA = a < b;
			ratio = b / a;
			if (
				(smallA && (ratio * l2 < 0.1)) ||
				(!smallA && (l1 / ratio > 0.1))
			) {
				l3 = expm1( ratio * log1p( l2 ) );
				l3 = l1 + l3 + ( l3 * l1 );
				l3 = a * log1p( l3 );
				result *= exp( l3 );
			}
			else {
				l3 = expm1( log1p( l1 ) / ratio );
				l3 = l2 + l3 + ( l3 * l2 );
				l3 = b * log1p( l3 );
				result *= exp( l3 );
			}
		}
		else if ( abs(l1) < abs(l2) ) {
			// First base near 1 only:
			l = ( a * log1p( l1 ) ) + ( b * ln( ( y*cgh ) / bgh ) );
			if ( l <= MIN_LN || l >= MAX_LN ) {
				l += ln(result);
				if ( l >= MAX_LN ) {
					return NaN;
				}
				result = exp( l );
			} else {
				result *= exp( l );
			}
		}
		else {
			// Second base near 1 only:
			l = ( b * log1p( l2 ) ) + ( a * ln( (x*cgh) / agh ) );
			if ( l <= MIN_LN || l >= MAX_LN ) {
				l += ln(result);
				if ( l >= MAX_LN ) {
					return NaN;
				}
				result = exp( l );
			} else {
				result *= exp( l );
			}
		}
	}
	else {
		// General case:
		b1 = (x * cgh) / agh;
		b2 = (y * cgh) / bgh;
		l1 = a * ln(b1);
		l2 = b * ln(b2);
		if (
			l1 >= MAX_LN ||
			l1 <= MIN_LN ||
			l2 >= MAX_LN ||
			l2 <= MIN_LN
		) {
			// Oops, under/overflow, sidestep if we can:
			if ( a < b ) {
				p1 = pow( b2, b / a );
				l3 = a * ( ln(b1) + ln(p1) );
				if ( l3 < MAX_LN && l3 > MIN_LN ) {
					result *= pow( p1 * b1, a );
				} else {
					l2 += l1 + ln(result);
					if ( l2 >= MAX_LN ) {
						return NaN;
					}
					result = exp( l2 );
				}
			}
			else {
				p1 = pow( b1, a / b );
				l3 = ( ln(p1) + ln(b2) ) * b;
				if ( l3 < MAX_LN && l3 > MIN_LN ) {
					result *= pow( p1 * b2, b );
				} else {
					l2 += l1 + ln( result );
					if (l2 >= MAX_LN) {
						return NaN;
					}
					result = exp( l2 );
				}
			}
		}
		else {
			// Finally the normal case:
			result *= pow( b1, a ) * pow( b2, b );
		}
	}
	return result;
}

// EXPORTS //

module.exports = ibetaPowerTerms;
<commit_msg>Update license header<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*
*
* ## Notice
*
* The original C++ code and copyright notice are from the [Boost library]{@link http://www.boost.org/doc/libs/1_62_0/boost/math/special_functions/beta.hpp}. The implementation has been modified for JavaScript.
*
* ```text
* (C) Copyright John Maddock 2006.
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
* ```
*/

'use strict';

// MODULES //

var lanczosSumExpGScaled = require( '@stdlib/math/base/special/gamma-lanczos-sum-expg-scaled' );
var expm1 = require( '@stdlib/math/base/special/expm1' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var abs = require( '@stdlib/math/base/special/abs' );
var exp = require( '@stdlib/math/base/special/exp' );
var pow = require( '@stdlib/math/base/special/pow' );
var max = require( '@stdlib/math/base/special/max' );
var min = require( '@stdlib/math/base/special/min' );
var ln = require( '@stdlib/math/base/special/ln' );
var MAX_LN = require( '@stdlib/constants/math/float64-max-ln' );
var MIN_LN = require( '@stdlib/constants/math/float64-min-ln' );
var G = require( '@stdlib/constants/math/float64-gamma-lanczos-g' );
var E = require( '@stdlib/constants/math/float64-e' );

// MAIN //

/**
* Computes the leading power terms in the incomplete beta function.
*
* When normalized,
*
* ```tex
* \frac{ x^a y^b }{ \operatorname{Beta}(a,b) }
* ```
*
* and otherwise
*
* ```tex
* x^a y^b
* ```
*
* ## Notes
*
* -   Almost all of the error in the incomplete beta comes from this function, particularly when \\( a \\) and \\( b \\) are large. Computing large powers are _hard_ though, and using logarithms just leads to horrendous cancellation errors.
*
* -   For \\( l1 * l2 > 0 \\) or \\( \operatorname{min}( a, b ) < 1 \\), the two power terms both go in the same direction (towards zero or towards infinity). In this case if either term overflows or underflows, then the product of the two must do so also. Alternatively, if one exponent is less than one, then we can't productively use it to eliminate overflow or underflow from the other term.  Problems with spurious overflow/underflow can't be ruled out in this case, but it is _very_ unlikely since one of the power terms will evaluate to a number close to 1.
*
* -   If \\( \max( \abs(l1), \abs(l2) ) < 0.5 \\), both exponents are near one and both the exponents are greater than one, and, further, these two power terms tend in opposite directions (one toward zero, the other toward infinity), so we have to combine the terms to avoid any risk of overflow or underflow. We do this by moving one power term inside the other, we have:
*
*     ```tex
*     (1 + l_1)^a \cdot (1 + l_2)^b \\
*     = ((1 + l_1) \cdot (1 + l_2)^(b/a))^a \\
*     = (1 + l_1 + l_3 + l_1*l_3)^a
*     ```
*
*     and
*
*     ```tex
*     l_3 = (1 + l_2)^(b/a) - 1 \\
*     = \exp((b/a) * \ln(1 + l_2)) - 1
*     ```
*
*     The tricky bit is deciding which term to move inside. By preference we move the larger term inside, so that the size of the largest exponent is reduced.  However, that can only be done as long as l3 (see above) is also small.
*
* @private
* @param {NonNegativeNumber} a - function parameter
* @param {NonNegativeNumber} b - function parameter
* @param {Probability} x - function parameter
* @param {Probability} y - probability equal to `1-x`
* @param {boolean} normalized - boolean indicating whether to evaluate the power terms of the regularized or non-regularized incomplete beta function
* @returns {number} power terms
*/
function ibetaPowerTerms( a, b, x, y, normalized ) {
	var result;
	var smallA;
	var ratio;
	var agh;
	var bgh;
	var cgh;
	var l1;
	var l2;
	var l3;
	var p1;
	var b1;
	var b2;
	var c;
	var l;

	if ( !normalized ) {
		// Can we do better here?
		return pow( x, a ) * pow( y, b );
	}
	c = a + b;

	// Combine power terms with Lanczos approximation:
	agh = a + G - 0.5;
	bgh = b + G - 0.5;
	cgh = c + G - 0.5;
	result = lanczosSumExpGScaled( c );
	result /= lanczosSumExpGScaled( a ) * lanczosSumExpGScaled( b );

	// Combine with the leftover terms from the Lanczos approximation:
	result *= sqrt( bgh / E );
	result *= sqrt( agh / cgh );

	// `l1` and `l2` are the base of the exponents minus one:
	l1 = ( ( x * b ) - ( y * agh ) ) / agh;
	l2 = ( ( y * a ) - ( x * bgh ) ) / bgh;
	if ( min( abs(l1), abs(l2) ) < 0.2 ) {
		// When the base of the exponent is very near 1 we get really gross errors unless extra care is taken:
		if ( l1 * l2 > 0 || min( a, b ) < 1 ) {
			if ( abs(l1) < 0.1 ) {
				result *= exp( a * log1p( l1 ) );
			} else {
				result *= pow( ( x*cgh ) / agh, a );
			}
			if ( abs(l2) < 0.1 ) {
				result *= exp( b * log1p( l2 ) );
			} else {
				result *= pow((y * cgh) / bgh, b);
			}
		}
		else if ( max( abs(l1), abs(l2) ) < 0.5 ) {
			smallA = a < b;
			ratio = b / a;
			if (
				(smallA && (ratio * l2 < 0.1)) ||
				(!smallA && (l1 / ratio > 0.1))
			) {
				l3 = expm1( ratio * log1p( l2 ) );
				l3 = l1 + l3 + ( l3 * l1 );
				l3 = a * log1p( l3 );
				result *= exp( l3 );
			}
			else {
				l3 = expm1( log1p( l1 ) / ratio );
				l3 = l2 + l3 + ( l3 * l2 );
				l3 = b * log1p( l3 );
				result *= exp( l3 );
			}
		}
		else if ( abs(l1) < abs(l2) ) {
			// First base near 1 only:
			l = ( a * log1p( l1 ) ) + ( b * ln( ( y*cgh ) / bgh ) );
			if ( l <= MIN_LN || l >= MAX_LN ) {
				l += ln(result);
				if ( l >= MAX_LN ) {
					return NaN;
				}
				result = exp( l );
			} else {
				result *= exp( l );
			}
		}
		else {
			// Second base near 1 only:
			l = ( b * log1p( l2 ) ) + ( a * ln( (x*cgh) / agh ) );
			if ( l <= MIN_LN || l >= MAX_LN ) {
				l += ln(result);
				if ( l >= MAX_LN ) {
					return NaN;
				}
				result = exp( l );
			} else {
				result *= exp( l );
			}
		}
	}
	else {
		// General case:
		b1 = (x * cgh) / agh;
		b2 = (y * cgh) / bgh;
		l1 = a * ln(b1);
		l2 = b * ln(b2);
		if (
			l1 >= MAX_LN ||
			l1 <= MIN_LN ||
			l2 >= MAX_LN ||
			l2 <= MIN_LN
		) {
			// Oops, under/overflow, sidestep if we can:
			if ( a < b ) {
				p1 = pow( b2, b / a );
				l3 = a * ( ln(b1) + ln(p1) );
				if ( l3 < MAX_LN && l3 > MIN_LN ) {
					result *= pow( p1 * b1, a );
				} else {
					l2 += l1 + ln(result);
					if ( l2 >= MAX_LN ) {
						return NaN;
					}
					result = exp( l2 );
				}
			}
			else {
				p1 = pow( b1, a / b );
				l3 = ( ln(p1) + ln(b2) ) * b;
				if ( l3 < MAX_LN && l3 > MIN_LN ) {
					result *= pow( p1 * b2, b );
				} else {
					l2 += l1 + ln( result );
					if (l2 >= MAX_LN) {
						return NaN;
					}
					result = exp( l2 );
				}
			}
		}
		else {
			// Finally the normal case:
			result *= pow( b1, a ) * pow( b2, b );
		}
	}
	return result;
}

// EXPORTS //

module.exports = ibetaPowerTerms;
<|endoftext|>


<commit_before>import React from 'react'
import createBlockNode from '../createBlockNode'
import createSpanNode from '../createSpanNode'
import mapToObject from './mapToObject'
import Header from '../preview/Header'
import Normal from '../preview/Normal'
import ListItem from '../preview/ListItem'
import Mark from '../preview/Mark'
import {getSpanType} from './spanHelpers'
import initializeSlatePlugins from './initializeSlatePlugins'

import {SLATE_DEFAULT_STYLE} from '../constants'

// When the slate-fields are rendered in the editor, their node data is stored in a parent container component.
// In order to use the node data as props inside our components, we have to dereference them here first (see list and header keys)
const slateTypeComponentMapping = {
  normal: Normal,
  h1(props) {
    return <Header level={1} {...props} />
  },
  h2(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={2} {...props} />
  },
  h3(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={3} {...props} />
  },
  h4(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={4} {...props} />
  },
  h5(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={5} {...props} />
  },
  h6(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={6} {...props} />
  },
  listItem(props) {  // eslint-disable-line react/no-multi-comp
    // eslint-disable-next-line react/prop-types
    const listItem = props.children[0] && props.children[0].props.parent.data.get('listItem')
    // eslint-disable-next-line react/prop-types
    const style = (props.children[0] && props.children[0].props.parent.data.get('style'))
      || SLATE_DEFAULT_STYLE
    const contentComponent = slateTypeComponentMapping[style]
    return <ListItem contentComponent={contentComponent} listItem={listItem} {...props} />
  }
}

function createSlatePreviewNode(props) {
  let component = null
  const style = props.children[0] && props.children[0].props.parent.data.get('style')
  const isListItem = props.children[0] && props.children[0].props.parent.data.get('listItem')
  if (isListItem) {
    component = slateTypeComponentMapping.listItem
  } else {
    component = slateTypeComponentMapping[style]
  }
  if (!component) {
    throw new Error(`No mapping for style '${style}' exists.`)
  }
  return component(props)
}

export default function prepareSlateForBlockEditor(blockEditor) {
  const type = blockEditor.props.type
  const blockType = type.of.find(ofType => ofType.name === 'block')
  if (!blockType) {
    throw new Error("'block' type is not defined in the schema (required).")
  }

  const styleField = blockType.fields.find(btField => btField.name === 'style')
  if (!styleField) {
    throw new Error("A field with name 'style' is not defined in the block type (required).")
  }

  const textStyles = styleField.type.options.list
    && styleField.type.options.list.filter(style => style.value)
  if (!textStyles || textStyles.length === 0) {
    throw new Error('The style fields need at least one style '
      + "defined. I.e: {title: 'Normal', value: 'normal'}.")
  }

  const listField = blockType.fields.find(btField => btField.name === 'list')
  let listItems = []
  if (listField) {
    listItems = listField.type.options.list
      && listField.type.options.list.filter(listStyle => listStyle.value)
  }

  const allowedMarks = blockType.fields.find(btField => btField.name === 'spans')
    .type.of.find(of => of.name === 'span')
    .fields.find(field => field.name === 'marks')
    .type
    .options
    .list.map(mark => mark.value)

  const memberTypesExceptBlock = type.of.filter(ofType => ofType.name !== 'block')
  const spanType = getSpanType(type).type

  const schema = {
    nodes: {
      ...mapToObject(memberTypesExceptBlock, ofType => [ofType.name, createBlockNode(ofType)]),
      span: createSpanNode(spanType),
      contentBlock: createSlatePreviewNode,
    },
    marks: mapToObject(allowedMarks, mark => {
      return [mark, Mark]
    })
  }
  return {
    listItems: listItems,
    textStyles: textStyles,
    schema: schema,
    plugins: initializeSlatePlugins(blockEditor)
  }
}
<commit_msg>[form-builder] Block editor: warn, not throw, and use defualt normal style, if style is not mapped to component<commit_after>import React from 'react'
import createBlockNode from '../createBlockNode'
import createSpanNode from '../createSpanNode'
import mapToObject from './mapToObject'
import Header from '../preview/Header'
import Normal from '../preview/Normal'
import ListItem from '../preview/ListItem'
import Mark from '../preview/Mark'
import {getSpanType} from './spanHelpers'
import initializeSlatePlugins from './initializeSlatePlugins'

import {SLATE_DEFAULT_STYLE} from '../constants'

// When the slate-fields are rendered in the editor, their node data is stored in a parent container component.
// In order to use the node data as props inside our components, we have to dereference them here first (see list and header keys)
const slateTypeComponentMapping = {
  normal: Normal,
  h1(props) {
    return <Header level={1} {...props} />
  },
  h2(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={2} {...props} />
  },
  h3(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={3} {...props} />
  },
  h4(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={4} {...props} />
  },
  h5(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={5} {...props} />
  },
  h6(props) {  // eslint-disable-line react/no-multi-comp
    return <Header level={6} {...props} />
  },
  listItem(props) {  // eslint-disable-line react/no-multi-comp
    // eslint-disable-next-line react/prop-types
    const listItem = props.children[0] && props.children[0].props.parent.data.get('listItem')
    // eslint-disable-next-line react/prop-types
    const style = (props.children[0] && props.children[0].props.parent.data.get('style'))
      || SLATE_DEFAULT_STYLE
    const contentComponent = slateTypeComponentMapping[style]
    return <ListItem contentComponent={contentComponent} listItem={listItem} {...props} />
  }
}

function createSlatePreviewNode(props) {
  let component = null
  const style = props.children[0] && props.children[0].props.parent.data.get('style')
  const isListItem = props.children[0] && props.children[0].props.parent.data.get('listItem')
  if (isListItem) {
    component = slateTypeComponentMapping.listItem
  } else {
    component = slateTypeComponentMapping[style]
  }
  if (!component) {
    // eslint-disable-next-line no-console
    console.warn(`No mapping for style '${style}' exists, using 'normal'`)
    component = slateTypeComponentMapping.normal
  }
  return component(props)
}

export default function prepareSlateForBlockEditor(blockEditor) {
  const type = blockEditor.props.type
  const blockType = type.of.find(ofType => ofType.name === 'block')
  if (!blockType) {
    throw new Error("'block' type is not defined in the schema (required).")
  }

  const styleField = blockType.fields.find(btField => btField.name === 'style')
  if (!styleField) {
    throw new Error("A field with name 'style' is not defined in the block type (required).")
  }

  const textStyles = styleField.type.options.list
    && styleField.type.options.list.filter(style => style.value)
  if (!textStyles || textStyles.length === 0) {
    throw new Error('The style fields need at least one style '
      + "defined. I.e: {title: 'Normal', value: 'normal'}.")
  }

  const listField = blockType.fields.find(btField => btField.name === 'list')
  let listItems = []
  if (listField) {
    listItems = listField.type.options.list
      && listField.type.options.list.filter(listStyle => listStyle.value)
  }

  const allowedMarks = blockType.fields.find(btField => btField.name === 'spans')
    .type.of.find(of => of.name === 'span')
    .fields.find(field => field.name === 'marks')
    .type
    .options
    .list.map(mark => mark.value)

  const memberTypesExceptBlock = type.of.filter(ofType => ofType.name !== 'block')
  const spanType = getSpanType(type).type

  const schema = {
    nodes: {
      ...mapToObject(memberTypesExceptBlock, ofType => [ofType.name, createBlockNode(ofType)]),
      span: createSpanNode(spanType),
      contentBlock: createSlatePreviewNode,
    },
    marks: mapToObject(allowedMarks, mark => {
      return [mark, Mark]
    })
  }
  return {
    listItems: listItems,
    textStyles: textStyles,
    schema: schema,
    plugins: initializeSlatePlugins(blockEditor)
  }
}
<|endoftext|>


<commit_before>'use strict';
/* globals process module */
/* eslint no-process-env: 0
 no-console: 0
 */

// Depends
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer-core');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const NODE_ENV = process.env.NODE_ENV || 'production';
const DEVELOPMENT = NODE_ENV === 'production' ? false : true;
const stylesLoader = 'css-loader?sourceMap!postcss-loader!sass-loader?' +
        'outputStyle=expanded&sourceMap=true&sourceMapContents=true';

const basemaps = JSON.stringify({
    layers: {
        Light: {
            url: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',
            properties: {
                attribution: '© ' +
                    'OpenStreetMap ©CartoDB',
                maxZoom: 30
            },

            default: true
        },
        Dark: {
            url: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png',
            properties: {
                attribution: '© ' +
                    'OpenStreetMap ©CartoDB',
                maxZoom: 30,
                subdomains: 'a'
            }
        },
        Aerial: {
            url: 'https://{s}.{base}.maps.cit.api.here.com/maptile/2.1/{type}/{mapID}/hybrid.day/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}',
            properties: {
                attribution: 'Map © 1987-2014 HERE',
                subdomains: '1234',
                mapID: 'newest',
                app_id: 'mXP4DZFBZGyBmuZBKNeo',
                app_code: 'kBWb6Z7ZLcuQanT_RoP60A',
                base: 'aerial',
                maxZoom: 30,
                maxNativeZoom: 20,
                type: 'maptile',
                language: 'eng',
                format: 'png8',
                size: '256'
            }
        },
        Streets: {
            url: 'https://{s}.base.maps.cit.api.here.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/256/png8?app_id={app_id}&app_code={app_code}',
            properties: {
                attribution: 'Map © 1987-2014 HERE',
                subdomains: '1234',
                app_id: 'mXP4DZFBZGyBmuZBKNeo',
                app_code: 'kBWb6Z7ZLcuQanT_RoP60A'
            }
        }
    },
    default: 'Aerial'
});

module.exports = function (_path) {
    let rootAssetPath = _path + 'src';

    let webpackConfig = {
        // entry points
        entry: {
            vendor: _path + '/src/app/index.vendor.js',
            app: _path + '/src/app/index.bootstrap.js',
            polyfill: _path + '/node_modules/babel-polyfill'
        },

        // output system
        output: {
            path: 'dist',
            filename: '[name].js',
            publicPath: '/'
        },

        // resolves modules
        resolve: {
            extensions: ['', '.js'],
            modulesDirectories: ['node_modules'],
            alias: {
                _appRoot: path.join(_path, 'src', 'app'),
                _images: path.join(_path, 'src', 'app', 'assets', 'images'),
                _stylesheets: path.join(_path, 'src', 'app', 'assets', 'styles'),
                _scripts: path.join(_path, 'src', 'app', 'assets', 'js')
            }
        },

        // modules resolvers
        module: {
            noParse: [],
            preLoaders: [
                {
                    test: /\.js$/,
                    loaders: ['eslint-loader'],
                    exclude: [/node_modules/, /tests\.webpack\.js/, /\.config.js/, /\.spec\.js$/]
                }
            ],
            loaders: [{
                test: /\.html$/,
                loaders: [
                    'ngtemplate-loader?relativeTo=' + _path,
                    'html-loader?attrs[]=img:src&attrs[]=img:data-src&attrs[]=source:src'
                ]
            }, {
                test: /\.js$/,
                loaders: [
                    'baggage-loader?[file].html&[file].css'
                ]
            }, {
                test: /\.js$/,
                exclude: [
                    path.resolve(_path, 'node_modules')
                ],
                loaders: [
                    'ng-annotate-loader'
                ]
            }, {
                test: /\.js$/,
                exclude: [
                    path.resolve(_path, 'node_modules'),
                    path.resolve(_path, 'src/app/core/aws-sdk-s3.module.js')
                ],
                loader: 'babel-loader',
                query: {
                    cacheDirectory: true,
                    plugins: ['transform-runtime', 'add-module-exports'],
                    presets: ['angular', 'latest']
                }
            }, {
                test: /\.css$/,
                loader: DEVELOPMENT ? 'style-loader!css-loader?sourceMap!postcss-loader'
                    : ExtractTextPlugin.extract('style-loader',
                                                'css-loader!postcss-loader')
            }, {
                test: /\.(scss|sass)$/,
                loader: DEVELOPMENT ? 'style-loader!' + stylesLoader
                    : ExtractTextPlugin.extract('style-loader', stylesLoader)
            }, {
                test: /\.(woff2|woff|ttf|eot|svg)(\?[0-9]+)?(#[0-9a-zA-Z]+)?$/,
                loaders: [
                    'url-loader?name=assets/fonts/[name]_[hash].[ext]'
                ]
            }, {
                test: /\.(jpe?g|png|gif)$/i,
                loaders: [
                    'url-loader?name=assets/images/[name]_[hash].[ext]&limit=10000!image-webpack'
                ]
            }, {
                test: /\.(m4v|ogg|webm)$/i,
                loaders: [
                    'url-loader?name=assets/video/[name]_[hash].[ext]&limit=10000'
                ]
            }, {
                test: require.resolve('angular-deferred-bootstrap'),
                loaders: [
                    'expose?deferredBootstrapper'
                ]
            }, {
                test: require.resolve('angular'),
                loaders: [
                    'expose?angular'
                ]
            }, {
                test: require.resolve('jquery'),
                loaders: [
                    'expose?$',
                    'expose?jQuery'
                ]
            }, {
                test: require.resolve('leaflet'),
                loaders: [
                    'expose?L'
                ]
            }, {
                test: require.resolve('jointjs'),
                loaders: [
                    'expose?joint'
                ]
            }, {
                test: require.resolve('moment'),
                loaders: [
                    'expose?moment'
                ]
            }, {
                test: require.resolve('mathjs'),
                loaders: [
                    'expose?mathjs'
                ]
            }, {
                test: /node_modules[\\\/]auth0-lock[\\\/].*\.js$/,
                loaders: ['transform-loader/cacheable?brfs',
                          'transform-loader/cacheable?packageify']
            }, {
                test: /node_modules[\\\/]auth0-lock[\\\/].*\.ejs$/,
                loader: 'transform-loader/cacheable?ejsify'
            }, {
                test: /\.json$/,
                loader: 'json'
            }]
        },

        // post css
        postcss: [autoprefixer({browsers: ['last 5 versions']})],

        imageWebpackLoader: {
            pngquant: {
                quality: '66-90',
                speed: 4
            }
        },

        eslint: {
            configFile: './.eslintrc'
        },

        // load plugins
        plugins: [
            new webpack.optimize.DedupePlugin(),
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                L: 'leaflet',
                mathjs: 'mathjs'
            }),
            new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
            new webpack.optimize.AggressiveMergingPlugin({
                moveToParents: true
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'common',
                async: true,
                children: true,
                minChunks: Infinity
            }),
            new ExtractTextPlugin(
                'assets/styles/css/[name]' +
                    (NODE_ENV === 'development' ? '' : '.[chunkhash]') +
                    '.css', {allChunks: true}
            ),
            new HtmlWebpackPlugin({
                filename: 'index.html',
                template: path.join(_path, 'src', 'tpl-index.html'),
                heapLoad: DEVELOPMENT ? '2743344218' : '3505855839',
                development: DEVELOPMENT
            }),
            new webpack.DefinePlugin({
                'BUILDCONFIG': {
                    APP_NAME: '\'RasterFoundry\'',
                    BASEMAPS: basemaps,
                    API_HOST: '\'\''
                }
            })
        ]
    };

    return webpackConfig;
};
<commit_msg>Change default basemap to light/positron<commit_after>'use strict';
/* globals process module */
/* eslint no-process-env: 0
 no-console: 0
 */

// Depends
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer-core');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const NODE_ENV = process.env.NODE_ENV || 'production';
const DEVELOPMENT = NODE_ENV === 'production' ? false : true;
const stylesLoader = 'css-loader?sourceMap!postcss-loader!sass-loader?' +
        'outputStyle=expanded&sourceMap=true&sourceMapContents=true';

const basemaps = JSON.stringify({
    layers: {
        Light: {
            url: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',
            properties: {
                attribution: '© ' +
                    'OpenStreetMap ©CartoDB',
                maxZoom: 30
            },

            default: true
        },
        Dark: {
            url: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png',
            properties: {
                attribution: '© ' +
                    'OpenStreetMap ©CartoDB',
                maxZoom: 30,
                subdomains: 'a'
            }
        },
        Aerial: {
            url: 'https://{s}.{base}.maps.cit.api.here.com/maptile/2.1/{type}/{mapID}/hybrid.day/{z}/{x}/{y}/{size}/{format}?app_id={app_id}&app_code={app_code}&lg={language}',
            properties: {
                attribution: 'Map © 1987-2014 HERE',
                subdomains: '1234',
                mapID: 'newest',
                app_id: 'mXP4DZFBZGyBmuZBKNeo',
                app_code: 'kBWb6Z7ZLcuQanT_RoP60A',
                base: 'aerial',
                maxZoom: 30,
                maxNativeZoom: 20,
                type: 'maptile',
                language: 'eng',
                format: 'png8',
                size: '256'
            }
        },
        Streets: {
            url: 'https://{s}.base.maps.cit.api.here.com/maptile/2.1/maptile/newest/normal.day/{z}/{x}/{y}/256/png8?app_id={app_id}&app_code={app_code}',
            properties: {
                attribution: 'Map © 1987-2014 HERE',
                subdomains: '1234',
                app_id: 'mXP4DZFBZGyBmuZBKNeo',
                app_code: 'kBWb6Z7ZLcuQanT_RoP60A'
            }
        }
    },
    default: 'Light'
});

module.exports = function (_path) {
    let rootAssetPath = _path + 'src';

    let webpackConfig = {
        // entry points
        entry: {
            vendor: _path + '/src/app/index.vendor.js',
            app: _path + '/src/app/index.bootstrap.js',
            polyfill: _path + '/node_modules/babel-polyfill'
        },

        // output system
        output: {
            path: 'dist',
            filename: '[name].js',
            publicPath: '/'
        },

        // resolves modules
        resolve: {
            extensions: ['', '.js'],
            modulesDirectories: ['node_modules'],
            alias: {
                _appRoot: path.join(_path, 'src', 'app'),
                _images: path.join(_path, 'src', 'app', 'assets', 'images'),
                _stylesheets: path.join(_path, 'src', 'app', 'assets', 'styles'),
                _scripts: path.join(_path, 'src', 'app', 'assets', 'js')
            }
        },

        // modules resolvers
        module: {
            noParse: [],
            preLoaders: [
                {
                    test: /\.js$/,
                    loaders: ['eslint-loader'],
                    exclude: [/node_modules/, /tests\.webpack\.js/, /\.config.js/, /\.spec\.js$/]
                }
            ],
            loaders: [{
                test: /\.html$/,
                loaders: [
                    'ngtemplate-loader?relativeTo=' + _path,
                    'html-loader?attrs[]=img:src&attrs[]=img:data-src&attrs[]=source:src'
                ]
            }, {
                test: /\.js$/,
                loaders: [
                    'baggage-loader?[file].html&[file].css'
                ]
            }, {
                test: /\.js$/,
                exclude: [
                    path.resolve(_path, 'node_modules')
                ],
                loaders: [
                    'ng-annotate-loader'
                ]
            }, {
                test: /\.js$/,
                exclude: [
                    path.resolve(_path, 'node_modules'),
                    path.resolve(_path, 'src/app/core/aws-sdk-s3.module.js')
                ],
                loader: 'babel-loader',
                query: {
                    cacheDirectory: true,
                    plugins: ['transform-runtime', 'add-module-exports'],
                    presets: ['angular', 'latest']
                }
            }, {
                test: /\.css$/,
                loader: DEVELOPMENT ? 'style-loader!css-loader?sourceMap!postcss-loader'
                    : ExtractTextPlugin.extract('style-loader',
                                                'css-loader!postcss-loader')
            }, {
                test: /\.(scss|sass)$/,
                loader: DEVELOPMENT ? 'style-loader!' + stylesLoader
                    : ExtractTextPlugin.extract('style-loader', stylesLoader)
            }, {
                test: /\.(woff2|woff|ttf|eot|svg)(\?[0-9]+)?(#[0-9a-zA-Z]+)?$/,
                loaders: [
                    'url-loader?name=assets/fonts/[name]_[hash].[ext]'
                ]
            }, {
                test: /\.(jpe?g|png|gif)$/i,
                loaders: [
                    'url-loader?name=assets/images/[name]_[hash].[ext]&limit=10000!image-webpack'
                ]
            }, {
                test: /\.(m4v|ogg|webm)$/i,
                loaders: [
                    'url-loader?name=assets/video/[name]_[hash].[ext]&limit=10000'
                ]
            }, {
                test: require.resolve('angular-deferred-bootstrap'),
                loaders: [
                    'expose?deferredBootstrapper'
                ]
            }, {
                test: require.resolve('angular'),
                loaders: [
                    'expose?angular'
                ]
            }, {
                test: require.resolve('jquery'),
                loaders: [
                    'expose?$',
                    'expose?jQuery'
                ]
            }, {
                test: require.resolve('leaflet'),
                loaders: [
                    'expose?L'
                ]
            }, {
                test: require.resolve('jointjs'),
                loaders: [
                    'expose?joint'
                ]
            }, {
                test: require.resolve('moment'),
                loaders: [
                    'expose?moment'
                ]
            }, {
                test: require.resolve('mathjs'),
                loaders: [
                    'expose?mathjs'
                ]
            }, {
                test: /node_modules[\\\/]auth0-lock[\\\/].*\.js$/,
                loaders: ['transform-loader/cacheable?brfs',
                          'transform-loader/cacheable?packageify']
            }, {
                test: /node_modules[\\\/]auth0-lock[\\\/].*\.ejs$/,
                loader: 'transform-loader/cacheable?ejsify'
            }, {
                test: /\.json$/,
                loader: 'json'
            }]
        },

        // post css
        postcss: [autoprefixer({browsers: ['last 5 versions']})],

        imageWebpackLoader: {
            pngquant: {
                quality: '66-90',
                speed: 4
            }
        },

        eslint: {
            configFile: './.eslintrc'
        },

        // load plugins
        plugins: [
            new webpack.optimize.DedupePlugin(),
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                L: 'leaflet',
                mathjs: 'mathjs'
            }),
            new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
            new webpack.optimize.AggressiveMergingPlugin({
                moveToParents: true
            }),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'common',
                async: true,
                children: true,
                minChunks: Infinity
            }),
            new ExtractTextPlugin(
                'assets/styles/css/[name]' +
                    (NODE_ENV === 'development' ? '' : '.[chunkhash]') +
                    '.css', {allChunks: true}
            ),
            new HtmlWebpackPlugin({
                filename: 'index.html',
                template: path.join(_path, 'src', 'tpl-index.html'),
                heapLoad: DEVELOPMENT ? '2743344218' : '3505855839',
                development: DEVELOPMENT
            }),
            new webpack.DefinePlugin({
                'BUILDCONFIG': {
                    APP_NAME: '\'RasterFoundry\'',
                    BASEMAPS: basemaps,
                    API_HOST: '\'\''
                }
            })
        ]
    };

    return webpackConfig;
};
<|endoftext|>


<commit_before>angular.module('celestial.login', ['ui.state', 'ui.bootstrap', 'ngResource', 'ngCookies'])
.config(function ($stateProvider) {
  $stateProvider.state( 'login', {
    url: '/login',
    views: {
      "main": {
        controller: 'LoginCtrl',
        templateUrl: 'login/login.tpl.html'
      }
    },
    data:{ pageTitle: 'Login' }
  });

})
.config(['$httpProvider', function ($httpProvider,$window) {
    $httpProvider.interceptors.push(function ($q) {
        return {
            'response': function (response) {
                return response;
            },
            'responseError': function (rejection) {
                if(rejection.status === 401) {
                    // location.reload();
                   window.location = "/login";
                }
                return $q.reject(rejection);
            }
        };
    });
}])
.factory('loginService', function($cookieStore ,$cookies, $location, $http,$window) {
  var loginService = {};

  loginService.logout = function() {
    $http.post('/logout').success(function(){
      $cookieStore.remove('celestial');
      $window.location = "/login";
    });
  };

 $http.get('/sessions').success(function(data){
      loginService.session = data;
 });

  return loginService;
})
.controller('LoginCtrl', function LoginController ($scope,$http,$location,loginService) {

});
<commit_msg>adding isAdmin isSuper<commit_after>angular.module('celestial.login', ['ui.state', 'ui.bootstrap', 'ngResource', 'ngCookies'])
.config(function ($stateProvider) {
  $stateProvider.state( 'login', {
    url: '/login',
    views: {
      "main": {
        controller: 'LoginCtrl',
        templateUrl: 'login/login.tpl.html'
      }
    },
    data:{ pageTitle: 'Login' }
  });
})
.config(['$httpProvider', function ($httpProvider,$window) {
    $httpProvider.interceptors.push(function ($q) {
        return {
            'response': function (response) {
                return response;
            },
            'responseError': function (rejection) {
                if(rejection.status === 401) {
                    // location.reload();
                   window.location = "/login";
                }
                return $q.reject(rejection);
            }
        };
    });
}])
.factory('loginService', function($cookieStore ,$cookies, $location, $http,$window) {
  var loginService = {};

  loginService.logout = function() {
    $http.post('/logout').success(function(){
      $cookieStore.remove('celestial');
      $window.location = "/login";
    });
  };

   $http.get('/sessions').success(function(data){
      loginService.session = data;
   });

   loginService.isSuper = function(call){
    return _.contains(loginService.session.roles,'celestial.roles/super-user');
   };

   loginService.isAdmin = function(call){
    return _.contains(loginService.session.roles,'celestial.roles/admin');
   };

  return loginService;
})
.controller('LoginCtrl', function LoginController ($scope,$http,$location,loginService) {

});
<|endoftext|>


<commit_before>;(function(f){typeof Promise==='function'&&f(Promise)}(function(P){
    'use strict';
    var pp = P.prototype;
    var gopn = Object.getOwnPropertyNames;

    function defMethod(target, name, func) {
        if(typeof target[name] === 'function') return;
        Object.defineProperty(target, name, {
            configurable : true,
            writable : false,
            enumerable : false,
            value : func
        });
    }

    defMethod(P, 'props', function props(obj) {
        var keys = gopn(obj);
        var i, len = i = keys.length;
        var arr = new Array(len);
        while(--i + 1) {
            arr[i] = obj[keys[i]];
        }
        return this.all(arr).then(function(rArr) {
            var result = {};
            var i = len;
            while(--i + 1) {
                result[keys[i]] = rArr[i];
            }
            return result;
        });
    });

    defMethod(P, 'defer', function defer() {
        var d = {};
        d.promise = new P(function(resolve, reject) {
            d.resolve = resolve;
            d.reject = reject;
        });
        return d;
    });

    defMethod(P, 'callback', function callback() {
        var d = this.defer();
        var cb = function(err, a1, a2, a3) {
            if(err) {
                return d.reject(err);
            }
            var len = arguments.length;
            switch(len) {
                case 0:
                case 1:
                    d.resolve();
                    break;
                case 2:
                    d.resolve(a1);
                    break;
                case 3:
                    d.resolve([a1, a2]);
                    break;
                case 4:
                    d.resolve([a1, a2, a3]);
                    break;
                default:
                    var args = new Array(len - 1);
                    while(--len) {
                        args[len - 1] = arguments[len]
                    }
                    d.resolve(args)
            }
        };
        cb.promise = d.promise;
        return cb;
    });
}));
<commit_msg>add static methods attempt, delay<commit_after>;(function(f){typeof Promise==='function'&&f(Promise)}(function(P){
    'use strict';
    var pp = P.prototype;
    var gopn = Object.getOwnPropertyNames;

    function defMethod(target, name, func) {
        if(typeof target[name] === 'function') return;
        Object.defineProperty(target, name, {
            configurable : true,
            writable : false,
            enumerable : false,
            value : func
        });
    }

    defMethod(P, 'props', function props(obj) {
        var keys = gopn(obj);
        var i, len = i = keys.length;
        var arr = new Array(len);
        while(--i + 1) {
            arr[i] = obj[keys[i]];
        }
        return this.all(arr).then(function(rArr) {
            var result = {};
            var i = len;
            while(--i + 1) {
                result[keys[i]] = rArr[i];
            }
            return result;
        });
    });

    defMethod(P, 'defer', function defer() {
        var d = {};
        d.promise = new P(function(resolve, reject) {
            d.resolve = resolve;
            d.reject = reject;
        });
        return d;
    });

    defMethod(P, 'callback', function callback() {
        var d = this.defer();
        var cb = function(err, a1, a2, a3) {
            if(err) {
                return d.reject(err);
            }
            var len = arguments.length;
            switch(len) {
                case 0:
                case 1:
                    d.resolve();
                    break;
                case 2:
                    d.resolve(a1);
                    break;
                case 3:
                    d.resolve([a1, a2]);
                    break;
                case 4:
                    d.resolve([a1, a2, a3]);
                    break;
                default:
                    var args = new Array(len - 1);
                    while(--len) {
                        args[len - 1] = arguments[len]
                    }
                    d.resolve(args)
            }
        };
        cb.promise = d.promise;
        return cb;
    });

    defMethod(P, 'attempt', function attempt(func) {
        return this.resolve().then(func);
    });

    defMethod(P, 'delay', function delay(t) {
        return new P(function(resolve) {
            if(typeof t !== 'number') {
                if(typeof setImmediate === 'function') {
                    setImmediate(resolve);
                    return;
                }
                setTimeout(resolve, 0)
                return;
            }
            setTimeout(resolve, t);
        });
    });
}));
<|endoftext|>


<commit_before>var hue = require("node-hue-api");
var hueapiBase = require("node-hue-api").HueApi;
var description = 'hueset_proto'
var hueIP = 'tbd';
var hueUser = 'tbd';
var hueapi = new hueapiBase();

hue.nupnpSearch(function(err, result) {
    if (err) throw err;
//     result = JSON.stringify(result)
    console.log(result[0]);
    hueIP = result[0].ipaddress;
    console.log('hueIP set as:', hueIP);
    console.log('Press button on Hue Bridge now.')
    configureHue();
});

function configureHue() {
    if(hueUser === 'tbd') {
        console.log('getting user...')
        hueapi.createUser(hueIP, description, function(err, user) {
            if (err) throw err;
            console.log(JSON.stringify(user));
        });
    } else {
        console.log('hueIP set as:', hueUser);
    }

}<commit_msg>hueconfig create user debug I<commit_after>var hue = require("node-hue-api");
var hueapiBase = require("node-hue-api").HueApi;
var description = 'hueset_proto'
var hueIP = 'tbd';
var hueUser = 'tbd';
var hueapi = new hueapiBase();

hue.nupnpSearch(function(err, result) {
    if (err) throw err;
    hueIP = result[0].ipaddress;
    console.log('hueIP set as:', hueIP);
    console.log('Press button on Hue Bridge now.')
    configureHue();
});

function configureHue() {
    if(hueUser === 'tbd') {
        hueapi.createUser(hueIP, description, function(err, user) {
            console.log('user response...')
            if (err) throw err;
            console.log(JSON.stringify(user));
        });
    } else {
        console.log('hueIP set as:', hueUser);
    }

}<|endoftext|>


<commit_before>module.exports = function (app) {
  app.view.fn('t', function () {
    var args = Array.prototype.slice.call(arguments, 0)
      , language = this.model.get('$lang.defaultLocale') || 'en'
      , translationInput = {}
      , translationPath = '';

    switch (args.length) {
      case 0:
        return '';
      case 1:
        translationPath = args[0];
        break;
      case 2:
        if (typeof args[1] === 'object') {
          translationPath = args[0];
          translationInput = args[1];
        } else {
          language = args[0];
          translationPath = args[1];
        }
        break;
      case 3:
        if (typeof args[2] === 'object') {
          language = args[0];
          translationInput = args[2];
          translationPath = args[1];
        } else {
          translationInput[args[1]] = args[2];
          translationPath = args[0];
        }
        break;
      default:
        if (args.length % 2) {
          translationPath = args[0];
          var i = 1;
        } else {
          language = args[0];
          translationPath = args[1];
          var i = 2;
        }
        for (i; i < args.length - 1; i+=2) {
          translationInput[args[i]] = args[i + 1];
        }
        break;
    }

    var $context = this.model.at('$lang.context');
    var $formats = this.model.at('$lang.formats');
    $formats.setNull('locale.' + language, Function($context.get('inc') + 'return ' + $context.get('locale.' + language))());
    if (!translationPath) return '';
    var viewPath = 't_' + language + '_' + translationPath.replace(/\./g, '_');
    var viewFn = app.view.getFns[viewPath];
    if (viewFn) return viewFn(translationInput);
    var translation = this.model.at('$lang.dictionary').at(language).get(translationPath);
    viewFn = Function('MessageFormat', 'return ' + translation)($formats.get());
    if (!viewFn) return translationPath;
    app.view.fn(viewPath, viewFn);
    return viewFn(translationInput);
  });
};<commit_msg>fixed content inc<commit_after>module.exports = function (app) {
  app.view.fn('t', function () {
    var args = Array.prototype.slice.call(arguments, 0)
      , language = this.model.get('$lang.defaultLocale') || 'en'
      , translationInput = {}
      , translationPath = '';

    switch (args.length) {
      case 0:
        return '';
      case 1:
        translationPath = args[0];
        break;
      case 2:
        if (typeof args[1] === 'object') {
          translationPath = args[0];
          translationInput = args[1];
        } else {
          language = args[0];
          translationPath = args[1];
        }
        break;
      case 3:
        if (typeof args[2] === 'object') {
          language = args[0];
          translationInput = args[2];
          translationPath = args[1];
        } else {
          translationInput[args[1]] = args[2];
          translationPath = args[0];
        }
        break;
      default:
        if (args.length % 2) {
          translationPath = args[0];
          var i = 1;
        } else {
          language = args[0];
          translationPath = args[1];
          var i = 2;
        }
        for (i; i < args.length - 1; i+=2) {
          translationInput[args[i]] = args[i + 1];
        }
        break;
    }

    var $context = this.model.at('$lang.context');
    var $formats = this.model.at('$lang.formats');
    $formats.setNull('locale.' + language, Function('return ' + $context.get('locale.' + language))());
    if (!translationPath) return '';
    var viewPath = 't_' + language + '_' + translationPath.replace(/\./g, '_');
    var viewFn = app.view.getFns[viewPath];
    if (viewFn) return viewFn(translationInput);
    var translation = this.model.at('$lang.dictionary').at(language).get(translationPath);
    viewFn = Function('MessageFormat', $context.get('inc') + 'return ' + translation)($formats.get());
    if (!viewFn) return translationPath;
    app.view.fn(viewPath, viewFn);
    return viewFn(translationInput);
  });
};<|endoftext|>


<commit_before>class Module {
  constructor(name = '') {
    this.name = name;
    this.deps = {};
  }
  addDependency(dep) {
    this.deps[dep] = new Module(dep);
    return this;
  }
  toObject() {
    return JSON.parse(this.toString());
  }
  toString() {
    let depsAsString = Object
      .keys(this.deps)
      .reduce((strAcc, key) => strAcc + this.deps[key].toString() + ',', '')
      .slice(0, -1);
    return `{\"${this.name}\": [${depsAsString}]}`;
  }
};
export default Module;<commit_msg>the Module can return now an array as well. It feels more easy to manipulate than the previous object<commit_after>class Module {
  constructor(name = '') {
    this.name = name;
    this.deps = {};
  }
  addDependency(dep) {
    this.deps[dep] = new Module(dep);
    return this;
  }
  toObject() {
    return JSON.parse(this.toString());
  }
  toString() {
    let depsAsString = Object
      .keys(this.deps)
      .reduce((strAcc, current) => strAcc + this.deps[current].toString() + ',', '')
      .slice(0, -1);
    return `{\"${this.name}\": [${depsAsString}]}`;
  }
  toArray() {
    let arr = [];
    arr.push(this.name);
    let depsAsArray = Object
      .keys(this.deps)
      .reduce((arrAcc, current) => arrAcc.concat(this.deps[current].toArray()), []);
    if (depsAsArray.length > 0) {
      arr.push(depsAsArray)
    }
    return arr;
  }
};
export default Module;<|endoftext|>


<commit_before>import { applyMiddleware as reduxApplyMiddleware, combine } from 'redux'
import thunk from 'redux-thunk'

export default function applyMiddleware (...additionalMiddlewares) {
  return reduxApplyMiddleware(thunk, ...additionalMiddlewares)
}
<commit_msg>Fix linter error<commit_after>import { applyMiddleware as reduxApplyMiddleware } from 'redux'
import thunk from 'redux-thunk'

export default function applyMiddleware (...additionalMiddlewares) {
  return reduxApplyMiddleware(thunk, ...additionalMiddlewares)
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        imgur_hide_user_light
// @namespace   imgur_stuff
// @include     https://imgur.com/account/*
// @include     http://imgur.com/account/*
// @include     https://imgur.com/gallery/*
// @include     http://imgur.com/gallery/*
// @include     https://imgur.com/user/*
// @include     http://imgur.com/user/*
// @version     1.4
// @grant       none
// ==/UserScript==

/*
* TODO
* - Add list to settings -> mod section (or inject into imgurs message block list ?)
* - Renove from gallery view
* - Navigate away when direct calling an blocked post ?
*/

//if (!localStorage.caption_filter) localStorage.caption_filter = {};
var blocked = {
  9730847: [1, 1, 1]
};
// post, comment, reply
blocked = $.parseJSON(localStorage.getItem('blocked_user')) || {};
// update blocked structure to point to arrays now
$.each(blocked, function(k, v){
  if(! $.isArray(v))
    blocked[k] = [0, 1, blocked[k]];
});

var captions = undefined;
var captioninstance = undefined;

/*
* Yadda yadda
*/
function handle_blocked_comments(blocked_cb) {
  var insideNav = Imgur.InsideNav._instance;
  captioninstance = insideNav._.captionInstance;
  captions = captioninstance._.captions[insideNav._.hash];
  var blocked_captions = captioninstance.getCaptionIdsByFilter(insideNav._.hash, function (caption) {
    return blocked.hasOwnProperty(caption.author_id) && blocked[caption.author_id][1] == 1;
  });
  $.grep(blocked_captions, function (v) {
    blocked_cb(captions.set[v]);
  });
}

/*
* Traverse the comment replies and test if there are any non blocked comments
*/
function has_nonblocked_childs(caption) {
  if (captions.children[caption.id] == null)
   return false
  for (var i = 0; i < captions.children[caption.id].length; ++i) {
    var child = captions.set[captions.children[caption.id][i]];
    if (!blocked.hasOwnProperty(child.author_id))
    return true;
    if (has_nonblocked_childs(child))
    return true;
  }
  return false;
}

// All the gui setup to add/remove blocked user
function setup_block_gui(){
  // TODO: make this look nicer
  var block_gui = $(
   '
' +
    '<input style="margin-left:5px;" type="checkbox" id="block_posts" />Block posts' +
    '<input style="margin-left:10px;" type="checkbox" id="block_comments" />Block comments' +
    '<input style="margin-left:10px;" type="checkbox" id="block_replies" />Block replies' +
    ''+
   '
'
  ).insertBefore('.panel-header');
  $('.panel-header').css('clear', 'right');
  // Get user id via imgur api form username (TODO: find a way without the api. It need to be there somewhere on the page already)
  var CLIENT_ID = 'cd0695f1226536b';
  var endpoint = 'https://api.imgur.com/3/account/' + window.location.pathname.split('/', 4) [2];
  $.ajax({
    url: endpoint,
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(response){
      if(response.success){
        var btn = $('<button style="margin-left:20px;"></button>');
        var checkbox_post = block_gui.find('#block_posts');
        var checkbox_comment = block_gui.find('#block_comments');
        var checkbox_reply = block_gui.find('#block_replies');
        if(blocked.hasOwnProperty(response.data.id)){
          btn.text("Unblock user", blocked[response.data.id]);
          checkbox_post.prop('checked', blocked[response.data.id][0] == 1);
          checkbox_comment.prop('checked', blocked[response.data.id][1] == 1);
          checkbox_reply.prop('checked', blocked[response.data.id][2] == 1);
        }else{
          btn.text("Block user");
          checkbox_post.prop('checked', false);
          checkbox_comment.prop('checked', false);
          checkbox_reply.prop('checked', false);
        }
        block_gui.find('img').replaceWith(btn);
        // Add/remove blocked user
        btn.click(function(){
          if(! blocked.hasOwnProperty(response.data.id)){
            blocked[response.data.id] = [
              checkbox_post.prop('checked') ? 1 : 0,
              checkbox_comment.prop('checked') ? 1 : 0,
              checkbox_reply.prop('checked') ? 1 : 0
            ];
            btn.text("Unblock user");
          }else{
            delete blocked[response.data.id];
            btn.text("Block user");
          }
          localStorage.setItem("blocked_user", JSON.stringify(blocked));
        });
        // Block posts ?
        checkbox_post.change(function(){
          if(blocked.hasOwnProperty(response.data.id)){
           blocked[response.data.id][0] = checkbox_post.prop('checked') ? 1 : 0;
           localStorage.setItem("blocked_user", JSON.stringify(blocked));
          }
        });
        // Block comments ?
        checkbox_comment.change(function(){
          if(blocked.hasOwnProperty(response.data.id)){
           blocked[response.data.id][1] = checkbox_comment.prop('checked') ? 1 : 0;
           localStorage.setItem("blocked_user", JSON.stringify(blocked));
          }
        });
        // Block replies ?
        checkbox_reply.change(function(){
          if(blocked.hasOwnProperty(response.data.id)){
           blocked[response.data.id][2] = checkbox_reply.prop('checked') ? 1 : 0;
           localStorage.setItem("blocked_user", JSON.stringify(blocked));
          }
        });
      }
    },
    error: undefined
  });
}

/*
* captioninstance.deleteCaption sometimes doesn't work (why ever), So lets just rewrite that
*/
function deleteCaption(caption_id) {
  captions.children[captions.parent[caption_id]] = $.grep(captions.children[captions.parent[caption_id]], function (child_id) {
    return child_id != caption_id;
  });
  delete captions.parent[caption_id];
  delete captions.set[caption_id];
  //delete captions.children[caption_id];
}

function hookit_pre(parent, funcname, callback){
  var _ori = parent[funcname];
  parent[funcname] = function(){
    arguments = callback.apply(this, arguments);
    return _ori.apply(this, arguments);
  }
}
function hookit_post(parent, funcname, callback){
  var _ori = parent[funcname];
  parent[funcname] = function(){
    var _ret = _ori.apply(this, arguments);
    _ret = callback.apply(this, [arguments, _ret]);
    return _ret;
  };
}

// Are we on the settings page ?
if (window.location.pathname.indexOf('/account/settings') == 0) {
  // TODO: implement
}
// Show hide and show buttons on user profile
else if (window.location.pathname.indexOf('/user/') == 0 && window.location.pathname.indexOf('/favorites/') == - 1) {
  setup_block_gui();
}
// Filter posts and comments
 else {
   // TODO: navigate away when first load is blocked ?
   // Filter posts:
   /* TODO: try this for the initial load
   hookit_pre(Imgur.InsideNav._instance._.sideGallery, '_loadPage', function(){
     console.log('asd load', arguments);
     return arguments;
   });
   */
   // This works sometimes for the initial load, but always for every load after that
   hookit_pre(Imgur.InsideNav._instance._.sideGallery, '_ajaxSuccess', function(args){
     arguments[0]['data'] = $.grep(arguments[0]['data'], function(v){
       return !(blocked.hasOwnProperty(v.account_id) && blocked[v.account_id][0] == 1);
     });
     return arguments;
   });
   imgur._.emitter.callbacks['sidegalleryPageLoad'].push({f:function(){
     // pretty dirsty but the values are overwritten soemwehere after the event
     // TODO: ...
     window.setTimeout(function(){
       Imgur.InsideNav._instance._.sideGallery.state.items = $.grep(Imgur.InsideNav._instance._.sideGallery.state.items, function(v){
         if((blocked.hasOwnProperty(v.account_id) && blocked[v.account_id][0] == 1))
          console.log('asd block', v);
         return !(blocked.hasOwnProperty(v.account_id) && blocked[v.account_id][0] == 1);
       });
       // recreate the box (TODO: Read that code)
       Imgur.InsideNav._instance._.sideGallery._onScroll();
     }, 1000);
   }, this_arg:{}});

  // Filter comments
  // I didn't found a fitting  event to filter the comments, so lets just hook the process comments function
  // TODO: try to run earlier or run once at site load for already loaded comments
  var _pcaptions = Imgur.InsideNav._instance.processCaptions;
  function process_captions_hook(ori, ori_this) {
    handle_blocked_comments(function (comment) {
      if(blocked[comment.author_id][1] == 0)
        return;
      //console.log('asd removed before render:', comment);
      if (blocked[comment.author_id][2] == 1 || !has_nonblocked_childs(comment)) {
        deleteCaption(comment.id);
      } else {
        comment.caption = 'Blocked';
      }
    });
    ori.call(Imgur.InsideNav._instance);
  }
  Imgur.InsideNav._instance.processCaptions = process_captions_hook.bind(this, _pcaptions, Imgur.InsideNav._instance);
  /*
  * Remove all already rendered comments. Used for the initial load.
  */
  function remove_rendered_comments() {
    handle_blocked_comments(function (comment) {
      //console.log('asd Removed after render:', comment);
      if (blocked[comment.author_id] == 1 || !has_nonblocked_childs(comment)) {
        captioninstance.deleteCaption(comment.id);
        $('.caption').filter('[data-id="' + comment.id + '"]').hide();
      } else {
        comment.caption = 'Blocked';
        $('.caption').filter('[data-id="' + comment.id + '"]').find('.usertext p span').text('Blocked');
      }
    });
  }
  remove_rendered_comments();
}
<commit_msg>Added settings mod page + reddit block<commit_after>// ==UserScript==
// @name        imgur_hide_user_light
// @namespace   imgur_stuff
// @include     https://imgur.com/account/*
// @include     http://imgur.com/account/*
// @include     https://imgur.com/gallery/*
// @include     http://imgur.com/gallery/*
// @include     https://imgur.com/user/*
// @include     http://imgur.com/user/*
// @version     1.4
// @grant       none
// ==/UserScript==

/*
* TODO
* - Add list to settings -> mod section (or inject into imgurs message block list ?)
* - Renove from gallery view
* - Navigate away when direct calling an blocked post ?
*/

var blocked = {
  9730847: [1, 1, 1]
};
// post, comment, reply, last seen username
blocked = $.parseJSON(localStorage.getItem('blocked_user')) || {};
// update blocked structure to point to arrays now
$.each(blocked, function(k, v){
  if(! $.isArray(v))
    blocked[k] = [0, 1, blocked[k], "?"];
  else if(v.length != 4)
    blocked[k] = [blocked[k][0], blocked[k][1], blocked[k][2], "?"];
});

var captions = undefined;
var captioninstance = undefined;

function inject_mod_menu(){
	if($('#_mod_menu_button').length > 0){
		return $('#mod_settings');
	}
	var btn = $('
mods
');
	$('#leftside-nav ul').append(btn);
	var space = $('

');
	$('.settings-content').append(space);
	btn.click(function(){
		btn.addClass("active");
		btn.parent().children().not('[data-type=mods]').removeClass('active');
		space.css('display', 'block');
		space.parent().children().not('#mod_settings').css('display', 'none');
	});
	btn.parent().children().not('[data-type=mods]').click(function(){
		space.css('display', 'none');
	});
	return space;
}

function setup_settings_gui(){
  var space = inject_mod_menu();
  var content = $('

');
  var user_table = $('

User name	Posts	Comments	Replies	Remove

');
  $.each(blocked, function(k, v){
    if(k == null) return;
    var row = $('

');
    row.find('td').get(0).innerHTML = ''+v[3]+'';
    row.find('td').get(1).innerHTML = v[0] == 1 ? 'Blocked' : 'Shown';
    row.find('td').get(2).innerHTML = v[1] == 1 ? 'Blocked' : 'Shown';
    row.find('td').get(3).innerHTML = v[2] == 1 ? 'Blocked' : 'Shown';
    var delbtn = $('delete');
    delbtn.click(function(){
      delete blocked[$(this).attr('data-id')];
      localStorage.setItem("blocked_user", JSON.stringify(blocked));
      $(this).parent().parent().remove();
      return false;
    });
    row.find('td').eq(4).append(delbtn);
    user_table.append(row);
  });
  var show_crossposts = $(''+(blocked.hasOwnProperty("null") ? 'Show' : 'Hide')+' crossposts');
  show_crossposts.click(function(){
    if(blocked.hasOwnProperty("null")){
      delete blocked[null];
      localStorage.setItem("blocked_user", JSON.stringify(blocked));
      show_crossposts.text('Hide crossposts');
    }else{
      blocked[null] = [1, 0, 0, null];
      localStorage.setItem("blocked_user", JSON.stringify(blocked));
      show_crossposts.text('Show crossposts');
    }
  });
  content.append('
Blocked user
');
  content.append(user_table);
  content.append('

Misc.
');
  content.append(show_crossposts);
  space.append(content);
}

// All the gui setup to add/remove blocked user
function setup_block_gui(){
  // TODO: make this look nicer
  var block_gui = $(
   '
' +
    '<input style="margin-left:5px;" type="checkbox" id="block_posts" />Block posts' +
    '<input style="margin-left:10px;" type="checkbox" id="block_comments" />Block comments' +
    '<input style="margin-left:10px;" type="checkbox" id="block_replies" />Block replies' +
    ''+
   '
'
  ).insertBefore('.panel-header');
  $('.panel-header').css('clear', 'right');
  // Get user id via imgur api form username (TODO: find a way without the api. It need to be there somewhere on the page already)
  var CLIENT_ID = 'cd0695f1226536b';
  var username = window.location.pathname.split('/', 4) [2];
  var endpoint = 'https://api.imgur.com/3/account/' + username;
  $.ajax({
    url: endpoint,
    method: 'GET',
    headers: {
      Authorization: 'Client-ID ' + CLIENT_ID,
      Accept: 'application/json'
    },
    success: function(response){
      // TODO: handle failed requests
      if(response.success){

        var btn = $('<button style="margin-left:20px;"></button>');
        var checkbox_post = block_gui.find('#block_posts');
        var checkbox_comment = block_gui.find('#block_comments');
        var checkbox_reply = block_gui.find('#block_replies');
        if(blocked.hasOwnProperty(response.data.id)){
          var user = blocked[response.data.id];
          // update name (if necessarry)
          if(user[3] != username){
            user[3] = username;
            localStorage.setItem("blocked_user", JSON.stringify(blocked));
          }
          btn.text("Unblock user", blocked[response.data.id]);
          checkbox_post.prop('checked', blocked[response.data.id][0] == 1);
          checkbox_comment.prop('checked', blocked[response.data.id][1] == 1);
          checkbox_reply.prop('checked', blocked[response.data.id][2] == 1);
        }else{
          btn.text("Block user");
          checkbox_post.prop('checked', false);
          checkbox_comment.prop('checked', false);
          checkbox_reply.prop('checked', false);
        }
        block_gui.find('img').replaceWith(btn);
        // Add/remove blocked user
        btn.click(function(){
          if(! blocked.hasOwnProperty(response.data.id)){
            blocked[response.data.id] = [
              checkbox_post.prop('checked') ? 1 : 0,
              checkbox_comment.prop('checked') ? 1 : 0,
              checkbox_reply.prop('checked') ? 1 : 0,
              username
            ];
            btn.text("Unblock user");
          }else{
            delete blocked[response.data.id];
            btn.text("Block user");
          }
          localStorage.setItem("blocked_user", JSON.stringify(blocked));
        });
        // Block posts ?
        checkbox_post.change(function(){
          if(blocked.hasOwnProperty(response.data.id)){
           blocked[response.data.id][0] = checkbox_post.prop('checked') ? 1 : 0;
           localStorage.setItem("blocked_user", JSON.stringify(blocked));
          }
        });
        // Block comments ?
        checkbox_comment.change(function(){
          if(blocked.hasOwnProperty(response.data.id)){
           blocked[response.data.id][1] = checkbox_comment.prop('checked') ? 1 : 0;
           localStorage.setItem("blocked_user", JSON.stringify(blocked));
          }
        });
        // Block replies ?
        checkbox_reply.change(function(){
          if(blocked.hasOwnProperty(response.data.id)){
           blocked[response.data.id][2] = checkbox_reply.prop('checked') ? 1 : 0;
           localStorage.setItem("blocked_user", JSON.stringify(blocked));
          }
        });
      }
    },
    error: undefined
  });
}

/*
* Yadda yadda
*/
function handle_blocked_comments(blocked_cb) {
  var insideNav = Imgur.InsideNav._instance;
  captioninstance = insideNav._.captionInstance;
  captions = captioninstance._.captions[insideNav._.hash];
  var blocked_captions = captioninstance.getCaptionIdsByFilter(insideNav._.hash, function (caption) {
    return blocked.hasOwnProperty(caption.author_id) && blocked[caption.author_id][1] == 1;
  });
  $.grep(blocked_captions, function (v) {
    blocked_cb(captions.set[v]);
  });
}

/*
* Traverse the comment replies and test if there are any non blocked comments
*/
function has_nonblocked_childs(caption) {
  if (captions.children[caption.id] == null)
   return false
  for (var i = 0; i < captions.children[caption.id].length; ++i) {
    var child = captions.set[captions.children[caption.id][i]];
    if (!blocked.hasOwnProperty(child.author_id))
    return true;
    if (has_nonblocked_childs(child))
    return true;
  }
  return false;
}

/*
* captioninstance.deleteCaption sometimes doesn't work (why ever), So lets just rewrite that
*/
function deleteCaption(caption_id) {
  captions.children[captions.parent[caption_id]] = $.grep(captions.children[captions.parent[caption_id]], function (child_id) {
    return child_id != caption_id;
  });
  delete captions.parent[caption_id];
  delete captions.set[caption_id];
  //delete captions.children[caption_id];
}

function hookit_pre(parent, funcname, callback){
  var _ori = parent[funcname];
  parent[funcname] = function(){
    arguments = callback.apply(this, arguments);
    return _ori.apply(this, arguments);
  }
}
function hookit_post(parent, funcname, callback){
  var _ori = parent[funcname];
  parent[funcname] = function(){
    var _ret = _ori.apply(this, arguments);
    _ret = callback.apply(this, [arguments, _ret]);
    return _ret;
  };
}

// Are we on the settings page ?
if (window.location.pathname.indexOf('/account/settings') == 0) {
  setup_settings_gui();
}
// Show hide and show buttons on user profile
else if (window.location.pathname.indexOf('/user/') == 0 && window.location.pathname.indexOf('/favorites/') == - 1) {
  // Why would you block yourself ?
  if(imgur._.auth.url != window.location.pathname.split('/', 4) [2]){
   setup_block_gui();
  }
}
// Filter posts and comments
 else {
   // TODO: navigate away when first load is blocked ?
   // Filter posts:
   /* TODO: try this for the initial load
   hookit_pre(Imgur.InsideNav._instance._.sideGallery, '_loadPage', function(){
     console.log('asd load', arguments);
     return arguments;
   });
   */
   // This works sometimes for the initial load, but always for every load after that
   hookit_pre(Imgur.InsideNav._instance._.sideGallery, '_ajaxSuccess', function(args){
     arguments[0]['data'] = $.grep(arguments[0]['data'], function(v){
       return !(blocked.hasOwnProperty(v.account_id) && blocked[v.account_id][0] == 1);
     });
     return arguments;
   });
   imgur._.emitter.callbacks['sidegalleryPageLoad'].push({f:function(){
     // pretty dirsty but the values are overwritten soemwehere after the event
     // TODO: ...
     window.setTimeout(function(){
       Imgur.InsideNav._instance._.sideGallery.state.items = $.grep(Imgur.InsideNav._instance._.sideGallery.state.items, function(v){
         if((blocked.hasOwnProperty(v.account_id) && blocked[v.account_id][0] == 1))
          console.log('asd block', v);
         return !(blocked.hasOwnProperty(v.account_id) && blocked[v.account_id][0] == 1);
       });
       // recreate the box (TODO: Read that code)
       Imgur.InsideNav._instance._.sideGallery._onScroll();
     }, 1000);
   }, this_arg:{}});

  // Filter comments
  // I didn't found a fitting  event to filter the comments, so lets just hook the process comments function
  // TODO: try to run earlier or run once at site load for already loaded comments
  var _pcaptions = Imgur.InsideNav._instance.processCaptions;
  function process_captions_hook(ori, ori_this) {
    handle_blocked_comments(function (comment) {
      if(blocked[comment.author_id][1] == 0)
        return;
      //console.log('asd removed before render:', comment);
      if (blocked[comment.author_id][2] == 1 || !has_nonblocked_childs(comment)) {
        deleteCaption(comment.id);
      } else {
        comment.caption = 'Blocked';
      }
    });
    ori.call(Imgur.InsideNav._instance);
  }
  Imgur.InsideNav._instance.processCaptions = process_captions_hook.bind(this, _pcaptions, Imgur.InsideNav._instance);
  /*
  * Remove all already rendered comments. Used for the initial load.
  */
  function remove_rendered_comments() {
    handle_blocked_comments(function (comment) {
      //console.log('asd Removed after render:', comment);
      if (blocked[comment.author_id] == 1 || !has_nonblocked_childs(comment)) {
        captioninstance.deleteCaption(comment.id);
        $('.caption').filter('[data-id="' + comment.id + '"]').hide();
      } else {
        comment.caption = 'Blocked';
        $('.caption').filter('[data-id="' + comment.id + '"]').find('.usertext p span').text('Blocked');
      }
    });
  }
  remove_rendered_comments();
}
<|endoftext|>


<commit_before>const grpc = require('grpc');
const path = require('path');
const debug = require('debug')('groa:application');
const loader = require('./loader');

class Application {

	constructor() {

		this.middleware = [];
		this.server = new grpc.Server();
		this.services = {};
		this.roots = [];
		this.protoFiles = [];
	}

	throw(...args) {
		let err = new Error();

		if (args.length === 0) {
			err.code = Application.status.UNKNOWN;
			err.message = 'Internal server error';
			throw err;
		}

		if (args[0] instanceof String) {
			err.code = Application.status.UNKNOWN;
			err.message = args[0];
		} else {
			err.code = args[0];

			if (args.length == 2) {
				err.message = args[1];
			}
		}

		throw err;
	}

	async _next(ctx, middlewares) {

		// Getting next middleware
		let iterator = middlewares.next();
		if (iterator.done === true) {
			return;
		}

		return await iterator.value(ctx, this._next.bind(this, ctx, middlewares));
	}

	async _handler(ctx) {

		// No handler
		if (this.middleware.length === 0) {
			ctx.status = Application.status.UNIMPLEMENTED;
			ctx.body = 'Method is not implemented';
			return;
		}

		// Getting iterator
		let middlewares = this.middleware[Symbol.iterator]();

		try {
			await this._next(ctx, middlewares);
		} catch(e) {
			ctx.status = e.code;

			if (ctx.status === undefined) {
				ctx.status = Application.status.ABORTED;
			}

			if (e.message instanceof String) {
				ctx.body = e.message;
			} else {
				ctx.body = JSON.stringify(e.message);
			}
		}

		if (!ctx.body) {
			ctx.status = Application.status.UNIMPLEMENTED;
			ctx.body = 'Method is not implemented';
		} else if (ctx.status === undefined) {
			ctx.status = Application.status.OK;
		}
	}

	async handler(objPath, call, callback) {

		// Preparing context
		let ctx = {
			app: this,
			path: objPath,
			status: undefined,
			message: undefined,
			throw: this.throw,
			requestStream: call.readable ? true : false,
			responseStream: call.writable ? true : false,
			req: {
				path: objPath,
				metadata: call.metadata.getMap(),
				body: call.readable ? call : call.request
			},
			body: undefined
		};

		if (call.writable) {
			// Streaming
			ctx.body = call;
			await this._handler(ctx);
		} else {
			// Normal request
			await this._handler(ctx);

			if (ctx.status === Application.status.OK) {
				callback(null, ctx.body);
			} else {

				// for specific status code and message
				callback({
					code: ctx.status,
					message: ctx.body
				});
			}
		}
	}

	use(fn) {

		if (typeof fn !== 'function')
			throw new TypeError('middleware must be a function!');

		debug('use %s', fn._name || fn.name || '-');

		this.middleware.push(fn);

		return this;
	}

	addProto(filename) {

		if (filename instanceof Array) {
			return filename.map((file) => {
				return this.loadProto(file);
			});
		}

		let file = path.resolve(filename);
		if (this.protoFiles.indexOf(file) === -1) {
			this.protoFiles.push(file);
		}
	}

	updateMethod(methodPath, opts) {

		if (opts.serialize)
			this.server.handlers[methodPath].serialize = opts.serialize;

		if (opts.deserialize)
			this.server.handlers[methodPath].deserialize = opts.deserialize;

	}

	registerService(service, implementations, opts) {

		const _register = () => {

			this.server.addService(service, implementations);

			// Customizations
			Object.entries(service).forEach(([ methodName, attrs ]) => {

				if (opts.serialize)
					this.server.handlers[attrs.path].serialize = opts.serialize;

				if (opts.deserialize)
					this.server.handlers[attrs.path].deserialize = opts.deserialize;
			});
		};

		if (this.server.started) {
			// Workaround: addServer will stop us adding service if server is started, so we set property.
			this.server.started = false;

			_register();

			this.server.started = true;
		} else {
			_register();
		}
	}

	async applyProto(proto, opts = {}) {

		opts = Object.assign({
			serialize: undefined,
			deserialize: undefined,
		}, opts);

		// Verifying
		for (let serviceName in proto.services) {
			let def = proto.services[serviceName];

			if (Object.keys(def.service).length === 0) {
				console.warn('Warning:', 'Ignore', serviceName, 'which is an empty service');
			}
		}

		let services = this.services = Object.assign(this.services, proto.services);

		const capitalize = function(str) {
			return str.charAt(0).toUpperCase() + str.slice(1);
		}

		// Preparing services
		Object.entries(proto.services).forEach(([ serviceName, def ]) => {

			let methods = Object.keys(def.service);

			// Ignore empty service
			if (methods.length === 0)
				return;

			let implementations = methods.reduce((implementations, method) => {

				implementations[method] = this.handler.bind(this, '/' + serviceName + '/' + capitalize(method));

				return implementations;
			}, {});

			// Register
			this.registerService(def.service, implementations, opts)
		});

		this.roots.push(proto.root);
	}

	async loadProto(filename) {

		let proto = await loader.loadProto(filename);

		await this.applyProto(proto);
	}

	lookupType(type) {

		let root = this.roots.find((root) => {
			try {
				return root.lookupType(type);
			} catch(e) {
				return false;
			}
		});

		if (root)
			return root.lookupType(type);
	}

	async _initializeServices() {

		for (let index in this.protoFiles) {

			let filename = this.protoFiles[index];

			await this.loadProto(filename);
		}
	}

	async _listen(port, host) {

		await this._initializeServices();

		this.server.bind(host + ':' + port, grpc.ServerCredentials.createInsecure());
		this.server.start();
	}

	async forceShutdown() {
		this.server.forceShutdown();
	}

	tryShutdown() {

		return new Promise((resolve, reject) => {
			this.server.tryShutdown((err) => {

				if (err)
					return reject(err);

				resolve();
			});
		});
	}

	listen(...args) {

		let callback;
		let port = 50051;
		let host = '0.0.0.0';
		if (args.length === 3) {
			port = args[0];
			host = args[1];
			callback = args[2];
		} else if (args.length === 2) {
			port = args[0];
			callback = args[1];
		} else {
			port = args[0];
		}

		this._listen(port, host)
			.then(() => {
				if (callback !== undefined) {
					callback();
				}
			})
			.catch((e) => {
				if (callback !== undefined) {
					callback(e);
				}
			});

		return this.server;
	}
};

Application.Loader = loader;
Application.status = grpc.status;
Application.Metadata = grpc.Metadata;
Application.grpc = grpc;
Application.Client = require('./client');

module.exports = Application;
<commit_msg>considered method is not implemented if body is set undefined<commit_after>const grpc = require('grpc');
const path = require('path');
const debug = require('debug')('groa:application');
const loader = require('./loader');

class Application {

	constructor() {

		this.middleware = [];
		this.server = new grpc.Server();
		this.services = {};
		this.roots = [];
		this.protoFiles = [];
	}

	throw(...args) {
		let err = new Error();

		if (args.length === 0) {
			err.code = Application.status.UNKNOWN;
			err.message = 'Internal server error';
			throw err;
		}

		if (args[0] instanceof String) {
			err.code = Application.status.UNKNOWN;
			err.message = args[0];
		} else {
			err.code = args[0];

			if (args.length == 2) {
				err.message = args[1];
			}
		}

		throw err;
	}

	async _next(ctx, middlewares) {

		// Getting next middleware
		let iterator = middlewares.next();
		if (iterator.done === true) {
			return;
		}

		return await iterator.value(ctx, this._next.bind(this, ctx, middlewares));
	}

	async _handler(ctx) {

		// No handler
		if (this.middleware.length === 0) {
			ctx.status = Application.status.UNIMPLEMENTED;
			ctx.body = 'Method is not implemented';
			return;
		}

		// Getting iterator
		let middlewares = this.middleware[Symbol.iterator]();

		try {
			await this._next(ctx, middlewares);
		} catch(e) {
			ctx.status = e.code;

			if (ctx.status === undefined) {
				ctx.status = Application.status.ABORTED;
			}

			if (e.message instanceof String) {
				ctx.body = e.message;
			} else {
				ctx.body = JSON.stringify(e.message);
			}
		}

		if (ctx.body === undefined) {
			ctx.status = Application.status.UNIMPLEMENTED;
			ctx.body = 'Method is not implemented';
		} else if (ctx.status === undefined) {
			ctx.status = Application.status.OK;
		}
	}

	async handler(objPath, call, callback) {

		// Preparing context
		let ctx = {
			app: this,
			path: objPath,
			status: undefined,
			message: undefined,
			throw: this.throw,
			requestStream: call.readable ? true : false,
			responseStream: call.writable ? true : false,
			req: {
				path: objPath,
				metadata: call.metadata.getMap(),
				body: call.readable ? call : call.request
			},
			body: undefined
		};

		if (call.writable) {
			// Streaming
			ctx.body = call;
			await this._handler(ctx);
		} else {
			// Normal request
			await this._handler(ctx);

			if (ctx.status === Application.status.OK) {
				callback(null, ctx.body);
			} else {

				// for specific status code and message
				callback({
					code: ctx.status,
					message: ctx.body
				});
			}
		}
	}

	use(fn) {

		if (typeof fn !== 'function')
			throw new TypeError('middleware must be a function!');

		debug('use %s', fn._name || fn.name || '-');

		this.middleware.push(fn);

		return this;
	}

	addProto(filename) {

		if (filename instanceof Array) {
			return filename.map((file) => {
				return this.loadProto(file);
			});
		}

		let file = path.resolve(filename);
		if (this.protoFiles.indexOf(file) === -1) {
			this.protoFiles.push(file);
		}
	}

	updateMethod(methodPath, opts) {

		if (opts.serialize)
			this.server.handlers[methodPath].serialize = opts.serialize;

		if (opts.deserialize)
			this.server.handlers[methodPath].deserialize = opts.deserialize;

	}

	registerService(service, implementations, opts) {

		const _register = () => {

			this.server.addService(service, implementations);

			// Customizations
			Object.entries(service).forEach(([ methodName, attrs ]) => {

				if (opts.serialize)
					this.server.handlers[attrs.path].serialize = opts.serialize;

				if (opts.deserialize)
					this.server.handlers[attrs.path].deserialize = opts.deserialize;
			});
		};

		if (this.server.started) {
			// Workaround: addServer will stop us adding service if server is started, so we set property.
			this.server.started = false;

			_register();

			this.server.started = true;
		} else {
			_register();
		}
	}

	async applyProto(proto, opts = {}) {

		opts = Object.assign({
			serialize: undefined,
			deserialize: undefined,
		}, opts);

		// Verifying
		for (let serviceName in proto.services) {
			let def = proto.services[serviceName];

			if (Object.keys(def.service).length === 0) {
				console.warn('Warning:', 'Ignore', serviceName, 'which is an empty service');
			}
		}

		let services = this.services = Object.assign(this.services, proto.services);

		const capitalize = function(str) {
			return str.charAt(0).toUpperCase() + str.slice(1);
		}

		// Preparing services
		Object.entries(proto.services).forEach(([ serviceName, def ]) => {

			let methods = Object.keys(def.service);

			// Ignore empty service
			if (methods.length === 0)
				return;

			let implementations = methods.reduce((implementations, method) => {

				implementations[method] = this.handler.bind(this, '/' + serviceName + '/' + capitalize(method));

				return implementations;
			}, {});

			// Register
			this.registerService(def.service, implementations, opts)
		});

		this.roots.push(proto.root);
	}

	async loadProto(filename) {

		let proto = await loader.loadProto(filename);

		await this.applyProto(proto);
	}

	lookupType(type) {

		let root = this.roots.find((root) => {
			try {
				return root.lookupType(type);
			} catch(e) {
				return false;
			}
		});

		if (root)
			return root.lookupType(type);
	}

	async _initializeServices() {

		for (let index in this.protoFiles) {

			let filename = this.protoFiles[index];

			await this.loadProto(filename);
		}
	}

	async _listen(port, host) {

		await this._initializeServices();

		this.server.bind(host + ':' + port, grpc.ServerCredentials.createInsecure());
		this.server.start();
	}

	async forceShutdown() {
		this.server.forceShutdown();
	}

	tryShutdown() {

		return new Promise((resolve, reject) => {
			this.server.tryShutdown((err) => {

				if (err)
					return reject(err);

				resolve();
			});
		});
	}

	listen(...args) {

		let callback;
		let port = 50051;
		let host = '0.0.0.0';
		if (args.length === 3) {
			port = args[0];
			host = args[1];
			callback = args[2];
		} else if (args.length === 2) {
			port = args[0];
			callback = args[1];
		} else {
			port = args[0];
		}

		this._listen(port, host)
			.then(() => {
				if (callback !== undefined) {
					callback();
				}
			})
			.catch((e) => {
				if (callback !== undefined) {
					callback(e);
				}
			});

		return this.server;
	}
};

Application.Loader = loader;
Application.status = grpc.status;
Application.Metadata = grpc.Metadata;
Application.grpc = grpc;
Application.Client = require('./client');

module.exports = Application;
<|endoftext|>