text:
package com.newatlanta.appengine.junit.h2;

import java.security.AccessControlException;
import java.security.Permission;

import org.h2.store.fs.FileSystem;
import org.h2.test.TestAll;
import org.h2.test.TestBase;
import org.h2.test.db.TestAlter;
import org.h2.test.db.TestAutoRecompile;
import org.h2.test.db.TestBackup;
import org.h2.test.db.TestBigDb;
import org.h2.test.db.TestBigResult;
import org.h2.test.db.TestCases;
import org.h2.test.db.TestCheckpoint;
import org.h2.test.db.TestCompatibility;
import org.h2.test.db.TestCsv;
import org.h2.test.db.TestDeadlock;
import org.h2.test.db.TestEncryptedDb;
import org.h2.test.db.TestExclusive;
import org.h2.test.db.TestFullText;
import org.h2.test.db.TestFunctionOverload;
import org.h2.test.db.TestFunctions;
import org.h2.test.db.TestIndex;
import org.h2.test.db.TestLargeBlob;
import org.h2.test.db.TestLinkedTable;
import org.h2.test.db.TestListener;
import org.h2.test.db.TestLob;
import org.h2.test.db.TestLogFile;
import org.h2.test.db.TestMemoryUsage;
import org.h2.test.db.TestMultiConn;
import org.h2.test.db.TestMultiDimension;
import org.h2.test.db.TestMultiThread;
import org.h2.test.db.TestMultiThreadedKernel;
import org.h2.test.db.TestOpenClose;
import org.h2.test.db.TestOptimizations;
import org.h2.test.db.TestOutOfMemory;
import org.h2.test.db.TestPowerOff;
import org.h2.test.db.TestReadOnly;
import org.h2.test.db.TestRights;
import org.h2.test.db.TestRunscript;
import org.h2.test.db.TestSQLInjection;
import org.h2.test.db.TestScript;
import org.h2.test.db.TestScriptSimple;
import org.h2.test.db.TestSequence;
import org.h2.test.db.TestSessionsLocks;
import org.h2.test.db.TestSpaceReuse;
import org.h2.test.db.TestSpeed;
import org.h2.test.db.TestTempTables;
import org.h2.test.db.TestTransaction;
import org.h2.test.db.TestTriggersConstraints;
import org.h2.test.db.TestTwoPhaseCommit;
import org.h2.test.db.TestView;
import org.h2.test.jaqu.AliasMapTest;
import org.h2.test.jaqu.SamplesTest;
import org.h2.test.jaqu.UpdateTest;
import org.h2.test.jdbc.TestBatchUpdates;
import org.h2.test.jdbc.TestCallableStatement;
import org.h2.test.jdbc.TestCancel;
import org.h2.test.jdbc.TestDatabaseEventListener;
import org.h2.test.jdbc.TestDriver;
import org.h2.test.jdbc.TestManyJdbcObjects;
import org.h2.test.jdbc.TestMetaData;
import org.h2.test.jdbc.TestNativeSQL;
import org.h2.test.jdbc.TestPreparedStatement;
import org.h2.test.jdbc.TestResultSet;
import org.h2.test.jdbc.TestStatement;
import org.h2.test.jdbc.TestTransactionIsolation;
import org.h2.test.jdbc.TestUpdatableResultSet;
import org.h2.test.jdbc.TestZloty;
import org.h2.test.jdbcx.TestConnectionPool;
import org.h2.test.jdbcx.TestDataSource;
import org.h2.test.jdbcx.TestXA;
import org.h2.test.jdbcx.TestXASimple;
import org.h2.test.mvcc.TestMvcc1;
import org.h2.test.mvcc.TestMvcc2;
import org.h2.test.mvcc.TestMvcc3;
import org.h2.test.mvcc.TestMvccMultiThreaded;
import org.h2.test.rowlock.TestRowLocks;
import org.h2.test.server.TestNestedLoop;
import org.h2.test.synth.TestBtreeIndex;
import org.h2.test.synth.TestFuzzOptimizations;
import org.h2.test.synth.TestMultiThreaded;
import org.h2.test.synth.TestRandomSQL;
import org.h2.test.unit.TestBitField;
import org.h2.test.unit.TestCache;
import org.h2.test.unit.TestClearReferences;
import org.h2.test.unit.TestCompress;
import org.h2.test.unit.TestDataPage;
import org.h2.test.unit.TestDate;
import org.h2.test.unit.TestDateIso8601;
import org.h2.test.unit.TestFile;
import org.h2.test.unit.TestIntArray;
import org.h2.test.unit.TestIntIntHashMap;
import org.h2.test.unit.TestMathUtils;
import org.h2.test.unit.TestOverflow;
import org.h2.test.unit.TestPattern;
import org.h2.test.unit.TestRecovery;
import org.h2.test.unit.TestScriptReader;
import org.h2.test.unit.TestSecurity;
import org.h2.test.unit.TestStringCache;
import org.h2.test.unit.TestStringUtils;
import org.h2.test.unit.TestValue;
import org.h2.test.unit.TestValueHashMap;
import org.junit.Test;

import com.newatlanta.appengine.h2.store.fs.FileSystemGae;
import com.newatlanta.appengine.junit.vfs.gae.GaeVfsTestCase;

public class GaeH2TestCase extends GaeVfsTestCase {

    private SecurityManager systemSecurityManager;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        System.setProperty( "h2.runFinalize", Boolean.FALSE.toString() );
        systemSecurityManager = System.getSecurityManager();
        System.setSecurityManager( new CustomSecurityManager( systemSecurityManager ) );
        FileSystem.register( FileSystemGae.getInstance() );
    }

    @Override
    public void tearDown() throws Exception {
        System.setSecurityManager( systemSecurityManager );
        systemSecurityManager = null;
        super.tearDown();
    }

    private void runTest( String className ) throws Exception {
        TestAll conf = new TestAll();
        conf.googleAppEngine = true;
        //conf.big = true;
        //conf.traceTest = true;
        TestBase.createCaller( className ).init( conf ).test();
    }

    // db

    @Test
    public void testScriptSimple() throws Exception {
        runTest( TestScriptSimple.class.getName() );
    }

    @Test
    public void testScript() throws Exception {
        runTest( TestScript.class.getName() );
    }

    @Test
    public void testAlter() throws Exception {
        runTest( TestAlter.class.getName() );
    }

    @Test
    public void testAutoRecompile() throws Exception {
        runTest( TestAutoRecompile.class.getName() );
    }

    @Test
    public void testBackup() throws Exception {
        runTest( TestBackup.class.getName() );
    }

    @Test
    public void testBigDb() throws Exception {
        runTest( TestBigDb.class.getName() );
    }

    @Test
    public void testBigResult() throws Exception {
        runTest( TestBigResult.class.getName() );
    }

    @Test
    public void testCases() throws Exception {
        runTest( TestCases.class.getName() );
    }

    @Test
    public void testCheckpoint() throws Exception {
        runTest( TestCheckpoint.class.getName() );
    }

    @Test
    public void testCompatibility() throws Exception {
        runTest( TestCompatibility.class.getName() );
    }

    @Test
    public void testCsv() throws Exception {
        runTest( TestCsv.class.getName() );
    }

    @Test
    public void testDeadlock() throws Exception {
        runTest( TestDeadlock.class.getName() );
    }

    @Test
    public void testExclusive() throws Exception {
        runTest( TestExclusive.class.getName() );
    }

    @Test
    public void testEncryptedDb() throws Exception {
        runTest( TestEncryptedDb.class.getName() );
    }

    @Test
    public void testFullText() throws Exception {
        runTest( TestFullText.class.getName() );
    }

    @Test
    public void testFunctionOverload() throws Exception {
        runTest( TestFunctionOverload.class.getName() );
    }

    @Test
    public void testFunctions() throws Exception {
        runTest( TestFunctions.class.getName() );
    }

    @Test
    public void testIndex() throws Exception {
        runTest( TestIndex.class.getName() );
    }

    @Test
    public void testLargeBlob() throws Exception {
        runTest( TestLargeBlob.class.getName() );
    }

    @Test
    public void testLinkedTable() throws Exception {
        runTest( TestLinkedTable.class.getName() );
    }

    @Test
    public void testListener() throws Exception {
        runTest( TestListener.class.getName() );
    }

    @Test
    public void testLob() throws Exception {
        // if the TestLob.testLobDelete() test fails, it's probably because the
        // file lastModifiedTime isn't being set properly; H2 assumes this is set
        // only when the file is opened for writing
        runTest( TestLob.class.getName() );
    }

    @Test
    public void testLogFile() throws Exception {
        runTest( TestLogFile.class.getName() );
    }

    @Test
    public void testMemoryUsage() throws Exception {
        runTest( TestMemoryUsage.class.getName() );
    }

    @Test
    public void testMultiConn() throws Exception {
        runTest( TestMultiConn.class.getName() );
    }

    @Test
    public void testMultiDimension() throws Exception {
        runTest( TestMultiDimension.class.getName() );
    }

    @Test
    public void testMultiThread() throws Exception {
        runTest( TestMultiThread.class.getName() );
    }

    @Test
    public void testMultiThreadedKernel() throws Exception {
        runTest( TestMultiThreadedKernel.class.getName() );
    }

    @Test
    public void testOpenClose() throws Exception {
        runTest( TestOpenClose.class.getName() );
    }

    @Test
    public void testOptimizations() throws Exception {
        runTest( TestOptimizations.class.getName() );
    }

    @Test
    public void testOutOfMemory() throws Exception {
        runTest( TestOutOfMemory.class.getName() );
    }

    @Test
    public void testPowerOff() throws Exception {
        runTest( TestPowerOff.class.getName() );
    }

    @Test
    public void testReadOnly() throws Exception {
        runTest( TestReadOnly.class.getName() );
    }

    @Test
    public void testRights() throws Exception {
        runTest( TestRights.class.getName() );
    }

    @Test
    public void testRunscript() throws Exception {
        runTest( TestRunscript.class.getName() );
    }

    @Test
    public void testSQLInjection() throws Exception {
        runTest( TestSQLInjection.class.getName() );
    }

    @Test
    public void testSessionsLocks() throws Exception {
        runTest( TestSessionsLocks.class.getName() );
    }

    @Test
    public void testSequence() throws Exception {
        runTest( TestSequence.class.getName() );
    }

    @Test
    public void testSpaceReuse() throws Exception {
        runTest( TestSpaceReuse.class.getName() );
    }

    @Test
    public void testSpeed() throws Exception {
        runTest( TestSpeed.class.getName() );
    }

    @Test
    public void testTempTables() throws Exception {
        runTest( TestTempTables.class.getName() );
    }

    @Test
    public void testTransaction() throws Exception {
        runTest( TestTransaction.class.getName() );
    }

    @Test
    public void testTriggersConstraints() throws Exception {
        runTest( TestTriggersConstraints.class.getName() );
    }

    @Test
    public void testTwoPhaseCommit() throws Exception {
        runTest( TestTwoPhaseCommit.class.getName() );
    }

    @Test
    public void testView() throws Exception {
        runTest( TestView.class.getName() );
    }

    // jaqu

    @Test
    public void testAliasMap() throws Exception {
        runTest( AliasMapTest.class.getName() );
    }

    @Test
    public void testSamples() throws Exception {
        runTest( SamplesTest.class.getName() );
    }

    @Test
    public void testUpdate() throws Exception {
        runTest( UpdateTest.class.getName() );
    }

    // jdbc

    @Test
    public void testBatchUpdates() throws Exception {
        runTest( TestBatchUpdates.class.getName() );
    }

    @Test
    public void testCallableStatement() throws Exception {
        runTest( TestCallableStatement.class.getName() );
    }

    @Test
    public void testCancel() throws Exception {
        runTest( TestCancel.class.getName() );
    }

    @Test
    public void testDatabaseEventListener() throws Exception {
        runTest( TestDatabaseEventListener.class.getName() );
    }

    @Test
    public void testDriver() throws Exception {
        runTest( TestDriver.class.getName() );
    }

    @Test
    public void testManyJdbcObjects() throws Exception {
        runTest( TestManyJdbcObjects.class.getName() );
    }

    @Test
    public void testMetaData() throws Exception {
        runTest( TestMetaData.class.getName() );
    }

    @Test
    public void testNativeSQL() throws Exception {
        runTest( TestNativeSQL.class.getName() );
    }

    @Test
    public void testPreparedStatement() throws Exception {
        runTest( TestPreparedStatement.class.getName() );
    }

    @Test
    public void testResultSet() throws Exception {
        runTest( TestResultSet.class.getName() );
    }

    @Test
    public void testStatement() throws Exception {
        runTest( TestStatement.class.getName() );
    }

    @Test
    public void testTransactionIsolation() throws Exception {
        runTest( TestTransactionIsolation.class.getName() );
    }

    @Test
    public void testUpdatableResultSet() throws Exception {
        runTest( TestUpdatableResultSet.class.getName() );
    }

    @Test
    public void testZloty() throws Exception {
        runTest( TestZloty.class.getName() );
    }

    // jdbcx

    @Test
    public void testConnectionPool() throws Exception {
        runTest( TestConnectionPool.class.getName() );
    }

    @Test
    public void testDataSource() throws Exception {
        runTest( TestDataSource.class.getName() );
    }

    @Test
    public void testXA() throws Exception {
        runTest( TestXA.class.getName() );
    }

    @Test
    public void testXASimple() throws Exception {
        runTest( TestXASimple.class.getName() );
    }

    // server

    @Test
    public void testNestedLoop() throws Exception {
        runTest( TestNestedLoop.class.getName() );
    }

    // mvcc & row level locking

    @Test
    public void testMvcc1() throws Exception {
        runTest( TestMvcc1.class.getName() );
    }

    @Test
    public void testMvcc2() throws Exception {
        runTest( TestMvcc2.class.getName() );
    }

    @Test
    public void testMvcc3() throws Exception {
        runTest( TestMvcc3.class.getName() );
    }

    @Test
    public void testMvccMultiThreaded() throws Exception {
        runTest( TestMvccMultiThreaded.class.getName() );
    }

    @Test
    public void testRowLocks() throws Exception {
        runTest( TestRowLocks.class.getName() );
    }

    // synth

    @Test
    public void testBtreeIndex() throws Exception {
        runTest( TestBtreeIndex.class.getName() );
    }

    @Test
    public void testFuzzOptimizations() throws Exception {
        runTest( TestFuzzOptimizations.class.getName() );
    }

    @Test
    public void testRandomSQL() throws Exception {
        runTest( TestRandomSQL.class.getName() );
    }

    @Test
    public void testMultiThreaded() throws Exception {
        runTest( TestMultiThreaded.class.getName() );
    }

    // testUnit

    @Test
    public void testBitField() throws Exception {
        runTest( TestBitField.class.getName() );
    }

    @Test
    public void testCache() throws Exception {
        runTest( TestCache.class.getName() );
    }

    @Test
    public void testClearReferences() throws Exception {
        runTest( TestClearReferences.class.getName() );
    }

    @Test
    public void testCompress() throws Exception {
        runTest( TestCompress.class.getName() );
    }

    @Test
    public void testDataPage() throws Exception {
        runTest( TestDataPage.class.getName() );
    }

    @Test
    public void testDate() throws Exception {
        runTest( TestDate.class.getName() );
    }

    @Test
    public void testDateIso8601() throws Exception {
        runTest( TestDateIso8601.class.getName() );
    }

    @Test
    public void testFile() throws Exception {
        runTest( TestFile.class.getName() );
    }

    @Test
    public void testIntArray() throws Exception {
        runTest( TestIntArray.class.getName() );
    }

    @Test
    public void testIntIntHashMap() throws Exception {
        runTest( TestIntIntHashMap.class.getName() );
    }

    @Test
    public void testMathUtils() throws Exception {
        runTest( TestMathUtils.class.getName() );
    }

    @Test
    public void testOverflow() throws Exception {
        runTest( TestOverflow.class.getName() );
    }

    @Test
    public void testPattern() throws Exception {
        runTest( TestPattern.class.getName() );
    }

    @Test
    public void testRecovery() throws Exception {
        runTest( TestRecovery.class.getName() );
    }

    @Test
    public void testScriptReader() throws Exception {
        runTest( TestScriptReader.class.getName() );
    }

    @Test
    public void testSecurity() throws Exception {
        runTest( TestSecurity.class.getName() );
    }

    @Test
    public void testStringCache() throws Exception {
        runTest( TestStringCache.class.getName() );
    }

    @Test
    public void testStringUtils() throws Exception {
        runTest( TestStringUtils.class.getName() );
    }

    @Test
    public void testValue() throws Exception {
        runTest( TestValue.class.getName() );
    }

    @Test
    public void testValueHashMap() throws Exception {
        runTest( TestValueHashMap.class.getName() );
    }

    @Test
    public void testValueMemory() throws Exception {
        runTest( TestRandomSQL.class.getName() );
    }

    /**
     * Custom security manager that prevents the H2 log writer thread
     * (WriterThread) from running.
     *
     */
    private class CustomSecurityManager extends SecurityManager {

        SecurityManager securityManager;

        private CustomSecurityManager( SecurityManager securityManager ) {
            this.securityManager = securityManager;
        }

        @Override
        public void checkPermission( Permission perm ) {
            if ( securityManager != null ) {
                securityManager.checkPermission( perm );
            }
        }

        @Override
        public void checkAccess( Thread t ) {
            if ( t.getName().startsWith( "H2 Log Writer" ) ) {
                throw new AccessControlException( "H2 Log Writer" );
            }
        }
    }
}


