text:
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <iterator>
#include <ctime>
#include <unordered_map>
#include <algorithm>
#include <sys/stat.h>
#include <sys/types.h>
#include <cmath>
#include <algorithm>
#include <cassert>
#include <chrono>

#include "lm.h"

/*
 * Constuct the compacted de bruijn graph from list of distinct kmers
 */

using namespace std;

// 10 chars to store the integer hash of a minimizer
#define MINIMIZER_STR_SIZE 10

// keep largest bucket seen, disregarding small ones
unsigned long nb_elts_in_largest_bucket = 10000;

string minimizer2string(int input_int)
{
    long long i = input_int;
    string str = to_string(i);
    assert(str.size() <= MINIMIZER_STR_SIZE);
    if(MINIMIZER_STR_SIZE > str.size())
        str.insert(0, MINIMIZER_STR_SIZE- str.size(), '0');
    return str;
}

bool nextchar(char * c){
	switch(*c){
		case 'a':
		*c='c';
		return true;
		case 'c':
		*c='g';
		return true;
		case 'g':
		*c='t';
		return true;
		case 't':
		*c='a';
		return false;
		default :
		cout<<"Problem with nextchar: "<<c;
		assert(0);
		return false;
	}
}

// reads k-mers and Put kmers in superbuckets
// (other behavior: just count m-mers)
void sortentry(string namefile, const int k, const int m, HashMap* hm, bool create_buckets, bool m_mer_count){
	int numbersuperbucket(pow(4,m));
	ofstream out[5000];
    ofstream checkpoint;
    if (create_buckets)
    {
    	for(long long i(0);i<numbersuperbucket;i++)
    		out[i].open(".bcalmtmp/z"+to_string(i),ofstream::app);
    }

	ifstream in(namefile);
	string buffer,kmer,prefix;
	in.seekg(0,ios_base::end);
	int64_t size(in.tellg()), buffsize(10000*(k+2)), n(size/buffsize),h;
	in.seekg(0,ios::beg);

	for(int j(0);j<=n;j++){
		if(j==n)
			buffer=readn(&in,size-n*buffsize);
		else
			buffer=readn(&in,buffsize);
		for(uint64_t i(0);i<buffer.size();i+=k+2){
			kmer=buffer.substr(i,k);

            if (m_mer_count)
            {
                count_m_mers(kmer, 2*m, k);
                continue;
            }

			int middlemin, leftmostmin, rightmostmin, min;

            middlemin=minimiserrc(kmer.substr(1,k-2),2*m,hm);
    		leftmostmin=minimiserrc(kmer.substr(0,2*m),2*m,hm);
    		rightmostmin=minimiserrc(kmer.substr(kmer.size()-2*m,2*m),2*m,hm);

            int leftmin = (leftmostmin < middlemin) ? leftmostmin : middlemin;

            int rightmin = (rightmostmin < middlemin) ? rightmostmin : middlemin ;

			min = (leftmin < rightmin) ? leftmin : rightmin;

			h = min/numbersuperbucket;

            if (create_buckets)
    			out[h]<<kmer<< minimizer2string(leftmin) << minimizer2string(rightmin) <<";";
            else
                cout << h << ":" << kmer<< minimizer2string(leftmin) << minimizer2string(rightmin) << ";\n";

            //checkpoint << kmer << minimizer2string(leftmin) << minimizer2string(rightmin) <<";\n";
		}
	}
    if (create_buckets)
        cout << "initial partitioning done" << endl;
}

//copy n characters from in to out
void copylm(ifstream* in,int64_t n,ofstream* out){
	int buffsize(1000000),nbbuffer(n/buffsize);
	string str;
	for(int j(0);j<nbbuffer;j++)	{
		str=readn(in,buffsize);
		*out<<str;
	}
	str=readn(in,n-nbbuffer*buffsize);
	*out<<str;
}

void copylmrv(ifstream* in,int64_t n,ofstream* out){
	int buffsize(1000000),nbbuffer(n/buffsize);
	int64_t pos(in->tellg());
	string str;
	int j;
	for(j=1;j<=nbbuffer;j++){
		in->seekg(pos+n-j*buffsize,ios::beg);
		str=readn(in,buffsize);
		*out<<reversecompletment(str);
	}
	int64_t rest=n-nbbuffer*buffsize;
	if(rest!=0){
		in->seekg(pos,ios::beg);
		str=readn(in,rest);
		*out<<reversecompletment(str);
	}
}

//Put nodes from superbuckets to buckets
void createbucket(const string superbucketname,const int k,const int m,HashMap* hm){
	int superbucketnum(stoi(superbucketname));
	ifstream in(".bcalmtmp/z"+superbucketname);
	if(!in.is_open()){
		cerr<<"Problem with Createbucket"<<endl;
		return;
	}
	in.seekg(0, ios_base::end);
	int64_t size(in.tellg()), buffsize(1000000), numberbuffer(size/buffsize),nb(pow(4,m)),suffix;
	if(size==0){
		remove((".bcalmtmp/z"+superbucketname).c_str());
		return;
	}
	in.seekg(0,ios::beg);
	ofstream out[5000];
	for(long long i(0);i<nb;i++){
		out[i].open(".bcalmtmp/"+to_string(superbucketnum*nb+i),ofstream::app);
	}
	int64_t lastposition(-1),position(0),point(0),mini;
	string buffer;
	vector<string> miniv;
	in.seekg(0);

	for(int j(0);j<=numberbuffer;j++){
		if(j==numberbuffer)
        {
			if(size-numberbuffer*buffsize-1!=-1){
				buffer=readn(&in,size-numberbuffer*buffsize-1);
				buffer+=";";
			}
			else
				buffer="";
        }
		else
		{
			buffer=readn(&in,buffsize);
			point+=buffsize;
		}
		for (uint64_t i(0); i<buffer.size(); i++,position++)
        {
			if((buffer)[i]==';'){
                int leftmin, rightmin;
				if(i>=(uint64_t)(MINIMIZER_STR_SIZE * 2))
                {
					leftmin = stoi(buffer.substr(i-(MINIMIZER_STR_SIZE * 2),MINIMIZER_STR_SIZE));
					rightmin = stoi(buffer.substr(i-MINIMIZER_STR_SIZE,MINIMIZER_STR_SIZE));
                }
				else{
					in.seekg(position-(MINIMIZER_STR_SIZE * 2));
					leftmin = stoi(readn(&in,MINIMIZER_STR_SIZE));
					rightmin = stoi(readn(&in,MINIMIZER_STR_SIZE));
                }
				string first_bucket_of_superbucket(to_string((long long)(superbucketnum*nb-1)));
				mini = minbutbiggerthan(leftmin, rightmin, first_bucket_of_superbucket);
				suffix=mini%nb;
				in.seekg(lastposition+1,ios_base::beg);
				copylm(&in,position-lastposition,&out[suffix]);
				lastposition=position;
			}
        }
		in.seekg(point);
	}
	remove((".bcalmtmp/z"+superbucketname).c_str());
}

//count the length of each node
vector<int64_t> countbucket(const string& name){
	vector<int64_t> count;
	ifstream in(".bcalmtmp/"+name);
	if(in){
		in.seekg( 0 , ios_base::end );
		int64_t size(in.tellg()),buffsize(10),numberbuffer(size/buffsize),lastposition(-1),position(0);
		if(size<2)
			return count;
		in.seekg(0,ios::beg);
		string buffer;

		for(int j(0);j<numberbuffer;j++){
			buffer=readn(&in,buffsize);
			for (uint64_t i(0); i<buffer.size(); i++,position++)
				if((buffer)[i]==';'){
					count.push_back(position-lastposition-1);
					lastposition=position;
				}
		}

		buffer=readn(&in,size-numberbuffer*buffsize);
		for (uint64_t i(0); i<buffer.size(); i++,position++)
			if((buffer)[i]==';'){
				count.push_back(position-lastposition-1);
				lastposition=position;
			}
	}
	return count;
}

//true iff node does not contain tag
bool notag(const string& node,const int64_t start,int64_t* n){
	for(uint64_t i(start);i<node.size();i++){
		if (node[i] >= '0' && node[i] <= '9'){
			*n=i;
			return false;
		}
	}
	return true;
}

//return length of tag
int taglength(const string& node, int64_t j){
	int n=1;
	for(uint64_t i(j+1);i<node.size();i++)
		if ((node[i] >= '0' && node[i] <= '9') || node[i]=='+' || node[i]=='-')
			n++;
		else
			return n;
	return n;
}

//Write a node remplacing tags by their sequences
void writeit(const string& outfile,const string& node, int leftmin, int rightmin, vector<pair<int64_t,int64_t>>* tagsposition,ifstream* tagfile,int64_t j,const string& fout){
	ofstream out(".bcalmtmp/"+outfile,ios::app);
	char rc;
	if(out){
		int64_t lastposition(0),tag,tagl,position,length;
		pair<int64_t,int64_t> pair;
		do{
			out<<node.substr(lastposition,j-lastposition-1);
			tagl=taglength(node,j);
			rc=node[j-1];
			if(rc=='+'){
				tag=stoi(node.substr(j,tagl));
			}
			else{
				tag=stoi(reversecompletment(node.substr(j,tagl)));
			}
			lastposition=j+tagl;
			pair=(*tagsposition)[tag];
			position=pair.first;
			length= pair.second;
			tagfile->seekg(position,ios_base::beg);
			if(rc=='+')
				copylm(tagfile,length,&out);
			if(rc=='-')
				copylmrv(tagfile,length,&out);
		}
		while(!notag(node,lastposition,&j));
		if(outfile!=fout)
			out<<node.substr(lastposition)<< minimizer2string(leftmin) << minimizer2string(rightmin) <<";";
		else
			out<<node.substr(lastposition) <<";"<<endl;
	}
	else
		cerr<<"writeitbug"<<endl;
}

void put(const string& outfile,const string& node, int leftmin, int rightmin, const string& fout){
	ofstream out(".bcalmtmp/"+outfile,ios::app);
	if(outfile==fout)
	    out<<node <<";" << endl;
    else
	    out<<node<< minimizer2string(leftmin) << minimizer2string(rightmin) <<";";
}

void putorwrite(const string& outfile, const string& node, int leftmin, int rightmin, vector<pair<int64_t,int64_t>>* tagsposition , ifstream* tagfile,const string& fout){
	int64_t i;
	if(notag(node,0,&i))
		put(outfile,node,leftmin, rightmin, fout);
	else
		writeit(outfile,node, leftmin, rightmin, tagsposition,tagfile,i,fout);
}

//Decide where to put a node
void goodplace(const string& node, int leftmin, int rightmin, int k, const string& bucketname,vector<pair<int64_t,int64_t>>* tagsposition,ifstream* tagfile,const int m,const string& nameout,HashMap* hm){
	int nb(pow(4,m)),prefixnumber(stoi(bucketname)/nb+1);
	long long mini(minbutbiggerthan(leftmin, rightmin, bucketname));
	if(mini==-1)
		putorwrite( nameout, node, leftmin, rightmin, tagsposition,tagfile,nameout);
	else{
		long long minipre(mini/nb);
		string miniprefix('z'+to_string(minipre));
		putorwrite( ((minipre >= prefixnumber) ?  miniprefix: to_string(mini)), node, leftmin, rightmin, tagsposition,tagfile,nameout);
	}
}

