adapted from uitil <https://github.com/FND/uitil>
182524
function debounce(delay, fn) {
	let timer;
	return function() {
		let args = arguments;
		if(timer) {
			clearTimeout(timer);
			timer = null;
		}
		timer = setTimeout(_ => {
			fn.apply(null, args);
			timer = null;
		}, delay);
	};
}
406918
function UI (input, output) {
  this.rl = readline.createInterface({
    input: input || ttys.stdin,
    output: output || ttys.stdout
  })
  
  // Delegated events bind.
  this.onLine = (function onLine () {
    _events.line.apply(this, arguments)
  }).bind(this)
  
  this.onKeypress = (function onKeypress () {
    if (this.rl) {
      _events.keypress.apply(this, arguments)
    }
  }).bind(this)
  
  this.forceClose = this.forceClose.bind(this)
  
  this.rl.addListener('line', this.onLine)
  this.rl.input.addListener('keypress', this.onKeypress)
  
  this.rl.on('SIGINT', this.forceClose)
  process.on('exit', this.forceClose)
}
48004
function T(iid, val, type, hasGetterSetter, internalIid) {
        var aret;
        associateSidWithFunction(val, internalIid);
        if (hasGetterSetter) {
            for (var offset in val) {
                if (hasGetOwnPropertyDescriptor && val.hasOwnProperty(offset)) {
                    var desc = Object.getOwnPropertyDescriptor(val, offset);
                    if (desc !== undefined) {
                        if (typeof desc.get === 'function') {
                            T(iid, desc.get, 12, false, internalIid);
                        }
                        if (typeof desc.set === 'function') {
                            T(iid, desc.set, 12, false, internalIid);
                        }
                    }
                }
            }
        }
        if (sandbox.analysis && sandbox.analysis.literal) {
            aret = sandbox.analysis.literal(iid, val, hasGetterSetter);
            if (aret) {
                val = aret.result;
            }
        }
        return (lastComputedValue = val);
    }
181516
function func(declarations, functions, functionMatcher, parseArgs) {
  if (!declarations) return;
  if (false !== parseArgs) parseArgs = true;

  declarations.forEach(function(decl){
    if ('comment' == decl.type) return;
    var generatedFuncs = [], result, generatedFunc;

    while (decl.value.match(functionMatcher)) {
      decl.value = decl.value.replace(functionMatcher, function(_, name, args){
        if (parseArgs) {
          args = args.split(/\s*,\s*/).map(strip);
        } else {
          args = [strip(args)];
        }
        // Ensure result is string
        result = '' + functions[name].apply(decl, args);

        // Prevent fall into infinite loop like this:
        //
        // {
        //   url: function(path) {
        //     return 'url(' + '/some/prefix' + path + ')'
        //   }
        // }
        //
        generatedFunc = {from: name, to: name + getRandomString()};
        result = result.replace(functionMatcherBuilder(name), generatedFunc.to + '($2)');
        generatedFuncs.push(generatedFunc);
        return result;
      });
    }

    generatedFuncs.forEach(function(func) {
      decl.value = decl.value.replace(func.to, func.from);
    })
  });
}
1241516
def ui_main(fmt_table, node_dict):
    """"""
    cmd_funct = {"quit": False,
                 "run": node_cmd,
                 "stop": node_cmd,
                 "connect": node_cmd,
                 "details": node_cmd,
                 "update": True}
    ui_print("\033[?25l")  # cursor off
    print("{}\n".format(fmt_table))
    sys.stdout.flush()
    # refresh_main values:
    #   None = loop main-cmd, True = refresh-list, False = exit-program
    refresh_main = None
    while refresh_main is None:
        cmd_name = get_user_cmd(node_dict)
        if callable(cmd_funct[cmd_name]):
            refresh_main = cmd_funct[cmd_name](cmd_name, node_dict)
        else:
            refresh_main = cmd_funct[cmd_name]
    if cmd_name != "connect" and refresh_main:
        ui_clear(len(node_dict) + 2)
    return refresh_main