text:
<component name="libraryTable">
  <library name="emmet-1.0.4">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/wearprotocol/build/intermediates/exploded-aar/com.github.florent37/emmet/1.0.4/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/wearprotocol/build/intermediates/exploded-aar/com.github.florent37/emmet/1.0.4/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>

redpajama_set_name: RedPajamaGithub


text:
 0 || $select.newItem">

  <ui-select-null ng-show="$select.nullItem"></ui-select-null>

 0">


text:
#include "ProgramParameters.h"

#include <commonlib/commonlib.h>
#include <qs/api/Administrator.h>
#include <org/invenireaude/qsystem/DataFactory.h>

namespace IAS {
namespace QS {
namespace Parameters {
/*************************************************************************/
const String ProgramParameters::StrCommonArgSpec("hm:");
/*************************************************************************/
ProgramParameters::ProgramParameters() throw(){
	IAS_TRACER;
}
/*************************************************************************/
ProgramParameters::~ProgramParameters() throw(){
	IAS_TRACER;
}
/*************************************************************************/
bool ProgramParameters::checkAndShowHelp(std::ostream& os){
	IAS_TRACER;

	if(hmIndicators.size() > 0 && !hmIndicators['h'])
		return false;

	showHelp(os);

	return true;
}
/*************************************************************************/
void ProgramParameters::showHelp(std::ostream& os){
	IAS_TRACER;

	os<<"\n\t"<<getExeName()<<" ";
	printCmdDesc(os);
	os<<std::endl<<std::endl;
	os<<"Options:"<<std::endl;
	os<<"\t-h\t\t This help."<<std::endl;
	printArgsDesc(os);
	os<<std::endl;

}
/*************************************************************************/
void ProgramParameters::init(int argc, char* argv[], const String& strArgSpec){
	IAS_TRACER;
	String strAllArgSpec(StrCommonArgSpec);
	strAllArgSpec+=strArgSpec;
	::IAS::ProgramParameters::init(argc,argv,strAllArgSpec);
}
/*************************************************************************/
void ProgramParameters::printCmdDesc(std::ostream& os) const {
	IAS_TRACER;
	os<<"test1";
}
/*************************************************************************/
void ProgramParameters::printArgsDesc(std::ostream& os) const {
	IAS_TRACER;
	os<<"test2";
}
/*************************************************************************/
}
}
}


text:
<!--
@license
Copyright (c) 2016 The Jviz Project Authors. All rights reserved.
The Jviz Project is under the MIT License. See https://github.com/jviz/jviz/blob/dev/LICENSE
-->
<script>
  //Samples object
  var jviz_bio_coverviewer_samples = function()
  {
    //Samples object
    this.count = 0; //Count the number of samples
    this.names = []; //Samples names
    this.color = []; //Samples colors
    this.empty = []; //Samples empty array
    this.layer = 3; //Samples layer
    this.default = jviz.colors('navy', 3); //Samples default color

    //Samples active
    this.active = {};
    this.active.list = []; //Samples active list
    this.active.index = []; //Samples active index

    //Samples line
    this.line = {};
    this.line.opacity = 1.0; //Samples lines opacity
    this.line.width = 2; //Samples lines width
    this.line.join = 'round'; //Background lines join

    //Return this
    return this;
  };

  //Parse the samples list
  jviz_bio_coverviewer_samples.prototype.parse = function(parent, list)
  {
    //Save the names
    this.names = list.slice(0);

    //Count the number of samples
    this.count = list.length;

    //Initialize the active samples list
    this.active.list = jviz.array.create(list.length, false);

    //Initialize the active samples index
    this.active.index = [];

    //Initialize the samples empty array
    this.empty = jviz.array.zeros(list.length);

    //Initialize the colors array
    this.color = jviz.array.create(list.length, this.default);

    //Calulate the background lines opacity
    parent._background.opacity = (this.count === 0) ? 0 : 1 / this.count;

    //Build the table samples
    //this.__table_build();
  };

  //Draw the samples
  jviz_bio_coverviewer_samples.prototype.draw = function(parent)
  {
    //Check the active samples count
    if(this.active.index.length === 0){ return; }

    //Get the draw zone
    var draw = parent.$.canvas.draw();

    //Get the canvas layer
    var canvas = new jviz.canvas(parent.$.canvas.layer(this.layer));

    //Clear the layer
    canvas.clear();

    //Lines array
    var lines = [];

    //Initialize the array
    for(var j = 0; j < this.active.index.length; j++){ lines[j] = []; }

    //Real position counter
    var p = draw.margin.left;

    //Read all the positions
    for(var i = 0; i < parent._draw.width; i++)
    {
      //Get the position
      var pos = Math.floor(parent._draw.start + i / parent._zoom.value);

      //Get the cover array
      var cover = (typeof parent._coverage.values[pos] === 'undefined') ? this.empty : parent._coverage.values[pos];

      //Draw the lines
      for(var j = 0; j < this.active.index.length; j++)
      {
        //Get the index
        var index = this.active.index[j];

        //Calculate the y position
        var py = parent._height - draw.margin.bottom - cover[index];

        //Push
        lines[j].push([p, py]);
      }

      //Increment the counter
      p = p + 1;
    }

    //Draw all the lines
    for(var j = 0; j < this.active.index.length; j++)
    {
      //Get the index
      var index = this.active.index[j];

      //Draw the line
      canvas.line(lines[j]);

      //Set the line style
      canvas.stroke({ width: this.line.width, color: this.color[index] });
    }
  };

  //Clear the samples
  jviz_bio_coverviewer_samples.prototype.clear = function(parent)
  {
    //Get the canvas layer
    var canvas = new jviz.canvas(parent.$.canvas.layer(this.layer));

    //Clear the layer
    canvas.clear();
  };

  //Show a sample
  jviz_bio_coverviewer_samples.prototype.show = function(parent, index)
  {
    //Check the index value
    if(index < 0 || this.count <= index){ return jviz.console.error('Invalid sample index'); }

    //Check if sample is active now
    if(this.active.list[index] === true){ return; }

    //Activate the sample
    this.active.list[index] = true;

    //Save the sample index
    this.active.index.push(index);

    //Update the color
    this.color[index] = this.get_color(parent);

    //Draw the samples
    this.draw(parent);
  };

  //Hide a sample
  jviz_bio_coverviewer_samples.prototype.hide = function(parent, index)
  {
    //Check the index value
    if(index < 0 || this.count <= index){ return jviz.console.error('Invalid sample index'); }

    //Remove the sample from the active list
    this.active.list[index] = false;

    //Remove the index
    this.active.index = jviz.array.remove(this.active.index, index);

    //Reset the sample color
    this.color[index] = this.default;

    //Check the number of samples
    if(this.active.index.length === 0)
    {
      //Clear the samples
      this.clear(parent);
    }
    else
    {
      //Draw the samples
      this.draw(parent);
    }
  };

  //Check if a sample is active
  jviz_bio_coverviewer_samples.prototype.is_active = function(index)
  {
    //Return if sample is active
    return this.active.index.indexOf(index) !== -1;
  };

  //Get a sample color
  jviz_bio_coverviewer_samples.prototype.get_color = function(parent)
  {
    //Read all the colors
    for(var i = 0; i < parent._colors.length; i++)
    {
      //Get the color
      var color = parent._colors[i];

      //Check if color exists
      if(this.color.indexOf(color) === -1){ return color; }
    }

    //Return the first color
    return parent._colors[0];
  };
