text:
/**
 * @file
 * @brief Contains the implementation of the TPZNodesetCompute methods.
 */
//
// C++ Implementation: tpznodesetcompute
//
// Description:
//
//
// Author: Philippe R. B. Devloo <phil@fec.unicamp.br>, (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "tpznodesetcompute.h"
#include "pzstack.h"
#include "pzblock.h"
#include <set>
#include <map>
#include <algorithm>
#include <iterator>
#include <fstream>
#include "pzlog.h"

#ifdef LOG4CXX
static LoggerPtr logger(Logger::getLogger("pz.mesh.nodesetcompute"));
#endif

//static std::ofstream out("nodeset.txt");

TPZNodesetCompute::TPZNodesetCompute()
{
  fMaxSeqNum = -1;
  fMaxLevel = -1;
}

TPZNodesetCompute::~TPZNodesetCompute()
{
}

    /**
    Group the node graph as passed by the parameters
    */
void TPZNodesetCompute::AnalyseGraph()
{
  fMaxSeqNum = -1;
  fMaxLevel = -1;
  int nnodes = fNodegraphindex.NElements()-1;
  fSeqNumber.Resize(nnodes);
  this->fLevel.Resize(nnodes);
  fSeqNumber.Fill(-1);
	fIsIncluded.Resize(nnodes);
	fIsIncluded.Fill(0);
  fLevel.Fill(0);
  TPZVec<std::set<int> > nodeset(nnodes);
  int in;
  for(in=0; in<nnodes; in++)
  {
	  if(!(in%1000))
	  {
		  std::cout << "*";
		  std::cout.flush();
	  }
	  AnalyseNode(in,nodeset);
  }
	std::cout << std::endl;

}

/**
 * This method will analyse the set inclusion of the current node, calling the method
 * recursively if another node need to be analysed first
 */
void TPZNodesetCompute::AnalyseNode(int node, TPZVec< std::set<int> > &nodeset)
{
  if(fSeqNumber[node] != -1) return;
  if(! nodeset[node].size())
  {
    nodeset[node].insert(&fNodegraph[fNodegraphindex[node]],&fNodegraph[fNodegraphindex[node+1]]);
    nodeset[node].insert(node);
  }
  int minlevel = 0;
  std::set<int>::iterator it;
  TPZStack<int> equalnodes;
  for(it = nodeset[node].begin(); it != nodeset[node].end(); it++)
  {
    int othernode = *it;
    if(othernode == node) continue;
    // build the data structure of the connected node
    if(! nodeset[othernode].size())
    {
      nodeset[othernode].insert(&fNodegraph[fNodegraphindex[othernode]],&fNodegraph[fNodegraphindex[othernode+1]]);
      nodeset[othernode].insert(othernode);
    }
    // the other node is included in my connectivity
    bool inc = includes(nodeset[node].begin(),nodeset[node].end(),nodeset[othernode].begin(),nodeset[othernode].end());
    // the other node has a different connectivity
    bool diff = nodeset[node] != nodeset[othernode];
    if( inc && diff)
    {
      // Analyse the connectivity graph of the other node
      // Its graph is smaller than mine
		fIsIncluded[othernode] = 1;
      AnalyseNode(othernode,nodeset);
      minlevel = minlevel < fLevel[othernode]+1 ? fLevel[othernode]+1 : minlevel;
#ifdef LOG4CXX
		if(fLevel[othernode] >= 0)
		{
			std::stringstream sout;
			sout << "The level of " << node << " is increased because of " << othernode << " ";
			sout << "Level of othernode " << fLevel[othernode] << " Seqnumber othernode " << fSeqNumber[othernode];
			LOGPZ_DEBUG(logger,sout.str())
		}
#endif
    }
    else if(!diff)
    {
      // The graphs are equal. These nodes should be grouped
		if(fIsIncluded[node])
		{
			fIsIncluded[othernode] = 1;
		}
      equalnodes.Push(othernode);
    }
    // the other node has been analysed (and is probably not equal...)
    if(inc && diff && fSeqNumber[othernode] != -1)
    {
		fIsIncluded[othernode] = 1;
      minlevel = minlevel < fLevel[othernode]+1 ? fLevel[othernode]+1 : minlevel;
    } else if(!diff && fSeqNumber[othernode] != -1)
    {
      // the level should be at least the level of the other node
      minlevel = minlevel < fLevel[othernode] ? fLevel[othernode] : minlevel;
		// should not happen because if the nodes are equal, they both have the same sequence number
		DebugStop();
    }
  }
  // assign a sequence number to the node
  fMaxSeqNum++;
  fSeqNumber[node] = fMaxSeqNum;
#ifdef LOG4CXX
	{
		std::stringstream sout;
		sout << "Assigning Seq Number " << fMaxSeqNum << " and level " << minlevel << " to nodes " << node << " " << equalnodes;
		LOGPZ_DEBUG(logger,sout.str())
	}
#endif
  fSeqCard.Push(1);
  // the maximum level of the set of nodes
  fMaxLevel = fMaxLevel < minlevel ? minlevel : fMaxLevel;
  // assign the level of the node
  fLevel[node] = minlevel;
	nodeset[node].erase(node);

  // memory clean up
  for(it = nodeset[node].begin(); it != nodeset[node].end(); it++)
  {
    int othernode = *it;
	  int level = fLevel[othernode];
	  int seq = fSeqNumber[othernode];
    if(seq != -1 && level <= minlevel)
	{
		nodeset[othernode].clear();
		if(othernode == node)
		{
			LOGPZ_ERROR(logger," othernode equal to node!!")
			DebugStop();
			break;
		}
	}
  }
  nodeset[node].clear();
  // initialize the datastructure of the nodes which have the same connectivity
  int neq = equalnodes.NElements();
  int ieq;
  for(ieq=0; ieq<neq; ieq++)
  {
    fSeqNumber[equalnodes[ieq]] = fMaxSeqNum;
    fLevel[equalnodes[ieq]] = minlevel;
    // I think this is overkill : this nodeset should already be empty...
    nodeset[equalnodes[ieq]].clear();
    // the number of nodes associated with this sequence number
    fSeqCard[fMaxSeqNum]++;
  }
}

void TPZNodesetCompute::BuildNodeGraph(TPZVec<int> &blockgraph, TPZVec<int> &blockgraphindex)
{
  int nnodes = fSeqNumber.NElements();
  blockgraphindex.Resize(fSeqCard.NElements()+1);
  blockgraph.Resize(nnodes);
  int seq = 0;
  blockgraphindex[0] = 0;
  blockgraphindex[1] = 0;
  for(seq=2; seq<=fSeqCard.NElements(); seq++)
  {
    blockgraphindex[seq] = blockgraphindex[seq-1]+fSeqCard[seq-2];
  }
  int in;
  for(in = 0; in< nnodes; in++)
  {
    int seqn = fSeqNumber[in];
    blockgraph[blockgraphindex[seqn+1]] = in;
    blockgraphindex[seqn+1]++;
  }
}

void TPZNodesetCompute::BuildVertexGraph(TPZStack<int> &blockgraph, TPZVec<int> &blockgraphindex)
{
  std::map<int,int> vertices;
  int nnodes = fSeqNumber.NElements();
  int in;
  for(in=0; in<nnodes; in++)
  {
    if(fLevel[in] == this->fMaxLevel) vertices[fSeqNumber[in]] = in;
  }
  int nvert = vertices.size();
  blockgraphindex.Resize(nvert+1);
  blockgraphindex[0] = 0;
  int iv = 1;
  std::map<int,int>::iterator it;
  for(it=vertices.begin(); it != vertices.end(); it++)
  {
    int node = (*it).second;
    blockgraph.Push(node);
    std::set<int> vertexset;
    std::set<int> included;
    std::set<int> notincluded;
    // The set will contain the connectivity of the node
    BuildNodeSet(node,vertexset);
    included.insert((*it).first);
    std::set<int>::iterator versetit;
    for(versetit = vertexset.begin(); versetit != vertexset.end(); versetit++)
    {
      int linkednode = *versetit;
      if(linkednode == node) continue;
      int seq = fSeqNumber[linkednode];

      // if the sequence number of the equation is already included in the nodeset of the vertex, put it in the blockgraph
      // this node has equal connectivity with other node
      if(included.count(seq))
      {
        blockgraph.Push(linkednode);
      }
      // if the seq number is recognized as not to be included stop analysing
      // this node has equal connectivity with other node
      else if(notincluded.count(seq))
      {
        continue;
      }
      // the equation hasn t been analysed yet
      else
      {
        std::set<int> locset;
        BuildNodeSet(linkednode,locset);
        // if its nodeset is included in the vertexset
        if(includes(vertexset.begin(),vertexset.end(),locset.begin(),locset.end()))
        {
          included.insert(seq);
          blockgraph.Push(linkednode);
        }
        // else this sequence number should not be analysed anymore
        else
        {
          notincluded.insert(seq);
        }
      }
    }
    blockgraphindex[iv] = blockgraph.NElements();
    iv++;
  }
}

void TPZNodesetCompute::BuildNodeSet(int node, std::set<int> &nodeset)
{
  nodeset.clear();
  nodeset.insert(&fNodegraph[fNodegraphindex[node]],&fNodegraph[fNodegraphindex[node+1]]);
  nodeset.insert(node);
}

/**
 * Look for elements formed by vertices, intersecting with the intersectvertices, one by one
 * If the intersection does not remove any of the intersectvertices, we found an element!
 */
void TPZNodesetCompute::AnalyseForElements(std::set<int> &vertices, std::set< std::set<int> > &elements)
{

  if(!vertices.size()) return;
  std::set<int> elem;
  std::set<int>::iterator intit,diffit;
	{
		std::stringstream sout;
		sout << __PRETTY_FUNCTION__ << " Original set of nodes ";
		Print(sout,vertices,0);
		LOGPZ_DEBUG(logger,sout.str())
	}
  for(intit = vertices.begin(); intit != vertices.end(); intit++)
  {
    std::set<int> locset,diffset,interset,unionset,loclocset;
    // locset = all nodes connected to a vertex
    BuildNodeSet(*intit,locset);
    // only diffset with nodes which have no connection with lower nodes interest us
    if(*locset.begin() < *vertices.begin()) continue;
    // diffset contains all vertices in the mesh, except for those in the influence zone of intit????
		set_difference(vertices.begin(),vertices.end(),locset.begin(),locset.end(),inserter(diffset,diffset.begin()));
    // the influence zone of the vertex includes other vertices
    if(diffset.size())
    {
#ifdef LOG4CXX
		{
			std::stringstream sout;
			sout << "Difference after taking the intersection with " << *intit;
			Print(sout,diffset," Difference set");
			LOGPZ_DEBUG(logger,sout.str())
		}
#endif
    // some unions need to be made before calling this method
      for(diffit=diffset.begin(); diffit!= diffset.end(); diffit++)
      {

        loclocset.clear();
        // locset now will contain the influence zone of each vertex node in diffset
        BuildNodeSet(*diffit,loclocset);
        if(*loclocset.begin() < *vertices.begin()) continue;
        unionset.insert(loclocset.begin(),loclocset.end());
      }
      // locset now contains the union of all influence zones of vertices influenced by intit
      diffset.clear();
      // diffset will now contain only vertex nodes
      set_intersection(unionset.begin(),unionset.end(),vertices.begin(),vertices.end(),inserter(diffset,diffset.begin()));
#ifdef LOG4CXX
		{
			std::stringstream sout;
			Print(sout,diffset,"First set to be reanalised");
			LOGPZ_DEBUG(logger,sout.str())
		}
#endif
      set_intersection(vertices.begin(),vertices.end(),locset.begin(),locset.end(),inserter(interset,interset.begin()));
#ifdef LOG4CXX
		{
			std::stringstream sout;
			Print(sout,interset,"Second set to be reanalised");
			LOGPZ_DEBUG(logger,sout.str())
		}
#endif
      AnalyseForElements(diffset,elements);
      AnalyseForElements(interset,elements);
      return;
    }
  }

  intit = vertices.begin();
  BuildNodeSet(*intit,elem);
  intit++;
//  elem = vertices;
  // this code doesnt make sense!!!
  for(;intit != vertices.end(); intit++)
  {
    std::set<int> locset,interset;
    BuildNodeSet(*intit,locset);
    set_intersection(elem.begin(),elem.end(),locset.begin(),locset.end(),inserter(interset,interset.begin()));
    elem = interset;
  }
  if(vertices != elem)
  {
#ifdef LOG4CXX
	  {
		  std::stringstream sout;
		  sout << "Discarding a vertex set as incomplete";
		  Print(sout,vertices,0);
		  LOGPZ_DEBUG(logger,sout.str())
	  }
#endif
  }
  else if(elem.size())
  {
#ifdef LOG4CXX
	  {
		  std::stringstream sout;
		  Print(sout,elem,"Inserted element");
		  LOGPZ_DEBUG(logger,sout.str())
	  }
#endif
    elements.insert(elem);
  }
}