1018982
function stringInterner() { // eslint-disable-line no-unused-vars
  const strings = [];
  const ids = {};
  return {
    intern: function internString(s) {
      const find = ids[s];
      if (find === undefined) {
        const id = strings.length;
        ids[s] = id;
        strings.push(s);
        return id;
      } else {
        return find;
      }
    },
    get: function getString(id) {
      return strings[id];
    },
  };
}
513326
function DefaultSkillResolutionStrategyFn() {
    const util = require('util');
    const extend = util._extend;
    const skillsMap = {};
    const undefinedSkills = [];

    this.addSkill = function(skill, options) {
        var minConfidence = 0;
        if(options instanceof Number) {
            minConfidence = options;
        } else if (options && options.minConfidence !== undefined) {
            minConfidence = options.minConfidence;
        }

        var skillClone = extend({}, skill);
        var botSkillObject = {skill: skillClone, minConfidence: minConfidence};

        if (skillClone.topic === undefined || skillClone.topic === 'undefined') {
            skillClone.topic = undefined;
            undefinedSkills.push(botSkillObject);
        }

        if(skillClone.topic instanceof Array) {
            skillClone.topic.forEach(function(topic) {
                if(skillsMap[topic] === undefined) skillsMap[topic] = [];
                skillsMap[topic].push(skillClone);
            });
        } else {
            if (skillsMap[skillClone.topic] === undefined) {
                skillsMap[skillClone.topic] = [];
            }

            skillsMap[skillClone.topic].push(botSkillObject);
        }
    };

    this.getSkills = function() {
        var topics = Object.keys(skillsMap);
        var skills = [];

        topics.forEach(function (topic) {
            skills.push(skillsMap[topic]);
        });

        return skills;
    };

    var _resolveSkillFromTopicWithConfidence = function ResolveSkillFromTopicWithConfidenceFn(topic) {
        if (topic.name === undefined) {
            if (undefinedSkills && undefinedSkills.length > 0) {
                return undefinedSkills[0];
            }

            return;
        }

        var botSkills = skillsMap[topic.name];
        var minConfidenceSkill = undefinedSkills[0];
        var minDistance = 999;
        if (botSkills !== undefined && botSkills.length > 0) {
            for (var i = 0; i < botSkills.length; i++) {
                var botSkill = botSkills[i];
                var distance = topic.confidence - botSkill.minConfidence;
                if (distance < 0) continue;
                if (distance < minDistance) {
                    minDistance = distance;
                    minConfidenceSkill = botSkill;
                }
                if (distance === 0) break;
            }
        }

        return minConfidenceSkill;
    };

    this.resolve = function(err, resolutionContext, callback) {
        var topics = resolutionContext.topics;
        var sentence = resolutionContext.sentence;
        var mostConfidentTopic = topics[0];
        var resolvedBotSkill = _resolveSkillFromTopicWithConfidence(mostConfidentTopic);
        var skill = resolvedBotSkill ? resolvedBotSkill.skill : undefined;

        if (skill === undefined) {
            return callback(new Error("could not resolve any skills"));
        }

        var clonedSkill = extend({}, skill);
        clonedSkill.sentence = sentence;
        clonedSkill.topic = mostConfidentTopic;

        return callback(undefined, clonedSkill);
    };

    return this;
}
659844
def hinit(func, x, t, pos_neg, f0, iord, hmax, rtol, atol, args):
    
    sk = atol + rtol * np.fabs(x)
    dnf = np.sum(np.square(f0 / sk), axis=0)
    dny = np.sum(np.square(x / sk), axis=0)

    h = np.sqrt(dny / dnf) * 0.01

    h = np.min([h, np.fabs(hmax)])
    h = custom_sign(h, pos_neg)

    # perform an explicit Euler step
    xx1 = x + h * f0
    f1 = np.array(func(xx1, t[0] + h, *args))

    # estimate the second derivative of the solution
    der2 = np.sum(np.square((f1 - f0) / sk), axis=0)
    der2 = np.sqrt(der2) / h

    # step size is computed such that h ** iord * max_d(norm(f0), norm(der2)) = 0.01
    der12 = np.max([np.fabs(der2), np.sqrt(dnf)])
    h1 = np.power(0.01 / der12, 1.0 / iord)

    h = np.min([100.0 * np.fabs(h), np.min([np.fabs(h1), np.fabs(hmax)])])

    return custom_sign(h, pos_neg), f0, f1, xx1
1310010
function toYaml(data, options) {
  var defaults = {indent: 2, skipInvalid: false, flowLevel: -1};
  var opts = extend(defaults, options);
  var fn = opts.safe ? yaml.safeDump : yaml.dump;
  return fn(data, opts);
}
903892
def widget_from_tuple(o):
        """"""
        if _matches(o, (Real, Real)):
            min, max, value = _get_min_max_value(o[0], o[1])
            if all(isinstance(_, Integral) for _ in o):
                cls = IntSlider
            else:
                cls = FloatSlider
            return cls(value=value, min=min, max=max)
        elif _matches(o, (Real, Real, Real)):
            step = o[2]
            if step <= 0:
                raise ValueError("step must be >= 0, not %r" % step)
            min, max, value = _get_min_max_value(o[0], o[1], step=step)
            if all(isinstance(_, Integral) for _ in o):
                cls = IntSlider
            else:
                cls = FloatSlider
            return cls(value=value, min=min, max=max, step=step)