</script>


text:
package org.jboss.weld.tests.resolution;

import jakarta.enterprise.context.Dependent;
import jakarta.inject.Inject;

@Dependent
public class LookupFoo {

    @Inject
    Foo foo;

    @Inject
    @Special
    FooBase<Baz> foobaz;

    public Foo getFoo() {
        return foo;
    }

    public FooBase<Baz> getFoobaz() {
        return foobaz;
    }

}


text:
var five = require("../lib/johnny-five.js"),
  args, pins, ranges;

/**
 * This program is useful for manual servo administration.
 *
 * ex. node eg/servo-diagnostic.js [ pin list ]
 *
 *     To setup servos on pins 10 and 11:
 *
 *     node eg/servo-diagnostic.js 10 11
 *
 *     To setup servos on pins 10 and 11 with custom ranges:
 *
 *     node eg/servo-diagnostic.js 10:10:170 11
 *
 *     Note: Ranges default to 0-180
 *
 */

args = process.argv.slice(2);

pins = [];
ranges = [];

args.forEach(function(val) {
  var vals = val.split(":").map(function(v) {
    return +v;
  });

  pins.push(vals[0]);

  ranges.push(
    vals.length === 3 ?
    vals.slice(1) : [0, 180]
  );
});

(new five.Board()).on("ready", function() {
  var servos;

  // With each provided pin number, create a servo instance
  pins.forEach(function(pin, k) {
    new five.Servo({
      pin: pin,
      range: ranges[k]
    });
  }, this);

  servos = new five.Servos();

  servos.center();

  // Inject a Servo Array into the REPL as "s"
  this.repl.inject({
    s: servos
  });
});


text:
(function() {

  /**
   * @requires jsts/geom/Location.js
   * @requires jsts/util/Assert.js
   */

  var Location = jsts.geom.Location;

  /**
   * Implements the simple graph of Nodes and EdgeEnd which is all that is
   * required to determine topological relationships between Geometries. Also
   * supports building a topological graph of a single Geometry, to allow
   * verification of valid topology.
   *

   * It is not necessary to create a fully linked PlanarGraph to
   * determine relationships, since it is sufficient to know how the Geometries
   * interact locally around the nodes. In fact, this is not even feasible,
   * since it is not possible to compute exact intersection points, and hence
   * the topology around those nodes cannot be computed robustly. The only Nodes
   * that are created are for improper intersections; that is, nodes which occur
   * at existing vertices of the Geometries. Proper intersections (e.g. ones
   * which occur between the interior of line segments) have their topology
   * determined implicitly, without creating a Node object to represent them.
   *
   * @constructor
   */
  jsts.operation.relate.RelateNodeGraph = function() {
    this.nodes = new jsts.geomgraph.NodeMap(
        new jsts.operation.relate.RelateNodeFactory());
  };

  /**
   * @private
   */
  jsts.operation.relate.RelateNodeGraph.prototype.nodes = null;

  jsts.operation.relate.RelateNodeGraph.prototype.build = function(geomGraph) {
    // compute nodes for intersections between previously noded edges
    this.computeIntersectionNodes(geomGraph, 0);
    /**
     * Copy the labelling for the nodes in the parent Geometry. These override
     * any labels determined by intersections.
     */
    this.copyNodesAndLabels(geomGraph, 0);

    /**
     * Build EdgeEnds for all intersections.
     */
    var eeBuilder = new jsts.operation.relate.EdgeEndBuilder();
    var eeList = eeBuilder.computeEdgeEnds(geomGraph.getEdgeIterator());
    this.insertEdgeEnds(eeList);
  };

  /**
   * Insert nodes for all intersections on the edges of a Geometry. Label the
   * created nodes the same as the edge label if they do not already have a
   * label. This allows nodes created by either self-intersections or mutual
   * intersections to be labelled. Endpoint nodes will already be labelled from
   * when they were inserted.
   *

   * Precondition: edge intersections have been computed.
   */
  jsts.operation.relate.RelateNodeGraph.prototype.computeIntersectionNodes = function(geomGraph,
      argIndex) {
    for (var edgeIt = geomGraph.getEdgeIterator(); edgeIt.hasNext();) {
      var e = edgeIt.next();
      var eLoc = e.getLabel().getLocation(argIndex);
      for (var eiIt = e.getEdgeIntersectionList().iterator(); eiIt.hasNext();) {
        var ei = eiIt.next();
        var n = this.nodes.addNode(ei.coord);
        if (eLoc === Location.BOUNDARY)
          n.setLabelBoundary(argIndex);
        else {
          if (n.getLabel().isNull(argIndex))
            n.setLabel(argIndex, Location.INTERIOR);
        }
      }
    }
  };

  /**
   * Copy all nodes from an arg geometry into this graph. The node label in the
   * arg geometry overrides any previously computed label for that argIndex.
   * (E.g. a node may be an intersection node with a computed label of BOUNDARY,
   * but in the original arg Geometry it is actually in the interior due to the
   * Boundary Determination Rule)
   */
  jsts.operation.relate.RelateNodeGraph.prototype.copyNodesAndLabels = function(geomGraph, argIndex) {
    for (var nodeIt = geomGraph.getNodeIterator(); nodeIt.hasNext();) {
      var graphNode = nodeIt.next();
      var newNode = this.nodes.addNode(graphNode.getCoordinate());
      newNode.setLabel(argIndex, graphNode.getLabel().getLocation(argIndex));
    }
  };

  jsts.operation.relate.RelateNodeGraph.prototype.insertEdgeEnds = function(ee) {
    for (var i = ee.iterator(); i.hasNext();) {
      var e = i.next();
      this.nodes.add(e);
    }
  };

  jsts.operation.relate.RelateNodeGraph.prototype.getNodeIterator = function() {
    return this.nodes.iterator();
  };

})();


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 56(2): 271 (2004)

#### Original name
Veluticeps setosa (Berk. & M.A. Curtis) Cooke, 1880

### Remarks
null


text:
package comparison.fields;

public class Static {
    public int f;
}


text:
/**下午2:24:13
 * @author zhangyh2
 * Ornamental.java
 * TODO
 */
package com.hellen.biz.imp;

import java.util.List;

import android.text.TextUtils;

import com.google.gson.reflect.TypeToken;
import com.hellen.base.APP;
import com.hellen.base.BaseListener;
import com.hellen.base.ConsHttpUrl;
import com.hellen.bean.BaseModel;
import com.hellen.bean.BaseModelPaser;
import com.hellen.bean.Main_Flower;
import com.hellen.biz.OrnamentalFlowerInterface.OrnamentalFlowerBiz;
import com.hellen.common.HttpClient;
import com.hellen.common.LogApp;
import com.hellen.common.SharePreferHelp;
import com.hellen.common.ToastApp;
import com.hellen.flower.R;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

/**
 * @author zhangyh2 Ornamental 下午2:24:13 TODO
 */
public class Ornamental implements OrnamentalFlowerBiz {

	/*
	 * (non-Javadoc)
	 *
	 * @see com.hellen.base.BasePresenter#onStart()
	 */
	@Override
	public void onStart() {
		// TODO Auto-generated method stub

	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * com.hellen.biz.OrnamentalFlowerInterface.OrnamentalFlowerBiz#findOrnamental
	 * (com.hellen.base.BaseListener)
	 */
	@Override
	public void findOrnamental(final BaseListener<List<Main_Flower>> listener) {
		// TODO Auto-generated method stub

		if (!APP.isNetworkConnected(APP.getInstance())) {
			ToastApp.showToast(R.string.neterror);
			// 用户没有网络,查看是否有缓存。有缓存则进行加载
			String resultBanner = SharePreferHelp.getValue(ConsHttpUrl.MAIN_FLOWER,
					null);
			if (TextUtils.isEmpty(resultBanner)) {
				return;
			}
			paserSucc(listener, resultBanner);
			return;
		}
		RequestParams requestParams = new RequestParams();
		requestParams.addQueryStringParameter("group", "FXL");
		requestParams.addQueryStringParameter("page", "1");
		HttpClient.get(APP.getInstance(), ConsHttpUrl.MAIN_FLOWER,
				requestParams, new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						// TODO Auto-generated method stub
						SharePreferHelp.putValue(ConsHttpUrl.MAIN_FLOWER,
								arg0.result.toString());
						paserSucc(listener, arg0.result.toString());
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub
						listener.onFaild(0, arg1);
						String resultBanner = SharePreferHelp.getValue(
								ConsHttpUrl.MAIN_FLOWER, null);
						if (TextUtils.isEmpty(resultBanner)) {
							return;
						}
						paserSucc(listener, resultBanner);
					}
				});
	}

	/**
	 * 上午11:01:42
	 *
	 * @author zhangyh2 TODO <a>对用户数据进行解析
	 * @param listener
	 */
	private void paserSucc(BaseListener<List<Main_Flower>> listener,
			String result) {
		BaseModel<List<Main_Flower>> data = new BaseModelPaser<List<Main_Flower>>()
				.paserJsonImp(result, new TypeToken<List<Main_Flower>>() {
				});
		if (data != null && data.getCode() == 200) {
			LogApp.i(result);
			if (data.getData() != null) {
				listener.onSucces(data.getData());
			} else {
				listener.onFaild(0, "bannars is null!");
			}
		} else {
			ToastApp.showToast(data.getMsg() + "");
			listener.onFaild(1, "parser json wrong");
		}
	}
}