//Compact a bucket and put the nodes on the right place
void compactbucket(const int& prefix,const int& suffix,const int k,const char *nameout,const int m,HashMap* hm){
	int64_t buffsize(k),postags(0),length,nb(pow(4,m));
	long long tagnumber(0),numberbucket(prefix*nb+suffix);
	string fullname(to_string(numberbucket)),node,tag,end;
	auto count(countbucket(fullname));
	if(count.size()==0)	{
		remove((".bcalmtmp/"+fullname).c_str());
		return;
	}

    // keep largest bucket seen
    if (count.size() > nb_elts_in_largest_bucket)
    {
        nb_elts_in_largest_bucket = count.size();
	    system(("cp .bcalmtmp/" + fullname + " largest_bucket.dot").c_str());
    }

	ifstream in(".bcalmtmp/"+fullname);
	ofstream tagfile(".bcalmtmp/tags"),out(".bcalmtmp/"+(string)nameout,ios_base::app);
	graph g(k);
	vector<pair<int64_t,int64_t>> tagsposition;

    // add nodes to graph
	if(in && tagfile && out){
		for(auto it=count.begin();it!=count.end();it++){
			length=*it;
			if(length-(MINIMIZER_STR_SIZE*2)<=2*buffsize){
				node=readn(&in,length+1);
				g.addvertex(node.substr(0,length-(MINIMIZER_STR_SIZE*2)));
                g.addleftmin(stoi(node.substr(length-(MINIMIZER_STR_SIZE*2),MINIMIZER_STR_SIZE)));
                g.addrightmin(stoi(node.substr(length-MINIMIZER_STR_SIZE,MINIMIZER_STR_SIZE)));
			}
			else{
				node=readn(&in,buffsize);
				tag=to_string(tagnumber);
				node+="+"+tag+"+";
				tagnumber++;
				copylm(&in,length-(MINIMIZER_STR_SIZE*2)-2*buffsize,&tagfile);
				tagsposition.push_back(make_pair(postags,length-(MINIMIZER_STR_SIZE*2)-2*buffsize));
				postags+=length-(MINIMIZER_STR_SIZE*2)-2*buffsize;
				end=readn(&in,buffsize);
				node+=end.substr(0,buffsize);
				g.addvertex(node);
                g.addleftmin(stoi(readn(&in,MINIMIZER_STR_SIZE)));
                g.addrightmin(stoi(readn(&in,MINIMIZER_STR_SIZE)));
                readn(&in,1); // the ';'
			}
		}
		tagfile.close();
	}

	remove((".bcalmtmp/"+fullname).c_str());
	g.debruijn();

	g.compressh(stoi(fullname),hm);
	ifstream fichiertagin(".bcalmtmp/tags");
    int node_index = 0;

	for(auto it(g.nodes.begin());it!=g.nodes.end();it++)
    {
		if(it->size()!=0)
        {
            int leftmin = g.leftmins[node_index];
            int rightmin = g.rightmins[node_index];
			goodplace(*it, leftmin, rightmin, k,fullname,&tagsposition,&fichiertagin,m,nameout,hm);
        }
        node_index++;
    }

	remove(".bcalmtmp/tags");
	return;
}

//Create a file with the nodes of the compacted graph
void createoutfile(const char *namein,const char *nameout,const int k,const int m){
	auto start=chrono::system_clock::now();
	HashMap hm(build_hash_map(2*m));
	int64_t nbsuperbucket(pow(4,m)),sys(0);
	mkdir(".bcalmtmp",0777);
	sys+=system("rm -rf .bcalmtmp/*");
	remove(nameout);

    // create the hash function
    init_m_mers_table(2*m);
    sortentry(namein,k,m,&hm, false, true);
    create_hash_function_from_m_mers(2*m);

	sortentry(namein,k,m,&hm);
	for(long long i(0);i<nbsuperbucket;i++){
		createbucket(to_string(i),k,m,&hm);
		for(int j(0);j<pow(4,m);j++)
			compactbucket(i,j,k,nameout,m,&hm);
	}
	sys+=system(("mv .bcalmtmp/"+(string)nameout+" "+(string)nameout).c_str());
	if(sys!=0)
		cerr<<"system call failed"<<endl;
	 auto end=chrono::system_clock::now();
	 auto waitedFor=end-start;
	 cout<<"Last for "<<chrono::duration_cast<chrono::seconds>(waitedFor).count()<<" seconds"<<endl;
}


text:
/*
  @author:   Conan Albrecht <ca@byu.edu>
  @version:  1.1
  @modified: 2012-02-29
  @license:  Public Domain; No warranty of any kind is given.  Use at your own risk.

  A JQuery plugin to freeze table columns and headers -- spreadsheet style.
    * Any items in the
 are frozen as headers.
    * The given number of columns are frozen.

  Please note that this is a big hack on the
 tag in HTML.  The script takes your table
  and splits it into 4 tables:
    Region 1    Region 2
    Region 3    Region 4

    - Region 1 is the top-left corner cell (or cells for multiple frozen columns/headers)
    - Region 2 is your
 cells, less the ones pulled off the left
    - Region 3 is your frozen columns on the left side.
    - Region 4 is the regular, unfrozen data of the table.
    The script keeps the row height of Regions 3 and 4 the same, and it keeps the column width of
    Regions 1 and 3/2 and 4 the same.  That makes the user think it's one big table still.
    When either Region 3 or 4 are scrolled, the script matches the other tables to it.

    The script makes four copies of your table, then deletes rows and columns as needed.  This ensures that
    the table/row/cell properties, events, etc. move into each area.  This approach works well with regular-sized
    tables, but it won't be efficient with huge tables.

  Options:
    The script takes several options.  All of these are listed (with comments) in the example below.

  Known issues:

    * It works with columns that span (), but *at least one
* in each region must be
      free of colspans.  In other words, you can span columns all you want, but you must leave at least
      one row a normal row with non-spanning columns in each of the four regions.  The algorithm in this
      script uses this non-colspanning row to figure out column widths.  In addition, tables can behave
      erratically when columns are spanned no the first row.  YMMV.
    * It has to allow the tables unlimited width to get a calculation of how big they need to be.  This
      "unlimited" width is currently set at 50,000 pixels.  You may want to adjust this if your table
      is bigger than this (wow!) or subsantially smaller (to save memory).
    * It doesn't support freezing of
 areas.
  Example (don't forget to set the path to jquery.freezetablecolumns.1.1.js appropriately):

<button id="mybutton">Adjust the Layout After Display (just another example)</button>

*/