1225355
def _dump_impl():
    # type: () -> List[FunctionData]
    """"""
    filtered_signatures = _filter_types(collected_signatures)
    sorted_by_file = sorted(iteritems(filtered_signatures),
                            key=(lambda p: (p[0].path, p[0].line, p[0].func_name)))
    res = []  # type: List[FunctionData]
    for function_key, signatures in sorted_by_file:
        comments = [_make_type_comment(args, ret_type) for args, ret_type in signatures]
        res.append(
            {
                'path': function_key.path,
                'line': function_key.line,
                'func_name': function_key.func_name,
                'type_comments': comments,
                'samples': num_samples.get(function_key, 0),
            }
        )
    return res
1175132
function () {

        var a = arguments;

        if( typeof a[1] === 'object' ){ 

            a[1].isUI = true;
            a[1].main = this;

        } else if( typeof a[1] === 'string' ){

            if( a[2] === undefined ) [].push.call(a, { isUI:true, main:this });
            else {
                a[2].isUI = true;
                a[2].main = this;
            }
            
        } 

        var u = add.apply( this, a );

        if( u === null ) return;


        //var n = add.apply( this, a );
        //var n = UIL.add( ...args );

        this.uis.push( u );
        //n.py = this.h;

        if( !u.autoWidth ){
            var y = u.c[0].getBoundingClientRect().top;
            if( this.prevY !== y ){
                this.calc( u.h + 1 );
                this.prevY = y;
            }
        }else{
            this.prevY = 0;//-1;
            this.calc( u.h + 1 );
        }

        return u;

    }
1151154
function __() {
    var us = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
    var store = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;

    store = typeof us === "boolean" ? us : store;
    us = typeof us === "boolean" ? [] : us;

    var seq = []; //seq is vanilla JS array + features
    seq.id = getID();
    seq.store = store;
    seq.us = us;
    seq.ds = [];
    seq.updatedTo = {};
    seq.us.map(function (u) {
      //  seq is a member of u.ds
      u.ds[u.ds.length] = seq;
      u.updatedTo[seq.id] = 0; // non-interference dependency
    });
    seq.IndexOnTimestamp = {};
    seq.TimestampOnIndex = {};
    seq.propagating = 0;
    seq.done = 0;
    seq.eqs = [];
    seq.addEq = function (eq) {
      return seq.eqs[seq.eqs.length] = eq;
    };
    seq.evalEqs = function (val) {
      var val0 = val;
      seq.eqs.map(function (eq) {
        return val = eq(val);
      });
      return seq.us.length === 0 ? val0 : val;
    };
    //api-----------------
    Object.keys(__.api).map(function (api) {
      seq[api] = __.api[api](__, seq, store);
    });
    //-----------------
    Object.defineProperties(seq, //detect t update on each seqs
    {
      t: {
        //foo.t
        get: function get() {
          return seq.valOnT;
        },
        set: function set(tval) {
          var sanityCheck = seq.propagating === 0 && seq.us.length !== 0 ? function () {
            throw new Error("Do not set a value of the sequence that depends on other sequences!");
          }() : function () {
            seq.propagating = 0;
            var core = seq.done === 0 ? function () {
              seq.valOnT = seq.evalEqs(tval); //self eqs eval
              seq.T = Date.now();
              var core1 = store ? function () {
                seq.IndexOnTimestamp[seq.T] = seq.length;
                seq.TimestampOnIndex[seq.length] = seq.T;
                seq[seq.length] = seq.valOnT; //after funcs
              }() : true;
              Object.keys(seq.updatedTo).map(function (key) {
                seq.updatedTo[key] = 1;
              });
              //clear updated us in non-interference way
              seq.us.map(function (u) {
                return u.updatedTo[seq.id] = 0;
              });
              seq.ds.map(function (d) {
                var usAllUpdated = d.us.map(function (u) {
                  return u.updatedTo[d.id];
                }).reduce(function (a, b) {
                  return a * b;
                });
                var core2 = usAllUpdated === 1 ? function () {
                  d.propagating = 1;
                  d.t = d.us.map(function (u) {
                    return u.t;
                  });
                }() : true;
              });
            }() : true;
          }();
        }
      }
    });
    return seq;
  }