void TPZNodesetCompute::BuildElementGraph(TPZStack<int> &blockgraph, TPZStack<int> &blockgraphindex)
{
#ifdef LOG4CXX
	{
		std::stringstream sout;
		sout << __PRETTY_FUNCTION__ << " entering build element graph\n";
		LOGPZ_DEBUG(logger,sout.str())
	}
#endif
  blockgraph.Resize(0);
  blockgraphindex.Resize(1);
  blockgraphindex[0] = 0;
  int in;
  int nnodes = this->fNodegraphindex.NElements()-1;
  std::set<int> nodeset;
  for(in=0; in<nnodes; in++)
  {
    std::set< std::set<int> > elements;
    BuildNodeSet(in,nodeset);
#ifdef LOG4CXX
	  {
		  std::stringstream sout;
		  sout << "Nodeset for " << in << ' ';
		  Print(sout,nodeset,"Nodeset");
		  LOGPZ_DEBUG(logger,sout.str())
	  }
#endif
    SubstractLowerNodes(in,nodeset);
#ifdef LOG4CXX
		  {
			  std::stringstream sout;
			  Print(sout,nodeset,"LowerNodes result");
			  LOGPZ_DEBUG(logger,sout.str())
		  }
#endif
    AnalyseForElements(nodeset,elements);
    std::set< std::set<int> >::iterator itel;
    for(itel = elements.begin(); itel != elements.end(); itel++)
    {
      std::set<int>::const_iterator it;
      for(it = (*itel).begin(); it!= (*itel).end(); it++)
      {
        blockgraph.Push(*it);
      }
      blockgraphindex.Push(blockgraph.NElements());
    }
  }
}

void TPZNodesetCompute::SubstractLowerNodes(int node, std::set<int> &nodeset)
{
  std::set<int> lownode,lownodeset,unionset;
  std::set<int>::iterator it;
#ifdef LOG4CXX
	{
		std::stringstream sout;
		sout << __PRETTY_FUNCTION__;
		Print(sout,nodeset," Incoming nodeset");
		LOGPZ_DEBUG(logger,sout.str())
	}
#endif
  for(it=nodeset.begin(); it != nodeset.end() && *it < node; it++)
  {
    BuildNodeSet(*it,lownodeset);
    unionset.insert(lownodeset.begin(),lownodeset.end());
    lownodeset.clear();
  }
  set_difference(nodeset.begin(),nodeset.end(),unionset.begin(),unionset.end(),
    inserter(lownode,lownode.begin()));
#ifdef LOG4CXX
	{
		std::stringstream sout;
		Print(sout,lownode," What is left after substracting the influence of lower numbered nodes ");
		LOGPZ_DEBUG(logger,sout.str())
	}
#endif
  unionset.clear();
  for(it=lownode.begin(); it!=lownode.end(); it++)
  {
    BuildNodeSet(*it,lownodeset);
    unionset.insert(lownodeset.begin(),lownodeset.end());
    lownodeset.clear();
  }
  lownode.clear();
  set_intersection(unionset.begin(),unionset.end(),nodeset.begin(),nodeset.end(),
    inserter(lownode,lownode.begin()));
#ifdef LOG4CXX
	{
		std::stringstream sout;
		Print(sout,lownode," Resulting lower nodeset");
		LOGPZ_DEBUG(logger,sout.str())
	}
#endif
  nodeset = lownode;
}

void TPZNodesetCompute::Print(std::ostream &file) const
{
  file << "TPZNodesetCompute\n";
  file << "Node graph\n";
  Print(file,fNodegraphindex,fNodegraph);
  file << "Node sequence number and level\n";
  int nnode = fNodegraphindex.NElements()-1;
  int in;
  for(in=0; in<nnode; in++) file << in << "/" << fSeqNumber[in] << "/" << fLevel[in] << " ";
  file << std::endl;
}

void TPZNodesetCompute::Print(std::ostream &file, const TPZVec<int> &graphindex, const TPZVec<int> &graph)
{
  int nnode = graphindex.NElements()-1;
  int in;
  for(in =0; in<nnode; in++)
  {
    file << "Node Number " << in;
    int first = graphindex[in];
    int last = graphindex[in+1];
    int jn;
    for(jn = first; jn< last; jn++) file << " " << graph[jn];
    file << std::endl;
  }
}

void TPZNodesetCompute::Print(std::ostream &file, const std::set<int> &nodeset, const char *text)
{
  if(text) file << text;
  std::set<int>::const_iterator it;
  for(it=nodeset.begin(); it!=nodeset.end(); it++) file << *it << ' ';
  file << std::endl;
}

  /**
  * Expand the graph acording to the block structure
  */
void TPZNodesetCompute::ExpandGraph(TPZVec<int> &graph, TPZVec<int> &graphindex, TPZBlock<REAL> &block,
    TPZVec<int> &expgraph, TPZVec<int> &expgraphindex)
{
  int expgraphsize = 0;
  int nbl = graph.NElements();
  expgraphindex.Resize(graphindex.NElements());
  int ibl;
  for(ibl=0; ibl<nbl; ibl++)
  {
    expgraphsize += block.Size(graph[ibl]);
  }
  expgraph.Resize(expgraphsize);
  int counter = 0;
  int numblocks = graphindex.NElements()-1;
  expgraphindex[0] = counter;
  int blcounter = 0;
  for(ibl=0; ibl < numblocks; ibl++)
  {
    int first = graphindex[ibl];
    int last = graphindex[ibl+1];
    int ieq;
    for(ieq = first; ieq<last; ieq++)
    {
      int blsize =  block.Size(graph[ieq]);
      int pos = block.Position(graph[ieq]);
      int b;
      for(b=0; b<blsize; b++)
      {
        expgraph[counter++] =  pos+b;
      }
    }
    if(expgraphindex[blcounter] != counter) expgraphindex[++blcounter] = counter;
  }
  expgraphindex.Resize(blcounter+1);
}

  /**
  * Color the graph into mutually independent blocks
  */
int TPZNodesetCompute::ColorGraph(TPZVec<int> &graph, TPZVec<int> &graphindex, int neq,
    TPZVec<int> &colors)
{
  TPZVec<int> eqcolor(neq);
  int color = 0;
  bool hasuncolored = true;
  int nblocks = graphindex.NElements()-1;
  colors.Resize(nblocks);
  colors.Fill(-1);
  while(hasuncolored)
  {
    hasuncolored = false;
    eqcolor.Fill(-1);
    int ibl;
    for(ibl=0; ibl<nblocks; ibl++)
    {
      if(colors[ibl] != -1) continue;
      int first = graphindex[ibl];
      int last = graphindex[ibl+1];
      int ieq;
      for(ieq=first; ieq<last; ieq++)
      {
        if(eqcolor[graph[ieq]] == color) break;
      }
      if(ieq != last)
      {
        hasuncolored = true;
      }
      else
      {
        colors[ibl] = color;
        for(ieq=first; ieq<last; ieq++)
        {
          eqcolor[graph[ieq]] = color;
        }
      }
    }
    color++;
  }
  return color;
}


text:
$(document).ready(function () {
    $('#lgname').click(function(){
		if(login==1)
		{
			window.location="memberHandler/profile.php";
		}
	});

});

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Shreyas Gaonkar">

    <title>How to Get Out of Your Own Way and Shine | AML Health Coach</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">

    <link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

Blogs

                        @amlhealthcoaching

                            How to Get Out of Your Own Way and SHINE

Posted by AML on May 12, 2016

                Thursday…I got invited to fly down to the Bahamas and spend the weekend learning from some of the most brilliant entrepreneurs, coaches and CEOs.  Initially, I had a million reasons why I couldn't go.  Until, I GOT OUT OF MY OWN WAY.

                When you begin to live in a way that is connected to your inner and true INTENTIONS and VALUES, the world around aligns to give you exactly what you need exactly when you need it. One of the most powerful and life-changing rituals I have is to start the day with affirmations and visualizing the exact experiences I wanted to have. Instead of getting caught up in thinking "I don't have" or "I want this but am clueless as to how I will get there", I just think about what I would like to create and then ask for assistance.  From there, I program my mind with powerful mantras to ensure inner confidence that I can achieve it.  This is key.  As Gabby Bernstein says...ASK. BELIEVE. RECEIVE.

                    Spending a weekend with visionaries in business taught me a few things:

                    Don't wait for the right moment because that moment will never come.  If you want it, you don't have to know every step to get there.  Just set a date and then go get it.

                    Focus on doing what you are great at and get help or outsource the things you are not so great at.  You are not meant to do and know it all.  Ask for help or find a coach/mentor to guide you. Hire someone to do the things you don't want to do.

                    Surround yourself with a dream team full of people that push you and inspire you to be your best self.  Cut out the ones who don't. This is key!

                    Failure is part of it.  It's what we do with failure that determines success.  If you don't believe me, check out this link below to see all of the famous people that failed and where they ended up

                Failure is part of it.  It's what we do with failure that determines success.  If you don't believe me, check out this link below to see all of the famous people that failed and where they ended up

If you are feeling stuck or unsure how to get what you truly desire in life, begin by being grateful for all you have.  Then, take some time to write about what you truly want to CREATE.  Connect to this vision every day.  Often in coaching, I see people lose sight of their bigger vision because they don't believe it's possible or they don't make time and space to clarify what it is they really want.  And I completely understand this because I have experienced it many times.  There have been times that I've forgotten it is only ME who holds the power in my heart to CREATE what it is I desire.  Wherever you are, whatever you are doing today, I invite you to REACH UP and take hold of the sun.  Let it light up your world.