(function( $ ) {
  $.fn.freezeTableColumns = function(options) {
    options = initOptions(options);
		var source_table = $(this);
		var main_id = source_table.attr('id');
		if (!main_id) {
		  console.log('jquery.freezetablecolumns.js: Error initializing frozen columns - source table must have a unique id attribute.');
		  return;
	  }

		// set up the four regions
		source_table.after('

');
		source_table.detach(); // remove the table from the document flow
		main_div = $('#' + main_id + '-div');
		main_div.append(
		  '
' +
		  '

' +
      '

' +
		  '
'
		);
		main_div.append(
      '
' +
		  '

' +
      '

' +
	    '
'
	  );

		// row 1 (corner area and header divs)
		// note that I use .children() rather than .find() in case the user's table cells have additional tables embedded within them
		var source_table_region1 = source_table.get(0).cloneNode(false);
		$(source_table_region1).removeAttr('id'); // only one of the four tables can have the original id
    moveElement(source_table_region1, $('#' + main_id + '-region1').children('div'));
    $('#' + main_id + '-region1').children('div').children('table').append('

');
    var thead = $('#' + main_id + '-region1 > div > table > thead');
    source_table.children('thead').children('tr').each(function(rowindex, rowelement) {
      thead.append('

');
      var tr = thead.children('tr:last');
      var cellindex = 0;
      $(rowelement).children('td,th').each(function() {
        if (cellindex >= options.numFrozen) {
          return false;
        }
        moveElement(this, tr);
        if (typeof $(this).attr('colspan') === "undefined") {
          cellindex += 1;
        }else{
          cellindex += $(this).attr('colspan');
        }
      });
    });
    var source_table_region2 = source_table.get(0).cloneNode(false);
		$(source_table_region2).removeAttr('id'); // only one of the four tables can have the original id
    moveElement(source_table_region2, $('#' + main_id + '-region2').children('div')); // second table is easier because we already removed the frozen td's -- just add what's left in the thead
		moveElement(source_table.children('thead'), $('#' + main_id + '-region2').children('div').children('table'));

    // row 2 (frozen columns and main data table divs)
    var source_table_region3 = source_table.get(0).cloneNode(false);
		$(source_table_region3).removeAttr('id'); // only one of the four tables can have the original id
    moveElement(source_table_region3, $('#' + main_id + '-region3').children('div'));
    $('#' + main_id + '-region3').children('div').children('table').append('

');
    var tbody = $('#' + main_id + '-region3 > div > table > tbody');
    source_table.children('tbody').children('tr').each(function(rowindex, rowelement) {
      tbody.append('

');
      var tr = tbody.children('tr:last');
      var cellindex = 0;
      $(rowelement).children('td,th').each(function() {
        if (cellindex >= options.numFrozen) {
          return false;
        }
        moveElement(this, tr);
        if (typeof $(this).attr('colspan') === "undefined") {
          cellindex += 1;
        }else{
          cellindex += $(this).attr('colspan');
        }
      });
    });
    moveElement(source_table, $('#' + main_id + '-region4').children('div')) // move whatever is left in the table

    // set to fixed-with
    for (var i = 1; i <= 4; i++) {
      $('#' + main_id + '-region' + i).children('div').children('table').css('table-layout', 'fixed');
    }

    // lay everything out
    source_table.freezeTableColumnsLayout(options);

    // set up the events to match elements when scrolled
    var scroll_affects = {  // source -> xscroll, yscroll
      '-region1': [ '-region3', '-region2' ],
      '-region2': [ '-region4', '-region1' ],
      '-region3': [ '-region1', '-region4' ],
      '-region4': [ '-region2', '-region3' ],
    }
    main_div.children('div').children('div').scroll(function(event) {
      var sourceid = $(this).attr('id').substr($(this).attr('id').lastIndexOf('-'));
      $('#' + main_id + scroll_affects[sourceid][0]).scrollLeft($(this).scrollLeft());
      $('#' + main_id + scroll_affects[sourceid][1]).scrollTop($(this).scrollTop());
    });//scroll

  };//freezeTableColumns

  /*
    Moves an element to a new parent.  I use the Javascript DOM methods here because
    JQuery's append strips and evaluates any attached javascript the user has in the table.
    This is not what the user expects, so move the table elements using DOM.
    I use this method any time I'm moving existing HTML I didn't place in the document.
  */
  function moveElement(element, newparent) {
    $(element).each(function(eindex, e) {
      $(newparent).get(0).appendChild(e);
    });
  }

  /*
    Adjusts the widths to an already-existing frozen table.  This allows you to adjust the main div height or width,
    cell contents, etc., and then lay everything out again.  The options are the same as the main function, but
    you can't change the number of frozen columns.  See the example at the top for, well, an example.
  */
  $.fn.freezeTableColumnsLayout = function(options) {
    options = initOptions(options);
    var main_id = $(this).attr('id');

		// make all the columns the same width
		function setColWidths(topRegion, bottomRegion) {
		  // clear the widths if needed
		  if (options.clearWidths) {
  		  topRegion.children('div').children('table').width('');
	  	  bottomRegion.children('div').children('table').width('');
		    topRegion.children('div').children('table').children('thead,tbody').children('tr').children('td,th').each(function() {
		      $(this).removeAttr('width');
		      $(this).css('width', '');
	      });
		    bottomRegion.children('div').children('table').children('thead,tbody').children('tr').children('td,th').each(function() {
		      $(this).removeAttr('width');
		      $(this).css('width', '');
	      });
	    }
		  // find the first
 without any colspan attributes (those mess up the algorithm)
		  var top_tr = null;
		  topRegion.children('div').children('table').children('thead,tbody').children('tr').each(function(index) {
		    if ($(this).children('td,th').filter('[colspan]').length == 0) { // i.e. this row has no colspans
  		    top_tr = $(this);
  		    return false;
	      }
	    });
		  var bottom_tr = null;
		  bottomRegion.children('div').children('table').children('thead,tbody').children('tr').each(function(index) {
		    if ($(this).children('td,th').filter('[colspan]').length == 0) { // i.e. this row has no colspans
  		    bottom_tr = $(this);
  		    return false;
	      }
	    });
	    if (top_tr == null || bottom_tr == null) {
  		  return;
      }
	    // set the widths of each column
	    topRegion.children('div').children('table').children('colgroup').remove();
	    topRegion.children('div').children('table').prepend('<colgroup></colgroup>');
	    bottomRegion.children('div').children('table').children('colgroup').remove();
	    bottomRegion.children('div').children('table').prepend('<colgroup></colgroup>');
  		top_tr.children('td,th').each(function(index) {
  		  var bottomcell = bottom_tr.children('td,th').eq(index);
  		  var maxwidth = Math.max($(this).width(), bottomcell.width()) + 10;
  		  topRegion.children('div').children('table').children('colgroup').append('<col width="' + maxwidth + '"/>');
  		  bottomRegion.children('div').children('table').children('colgroup').append('<col width="' + maxwidth + '"/>');
  	  });//each
    }//setColWidths function
    setColWidths($('#' + main_id + '-region1'), $('#' + main_id + '-region3'));
    setColWidths($('#' + main_id + '-region2'), $('#' + main_id + '-region4'));

    // make all the rows the same height
    function setRowHeights(left_region, right_region) {
      left_region.children('div').children('table').children('thead,tbody').children('tr').each(function(index) {
        var right_region_tr = right_region.children('div').children('table').children('tbody,thead').children('tr').eq(index);
        var maxheight = Math.max($(this).height(), right_region_tr.height());
        $(this).height(maxheight);
        right_region_tr.height(maxheight);
      });
    }//setRowHeights
    setRowHeights($('#' + main_id + '-region1'), $('#' + main_id + '-region2'));
    setRowHeights($('#' + main_id + '-region3'), $('#' + main_id + '-region4'));

		// set row 2 height to follow the required height
		var row1height = $('#' + main_id + '-div').children('#' + main_id + '-row1').outerHeight();
		$('#' + main_id + '-div').children('#' + main_id + '-row2').height(options.height - row1height);

    // calculate how big the tables want to be, given an "unlimited" space (50,000 in this case)
    $('#' + main_id + '-region1').children('div').width(50000);
    $('#' + main_id + '-region2').children('div').width(50000);
    $('#' + main_id + '-region3').children('div').width(50000);
    $('#' + main_id + '-region4').children('div').width(50000);
    var region1_3div = Math.max($('#' + main_id + '-region1').children('div').children('table').outerWidth(), $('#' + main_id + '-region3').children('div').children('table').outerWidth());
    var region2_4div = Math.max($('#' + main_id + '-region1').children('div').children('table').outerWidth(), $('#' + main_id + '-region4').children('div').children('table').outerWidth());
    if (options.frozenWidth < 0) {
      options.frozenWidth = region1_3div;
    }

    // set the widths for both the containing divs (with the overflow scrolls) and the inner divs (that give the tables all the room they want)
    $('#' + main_id + '-region1').width(options.frozenWidth);
    $('#' + main_id + '-region1').children('div').width(region1_3div);
    $('#' + main_id + '-region2').width(options.width - options.frozenWidth);
    $('#' + main_id + '-region2').children('div').width(region2_4div);
    $('#' + main_id + '-region3').width(options.frozenWidth);
    $('#' + main_id + '-region3').children('div').width(region1_3div);
    $('#' + main_id + '-region4').width(options.width - options.frozenWidth);
    $('#' + main_id + '-region4').children('div').width(region2_4div);
  };//freezeTableColumnsLayout

  /* Initializes the options with default values - not meant to be called externally */
  function initOptions(options) {
		return $.extend({
      width:       800,
      height:      800,
      numFrozen:   1,
      frozenWidth: -1, // default is dynamic
      clearWidths: true,
		}, options || {});//extend
  };//initOptions

})( jQuery );

redpajama_set_name: RedPajamaGithub


text:
title: Telerik.Charting.ColorBlend
page_title: Telerik.Charting.ColorBlend
description: Telerik.Charting.ColorBlend
---

# Telerik.Charting.ColorBlend

Defines arrays of elements and positions used for interpolating GradientElement blending in a multicolor gradient.

## Inheritance Hierarchy

* System.Object
* Telerik.Charting.ChartingStateManagedCollection`1 : IChartingStateManager, ICollection, ICollection`1, IEnumerable, IEnumerable`1, IList, IList`1
* Telerik.Charting.ColorBlend : ICloneable

## Properties

###  Count `Int32`

Gets items count in collection

###  First `T`

Link to first item in collection

###  IsReadOnly `Boolean`

Gets true if collection is read-only

###  Item `T`

Gets the collection item at given index

###  Last `T`

Link to last item in collection

###  List `IList`1`

Items list

## Methods

###  Add

Adds new item in collection

#### Parameters

#### item ``0`

Item to add

#### Returns

`System.Void`

###  AddRange

Adds a range of elements to the collection.

#### Parameters

#### blend `Telerik.Charting.ColorBlend`

Object that contains element to add

#### Returns

`System.Void`

###  AddRange

Adds items range in collection

#### Parameters

#### itemsToAdd ``0`

Items array to add

#### Returns

`System.Void`

###  Clear

Clears collection

#### Returns

`System.Void`

###  Clone

Clone this object.

#### Returns

`System.Object` New instance of ColorBlend class with the same fields as this one.

###  Compare

Color blends comparer

#### Parameters

#### a `Telerik.Charting.ColorBlend`

First object for comparing

#### b `Telerik.Charting.ColorBlend`

Second object for comparing

#### Returns

`System.Boolean` Whether objects equal or not

###  Contains

Checks does collection contain the given item

#### Parameters

#### item ``0`

Item to check

#### Returns

`System.Boolean` True if item is a collection member

###  CopyTo

Copies the entire System.Collections.Generic.List<T> to a compatible one-dimensional
                array, starting at the specified index of the target array.

#### Parameters

#### array ``0`

The one-dimensional System.Array that is the destination of the elements

#### arrayIndex `System.Int32`

The zero-based index in array at which copying begins

#### Returns

`System.Void`

###  Equals

Comparing two objects.

#### Parameters

#### obj `System.Object`

Object to compare.

#### Returns

`System.Boolean` Whether objects equal or not

###  GetBrush

Returns gradient brush

#### Parameters

#### rectangle `System.Drawing.RectangleF`

Rectangle of brush

#### angle `System.Single`

Angle of brush.

#### Returns

`System.Drawing.Drawing2D.LinearGradientBrush` Gradient brush

###  GetColor

Gets color at specified position.

#### Parameters

#### pos `System.Single`

Position to get color.

#### Returns

`System.Drawing.Color` Color at specified position.

###  GetColors

Gets ColorBlend's colors.

#### Returns

`System.Drawing.Color[]` ColorBlend's colors.

###  GetEnumerator

Returns an enumerator that iterates through the System.Collections.Generic.List>T<.

#### Returns

`System.Collections.Generic.IEnumerator`1` A System.Collections.Generic.List>T<.Enumerator for the System.Collections.Generic.List>T<.

###  GetPositions

Gets ColorBlend's positions.

#### Returns

`System.Single[]` ColorBlend's positions.

###  IndexOf

Item index in collection

#### Parameters

#### item ``0`

Item to get index of

#### Returns

`System.Int32` Index

###  Insert

Inserts item at the given index

#### Parameters

#### index `System.Int32`

Index

#### item ``0`

Item to insert

#### Returns

`System.Void`

###  LoadFrom

Load pairs colors\positions from specified object.

#### Parameters

#### blend `Telerik.Charting.ColorBlend`

Object to load from.

#### Returns

`System.Void`

###  LoadViewState

Loads collection from view state

#### Parameters

#### state `System.Object`

View state to load from

#### Returns

`System.Void`

###  OnClear

Before collection clearing event

#### Returns

`System.Void`

###  OnClearComplete

Collection after clean event

#### Returns

`System.Void`

###  OnInsert

Item before insert event

#### Parameters

#### index `System.Int32`

Index to insert at

#### value `System.Object`

Value to insert

#### Returns

`System.Void`

###  OnInsertComplete

Item after insert event

#### Parameters

#### index `System.Int32`

Index to insert at

#### value `System.Object`

Value to insert

#### Returns

`System.Void`

###  OnRemove

Item before remove event

#### Parameters

#### index `System.Int32`

Index to insert at

#### value `System.Object`

Value to insert

#### Returns

`System.Void`

###  OnRemoveComplete

Item after remove event

#### Parameters

#### index `System.Int32`

Index to insert at

#### value `System.Object`

Value to insert

#### Returns

`System.Void`

###  PopulateFromXml

Populates collection from XML element

#### Parameters

#### rootElement `System.Xml.XmlElement`

XmlElement to import from

#### Returns

`System.Void`

###  Remove

Removes item from collection

#### Parameters

#### item ``0`

Item to remove

#### Returns

`System.Boolean` True in case of success

###  RemoveAt

Removes item from collection at given index

#### Parameters

#### index `System.Int32`

Index to remove at

#### Returns

`System.Void`

###  SaveViewState

Saves collection to a view state

#### Returns

`System.Object` Saved state bag object

###  SetDirty

Sets is item in the dirty state

#### Returns

`System.Void`

###  SetItemDirty

Marks collection item dirty

#### Parameters

#### item ``0`

Item to mark

#### Returns

`System.Void`


text:
namespace blink {

SharedWorkerContentSettingsProxy::SharedWorkerContentSettingsProxy(
    mojo::PendingRemote<mojom::blink::WorkerContentSettingsProxy> host_info)
    : host_info_(std::move(host_info)) {}
SharedWorkerContentSettingsProxy::~SharedWorkerContentSettingsProxy() = default;

bool SharedWorkerContentSettingsProxy::AllowStorageAccessSync(
    StorageType storage_type) {
  bool result = false;
  switch (storage_type) {
    case StorageType::kIndexedDB: {
      SCOPED_UMA_HISTOGRAM_TIMER("ServiceWorker.AllowIndexedDBTime");
      GetService()->AllowIndexedDB(&result);
      break;
    }
    case StorageType::kCacheStorage: {
      SCOPED_UMA_HISTOGRAM_TIMER("ServiceWorker.AllowCacheStorageTime");
      GetService()->AllowCacheStorage(&result);
      break;
    }
    case StorageType::kWebLocks: {
      SCOPED_UMA_HISTOGRAM_TIMER("ServiceWorker.AllowWebLocksTime");
      GetService()->AllowWebLocks(&result);
      break;
    }
    case StorageType::kFileSystem: {
      SCOPED_UMA_HISTOGRAM_TIMER("ServiceWorker.RequestFileSystemAccessTime");
      GetService()->RequestFileSystemAccessSync(&result);
      break;
    }
    default: {
      // TODO(shuagga@microsoft.com): Revisit this default in the future.
      return true;
    }
  }

  return result;
}

// Use ThreadSpecific to ensure that |content_settings_instance_host| is
// destructed on worker thread.
// Each worker has a dedicated thread so this is safe.
mojo::Remote<mojom::blink::WorkerContentSettingsProxy>&
SharedWorkerContentSettingsProxy::GetService() {
  DEFINE_THREAD_SAFE_STATIC_LOCAL(
      ThreadSpecific<mojo::Remote<mojom::blink::WorkerContentSettingsProxy>>,
      content_settings_instance_host, ());
  if (!content_settings_instance_host.IsSet()) {
    DCHECK(host_info_.is_valid());
    content_settings_instance_host->Bind(std::move(host_info_));
  }
  return *content_settings_instance_host;
}

}  // namespace blink


text:
module MT940Structured::Parsers::Abnamro

  class TransactionParser
    include MT940Structured::Parsers::DateParser
    include MT940Structured::Parsers::IbanSupport
    include MT940Structured::Parsers::StructuredDescriptionParser
    include MT940Structured::Parsers::DefaultLine61Parser

    def get_regex_for_line_61
      /^:61:(\d{6})(\d{4})?(C|D)(\d+),(\d{0,2})/
    end

    def enrich_transaction(transaction, line_86)
      transaction.contra_account = "NONREF" #default
      line_86 = line_86.gsub(/:86:/, '')
      case line_86
        when /\/TRTP\/(?:SEPA|IDEAL|ACCEPTGIRO)/
          parse_result = Line86.parse(line_86)
          transaction.contra_account_iban = parse_result.counter_party.iban
          transaction.contra_account = iban_to_account transaction.contra_account_iban if transaction.contra_account_iban
          transaction.contra_account_owner = parse_result.counter_party.name
          transaction.description = parse_result.remi
          transaction.eref = parse_result.eref
        when /^(GIRO)\s+(\d+)(.+)/
          transaction.contra_account = $2.rjust(9, '000000000')
          transaction.description = $3.strip
        when /^(\d{2}.\d{2}.\d{2}.\d{3})(.+)/
          transaction.description = $2.strip
          transaction.contra_account = $1.gsub('.', '')
        when /SEPA IDEAL/
          transaction.description = parse_single_value(line_86, /OMSCHRIJVING\:(.+)?/)
          parse_iban_bic(line_86, transaction)
          transaction.contra_account_owner = parse_single_value line_86, /NAAM\:(.+)?OMSCHRIJVING\:/
        when /SEPA ACCEPTGIROBETALING/
          transaction.description = parse_single_value(line_86, /(BETALINGSKENM\.\:.+)/)
          parse_iban_bic(line_86, transaction)
          transaction.contra_account_owner = parse_single_value line_86, /NAAM\:(.+)?BETALINGSKENM\.\:/
        when /SEPA OVERBOEKING/
          transaction.description = parse_single_value(line_86, /OMSCHRIJVING\:(.+)?/)
          parse_iban_bic(line_86, transaction)
          transaction.contra_account_owner = parse_single_value line_86, /NAAM\:(.+)?OMSCHRIJVING\:/
        when /SEPA INCASSO ALGEMEEN DOORLOPEND/
          transaction.description = parse_single_value(line_86, /OMSCHRIJVING\:(.+)?IBAN\:/)
          parse_iban_bic(line_86, transaction)
          transaction.contra_account_owner = parse_single_value line_86, /NAAM\:(.+)?MACHTIGING\:/
        when /SEPA PERIODIEKE OVERB\./
          transaction.description = parse_single_value(line_86, /OMSCHRIJVING\:(.+)?/)
          parse_iban_bic(line_86, transaction)
          transaction.contra_account_owner = parse_single_value line_86, /NAAM\:(.+)?OMSCHRIJVING\:/
        else
          transaction.description = line_86
      end
    end

    private

    def parse_structured_line_86(line_86, transaction)
      description_parts = line_86[4..-1].split('/')
      transaction.contra_account_iban = parse_description_after_tag description_parts, IBAN_R
      transaction.contra_account = iban_to_account transaction.contra_account_iban
      transaction.contra_account_owner = parse_description_after_tag description_parts, NAME_R
      transaction.description = parse_description_after_tag description_parts, REMI_R
    end

    def parse_single_value(line_86, regex)
      $1.strip if line_86.match regex
    end

    def parse_iban_bic(line_86, transaction)
      if line_86.match /IBAN\:\s(.*?)\s/
        transaction.contra_account_iban = $1.strip
        transaction.contra_account = iban_to_account transaction.contra_account_iban
      end
    end
  end
end


text:
package vc.kotori.framework.web.interceptor;

import vc.kotori.framework.util.IpUtil ;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 */
public class CtxInterceptor implements HandlerInterceptor {

	public static final String CONTEXT_NAME = "ctx";

	public static final String SCHEME_SUFFEX = "://";

	public static final String SEPARATE_SERVER_PORT = ":";

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception e) throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object args, ModelAndView modelAndView) throws Exception {
		if (modelAndView == null || modelAndView.getModel() == null) {
			return;
		}

//		modelAndView.addObject("areaName", IpUtil.getArea(request).getName());

		StringBuilder ctx = new StringBuilder();
		ctx.append(request.getScheme());
		ctx.append(SCHEME_SUFFEX);
		ctx.append(request.getServerName());
		if (request.getServerPort() != 80) {
			ctx.append(SEPARATE_SERVER_PORT);
			ctx.append(request.getServerPort());
		}
		ctx.append(request.getContextPath());

		modelAndView.getModel().put(CONTEXT_NAME, ctx.toString());

		//重定向操作特殊处理
		if (modelAndView.getViewName().startsWith("redirect:")) {
			modelAndView.getModel().clear();
		}
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		return true;
	}

}


text:
import sys

import tensorflow as tf
import numpy as np
from zoo import init_nncontext
from zoo.tfpark import KerasModel, TFDataset

def get_data_rdd(dataset, sc):
    from bigdl.dataset import mnist
    (images_data, labels_data) = mnist.read_data_sets("/tmp/mnist", dataset)
    image_rdd = sc.parallelize(images_data)
    labels_rdd = sc.parallelize(labels_data)
    rdd = image_rdd.zip(labels_rdd) \
        .map(lambda rec_tuple: ((rec_tuple[0] - mnist.TRAIN_MEAN) / mnist.TRAIN_STD,
                                np.array(rec_tuple[1])))
    return rdd

def main(max_epoch):
    sc = init_nncontext()

    training_rdd = get_data_rdd("train", sc)
    testing_rdd = get_data_rdd("test", sc)

    dataset = TFDataset.from_rdd(training_rdd,
                                 features=(tf.float32, [28, 28, 1]),
                                 labels=(tf.int32, []),
                                 batch_size=320,
                                 val_rdd=testing_rdd)

    model = tf.keras.Sequential(
        [tf.keras.layers.Flatten(input_shape=(28, 28, 1)),
         tf.keras.layers.Dense(64, activation='relu'),
         tf.keras.layers.Dense(64, activation='relu'),
         tf.keras.layers.Dense(10, activation='softmax'),
         ]
    )

    model.compile(optimizer=tf.keras.optimizers.RMSprop(),
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    keras_model = KerasModel(model)

    keras_model.fit(dataset,
                    epochs=max_epoch,
                    distributed=True)

    eval_dataset = TFDataset.from_rdd(
        testing_rdd,
        features=(tf.float32, [28, 28, 1]),
        labels=(tf.int32, []), batch_per_thread=80)
    result = keras_model.evaluate(eval_dataset)

    print(result)
    # >> [0.08865142822265625, 0.9722]

    # the following assert is used for internal testing
    assert result['acc Top1Accuracy'] > 0.95

    model.save_weights("/tmp/mnist_keras.h5")

if __name__ == '__main__':

    max_epoch = 5

    if len(sys.argv) > 1:
        max_epoch = int(sys.argv[1])
    main(max_epoch)


text:
package yamlconf

import (
	"fmt"
	"os"
	"sync"
	"time"

	"github.com/getlantern/deepcopy"
	"github.com/getlantern/golog"
)

var (
	log = golog.LoggerFor("yamlconf")
)

// Config is the interface for configuration objects that provide the in-memory
// representation of yaml configuration managed by yamlconf.
type Config interface {
	GetVersion() int

	SetVersion(version int)

	ApplyDefaults()
}

// Manager exposes a facility for managing configuration a YAML configuration
// file. After creating a Manager, one must call the Init() method to start the
// necessary background processing.  If you set a CustomPoll function, you need
// to call StartPolling() also.
//
// As the configuration is updated, the updated version of the config is made
// available via the Next() method. Configs are always copied, never updated in
// place.
//
// The config can be updated in several ways:
//
// 1. Programmatically - Clients can call the Manager's Update() method.
// 2. Updating the file on disk directly
// 3. Using the optional HTTP config server
// 4. Optionally specifying a custom polling mechanism (e.g. for fetching updates)
// from a server.
//
// When the file on disk is updated, Manager uses optimistic locking to make
// sure that manual updates to the file don't overwrite intervening programmatic
// updates. Specifically, the Config includes a Version field. Every time that
// a programmatic update is made, the Version field is incremented. If someone
// edits the file and then saves it, but there was an intervening programmatic
// update, the Version in the file will not match the Version in memory, and the
// file will be rejected and overwritten with the latest Version from memory.
//
// Programmatic updates (including ones via the HTTP config server and custom
// polling) are processed serialy. Since these operations are all defined as
// mutators that receive the current version of the config, the order of
// processing doesn't really matter.
//
// The optional HTTP config server provides an HTTP REST endpoint that allows
// making updates to portions of the config. The portion of the config is
// identified by the path. The allowed operations are POST (insert/update) and
// DELETE (delete), both of which expect a YAML fragment in their body.
//
// For example, given a config like this:
//
//   items:
//     a:
//       description: Item A
//       price: 55
//     b:
//       description: Item B
//       price: 23
//
// If applying the following sequence of calls:
//
//   POST /items/a "price: 56"
//   DELETE /items/b
//   POST /items/c "description: Item C\nprice:19"
//
// We would end up with the following configuration:
//
//   items:
//     a:
//       description: Item A
//       price: 56
//     c:
//       description: Item C
//       price: 19
//
//
type Manager struct {
	// FilePath: required, path to the config file on disk
	FilePath string

	// FilePollInterval: how frequently to poll the file for changes, defaults
	// to 1 second
	FilePollInterval time.Duration

	// EmptyConfig: required, factor for new empty Configs
	EmptyConfig func() Config

	// OneTimeSetup: optional, provides the ability to perform one-time setup
	// on the configuration at start time (for example applying command-line
	// flags)
	OneTimeSetup func(cfg Config) error

	// CustomPoll: optionally, specify a custom polling function that returns
	// a mutator for applying the result of polling, the time to wait till the
	// next poll, and an error (if polling itself failed). This is useful for
	// example for fetching config updates from a remote server.
	CustomPoll func(currentCfg Config) (mutate func(cfg Config) error, waitTime time.Duration, err error)

	once      sync.Once
	cfg       Config
	cfgMutex  sync.RWMutex
	fileInfo  os.FileInfo
	deltasCh  chan *delta
	nextCfgCh chan Config
}

type mutator func(cfg Config) error

// delta is an operation that changes to the configuration
type delta struct {
	mutate mutator
	errCh  chan error
}

// Next gets the next version of the Config, blocking until the config is
// updated.
func (m *Manager) Next() Config {
	return <-m.nextCfgCh
}

// Update updates the config by using the given mutator function.
func (m *Manager) Update(mutate func(cfg Config) error) error {
	errCh := make(chan error)
	m.deltasCh <- &delta{mutator(mutate), errCh}
	return <-errCh
}

// Init starts the Manager, returning the initial Config (i.e. what was on
// disk). If no config exists on disk, an empty config with ApplyDefaults() will
// be created and saved.
func (m *Manager) Init() (Config, error) {
	if m.EmptyConfig == nil {
		return nil, fmt.Errorf("EmptyConfig must be specified")
	}
	if m.FilePath == "" {
		return nil, fmt.Errorf("FilePath must be specified")
	}
	if m.FilePollInterval == 0 {
		m.FilePollInterval = 1 * time.Second
	}
	m.deltasCh = make(chan *delta)
	m.nextCfgCh = make(chan Config)

	err := m.loadFromDisk()
	if err != nil {
		// Problem reading config, assume that we need to save a new one
		cfg := m.EmptyConfig()
		cfg.ApplyDefaults()
		if m.OneTimeSetup != nil {
			err := m.OneTimeSetup(cfg)
			if err != nil {
				return nil, fmt.Errorf("Unable to perform one-time setup: %s", err)
			}
		}
		_, err = m.saveToDiskAndUpdate(cfg)
		if err != nil {
			return nil, err
		}
	} else {
		// Always save whatever we loaded, which will cause defaults to be
		// applied and formatting to be made consistent
		copied, err := m.copy(m.cfg)
		if m.OneTimeSetup != nil {
			err := m.OneTimeSetup(copied)
			if err != nil {
				return nil, fmt.Errorf("Unable to perform one-time setup: %s", err)
			}
		}
		if err == nil {
			_, err = m.saveToDiskAndUpdate(copied)
		}
		if err != nil {
			return nil, fmt.Errorf("Unable to perform initial update of config on disk: %s", err)
		}
	}

	go m.processUpdates()

	return m.getCfg(), nil
}

// StartPolling starts polling if there is a custom polling function defined.
func (m *Manager) StartPolling() {
	if m.CustomPoll != nil {
		go m.once.Do(func() { m.processCustomPolling() })
	}
}

func (m *Manager) processUpdates() {
	for {
		log.Trace("Waiting for next update")
		changed := false
		select {
		case delta := <-m.deltasCh:
			log.Trace("Apply delta")
			updated, err := m.copy(m.getCfg())
			err = delta.mutate(updated)
			if err != nil {
				delta.errCh <- err
				continue
			}
			changed, err = m.saveToDiskAndUpdate(updated)
			delta.errCh <- err
			if err != nil {
				continue
			}
		case <-time.After(m.FilePollInterval):
			log.Trace("Read update from disk")
			var err error
			changed, err = m.reloadFromDisk()
			if err != nil {
				log.Errorf("Unable to read updated config from disk: %s", err)
				continue
			}
		}

		if changed {
			log.Trace("Publish changed config")
			m.nextCfgCh <- m.cfg
		}
	}
}

func (m *Manager) processCustomPolling() {
	for {
		waitTime := m.poll()
		time.Sleep(waitTime)
	}
}

func (m *Manager) poll() time.Duration {
	mutate, waitTime, err := m.CustomPoll(m.getCfg())
	if err != nil {
		log.Errorf("Custom polling failed: %s", err)
	} else {
		err = m.Update(mutate)
		if err != nil {
			log.Errorf("Unable to apply update from custom polling: %s", err)
		}
	}
	return waitTime
}

func (m *Manager) setCfg(cfg Config) {
	m.cfgMutex.Lock()
	defer m.cfgMutex.Unlock()
	m.cfg = cfg
}

func (m *Manager) getCfg() Config {
	m.cfgMutex.RLock()
	defer m.cfgMutex.RUnlock()
	return m.cfg
}

func (m *Manager) copy(orig Config) (copied Config, err error) {
	copied = m.EmptyConfig()
	err = deepcopy.Copy(copied, orig)
	return
}


text:
var React = require('react');
var AltText = require('./AltText');
var Toolbar = require('./Toolbar');

var { Button, FormIconField, FormInput, ResponsiveText } = require('elemental');

var Header = React.createClass({

	displayName: 'ItemViewHeader',

	getInitialState () {
		return {
			searchIsVisible: false,
			searchIsFocused: false,
			searchString: ''
		};
	},

	componentDidUpdate (prevProps, prevState) {
		if (this.state.searchIsVisible && !prevState.searchIsVisible) {
			this.refs.searchField.getDOMNode().focus();
		}
	},

	toggleCreate (visible) {
		this.props.toggleCreate(visible);
	},

	toggleSearch (visible) {
		this.setState({
			searchIsVisible: visible,
			searchIsFocused: visible,
			searchString: ''
		});
	},

	searchFocusChanged (focused) {
		this.setState({
			searchIsFocused: focused
		});
	},

	searchStringChanged (event) {
		this.setState({
			searchString: event.target.value
		});
	},

	renderDrilldown () {
		if (this.state.searchIsVisible) return null;
		/* eslint-disable no-script-url */
		return (
			<Toolbar.Section left>
				{this.renderDrilldownItems()}
				{this.renderSearch()}
			</Toolbar.Section>
		);
		/* eslint-enable */
	},

	renderDrilldownItems () {

		var list = this.props.list;
		var items = this.props.data.drilldown ? this.props.data.drilldown.items : [];

		var els = items.map(function(dd) {

			var links = [];

			dd.items.forEach(function(el, i) {
				links.push({el.label});
				if (i < dd.items.length - 1) {
					links.push(,);//eslint-disable-line comma-spacing
				}
			});

			var more = dd.more ? ... : '';

			return (

					{links}
					{more}

			);

		});

		if (!els.length) {
			return (
				<Button type="link" href={'/keystone/' + list.path}>

					{list.plural}
				</Button>
			);
		} else {
			// add the current list
			els.push(

					{list.plural}

			);
			return
{els}
;
		}

	},

	renderSearch () {
		var list = this.props.list;
		return (
			<form action={'/keystone/' + list.path} className="EditForm__header__search">
				<FormIconField iconPosition="left" iconColor="primary" iconKey="search" className="EditForm__header__search-field">
					<FormInput
						ref="searchField"
						type="search"
						name="search"
						value={this.state.searchString}
						onChange={this.searchStringChanged}
						onFocus={this.searchFocusChanged.bind(this, true)}
						onBlur={this.searchFocusChanged.bind(this, false)}
						placeholder="Search"
						className="EditForm__header__search-input" />
				</FormIconField>
			</form>
		);
	},

	renderInfo () {
		return (
			<Toolbar.Section right>
				{this.renderCreateButton()}
			</Toolbar.Section>
		);
	},

	renderCreateButton () {
		if (this.props.list.nocreate) return null;

		var props = {};
		if (this.props.list.autocreate) {
			props.href = '?new' + Keystone.csrf.query;
		} else {
			props.onClick = this.toggleCreate.bind(this, true);
		}
		return (
			<Button type="success" {...props}>

				<ResponsiveText hiddenXS={`New ${this.props.list.singular}`} visibleXS="Create" />
			</Button>
		);
		/* eslint-enable */
	},

	render () {
		return (
			<Toolbar>
				{this.renderDrilldown()}
				{this.renderInfo()}
			</Toolbar>
		);
	}

});

module.exports = Header;


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
  ~ Copyright (c) 2016 Haulmont
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<window xmlns="http://schemas.haulmont.com/cuba/window.xsd" caption="msg://browseCaption"
        class="com.haulmont.timesheets.gui.weeklytimesheets.SimpleWeeklyTimesheets" focusComponent="weeklyTsTable"
        messagesPack="com.haulmont.timesheets.gui.weeklytimesheets">
    <dsContext>
        <groupDatasource id="weeklyEntriesDs" allowCommit="false"
                         class="com.haulmont.timesheets.entity.WeeklyReportEntry" refreshMode="NEVER"/>
        <collectionDatasource id="projectsDs" class="com.haulmont.timesheets.entity.Project" view="project-full">
            <query>
                <![CDATA[
                select pr
                from ts$Project pr,
                    in(pr.participants) p
                where
                    p.user.id = :session$userId and
                    pr.status = 'open'
                order by pr.name
                    ]]>
            </query>
        </collectionDatasource>
    </dsContext>
    <actions>
        <action id="add" icon="icons/plus-btn.png" invoke="addReport" shortcut="CTRL-ALT-PLUS"/>
        <action id="submitAll" caption="msg://submitAll" invoke="submitAll" shortcut="CTRL-ENTER"/>
    </actions>
    <layout expand="weeklyTsTable" spacing="true">
        <frame id="commandLine" screen="command-line-frame"/>

        <groupTable id="weeklyTsTable" aggregatable="true" editable="true" multiselect="true" width="100%">
            <actions>
                <action id="remove"/>
            </actions>
            <columns>
                <column id="project"/>
                <column id="task"/>
            </columns>
            <rows datasource="weeklyEntriesDs"/>
            <buttonsPanel width="100%">
                <hbox align="MIDDLE_LEFT" spacing="true">
                    <button action="add"/>
                    <button action="weeklyTsTable.remove"/>
                </hbox>
                <label id="weekCaption" align="MIDDLE_CENTER" stylename="h2"/>
                <hbox id="weekNavigationBox" align="BOTTOM_RIGHT" spacing="true">
                    <button action="submitAll"/>
                    <linkButton align="MIDDLE_RIGHT" icon="font-icon:CHEVRON_LEFT" id="showPreviousWeek"/>
                    <linkButton align="MIDDLE_RIGHT" caption="msg://today" id="setToday"/>
                    <linkButton align="MIDDLE_RIGHT" icon="font-icon:CHEVRON_RIGHT" id="showNextWeek"/>
                    <dateField id="dateField" align="MIDDLE_RIGHT" resolution="DAY" stylename="simple"/>
                </hbox>
            </buttonsPanel>
        </groupTable>
    </layout>
</window>


text:
var BaseCollection = require('../lib/base-collection');
var SearchResult = require('../models/search-result');

var qs = require('querystring');
var path = require('path');

var SearchResults = BaseCollection.extend({
    model: SearchResult,
    url: function(){
        var searchTerm = encodeURIComponent(this.searchTerm);
        return 'http://localhost:8080/api/data/2.5/find?q='+searchTerm+'&type=like&units=metric';
    },
    setSearchTerm: function(searchTerm){
        this.searchTerm = searchTerm;
    },
    parse: function(response){
        if (response.cod !== '200') {
            return;
        }
        return response.list;
    }
});

module.exports = SearchResults;


text:
package harvester

import (
	"fmt"
	"strconv"
	"time"

	"github.com/mcuadros/harvester/src/intf"

	. "gopkg.in/check.v1"
)

type WriterSuite struct{}

var _ = Suite(&WriterSuite{})

func (s *WriterSuite) TestWriteFromChannelSingleOutput(c *C) {
	output := new(MockOutput)
	output.Return = true

	outputs := []intf.Output{output}
	outputsFactory := func() []intf.Output {
		return outputs
	}

	writer := NewWriter()
	writer.SetOutputsFactory(outputsFactory)
	writer.SetThreads(1)
	writer.Setup()
	writer.Boot()

	recordChan, closeChan := writer.GetChannels()
	go func() {
		for i := 0; i < 10; i++ {
			recordChan <- intf.Record{"foo": fmt.Sprintf("%d", i)}
		}

		close(recordChan)
		close(closeChan)
	}()

	for {
		time.Sleep(100 * time.Microsecond)
		if !writer.IsAlive() {
			break
		}
	}

	created, failed, _, _ := writer.GetCounters()
	c.Assert(created, Equals, int32(10))
	c.Assert(failed, Equals, int32(0))
	c.Assert(output.Count, Equals, 45)

}

func (s *WriterSuite) TestWriteFromChannelMultipleOutput(c *C) {
	outputw := new(MockOutput)
	outputw.Return = true
	outputf := new(MockOutput)
	outputf.Return = false

	outputs := []intf.Output{outputw, outputf}
	outputsFactory := func() []intf.Output {
		return outputs
	}

	writer := NewWriter()
	writer.SetOutputsFactory(outputsFactory)
	writer.SetThreads(1)
	writer.Setup()
	writer.Boot()

	recordChan, closeChan := writer.GetChannels()
	go func() {

		for i := 0; i < 10; i++ {
			recordChan <- intf.Record{"foo": fmt.Sprintf("%d", i)}
		}

		close(recordChan)
		close(closeChan)
	}()

	for {
		time.Sleep(100 * time.Microsecond)
		if !writer.IsAlive() {
			break
		}
	}

	created, failed, _, _ := writer.GetCounters()
	c.Assert(created, Equals, int32(10))
	c.Assert(failed, Equals, int32(10))
	c.Assert(outputw.Count, Equals, 45)
	c.Assert(outputf.Count, Equals, 45)

}

func (s *WriterSuite) TestWriteIsAlive(c *C) {
	outputw := new(MockOutput)
	outputw.Return = true
	outputf := new(MockOutput)
	outputf.Return = false

	outputs := []intf.Output{outputw, outputf}
	outputsFactory := func() []intf.Output {
		return outputs
	}

	writer := NewWriter()
	writer.SetOutputsFactory(outputsFactory)
	writer.SetThreads(1)
	writer.Setup()
	writer.Boot()

	channel, _ := writer.GetChannels()

	c.Assert(writer.IsAlive(), Equals, true)

	time.Sleep(100 * time.Microsecond)
	c.Assert(writer.IsAlive(), Equals, true)
	close(channel)

	time.Sleep(100 * time.Microsecond)
	c.Assert(writer.IsAlive(), Equals, false)
}

type MockOutput struct {
	Count  int
	Return bool
}

func (self *MockOutput) PutRecord(record intf.Record) bool {
	number, _ := strconv.Atoi(record["foo"].(string))
	self.Count += number
	return self.Return
}


text:
"""

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

"""

# Definition for a  binary tree node
class TreeNode:
	def __init__(self, x):
		self.val = x
		self.left = None
		self.right = None

class Solution:
	# @param root, a tree node
	# @param sum, an integer
	# @return a boolean
	def hasPathSum(self, root, sum):
		return self.hasPathSumHelper(root, sum)

	def hasPathSumHelper(self, root, sum):
		# base case
		if root == None: return False

		if root.left == None and root.right == None and sum == root.val:
			return True

		has_left_sum = self.hasPathSumHelper(root.left, sum - root.val)
		has_right_sum = self.hasPathSumHelper(root.right, sum - root.val)

		return  has_left_sum or has_right_sum

s = Solution()
t = TreeNode(1)
t.left = TreeNode(2)
#t.right = TreeNode(3)
print s.hasPathSum(t,3)


text:
@import play.api.i18n.Messages
@import play.api.mvc.RequestHeader
@import controllers.AssetsFinder
@()(implicit request: RequestHeader, messages: Messages, assets: AssetsFinder)

@main(messages("help.title")) {

@messages("help.title")

      info @messages("help.issue")

      library_books @messages("help.document")

}


text:
package org.owasp.webgoat.plugin;

import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.html.B;
import org.apache.ecs.html.Div;
import org.apache.ecs.html.Input;
import org.apache.ecs.html.P;
import org.apache.ecs.html.TD;
import org.apache.ecs.html.TR;
import org.apache.ecs.html.Table;
import org.owasp.webgoat.lessons.Category;
import org.owasp.webgoat.lessons.LessonAdapter;
import org.owasp.webgoat.session.ECSFactory;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.util.HtmlEncoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

public class EncodingLesson extends LessonAdapter
{
    private final static String INPUT = "input";

    private final static String KEY = "key";

    // local encoders

    private static sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();

    private static sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();

    // encryption constant

    private static byte[] salt = { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00,
            (byte) 0x00, (byte) 0x00 };

    /**
     * Returns the base 64 decoding of a string.
     *
     * @param str
     *            Description of the Parameter
     * @return Description of the Return Value
     * @exception IOException
     *                Description of the Exception
     */

    public static String base64Decode(String str) throws IOException
    {

        byte[] b = decoder.decodeBuffer(str);

        return (new String(b));
    }

    /**
     * Description of the Method
     *
     * @param c
     *            Description of the Parameter
     * @return Description of the Return Value
     * @exception IOException
     *                Description of the Exception
     */

    public static String base64Decode(char[] c) throws IOException
    {

        return base64Decode(new String(c));
    }

    /**
     * Description of the Method
     *
     * @param c
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String base64Encode(char[] c)
    {

        return base64Encode(new String(c));
    }

    /**
     * Returns the base 64 encoding of a string.
     *
     * @param str
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String base64Encode(String str)
    {

        byte[] b = str.getBytes();

        return (encoder.encode(b));
    }

    /**
     * Description of the Method
     *
     * @param b
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String base64Encode(byte[] b)
    {

        return (encoder.encode(b));
    }

    /**
     * Description of the Method
     *
     * @param s
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    protected Element createContent(WebSession s)
    {

        ElementContainer ec = new ElementContainer();

        try
        {

            String userInput = s.getParser().getRawParameter(INPUT, "");

            String userKey = s.getParser().getStringParameter(KEY, "");

            Table table = new Table();

            TR tr = new TR();

            tr.addElement(new TD("Enter a string: "));

            Input input = new Input(Input.TEXT, INPUT, userInput);

            tr.addElement(new TD().addElement(input));

            table.addElement(tr);

            tr = new TR();

            tr.addElement(new TD("Enter a password (optional): "));

            Input key = new Input(Input.TEXT, KEY, userKey);

            tr.addElement(new TD().addElement(key));

            table.addElement(tr);

            tr = new TR();

            Element b = ECSFactory.makeButton("Go!");

            tr.addElement(new TD().setAlign("center").setColSpan(2).addElement(b));

            table.addElement(tr);

            ec.addElement(table);

            ec.addElement(new P());

            Table t = new Table();

            t.setWidth("100%");

            t.setBorder(0);

            t.setCellSpacing(1);

            t.setCellPadding(4);

            String description;

            t.addElement(makeTitleRow("Description", "Encoded", "Decoded"));

            description = "Base64 encoding is a simple reversable encoding used to encode bytes into ASCII characters. Useful for making bytes into a printable string, but provides no security.";

            // t.addElement( makeDescriptionRow( description ) );
            t.addElement(makeRow(description, base64Encode(userInput), base64Decode(userInput)));
            // t.addElement( makeSpacerRow() );

            description = "Entity encoding uses special sequences like & for special characters. This prevents these characters from being interpreted by most interpreters.";

            t.addElement(makeRow(description, HtmlEncoder.encode(userInput), HtmlEncoder.decode(userInput)));

            description = "Password based encryption (PBE) is strong encryption with a text password. Cannot be decrypted without the password";

            t.addElement(makeRow(description, encryptString(userInput, userKey), decryptString(userInput, userKey)));
            description = "MD5 hash is a checksum that can be used to validate a string or byte array, but cannot be reversed to find the original string or bytes. For obscure cryptographic reasons, it is better to use SHA-256 if you have a choice.";

            t.addElement(makeRow(description, hashMD5(userInput), "Cannot reverse a hash"));

            description = "SHA-256 hash is a checksum that can be used to validate a string or byte array, but cannot be reversed to find the original string or bytes.";

            t.addElement(makeRow(description, hashSHA(userInput), "N/A"));

            description = "Unicode encoding is...";

            t.addElement(makeRow(description, "Not Implemented", "Not Implemented"));

            description = "URL encoding is...";

            t.addElement(makeRow(description, urlEncode(userInput), urlDecode(userInput)));

            description = "Hex encoding simply encodes bytes into %xx format.";

            t.addElement(makeRow(description, hexEncode(userInput), hexDecode(userInput)));

            description = "Rot13 encoding is a way to make text unreadable, but is easily reversed and provides no security.";

            t.addElement(makeRow(description, rot13(userInput), rot13(userInput)));

            description = "XOR with password encoding is a weak encryption scheme that mixes a password into data.";

            t.addElement(makeRow(description, xorEncode(userInput, userKey), xorDecode(userInput, userKey)));

            description = "Double unicode encoding is...";

            t.addElement(makeRow(description, "Not Implemented", "Not Implemented"));

            description = "Double URL encoding is...";

            t.addElement(makeRow(description, urlEncode(urlEncode(userInput)), urlDecode(urlDecode(userInput))));

            ec.addElement(t);

        }

        catch (Exception e)
        {

            s.setMessage("Error generating " + this.getClass().getName());

            e.printStackTrace();

        }

        if (getLessonTracker(s).getNumVisits() > 3)
        {
            makeSuccess(s);
        }

        return (ec);
    }

    /**
     * Convenience method for encrypting a string.
     *
     * @param str
     *            Description of the Parameter
     * @param pw
     *            Description of the Parameter
     * @return String the encrypted string.
     */

    public static synchronized String decryptString(String str, String pw)
    {

        try
        {

            PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);

            SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

            Cipher passwordDecryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");

            char[] pass = pw.toCharArray();

            SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));

            passwordDecryptCipher.init(Cipher.DECRYPT_MODE, k, ps);

            byte[] dec = decoder.decodeBuffer(str);

            byte[] utf8 = passwordDecryptCipher.doFinal(dec);

            return new String(utf8, "UTF-8");
        }

        catch (Exception e)
        {

            return ("This is not an encrypted string");
        }

    }

    /**
     * Convenience method for encrypting a string.
     *
     * @param str
     *            Description of the Parameter
     * @param pw
     *            Description of the Parameter
     * @return String the encrypted string.
     * @exception SecurityException
     *                Description of the Exception
     */

    public static synchronized String encryptString(String str, String pw) throws SecurityException
    {

        try
        {

            PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt, 20);

            SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithMD5AndDES");

            Cipher passwordEncryptCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");

            char[] pass = pw.toCharArray();

            SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(pass));

            passwordEncryptCipher.init(Cipher.ENCRYPT_MODE, k, ps);

            byte[] utf8 = str.getBytes("UTF-8");

            byte[] enc = passwordEncryptCipher.doFinal(utf8);

            return encoder.encode(enc);
        }

        catch (Exception e)
        {

            return ("Encryption error");
        }

    }

    /**
     * Gets the category attribute of the Encoding object
     *
     * @return The category value
     */

    protected Category getDefaultCategory()
    {
        return Category.INSECURE_STORAGE;
    }

    /**
     * Gets the hints attribute of the HelloScreen object
     *
     * @return The hints value
     */

    public List<String> getHints(WebSession s)
    {

        List<String> hints = new ArrayList<String>();
        hints.add("Enter a string and press 'go'");
        hints.add("Enter 'abc' and notice the rot13 encoding is 'nop' ( increase each letter by 13 characters ).");
        hints.add("Enter 'a c' and notice the url encoding is 'a+c' ( ' ' is converted to '+' ).");
        return hints;
    }

    /**
     * Gets the instructions attribute of the Encoding object
     *
     * @return The instructions value
     */

    public String getInstructions(WebSession s)
    {
        return "This lesson will familiarize the user with different encoding schemes.  ";
    }

    private final static Integer DEFAULT_RANKING = new Integer(15);

    protected Integer getDefaultRanking()
    {
        return DEFAULT_RANKING;
    }

    /**
     * Gets the title attribute of the HelloScreen object
     *
     * @return The title value
     */

    public String getTitle()
    {
        return ("Encoding Basics");
    }

    /**
     * Returns the MD5 hash of a String.
     *
     * @param str
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String hashMD5(String str)
    {

        byte[] b = str.getBytes();
        MessageDigest md = null;

        try
        {
            md = MessageDigest.getInstance("MD5");
            md.update(b);
        } catch (NoSuchAlgorithmException e)
        {
            // it's got to be there
            e.printStackTrace();
        }
        return (base64Encode(md.digest()));
    }

    /**
     * Returns the SHA hash of a String.
     *
     * @param str
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String hashSHA(String str)
    {
        byte[] b = str.getBytes();
        MessageDigest md = null;
        try
        {
            md = MessageDigest.getInstance("SHA-256");
            md.update(b);
        } catch (NoSuchAlgorithmException e)
        {
            // it's got to be there
            e.printStackTrace();
        }
        return (base64Encode(md.digest()));
    }

    /**
     * Description of the Method
     *
     * @param hexString
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String hexDecode(String hexString)
    {
        try
        {
            if ((hexString.length() % 3) != 0) { return ("String not comprised of Hex digit pairs."); }
            char[] chars = new char[hexString.length()];
            char[] convChars = new char[hexString.length() / 3];
            hexString.getChars(0, hexString.length(), chars, 0);
            for (int i = 1; i < hexString.length(); i += 3)
            {
                String hexToken = new String(chars, i, 2);
                convChars[i / 3] = (char) Integer.parseInt(hexToken, 16);
            }
            return new String(convChars);
        } catch (NumberFormatException nfe)
        {
            return ("String not comprised of Hex digits");
        }
    }

    /**
     * Description of the Method
     *
     * @param asciiString
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String hexEncode(String asciiString)
    {
        char[] ascii = new char[asciiString.length()];
        asciiString.getChars(0, asciiString.length(), ascii, 0);
        StringBuffer hexBuff = new StringBuffer();
        for (int i = 0; i < asciiString.length(); i++)
        {
            hexBuff.append("%");
            hexBuff.append(Integer.toHexString(ascii[i]));
        }
        return hexBuff.toString().toUpperCase();
    }

    /**
     * The main program for the Encoding class
     *
     * @param args
     *            The command line arguments
     */

    public static void main(String[] args)
    {
        try
        {
            String userInput = args[0];
            String userKey = args[1];
            System.out.println("Working with: " + userInput);
            System.out.print("Base64 encoding: ");
            System.out.println(base64Encode(userInput) + " : " + base64Decode(userInput));
            System.out.print("Entity encoding: ");
            System.out.println(HtmlEncoder.encode(userInput) + " : " + HtmlEncoder.decode(userInput));
            System.out.print("Password based encryption (PBE): ");
            System.out.println(encryptString(userInput, userKey) + " : " + decryptString(userInput, userKey));
            System.out.print("MD5 hash: ");
            System.out.println(hashMD5(userInput) + " : " + "Cannot reverse a hash");
            System.out.print("SHA-256 hash: ");
            System.out.println(hashSHA(userInput) + " : " + "Cannot reverse a hash");
            System.out.print("Unicode encoding: ");
            System.out.println("Not Implemented" + " : " + "Not Implemented");
            System.out.print("URL encoding: ");
            System.out.println(urlEncode(userInput) + " : " + urlDecode(userInput));
            System.out.print("Hex encoding: ");
            System.out.println(hexEncode(userInput) + " : " + hexDecode(userInput));
            System.out.print("Rot13 encoding: ");
            System.out.println(rot13(userInput) + " : " + rot13(userInput));
            System.out.print("XOR with password: ");
            System.out.println(xorEncode(userInput, userKey) + " : " + xorDecode(userInput, userKey));
            System.out.print("Double unicode encoding is...");
            System.out.println("Not Implemented" + " : " + "Not Implemented");
            System.out.print("Double URL encoding: ");
            System.out.println(urlEncode(urlEncode(userInput)) + " : " + urlDecode(urlDecode(userInput)));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Description of the Method
     *
     * @param value1
     *            Description of the Parameter
     * @param value2
     *            Description of the Parameter
     * @param description
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    private TR makeRow(String description, String value1, String value2)
    {

        TD desc = new TD().addElement(description).setBgColor("#bbbbbb");
        TD val1 = new TD()
                .addElement(new Div().addElement(value1).setStyle("overflow:auto; height:60px; width:100px;"))
                .setBgColor("#dddddd");
        TD val2 = new TD()
                .addElement(new Div().addElement(value2).setStyle("overflow:auto; height:60px; width:100px;"))
                .setBgColor("#dddddd");
        TR tr = new TR();

        tr.addElement(desc);
        tr.addElement(val1);
        tr.addElement(val2);

        return tr;
    }

    /**
     * Description of the Method
     *
     * @param value1
     *            Description of the Parameter
     * @param value2
     *            Description of the Parameter
     * @param description
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    private TR makeTitleRow(String description, String value1, String value2)
    {
        TD desc = new TD().addElement(new B().addElement(description));
        TD val1 = new TD().addElement(new B().addElement(value1));
        TD val2 = new TD().addElement(new B().addElement(value2));
        desc.setAlign("center");
        val1.setAlign("center");
        val2.setAlign("center");
        TR tr = new TR();
        tr.addElement(desc);
        tr.addElement(val1);
        tr.addElement(val2);
        return (tr);
    }

    /**
     * Description of the Method
     *
     * @param input
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static synchronized String rot13(String input)
    {
        StringBuffer output = new StringBuffer();
        if (input != null)
        {
            for (int i = 0; i < input.length(); i++)
            {
                char inChar = input.charAt(i);
                if ((inChar >= 'A') & (inChar <= 'Z'))
                {
                    inChar += 13;
                    if (inChar > 'Z')
                    {
                        inChar -= 26;
                    }
                }
                if ((inChar >= 'a') & (inChar <= 'z'))
                {
                    inChar += 13;
                    if (inChar > 'z')
                    {
                        inChar -= 26;
                    }
                }
                output.append(inChar);
            }
        }
        return output.toString();
    }

    /**
     * Description of the Method
     *
     * @param str
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String unicodeDecode(String str)
    {
        // FIXME: TOTALLY EXPERIMENTAL

        try
        {
            ByteBuffer bbuf = ByteBuffer.allocate(str.length());
            bbuf.put(str.getBytes());
            Charset charset = Charset.forName("ISO-8859-1");
            CharsetDecoder decoder = charset.newDecoder();
            CharBuffer cbuf = decoder.decode(bbuf);
            return (cbuf.toString());
        } catch (Exception e)
        {
            return ("Encoding problem");
        }
    }

    /**
     * Description of the Method
     *
     * @param str
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String unicodeEncode(String str)
    {
        // FIXME: TOTALLY EXPERIMENTAL
        try
        {
            Charset charset = Charset.forName("ISO-8859-1");
            CharsetEncoder encoder = charset.newEncoder();
            ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(str));
            return (new String(bbuf.array()));
        } catch (Exception e)
        {
            return ("Encoding problem");
        }
    }

    /**
     * Description of the Method
     *
     * @param str
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String urlDecode(String str)
    {
        try
        {
            return (URLDecoder.decode(str, "UTF-8"));
        } catch (Exception e)
        {
            return ("Decoding error");
        }
    }

    /**
     * Description of the Method
     *
     * @param str
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static String urlEncode(String str)
    {
        try
        {
            return (URLEncoder.encode(str, "UTF-8"));
        } catch (Exception e)
        {
            return ("Encoding error");
        }
    }

    /**
     * Description of the Method
     *
     * @param input
     *            Description of the Parameter
     * @param userKey
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static synchronized char[] xor(String input, String userKey)
    {
        if ((userKey == null) || (userKey.trim().length() == 0))
        {
            userKey = "Goober";
        }
        char[] xorChars = userKey.toCharArray();
        int keyLen = xorChars.length;
        char[] inputChars = null;
        char[] outputChars = null;
        if (input != null)
        {
            inputChars = input.toCharArray();
            outputChars = new char[inputChars.length];
            for (int i = 0; i < inputChars.length; i++)
            {
                outputChars[i] = (char) (inputChars[i] ^ xorChars[i % keyLen]);
            }
        }
        return outputChars;
    }

    /**
     * Description of the Method
     *
     * @param input
     *            Description of the Parameter
     * @param userKey
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static synchronized String xorDecode(String input, String userKey)
    {
        try
        {
            String decoded = base64Decode(input);
            return new String(xor(decoded, userKey));
        } catch (Exception e)
        {
            return "String not XOR encoded.";
        }
    }

    /**
     * Description of the Method
     *
     * @param input
     *            Description of the Parameter
     * @param userKey
     *            Description of the Parameter
     * @return Description of the Return Value
     */

    public static synchronized String xorEncode(String input, String userKey)
    {
        return base64Encode(xor(input, userKey));
    }

}


text:
import React from 'react';
import firebase from 'firebase';
import FirebaseAuth from 'react-firebaseui/dist/FirebaseAuth';
import auth from 'services/auth';

const uiConfig = {
  signInFlow: 'popup',
  signInOptions: [
    // add more auth providers here!
    firebase.auth.GoogleAuthProvider.PROVIDER_ID,
  ],
};

class RequiresAuthentication extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      authenticated: false,
      initialized: false,
    };
  }

  removeAuthStateChangeObserver = null;

  componentDidMount = () => {
    if (auth.isEnabled) {
      const remove = auth.firebaseApp.auth().onAuthStateChanged(user => {
        this.setState({ authenticated: !!user, initialized: true });
      });

      this.removeAuthStateChangeObserver = remove;
    }
  };

  componentWillUnmount = () => {
    if (this.removeAuthStateChangeObserver) {
      this.removeAuthStateChangeObserver();
    }
  };

  render = () => {
    if (!auth.isEnabled) {
      return this.props.children;
    }

    if (!this.state.initialized) {
      return null;
    }

    return this.state.authenticated
      ? this.props.children
      : <FirebaseAuth uiConfig={uiConfig} firebaseAuth={auth.firebaseApp.auth()} />;
  };
}