text:
package sqlhooks

import (
	"database/sql"
	"os"
	"testing"
	"time"

	"github.com/mattn/go-sqlite3"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func setUp(t *testing.T) func() {
	dbName := "sqlite3test.db"

	db, err := sql.Open("sqlite3", dbName)
	require.NoError(t, err)
	defer db.Close()

	_, err = db.Exec("CREATE table users(id int, name text)")
	require.NoError(t, err)

	return func() { os.Remove(dbName) }
}

func TestSQLite3(t *testing.T) {
	defer setUp(t)()
	s := newSuite(t, &sqlite3.SQLiteDriver{}, "sqlite3test.db")

	s.TestHooksExecution(t, "SELECT * FROM users WHERE id = ?", 1)
	s.TestHooksArguments(t, "SELECT * FROM users WHERE id = ? AND name = ?", int64(1), "Gus")
	s.TestHooksErrors(t, "SELECT 1+1")
	s.TestErrHookHook(t, "SELECT * FROM users WHERE id = $2", "INVALID_ARGS")

	t.Run("DBWorks", func(t *testing.T) {
		s.hooks.reset()
		if _, err := s.db.Exec("DELETE FROM users"); err != nil {
			t.Fatal(err)
		}

		stmt, err := s.db.Prepare("INSERT INTO users (id, name) VALUES(?, ?)")
		require.NoError(t, err)
		for range [5]struct{}{} {
			_, err := stmt.Exec(time.Now().UnixNano(), "gus")
			require.NoError(t, err)
		}

		var count int
		require.NoError(t,
			s.db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count),
		)
		assert.Equal(t, 5, count)
	})
}


text:
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/conf.h>

int main(int argc, char **argv)
{
    BIO *sbio = NULL, *out = NULL;
    int i, len, rv;
    char tmpbuf[1024];
    SSL_CTX *ctx = NULL;
    SSL_CONF_CTX *cctx = NULL;
    SSL *ssl = NULL;
    CONF *conf = NULL;
    STACK_OF(CONF_VALUE) *sect = NULL;
    CONF_VALUE *cnf;
    const char *connect_str = "localhost:4433";
    long errline = -1;

    ERR_load_crypto_strings();
    ERR_load_SSL_strings();
    SSL_library_init();

    conf = NCONF_new(NULL);

    if (NCONF_load(conf, "connect.cnf", &errline) <= 0) {
        if (errline <= 0)
            fprintf(stderr, "Error processing config file\n");
        else
            fprintf(stderr, "Error on line %ld\n", errline);
        goto end;
    }

    sect = NCONF_get_section(conf, "default");

    if (sect == NULL) {
        fprintf(stderr, "Error retrieving default section\n");
        goto end;
    }

    ctx = SSL_CTX_new(TLS_client_method());
    cctx = SSL_CONF_CTX_new();
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT);
    SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE);
    SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
    for (i = 0; i < sk_CONF_VALUE_num(sect); i++) {
        cnf = sk_CONF_VALUE_value(sect, i);
        rv = SSL_CONF_cmd(cctx, cnf->name, cnf->value);
        if (rv > 0)
            continue;
        if (rv != -2) {
            fprintf(stderr, "Error processing %s = %s\n",
                    cnf->name, cnf->value);
            ERR_print_errors_fp(stderr);
            goto end;
        }
        if (strcmp(cnf->name, "Connect") == 0) {
            connect_str = cnf->value;
        } else {
            fprintf(stderr, "Unknown configuration option %s\n", cnf->name);
            goto end;
        }
    }

    if (!SSL_CONF_CTX_finish(cctx)) {
        fprintf(stderr, "Finish error\n");
        ERR_print_errors_fp(stderr);
        goto err;
    }

    /*
     * We'd normally set some stuff like the verify paths and * mode here
     * because as things stand this will connect to * any server whose
     * certificate is signed by any CA.
     */

    sbio = BIO_new_ssl_connect(ctx);

    BIO_get_ssl(sbio, &ssl);

    if (!ssl) {
        fprintf(stderr, "Can't locate SSL pointer\n");
        goto end;
    }

    /* Don't want any retries */
    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);

    /* We might want to do other things with ssl here */

    BIO_set_conn_hostname(sbio, connect_str);

    out = BIO_new_fp(stdout, BIO_NOCLOSE);
    if (BIO_do_connect(sbio) <= 0) {
        fprintf(stderr, "Error connecting to server\n");
        ERR_print_errors_fp(stderr);
        goto end;
    }

    if (BIO_do_handshake(sbio) <= 0) {
        fprintf(stderr, "Error establishing SSL connection\n");
        ERR_print_errors_fp(stderr);
        goto end;
    }

    /* Could examine ssl here to get connection info */

    BIO_puts(sbio, "GET / HTTP/1.0\n\n");
    for (;;) {
        len = BIO_read(sbio, tmpbuf, 1024);
        if (len <= 0)
            break;
        BIO_write(out, tmpbuf, len);
    }
 end:
    SSL_CONF_CTX_free(cctx);
    BIO_free_all(sbio);
    BIO_free(out);
    NCONF_free(conf);
    return 0;
}


text:
namespace Rosalia.Core.Logging
{
    public class FilterLogRenderer : ILogRenderer
    {
        private readonly ILogRenderer _nestedRenderer;
        private readonly MessageLevel _level;

        public FilterLogRenderer(ILogRenderer nestedRenderer, MessageLevel level)
        {
            _nestedRenderer = nestedRenderer;
            _level = level;
        }

        public void Dispose()
        {
            _nestedRenderer.Dispose();
        }

        public void Init()
        {
            _nestedRenderer.Init();
        }

        public void Render(Message message, Identities source)
        {
            if (message.Level >= _level)
            {
                _nestedRenderer.Render(message, source);
            }
        }
    }
}


text:
<?php

namespace Mcwork\Model\Pages;

use Mcwork\Model\Cache\DeleteCache;

/**
 * Save model provides method to prepae insert and update datas
 *
 * @author Michael Jochum, michael.jochum@jochum-mediaservices.de
 */
class SaveFeedLinks extends DeleteCache
{

    /**
     * Prepare datas before save
     *
     * @see \ContentinumComponents\Mapper\Process::save()
     */
    public function save($datas, $entity = null, $stage = '', $id = null)
    {
        $groupIdent = $datas['namegroup'];
        $feedgroup = $this->fetchRow("SELECT * FROM web_content_namegroup WHERE id = {$groupIdent}");
        $date = date('Y-m-d H:i:s');
        $insert = array(
            'id' =>  $this->sequence() + 1,
            'web_pages_id' => $datas['webPages'],
            'web_medias_id' => 1,
            'linkgroup' => 1,
            'name' => $feedgroup['name'],
            'meta_rel' => 'alternate',
            'meta_type' => 'application/rss+xml',
            'meta_title' => $feedgroup['feed_title'],
            'meta_link' =>  $datas['host'] . '/feed/' . $feedgroup['feed_url'],
            'item_rang' => $this->sequence('linkgroup', 1, 'itemRang') + 1,
            'created_by' => $this->getUserIdent(),
            'update_by' => $this->getUserIdent(),
            'register_date' => $date,
            'up_date' => $date
        );
        $this->insertQuery('web_pages_headlinks', $insert);
        $this->emptyCache('contentinum_page_header');
    }
}


text:
import { logger } from '../lib/logger';
import { FederationRoomEvents, Subscriptions, Users } from '../../../models/server';
import { normalizers } from '../normalizers';
import { deleteRoom } from '../../../lib/server/functions';
import { getFederationDomain } from '../lib/getFederationDomain';
import { dispatchEvents } from '../handler';
import { checkRoomType, checkRoomDomainsLength } from '../functions/helpers';

export async function doAfterCreateRoom(room, users, subscriptions) {
	const normalizedUsers = [];

	//
	// Add user events
	//
	const addUserEvents = [];

	for (const user of users) {
		/* eslint-disable no-await-in-loop */

		const subscription = subscriptions[user._id];

		const normalizedSourceUser = normalizers.normalizeUser(user);
		const normalizedSourceSubscription = normalizers.normalizeSubscription(subscription);

		normalizedUsers.push(normalizedSourceUser);

		const addUserEvent = await FederationRoomEvents.createAddUserEvent(getFederationDomain(), room._id, normalizedSourceUser, normalizedSourceSubscription);

		addUserEvents.push(addUserEvent);

		/* eslint-enable no-await-in-loop */
	}

	//
	// Genesis
	//

	// Normalize room
	const normalizedRoom = normalizers.normalizeRoom(room, normalizedUsers);

	// Check if the number of domains is allowed
	if (!checkRoomDomainsLength(normalizedRoom.federation.domains)) {
		throw new Error('Cannot federate rooms with more than 10 domains');
	}

	// Ensure a genesis event for this room
	const genesisEvent = await FederationRoomEvents.createGenesisEvent(getFederationDomain(), normalizedRoom);

	// Dispatch the events
	dispatchEvents(normalizedRoom.federation.domains, [genesisEvent, ...addUserEvents]);
}

async function afterCreateRoom(roomOwner, room) {
	// If the room is federated, ignore
	if (room.federation) { return roomOwner; }

	// Find all subscriptions of this room
	let subscriptions = Subscriptions.findByRoomIdWhenUsernameExists(room._id).fetch();
	subscriptions = subscriptions.reduce((acc, s) => {
		acc[s.u._id] = s;

		return acc;
	}, {});

	// Get all user ids
	const userIds = Object.keys(subscriptions);

	// Load all the users
	const users = Users.findUsersWithUsernameByIds(userIds).fetch();

	// Check if there is a federated user on this room
	const hasFederatedUser = users.find((u) => u.username.indexOf('@') !== -1);

	// If there are not federated users on this room, ignore it
	if (!hasFederatedUser) { return roomOwner; }

	try {
		// If the room is not on the allowed types, ignore
		if (!checkRoomType(room)) {
			throw new Error('Channels cannot be federated');
		}

		logger.client.debug(() => `afterCreateRoom => roomOwner=${ JSON.stringify(roomOwner, null, 2) } room=${ JSON.stringify(room, null, 2) }`);

		await doAfterCreateRoom(room, users, subscriptions);
	} catch (err) {
		deleteRoom(room._id);

		logger.client.error('afterCreateRoom => Could not create federated room:', err);
	}

	return room;
}

export const definition = {
	hook: 'afterCreateRoom',
	callback: (roomOwner, room) => Promise.await(afterCreateRoom(roomOwner, room)),
	id: 'federation-after-create-room',
};


text:
catname = "Andromeda"
print len(catname)

dloc = catname.index("m")
print dloc

print catname.count("d")

print catname[0:5]

# Andromeda is a cutie!
message = "Andromeda is not a cutie!"
print message[0:13] + message[17:25]
print("%s %s") % (message[0:12], message[17:25])

print message[::-1]

# I'm so happy we have her!
newmsg = "I'm so sad we have such a bad cat"
print("%s" "happy" "%s" "her!") % (newmsg[0:7], newmsg[10:19])

print catname.upper()
print "Rachel".upper()

if message.startswith("Andromeda"):
  print newmsg

splitmsg = message.split(" ")
print " ".join(splitmsg)


text:
/* eslint max-len:0 */
'use strict';

const assert = require('chai').assert;
const { SVGPathData } = require('..');