text:
declare module M {
  declare class C {
  }
}

//// [parserClassDeclaration7.js]


text:
Javascript Code Conventions (Maintainable JavaScript)
=====================================================

Maintainable JavaScript tackles the difficult problem of writing code as part of a large team. When you're writing code that only you will change, there aren't any issues. As soon as you're writing code that someone else is going to also be changing, you need to think harder about the decisions you make. Will another developer be able to understand what you did? Did you organize your code in such a way that it's easy to adapt and extend? Long after you're gone, will others be able to continue using the same code, or will it need to be rewritten because no one understands it? To make it works fine, read below.

Must watch: https://www.youtube.com/watch?v=c-kav7Tf834

1) Style Guide: Ensure everyone's speaking the same language

	All developers should follow the same conventions when coding. This project uses google style guide for javascript (https://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml)

2) Programming Practices: Common patterns for common problems which allow for easier code changes and debugging

3) Automation of Code tasks: make easier to perform complex multi-step tasks.


text:
(function() {
  'use strict';
  var app = angular.module('app.ui.services', []);

  app.factory('logger', [
    function() {
      var logIt;
      toastr.options = {
        'closeButton': true,
        'positionClass': 'toast-bottom-right',
        'timeOut': '3000'
      };
      logIt = function(message, type) {
        return toastr[type](message);
      };
      return {
        log: function(message) {
          logIt(message, 'info');
        },
        logWarning: function(message) {
          logIt(message, 'warning');
        },
        logSuccess: function(message) {
          logIt(message, 'success');
        },
        logError: function(message) {
          logIt(message, 'error');
        }
      };
    }
  ]);

}).call(this);


text:
import os
import subprocess
from glob import glob
import time

def is_dakota_installed():
    '''
    Returns True if Dakota is installed and in the execution path;
    otherwise, False.
    '''
    try:
        subprocess.call(['dakota', '--version'])
    except OSError:
        return False
    else:
        return True

def get_input_file(experiment):
    '''
    Returns basename of Dakota input file, if present, or None.
    '''
    input_file = glob(os.path.join(experiment, '*.in'))
    if len(input_file) == 0:
        return None
    else:
        return os.path.basename(input_file[0])

def run_experiment(experiment):
    '''
    Performs the specified Dakota experiment.
    '''
    start_dir = os.getcwd()
    try:
        infile = get_input_file(experiment)
        outfile = os.path.splitext(infile)[0] + '.out'
        os.chdir(experiment)
        start_time = time.time()
        subprocess.check_output(['dakota',
                                 '-i', infile,
                                 '-o', outfile,
                                 '-no_input_echo'],
                                stderr=subprocess.STDOUT)
        elapsed_time = time.time() - start_time
    except AttributeError:
        status = 'Error: DAKOTA input file not found.'
    except subprocess.CalledProcessError as e:
        status = e
    else:
        status = 'Finished.\n%s %.1f %s' \
                 % ('Elapsed time:', elapsed_time, 's')
    finally:
        os.chdir(start_dir)
    return status

def print_error_status(error):
    '''
    Displays an error summary from Dakota on a failed run.
    '''
    print('Error: DAKOTA run failed.')
    print('Command:\n' + '\t' + str(error.cmd))
    print('Return code:\n' + '\t' + str(error.returncode))
    print('Output:')
    for line in error.output.split('\n'):
        print('\t' + line)

def main():
    import argparse
    from dakota_utils import __version__, run_script

    parser = argparse.ArgumentParser(
        description="Runs a Dakota experiment on a CSDMS model.")
    parser.add_argument("experiment",
                        help="path to directory with Dakota experiment files")
    parser.add_argument('--version', action='version',
                        version=run_script + ' ' + __version__)
    args = parser.parse_args()

    if is_dakota_installed() is False:
        print('Error: DAKOTA must be installed and in the execution path.')
        return

    if os.path.isdir(args.experiment) is False:
        print('Error: Experiment path does not exist.')
        return
    else:
        print('Experiment: ' +
              os.path.basename(os.path.abspath(args.experiment)))

    status = run_experiment(args.experiment)
    if status.__class__ is subprocess.CalledProcessError:
        print_error_status(status)
    else:
        print(status)

if __name__ == '__main__':
    main()


text:
Over time, websites change and it might be necessary to alter some URLs as well. However, in many cases it is important to maintain compatibility with the old system. This can be achieved using redirections.

## Redirect to another route

During configuration, you can define redirections using the following code-snippets:

```CSHARP
config.RouteTable.AddRouteRedirection(
    name: "Redirection1",
    urlPattern: "my/url/page/{Id}",
    targetRouteNameProvider: context => "TargetPage",
    defaultValues: null,
    permanent: false,
    parametersProvider: null,
    urlSuffixProvider: null);
```

In the example above, we can see an addition of a new redirection record to the route table. This record is named *Redirection1* and specifies that any access to a page that matches the *my/page/url{Id}* pattern will be redirected to the route named *TargetPage*. This redirection is temporary (i.e. non-permanent).

+ The first argument specifies a **name of the redirection**. This name is not displayed anywhere, it is only a string which identifies the redirection within the framework.

+ The second argument is the **route URL pattern** that we are redirecting from. More information on routes and route parameters can accessed on [routing overview](~/pages/concepts/routing/overview).

+ The third argument is either a **target route name**, or a **target route name provider** (there are two overloads). The first overload is quite straight forward, as it always redirects to the route determined by the given `string`. The second overload expects a `Func<IDotvvmRequestContext, string>`, as can be seen in the code snippet above. This can be used to obtain context-based redirection targets.

+ The fourth argument (optional) specifies **default values for [route parameters](parameters)**.

+ The fifth argument (optional) specifies whether this redirection is **permanent**. The default value is `false`, which means non-permanent.

+ The sixth argument (optional) is a **parameters provider** of type `Func<IDotVVMRequestContext, Dictionary<string, object?>>`. This provider can be used to perform context-based transformations on parameters. An example that copies obtained parameters and alters the *Id* parameter by setting it with value *123* can be seen in the snippet below.

```CSHARP
    parametersProvider: context => {
        var newDict = new Dictionary<string, object>(context.Parameters);
        newDict["Id"] = 123;
        return newDict;
    });
```

+ The last argument (optional) is a **provider for URL suffix** (which consists of query string and fragment). The default value is `null` which means that the query string will be kept as is. If you want to transform it, specify your own function.

## Redirect to another URL

In case your website is split into multiple applications, or you need to redirect to a custom URL, you might find URL redirections quite useful. These redirections can be defined in the following way:

```CSHARP
config.RouteTable.AddUrlRedirection(
    name: "Redirect2",
    urlPattern: "my/page/url{Id}",
    targetUrlProvider: context => "https://www.dotvvm.com"
    defaultValues: null,
    permanent: true);
```

In the example above, we can see a new redirection addition to the route table. This record is named *Redirection2* and specifies that any access to a page that matches the *my/page/url{Id}* pattern will be redirected to *https://dotvvm.com*. This redirection is permanent.

+ The first argument specifies a **name of the redirection**. This name is not displayed anywhere, it is only a string which identifies the redirection within the route table.

+ The second argument is the **route URL pattern** that we are redirecting from. More information on routes and route parameters can accessed on [routing overview](~/pages/concepts/routing/overview).

+ The third argument is either a **target URL**, or a **target URL provider** (there are two overloads). The first overload is quite straight forward, as it always redirects to the URL determined by the given `string`. The second overload expects a `Func<IDotvvmRequestContext, string>`, as can be seen in the code snippet above. This can be used to obtain context-based redirection targets.

+ The fourth argument (optional) specifies **default values for [route parameters](parameters)**.

+ The fifth argument (optional) specifies whether this redirection is **permanent**. The default value is `false`, which means non-permanent.

## See also

* [Parameters](~/pages/concepts/routing/parameters)
* [Auto-discover routes](~/pages/concepts/routing/auto-discover-routes)
* [Custom presenter](~/pages/concepts/routing/custom-presenters)


text:
import { type, identical, pipe, curryN } from 'ramda';

/**
 * Checks if value is `RegExp` object.
 *
 * @func isRegExp
 * @memberOf RA
 * @since {@link https://char0n.github.io/ramda-adjunct/2.5.0|v2.5.0}
 * @category Type
 * @sig * -> Boolean
 * @param {*} val The value to test
 * @return {boolean}
 * @see {@link RA.isNotRegExp|isNotRegExp}
 * @example
 *
 * RA.isRegExp(new RegExp()); //=> true
 * RA.isRegExp(/(?:)/); //=> true
 * RA.isRegExp(1); //=> false
 */
const isRegExp = curryN(1, pipe(type, identical('RegExp')));

export default isRegExp;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package mobemu.parsers;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import mobemu.node.Context;
import mobemu.node.Topic;
import mobemu.trace.Contact;
import mobemu.trace.Parser;
import static mobemu.trace.Parser.MILLIS_PER_SECOND;
import mobemu.trace.Trace;

/**
 * SocialBlueConn trace parser
 * (http://crawdad.org/unical/socialblueconn/20150208/).
 *
 * @author Radu
 */
public class SocialBlueConn implements Parser {

    private Trace trace;
    private Map<Integer, Context> context;
    private boolean[][] socialNetwork;

    /**
     * Constructs a {@link StAndrews} object.
     */
    public SocialBlueConn() {
        String prefix = "traces" + File.separator + "socialblueconn" + File.separator;
        parseSocialBlueConn(prefix + "contacts" + File.separator + "Bluetooth_contacts.txt",
                prefix + "friendships" + File.separator + "Facebook_friendships.txt",
                prefix + "interests", 15);
    }

    @Override
    public Trace getTraceData() {
        trace.sort();
        return trace;
    }

    @Override
    public Map<Integer, Context> getContextData() {
        return context;
    }

    @Override
    public boolean[][] getSocialNetwork() {
        return socialNetwork;
    }

    @Override
    public int getNodesNumber() {
        return socialNetwork.length;
    }

	@Override
	public int getStaticNodesNumber() {
		return 0;
	}