export default RequiresAuthentication;


text:
package de.tudresden.inf.lat.wikihtml.renderer.part;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import de.tudresden.inf.lat.wikihtml.renderer.common.ConversionToken;
import de.tudresden.inf.lat.wikihtml.renderer.common.WikiLinePartToken;

/**
 *
 * @author Julian Mendez
 *
 */
public class DateVariableRendererTest {

	public static final Date date20041103195347 = new Date(((long) 1) * 0x100 * 0x10000 * 0x10000);

	public DateVariableRendererTest() {
	}

	@Test
	public void testCurrentDay() {
		tryItem("{{CURRENTDAY}}", "3");
	}

	@Test
	public void testCurrentDay2() {
		tryItem("{{CURRENTDAY2}}", "03");
	}

	@Test
	public void testCurrentDayName() {
		tryItem("{{CURRENTDAYNAME}}", "Wednesday");
	}

	@Test
	public void testCurrentDayOfWeek() {
		tryItem("{{CURRENTDOW}}", "3");
	}

	@Test
	public void testCurrentHour() {
		tryItem("{{CURRENTHOUR}}", "19");
	}

	@Test
	public void testCurrentMonth() {
		tryItem("{{CURRENTMONTH}}", "11");
	}

	@Test
	public void testCurrentMonthAbbrev() {
		tryItem("{{CURRENTMONTHABBREV}}", "Nov");
	}