describe('Parsing close path commands', () => {

  it('should work', () => {
    const commands = new SVGPathData('Z').commands;

    assert.equal(commands[0].type, SVGPathData.CLOSE_PATH);
  });

  it('should work with spaces before', () => {
    const commands = new SVGPathData('   Z').commands;

    assert.equal(commands[0].type, SVGPathData.CLOSE_PATH);
  });

  it('should work with spaces after', () => {
    const commands = new SVGPathData('Z    ').commands;

    assert.equal(commands[0].type, SVGPathData.CLOSE_PATH);
  });

  it('should work before a command sequence', () => {
    const commands = new SVGPathData(' Z M10,10 L10,10 H10 V10').commands;

    assert.equal(commands[0].type, SVGPathData.CLOSE_PATH);
  });

  it('should work after a command sequence', () => {
    const commands = new SVGPathData('M10,10 L10,10 H10 V10 Z').commands;

    assert.equal(commands[4].type, SVGPathData.CLOSE_PATH);
  });

  it('should work in a command sequence', () => {
    const commands = new SVGPathData('M10,10 L10,10 H10 V10 Z M10,10 L10,10 H10 V10').commands;

    assert.equal(commands[4].type, SVGPathData.CLOSE_PATH);
  });

});

describe('Encoding close path commands', () => {

  it('should work with one command', () => {
    assert.equal(
      new SVGPathData('z').encode(),
      'z'
    );
  });

  it('should work with several commands', () => {
    assert.equal(
      new SVGPathData('zzzz').encode(),
      'zzzz'
    );
  });

});


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Swagger UI</title>
    <link rel="icon" type="image/png" href="images/favicon-32x32.png" sizes="32x32"/>
    <link rel="icon" type="image/png" href="images/favicon-16x16.png" sizes="16x16"/>
    <link href='css/typography.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='css/reset.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='css/screen.css' media='screen' rel='stylesheet' type='text/css'/>
    <link href='css/reset.css' media='print' rel='stylesheet' type='text/css'/>
    <link href='css/print.css' media='print' rel='stylesheet' type='text/css'/>

        swagger
        <form id='api_selector'>

<input placeholder="http://example.com/api" id="input_baseUrl" name="baseUrl"
                                      type="text"/>

<input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/>

Explore

        </form>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>seth-client — seth-client Man Pages</title>

    <link rel="stylesheet" href="_static/guide.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="_static/seth.ico"/>

seth-client¶

A seth-client is an agent that runs locally on every node that is registered with the Seth server. When a seth-client is run, it will perform all of the steps that are required to bring the node into the expected state, including:

Registering and authenticating the node with the Seth server

Building the node object

Synchronizing cookbooks

Compiling the resource collection by loading each of the required cookbooks, including recipes, attributes, and all other dependencies

Taking the appropriate and required actions to configure the node

Looking for exceptions and notifications, handling each as required

The seth-client executable is run as a command-line tool.

Note

A client.rb file is used to specify the configuration details for the seth-client. This file is the default configuration file and is loaded every time the seth-client executable is run. The seth-client executable can be run as a daemon.

On UNIX- and Linux-based machines, the configuration file is located at: <tt class="docutils literal">/etc/seth/client.rb</tt>. On Microsoft Windows machines, the configuration file is located at <tt class="docutils literal">C:\seth\client.rb</tt>. When a client.rb file is present in this directory, the settings contained within that file will override the default configuration settings.

Options¶

This command has the following syntax:

seth-client OPTION VALUE OPTION VALUE ...

This command has the following options:

<tt class="docutils literal">-A</tt>, <tt class="docutils literal">--fatal-windows-admin-check</tt>

Use to cause a seth-client run to fail when the seth-client does not have administrator privileges in Microsoft Windows.

<tt class="docutils literal">--seth-zero-port PORT</tt>

The port on which seth-zero will listen.

<tt class="docutils literal">-F FORMAT</tt>, <tt class="docutils literal">--format FORMAT</tt>

The output format: <tt class="docutils literal">doc</tt> (default) or <tt class="docutils literal">min</tt>.

Use <tt class="docutils literal">doc</tt> to print the progress of the seth-client run using full strings that display a summary of updates as they occur.

Use <tt class="docutils literal">min</tt> to print the progress of the seth-client run using single characters. A summary of updates is printed at the end of the seth-client run. A dot (<tt class="docutils literal">.</tt>) is printed for events that do not have meaningful status information, such as loading a file or synchronizing a cookbook. For resources, a dot (<tt class="docutils literal">.</tt>) is printed when the resource is up to date, an <tt class="docutils literal">S</tt> is printed when the resource is skipped by <tt class="docutils literal">not_if</tt> or <tt class="docutils literal">only_if</tt>, and a <tt class="docutils literal">U</tt> is printed when the resource is updated.

Other formatting options are available when those formatters are configured in the client.rb file using the <tt class="docutils literal">add_formatter</tt> option.

<tt class="docutils literal">--force-formatter</tt>

Indicates that formatter output will be used instead of logger output.

<tt class="docutils literal">--force-logger</tt>

Indicates that logger output will be used instead of formatter output.

<tt class="docutils literal">-g GROUP</tt>, <tt class="docutils literal">--group GROUP</tt>

The name of the group that owns a process. This is required when starting any executable as a daemon.

<tt class="docutils literal">-h</tt>, <tt class="docutils literal">--help</tt>

Shows help for the command.

<tt class="docutils literal">-i SECONDS</tt>, <tt class="docutils literal">--interval SECONDS</tt>

The frequency (in seconds) at which the seth-client runs. Default value: <tt class="docutils literal">1800</tt>.

<tt class="docutils literal">-j PATH</tt>, <tt class="docutils literal">--json-attributes PATH</tt>

The path to a file that contains JSON data.

<tt class="docutils literal">-k KEY_FILE</tt>, <tt class="docutils literal">--client_key KEY_FILE</tt>

The location of the file which contains the client key. Default value: <tt class="docutils literal">/etc/seth/client.pem</tt>.

<tt class="docutils literal">-K KEY_FILE</tt>, <tt class="docutils literal">--validation_key KEY_FILE</tt>

The location of the file which contains the key used when a seth-client is registered with a Seth server. A validation key is signed using the <tt class="docutils literal">validation_client_name</tt> for authentication. Default value: <tt class="docutils literal">/etc/seth/validation.pem</tt>.

<tt class="docutils literal">-l LEVEL</tt>, <tt class="docutils literal">--log_level LEVEL</tt>

The level of logging that will be stored in a log file.

<tt class="docutils literal">-L LOGLOCATION</tt>, <tt class="docutils literal">--logfile c</tt>

The location in which log file output files will be saved. If this location is set to something other than <tt class="docutils literal">STDOUT</tt>, standard output logging will still be performed (otherwise there would be no output other than to a file). This is recommended when starting any executable as a daemon. Default value: <tt class="docutils literal">STDOUT</tt>.

<tt class="docutils literal">--[no-]color</tt>

Indicates whether colored output will be used. Default setting: <tt class="docutils literal">--color</tt>.

<tt class="docutils literal">-N NODE_NAME</tt>, <tt class="docutils literal">--node-name NODE_NAME</tt>

The name of the node.

<tt class="docutils literal">-o RUN_LIST_ITEM</tt>, <tt class="docutils literal">--override-runlist RUN_LIST_ITEM</tt>

Replace the current run list with the specified items.

<tt class="docutils literal">--once</tt>

Indicates that the seth-client is run once and that interval and splay options are cancelled.

<tt class="docutils literal">-P PID_FILE</tt>, <tt class="docutils literal">--pid PID_FILE</tt>

The location in which a process identification number (pid) is saved. An executable, when started as a daemon, will write the pid to the specified file. Default value: <tt class="docutils literal">/tmp/name-of-executable.pid</tt>.

<tt class="docutils literal">-R</tt>, <tt class="docutils literal">--enable-reporting</tt>

Use to enable data collection reporting during a seth-client run.

<tt class="docutils literal">-s SECONDS</tt>, <tt class="docutils literal">--splay SECONDS</tt>

A number (in seconds) to add to the <tt class="docutils literal">interval</tt> that is used to determine the frequency of seth-client runs. This number can help prevent server load when there are many clients running at the same time.

<tt class="docutils literal">-S seth_SERVER_URL</tt>, <tt class="docutils literal">--server seth_SERVER_URL</tt>

The URL for the Seth server.

<tt class="docutils literal">-u USER</tt>, <tt class="docutils literal">--user USER</tt>

The user that owns a process. This is required when starting any executable as a daemon.

<tt class="docutils literal">-v</tt>, <tt class="docutils literal">--version</tt>

The version of the seth-client.

<tt class="docutils literal">-W</tt>, <tt class="docutils literal">--why-run</tt>

Indicates that the executable will be run in why-run mode, which is a type of seth-client run that does everything except modify the system. Use why-run mode to understand why the seth-client makes the decisions that it makes and to learn more about the current and proposed state of the system.

<tt class="docutils literal">-z</tt>, <tt class="docutils literal">--local-mode</tt>

Indicates that the seth-client will be run in local mode, which allows all commands that work against the Seth server to also work against the local seth-repo.

Run with Elevated Privileges¶

The seth-client may need to be run with elevated privileges in order to get a recipe to converge correctly. On UNIX and UNIX-like operating systems this can be done by running the command as root. On Microsoft Windows this can be done by running the command prompt as an administrator.

Linux¶

On Linux, the following error sometimes occurs when the permissions used to run the seth-client are incorrect:

$ seth-client
[Tue, 29 Nov 2011 19:46:17 -0800] INFO: *** Seth 10.X.X ***
[Tue, 29 Nov 2011 19:46:18 -0800] WARN: Failed to read the private key /etc/seth/client.pem: #<Errno::EACCES: Permission denied - /etc/seth/client.pem>

This can be resolved by running the command as root. There are a few ways this can be done:

Log in as root and then run the seth-client

Use <tt class="docutils literal">su</tt> to become the root user, and then run the seth-client. For example:

$ su

and then:

$ seth-client

Use the sudo utility

$ sudo seth-client

Give a user access to read <tt class="docutils literal">/etc/seth</tt> and also the files accessed by the seth-client. This requires super user privileges and, as such, is not a recommended approach

Windows¶

On Microsoft Windows, running without elevated privileges (when they are necessary) is an issue that fails silently. It will appear that the seth-client completed its run successfully, but the changes will not have been made. When this occurs, do one of the following to run the seth-client as the administrator:

Log in to the administrator account. (This is not the same as an account in the administrator’s security group.)

Run the seth-client process from the administrator account while being logged into another account. Run the following command:

$ runas /user:Administrator "cmd /C seth-client"

This will prompt for the administrator account password.

Open a command prompt by right-clicking on the command prompt application, and then selecting Run as administrator. After the command window opens, the seth-client can be run as the administrator

Examples¶

Start a Seth run when the seth-client is running as a daemon

A seth-client that is running as a daemon can be woken up and started by sending the process a <tt class="docutils literal">SIGUSR1</tt>. For example, to trigger a seth-client run on a machine running Linux:

$ sudo killall -USR1 seth-client

Start a Seth run manually

$ ps auxw|grep seth-client

to return something like:

root           66066   0.9  0.0  2488880    264 s001  S+   10:26AM   0:03.05
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby /usr/bin/seth-client -i 3600 -s 20

and then enter:

$ sudo kill -USR1 66066


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

    var io;

    var broadcast = function(room, event, data) {
        if(io) {
            io.sockets.in(room).emit(event, data);
        }
        else {
            broadcast.lastMessage = {
                room: room,
                event: event,
                data: data
            };
        }
    };

    broadcast.setIo = function(socketIo) {
        io = socketIo;
    };

    module.exports = broadcast;

}());