    /**
     * Parses the SocialBlueConn trace.
     *
     * @param contacts contacts file
     * @param friendship social connections file
     * @param interestsFolder folder with interests file
     * @param devices number of devices in the trace
     */
    private void parseSocialBlueConn(String contacts, String friendship, String interestsFolder, int devices) {
        trace = new Trace("SocialBlueConn");
        socialNetwork = new boolean[devices][devices];
        context = new HashMap<>();

        long end = Long.MIN_VALUE;
        long start = Long.MAX_VALUE;

        // parse contacts file.
        try {
            String line;
            FileInputStream fstream = new FileInputStream(contacts);
            try (DataInputStream in = new DataInputStream(fstream)) {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));

                while ((line = br.readLine()) != null) {
                    String[] tokens;
                    String delimiter = "\\s+";

                    tokens = line.split(delimiter);

                    int observerID = Integer.parseInt(tokens[0]) - 1;
                    int observedID = Integer.parseInt(tokens[1]) - 1;

                    if (observedID >= devices) {
                        continue;
                    }

                    long contactStart = Long.parseLong(tokens[2]);
                    contactStart -= contactStart % MILLIS_PER_SECOND;

                    // since the ending of the contact isn't specified, we'll assume it is a second
                    long contactEnd = contactStart + MILLIS_PER_SECOND;

                    if (trace.getContactsCount() > 0) {
                        Contact previousContact = trace.getContactAt(trace.getContactsCount() - 1);

                        if (previousContact.getObserver() == observerID && previousContact.getObserved() == observedID
                                && Math.abs(previousContact.getStart() - contactStart) < 10 * MILLIS_PER_MINUTE) {
                            previousContact.setEnd(Math.max(previousContact.getEnd(), contactEnd));
                            continue;
                        }
                    }

                    trace.addContact(new Contact(observerID, observedID, contactStart, contactEnd));

                    // compute trace zero time.
                    if (contactStart < start) {
                        start = contactStart;
                    }

                    // compute trace duration.
                    if (contactEnd > end) {
                        end = contactEnd;
                    }
                }
            }
        } catch (IOException | NumberFormatException e) {
            System.err.println("SocialBlueConn Parser exception: " + e.getMessage());
        }

        trace.setStartTime(start);
        trace.setEndTime(end);
        trace.setSampleTime(MILLIS_PER_SECOND);

        // parse friendship file.
        try {
            String line;
            FileInputStream fstream = new FileInputStream(friendship);
            try (DataInputStream in = new DataInputStream(fstream)) {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));

                br.readLine();

                while ((line = br.readLine()) != null) {
                    if (line.isEmpty()) {
                        continue;
                    }

                    String[] tokens;
                    String delimiter = "\\s+";

                    tokens = line.split(delimiter);

                    int observerID = Integer.parseInt(tokens[0]) - 1;

                    for (int i = 1; i < tokens.length; i++) {
                        socialNetwork[observerID][i - 1] = (Integer.parseInt(tokens[i]) == 1);
                    }
                }
            }
        } catch (IOException | NumberFormatException e) {
            System.err.println("SocialBlueConn Parser exception: " + e.getMessage());
        }

        // parse interest files.
        File dir = new File(interestsFolder);
        File[] files = dir.listFiles(new FileFilter() {

            @Override
            public boolean accept(File file) {
                return !file.getName().contains("legend");
            }
        });

        Map<String, Integer> interestsSeen = new HashMap<>();
        int currentId = 0;

        for (File file : files) {
            try {
                String line;
                FileInputStream fstream = new FileInputStream(file);
                try (DataInputStream in = new DataInputStream(fstream)) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(in));

                    br.readLine();
                    line = br.readLine();

                    String[] interestIds;
                    String delimiter = "\\s+";
                    interestIds = line.split(delimiter);

                    for (int i = 1; i < interestIds.length; i++) {
                        if (!interestsSeen.containsKey(interestIds[i])) {
                            interestsSeen.put(interestIds[i], currentId++);
                        }
                    }

                    while ((line = br.readLine()) != null) {
                        String[] tokens;
                        delimiter = "\\s+";

                        tokens = line.split(delimiter);

                        int observerID = Integer.parseInt(tokens[0]) - 1;
                        Context contextItem = context.get(observerID);
                        if (contextItem == null) {
                            contextItem = new Context(observerID);
                        }

                        for (int i = 1; i < tokens.length; i++) {
                            if (Integer.parseInt(tokens[i]) == 1) {
                                contextItem.addTopic(new Topic(interestsSeen.get(interestIds[i]), 0));
                            }
                        }

                        context.put(contextItem.getId(), contextItem);
                    }
                }
            } catch (IOException | NumberFormatException e) {
                System.err.println("SocialBlueConn Parser exception: " + e.getMessage());
            }
        }
    }
}


text:
(function() {
  'use strict';

  angular
    .module('horizon.app.core.trunks')
    .factory('horizon.app.core.trunks.actions.delete.service', deleteService);

  deleteService.$inject = [
    '$q',
    '$location',
    'horizon.app.core.openstack-service-api.neutron',
    'horizon.app.core.openstack-service-api.policy',
    'horizon.app.core.trunks.resourceType',
    'horizon.framework.util.actions.action-result.service',
    'horizon.framework.widgets.modal.deleteModalService'
  ];

  function deleteService(
    $q,
    $location,
    neutron,
    policy,
    resourceType,
    actionResultService,
    deleteModal
  ) {
    var service = {
      allowed: allowed,
      perform: perform
    };

    return service;

    ////////////

    function allowed() {
      return policy.ifAllowed(
        {rules: [
          ['network', 'delete_trunk']
        ]}
      );
    }

    function perform(items, scope) {
      var trunks = angular.isArray(items) ? items : [items];

      return openModal().then(onComplete);

      function openModal() {
        return deleteModal.open(
          scope,
          trunks,
          {
            labels: labelize(trunks.length),
            deleteEntity: neutron.deleteTrunk
          }
        );
      }

      function onComplete(result) {
        var actionResult = actionResultService.getActionResult();

        result.pass.forEach(function markDeleted(item) {
          actionResult.deleted(resourceType, item.context.id);
        });
        result.fail.forEach(function markFailed(item) {
          actionResult.failed(resourceType, item.context.id);
        });
      }
    }

    function labelize(count) {
      return {
        title: ngettext(
          'Confirm Delete Trunk',
          'Confirm Delete Trunks',
          count),

        message: ngettext(
          'You have selected "%s". Deleted Trunk is not recoverable.',
          'You have selected "%s". Deleted Trunks are not recoverable.',
          count),

        submit: ngettext(
          'Delete Trunk',
          'Delete Trunks',
          count),

        success: ngettext(
          'Deleted Trunk: %s.',
          'Deleted Trunks: %s.',
          count),

        error: ngettext(
          'Unable to delete Trunk: %s.',
          'Unable to delete Trunks: %s.',
          count)
      };
    }

  }

})();


text:
#Flight: 이벤트 주도 웹 어플리케이션 프레임워크