	@Test
	public void testCurrentMonthName() {
		tryItem("{{CURRENTMONTHNAME}}", "November");
	}

	@Test
	public void testCurrentTime() {
		tryItem("{{CURRENTTIME}}", "19:53");
	}

	@Test
	public void testCurrentTimeStamp() {
		tryItem("{{CURRENTTIMESTAMP}}", "20041103195347");
	}

	@Test
	public void testCurrentWeek() {
		tryItem("{{CURRENTWEEK}}", "45");
	}

	@Test
	public void testCurrentYear() {
		tryItem("{{CURRENTYEAR}}", "2004");
	}

	private void tryItem(String variableName, String expectedResult) {
		DateVariableRenderer renderer = new DateVariableRenderer();
		String prefix = "some text here ";
		String suffix = " and some text here";
		ConversionToken token = new WikiLinePartToken(prefix + variableName + suffix);
		List<ConversionToken> expected = new ArrayList<>();
		expected.add(new WikiLinePartToken(prefix + expectedResult + suffix));
		List<ConversionToken> output = renderer.render(token, date20041103195347);
		Assertions.assertEquals(expected, output);
	}

}


text:
package com.bq.models;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.text.TextUtils;

/**
 * 好友分组列表。
 *
 * @author SINA
 * @since 2013-11-27
 */