text:
DIR=$( dirname "${BASH_SOURCE}" )
BASE_PATH="$DIR/.."

# Installing dependencies

echo "Starting install process ..."
cd "$BASE_PATH"

which bundle
if [ $? -eq 0 ]
then
  echo "bundler is already installed"
else
  echo "installing bundler ..."
  gem install bundler
fi

echo "Installing necessary ruby gems using bundler ..."
bundle install
echo "Installing necessary puppet modules from the forge ..."
bundle exec librarian-puppet install


text:
#ifndef SPIRE_RENDER_ARC_BALL_CAMERA_HPP
#define SPIRE_RENDER_ARC_BALL_CAMERA_HPP

#include <es-log/trace-log.h>
#include <es-acorn/Acorn.hpp>
#include <spire/scishare.h>

namespace ren {

// Mouse based arc ball camera.
void        registerSystem_ArcBallCameraMouse(spire::Acorn& core);
const char* getSystemName_ArcBallCameraMouse();

// Todo: Touch based arc ball camera.

} // namespace ren

#endif


text:
import sys

if hasattr(sys, 'real_prefix'):
    print "aber hallo"

print (".venv created. Starting.....")

from gevent.pywsgi import WSGIServer
from PyLoggi import create_app

module = create_app(1, 2)

http_server = WSGIServer(('', 5000), module)
http_server.serve_forever()


text:
/* Created by frank on 14-6-12. */
var app = require('../app')

module.exports = app.directive(
    'ffDraggable',
    function ($timeout, $parse) {
        return {
            link: function ($scope, $element, $attrs) {
                $element
                    .prop('draggable', true)
                    .on('dragstart', function () {
                        this.classList.add('drag')
                    })
                    .on('dragend', function (e) {
                        this.classList.remove('drag')
                    })
            }
        }
    }
)


text:
namespace _04.Weather
{
    using System;
    using System.Collections.Generic;
    using System.Text.RegularExpressions;
    using System.Linq;

    public class Weather
    {
        public static void Main()
        {
            Dictionary<string, Dictionary<double, string>> cities =
                new Dictionary<string, Dictionary<double, string>>();

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "end") break;
                string regex = @"(?<city>[A-Z]{2})(?<temperature>[0-9]{2}\.[0-9]*)(?<weather>([A-Z][a-z]|[a-z])[a-z]*\|)";

                foreach (Match m in Regex.Matches(input, regex))
                {
                    string cityName = m.Groups["city"].Value;
                    double temperature = double.Parse(m.Groups["temperature"].Value);
                    string weather = m.Groups["weather"].Value.Trim('|');

                    cities[cityName] = new Dictionary<double, string>();
                    cities[cityName][temperature] = weather;
                }
            }

            foreach (var city in cities.OrderBy(x => x.Value.Keys.Average()))
            {
                foreach (var temp in city.Value)
                {
                    Console.WriteLine("{0} => {1:f2} => {2}", city.Key,temp.Key, temp.Value);
                }
            }
        }
    }
}


text:
<?php
declare(strict_types=1);

namespace Cake\Database\Exception;

use Cake\Core\Exception\Exception;

/**
 * Class MissingDriverException
 */
class MissingDriverException extends Exception
{
    /**
     * @inheritDoc
     */
    protected $_messageTemplate = 'Database driver %s could not be found.';
}


text:
=begin

Copyright 2012-2013 inBloom, Inc. and its affiliates.

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.

=end

require 'yaml'

class Demographics

  def initialize(demographics = nil, choices = nil)

    defaultDemographics = File.join("#{File.dirname(__FILE__)}", '../../scenarios/defaults/demographics.yml')
    defaultChoices = File.join("#{File.dirname(__FILE__)}", '../../scenarios/defaults/choices.yml')

    @choices = YAML.load_file(defaultDemographics)
    @choices = @choices.merge!(YAML.load_file(defaultChoices))
    if demographics.nil? == false
      @choices = @choices.merge!(YAML.load_file(demographics))
    end
    if choices.nil? == false
      @choices = @choices.merge!(YAML.load_file(choices))
    end
  end

  def [](key)
    @choices[key]
  end

end


text:
@implementation FakeMPStreamAdPlacer

- (NSString *)reuseIdentifierForRenderingClassAtIndexPath:(NSIndexPath *)indexPath
{
    return @"FAKE_reuse_identifier";
}

- (void)insertItemsAtIndexPaths:(NSArray *)originalIndexPaths
{
    self.didInsertItems = YES;
}

- (NSIndexPath *)adjustedIndexPathForOriginalIndexPath:(NSIndexPath *)indexPath
{
    if (!self.didInsertItems) {
        return indexPath;
    } else {
        NSUInteger indexes[2] = {[indexPath indexAtPosition:0], [indexPath indexAtPosition:1] + 1};
        return [NSIndexPath indexPathWithIndexes:indexes length:2];
    }
}

- (NSArray *)adjustedIndexPathsForOriginalIndexPaths:(NSArray *)indexPaths
{
    if (!self.didInsertItems) {
        return indexPaths;
    }

    NSMutableArray *array = [NSMutableArray array];
    [indexPaths enumerateObjectsUsingBlock:^(NSIndexPath *indexPath, NSUInteger idx, BOOL *stop) {
        [array addObject:[self adjustedIndexPathForOriginalIndexPath:indexPath]];
    }];
    return array;
}

@end


text:
package food2fork.com.findmyrecipe.activities;

import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import food2fork.com.findmyrecipe.MaterialSearchView;
import food2fork.com.findmyrecipe.MenuItemClickListener;
import food2fork.com.findmyrecipe.OnImagesLoadedListener;
import food2fork.com.findmyrecipe.R;
import food2fork.com.findmyrecipe.Recipe;
import food2fork.com.findmyrecipe.SearchState;
import food2fork.com.findmyrecipe.SearchHistory;
import food2fork.com.findmyrecipe.SearchResult;
import food2fork.com.findmyrecipe.SearchTaskFragment;
import food2fork.com.findmyrecipe.utils.ServerUtility;
import food2fork.com.findmyrecipe.utils.Utility;
import food2fork.com.findmyrecipe.adapters.RecipeListAdapter;

/**
 * @author Alexei Ivanov
 */
public class SearchActivity extends BaseActivity implements SearchTaskFragment.TaskCallbacks {

    private static final int MAX_COUNT = 30;
    private static final int HIDE_KEYBOARD_DELAY = 500;
    private static final String SEARCH_FRAGMENT_TAG = "SEARCH_FRAGMENT";

    private int mPage;
    private int mCount;
    private boolean mKeyboardIsVisible;

    private ProgressDialog mProgressDialog;
    private Exception exception = null;

    private String mQuery;
    private ListView mListView;
    private SearchHistory mHistory;
    private RecipeListAdapter mAdapter;
    private MaterialSearchView mSearchView;

    private FloatingActionButton mButtonPrevious;
    private FloatingActionButton mButtonNext;
    private FragmentManager mFragmentManager;
    private SearchTaskFragment mTaskFragment;

    public String getQuery() {
        return mQuery;
    }

    public int getPage() {
        return mPage;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            toolbar.setElevation(0);
            toolbar.setTitleTextColor(getResources().getColor(R.color.colorWhite, getTheme()));
            setSupportActionBar(toolbar);
        }

        mPage = 1;
        mButtonPrevious = (FloatingActionButton) findViewById(R.id.button_previous);
        mButtonNext = (FloatingActionButton) findViewById(R.id.button_next);

        mButtonPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                previous();
            }
        });

        mButtonNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                next();
            }
        });

        mHistory = new SearchHistory(this);
        mSearchView = (MaterialSearchView) findViewById(R.id.search_view);
        mSearchView.setVisibility(View.VISIBLE);
        mSearchView.setVoiceSearch(false);
        mSearchView.setCursorDrawable(R.drawable.color_cursor_white);
        mSearchView.setEllipsize(true);
        mSearchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                search(query, 1);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });

        mSearchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
            @Override
            public void onSearchViewShown() {
                // do some magic
            }

            @Override
            public void onSearchViewClosed() {
                if (mKeyboardIsVisible) {
                    final Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            updateButtonsVisibility();
                        }
                    }, HIDE_KEYBOARD_DELAY); // giving it appropriate delay to hide the keyboard
                } else {
                    updateButtonsVisibility();
                }
            }
        });

        mListView = (ListView) findViewById(R.id.search_list);
        mFragmentManager = getFragmentManager();
        mTaskFragment = (SearchTaskFragment) mFragmentManager.findFragmentByTag(SEARCH_FRAGMENT_TAG);

//        if (mTaskFragment == null) {
//            mTaskFragment = SearchTaskFragment.newInstance(mQuery);
//            mFragmentManager.beginTransaction().add(mTaskFragment, SEARCH_FRAGMENT_TAG).commit();
//        }
//        mSuggestions = new SearchRecentSuggestions(this,
//                RecipeSuggestionProvider.AUTHORITY, RecipeSuggestionProvider.MODE);

        // Get the intent, verify the action and get the query