[![Build Status](https://travis-ci.org/witter/flight.png?branch=master)](http://travis-ci.org/twitter/flight)

Flight 는 경량, 컴포넌트 기반 자바스크립트 프레임워크component-based JavaScript framework that maps behavior to DOM
nodes. Twitter uses it for their web applications.

Components cannot be directly referenced, instead they communicate by triggering and subscribing to events.
Consequently every component, and every component API, is entirely decoupled from every other component, so
that components are highly portable and easily testable.

As an added bonus, Flight includes a simple and safe mixin infrastructure allowing components to be easily
extended with minimal boilerplate.

**[Follow us on Twitter](https://twitter.com/flight)**
**[Visit our Google Group](https://groups.google.com/forum/?fromgroups#!forum/twitter-flight)**

## Sample App

By way of example, we've included a simple email client built over the Flight framework. The source code for this
app is in the [demo](https://github.com/twitter/flight/tree/gh-pages/demo) directory and you can run the demo [here](http://twitter.github.com/flight/demo/).

## Browser Support

Flight has been tested on all major browsers: Chrome, Firefox, Safari, Opera and IE7 and upwards.

## Installation

To ensure Flight is installed with the correct dependencies, we recommend using [bower](https://github.com/twitter/bower).
Your client app will need a `component.json` file that looks something like this:

    {
      "name": "myApp",
      "version": "1.2.1",
      "dependencies": {
        "flight": "~1.0.0"
      }
    }

Then running `bower install` will add flight to the `components` directory of `myApp`.

## Dependencies

Flight uses [ES5-shim](https://github.com/kriskowal/es5-shim) to polyfill ES5 support for older browsers and [JQuery](http://jquery.com)
for DOM manipulation API. If you install flight with bower, these apps will be deployed in the `components`
folder. Additionally you will need to include an AMD implementation such as [require.js](http://requirejs.org/)
or [loadrunner](https://github.com/danwrong/loadrunner).

These files are loaded in the sample app at `demo/index.html`.

```html
<script src='components/jquery/jquery.js'></script>
<script src='components/es5-shim/es5-shim.js'></script>
<script src='components/es5-shim/es5-sham.js'></script>
<script data-main="requireMain.js" src='components/requirejs/require.js'></script>
```

## How do I use it?

1.  Define a component
2.  Attach a component instance to a DOM node

## Components

### What is a component?

- A Component is nothing more than a constructor with properties mixed into its prototype.
- Every Component comes with a set of basic functionality such as event handling and component registration.
- Additionally, each Component definition mixes in a set of custom properties which describe its behavior.
- When a component is attached to a DOM node, a new instance of that component is created. Each component
instance references the DOM node via its `node` property.
- Component instances cannot be referenced directly; they communicate with other components via events.

### How do I define a component?

Flight expects its client apps to support [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD)-style module definitions.

To define a component, create a module that depends on Flight's component module (`lib/component.js`). The
latter module exports a function which we'll call `defineComponent`.

```js
define(
  [
    'components/flight/lib/component'
  ],

  function(defineComponent) {
    //..
  }
);
```

`defineComponent` accepts any number of [mixin](#mixins) functions and returns a new Component constructor
with those mixins applied to its prototype.

Each Component definition should include a function declaration describing its
basic behavior (we can think of this function as the Component's core mixin). By passing this function to
`defineComponent` we can define a simple Component:

```js
/* mySimpleComponent.js */

define(
  [
    'components/flight/lib/component'
  ],

  function(defineComponent)  {

    return defineComponent(mySimpleComponent);

    function mySimpleComponent() {
      this.doSomething = function() {
        //...
      }

      this.doSomethingElse = function() {
        //...
      }
    }
  }
);
```

Components make no assumptions about the existence of other objects. If you were to remove all other
JavaScript on the site, this component would still work as intended.

### How do I attach a Component to a DOM node?

Each Component constructor has an `attachTo` method which accepts two arguments. The first argument is a DOM
node (or a jQuery object or CSS selector representing one or more DOM nodes). The second is an `options` object.
If extra arguments are supplied, they are merged into the first options argument. These options will be merged
into the `defaults` object which is a property of the component instance.

Invoking `attachTo` will create a new instance and attach it to the supplied DOM node. If the first argument
resolves to one or more DOM nodes, an instance will be created for each node.

Here we are creating an instance of an Inbox Component and attaching it to a node with id `inbox`. We're also
passing in values for a couple of selectors which will override the values defined in the components `defaults`
object (if they exist). More on `defaults` [here](#defaults-and-options).

```js
/* attach an inbox component to a node with id 'inbox'*/

define(
  [
    'components/inbox'
  ],

  function(Inbox) {
    Inbox.attachTo('#inbox', {
      'nextPageSelector': '#nextPage',
      'previousPageSelector': '#previousPage',
    });
  }
);
```

It's important to understand that `attachTo` does not return the new instance, or any other value. You should
never need a reference to component instances - they should only respond to events.

### Initializing a component

When a component is created we usually want it to perform an initial setup routine. Every Component has an
empty initialize method attached to its prototype and we can augment this method by supplying a function as
an argument to a special `after` method. (We'll talk about `before`, `after` and `around` in detail in the
[advice](#advice) section of this document).

The initialize function is a good place to set up event listeners that bind to callbacks.

```js
define(
  [
    'components/flight/lib/component'
  ],

  function(defineComponent)  {

    return defineComponent(inbox);

    function inbox() {
      //define custom functions here
      //...

      // now initialize the component
      this.after('initialize', function() {
        this.on('click', doThisThing);
        this.on('mouseover', doThatThing);
      });
    }
  }
);
```
### Defaults and Options

In addition to functions, most components need to define attributes too. In Flight, default values are
assigned by passing an object to the `defaultAttrs` function

```js
define(
  [
    'flight/lib/component'
  ],

  function(defineComponent) {

    return defineComponent(button);

    function button() {
      this.defaultAttrs({
        buttonClass: 'js-button',
        text: 'Click me'
      });

      this.after('initialize', function() {
        //..
      });
    }

  }
);
```

The object will be assigned to, or merged with, the `attr` property of the component and can be accessed
accordingly:

```js
this.after('initialize', function() {
  this.$node
      .addClass(this.attr.buttonClass)
      .text(this.attr.text);
});
```

These can be overridden in options...

```js
/* attach button with text as option */

define(
  [
    'components/button'
  ],

  function(Button) {
    Button.attachTo("#foo", {
      text: "Don't click me",
      buttonClass: "js-not-a-button"
    });
  }
);
```

...or by [mixins](#overriding-defaults-in-a-mixin).

### Finding elements

Flight's `select` method takes a [selector attribute](#defaults-and-options) as its argument and will return
all matching elements within the component's `node`. This is a handy alternative to jQuery's `this.$node.find()`
and prevents accidental access to elements outside of `this.node`.

```js
this.defaultAttrs({
  menuItemSelector: '.menu-item',
  selectedClass: 'selected'
});

this.selectMenuItem = function(e) {
  // toggle 'selected' class on all list items
  this.select('menuItemSelector').toggleClass(this.attr.selectedClass);

  //...
};
```

### Interacting with the DOM

Once attached, component instances have direct access to their node object via the `node` property. (There's
also a jQuery version of the node available via the `$node` property.)

### Events in Flight

Events are how Flight components interact. The Component prototype supplies methods for triggering events as
well as for subscribing to and unsubscribing from events. These Component event methods are actually just convenient
wrappers around regular event methods on DOM nodes.

#### Triggering events

The `trigger` method takes up to three arguments representing the triggering element, the event type (e.g.
`'click'` or `'saveRequested'`) and the event payload which must always be an object. Only the event type is
mandatory. If the element is not supplied then the component's `node` property is used.

```js
this.saveButtonClicked = function() {
  this.trigger('saveRequested', currentDocument);
}

this.updateSuccessful = function() {
  this.trigger(document, 'transactionComplete', successData);
}
```

You can also specify a default function that will be called by the component, providing nothing in the event's
bubble chain invokes `preventDefault`. Default functions in custom events are analagous to the default behaviors
of native events.

To define a default function, make the event argument an object that defines the event type and the `defaultFunction`.
A common use case is defining default behavior for keyboard events:

```js
this.trigger('#textInput', {type: 'escapePressed', defaultFunction: this.blur});
```

#### Subscribing to events

A component instance can listen to an event and register a callback to be invoked using the `on` method of the
component prototype. There are three possible arguments: the DOM node to listen on, the event type to listen
to, and the event handler (callback) to be invoked. Again the DOM node is optional and defaults to the component
instance's `node` value. Flight will automatically bind the context (`this`) of the callback to the component instance.

The callback argument can be either a function to be invoked...

```js
this.after('initialize', function() {
  this.on(document, 'dataSent', this.refreshList);
  this.on('click', this.selectItem);
});
```

...or an object that maps event targets to callbacks...

```js
this.after('initialize', function() {
  this.on('click', {
    menuItemSelector: this.selectMenuItem,
    saveButtonSelector: this.saveAll
  });
});
```

The latter case is effectively event delegation; selector values are resolved, at event time, by keying into the `attr` property
of the component (see [`defaults and options`](#defaults-and-options)).
For the above example we would expect the `defaultAttrs` call to look something like this:

```js
this.defaultAttrs({
  menuItemSelector: '.menuItem',
  saveButtonSelector: '#save'
});
```

#### Unsubscribing from events

If we no longer want a component instance to listen to an event we can use the `off` method to unsubscribe.
This method takes up to three arguments: the DOM node that was listening to the event, the event type, and the
callback. The DOM node argument is optional and defaults to the component's `node` property. The callback is
also optional and when not supplied the component instance detaches all callbacks for the event type.

```js
function disableAllDropdowns() {
  this.off('#select', 'click');
}

function noHighlightOnHover() {
  this.off('hover', this.highlight);
}
```

Note: when a component is [torn down](#teardown), it automatically unsubscribes from all events.

### Putting it together

Here's an example of a navigation menu component.

```js
define(
  [
    'flight/lib/component'
  ],

  function(defineComponent) {

    return defineComponent(navigationMenu);

    function navigationMenu() {
      this.defaultAttrs({
        menuItemSelector: '.menu-item',
        selectedClass: 'selected'
      });

      // mark menu item as selected. mark others as not selected. trigger uiLoadUrl event
      this.selectMenuItem = function(e) {
        // toggle 'selected' class on all list items
        this.select('menuItemSelector').toggleClass(this.attr.selectedClass);

        // let some other component worry about loading the content & displaying it
        this.trigger('uiLoadUrl', {
          url: $(e.target).attr('href')
        });
      };

      this.after('initialize', function() {
        // 'menuItemSelector' is defined in defaultAttr
        this.on('click', {
          menuItemSelector: this.selectMenuItem
        });
      });
    }

  }
);
```

We can attach the component to a `ul.menu` element like the one below:

```html
<nav>
  <ul class="menu">
    <li class="menu-item selected">
      <a href="apage.html">A page</a>
    </li>
    <li class="menu-item">
      <a href="anotherpage.html">Another page</a>
    </li>
  </ul>
</nav>
```

Now we have a simple menu component that can be attached to any element that has `.menu-item` children.

## Teardown

Flight provides a set of methods which remove components and their event bindings. It's a good idea to use teardown
components after each unit test - and teardown also good for unbinding event listeners when, for example, the user
navigates away from a page.

There are three levels of teardown:

* On `defineComponent` (i.e. the object exported by `lib/component.js`) - deletes every instance of
every component and all their event bindings.

```js
define(
  [
    'flight/lib/component'
  ],

  function(defineComponent) {

    return defineComponent(navigationMenu);

    function navigationMenu() {

      this.resetEverything = function() {
        //remove every component instance and all event listeners
        defineComponent.teardownAll();
      };
      //..
    }
  }
);
```

* On a Component constructor - deletes every instance of that Component type and all their event bindings.

```js
define(
  [
    'ui/navigationMenu'
  ],

  function(NavigationMenu) {
    //..
    //remove all instances of NavigationMenu and all their event bindings
    NavigationMenu.teardownAll();
  }
);
```

* On a component instance - deletes this instance and its event bindings

```js
define(
  [
    'flight/lib/component'
  ],

  function(defineComponent) {

    return defineComponent(videoPlayer);

    function videoPlayer() {

      this.closeVideoWidget = function() {
        //remove this component instance and its event bindings
        this.teardown();
      };
      //..
    }
  }
);
```

## Mixins

- In Flight, a mixin is a function which assigns properties to a target object (represented by the `this`
keyword).
- A typical mixin defines a set of functionality that will be useful to more than one component.
- One mixin can be applied to any number of [Component](#components) definitions.
- One Component definition can have any number of mixins applied to it.
- Each Component defines a [*core*](#core_mixin) mixin within its own module.
- A mixin can itself have mixins applied to it.

### How do I define a mixin?

Mixin definitions are like Component definitions but without the call to `defineComponent`.

```js

define(
  [],

  function() {

    function withDropdown() {
      this.openDropdown = function() {
        //...
      };
      this.selectItem = function() {
        //...
      };
    }

    // return the mixin function
    return withDropdown;
  }
);
```

### How do I apply mixins to a component?

In the Component definition, pass the required mixins as arguments to the `defineComponent` function:

```js
define(
  [
    'flight/lib/component',
    'mixins/with_dialog',
    'mixins/with_dropdown'
  ],

  function(defineComponent, withDialog, withDropdown) {

    defineComponent(fancyComponent, withDialog, withDropdown);

    function fancyComponent() {
      //...
    }
  }
);
```

### How do I apply mixins to a regular object?

Under the covers, Components add mixins using Flight's `compose` module, which amongst other things, prevents
mixins from clobbering existing method names. If you ever need to apply a mixin to something other than a
component (e.g. to another mixin), you can invoke `compose.mixin` directly:

```js
define(
  [
    'mixins/with_positioning'
  ],

  function(withPositioning) {

    function withDialog() {
      //mix withPositioning into withDialog
      compose.mixin(this, [withPositioning]);

      //...
    }

    // return the mixin function
    return withDialog;
  }
);
```

### Overriding defaults in a mixin

The `defaultAttr` method is available to both component and mixin modules. When used with mixins it will not
overwrite attributes already defined in the component module.

```js
/* mixins/big_button */

define(
  [],

  function() {

    function bigButton() {
      this.defaultAttrs({
        buttonClass: 'js-button-big'
      });
    }

    return bigButton;

  }
);
```
## Advice

In Flight, advice is a mixin (`'lib/advice.js'`) that defines `before`, `after` and `around` methods.

These can be used to modify existing functions by adding custom code. All Components have advice mixed in to
their prototype so that mixins can augment existing functions without requiring knowledge
of the original implementation. Moreover, since Component's are seeded with an empty `initialize` method,
Component definitions will typically use `after` to define custom `initialize` behavior.

### before and after

You can add custom code before or after an existing method by calling the respective advice function with two
arguments. The first is the name of the function you want to augment, the second is a custom function to be
invoked before or after the original:

```js
define(
  [],

  function() {

    function withDrama() {
      this.before('announce', function() {
        clearThroat();
      });
      this.after('leaving', function() {
        slamDoor();
      });
    }

    return withDrama;
  }
);
```

### around

This method is similar to `before` and `after` but allows the existing function to be invoked in the middle of
your custom code (it's similar to [underscore](http://underscorejs.org/)'s `_wrap` function). Again the first argument is the existing function
while the second is the custom function to go around it. The existing function will be passed to the custom
function as an argument so that it can be referenced. If the custom function does not call the existing function
then it will replace that function instead of surround it:

```js
define(
  [],

  function() {

    function withDrama() {
      this.around('announce', function(basicAnnounce) {
        clearThroat();
        basicAnnounce();
        bow();
      });
    }

    return withDrama;
  }
);
```

### Making advice available to regular objects

Advice can be mixed in to non-components using the compose module:

```js
//a simple module: 'test/myObj'
define(
  [],

  function() {
    var myObj = {
      print: function() {
        console.log("hello");
      }
    };

    return myObj;
  }
);

//import myObj and augment it
define(
  [
    'lib/advice',
    'lib/compose',
    'test/myObj'
  ],

  function(advice, compose, myObj) {

    //add advice functions to myObj
    compose.mixin(myObj, [advice.withAdvice]);

    //augment print function
    myObj.after('print', function() {
      console.log("world");
    });
  }
);
```

## Debugging

Flight ships with a debug module which can help you trace the sequence of event triggering and binding. By default
the console will log every trigger, bind and unbind event. By sending instructions to your browser console, you
can filter logged events by type or by name or turn them off completely:

    DEBUG.events.logByAction('trigger'); //only log event triggers
    DEBUG.events.logByName('click'); //only log events named 'click' - accepts * as wildcard
    DEBUG.events.logNone(); //log nothing
    DEBUG.events.logAll(); //log everything

## Authors

+ [@angus-c](http://github.com/angus-c)
+ [@danwrong](http://github.com/danwrong)
+ [@kpk](http://github.com/kennethkufluk)

Thanks for assistance and contributions:

+ [@sayrer](https://github.com/sayrer)
+ [@shinypb](https://github.com/shinypb)
+ [@kloots](https://github.com/kloots)
+ [@marcelduran](https://github.com/marcelduran)
+ [@tbrd](https://github.com/tbrd)
+ [@necolas](https://github.com/necolas)
+ [@fat](https://github.com/fat)
+ [@mkuklis](https://github.com/mkuklis)
+ [@jrburke](https://github.com/jrburke)
+ [@garann](https://github.com/garann)
+ [@WebReflection](https://github.com/WebReflection)
+ [@coldhead](https://github.com/coldhead)
+ [@paulirish](https://github.com/paulirish)
+ [@nimbupani](https://github.com/nimbupani)
+ [@mootcycle](https://github.com/mootcycle)

Special thanks to the rest of the Twitter web team for their abundant contributions and feedback.

## License

Copyright 2013 Twitter, Inc and other contributors.

Licensed under the MIT License


text:
#ifndef __SPINLOCK_H
#define __SPINLOCK_H

/* Need to include this for errval_t */
#include <errors/errno.h>

#define PRINTF_LOCK 0

extern errval_t spinlock_init(void);
extern errval_t spinlock_early_init(void);

/* XXX - this is unimplemented on ARMv8 */
static inline void spinlock_acquire(int locknumber) {}
static inline void spinlock_release(int locknumber) {}

#endif //__SPINLOCK_H


text:
"""Support for Logi Circle devices."""
import asyncio

from aiohttp.client_exceptions import ClientResponseError
import async_timeout
from logi_circle import LogiCircle
from logi_circle.exception import AuthorizationFailed
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.components import persistent_notification
from homeassistant.components.camera import ATTR_FILENAME
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
    ATTR_ENTITY_ID,
    ATTR_MODE,
    CONF_API_KEY,
    CONF_CLIENT_ID,
    CONF_CLIENT_SECRET,
    CONF_MONITORED_CONDITIONS,
    CONF_SENSORS,
    EVENT_HOMEASSISTANT_STOP,
    Platform,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.typing import ConfigType

from . import config_flow
from .const import (
    CONF_REDIRECT_URI,
    DATA_LOGI,
    DEFAULT_CACHEDB,
    DOMAIN,
    LED_MODE_KEY,
    RECORDING_MODE_KEY,
    SENSOR_TYPES,
    SIGNAL_LOGI_CIRCLE_RECONFIGURE,
    SIGNAL_LOGI_CIRCLE_RECORD,
    SIGNAL_LOGI_CIRCLE_SNAPSHOT,
)

NOTIFICATION_ID = "logi_circle_notification"
NOTIFICATION_TITLE = "Logi Circle Setup"

_TIMEOUT = 15  # seconds

SERVICE_SET_CONFIG = "set_config"
SERVICE_LIVESTREAM_SNAPSHOT = "livestream_snapshot"
SERVICE_LIVESTREAM_RECORD = "livestream_record"

ATTR_VALUE = "value"
ATTR_DURATION = "duration"

PLATFORMS = [Platform.CAMERA, Platform.SENSOR]

SENSOR_KEYS = [desc.key for desc in SENSOR_TYPES]

SENSOR_SCHEMA = vol.Schema(
    {
        vol.Optional(CONF_MONITORED_CONDITIONS, default=SENSOR_KEYS): vol.All(
            cv.ensure_list, [vol.In(SENSOR_KEYS)]
        )
    }
)

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {
                vol.Required(CONF_CLIENT_ID): cv.string,
                vol.Required(CONF_CLIENT_SECRET): cv.string,
                vol.Required(CONF_API_KEY): cv.string,
                vol.Required(CONF_REDIRECT_URI): cv.string,
                vol.Optional(CONF_SENSORS, default={}): SENSOR_SCHEMA,
            }
        )
    },
    extra=vol.ALLOW_EXTRA,
)

LOGI_CIRCLE_SERVICE_SET_CONFIG = vol.Schema(
    {
        vol.Optional(ATTR_ENTITY_ID): cv.comp_entity_ids,
        vol.Required(ATTR_MODE): vol.In([LED_MODE_KEY, RECORDING_MODE_KEY]),
        vol.Required(ATTR_VALUE): cv.boolean,
    }
)

LOGI_CIRCLE_SERVICE_SNAPSHOT = vol.Schema(
    {
        vol.Optional(ATTR_ENTITY_ID): cv.comp_entity_ids,
        vol.Required(ATTR_FILENAME): cv.template,
    }
)

LOGI_CIRCLE_SERVICE_RECORD = vol.Schema(
    {
        vol.Optional(ATTR_ENTITY_ID): cv.comp_entity_ids,
        vol.Required(ATTR_FILENAME): cv.template,
        vol.Required(ATTR_DURATION): cv.positive_int,
    }
)

async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up configured Logi Circle component."""
    if DOMAIN not in config:
        return True

    conf = config[DOMAIN]

    config_flow.register_flow_implementation(
        hass,
        DOMAIN,
        client_id=conf[CONF_CLIENT_ID],
        client_secret=conf[CONF_CLIENT_SECRET],
        api_key=conf[CONF_API_KEY],
        redirect_uri=conf[CONF_REDIRECT_URI],
        sensors=conf[CONF_SENSORS],
    )

    hass.async_create_task(
        hass.config_entries.flow.async_init(
            DOMAIN, context={"source": config_entries.SOURCE_IMPORT}
        )
    )

    return True

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Logi Circle from a config entry."""
    logi_circle = LogiCircle(
        client_id=entry.data[CONF_CLIENT_ID],
        client_secret=entry.data[CONF_CLIENT_SECRET],
        api_key=entry.data[CONF_API_KEY],
        redirect_uri=entry.data[CONF_REDIRECT_URI],
        cache_file=hass.config.path(DEFAULT_CACHEDB),
    )

    if not logi_circle.authorized:
        persistent_notification.create(
            hass,
            (
                f"Error: The cached access tokens are missing from {DEFAULT_CACHEDB}.
"
                f"Please unload then re-add the Logi Circle integration to resolve."
            ),
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID,
        )
        return False

    try:
        async with async_timeout.timeout(_TIMEOUT):
            # Ensure the cameras property returns the same Camera objects for
            # all devices. Performs implicit login and session validation.
            await logi_circle.synchronize_cameras()
    except AuthorizationFailed:
        persistent_notification.create(
            hass,
            "Error: Failed to obtain an access token from the cached "
            "refresh token.
"
            "Token may have expired or been revoked.
"
            "Please unload then re-add the Logi Circle integration to resolve",
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID,
        )
        return False
    except asyncio.TimeoutError:
        # The TimeoutError exception object returns nothing when casted to a
        # string, so we'll handle it separately.
        err = f"{_TIMEOUT}s timeout exceeded when connecting to Logi Circle API"
        persistent_notification.create(
            hass,
            f"Error: {err}
You will need to restart hass after fixing.",
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID,
        )
        return False
    except ClientResponseError as ex:
        persistent_notification.create(
            hass,
            f"Error: {ex}
You will need to restart hass after fixing.",
            title=NOTIFICATION_TITLE,
            notification_id=NOTIFICATION_ID,
        )
        return False

    hass.data[DATA_LOGI] = logi_circle

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    async def service_handler(service: ServiceCall) -> None:
        """Dispatch service calls to target entities."""
        params = dict(service.data)

        if service.service == SERVICE_SET_CONFIG:
            async_dispatcher_send(hass, SIGNAL_LOGI_CIRCLE_RECONFIGURE, params)
        if service.service == SERVICE_LIVESTREAM_SNAPSHOT:
            async_dispatcher_send(hass, SIGNAL_LOGI_CIRCLE_SNAPSHOT, params)
        if service.service == SERVICE_LIVESTREAM_RECORD:
            async_dispatcher_send(hass, SIGNAL_LOGI_CIRCLE_RECORD, params)

    hass.services.async_register(
        DOMAIN,
        SERVICE_SET_CONFIG,
        service_handler,
        schema=LOGI_CIRCLE_SERVICE_SET_CONFIG,
    )

    hass.services.async_register(
        DOMAIN,
        SERVICE_LIVESTREAM_SNAPSHOT,
        service_handler,
        schema=LOGI_CIRCLE_SERVICE_SNAPSHOT,
    )

    hass.services.async_register(
        DOMAIN,
        SERVICE_LIVESTREAM_RECORD,
        service_handler,
        schema=LOGI_CIRCLE_SERVICE_RECORD,
    )

    async def shut_down(event=None):
        """Close Logi Circle aiohttp session."""
        await logi_circle.auth_provider.close()

    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, shut_down)
    )

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

    logi_circle = hass.data.pop(DATA_LOGI)

    # Tell API wrapper to close all aiohttp sessions, invalidate WS connections
    # and clear all locally cached tokens
    await logi_circle.auth_provider.clear_authorization()

    return unload_ok


text:
java_import 'org.quartz.JobKey'
java_import 'org.quartz.JobBuilder'
java_import 'org.quartz.TriggerBuilder'
java_import 'org.quartz.impl.StdSchedulerFactory'
java_import 'org.quartz.SimpleScheduleBuilder'
java_import 'org.quartz.CronScheduleBuilder'

module Quartz
  module Scheduler
    def self.included(base)
      base.class_eval do
        include InstanceMethods
        extend ClassMethods
        include Singleton
      end
    end

    module ClassMethods
      def schedule(name, options, &block)
        instance.schedule(name, options, block)
      end
    end

    module InstanceMethods
      def schedule(name, options, block)
        job_code_blocks.jobs[name.to_s] = block

        job_class = (options[:disallow_concurrent] ? Quartz::CronJobSingle : Quartz::CronJob)
        job = JobBuilder.new_job(job_class.java_class).with_identity("#{name}", self.class.to_s).build

        if options[:cron]
          trigger_schedule = CronScheduleBuilder.cron_schedule(options[:cron])
        else
          trigger_schedule = SimpleScheduleBuilder.simple_schedule.
                          with_interval_in_seconds(options[:every].to_i).repeat_forever
        end

        trigger = TriggerBuilder.new_trigger.with_identity("#{name}_trigger", self.class.to_s).
                          with_schedule(trigger_schedule).build

        scheduler.schedule_job(job, trigger)
      end

      def scheduler_factory
        @scheduler_factory ||= StdSchedulerFactory.new
      end

      def scheduler
        @scheduler ||= scheduler_factory.get_scheduler
      end

      def job_code_blocks
        JobBlocksContainer.instance
      end

      def run
        scheduler.start
      end

      def interrupt
        scheduler.standby                                      # don't trigger new jobs
        scheduler.getCurrentlyExecutingJobs.each do |job_context|
          scheduler.interrupt(job_context.job_detail.key)      # interrupt job
        end
      end

      def stop
        interrupt
        scheduler.shutdown(true)
      end
    end
  end
end


text:
/**
 * Durandal events originate from backbone.js but also combine some ideas from signals.js as well as some additional improvements.
 * Events can be installed into any object and are installed into the `app` module by default for convenient app-wide eventing.
 * @module events
 * @requires system
 */
define(['durandal/system'], function (system) {
    var eventSplitter = /\s+/;
    var Events = function() { };

    /**
     * Represents an event subscription.
     * @class Subscription
     */
    var Subscription = function(owner, events) {
        this.owner = owner;
        this.events = events;
    };

    /**
     * Attaches a callback to the event subscription.
     * @method then
     * @param {function} callback The callback function to invoke when the event is triggered.
     * @param {object} [context] An object to use as `this` when invoking the `callback`.
     * @chainable
     */
    Subscription.prototype.then = function (callback, context) {
        this.callback = callback || this.callback;
        this.context = context || this.context;

        if (!this.callback) {
            return this;
        }

        this.owner.on(this.events, this.callback, this.context);
        return this;
    };

    /**
     * Attaches a callback to the event subscription.
     * @method on
     * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, the previous callback will be re-activated.
     * @param {object} [context] An object to use as `this` when invoking the `callback`.
     * @chainable
     */
    Subscription.prototype.on = Subscription.prototype.then;

    /**
     * Cancels the subscription.
     * @method off
     * @chainable
     */
    Subscription.prototype.off = function () {
        this.owner.off(this.events, this.callback, this.context);
        return this;
    };

    /**
     * Creates an object with eventing capabilities.
     * @class Events
     */

    /**
     * Creates a subscription or registers a callback for the specified event.
     * @method on
     * @param {string} events One or more events, separated by white space.
     * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, a subscription instance is returned.
     * @param {object} [context] An object to use as `this` when invoking the `callback`.
     * @return {Subscription|Events} A subscription is returned if no callback is supplied, otherwise the events object is returned for chaining.
     */
    Events.prototype.on = function(events, callback, context) {
        var calls, event, list;

        if (!callback) {
            return new Subscription(this, events);
        } else {
            calls = this.callbacks || (this.callbacks = {});
            events = events.split(eventSplitter);

            while (event = events.shift()) {
                list = calls[event] || (calls[event] = []);
                list.push(callback, context);
            }

            return this;
        }
    };

    /**
     * Removes the callbacks for the specified events.
     * @method off
     * @param {string} [events] One or more events, separated by white space to turn off. If no events are specified, then the callbacks will be removed.
     * @param {function} [callback] The callback function to remove. If `callback` is not provided, all callbacks for the specified events will be removed.
     * @param {object} [context] The object that was used as `this`. Callbacks with this context will be removed.
     * @chainable
     */
    Events.prototype.off = function(events, callback, context) {
        var event, calls, list, i;

        // No events
        if (!(calls = this.callbacks)) {
            return this;
        }

        //removing all
        if (!(events || callback || context)) {
            delete this.callbacks;
            return this;
        }

        events = events ? events.split(eventSplitter) : system.keys(calls);

        // Loop through the callback list, splicing where appropriate.
        while (event = events.shift()) {
            if (!(list = calls[event]) || !(callback || context)) {
                delete calls[event];
                continue;
            }

            for (i = list.length - 2; i >= 0; i -= 2) {
                if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) {
                    list.splice(i, 2);
                }
            }
        }

        return this;
    };

    /**
     * Triggers the specified events.
     * @method trigger
     * @param {string} [events] One or more events, separated by white space to trigger.
     * @chainable
     */
    Events.prototype.trigger = function(events) {
        var event, calls, list, i, length, args, all, rest;
        if (!(calls = this.callbacks)) {
            return this;
        }

        rest = [];
        events = events.split(eventSplitter);
        for (i = 1, length = arguments.length; i < length; i++) {
            rest[i - 1] = arguments[i];
        }

        // For each event, walk through the list of callbacks twice, first to
        // trigger the event, then to trigger any `"all"` callbacks.
        while (event = events.shift()) {
            // Copy callback lists to prevent modification.
            if (all = calls.all) {
                all = all.slice();
            }

            if (list = calls[event]) {
                list = list.slice();
            }

            // Execute event callbacks.
            if (list) {
                for (i = 0, length = list.length; i < length; i += 2) {
                    list[i].apply(list[i + 1] || this, rest);
                }
            }

            // Execute "all" callbacks.
            if (all) {
                args = [event].concat(rest);
                for (i = 0, length = all.length; i < length; i += 2) {
                    all[i].apply(all[i + 1] || this, args);
                }
            }
        }

        return this;
    };

    /**
     * Creates a function that will trigger the specified events when called. Simplifies proxying jQuery (or other) events through to the events object.
     * @method proxy
     * @param {string} events One or more events, separated by white space to trigger by invoking the returned function.
     * @return {function} Calling the function will invoke the previously specified events on the events object.
     */
    Events.prototype.proxy = function(events) {
        var that = this;
        return (function(arg) {
            that.trigger(events, arg);
        });
    };

    /**
     * Creates an object with eventing capabilities.
     * @class EventsModule
     * @static
     */

    /**
     * Adds eventing capabilities to the specified object.
     * @method includeIn
     * @param {object} targetObject The object to add eventing capabilities to.
     */
    Events.includeIn = function(targetObject) {
        targetObject.on = Events.prototype.on;
        targetObject.off = Events.prototype.off;
        targetObject.trigger = Events.prototype.trigger;
        targetObject.proxy = Events.prototype.proxy;
    };

    return Events;
});


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
    switch (arguments.length) {
        case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
        case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
        case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
    }
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var angular2_1 = require('angular2/angular2');
var router_1 = require('angular2/router');
var service_1 = require('./service');
var datepipe_1 = require('./datepipe');
var LatestComponent = (function () {
    function LatestComponent() {
        var self = this;
        this.dataRef = new service_1.FirebaseService().dataRef;
        this.dataRef.orderByChild("date").limitToLast(20).on('value', function (data) {
            self.votes = [];
            data.forEach(function (childSnapshot) {
                var childData = childSnapshot.val();
                self.votes.unshift(childData);
            });
        });
    }
    LatestComponent = __decorate([
        angular2_1.Component({
            directives: [router_1.RouterLink, angular2_1.CORE_DIRECTIVES],
            componentServices: [service_1.FirebaseService],
            templateUrl: "template/latest.html",
            pipes: [datepipe_1.DateFormatPipe],
            selector: 'latest-component'
        }),
        __metadata('design:paramtypes', [])
    ], LatestComponent);
    return LatestComponent;
})();
exports.LatestComponent = LatestComponent;
//# sourceMappingURL=latest.js.map


text:
function middlewareComprobarNoTenerSesion($this, $localStorage, $sessionStorage, rolAdmin) {
  if (typeof $sessionStorage.usuario == "undefined") {
    $this.next();
  } else {
    if ($sessionStorage.usuario.rol_id == rolAdmin) {
      $this.redirectTo('/menuPrincipal');
    } else {
      $this.redirectTo('/');
    }
  }
}


text:
// This software is part of the Autofac IoC container
// Copyright © 2011 Autofac Contributors
// http://autofac.org
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Collections.Generic;

namespace Autofac.Core
{
    /// <summary>
    /// Fired before the activation process to allow parameters to be changed or an alternative
    /// instance to be provided.
    /// </summary>
    public class PreparingEventArgs : EventArgs
    {
        private IEnumerable<Parameter> _parameters;

        /// <summary>
        /// Initializes a new instance of the <see cref="PreparingEventArgs"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="component">The component.</param>
        /// <param name="parameters">The parameters.</param>
        public PreparingEventArgs(IComponentContext context, IComponentRegistration component, IEnumerable<Parameter> parameters)
        {
            if (context == null) throw new ArgumentNullException(nameof(context));
            if (component == null) throw new ArgumentNullException(nameof(component));
            if (parameters == null) throw new ArgumentNullException(nameof(parameters));

            Context = context;
            Component = component;
            _parameters = parameters;
        }

        /// <summary>
        /// Gets the context in which the activation is occurring.
        /// </summary>
        public IComponentContext Context { get; }

        /// <summary>
        /// Gets the component providing the instance being activated.
        /// </summary>
        public IComponentRegistration Component { get; }

        /// <summary>
        /// Gets or sets the parameters supplied to the activator.
        /// </summary>
        public IEnumerable<Parameter> Parameters
        {
            get
            {
                return _parameters;
            }

            set
            {
                if (value == null) throw new ArgumentNullException(nameof(value));
                _parameters = value;
            }
        }
    }
}


text:
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Runtime.Serialization;

using Moq;
using NUnit.Framework;

using WhenItsDone.Data.Contracts;
using WhenItsDone.Data.Repositories;
using WhenItsDone.Models.Contracts;

namespace WhenItsDone.Data.Tests.RepositoriesTests.AsyncGenericRepositoryTests
{
    [TestFixture]
    public class Update_Should
    {
        [Test]
        public void ThrowArgumentNullExceptionWithCorrectMessage_WhenEntityParameterIsNull()
        {
            // Arange
            IDbModel entity = null;

            var fakeDbSet = new Mock<DbSet<IDbModel>>();

            var mockDbContext = new Mock<IWhenItsDoneDbContext>();
            mockDbContext.Setup(mock => mock.Set<IDbModel>()).Returns(fakeDbSet.Object);

            var asyncGenericRepositoryInstace = new GenericAsyncRepository<IDbModel>(mockDbContext.Object);

            // Act & Assert
            Assert.That(
                () => asyncGenericRepositoryInstace.Update(entity),
                Throws.InstanceOf<ArgumentNullException>().With.Message.Contains(nameof(entity)));
        }

        [Test]
        public void InvokeDbContextEntryMethodOnce_WhenParametersAreValid()
        {
            // Arange
            var mockedStaful = new Mock<IStateful<IDbModel>>();

            var fakeDbSet = new Mock<DbSet<IDbModel>>();

            var fakeDbModel = new Mock<IDbModel>();

            var mockDbContext = new Mock<IWhenItsDoneDbContext>();
            mockDbContext.Setup(mock => mock.Set<IDbModel>()).Returns(fakeDbSet.Object);
            mockDbContext.Setup(mock => mock.GetStateful(It.IsAny<IDbModel>())).Returns(mockedStaful.Object);

            var asyncGenericRepositoryInstace = new GenericAsyncRepository<IDbModel>(mockDbContext.Object);

            // Act
            asyncGenericRepositoryInstace.Update(fakeDbModel.Object);

            // Assert
            mockDbContext.Verify(mock => mock.GetStateful(It.IsAny<IDbModel>()), Times.Once());
        }

        [Test]
        public void InvokeDbContextEntryMethodWithCorrectParameter_WhenParametersAreValid()
        {
            // Arange
            var mockedStaful = new Mock<IStateful<IDbModel>>();

            var fakeDbSet = new Mock<DbSet<IDbModel>>();

            var fakeDbModel = new Mock<IDbModel>();

            var mockDbContext = new Mock<IWhenItsDoneDbContext>();
            mockDbContext.Setup(mock => mock.Set<IDbModel>()).Returns(fakeDbSet.Object);
            mockDbContext.Setup(mock => mock.GetStateful(It.IsAny<IDbModel>())).Returns(mockedStaful.Object);

            var asyncGenericRepositoryInstace = new GenericAsyncRepository<IDbModel>(mockDbContext.Object);

            // Act
            asyncGenericRepositoryInstace.Update(fakeDbModel.Object);

            // Assert
            mockDbContext.Verify(mock => mock.GetStateful(fakeDbModel.Object), Times.Once());
        }

        [Test]
        public void ChangeStateOf_Stateful_WhenCalledWithValidParameters()
        {
            // Arange
            var mockedStaful = new Mock<IStateful<IDbModel>>();
            mockedStaful.SetupSet(x => x.State = EntityState.Modified).Verifiable();

            var fakeDbSet = new Mock<DbSet<IDbModel>>();

            var fakeDbModel = new Mock<IDbModel>();

            var mockDbContext = new Mock<IWhenItsDoneDbContext>();
            mockDbContext.Setup(mock => mock.Set<IDbModel>()).Returns(fakeDbSet.Object);
            mockDbContext.Setup(mock => mock.GetStateful(It.IsAny<IDbModel>())).Returns(mockedStaful.Object);

            var asyncGenericRepositoryInstace = new GenericAsyncRepository<IDbModel>(mockDbContext.Object);

            // Act
            asyncGenericRepositoryInstace.Update(fakeDbModel.Object);

            // Assert
            mockedStaful.Verify();
        }
    }
}


text:
<?php

class Google_Service_ShoppingContent_AccountShippingRateTableCell extends Google_Model
{
  protected $conditionType = 'Google_Service_ShoppingContent_AccountShippingCondition';
  protected $conditionDataType = '';
  protected $rateType = 'Google_Service_ShoppingContent_Price';
  protected $rateDataType = '';

  public function setCondition(Google_Service_ShoppingContent_AccountShippingCondition $condition)
  {
    $this->condition = $condition;
  }
  public function getCondition()
  {
    return $this->condition;
  }
  public function setRate(Google_Service_ShoppingContent_Price $rate)
  {
    $this->rate = $rate;
  }
  public function getRate()
  {
    return $this->rate;
  }
}


text:
export interface IncludedAlways {
    a: string;
};


text:
<!doctype html>
<html dir="$i18n{textdirection}" lang="$i18n{language}">
<head>
  <meta charset="utf8">
  <base href="chrome://cellular-setup">
  <style>
    html,
    body {
      display: flex;
      height: 100%;
      justify-content: center;
      margin: 0;
      overflow: hidden;
      width: 100%;
    }
  </style>
</head>
<body>
  <link rel="import" href="chrome://resources/css/text_defaults_md.css">
  <link rel="import" href="i18n_setup.html">
  <link rel="import" href="chrome://resources/cr_components/chromeos/cellular_setup/cellular_setup.html">
  <cellular-setup></cellular-setup>
</body>
</html>


text: prefix + cache.getName() + suffix;


text:
package transport

import (
	"fmt"
	"net"
	"net/http"
	"strings"
	"sync"
	"time"

	utilnet "k8s.io/apimachinery/pkg/util/net"
	"k8s.io/apimachinery/pkg/util/wait"
)

// TlsTransportCache caches TLS http.RoundTrippers different configurations. The
// same RoundTripper will be returned for configs with identical TLS options If
// the config has no custom TLS options, http.DefaultTransport is returned.
type tlsTransportCache struct {
	mu         sync.Mutex
	transports map[tlsCacheKey]*http.Transport
}

const idleConnsPerHost = 25

var tlsCache = &tlsTransportCache{transports: make(map[tlsCacheKey]*http.Transport)}

type tlsCacheKey struct {
	insecure           bool
	caData             string
	certData           string
	keyData            string
	certFile           string
	keyFile            string
	getCert            string
	serverName         string
	nextProtos         string
	dial               string
	disableCompression bool
	proxy              string
}

func (t tlsCacheKey) String() string {
	keyText := "<none>"
	if len(t.keyData) > 0 {
		keyText = "<redacted>"
	}
	return fmt.Sprintf("insecure:%v, caData:%#v, certData:%#v, keyData:%s, getCert: %s, serverName:%s, dial:%s disableCompression:%t, proxy: %s", t.insecure, t.caData, t.certData, keyText, t.getCert, t.serverName, t.dial, t.disableCompression, t.proxy)
}

func (c *tlsTransportCache) get(config *Config) (http.RoundTripper, error) {
	key, err := tlsConfigKey(config)
	if err != nil {
		return nil, err
	}

	// Ensure we only create a single transport for the given TLS options
	c.mu.Lock()
	defer c.mu.Unlock()

	// See if we already have a custom transport for this config
	if t, ok := c.transports[key]; ok {
		return t, nil
	}

	// Get the TLS options for this client config
	tlsConfig, err := TLSConfigFor(config)
	if err != nil {
		return nil, err
	}
	// The options didn't require a custom TLS config
	if tlsConfig == nil && config.Dial == nil && config.Proxy == nil {
		return http.DefaultTransport, nil
	}

	dial := config.Dial
	if dial == nil {
		dial = (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
		}).DialContext
	}

	// If we use are reloading files, we need to handle certificate rotation properly
	// TODO(jackkleeman): We can also add rotation here when config.HasCertCallback() is true
	if config.TLS.ReloadTLSFiles {
		dynamicCertDialer := certRotatingDialer(tlsConfig.GetClientCertificate, dial)
		tlsConfig.GetClientCertificate = dynamicCertDialer.GetClientCertificate
		dial = dynamicCertDialer.connDialer.DialContext
		go dynamicCertDialer.Run(wait.NeverStop)
	}

	proxy := http.ProxyFromEnvironment
	if config.Proxy != nil {
		proxy = config.Proxy
	}

	// Cache a single transport for these options
	c.transports[key] = utilnet.SetTransportDefaults(&http.Transport{
		Proxy:               proxy,
		TLSHandshakeTimeout: 10 * time.Second,
		TLSClientConfig:     tlsConfig,
		MaxIdleConnsPerHost: idleConnsPerHost,
		DialContext:         dial,
		DisableCompression:  config.DisableCompression,
	})
	return c.transports[key], nil
}

// tlsConfigKey returns a unique key for tls.Config objects returned from TLSConfigFor
func tlsConfigKey(c *Config) (tlsCacheKey, error) {
	// Make sure ca/key/cert content is loaded
	if err := loadTLSFiles(c); err != nil {
		return tlsCacheKey{}, err
	}
	k := tlsCacheKey{
		insecure:           c.TLS.Insecure,
		caData:             string(c.TLS.CAData),
		getCert:            fmt.Sprintf("%p", c.TLS.GetCert),
		serverName:         c.TLS.ServerName,
		nextProtos:         strings.Join(c.TLS.NextProtos, ","),
		dial:               fmt.Sprintf("%p", c.Dial),
		disableCompression: c.DisableCompression,
		proxy:              fmt.Sprintf("%p", c.Proxy),
	}

	if c.TLS.ReloadTLSFiles {
		k.certFile = c.TLS.CertFile
		k.keyFile = c.TLS.KeyFile
	} else {
		k.certData = string(c.TLS.CertData)
		k.keyData = string(c.TLS.KeyData)
	}

	return k, nil
}


text:
<?xml version="1.0" encoding="UTF-8" ?>

No documentation is currently available.


text:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>airbus_cobot_gui: airbus_cobot_gui.control_mode.control_mode Namespace Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Namespaces

Classes

Files

Namespace List

Namespace Members

airbus_cobot_gui

control_mode

control_mode

Classes |
Variables

airbus_cobot_gui.control_mode.control_mode Namespace Reference

Classes

class  	ControlMode

 	Class for difine different control mode.  More...

class  	ControlModeWidget

Variables

tuple 	a = QApplication(sys.argv)

tuple 	utt_appli = QMainWindow()

Variable Documentation

          tuple airbus_cobot_gui.control_mode.control_mode.a = QApplication(sys.argv)

Definition at line 100 of file control_mode.py.

          tuple airbus_cobot_gui.control_mode.control_mode.utt_appli = QMainWindow()

Definition at line 102 of file control_mode.py.

airbus_cobot_gui

Author(s):

autogenerated on Thu Dec 17 2015 11:42:05


text:
#include "defs.h"
#include "python-internal.h"
#include "top.h"
#include "cli/cli-utils.h"

/* Readline function suitable for PyOS_ReadlineFunctionPointer, which
   is used for Python's interactive parser and raw_input.  In both
   cases, sys_stdin and sys_stdout are always stdin and stdout
   respectively, as far as I can tell; they are ignored and
   command_line_input is used instead.  */

static char *
gdbpy_readline_wrapper (FILE *sys_stdin, FILE *sys_stdout,
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 4
			const char *prompt)
#else
			char *prompt)
#endif
{
  int n;
  char *p = NULL, *q;

  TRY
    {
      p = command_line_input (prompt, "python");
    }
  /* Handle errors by raising Python exceptions.  */
  CATCH (except, RETURN_MASK_ALL)
    {
      /* Detect user interrupt (Ctrl-C).  */
      if (except.reason == RETURN_QUIT)
	return NULL;

      /* The thread state is nulled during gdbpy_readline_wrapper,
	 with the original value saved in the following undocumented
	 variable (see Python's Parser/myreadline.c and
	 Modules/readline.c).  */
      PyEval_RestoreThread (_PyOS_ReadlineTState);
      gdbpy_convert_exception (except);
      PyEval_SaveThread ();
      return NULL;
    }
  END_CATCH

  /* Detect EOF (Ctrl-D).  */
  if (p == NULL)
    {
      q = (char *) PyMem_RawMalloc (1);
      if (q != NULL)
	q[0] = '\0';
      return q;
    }

  n = strlen (p);

  /* Copy the line to Python and return.  */
  q = (char *) PyMem_RawMalloc (n + 2);
  if (q != NULL)
    {
      strcpy (q, p);
      q[n] = '\n';
      q[n + 1] = '\0';
    }
  return q;
}

/* Initialize Python readline support.  */

void
gdbpy_initialize_gdb_readline (void)
{
  /* Python's readline module conflicts with GDB's use of readline
     since readline is not reentrant.  Ideally, a reentrant wrapper to
     GDB's readline should be implemented to replace Python's readline
     and prevent conflicts.  For now, this file implements a
     sys.meta_path finder that simply fails to import the readline
     module.  */
  if (PyRun_SimpleString ("\
import sys\n\
\n\
class GdbRemoveReadlineFinder:\n\
  def find_module(self, fullname, path=None):\n\
    if fullname == 'readline' and path is None:\n\
      return self\n\
    return None\n\
\n\
  def load_module(self, fullname):\n\
    raise ImportError('readline module disabled under GDB')\n\
\n\
sys.meta_path.append(GdbRemoveReadlineFinder())\n\
") == 0)
    PyOS_ReadlineFunctionPointer = gdbpy_readline_wrapper;
}


text:
Indescriptive Naming

¿Bastante obvio no?

Todavia necesita ser aclarado

Indescriptive Naming

      Nombra tus clases, métodos, atributos y variables adecuadamente.

Indescriptive Naming

¡No abrevies!

Escribimos código para personas no para las computadoras, ellas no entienden lo que escribes, solo entienden de 0 y 1.

Los lenguajes de programación son para humanos