public class GroupList {
    /** 分组列表 **/
    public ArrayList<Group> groupList;
    /** 分组数目 **/
    public int total_number;

    public static GroupList parse(String jsonString) {
        if (TextUtils.isEmpty(jsonString)) {
            return null;
        }

        GroupList groupList = new GroupList();
        try {
            JSONObject jsonObject  = new JSONObject(jsonString);
            groupList.total_number = jsonObject.optInt("total_number");

            JSONArray jsonArray = jsonObject.optJSONArray("lists");
            if (jsonArray != null && jsonArray.length() > 0) {
                int length = jsonArray.length();
                groupList.groupList = new ArrayList<Group>(length);
                for (int ix = 0; ix < length; ix++) {
                    groupList.groupList.add(Group.parse(jsonArray.optJSONObject(ix)));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return groupList;
    }
}


text:
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F1xx_IT_H
#define __STM32F1xx_IT_H

#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* Exported macro ------------------------------------------------------------*/
/* Exported functions ------------------------------------------------------- */

void SysTick_Handler(void);
void USB_LP_CAN1_RX0_IRQHandler(void);
void EXTI9_5_IRQHandler(void);
void TIM4_IRQHandler(void);
void I2C1_EV_IRQHandler(void);
void I2C1_ER_IRQHandler(void);
void USART2_IRQHandler(void);
void SDIO_IRQHandler(void);

#ifdef __cplusplus
}
#endif

#endif /* __STM32F1xx_IT_H */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
module Distribution.Solver.Types.PackageFixedDeps
    ( PackageFixedDeps(..)
    ) where

import           Distribution.InstalledPackageInfo ( InstalledPackageInfo )
import           Distribution.Package
                   ( Package(..), UnitId(..), pkgName, installedDepends)
import           Distribution.Solver.Types.ComponentDeps ( ComponentDeps )
import qualified Distribution.Solver.Types.ComponentDeps as CD
import           Distribution.Text (display)

-- | Subclass of packages that have specific versioned dependencies.
--
-- So for example a not-yet-configured package has dependencies on version
-- ranges, not specific versions. A configured or an already installed package
-- depends on exact versions. Some operations or data structures (like
--  dependency graphs) only make sense on this subclass of package types.
--
class Package pkg => PackageFixedDeps pkg where
  depends :: pkg -> ComponentDeps [UnitId]

instance PackageFixedDeps InstalledPackageInfo where
  depends pkg = CD.fromInstalled (display (pkgName (packageId pkg)))
                                 (installedDepends pkg)


text:
#include "FGlib.h"

FG_vector<float>::ptr compute_transitivity(FG_graph::ptr fg) {
	BOOST_LOG_TRIVIAL(info) << "Transitivity starts";
	struct timeval start, end;
	gettimeofday(&start, NULL);

	FG_vector<vsize_t>::ptr deg_v = get_degree(fg, BOTH_EDGES);
	FG_vector<size_t>::ptr ss_v = compute_local_scan(fg);
	FG_vector<float>::ptr trans_v = FG_vector<float>::create(deg_v->get_size());

#pragma omp parallel for
	for (vsize_t i = 0; i < deg_v->get_size(); i++) {
		size_t curr_deg = deg_v->get(i);
		curr_deg > 0 ? trans_v->set(i, (ss_v->get(i)/(float)((curr_deg+1) * (curr_deg)))):
					   trans_v->set(i, 0);
	}

	gettimeofday(&end, NULL);
	BOOST_LOG_TRIVIAL(info)
		<< boost::format("Transitivity takes %1% seconds") % time_diff(start, end);
	return trans_v;
}


text:
jsVideoUrlParser [![Build Status](https://travis-ci.org/Zod-/jsVideoUrlParser.svg)](https://travis-ci.org/Zod-/jsVideoUrlParser) [![Gitter](https://badges.gitter.im/Zod-/jsVideoUrlParser.svg)](https://gitter.im/Zod-/jsVideoUrlParser?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
================

A javascript parser to extract informations like provider, id, channel, start time from media urls.

# Supported providers
 - [YouTube](https://www.youtube.com/)
 - [Vimeo](https://vimeo.com/)
 - [Twitch](https://www.twitch.tv/)
 - [Dailymotion](https://www.dailymotion.com)
 - [Canal+](https://www.mycanal.fr/)
 - [Youku](https://www.youku.com/)
 - [Coub](https://coub.com/)
 - [Wistia](https://wistia.com/)
 - [SoundCloud](https://soundcloud.com/)
 - [TeacherTube](https://www.teachertube.com)

# Building Locally
```
npm install
npm run lint
npm run test
npm run build
```

# npm
```
npm install js-video-url-parser
```

# bower
```shell
bower install js-video-url-parser
```

# Usage
## ES2015+ / Webpack
```
// All plugins
import urlParser from "js-video-url-parser";

// Choose individual plugins
import urlParser from "js-video-url-parser/lib/base";
import "js-video-url-parser/lib/provider/canalplus";
import "js-video-url-parser/lib/provider/coub";
import "js-video-url-parser/lib/provider/dailymotion";
import "js-video-url-parser/lib/provider/twitch";
import "js-video-url-parser/lib/provider/vimeo";
import "js-video-url-parser/lib/provider/wistia";
import "js-video-url-parser/lib/provider/youku";
import "js-video-url-parser/lib/provider/youtube";
import "js-video-url-parser/lib/provider/teachertube";

```
## Parsing

Parsing a url will return a videoInfo object with all the information

```javascript
> urlParser.parse('http://www.youtube.com/watch?v=HRb7B9fPhfA')
{
  mediaType: 'video',
  id: 'HRb7B9fPhfA',
  provider: 'youtube'
}

> urlParser.parse('https://vimeo.com/97276391')
{
  mediaType: 'video',
  id: '97276391',
  provider: 'vimeo'
}
```

Any url parameters expect for ids will be saved in the params object. Some
providers have special parameters for example the start parameter which dictates
at how many seconds the video starts. Special parameters can be found in the
different descriptions for the providers.
```javascript
> urlParser.parse('https://www.youtube.com/watch?v=6xLcSTDeB7A&index=25&list=PL46F0A159EC02DF82&t=1m40')
{
  provider: 'youtube',
  id: 'yQaAGmHNn9s',
  list: 'PL46F0A159EC02DF82',
  mediaType: 'video',
  params: {
    start: 100,
    index: '25'
  }
}
```

Parsing an incorrect url or trying to create one with an invalid object will return undefined
```javascript
> urlParser.parse('https://www.youuutube.com/watch?v=97276391')
> urlParser.create({ videoInfo: { provider: 'youtube' })
undefined
```

## Url Creation

The videoInfo objects can be turned back into urls with the `.create` function.
The required parameter for this is the videoInfo object itself. Optional ones are
the format of the url and the url parameters that should be added. Each provider
has it's own default format.

```javascript
> urlParser.create({
    videoInfo: {
      provider: 'youtube',
      id: 'HRb7B9fPhfA',
      mediaType: 'video'
    },
    format: 'long',
    params: {
      foo: 'bar'
    }
  })
'https://www.youtube.com/watch?foo=bar&v=HRb7B9fPhfA'
```
Parsing and creating can also be chained together to clean up an url for example.
If you still want to reuse the generated parameters object you can use the keyword
`'internal'` as params.

```javascript
> urlParser.create({
  videoInfo: urlParser.parse('https://youtube.com/watch?foo=bar&v=HRb7B9fPhfA')
})
'https://www.youtube.com/watch?v=HRb7B9fPhfA'

> urlParser.create({
  videoInfo: urlParser.parse('https://youtube.com/watch?foo=bar&v=HRb7B9fPhfA'),
  params: 'internal'
})
'https://www.youtube.com/watch?foo=bar&v=HRb7B9fPhfA'
```

## Adding a provider

Add a new file in the `lib/provider/` directory with the template found [here](lib/provider/template.js) and also add it to [index.js](lib/index.js).
<br>
Add some tests in `lib/provider/` with the template found
[here](lib/provider/template.test.js).

Run `npm run test` to create the parser and test your plugin.

## Provider information and examples
 - [YouTube](https://github.com/Zod-/jsVideoUrlParser/wiki/YouTube)
 - [Vimeo](https://github.com/Zod-/jsVideoUrlParser/wiki/Vimeo)
 - [Twitch](https://github.com/Zod-/jsVideoUrlParser/wiki/Twitch)
 - [Dailymotion](https://github.com/Zod-/jsVideoUrlParser/wiki/Dailymotion)
 - [Canal+](https://github.com/Zod-/jsVideoUrlParser/wiki/Canal-)
 - [Youku](https://github.com/Zod-/jsVideoUrlParser/wiki/Youku)
 - [Coub](https://github.com/Zod-/jsVideoUrlParser/wiki/Coub)
 - [Wistia](https://github.com/Zod-/jsVideoUrlParser/wiki/Wistia)
 - [SoundCloud](https://github.com/Zod-/jsVideoUrlParser/wiki/SoundCloud)
 - [TeacherTube](https://github.com/Zod-/jsVideoUrlParser/wiki/TeacherTube)

# License

[MIT](https://github.com/Zod-/jsVideoUrlParser/blob/master/LICENSE)


text:
require 'dfp_api'

def delete_custom_targeting_values(dfp, custom_targeting_key_id)
  # Get the CustomTargetingService.
  custom_targeting_service = dfp.service(:CustomTargetingService, API_VERSION)

  # Define initial values.
  custom_target_value_ids = []

  # Create statement to only select custom values by the given custom targeting
  # key ID.
  statement = dfp.new_statement_builder do |sb|
    sb.where = 'customTargetingKeyId = :key_id'
    sb.with_bind_variable('key_id', custom_targeting_key_id)
  end

  page = {:total_result_set_size => 0}
  begin
    # Get custom targeting values by statement.
    page = custom_targeting_service.get_custom_targeting_values_by_statement(
        statement.to_statement()
    )

    unless page[:results].nil?
      # Increase query offset by page size.
      page[:results].each do |value|
        # Add value ID to the list for deletion.
        custom_target_value_ids << value[:id]
      end
    end

    # Increase the statement offset by the page size to get the next page.
    statement.offset += statement.limit
  end while statement.offset < page[:total_result_set_size]

  # Print a footer.
  puts 'Number of custom targeting value to be deleted: %d' %
      custom_target_value_ids.size

  if !(custom_target_value_ids.empty?)
    # Modify statement for action, note, values are still present.
    statement.configure do |sb|
      sb.where = 'customTargetingKeyId = :key_id AND id IN (%s)' %
          custom_target_value_ids.join(', ')
      sb.offset = nil
      sb.limit = nil
    end

    # Perform action.
    result = custom_targeting_service.perform_custom_targeting_value_action(
        {:xsi_type => 'DeleteCustomTargetingValues'},
        statement.to_statement()
    )

    # Display the results.
    if !result.nil? && result[:num_changes] > 0
      puts 'Number of custom targeting values deleted: %d' %
          result[:num_changes]
    else
      puts 'No custom targeting values were deleted.'
    end
  end
end

if __FILE__ == $0
  API_VERSION = :v201711

  # Get DfpApi instance and load configuration from ~/dfp_api.yml.
  dfp = DfpApi::Api.new

  # To enable logging of SOAP requests, set the log_level value to 'DEBUG' in
  # the configuration file or provide your own logger:
  # dfp.logger = Logger.new('dfp_xml.log')

  begin
    custom_targeting_key_id = 'INSERT_CUSTOM_TARGETING_KEY_ID_HERE'.to_i
    delete_custom_targeting_values(dfp, custom_targeting_key_id)

  # HTTP errors.
  rescue AdsCommon::Errors::HttpError => e
    puts "HTTP Error: %s" % e

  # API errors.
  rescue DfpApi::Errors::ApiException => e
    puts "Message: %s" % e.message
    puts 'Errors:'
    e.errors.each_with_index do |error, index|
      puts "\tError [%d]:" % (index + 1)
      error.each do |field, value|
        puts "\t\t%s: %s" % [field, value]
      end
    end
  end
end


text:
from verta._swagger.base_type import BaseType

class VersioningFolderElement(BaseType):
  def __init__(self, element_name=None, created_by_commit=None):
    required = {
      "element_name": False,
      "created_by_commit": False,
    }
    self.element_name = element_name
    self.created_by_commit = created_by_commit

    for k, v in required.items():
      if self[k] is None and v:
        raise ValueError('attribute {} is required'.format(k))

  @staticmethod
  def from_json(d):

    tmp = d.get('element_name', None)
    if tmp is not None:
      d['element_name'] = tmp
    tmp = d.get('created_by_commit', None)
    if tmp is not None:
      d['created_by_commit'] = tmp

    return VersioningFolderElement(**d)


text:
package engine.actions;

/**
 * Pauses specified background music
 * @author Will
 *
 */

public class PauseBackgroundMusic extends SoundAction {

    public PauseBackgroundMusic (String soundPath) {
        super(soundPath);
    }

    @Override
    public void execute () {
        mySoundUtility.pauseBackGroundMusic(mySoundPath);
    }

}