//        handleIntent(getIntent());
    }

    @Override
    protected void onSaveInstanceState(Bundle state) {
        //  Credits: Alex Lockwood (http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html)
        if (mAdapter != null) {
            ArrayList<Recipe> recipes = mAdapter.getRecipes();
            state.putParcelableArrayList("recipes", recipes);
            state.putString("mQuery", mQuery);
            state.putInt("mCount", mCount);
            state.putInt("mPage", mPage);
        }
        super.onSaveInstanceState(state);
    }

    @Override
    protected void onRestoreInstanceState(Bundle state) {
        //  Credits: Alex Lockwood (http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html)
        super.onRestoreInstanceState(state);
        ArrayList<Recipe> recipes = state.getParcelableArrayList("recipes");
        mQuery = state.getString("mQuery");
        mCount = state.getInt("mCount");
        mPage = state.getInt("mPage");
        mFragmentManager = getFragmentManager();
        mTaskFragment = (SearchTaskFragment) mFragmentManager.findFragmentByTag(SEARCH_FRAGMENT_TAG);

        if (recipes != null) {
            loadListView(recipes);
        }
        updateButtonsVisibility();
    }

    @Override
    public void onBackPressed() {
        if (mSearchView.isSearchOpen()) {
            mKeyboardIsVisible = false;
            mSearchView.closeSearch();
        } else if (mButtonPrevious.getVisibility() == View.VISIBLE) {
            previous();
        } else if (mHistory.sizeOf() > 1) {
            getPreviousSearchResult(Integer.MIN_VALUE);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_search, menu);
        MenuItem item = menu.findItem(R.id.action_search);

        mSearchView.setMenuItem(item, new MenuItemClickListener() {
            @Override
            public void onClick() {
                mSearchView.setSuggestions(mHistory.getHistoryCache());
                mButtonPrevious.setVisibility(View.GONE);
                mButtonNext.setVisibility(View.GONE);
                mSearchView.setQuery(mQuery, false);
                mKeyboardIsVisible = true; // setMenuItem() will invoke showSearch() which will request focus on the text view
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onPause() {
        mHistory.save();
        super.onPause();
    }

    @Override
    public void onDestroy() {
        mHistory.close(); // close the db
        super.onDestroy();
    }

    private void search(String query, int page) {
        query = query.trim();
        if (query.equals(mQuery) && page == mPage) {
            return;
        }

        mPage = page;
        mQuery = query;
        SearchResult result = Utility.getSearchResult(Utility.getHashCode(mQuery, mPage));
        if (result != null) {
            updateListViewWithResult(result);   // this should update the count
            updateButtonsVisibility(); // this should be called after count has been updated
\        } else {
            mHistory.push(mQuery);
            try {
                query = URLEncoder.encode(query, ServerUtility.ENCODING);
            } catch (UnsupportedEncodingException e) {
                // do not do any encoding
            }
            query = Utility.QUERY_PARAM + query;
            if (page > 1) {
                query += Utility.PAGE_PARAM + page;
            } else {
                mButtonPrevious.setVisibility(View.GONE);
            }

            mTaskFragment = SearchTaskFragment.newInstance(query);
            mFragmentManager.beginTransaction().add(mTaskFragment, SEARCH_FRAGMENT_TAG).commit();
        }
    }

    // we use page parameter here so that we remember to update mPage before calling this method
    private void getPreviousSearchResult(int page) {
        // if page equals minimum value, back button has been pressed
        if (page == Integer.MIN_VALUE) {
            Utility.removeSearchResult(Utility.getHashCode(mHistory.pop(), mPage)) ; // pop the most recent
            mQuery = mHistory.pop(); // pop the previous
            mPage = 1;
        } else { // should simply be going back one page
            mPage = page;
        }
        SearchResult result = Utility.getSearchResult(Utility.getHashCode(mQuery, mPage));
        if (result != null) {
            updateListViewWithResult(result);
        } else {
            // the implementation of setQuery does its own null and emptiness checks
            mSearchView.setQuery(mQuery, true); // this will perform a new search, which will push current query onto the history stack
        }
    }

    private void updateListViewWithResult(SearchResult result) {
        mPage = result.getPage();
        mQuery = result.getSearchTerm(); // should not be necessary
        Utility.setBitmapMemCache(result.getMemoryCache());
        mAdapter = result.getAdapter();
        mAdapter.notifyDataSetChanged();
        mCount = mAdapter.getCount();
        mListView.setAdapter(mAdapter);
        mListView.refreshDrawableState();
//            mHistory.push(mQuery); // push the previous (which is now the current) query back onto the stack
    }

    private void updateButtonsVisibility() {
        if (mPage > 1) {
            mButtonPrevious.setVisibility(View.VISIBLE);
        } else {
            mButtonPrevious.setVisibility(View.GONE);
        }
        if (mCount == MAX_COUNT) {
            mButtonNext.setVisibility(View.VISIBLE);
        } else {
            mButtonNext.setVisibility(View.GONE);
        }
    }

    private void loadListView(final List<Recipe> recipes) {
        if (mQuery == null) {
            return;
        }
        mAdapter = new RecipeListAdapter(this, recipes);
        Utility.resetBitmapCache(); // clear the cache before loading new images and new adapter
        for (Recipe r : recipes) {
            r.loadImage(mAdapter);
        }

        mAdapter.setOnImagesLoadedListener(new OnImagesLoadedListener() {
            @Override
            public void imagesLoaded(SearchState state) {  // at this point cache shall contain the (new) images for this query
                String hashCode = Utility.getHashCode(state.getQuery(), state.getPage());
                if (!Utility.resultHistoryContainsResult(hashCode)) {
                    saveSearchResult(new SearchResult(state.getAdapter(), state.getCache(), state.getQuery(), state.getPage()));
                }
            }
        });
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                 @Override
                 public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                     if(!mAdapter.getRecipes().isEmpty() && mAdapter.getRecipes().get(position) != null) {
                         Bundle extras = new Bundle();
                         extras.putSerializable(Utility.RECIPE, mAdapter.getRecipes().get(position));
                         navigateToActivity(RecipeActivity.class, extras);
                     }
                 }
             }
        );
    }

    private void saveSearchResult(SearchResult searchResult) {
        Utility.addSearchResult(searchResult);
    }

    private void previous() {
        mPage--;
        updateButtonsVisibility();
        getPreviousSearchResult(mPage);
//        search(mQuery, page);
    }

    private void next() {
        int page = mPage + 1; // keep this in order to prevent duplicate requests ->
                              // search method will compare given page against current

        // try fetching search result from cache
        SearchResult result = Utility.getSearchResult(Utility.getHashCode(mQuery, page));
        if (result != null) {
            mPage = page; // update the page too
            updateButtonsVisibility();
            updateListViewWithResult(result);
        } else {
            search(mQuery, page);
        }
    }

    // SearchTaskFragment.TaskCallbacks implementation beyond this comment

    @Override
    public void onPreExecute() {
        mProgressDialog = ProgressDialog.show(SearchActivity.this, "", getResources().getString(R.string.please_wait));
    }

    @Override
    public void onProgressUpdate(int percent) {

    }

    @Override
    public void onCancelled() {

    }

    @Override
    public void onPostExecute(final List<Recipe> result) {
        if(!SearchActivity.this.isDestroyed()) {
            if (mProgressDialog != null) mProgressDialog.dismiss();

            if (mTaskFragment.getException() == null) {
                if (!result.isEmpty()){
                    if (mListView == null) mListView = (ListView) findViewById(R.id.search_list);
                    mCount = mTaskFragment.getCount();
                    loadListView(result);
                    mSearchView.clearFocus();
                    updateButtonsVisibility();
                } else {
                    showToast(R.string.no_results);
                }
                mSearchView.setQuery(mQuery, false);
            } else {
                SearchActivity.this.displayMessage(exception);
            }
        }
    }

    // unused methods beyond this comment

//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        if (item.getItemId() == R.id.action_search) {
//            mSearchView.requestFocus();
//        }
//        return super.onOptionsItemSelected(item);
//    }

//    @Override
//    public boolean onSearchRequested() {
//        handleIntent(getIntent());
//        return super.onSearchRequested();
//    }
//
//    @Override
//    protected void onNewIntent(Intent intent) {
//        setIntent(intent);
//        handleIntent(intent);
//    }

//    private void handleIntent(Intent intent) {
//        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
//            String query = intent.getStringExtra(SearchManager.QUERY);
//            mSuggestions.saveRecentQuery(query, null);
//            search(query, mPage);
//        }
//    }

}


text:
<!DOCTYPE html>

	<title>Part BOM Editor</title>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

	<meta http-equiv="cache-control" content="no-cache" />


text:
#pragma once

#include "JSCJSValue.h"
#include "ObjectPropertyConditionSet.h"
#include "PropertyOffset.h"

namespace JSC {

class CodeBlock;
class StructureChain;

// This class is useful for figuring out how to inline a cached get-like access. We
// say "get-like" because this is appropriate for loading the GetterSetter object in
// a put_by_id that hits a setter. Notably, this doesn't figure out how to call
// accessors, or even whether they should be called. What it gives us, is a way of
// determining how to load the value from the requested property (identified by a
// StringImpl* uid) from an object of the given structure in the given CodeBlock,
// assuming that such an access had already been cached by Repatch (and so Repatch had
// already done a bunch of safety checks). This doesn't reexecute any checks that
// Repatch would have executed, and for prototype chain accesses, it doesn't ask the
// objects in the prototype chain whether their getOwnPropertySlot would attempt to
// intercept the access - so this really is only appropriate if you already know that
// one of the JITOperations had OK'd this for caching and that Repatch concurred.
//
// The typical use pattern is something like:
//
//     ComplexGetStatus status = ComplexGetStatus::computeFor(...);
//     switch (status.kind()) {
//     case ComplexGetStatus::ShouldSkip:
//         // Handle the case where this kind of access is possibly safe but wouldn't
//         // pass the required safety checks. For example, if an IC gives us a list of
//         // accesses and one of them is ShouldSkip, then we should pretend as if it
//         // wasn't even there.
//         break;
//     case ComplexGetStatus::TakesSlowPath:
//         // This kind of access is not safe to inline. Bail out of any attempst to
//         // inline.
//         break;
//     case ComplexGetStatus::Inlineable:
//         // The good stuff goes here. If it's Inlineable then the other properties of
//         // the 'status' object will tell you everything you need to know about how
//         // to execute the get-like operation.
//         break;
//     }

class ComplexGetStatus {
public:
    enum Kind {
        ShouldSkip,
        TakesSlowPath,
        Inlineable
    };

    ComplexGetStatus()
        : m_kind(ShouldSkip)
        , m_offset(invalidOffset)
    {
    }

    static ComplexGetStatus skip()
    {
        return ComplexGetStatus();
    }

    static ComplexGetStatus takesSlowPath()
    {
        ComplexGetStatus result;
        result.m_kind = TakesSlowPath;
        return result;
    }

    static ComplexGetStatus computeFor(
        Structure* headStructure, const ObjectPropertyConditionSet&, UniquedStringImpl* uid);

    Kind kind() const { return m_kind; }
    PropertyOffset offset() const { return m_offset; }
    const ObjectPropertyConditionSet& conditionSet() const { return m_conditionSet; }

private:
    Kind m_kind;
    PropertyOffset m_offset;
    ObjectPropertyConditionSet m_conditionSet;
};

} // namespace JSC


text:
package lookup

import (
	"io/ioutil"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/Sirupsen/logrus"
)

// relativePath returns the proper relative path for the given file path. If
// the relativeTo string equals "-", then it means that it's from the stdin,
// and the returned path will be the current working directory. Otherwise, if
// file is really an absolute path, then it will be returned without any
// changes. Otherwise, the returned path will be a combination of relativeTo
// and file.
func relativePath(file, relativeTo string) string {
	// stdin: return the current working directory if possible.
	if relativeTo == "-" {
		if cwd, err := os.Getwd(); err == nil {
			return cwd
		}
	}

	// If the given file is already an absolute path, just return it.
	// Otherwise, the returned path will be relative to the given relativeTo
	// path.
	if filepath.IsAbs(file) {
		return file
	}

	abs, err := filepath.Abs(filepath.Join(path.Dir(relativeTo), file))
	if err != nil {
		logrus.Errorf("Failed to get absolute directory: %s", err)
		return file
	}
	return abs
}

// FileConfigLookup is a "bare" structure that implements the project.ResourceLookup interface
type FileConfigLookup struct {
}

// Lookup returns the content and the actual filename of the file that is "built" using the
// specified file and relativeTo string. file and relativeTo are supposed to be file path.
// If file starts with a slash ('/'), it tries to load it, otherwise it will build a
// filename using the folder part of relativeTo joined with file.
func (f *FileConfigLookup) Lookup(file, relativeTo string) ([]byte, string, error) {
	file = relativePath(file, relativeTo)
	logrus.Debugf("Reading file %s", file)
	bytes, err := ioutil.ReadFile(file)
	return bytes, file, err
}

// ResolvePath returns the path to be used for the given path volume. This
// function already takes care of relative paths.
func (f *FileConfigLookup) ResolvePath(path, inFile string) string {
	vs := strings.SplitN(path, ":", 2)
	if len(vs) != 2 || filepath.IsAbs(vs[0]) {
		return path
	}

	if !strings.HasPrefix(vs[0], "./") && !strings.HasPrefix(vs[0], "~/") &&
		!strings.HasPrefix(vs[0], "/") {

		logrus.Warnf("The mapping \"%s\" is ambiguous. In a future version of Docker, it will "+
			"designate a \"named\" volume (see https://github.com/docker/docker/pull/14242). "+
			"To prevent unexpected behaviour, change it to \"./%s\".", vs[0], vs[0])
	}
	vs[0] = relativePath(vs[0], inFile)
	return strings.Join(vs, ":")
}