1134358
function (str, notlid = false, includeTlido = false, includeIndent = true) {

        var otxt = str;

        var reSTCDeco = /((@[a-zA-Z0-9._-]+))/g;

        if (this.has(str)) {
            var r = new Object();

            var decorator =
                this.get(otxt);
            if (includeIndent)
                r.indent = otxt.indexOf(decorator) - 1;



            r.deco = decorator;
            r.src = str;
            // var tlido = null;


            if (!notlid && tlid.has(str)) {
                var tlido = tlid.xtro(str);
                //  console.log(tlido);

                otxt = tlido.txt; //cleared from tlid text

                if (includeTlido) {
                    r.tlido = new Object();
                    r.tlido = tlido;
                    //    JSON.stringify(tlido);
                }
                r.tlid = tlido.tlid;
            }

            var clnTxt = this.cleanDecorator(decorator, otxt);
            r.txt = clnTxt;


            return r;
        }
        else return null;
    }
1310363
def _ioctl (self, func, args):
        """"""
        import fcntl
        return fcntl.ioctl(self.sockfd.fileno(), func, args)
1313545
def sliding_impl(wrap, size, step, sequence):
    
    i = 0
    n = len(sequence)
    while i + size <= n or (step != 1 and i < n):
        yield wrap(sequence[i: i + size])
        i += step
318190
function define (HTMLFile, utils) {
  const { callable } = utils;
  const { debug, error, strong } = utils.cnsl;
  const { regexpEscape, uniqueMatch } = utils.string;

  return class DUSTFile extends HTMLFile {
    /**
     * Constructor
     * @param {String} id
     * @param {String} filepath
     * @param {Object} options
     *  - {Object} caches
     *  - {Object} fileExtensions
     *  - {Function} fileFactory
     *  - {Object} globalAliases
     *  - {Array} npmModulepaths
     *  - {Object} pluginOptions
     *  - {Object} runtimeOptions
     */
    constructor (id, filepath, options) {
      super(id, filepath, options);

      this.workflows.writeable = WORKFLOW_WRITEABLE;
    }

    /**
     * Parse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    parse (buildOptions, fn) {
      super.parse(buildOptions, (err) => {
        if (err) return fn(err);
        // Add sidecar json file
        const sidecarData = super.parseSidecarDependency();
        // Parse includes
        let matches = uniqueMatch(this.content, RE_INCLUDE)
          .map((match) => {
            match.id = match.match;
            return match;
          });

        if (sidecarData) matches.push(sidecarData);
        super.addDependencies(matches, buildOptions);
        fn();
      });
    }

    /**
     * Inline css/img/js dependency content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineInlineable (buildOptions, fn) {
      // Only dependencies
      parallel([...this.getAllDependencies()].reduce((inlineable, file) => {
        if (file instanceof DUSTFile && this.dependencyReferences.length) {
          inlineable.push(callable(file, 'inline', buildOptions));
        }
        return inlineable;
      }, []), fn);
    }

    /**
     * Inline partials content
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Boolean} helpers
     *  - {Array} ignoredFiles
     *  - {Boolean} import
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    inlineIncludes (buildOptions, fn) {
      [...this.getAllDependencies(), this].forEach((file) => {
        if (file instanceof DUSTFile && file.dependencyReferences.length) {
          let content = file.content;

          file.dependencyReferences.forEach((reference) => {
            if (reference.file && reference.context) {
              content = content.replace(new RegExp(regexpEscape(reference.context), 'g'), reference.file.content);
            }
          });

          file.setContent(content);
        }
      });
      fn();
    }

    /**
     * Compile file contents
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    compile (buildOptions, fn) {
      // Keep whitespace
      dust.optimizers.format = (ctx, node) => node;
      // Precompile and load
      const source = dust.compile(this.content, this.filepath);

      dust.loadSource(source);
      dust.render(this.filepath, this.findSidecarDependency(), (err, content) => {
        if (err) {
          if (!this.options.runtimeOptions.watch) return fn(err);
          error(err, 4, false);
        }
        this.setContent(content);
        debug(`compile: ${strong(this.relpath)}`, 4);
        fn();
      });
    }

    /**
     * Reparse file contents for dependency references
     * @param {Object} buildOptions
     *  - {Boolean} batch
     *  - {Boolean} bootstrap
     *  - {Boolean} boilerplate
     *  - {Boolean} browser
     *  - {Boolean} bundle
     *  - {Boolean} compress
     *  - {Array} ignoredFiles
     *  - {Boolean} helpers
     *  - {Boolean} watchOnly
     * @param {Function} fn(err)
     */
    reparse (buildOptions, fn) {
      this.allDependencies = null;
      this.allDependencyReferences = null;
      this.dependencies = [];
      this.dependencyReferences = [];

      super.parse(buildOptions, fn);
    }
  };
}