text:
rss: false
layout: update
published: true
title: Preview JavaScript values inline while debugging
date: 2015-07-07
article:
  written_on: 2015-07-07
  updated_on: 2015-07-07
authors:
- umarhansa
collection: updates
type: tip
category: tools
product: chrome-devtools
description: Learn how to preview the values of JavaScript variables in DevTools while
  debugging.
featured-image: /web/updates/images/2015-07-07-preview-javascript-values-inline-while-debugging/inline-js-values.gif
source_name: DevTips
source_url: https://umaar.com/dev-tips/41-inline-js-values
permalink: /updates/2015/07/07/preview-javascript-values-inline-while-debugging.html
---

While debugging, you can preview the values of JavaScript variables at that current point in time - this even works with minified scripts (after you pretty print).

To enable this feature (if it's not already):

Go to DevTools settings (the cog wheel).

Check General > Sources > Display variable values inline while debugging.


text:
	<title>Clive Palmer's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Clive Palmer's panel show appearances

Clive Palmer (born 1954-03-26[ref]) has appeared in 8 episodes between 2010-2015.  Clive Palmer on Wikipedia.

2010

2011

2012

2013

2014

2015

2015-05-11 / Q&A

2014-08-18 / Q&A

2014-02-24 / Q&A

2013-09-16 / Q&A

2013-05-13 / Q&A

2012-04-26 / Q&A

2011-09-05 / Q&A

2010-09-13 / Q&A


text:
<?php

/**
 * Product type model
 *
 * @category    Mage
 * @package     Mage_Catalog
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Mage_Catalog_Model_Product_Type
{
    /**
     * Available product types
     */
    const TYPE_SIMPLE       = 'simple';
    const TYPE_BUNDLE       = 'bundle';
    const TYPE_CONFIGURABLE = 'configurable';
    const TYPE_GROUPED      = 'grouped';
    const TYPE_VIRTUAL      = 'virtual';

    const DEFAULT_TYPE      = 'simple';
    const DEFAULT_TYPE_MODEL    = 'catalog/product_type_simple';
    const DEFAULT_PRICE_MODEL   = 'catalog/product_type_price';

    static protected $_types;
    static protected $_compositeTypes;
    static protected $_priceModels;
    static protected $_typesPriority;

    /**
     * Product type instance factory
     *
     * @param   Mage_Catalog_Model_Product $product
     * @param   bool $singleton
     * @return  Mage_Catalog_Model_Product_Type_Abstract
     */
    public static function factory($product, $singleton = false)
    {
        $types = self::getTypes();
        $typeId = $product->getTypeId();

        if (!empty($types[$typeId]['model'])) {
            $typeModelName = $types[$typeId]['model'];
        } else {
            $typeModelName = self::DEFAULT_TYPE_MODEL;
            $typeId = self::DEFAULT_TYPE;
        }

        if ($singleton === true) {
            $typeModel = Mage::getSingleton($typeModelName);
        }
        else {
            $typeModel = Mage::getModel($typeModelName);
            $typeModel->setProduct($product);
        }
        $typeModel->setConfig($types[$typeId]);
        return $typeModel;
    }

    /**
     * Product type price model factory
     *
     * @param   string $productType
     * @return  Mage_Catalog_Model_Product_Type_Price
     */
    public static function priceFactory($productType)
    {
        if (isset(self::$_priceModels[$productType])) {
            return self::$_priceModels[$productType];
        }

        $types = self::getTypes();

        if (!empty($types[$productType]['price_model'])) {
            $priceModelName = $types[$productType]['price_model'];
        } else {
            $priceModelName = self::DEFAULT_PRICE_MODEL;
        }

        self::$_priceModels[$productType] = Mage::getModel($priceModelName);
        return self::$_priceModels[$productType];
    }

    static public function getOptionArray()
    {
        $options = array();
        foreach(self::getTypes() as $typeId=>$type) {
            $options[$typeId] = Mage::helper('catalog')->__($type['label']);
        }

        return $options;
    }

    static public function getAllOption()
    {
        $options = self::getOptionArray();
        array_unshift($options, array('value'=>'', 'label'=>''));
        return $options;
    }

    static public function getAllOptions()
    {
        $res = array();
        $res[] = array('value'=>'', 'label'=>'');
        foreach (self::getOptionArray() as $index => $value) {
            $res[] = array(
               'value' => $index,
               'label' => $value
            );
        }
        return $res;
    }

    static public function getOptions()
    {
        $res = array();
        foreach (self::getOptionArray() as $index => $value) {
            $res[] = array(
               'value' => $index,
               'label' => $value
            );
        }
        return $res;
    }

    static public function getOptionText($optionId)
    {
        $options = self::getOptionArray();
        return isset($options[$optionId]) ? $options[$optionId] : null;
    }

    static public function getTypes()
    {
        if (is_null(self::$_types)) {
            $productTypes = Mage::getConfig()->getNode('global/catalog/product/type')->asArray();
            foreach ($productTypes as $productKey => $productConfig) {
                $moduleName = 'catalog';
                if (isset($productConfig['@']['module'])) {
                    $moduleName = $productConfig['@']['module'];
                }
                $translatedLabel = Mage::helper($moduleName)->__($productConfig['label']);
                $productTypes[$productKey]['label'] = $translatedLabel;
            }
            self::$_types = $productTypes;
        }

        return self::$_types;
    }

    /**
     * Return composite product type Ids
     *
     * @return array
     */
    static public function getCompositeTypes()
    {
        if (is_null(self::$_compositeTypes)) {
            self::$_compositeTypes = array();
            $types = self::getTypes();
            foreach ($types as $typeId=>$typeInfo) {
                if (array_key_exists('composite', $typeInfo) && $typeInfo['composite']) {
                    self::$_compositeTypes[] = $typeId;
                }
            }
        }
        return self::$_compositeTypes;
    }

    /**
     * Return product types by type indexing priority
     *
     * @return array
     */
    public static function getTypesByPriority()
    {
        if (is_null(self::$_typesPriority)) {
            self::$_typesPriority = array();
            $a = array();
            $b = array();

            $types = self::getTypes();
            foreach ($types as $typeId => $typeInfo) {
                $priority = isset($typeInfo['index_priority']) ? abs(intval($typeInfo['index_priority'])) : 0;
                if (!empty($typeInfo['composite'])) {
                    $b[$typeId] = $priority;
                } else {
                    $a[$typeId] = $priority;
                }
            }

            asort($a, SORT_NUMERIC);
            asort($b, SORT_NUMERIC);

            foreach (array_keys($a) as $typeId) {
                self::$_typesPriority[$typeId] = $types[$typeId];
            }
            foreach (array_keys($b) as $typeId) {
                self::$_typesPriority[$typeId] = $types[$typeId];
            }
        }
        return self::$_typesPriority;
    }
}


text:
package org.kaazing.gateway.transport.pipe;

import java.util.Collection;
import java.util.LinkedList;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.filterchain.IoFilterChain;
import org.apache.mina.core.write.WriteRequest;
import org.apache.mina.core.write.WriteRequestQueue;
import org.apache.mina.core.write.WriteToClosedSessionException;
import org.kaazing.mina.core.service.AbstractIoProcessor;

public class NamedPipeProcessor extends AbstractIoProcessor<NamedPipeSession> {

	private volatile boolean disposing;

	@Override
	protected void add0(NamedPipeSession session) {
		// nothing to do
	}

	@Override
	protected void remove0(NamedPipeSession session) {
        session.getService().getListeners().fireSessionDestroyed(session);

        session.setRemoteSession(null);
	}

	@Override
	protected void flush0(NamedPipeSession session) {
		// two threads can call flush in parallel since
		// resuming read on the remote session can also trigger a flush
		// instead of synchronization, we use the "atomic-2-step" so that
		// neither thread is blocked, but all write requests are still flushed
		try {
			// step-1: first thread in performs a flush
			if (session.beginFlush()) {
				flushInternal(session);
			}
		}
		finally {
			// step-2: last thread out performs a flush
			if (session.endFlush()) {
				flushInternal(session);
			}
		}
	}

	@Override
	protected void updateTrafficControl0(NamedPipeSession session) {

		// handle resume write
		if (!session.isWriteSuspended()) {
			flush(session);
		}

		// handle resume read
		if (!session.isReadSuspended()) {
			NamedPipeSession remoteSession = session.getRemoteSession();
			if (remoteSession != null && !remoteSession.isWriteSuspended()) {
				// this requires processor.flush(session) to be thread-safe
				NamedPipeProcessor remoteProcessor = remoteSession.getProcessor();
				remoteProcessor.flush(remoteSession);
			}
		}
	}

	@Override
	public void dispose() {
		disposing = true;
	}

	@Override
	public boolean isDisposing() {
		return disposing;
	}

	@Override
	public boolean isDisposed() {
		// nothing to dispose
		return disposing;
	}

	private void flushInternal(NamedPipeSession session) {
		WriteRequestQueue writeRequestQueue = session.getWriteRequestQueue();
		IoFilterChain filterChain = session.getFilterChain();

        if (session.setFlushInternalStarted()) {

            try {

                // cannot write buffers to remote session if it cannot read them
                NamedPipeSession remoteSession = session.getRemoteSession();
                if (remoteSession == null || remoteSession.isReadSuspended()) {
                    return;
                }

                IoFilterChain remoteFilterChain = remoteSession.getFilterChain();

                do {
                    WriteRequest request = session.getCurrentWriteRequest();
                    if (request == null) {
                        request = writeRequestQueue.poll(session);
                        if (request == null) {
                            break;
                        }
                        session.setCurrentWriteRequest(request);
                    }
                    Object message = request.getMessage();
                    if (message instanceof IoBuffer) {
                        IoBuffer buf = (IoBuffer) request.getMessage();
                        try {
                            // hold current remaining bytes so we know how much was written
                            int writableBytes = buf.remaining();

                            if (writableBytes != 0) {

                                if (session.isClosing()) {
                                    Collection<WriteRequest> unwritten = new LinkedList<>();
                                    while (request != null) {
                                        unwritten.add(request);
                                        request = writeRequestQueue.poll(session);
                                    }
                                    if (!unwritten.isEmpty()) {
                                        for(WriteRequest wr: unwritten) {
                                            System.out.println(session.toString() + " " + wr.getOriginalRequest().getMessage());
                                        }
                                        WriteToClosedSessionException exception = new WriteToClosedSessionException(unwritten);
                                        filterChain.fireExceptionCaught(exception);
                                        return;
                                    }
                                }
                                IoBuffer dup = buf.duplicate();
                                remoteFilterChain.fireMessageReceived(dup);

                                // cleanup and fire message sent
                                session.setCurrentWriteRequest(null);
                                filterChain.fireMessageSent(request);

                                // increment session written bytes
                                session.increaseWrittenBytes(writableBytes, System.currentTimeMillis());
                            }
                            else {
                                // cleanup and fire message sent
                                session.setCurrentWriteRequest(null);
                                buf.reset();
                                filterChain.fireMessageSent(request);
                            }
                        }
                        catch (Exception e) {
                            request.getFuture().setException(e);
                        }
                    }
                    else {
                        throw new IllegalStateException("Don't know how to handle message of type '" + message.getClass().getName() + "'.  Are you missing a protocol encoder?");
                    }
                } while (true);

            } finally {
                session.setFlushInternalComplete();
            }
        }
	}
}