text:
namespace crashpad {

//! \brief A ProcessSnapshot of a running (or crashed) process running on a
//!     Fuchsia system. This class is not yet implemented.
class ProcessSnapshotFuchsia : public ProcessSnapshot {
 public:
  ProcessSnapshotFuchsia();

  ProcessSnapshotFuchsia(const ProcessSnapshotFuchsia&) = delete;
  ProcessSnapshotFuchsia& operator=(const ProcessSnapshotFuchsia&) = delete;

  ~ProcessSnapshotFuchsia() override;

  //! \brief Initializes the object.
  //!
  //! \param[in] process The process handle to create a snapshot from.
  //!
  //! \return `true` if the snapshot could be created, `false` otherwise with
  //!     an appropriate message logged.
  bool Initialize(const zx::process& process);

  //! \brief Initializes the object's exception.
  //!
  //! This populates the data to be returned by Exception(). The thread
  //! identified by \a thread_id must be in an exception.
  //!
  //! This method must not be called until after a successful call to
  //! Initialize().
  //!
  //! \param[in] thread_id Koid of the thread which sustained the exception.
  //! \param[in] report The `zx_exception_report_t` for the thread which
  //!     sustained the exception.
  //! \return `true` if the exception information could be initialized, `false`
  //!     otherwise with an appropriate message logged. When this method returns
  //!     `false`, the ProcessSnapshotFuchsia object's validity remains
  //!     unchanged.
  bool InitializeException(zx_koid_t thread_id,
                           const zx_exception_report_t& report);

  //! \brief Returns options from CrashpadInfo structures found in modules in
  //!     the process.
  //!
  //! \param[out] options Options set in CrashpadInfo structures in modules in
  //!     the process.
  void GetCrashpadOptions(CrashpadInfoClientOptions* options);

  //! \brief Sets the value to be returned by ReportID().
  //!
  //! On Fuchsia, the crash report ID is under the control of the snapshot
  //! producer, which may call this method to set the report ID. If this is not
  //! done, ReportID() will return an identifier consisting entirely of zeroes.
  void SetReportID(const UUID& report_id) { report_id_ = report_id; }

  //! \brief Sets the value to be returned by ClientID().
  //!
  //! On Fuchsia, the client ID is under the control of the snapshot producer,
  //! which may call this method to set the client ID. If this is not done,
  //! ClientID() will return an identifier consisting entirely of zeroes.
  void SetClientID(const UUID& client_id) { client_id_ = client_id; }

  //! \brief Sets the value to be returned by AnnotationsSimpleMap().
  //!
  //! On Fuchsia, all process annotations are under the control of the snapshot
  //! producer, which may call this method to establish these annotations.
  //! Contrast this with module annotations, which are under the control of the
  //! process being snapshotted.
  void SetAnnotationsSimpleMap(
      const std::map<std::string, std::string>& annotations_simple_map) {
    annotations_simple_map_ = annotations_simple_map;
  }

  // ProcessSnapshot:
  crashpad::ProcessID ProcessID() const override;
  crashpad::ProcessID ParentProcessID() const override;
  void SnapshotTime(timeval* snapshot_time) const override;
  void ProcessStartTime(timeval* start_time) const override;
  void ProcessCPUTimes(timeval* user_time, timeval* system_time) const override;
  void ReportID(UUID* report_id) const override;
  void ClientID(UUID* client_id) const override;
  const std::map<std::string, std::string>& AnnotationsSimpleMap()
      const override;
  const SystemSnapshot* System() const override;
  std::vector<const ThreadSnapshot*> Threads() const override;
  std::vector<const ModuleSnapshot*> Modules() const override;
  std::vector<UnloadedModuleSnapshot> UnloadedModules() const override;
  const ExceptionSnapshot* Exception() const override;
  std::vector<const MemoryMapRegionSnapshot*> MemoryMap() const override;
  std::vector<HandleSnapshot> Handles() const override;
  std::vector<const MemorySnapshot*> ExtraMemory() const override;
  const ProcessMemory* Memory() const override;

 private:
  // Initializes threads_ on behalf of Initialize().
  void InitializeThreads();

  // Initializes modules_ on behalf of Initialize().
  void InitializeModules();

  internal::SystemSnapshotFuchsia system_;
  std::vector<std::unique_ptr<internal::ThreadSnapshotFuchsia>> threads_;
  std::vector<std::unique_ptr<internal::ModuleSnapshotElf>> modules_;
  std::unique_ptr<internal::ExceptionSnapshotFuchsia> exception_;
  ProcessReaderFuchsia process_reader_;
  ProcessMemoryRange memory_range_;
  std::map<std::string, std::string> annotations_simple_map_;
  std::vector<std::unique_ptr<internal::MemoryMapRegionSnapshotFuchsia>>
      memory_map_;
  UUID report_id_;
  UUID client_id_;
  timeval snapshot_time_;
  InitializationStateDcheck initialized_;
};

}  // namespace crashpad

#endif  // CRASHPAD_SNAPSHOT_FUCHSIA_PROCESS_SNAPSHOT_FUCHSIA_H_


text:
package com.planet_ink.coffee_mud.Abilities.Prayers;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class Prayer_Tremor extends Prayer
{
	public String ID() { return "Prayer_Tremor"; }
	public String name(){ return "Tremor";}
	public String displayText(){return "(Tremor)";}
	public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_CREATION;}
	public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
	public int maxRange(){return adjustedMaxInvokerRange(3);}
	protected int canAffectCode(){return 0;}
	protected int canTargetCode(){return 0;}
	public long flags(){return Ability.FLAG_HOLY|Ability.FLAG_UNHOLY;}
	protected boolean oncePerRd=false;

	public boolean tick(Tickable ticking, int tickID)
	{ oncePerRd=false; return super.tick(ticking,tickID);}

	public void affectEnvStats(Environmental affected, EnvStats affectableStats)
	{
		super.affectEnvStats(affected,affectableStats);
		// when this spell is on a MOBs Affected list,
		// it should consistantly put the mob into
		// a sleeping state, so that nothing they do
		// can get them out of it.
		affectableStats.setDisposition(affectableStats.disposition()|EnvStats.IS_SITTING);
	}

	public boolean okMessage(Environmental myHost, CMMsg msg)
	{
		// undo the affects of this spell
		if((affected==null)||(!(affected instanceof MOB)))
			return super.okMessage(myHost,msg);
		MOB mob=(MOB)affected;
		if((msg.amISource(mob))
		&&(msg.sourceMinor()==CMMsg.TYP_STAND)
		&&(mob.location()!=null))
		{
			if(!oncePerRd)
			{
				oncePerRd=true;
				mob.location().show(mob,null,CMMsg.MASK_ALWAYS|CMMsg.MSG_NOISYMOVEMENT,"<S-NAME> attempt(s) to stand up, and falls back down!");
			}
			return false;
		}
		return super.okMessage(myHost,msg);
	}

	public void unInvoke()
	{
		// undo the affects of this spell
		if((affected==null)||(!(affected instanceof MOB)))
			return;
		MOB mob=(MOB)affected;

		super.unInvoke();
		if(canBeUninvoked())
		{
			if((mob.location()!=null)&&(!mob.amDead()))
			{
				CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_NOISYMOVEMENT,"<S-NAME> regain(s) <S-HIS-HER> feet as the ground stops shaking.");
				if(mob.location().okMessage(mob,msg))
				{
					mob.location().send(mob,msg);
					CMLib.commands().postStand(mob,true);
				}
			}
			else
				mob.tell("The movement under your feet stops.");
		}
	}

	public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto, int asLevel)
	{
		HashSet h=properTargets(mob,givenTarget,auto);
		if(h==null)
		{
			mob.tell("There doesn't appear to be anyone here worth shaking up.");
			return false;
		}

		// the invoke method for spells receives as
		// parameters the invoker, and the REMAINING
		// command line parameters, divided into words,
		// and added as String objects to a vector.
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{

			if(mob.location().show(mob,null,this,verbalCastCode(mob,null,auto),(auto?"":"^S<S-NAME> "+prayWord(mob)+" thunderously.^?")+CMProps.msp("earthquake.wav",40)))
			for(Iterator f=h.iterator();f.hasNext();)
			{
				MOB target=(MOB)f.next();

				// it worked, so build a copy of this ability,
				// and add it to the affects list of the
				// affected MOB.  Then tell everyone else
				// what happened.
				CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),null);
				if(CMLib.flags().isInFlight(target))
					mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,"<S-NAME> seem(s) unaffected.");
				else
				if((mob.location().okMessage(mob,msg))&&(target.fetchEffect(this.ID())==null))
				{
					mob.location().send(mob,msg);
					if(msg.value()<=0)
					{
						if(target.charStats().getBodyPart(Race.BODY_LEG)>0)
						{
							success=maliciousAffect(mob,target,asLevel,2,-1);
							if(success)
							{
								if(target.location()==mob.location())
									CMLib.combat().postDamage(mob,target,this,10,CMMsg.MASK_ALWAYS|CMMsg.TYP_CAST_SPELL,-1,"The ground underneath <T-NAME> shakes as <T-NAME> fall(s) to the ground!!");
							}
						}
						else
							mob.location().show(target,null,CMMsg.MSG_OK_VISUAL,"<S-NAME> seem(s) unaffected by the quake.");
					}
				}
			}
		}
		else
			return maliciousFizzle(mob,null,"<S-NAME> "+prayWord(mob)+" thunderously, but nothing happens.");

		// return whether it worked
		return success;
	}
}

redpajama_set_name: RedPajamaGithub


text:
trap_handler()
{
    ERRLINE="$1"
    ERRVAL="$2"
    echo "line ${ERRLINE} exit status: ${ERRVAL}" >&2
    # The script should usually exit on error
    exit $ERRVAL
}
trap 'trap_handler ${LINENO} $?' ERR

for REQUIRED in git jq ssh
do
    if ! which $REQUIRED >/dev/null 2>&1
    then
        echo "Required '$REQUIRED' not found in \$PATH"
        exit 1
    fi
done

source $GOPHER_INSTALLDIR/lib/gopherbot_v1.sh

if [ -e ".restore" ]
then
    Log "Warn" "Found '.restore' file; restore in progress, not starting a backup"
    exit 0
fi

PTYPE="$GOPHER_PIPELINE_TYPE"

if [ "$PTYPE" == "plugCommand" -o "$PTYPE" == "jobCommand" ]
then
    Say "Starting backup requested by user $GOPHER_USER in channel: $GOPHER_START_CHANNEL"
fi

FailTask tail-log

if [ ! "$GOPHER_CUSTOM_REPOSITORY" ]
then
    Log "Error" "GOPHER_CUSTOM_REPOSITORY not set"
    exit 1
fi

if ! Exclusive "backup"
then
    Log "Info" "Unable to get exclusive access to 'backup', exiting"
    exit 0
fi

if [ "$GOPHER_STATE_REPOSITORY" ]
then
    PUSHBRANCH="${GOPHER_STATE_BRANCH:-main}"
    cd "$GOPHER_STATEDIR"
    if [ ! -d .git ]
    then
        NEWREPO="true"
        git init -b $PUSHBRANCH
        git remote add origin $GOPHER_STATE_REPOSITORY
        FailTask exec rm -rf ".git"
    fi
else
    GOPHER_STATE_REPOSITORY="$GOPHER_CUSTOM_REPOSITORY"
    PUSHBRANCH="${GOPHER_STATE_BRANCH:-robot-state}"
    if [ ! -d "$GOPHER_STATEDIR/.git" ]
    then
        if [ ! -d "$GOPHER_CONFIGDIR/.git" ]
        then
            Log "Error" "Backup to state branch specified, but $GOPHER_CONFIGDIR/.git doesn't exist"
            exit 0
        fi
        NEWREPO="true"
        # NOTE: technically, with no exclusive lock, GOPHER_CONFIGDIR
        # could change during the copy; however, this only happens once
        # on the first backup.
        cp -a "$GOPHER_CONFIGDIR" "$GOPHER_STATEDIR/custom"
        cd "$GOPHER_STATEDIR/custom"
        git checkout --orphan robot-state
        git rm -rf .
        mv .git/ ..
        cd ..
        rm -rf custom/
        CONFIGREPO=$(git remote get-url origin)
        GOPHER_STATE_REPOSITORY="$CONFIGREPO"
        FailTask exec rm -rf ".git"
    else
        cd "$GOPHER_STATEDIR"
    fi
fi

if [ -e ".failed" ]
then
    rm ".failed"
    FAILED="true"
fi

if [ -d "brain" -a ! -e "brain/README.txt" ]
then
    echo "Placeholder file for git backups, ensures brain directory is created." > brain/README.txt
fi

# Ignore known, noisy memories created by the default robot;
# ignore any memory with a leading underscore.
for IGNORE in 'bot:histories*' '*:repostats*' '*:_*'
do
    ALL_IGNORED=$(grep -F "$IGNORE" .gitignore || :)
    unset FOUND
    for IGNORED in $ALL_IGNORED
    do
        if [ "$IGNORED" == "$IGNORE" ]
        then
            FOUND=true
        fi
    done
    if [ ! "$FOUND" ]
    then
        Log "Debug" "Adding '$IGNORE' to .gitignore"
        echo "$IGNORE" >> .gitignore
    fi
done

CHANGES=$(git status --porcelain)

if [ ! "$CHANGES" -a ! "$NEWREPO" -a ! "$FAILED" ] # no changes
then
    if [ "$PTYPE" == "plugCommand" -o "$PTYPE" == "jobCommand" ]
    then
        Say "No changes, exiting..."
    fi
    exit 0
fi

SetWorkingDirectory "$GOPHER_STATEDIR"

if [ "$NEWREPO" ]
then
    AddTask git-init "$GOPHER_STATE_REPOSITORY"
else
    ORIGIN=$(git remote get-url origin)
    AddTask git-init "$ORIGIN"
    FailTask exec touch ".failed"
fi
if [ "$CHANGES" ]
then
    AddTask pause-brain
    FailTask resume-brain
    AddTask exec git add --all
    AddTask resume-brain
    AddTask exec git commit -m "Automated backup of robot state"
fi
if [ "$NEWREPO" ]
then
    AddTask exec git push -u origin $PUSHBRANCH
else
    AddTask exec git push
fi
if [ "$PTYPE" == "plugCommand" -o "$PTYPE" == "jobCommand" ]
then
    AddTask say "Backup complete"
fi


text:
<?php

namespace Phpsog;

use Kaloa\Filesystem\PathHelper;
use Phpsog\Application;
use Phpsog\Exporter;
use Phpsog\Logger;
use Symfony\Component\EventDispatcher\EventDispatcher;

/**
 *
 */
class Factory
{
    /**
     *
     * @return Application
     */
    public function createNewApplication($phpsogDirectory = null, $projectDirectory = null)
    {
        if ($phpsogDirectory === null) {
            $phpsogDirectory = getcwd();
        }

        if ($projectDirectory === null) {
            $projectDirectory = getcwd();
        }

        $logger      = new BufferLogger();
        $ph          = new PathHelper();
        $dispatcher  = new EventDispatcher();
        $exporter    = new Exporter($ph, $dispatcher);
        $application = new Application($logger, $dispatcher, $exporter, $ph,
                $phpsogDirectory, $projectDirectory);

        return $application;
    }
}


text:
// npm install gulp gulp-concat gulp-util gulp-rename gulp-uglify gulp-ruby-sass gulp-minify-css gulp-minify-html gulp-autoprefixer colors --save-dev
// Dependent on ruby's sass compiler

var gulp 			= require('gulp');
var gutil 			= require('gulp-util');

var grename 		= require('gulp-rename');
var concat 			= require('gulp-concat');
var uglify 			= require('gulp-uglify');
var sass 			= require('gulp-ruby-sass');
var minifycss 		= require('gulp-minify-css');
var jade 			= require('gulp-jade');
//var minifyhtml = require('gulp-minify-html');
var autoprefixer 	= require('gulp-autoprefixer');

var exec 			= require('child_process').exec;
var sys 			= require('sys');
var colors 			= require('colors');

var currentDate = new Date();

var config = {
/*	html: {
		directory: 'app/assets/views/',
		destination: 'public/views/compiled/',
		config: {
			empty: true,
			cdata: true,
			comments: true,
			conditionals: true,
			spare: true,
			quotes: true
		},
	}, */
	jade: {
		directory: 'app/assets/jade/',
		destination: 'public/views/',
		config: {
			pretty: true
		}
	},
	sass: {
		directory: 'app/assets/sass/',
		destination: 'public/css/',
		config: {
			style: 'compressed'
		}
	},
	javascript: {
		directory: 'app/assets/javascript/',
		source: {
			controllers: 'controllers/',
			directives: 'directives/',
			repositories: 'repositories/',
			services: 'services/'
		},
		destination: 'public/js/',
		config: {
			rename: {
				suffix: ".min"
			}
		}
	},
	autoprefixer: {
		config: 'last 5 version'
	}
};

gulp.task('js', function() {
	var directory = config.javascript.directory;
	sys.puts(currentDate.toLocaleString().inverse.white);
	sys.puts('Building Javascript [Directory \'' + directory + '\'...');
	// Build Frontend Main Components
	gulp.src(directory + '*.js')
		.pipe(concat('main.js'))
		//.pipe(uglify())
		//.pipe(grename(config.javascript.config.rename))
		.pipe(gulp.dest(config.javascript.destination));

	// Build Frontend Controller Components
	gulp.src(directory + config.javascript.source.controllers + '**/*.js')
		.pipe(concat('controllers.js'))
		//.pipe(uglify())
		//.pipe(grename(config.javascript.config.rename))
		.pipe(gulp.dest(config.javascript.destination));

	// Build Frontend Directives Components
	gulp.src(directory + config.javascript.source.directives + '**/*.js')
		.pipe(concat('directives.js'))
		//.pipe(uglify())
		//.pipe(grename(config.javascript.config.rename))
		.pipe(gulp.dest(config.javascript.destination));

	// Build Frontend Repository Components
	gulp.src(directory + config.javascript.source.repositories + '**/*.js')
		.pipe(concat('repositories.js'))
		//.pipe(uglify())
		//.pipe(grename(config.javascript.config.rename))
		.pipe(gulp.dest(config.javascript.destination));

	// Build Frontend Service Components
	gulp.src(directory + config.javascript.source.services + '**/*.js')
		.pipe(concat('services.js'))
		//.pipe(uglify())
		//.pipe(grename(config.javascript.config.rename))
		.pipe(gulp.dest(config.javascript.destination));
});

gulp.task('css', function() {
	return gulp.src(config.sass.directory + '*.scss')
		.pipe(concat('main.css'))
		.pipe(sass(config.sass.config).on('error', gutil.log))
		.pipe(autoprefixer(config.autoprefixer.config).on('error', gutil.log))
		.pipe(gulp.dest(config.sass.destination));
});

//gulp.task('html', function () {
//
//	// Build Frontend Views
//	gulp.src(config.html.directory + '**/*.html')
//		.pipe(minifyhtml(config.html.config))
//		.pipe(gulp.dest(config.html.destination));
//}); */

gulp.task('jade', function () {

	return gulp.src(config.jade.directory + '**/*.jade')
		.pipe(jade(config.jade.config))
		.pipe(gulp.dest(config.jade.destination));
})

gulp.task('watch', function() {
//	gulp.watch(config.html.directory + '/**/*.html', ['html']);

	gulp.watch(config.jade.directory + '**/*.jade', ['jade']);

	gulp.watch(config.sass.directory + '**/*.sass', ['css']);
	gulp.watch(config.sass.directory + '**/*.scss', ['css']);

	gulp.watch(config.javascript.directory + '**/*.js', ['js']);
});

gulp.task('default', ['js', 'css', 'watch', 'jade']);


text:
package st.ustp.siie.scanner.item;

import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import st.zudamue.support.android.adapter.ItemDataSet;
import st.zudamue.support.android.adapter.ItemViewHolder;
import st.ustp.siie.scanner.R;

/**
 * Created by daniel on 5/31/17.
 */

public class ItemRow extends ItemViewHolder<ItemRow.DataSet> {

    private TextView tvInfoValue;
    private TextView tvInfoLabel;
    private ImageView ivInfoIcon;
    private ImageView ivInfoIconAction;
    private View viewSeparador;
    private View.OnClickListener onIconActionClick;
    private View.OnClickListener onItemClick;
    private int bottom;

    private ItemRow(View view) {
        super(view);
        this.tvInfoLabel = (TextView) this.itemView.findViewById( R.id.tv_info_label );
        this.tvInfoValue = (TextView) this.itemView.findViewById( R.id.tv_info_value );
        this.ivInfoIcon = (ImageView) this.itemView.findViewById( R.id.iv_info_icon );
        this.ivInfoIconAction = (ImageView) this.itemView.findViewById( R.id.iv_info_icon_action);
        this.viewSeparador = this.findViewById( R.id.view_info_separator );
        this.onIconActionClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iconActionClick();
            }
        };

        this.onItemClick = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemClick();
            }
        };
    }

    private void itemClick() {
        if( getDataSet() != null ){
            this.callback( this.getDataSet().callbackItem );
        }
    }

    private void iconActionClick() {
        if( getDataSet() != null ){
            this.callback( this.getDataSet().callbackAction );
        }
    }

    @Override
    public void onBind( DataSet dataSet, int currentAdapterPosition, int totalDataSet) {
        this.dataSet( dataSet );
        this.tvInfoValue.setText( dataSet.value);
        this.tvInfoLabel.setText( dataSet.label );
        this.putImage( this.ivInfoIcon, dataSet.imageIcon);
        this.putImage( this.ivInfoIconAction, dataSet.imageIconAction);
        if( dataSet.hasSeparador() ) this.viewSeparador.setVisibility( View.VISIBLE );
        else this.viewSeparador.setVisibility( View.GONE );

        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) this.itemView.getLayoutParams();
        int left = params.leftMargin;
        int right = params.rightMargin;
        int top = params.topMargin;
        int bottom = params.bottomMargin;
        if( this.bottom == 0 ) this.bottom  = bottom;

        if( dataSet.sapaceBottom ){
            bottom = (int) getContext().getResources().getDimension( R.dimen.dp_16 );
        } else {
            bottom = this.bottom;
        }
        params.setMargins( left, top, right, bottom );

        if( dataSet.imageIconAction != null && dataSet.callbackAction != null ) {
            this.ivInfoIconAction.setOnClickListener( this.onIconActionClick );
        }else {
            this.ivInfoIconAction.setOnClickListener( null );
        }

        if( dataSet.callbackItem != null ){
            this.itemView.setOnClickListener( this.onItemClick );
        } else {
            this.itemView.setOnClickListener( null );
        }

    }

    private void putImage(ImageView imageView, Object data) {
        imageView.setImageBitmap( null );
        if( data == null ) {
            return;
        }
        if( data instanceof Bitmap ) imageView.setImageBitmap( ( Bitmap ) data);
        if( data instanceof Integer ) imageView.setImageResource(( Integer ) data);
        if( data instanceof Drawable ) imageView.setImageDrawable( ( Drawable ) data);
        if( data instanceof Uri ) imageView.setImageURI( ( Uri ) data);
        if( data instanceof Matrix ) imageView.setImageMatrix( ( Matrix ) data);
    }

    public static DataSet newDataSet(String label, String value) {
        return new DataSet( label, value );
    }

    public static ItemRow newInstance(View view) {
        return new ItemRow( view );
    }

    public static class DataSet implements ItemDataSet {

        private String label;
        private String value;
        private Object imageIcon;
        private Object imageIconAction;
        private boolean separtator;
        private ItemCallback< DataSet > callbackAction;
        private ItemCallback< DataSet > callbackItem;
        private boolean sapaceBottom;

        public DataSet(String nomeCampo, String valorCampo) {
            this.label = nomeCampo;
            this.value = valorCampo;
            this.separtator = false;
        }

        public DataSet setImageIcon(Object imageIcon) {
            this.imageIcon = imageIcon;
            return this;
        }

        public DataSet setImageIconAction(Object imageIconAction) {
            this.imageIconAction = imageIconAction;
            return this;
        }

        public DataSet setSepartator(boolean separtator) {
            this.separtator = separtator;
            return this;
        }

        public DataSet setCallbackAction(ItemCallback<DataSet> callbackAction) {
            this.callbackAction = callbackAction;
            return this;
        }

        public DataSet setCallbackItem(ItemCallback<DataSet> callbackItem) {
            this.callbackItem = callbackItem;
            return this;
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_row_information;
        }

        public boolean hasSeparador() {
            return this.separtator;
        }

        public DataSet setSapaceBottom(boolean sapaceBottom) {
            this.sapaceBottom = sapaceBottom;
            return this;
        }
    }
}


text:
<?php

namespace Illuminate\Broadcasting\Broadcasters;

use Ably\AblyRest;
use Ably\Models\Message as AblyMessage;
use Illuminate\Support\Str;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * @author Matthew Hall (matthall28@gmail.com)
 * @author Taylor Otwell (taylor@laravel.com)
 */
class AblyBroadcaster extends Broadcaster
{
    /**
     * The AblyRest SDK instance.
     *
     * @var \Ably\AblyRest
     */
    protected $ably;

    /**
     * Create a new broadcaster instance.
     *
     * @param  \Ably\AblyRest  $ably
     * @return void
     */
    public function __construct(AblyRest $ably)
    {
        $this->ably = $ably;
    }

    /**
     * Authenticate the incoming request for a given channel.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     *
     * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
     */
    public function auth($request)
    {
        $channelName = $this->normalizeChannelName($request->channel_name);

        if (empty($request->channel_name) ||
            ($this->isGuardedChannel($request->channel_name) &&
            ! $this->retrieveUser($request, $channelName))) {
            throw new AccessDeniedHttpException;
        }

        return parent::verifyUserCanAccessChannel(
            $request, $channelName
        );
    }

    /**
     * Return the valid authentication response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $result
     * @return mixed
     */
    public function validAuthenticationResponse($request, $result)
    {
        if (Str::startsWith($request->channel_name, 'private')) {
            $signature = $this->generateAblySignature(
                $request->channel_name, $request->socket_id
            );

            return ['auth' => $this->getPublicToken().':'.$signature];
        }

        $channelName = $this->normalizeChannelName($request->channel_name);

        $user = $this->retrieveUser($request, $channelName);

        $broadcastIdentifier = method_exists($user, 'getAuthIdentifierForBroadcasting')
                    ? $user->getAuthIdentifierForBroadcasting()
                    : $user->getAuthIdentifier();

        $signature = $this->generateAblySignature(
            $request->channel_name,
            $request->socket_id,
            $userData = array_filter([
                'user_id' => (string) $broadcastIdentifier,
                'user_info' => $result,
            ])
        );

        return [
            'auth' => $this->getPublicToken().':'.$signature,
            'channel_data' => json_encode($userData),
        ];
    }

    /**
     * Generate the signature needed for Ably authentication headers.
     *
     * @param  string  $channelName
     * @param  string  $socketId
     * @param  array|null  $userData
     * @return string
     */
    public function generateAblySignature($channelName, $socketId, $userData = null)
    {
        return hash_hmac(
            'sha256',
            sprintf('%s:%s%s', $socketId, $channelName, $userData ? ':'.json_encode($userData) : ''),
            $this->getPrivateToken(),
        );
    }

    /**
     * Broadcast the given event.
     *
     * @param  array  $channels
     * @param  string  $event
     * @param  array  $payload
     * @return void
     */
    public function broadcast(array $channels, $event, array $payload = [])
    {
        foreach ($this->formatChannels($channels) as $channel) {
            $this->ably->channels->get($channel)->publish(
                $this->buildAblyMessage($event, $payload)
            );
        }
    }

    /**
     * Build an Ably message object for broadcasting.
     *
     * @param  string  $event
     * @param  array  $payload
     * @return \Ably\Models\Message
     */
    protected function buildAblyMessage($event, array $payload = [])
    {
        return tap(new AblyMessage, function ($message) use ($event, $payload) {
            $message->name = $event;
            $message->data = $payload;
            $message->connectionKey = data_get($payload, 'socket');
        });
    }

    /**
     * Return true if the channel is protected by authentication.
     *
     * @param  string  $channel
     * @return bool
     */
    public function isGuardedChannel($channel)
    {
        return Str::startsWith($channel, ['private-', 'presence-']);
    }

    /**
     * Remove prefix from channel name.
     *
     * @param  string  $channel
     * @return string
     */
    public function normalizeChannelName($channel)
    {
        if ($this->isGuardedChannel($channel)) {
            return Str::startsWith($channel, 'private-')
                        ? Str::replaceFirst('private-', '', $channel)
                        : Str::replaceFirst('presence-', '', $channel);
        }

        return $channel;
    }

    /**
     * Format the channel array into an array of strings.
     *
     * @param  array  $channels
     * @return array
     */
    protected function formatChannels(array $channels)
    {
        return array_map(function ($channel) {
            $channel = (string) $channel;

            if (Str::startsWith($channel, ['private-', 'presence-'])) {
                return Str::startsWith($channel, 'private-')
                    ? Str::replaceFirst('private-', 'private:', $channel)
                    : Str::replaceFirst('presence-', 'presence:', $channel);
            }

            return 'public:'.$channel;
        }, $channels);
    }

    /**
     * Get the public token value from the Ably key.
     *
     * @return mixed
     */
    protected function getPublicToken()
    {
        return Str::before($this->ably->options->key, ':');
    }

    /**
     * Get the private token value from the Ably key.
     *
     * @return mixed
     */
    protected function getPrivateToken()
    {
        return Str::after($this->ably->options->key, ':');
    }

    /**
     * Get the underlying Ably SDK instance.
     *
     * @return \Ably\AblyRest
     */
    public function getAbly()
    {
        return $this->ably;
    }
}


text:
#pragma once
#include "RHI\RHITypes.h"
#include "RHI\RHI.h"
#include <map>
namespace MemoryUtils
{
	template<typename T>
	static void DeleteVector(std::vector<T*>& target)
	{
		for (int i = 0; i < target.size(); i++)
		{
			SafeDelete(target[i]);
		}
		target.clear();
	}
	template<typename T>
	static void DeleteCArray(T* target, int Length)
	{
		for (int i = 0; i < Length; i++)
		{
			delete target[i];
			target[i] = nullptr;
		}
	}

	template<typename T>
	static void DeleteReleaseableCArray(T* target, int Length)
	{
		for (int i = 0; i < Length; i++)
		{
			if (target[i] != nullptr)
			{
				target[i]->Release();
				target[i] = nullptr;
			}
		}
	}
	template<typename T>
	static void DeleteReleaseableVector(std::vector<T*>& target)
	{
		for (int i = 0; i < target.size(); i++)
		{
			if (target[i] != nullptr)
			{
				target[i]->Release();
				target[i] = nullptr;
			}
		}
		target.clear();
	}
	template<class S, class T>
	static void DeleteReleaseableMap(std::map<S, T>& target)
	{
		/*std::map<S, T>::iterator it;
		for (it = target.begin(); it != target.end(); it++)
		{
			it->second.Release();
		}*/
	}
	namespace RHIUtil
	{
		template<typename T>
		static void DeleteRHICArray(T* target, int Length)
		{
			for (int i = 0; i < Length; i++)
			{
				EnqueueSafeRHIRelease(target[i]);
				target[i] = nullptr;
			}
		}
		template<typename T>
		static void DeleteVector(std::vector<T*>& target)
		{
			for (int i = 0; i < target.size(); i++)
			{
				EnqueueSafeRHIRelease(target[i]);
				target[i] = nullptr;
			}
			target.clear();
		}
	}
};


text: Sign in for landing page of Bubbles


text:
package com.tora.benchmarks.states;

import com.tora.benchmarks.repository.CollectionRepository;
import com.tora.benchmarks.repository.InMemoryRepository;
import com.tora.benchmarks.repository.Order;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * @author Ovidiu Maja<ovi.dan89@gmail.com>
 * @version Oct 19, 2017
 */
public enum RepositorySupplier implements Supplier<InMemoryRepository<Order>> {
    HASH_SET() {
        @Override
        public InMemoryRepository<Order> get() {
            return new CollectionRepository<>(HashSet::new);
        }
    },

    TREE_SET() {
        @Override
        public InMemoryRepository<Order> get() {
            return new CollectionRepository<>(TreeSet::new);
        }
    },

    ARRAY_LIST() {
        @Override
        public InMemoryRepository<Order> get() {
            return new CollectionRepository<>(ArrayList::new);
        }
    },

    LINKED_LIST() {
        @Override
        public InMemoryRepository<Order> get() {
            return new CollectionRepository<>(LinkedList::new);
        }
    },

    CONCURRENT_HASH_MAP() {
        @Override
        public InMemoryRepository<Order> get() {
            return new CollectionRepository<>(() -> Collections.newSetFromMap(new ConcurrentHashMap<Order, Boolean>()));
        }
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
    xmlns:skin="http://schemas.android.com/android/skin"
android:layout_width="match_parent"
android:layout_height="@dimen/material_drawer_account_header_compact"
android:orientation="horizontal"
android:paddingEnd="@dimen/material_drawer_vertical_padding"
android:paddingLeft="@dimen/material_drawer_vertical_padding"
android:paddingRight="@dimen/material_drawer_vertical_padding"
android:paddingStart="@dimen/material_drawer_vertical_padding"
    skin:enable="true"
    android:id="@+id/ll_weather">

<ImageView
    android:id="@+id/iv_weather_icon"
    android:layout_width="@dimen/material_drawer_item_primary_icon"
    android:layout_height="@dimen/material_drawer_item_primary"
    android:layout_gravity="center_vertical"
    android:paddingBottom="@dimen/material_drawer_item_primary_icon_padding"
    android:paddingEnd="@dimen/material_drawer_item_primary_icon_padding_right"
    android:paddingLeft="0dp"
    android:paddingRight="@dimen/material_drawer_item_primary_icon_padding_right"
    android:paddingStart="0dp"
    android:src="@drawable/weather"
    android:paddingTop="@dimen/material_drawer_item_primary_icon_padding" />

    <TextView
        android:id="@+id/weather_text"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:fontFamily="sans-serif-medium"
        android:gravity="center_vertical|start"
        android:lines="1"
        android:layout_gravity="center_vertical"
        android:singleLine="true"
        android:textDirection="anyRtl"
        android:textColor="@color/colorPrimary"
        skin:enable="true"
        android:textSize="@dimen/material_drawer_item_primary_text"
        android:text="正在获取天气信息……" />

<LinearLayout
    android:id="@+id/material_drawer_badge_container"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    >

    <TextView
        android:id="@+id/tv_weather_temp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0°"
        skin:enable="true"
        android:textColor="@color/colorPrimary"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tv_weather_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        skin:enable="true"
        android:text="中国"
        android:textColor="@color/colorPrimary"
        android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
    <!--<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/ll_weather"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="bottom|right"
        android:orientation="vertical"
        android:paddingRight="@dimen/dp_five"
        android:visibility="visible">

        <TextView
            android:id="@+id/tv_weather_temp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="5°"
            android:textColor="@color/colorPrimary"
            android:textSize="24sp" />
        >

        <TextView
            android:id="@+id/tv_weather_city"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="杭州市"
            android:textColor="@color/colorPrimary"
            android:textSize="14sp" />

    </LinearLayout>-->


text:
import React from 'react'
import {RouteHandler} from 'react-router'
import Head from './head/head'
import Header from './header/header'
import Footer from './footer/footer'
import Sidebar from './sidebar/sidebar'
import stringify from 'json-stable-stringify'

export default class Html extends React.Component {
    static getDependencies() {
        return [Sidebar]
    }
    outputScript() {
        var data = this.props.data
        if (typeof data === 'object') {
            data = stringify(data)
        }

        return {__html: "var initialData = " + data}
    }
    render() {
        return (

                            <Sidebar className="col-lg-2" data={this.props.data.Sidebar} />

                                <RouteHandler data={this.props.data} />

        )
    }
}


text:
#include "base/types.h"
#include "render/glcontext.h"
#include "math/vec4.h"
#include "render/gpuprogram.h"
#include "render/texture.h"
#include "render/framebuffer.h"

namespace base {
namespace opengl {

template<GLenum State, bool init>
class BoolState
{
public:
    BoolState(DeviceContext& context) : gl(context) {
        currentState = init;
    }
    bool set(bool newState) {
        if (newState == currentState)
            return currentState;
        currentState = newState;
        if (currentState)
            gl.Enable(State);
        else
            gl.Disable(State);
        return currentState;
    }
    bool get() const { return currentState; }
private:
    DeviceContext& gl;
    bool currentState;
};

template<bool init>
class DepthWriteState
{
public:
    DepthWriteState(DeviceContext& context) : gl(context) {
        currentState = init;
    }
    bool set(bool newState) {
        if (newState == currentState)
            return currentState;
        currentState = newState;
        if (currentState)
            gl.DepthMask(GL_TRUE);
        else
            gl.DepthMask(GL_FALSE);
        return currentState;
    }
private:
    DeviceContext& gl;
    bool currentState;
};

class ViewportState
{
public:
    ViewportState(DeviceContext& context) : gl(context), viewport(0, 0, 0, 0) {
    }

    void set(const math::vec4f& v) {
        if (v == viewport)
            return;
        viewport = v;
        gl.Viewport(static_cast<i32>(viewport.x), static_cast<i32>(viewport.y), static_cast<i32>(viewport.z), static_cast<i32>(viewport.w));
    }
private:
    DeviceContext& gl;
    math::vec4f viewport;
};

class GpuProgramState
{
public:
    GpuProgramState(DeviceContext& context) : gl(context), current_(nullptr) {}
    bool set(GpuProgram* program)
    {
        if (current_ == program)
            return false;
        current_ = program;
        if (current_ == nullptr)
            gl.UseProgram(0u);
        else
            gl.UseProgram(current_->handle());
        return true;
    }
    GpuProgram& current() { return *current_; }
private:
    DeviceContext& gl;
    GpuProgram* current_;
};

template<GLenum Buffer>
class BufferState
{
public:
    BufferState(DeviceContext& context) : gl(context), current(0) {}
    void set(u32 buffer)
    {
        if (current == buffer)
            return;
        current = buffer;
        gl.BindBuffer(Buffer, current);
    }
private:
    DeviceContext& gl;
    u32 current;
};

class TextureUnitState
{
public:
    TextureUnitState(DeviceContext& context) : gl(context), current(0xffff) {}
    void set(u32 unit)
    {
        if (current == unit)
            return;
        current = unit;
        gl.ActiveTexture(GL_TEXTURE0 + unit);
    }
private:
    DeviceContext& gl;
    u32 current;
};

class TextureState
{
public:
    Texture* current_;
    TextureState() : current_(nullptr) {}
    void set(Texture* newState) {
        if (current_ == newState)
            return;
        if (newState == nullptr)
            current_->unbind();
        else
            newState->bind();
        current_ = newState;
    }
};

class FramebufferState {
public:
    Framebuffer* current_;
    FramebufferState() : current_(nullptr) {
    }

    void set(Framebuffer* newState) {
        if (newState == current_) {
            if (current_ != nullptr && !current_->initialized()) {
                current_->complete();
            }
            return;
        }
        if (newState == nullptr) {
            current_->unbind();
        } else {
            newState->bind();
        }
        current_ = newState;
    }
};

class Mesh;

class RenderState
{
public:
    RenderState(DeviceContext& context);

public:

    BoolState<GL_CULL_FACE, false> cullface;
    BoolState<GL_DEPTH_TEST, false> depthTest;
    BoolState<GL_BLEND, false> blend;
    DepthWriteState<true> depthWrite;
    ViewportState viewportArea;
    GpuProgramState program;
    BufferState<GL_ELEMENT_ARRAY_BUFFER> indexBuffer;
    BufferState<GL_ARRAY_BUFFER> vertexBuffer;
    TextureUnitState activeTexture;
    TextureState textureState;
    FramebufferState framebuffer;

    NEGINE_API void render(const Mesh& mesh, u32 from, u32 count);
private:
    DeviceContext& gl;
};

}
}


text:
ODIR=../../temp
LIB=fpgalib
LIBS=../../temp
STANDALONE=1
include ../../makes/ghdl.mk

bin: sync_pkg.o ffchain.o gray_sync.o divider.o boundary.o debounce.o syncClockDomains.o
test: run_ffchain_tb run_boundary_tb

simul_pkg.o:
	make -C ../simul bin

ffchain_tb.o: simul_pkg.o sync_pkg.o ffchain.o
syncClockDomains.o: sync_pkg.o
boundary_tb.o: sync_pkg.o boundary.o

run_ffchain_tb: ffchain_tb
run_boundary_tb: boundary_tb


text:
require "bundler/capistrano"

load "config/recipes/base"
load "config/recipes/apachevhost"

server "75.98.173.74", :web, :app, :db, primary: true

set :user, "deploy"
set :domain, "valleysummit.stagingarea.us"
set :application, "valleysummit"
set :deploy_to, "/var/www/#{application}/app"
set :deploy_via, :remote_cache
set :use_sudo, false

set :scm, "git"
set :repository, "git@github.com:alnutile/#{application}.git"
set :branch, "development"

default_run_options[:pty] = true
ssh_options[:forward_agent] = true

after "deploy", "deploy:cleanup" # keep only the last 5 releases


text:
<?php

return [
    'range'         => [
        'label'        => 'Range Input',
        'instructions' => 'Capture a range of values with two drag handles?',
        'disabled'     => 'Disabled',
        'enabled'      => 'Enabled',
        'min'          => 'Fixed to minimum value',
        'max'          => 'Fixed to maximum value'
    ],
    'min'           => [
        'label'        => 'Minimum Value',
        'instructions' => 'What is the minimum value allowed?'
    ],
    'max'           => [
        'label'        => 'Maximum Value',
        'instructions' => 'What is the maximum value allowed?'
    ],
    'step'          => [
        'label'        => 'Step',
        'instructions' => 'Enter the slider\'s step size.'
    ],
    'default_value' => [
        'label'        => 'Default Value',
        'instructions' => 'Enter the default value or value range if any.',
        'placeholder'  => '4,9'
    ]
];


text:
layout: page
title: Frederick Corporation Party
date: 2016-05-24
author: Evelyn Jacobs
tags: weekly links, java
status: published
summary: Sed posuere ipsum eget mi lobortis facilisis. Ut eget.
banner: images/banner/office-01.jpg
booking:
  startDate: 12/11/2016
  endDate: 12/13/2016
  ctyhocn: CFORDHX
  groupCode: FCP
published: true
---
Cras fringilla elit massa, sit amet laoreet mauris elementum vel. Nulla eros magna, varius ac tellus at, elementum fermentum ante. In vel purus eget lacus porttitor tempus. Vivamus lorem nibh, fringilla et pharetra eget, porta non justo. Curabitur arcu mauris, condimentum eu sollicitudin in, feugiat vitae ligula. Aenean sollicitudin tristique dui, sit amet interdum quam porttitor sed. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras sit amet arcu dapibus tortor bibendum pretium vitae vitae lorem.

* Praesent porta diam id risus auctor molestie
* Mauris congue purus a velit ullamcorper, eu interdum dui convallis
* Duis tristique nisl at turpis condimentum, a semper magna hendrerit
* Aenean at nisi sed nisl ornare venenatis.

Nulla nec tortor blandit, euismod orci ac, porttitor libero. Suspendisse porta quam et ligula feugiat, semper consectetur velit molestie. Praesent id magna quis sem vulputate molestie. Suspendisse diam lacus, mollis sit amet magna dignissim, pellentesque venenatis sapien. In at lectus elementum, aliquam tortor sit amet, mollis justo. Proin commodo dapibus lacus, at viverra sem auctor et. Nunc dapibus arcu ac libero ullamcorper tincidunt. Nullam egestas nibh turpis, eget bibendum lectus convallis eget.


text:
cask :v1 => 'mplayerx' do
  version '1.1.0-1854'
  sha256 '6a32302dc47e3776039cbcdf68726ebabac3b8a07933d01a48bc3d2ad3827aaa'

  # sourceforge.net is the official download host per the vendor homepage
  url "http://downloads.sourceforge.net/project/mplayerx-osx/MPlayerX-#{version}.zip"
  name 'MPlayerX'
  homepage 'http://mplayerx.org/'
  license :oss

  app 'MPlayerX.app'

  zap :delete => [
                  '~/.mplayer',
                  '~/Library/Application Support/MPlayerX',
                  '~/Library/Preferences/org.niltsh.MPlayerX.LSSharedFileList.plist',
                  '~/Library/Preferences/org.niltsh.MPlayerX.plist',
                  '~/Library/Caches/org.niltsh.MPlayerX'
                 ]
end


text:
package me.videa.voice.show;

import me.videa.base.functions.TtsSettings;
import me.videa.utils.ApkInstaller;
import me.videa.voice.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
import com.iflytek.sunflower.FlowerCollector;

public class TtsDemo extends Activity implements OnClickListener {
	private static String TAG = TtsDemo.class.getSimpleName();
	// 语音合成对象
	private SpeechSynthesizer mTts;

	// 默认发音人
	private String voicer="xiaoyan";

	private String[] cloudVoicersEntries;
	private String[] cloudVoicersValue ;

	// 缓冲进度
	private int mPercentForBuffering = 0;
	// 播放进度
	private int mPercentForPlaying = 0;

	// 云端/本地单选按钮
	private RadioGroup mRadioGroup;
	// 引擎类型
	private String mEngineType = SpeechConstant.TYPE_CLOUD;
	// 语音+安装助手类
	ApkInstaller mInstaller ;

	private Toast mToast;
	private SharedPreferences mSharedPreferences;

	@SuppressLint("ShowToast")
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ttsdemo);

		initLayout();
		// 初始化合成对象
		mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);

		// 云端发音人名称列表
		cloudVoicersEntries = getResources().getStringArray(R.array.voicer_cloud_entries);
		cloudVoicersValue = getResources().getStringArray(R.array.voicer_cloud_values);

		mSharedPreferences = getSharedPreferences(TtsSettings.PREFER_NAME, MODE_PRIVATE);
		mToast = Toast.makeText(this,"",Toast.LENGTH_SHORT);

		mInstaller = new  ApkInstaller(TtsDemo.this);
	}

	/**
	 * 初始化Layout。
	 */
	private void initLayout() {
		findViewById(R.id.tts_play).setOnClickListener(TtsDemo.this);
		findViewById(R.id.tts_cancel).setOnClickListener(TtsDemo.this);
		findViewById(R.id.tts_pause).setOnClickListener(TtsDemo.this);
		findViewById(R.id.tts_resume).setOnClickListener(TtsDemo.this);
		findViewById(R.id.image_tts_set).setOnClickListener(TtsDemo.this);

		findViewById(R.id.tts_btn_person_select);
		findViewById(R.id.tts_btn_person_select).setOnClickListener(TtsDemo.this);

		mRadioGroup=((RadioGroup) findViewById(R.id.tts_rediogroup));
		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.tts_radioCloud:
					mEngineType = SpeechConstant.TYPE_CLOUD;
					break;
				case R.id.tts_radioLocal:
					mEngineType =  SpeechConstant.TYPE_LOCAL;
					/**
					 * 选择本地合成
					 * 判断是否安装语音+,未安装则跳转到提示安装页面
					 */
					if (!SpeechUtility.getUtility().checkServiceInstalled()) {
						mInstaller.install();
					}
					break;
				default:
					break;
				}

			}
		} );
	}

	@Override
	public void onClick(View view) {
		switch(view.getId()) {
		case R.id.image_tts_set:
			if(SpeechConstant.TYPE_CLOUD.equals(mEngineType)){
				Intent intent = new Intent(TtsDemo.this, TtsSettings.class);
				startActivity(intent);
			}else{
				// 本地设置跳转到语音+中
				if (!SpeechUtility.getUtility().checkServiceInstalled()) {
					mInstaller.install();
				}else {
					SpeechUtility.getUtility().openEngineSettings(null);
				}
			}
			break;
		// 开始合成
		// 收到onCompleted 回调时,合成结束、生成合成音频
        // 合成的音频格式:只支持pcm格式
		case R.id.tts_play:
			String text = ((EditText) findViewById(R.id.tts_text)).getText().toString();
			// 设置参数
			setParam();
			int code = mTts.startSpeaking(text, mTtsListener);
//			/**
//			 * 只保存音频不进行播放接口,调用此接口请注释startSpeaking接口
//			 * text:要合成的文本,uri:需要保存的音频全路径,listener:回调接口
//			*/
//			String path = Environment.getExternalStorageDirectory()+"/tts.pcm";
//			int code = mTts.synthesizeToUri(text, path, mTtsListener);

			if (code != ErrorCode.SUCCESS) {
				if(code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED){
					//未安装则跳转到提示安装页面
					mInstaller.install();
				}else {
					showTip("语音合成失败,错误码: " + code);
				}
			}
			break;
		// 取消合成
		case R.id.tts_cancel:
			mTts.stopSpeaking();
			break;
		// 暂停播放
		case R.id.tts_pause:
			mTts.pauseSpeaking();
			break;
		// 继续播放
		case R.id.tts_resume:
			mTts.resumeSpeaking();
			break;
		// 选择发音人
		case R.id.tts_btn_person_select:
			showPresonSelectDialog();
			break;
		}
	}

	private int selectedNum=0;
	/**
	 * 发音人选择。
	 */
	private void showPresonSelectDialog() {
		switch (mRadioGroup.getCheckedRadioButtonId()) {
		// 选择在线合成
		case R.id.tts_radioCloud:
			new AlertDialog.Builder(this).setTitle("在线合成发音人选项")
				.setSingleChoiceItems(cloudVoicersEntries, // 单选框有几项,各是什么名字
						selectedNum, // 默认的选项
						new DialogInterface.OnClickListener() { // 点击单选框后的处理
					public void onClick(DialogInterface dialog,
							int which) { // 点击了哪一项
						voicer = cloudVoicersValue[which];
						if ("catherine".equals(voicer) || "henry".equals(voicer) || "vimary".equals(voicer)) {
							 ((EditText) findViewById(R.id.tts_text)).setText(R.string.text_tts_source_en);
						}else {
							((EditText) findViewById(R.id.tts_text)).setText(R.string.text_tts_source);
						}
						selectedNum = which;
						dialog.dismiss();
					}
				}).show();
			break;

		// 选择本地合成
		case R.id.tts_radioLocal:
			if (!SpeechUtility.getUtility().checkServiceInstalled()) {
				mInstaller.install();
			}else {
				SpeechUtility.getUtility().openEngineSettings(SpeechConstant.ENG_TTS);
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 初始化监听。
	 */
	private InitListener mTtsInitListener = new InitListener() {
		@Override
		public void onInit(int code) {
			Log.d(TAG, "InitListener init() code = " + code);
			if (code != ErrorCode.SUCCESS) {
        		showTip("初始化失败,错误码:"+code);
        	} else {
				// 初始化成功,之后可以调用startSpeaking方法
        		// 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成,
        		// 正确的做法是将onCreate中的startSpeaking调用移至这里
			}
		}
	};

	/**
	 * 合成回调监听。
	 */
	private SynthesizerListener mTtsListener = new SynthesizerListener() {
		@Override
		public void onSpeakBegin() {
			showTip("开始播放");
		}

		@Override
		public void onSpeakPaused() {
			showTip("暂停播放");
		}

		@Override
		public void onSpeakResumed() {
			showTip("继续播放");
		}

		@Override
		public void onBufferProgress(int percent, int beginPos, int endPos,
				String info) {
			// 合成进度
			mPercentForBuffering = percent;
			showTip(String.format(getString(R.string.tts_toast_format),
					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onSpeakProgress(int percent, int beginPos, int endPos) {
			// 播放进度
			mPercentForPlaying = percent;
			showTip(String.format(getString(R.string.tts_toast_format),
					mPercentForBuffering, mPercentForPlaying));
		}

		@Override
		public void onCompleted(SpeechError error) {
			if (error == null) {
				showTip("播放完成");
			} else if (error != null) {
				showTip(error.getPlainDescription(true));
			}
		}

		@Override
		public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {

		}
	};

	private void showTip(final String str) {
		mToast.setText(str);
		mToast.show();
	}

	/**
	 * 参数设置
	 * @param param
	 * @return
	 */
	private void setParam(){
		// 清空参数
		mTts.setParameter(SpeechConstant.PARAMS, null);
		// 根据合成引擎设置相应参数
		if(mEngineType.equals(SpeechConstant.TYPE_CLOUD)) {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
			// 设置在线合成发音人
			mTts.setParameter(SpeechConstant.VOICE_NAME,voicer);
		}else {
			mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_LOCAL);
			// 设置本地合成发音人 voicer为空,默认通过语音+界面指定发音人。
			mTts.setParameter(SpeechConstant.VOICE_NAME,"");
		}
		//设置合成语速
		mTts.setParameter(SpeechConstant.SPEED,mSharedPreferences.getString("speed_preference", "50"));
		//设置合成音调
		mTts.setParameter(SpeechConstant.PITCH,mSharedPreferences.getString("pitch_preference", "50"));
		//设置合成音量
		mTts.setParameter(SpeechConstant.VOLUME,mSharedPreferences.getString("volume_preference", "50"));
		//设置播放器音频流类型
		mTts.setParameter(SpeechConstant.STREAM_TYPE,mSharedPreferences.getString("stream_preference", "3"));

		// 设置播放合成音频打断音乐播放,默认为true
		mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");

		// 设置合成音频保存路径,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
		mTts.setParameter(SpeechConstant.PARAMS,"tts_audio_path="+Environment.getExternalStorageDirectory()+"/test.pcm");
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mTts.stopSpeaking();
		// 退出时释放连接
		mTts.destroy();
	}

	@Override
	protected void onResume() {
		//移动数据统计分析
		FlowerCollector.onResume(TtsDemo.this);
		FlowerCollector.onPageStart(TAG);
		super.onResume();
	}
	@Override
	protected void onPause() {
		//移动数据统计分析
		FlowerCollector.onPageEnd(TAG);
		FlowerCollector.onPause(TtsDemo.this);
		super.onPause();
	}
}


text:
echo "Installing dependencies..."

if [ "$(which mongod)" == "" ]; then
  echo "== MongoDB is not installed"
  sudo apt-get -y install mongodb

  echo "==== Stop default MongoDB instance"
  sudo mongod --shutdown --config /etc/mongodb.conf
fi

if [ "$(which npm)" == "" ]; then
  echo "== npm is not installed"
  sudo apt-get -y install npm
fi

echo "Done installing dependencies"

if [ "$(ps -ef | grep 'mongodb' | grep -v 'grep')" == "" ]; then
  echo "Starting MongoDB database"

  mkdir -p $HOME/mongodb/log
  mongod --dbpath $HOME/mongodb --logpath $HOME/mongodb/mongodb.log --logappend &
  echo "Started MongoDB database"
else
  echo "MongoDB is already running"
fi

echo "Installing npm modules..."
npm install
echo "Done installing npm modules"

echo "Setup complete"


text:
/*
 *   This file is part of SGEA - Sistema de Gestão de Eventos Acadêmicos - TADS IFNMG Campus Januária.
 *
 *   SGEA is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   SGEA is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with SGEA.  If not, see <http://www.gnu.org/licenses/>.
 */
package br.edu.ifnmg.GerenciamentoEventos.Infraestrutura.Dados;

import br.edu.ifnmg.DataAccess.DAOGenerico;
import br.edu.ifnmg.GerenciamentoEventos.DomainModel.Inscricao;
import br.edu.ifnmg.DomainModel.Pessoa;
import br.edu.ifnmg.GerenciamentoEventos.DomainModel.Questionario;
import br.edu.ifnmg.GerenciamentoEventos.DomainModel.QuestionarioResposta;
import br.edu.ifnmg.GerenciamentoEventos.DomainModel.Servicos.QuestionarioRespostaRepositorio;
import java.util.List;
import javax.ejb.Singleton;
import javax.ejb.Stateless;

/**
 *
 * @author petronio
 */
@Singleton
public class QuestionarioRespostaDAO
        extends DAO<QuestionarioResposta>
        implements QuestionarioRespostaRepositorio {

    public QuestionarioRespostaDAO() {
        super(QuestionarioResposta.class);
    }

    @Override
    public List<QuestionarioResposta> Buscar(QuestionarioResposta obj) {
                IgualA("id", obj.getId())
                .IgualA("pessoa", obj.getPessoa())
                .IgualA("questionario", obj.getQuestionario());
        return Buscar();
    }

    @Override
    public QuestionarioResposta Abrir(Pessoa p, Questionario q) {
                IgualA("pessoa", p)
                .IgualA("questionario", q);
        return Abrir();
    }

    @Override
    public QuestionarioResposta Abrir(Inscricao i) {
        return IgualA("inscricao", i).Abrir();
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: lucius
 * Date: 24.08.16
 * Time: 19:34
 */

namespace HitobitoConnector;

class RetrieveDataJob
{
    /**
     * @var HitobitoConnectorInterface
     */
    protected $connector;
    /**
     * @var ResultSetInterface
     */
    protected $resultset;
    public function __construct(HitobitoConnectorInterface $connector, ResultSetInterface $resultset)
    {
        $this->connector = $connector;
        $this->resultset = $resultset;
    }

    public function retrieveData(){

        //log in add logged in person to resultset
        $this->connector->sendAuth();

        $loggedInPerson = $this->connector->getAuthenticatedPerson();

        $this->resultset->addPerson($loggedInPerson);

    }

}


text:
/*
 * This file is subject to the terms of the GFX License. If a copy of
 * the license was not distributed with this file, you can obtain one at:
 *
 *              http://ugfx.org/license.html
 */

#ifndef GAUDIO_PLAY_CONFIG_H
#define GAUDIO_PLAY_CONFIG_H

#if GFX_USE_GAUDIO && GAUDIO_NEED_PLAY

/*===========================================================================*/
/* Driver hardware support.                                                  */
/*===========================================================================*/

/* Note:
 * 	The VS1053 has an internal processor which can decode many file formats directly.
 * 	If you want to use anything other than raw PCM then you should use GAUDIO_PLAY_FORMAT_FILE and pipe
 * 	the entire file as if it was sound data. It doesn't matter if you choose the mono or stereo channel
 * 	as the codec chip automatically detects the real format itself.
 * 	No testing is made of the file format - if there is an error it can only be detected by the codec chip
 * 	and its behaviour is undefined (we haven't tested).
 * 	Note that some formats require a firmware patch to be installed to play correctly.
 * 	In this case define VS1053_FIRMWARE_PATCH as TRUE in your gfxconf.h file and include the patch file
 * 	in your project directory. The patch file MUST be called "vs1053_patch.plg".
 */
#define GAUDIO_PLAY_MAX_SAMPLE_FREQUENCY		48000
#define GAUDIO_PLAY_NUM_FORMATS					3
#define GAUDIO_PLAY_FORMAT1						ARRAY_DATA_16BITSIGNED
#define GAUDIO_PLAY_FORMAT2						ARRAY_DATA_8BITUNSIGNED
#define GAUDIO_PLAY_FORMAT3						ARRAY_DATA_UNKNOWN
#define GAUDIO_PLAY_FORMAT_FILE					ARRAY_DATA_UNKNOWN
#define GAUDIO_PLAY_NUM_CHANNELS				2
#define GAUDIO_PLAY_CHANNEL0_IS_STEREO			FALSE
#define GAUDIO_PLAY_CHANNEL1_IS_STEREO			TRUE
#define	GAUDIO_PLAY_MONO						0
#define	GAUDIO_PLAY_STEREO						1

#endif	/* GFX_USE_GAUDIO && GAUDIO_NEED_PLAY */

#endif	/* GAUDIO_PLAY_CONFIG_H */


text:
using System.Collections.Generic;
using System.Linq;

namespace Arma3BEClient.Common.Extensions
{
    public static class EnumerableExtensions
    {
        public static IEnumerable<T[]> Paged<T>(this IEnumerable<T> list, int pageSize)
        {
            var result = new List<T[]>();

            var page = new List<T>();

            foreach (var item in list)
            {
                page.Add(item);
                if (page.Count == pageSize)
                {
                    result.Add(page.ToArray());
                    page = new List<T>();
                }
            }

            if (page.Any())
            {
                result.Add(page.ToArray());
            }

            return result;
        }
    }
}


text:
#include <errno.h>
#include <malloc.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <sys/fcntl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/unistd.h>

#include <psptypes.h>
#include <pspiofilemgr.h>
#include <pspmodulemgr.h>
#include <pspsysmem.h>
#include <pspthreadman.h>
#include <psputils.h>

/* These functions aren't exposed in any public headers, and they probably don't need to be. */
int sceKernelStdin(void);
int sceKernelStdout(void);
int sceKernelStderr(void);

extern char * __psp_argv_0;
extern int __psp_cwd_initialized;
extern char __psp_cwd[MAXPATHLEN + 1];
extern void __psp_init_cwd(void);
extern int __psp_path_absolute(const char *in, char *out, int len);

/* If we're being built for PSPSDK's libc this function isn't defined. */
#ifdef F_glue_gettimeofday
int gettimeofday(struct timeval *tp, void *tzp)
{
	return sceKernelLibcGettimeofday(tp, tzp);
}
#endif

#if defined(F_clock) || defined(F_glue_clock)
clock_t clock(void)
{
	return sceKernelLibcClock();
}
#endif

#if defined(F_time) || defined(F_glue_time)
time_t time(time_t *t)
{
	return sceKernelLibcTime(t);
}
#endif

/* PSP-compatible sbrk(). */
#if defined(F__sbrk) || defined(F_glue__sbrk)

#define DEFAULT_PRX_HEAP_SIZE_KB 64

/* If defined it specifies the desired size of the heap, in KB. */
extern unsigned int sce_newlib_heap_kb_size __attribute__((weak));
extern int __pspsdk_is_prx __attribute__((weak));

/* UID of the memory block that represents the heap. */
static SceUID __psp_heap_blockid;

void * _sbrk(ptrdiff_t incr)
{
	static void * heap_bottom = NULL;
	static void * heap_top = NULL;
	static void * heap_ptr = NULL;

	/* Has our heap been initialized? */
	if (heap_bottom == NULL) {
		/* No, initialize the heap. */
		SceSize heap_size = (SceSize) -1;

		if (&sce_newlib_heap_kb_size != NULL) {
			heap_size = sce_newlib_heap_kb_size;
		} else if(&__pspsdk_is_prx != NULL) {
			heap_size = DEFAULT_PRX_HEAP_SIZE_KB;
		}

		if (heap_size == (unsigned int) -1) {
			heap_size = sceKernelMaxFreeMemSize();
		} else {
			heap_size *= 1024;
		}

		if (heap_size != 0) {
			__psp_heap_blockid = sceKernelAllocPartitionMemory(2, "block", PSP_SMEM_Low, heap_size, NULL);
			if (__psp_heap_blockid > 0) {
				heap_bottom = sceKernelGetBlockHeadAddr(__psp_heap_blockid);
				heap_ptr = heap_bottom;
				heap_top = (unsigned char *) heap_bottom + heap_size;
			}
		}
	}

	void * heap_addr = (void *) -1;
	void * next_heap_ptr = (void *) ((ptrdiff_t) heap_ptr + incr);
	if ((heap_bottom != NULL) && (next_heap_ptr >= heap_bottom) && (next_heap_ptr < heap_top)) {
		heap_addr = heap_ptr;
		heap_ptr = next_heap_ptr;
	}

	return heap_addr;
}

/* Free the heap. */
int __psp_free_heap(void)
{
	if (__psp_heap_blockid > 0) {
		return sceKernelFreePartitionMemory(__psp_heap_blockid);
	}

	return __psp_heap_blockid;
}
#endif

#if defined(F__exit) || defined(F_glue__exit)
extern int sce_newlib_nocreate_thread_in_start __attribute__((weak));

extern int __psp_free_heap(void);

void _exit(int status)
{
	if (&sce_newlib_nocreate_thread_in_start != NULL) {
		/* Free the heap created by _sbrk(). */
		__psp_free_heap();

		sceKernelSelfStopUnloadModule(1, 0, NULL);
	} else {
		if (status == 0) {
			/* Free the heap created by _sbrk(). */
			__psp_free_heap();
		}

		sceKernelExitThread(status);
	}

	while (1) ;
}
#endif

/* newlib's errno.h wants a function that returns a pointer to errno. */
#ifdef F_glue___errno
#undef errno

int errno;

/* TODO: Should this be made reentrant (wrapping interrupt disable/enable
   around it should do it)? */
int * __errno(void)
{
	return &errno;
}
#endif


text:
package com.siyeh.igtest.numeric;

public class ConstantMathCallInspection{
    public void foo()
    {
        final double v = Math.sin(0.0);
        final double v1 = Math.asin(1.0);
        final long round = Math.round(2.5);
        long belowMin = Math.abs((long) Integer.MIN_VALUE + 1L);
    }
}


text:
package de.uni.freiburg.iig.telematik.secsy.logic.transformation.transformer.trace;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import de.invation.code.toval.misc.SetUtils;
import de.invation.code.toval.properties.PropertyException;
import de.invation.code.toval.validate.ParameterException;
import de.invation.code.toval.validate.Validate;
import de.uni.freiburg.iig.telematik.secsy.logic.generator.LogEntryGenerator;
import de.uni.freiburg.iig.telematik.secsy.logic.generator.log.SimulationLogEntry;
import de.uni.freiburg.iig.telematik.secsy.logic.transformation.TraceTransformerEvent;
import de.uni.freiburg.iig.telematik.secsy.logic.transformation.TraceTransformerResult;
import de.uni.freiburg.iig.telematik.secsy.logic.transformation.transformer.properties.AbstractTransformerProperties;
import de.uni.freiburg.iig.telematik.secsy.logic.transformation.transformer.properties.ObfuscationTransformerProperties;
import de.uni.freiburg.iig.telematik.secsy.logic.transformation.transformer.trace.abstr.AbstractMultipleTraceTransformer;
import de.uni.freiburg.iig.telematik.sewol.log.EntryField;
import de.uni.freiburg.iig.telematik.sewol.log.LockingException;
import de.uni.freiburg.iig.telematik.sewol.log.LogTrace;

public class ObfuscationTransformer extends AbstractMultipleTraceTransformer<ObfuscationTransformerProperties, ObfuscationTransformer> {

	private static final long serialVersionUID = 7410869336999582929L;

	private final String CUSTOM_SUCCESS_FORMAT = "entry %s, field %s: %s -> %s";

	public static final String hint = "
An obfuscation transformer removes values of specific fields" +
									  "from events of a process trace. transformer parameterization" +
									  "allows to specify a set of log entry fields that may be" +
									  "removed. The number of appliances per trace is randomly" +
									  "chosen with an adjustable upper bound.
";

	LogEntryGenerator entryGenerator = null;
	Set<EntryField> excludedFields = new HashSet<EntryField>(Arrays.asList(ObfuscationTransformerProperties.defaultExcludedFields));

	public ObfuscationTransformer(ObfuscationTransformerProperties properties) throws PropertyException {
		super(properties);
		excludedFields = properties.getExcludedFields();
	}

	public ObfuscationTransformer(Double activationProbability, Integer maxAppliance){
		super(activationProbability, maxAppliance);
	}

	public ObfuscationTransformer() {
		super();
	}

	/**
	 * Sets the transformer-specific properties and requires the following values:

	 *

	 *
Set&ltEntryField&gt: Excluded Fields.

	 * Fields for which no obfuscation is allowed.

	 *

	 * @see EntryField
	 * @see {@link #setExcludedFields(Set)}
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void setProperties(Object[] properties) throws Exception {
		Validate.notNull(properties);
		Validate.notEmpty(properties);
		if(properties.length != 1)
			throw new ParameterException("Wrong number of parameters. Expected 1, but got " + properties.length);
		Validate.noNullElements(properties);
		Validate.type(properties[0], Set.class);
		Set<EntryField> excludedFields = null;
		try {
			excludedFields = (Set<EntryField>) properties[0];
		} catch(Exception e){
			throw new ParameterException("Wrong parameter type: " + e.getMessage());
		}
		setExcludedFields(excludedFields);
	}

	public Set<EntryField> getExcludedFields(){
		return Collections.unmodifiableSet(excludedFields);
	}

	public void setExcludedFields(Set<EntryField> excludedFields){
		Validate.notNull(excludedFields);
		Validate.noNullElements(excludedFields);
		this.excludedFields.clear();
		this.excludedFields.addAll(excludedFields);
	}

	@Override
	protected TraceTransformerResult applyTransformation(TraceTransformerEvent event){
		Validate.notNull(event);
		entryGenerator = (LogEntryGenerator) event.sender;
		return super.applyTransformation(event);
	}

	@Override
	protected boolean applyEntryTransformation(LogTrace<SimulationLogEntry> trace, SimulationLogEntry entry, TraceTransformerResult transformerResult){
		//Find all fields that can be obfuscated
		List<EntryField> possibleFields = new ArrayList<EntryField>();
		possibleFields.remove(EntryField.ORIGINATOR_CANDIDATES);
		for(EntryField field: EntryField.values()){
			if(!entry.isFieldLocked(field) && entryGenerator.providesLogInformation(field))
				possibleFields.add(field);
		}
		possibleFields.removeAll(excludedFields);
		if(possibleFields.isEmpty())
			return false;

		//Try to apply an obfuscation
		Obfuscation obfuscation;
		String activityName = entry.getActivity();
		Collections.shuffle(possibleFields);
		for(EntryField field: possibleFields){
			obfuscation = applyObfuscation(field, entry);
			if(obfuscation.isSuccess()){
				addMessageToResult(getSuccessMessage(activityName, field, obfuscation.getOldValue(), obfuscation.getNewValue()), transformerResult);
				entry.lockField(field, "Transformer-Enforcement: Obfuscation");
				return true;
			}
		}
		return false;
	}

	protected Obfuscation applyObfuscation(EntryField field, SimulationLogEntry entry){
		Validate.notNull(field);
		Validate.notNull(entry);
		Obfuscation result = new Obfuscation(field, entry.getFieldValue(field));
		if(appliancePossible(field, entry) && setNewValueFor(field, entry))
			result.setNewValue(entry.getFieldValue(field));
		return result;

	}

	protected boolean appliancePossible(EntryField field, SimulationLogEntry entry){
		Validate.notNull(field);
		Validate.notNull(entry);
		switch (field) {
		case ACTIVITY:
			return entry.getActivity() != null;
		case ORIGINATOR:
			return entry.getOriginator() != null;
		case EVENTTYPE:
			return entry.getEventType() != null;
		case DATA:
			return !entry.getDataAttributes().isEmpty();
		default:
			return false;
		}
	}

	protected boolean setNewValueFor(EntryField field, SimulationLogEntry entry){
		Validate.notNull(field);
		Validate.notNull(entry);
		try{
			switch (field) {
			case ACTIVITY:
				entry.setActivity(null);
				return true;
			case ORIGINATOR:
				entry.removeAllOriginatorCandidates();
				return true;
			case EVENTTYPE:
				entry.setEventType(null);
				return true;
			case DATA:
				entry.removeDataAttribute(SetUtils.getRandomElement(entry.getDataAttributes()));
				return true;
			default:
				return false;
			}
		} catch (LockingException e) {
			return false;
		}
	}

	private String getSuccessMessage(String activity, EntryField field, Object oldValue, Object newValue){
		return getNoticeMessage(String.format(CUSTOM_SUCCESS_FORMAT, activity, field, oldValue, newValue));
	}

	@Override
	public List<EntryField> requiredEntryFields() {
		return new ArrayList<EntryField>();
	}

    @Override
    protected ObfuscationTransformerProperties newProperties() {
        return new ObfuscationTransformerProperties();
    }

	protected class Obfuscation{
		private EntryField field;
		private Object oldValue;
		private Object newValue;
		private boolean success;

		public Obfuscation(EntryField field, Object oldValue, Object newValue){
			Validate.notNull(field);
			this.field = field;
			this.oldValue = oldValue;
			setNewValue(newValue);
		}

		public Obfuscation(EntryField field, Object oldValue){
			Validate.notNull(field);
			this.field = field;
			this.oldValue = oldValue;
			this.newValue = oldValue;
			success = false;
		}

		public EntryField getField() {
			return field;
		}

		public Object getOldValue() {
			return oldValue;
		}

		public Object getNewValue() {
			return newValue;
		}

		public boolean isSuccess() {
			return success;
		}

		public void setNewValue(Object newValue) {
			this.newValue = newValue;
			success = !oldValue.equals(newValue);
			if(oldValue instanceof Collection && newValue instanceof Collection){
				Collection<?> oldColl = (Collection<?>) oldValue;
				Collection<?> newColl = (Collection<?>) newValue;
				success = !oldColl.containsAll(newColl) || !newColl.containsAll(oldColl);
			}
		}

	}

	@Override
	protected void fillProperties(ObfuscationTransformerProperties properties) throws PropertyException {
		super.fillProperties(properties);
		properties.setExcludedFields(excludedFields);
	}

	@Override
	public String getHint() {
		return hint;
	}

	@Override
	public boolean requiresTimeGenerator() {
		return false;
	}

	@Override
	public boolean requiresContext() {
		return false;
	}

}


text:
from django.forms import ChoiceField, Field, Form, Select
from django.test import SimpleTestCase

class BasicFieldsTests(SimpleTestCase):

    def test_field_sets_widget_is_required(self):
        self.assertTrue(Field(required=True).widget.is_required)
        self.assertFalse(Field(required=False).widget.is_required)

    def test_cooperative_multiple_inheritance(self):
        class A(object):
            def __init__(self):
                self.class_a_var = True
                super(A, self).__init__()

        class ComplexField(Field, A):
            def __init__(self):
                super(ComplexField, self).__init__()

        f = ComplexField()
        self.assertTrue(f.class_a_var)

    def test_field_deepcopies_widget_instance(self):
        class CustomChoiceField(ChoiceField):
            widget = Select(attrs={'class': 'my-custom-class'})

        class TestForm(Form):
            field1 = CustomChoiceField(choices=[])
            field2 = CustomChoiceField(choices=[])

        f = TestForm()
        f.fields['field1'].choices = [('1', '1')]
        f.fields['field2'].choices = [('2', '2')]
        self.assertEqual(f.fields['field1'].widget.choices, [('1', '1')])
        self.assertEqual(f.fields['field2'].widget.choices, [('2', '2')])

class DisabledFieldTests(SimpleTestCase):
    def test_disabled_field_has_changed_always_false(self):
        disabled_field = Field(disabled=True)
        self.assertFalse(disabled_field.has_changed('x', 'y'))


text:
namespace llvm {
namespace object {

typedef MachOObject::LoadCommandInfo LoadCommandInfo;

class MachOObjectFile : public ObjectFile {
public:
  MachOObjectFile(MemoryBuffer *Object, MachOObject *MOO, error_code &ec);

  virtual symbol_iterator begin_symbols() const;
  virtual symbol_iterator end_symbols() const;
  virtual symbol_iterator begin_dynamic_symbols() const;
  virtual symbol_iterator end_dynamic_symbols() const;
  virtual library_iterator begin_libraries_needed() const;
  virtual library_iterator end_libraries_needed() const;
  virtual section_iterator begin_sections() const;
  virtual section_iterator end_sections() const;

  virtual uint8_t getBytesInAddress() const;
  virtual StringRef getFileFormatName() const;
  virtual unsigned getArch() const;
  virtual StringRef getLoadName() const;

  MachOObject *getObject() { return MachOObj; }

  static inline bool classof(const Binary *v) {
    return v->isMachO();
  }
  static inline bool classof(const MachOObjectFile *v) { return true; }

protected:
  virtual error_code getSymbolNext(DataRefImpl Symb, SymbolRef &Res) const;
  virtual error_code getSymbolName(DataRefImpl Symb, StringRef &Res) const;
  virtual error_code getSymbolFileOffset(DataRefImpl Symb, uint64_t &Res) const;
  virtual error_code getSymbolAddress(DataRefImpl Symb, uint64_t &Res) const;
  virtual error_code getSymbolSize(DataRefImpl Symb, uint64_t &Res) const;
  virtual error_code getSymbolNMTypeChar(DataRefImpl Symb, char &Res) const;
  virtual error_code getSymbolFlags(DataRefImpl Symb, uint32_t &Res) const;
  virtual error_code getSymbolType(DataRefImpl Symb, SymbolRef::Type &Res) const;
  virtual error_code getSymbolSection(DataRefImpl Symb,
                                      section_iterator &Res) const;

  virtual error_code getSectionNext(DataRefImpl Sec, SectionRef &Res) const;
  virtual error_code getSectionName(DataRefImpl Sec, StringRef &Res) const;
  virtual error_code getSectionAddress(DataRefImpl Sec, uint64_t &Res) const;
  virtual error_code getSectionSize(DataRefImpl Sec, uint64_t &Res) const;
  virtual error_code getSectionContents(DataRefImpl Sec, StringRef &Res) const;
  virtual error_code getSectionAlignment(DataRefImpl Sec, uint64_t &Res) const;
  virtual error_code isSectionText(DataRefImpl Sec, bool &Res) const;
  virtual error_code isSectionData(DataRefImpl Sec, bool &Res) const;
  virtual error_code isSectionBSS(DataRefImpl Sec, bool &Res) const;
  virtual error_code isSectionRequiredForExecution(DataRefImpl Sec,
                                                   bool &Res) const;
  virtual error_code isSectionVirtual(DataRefImpl Sec, bool &Res) const;
  virtual error_code isSectionZeroInit(DataRefImpl Sec, bool &Res) const;
  virtual error_code sectionContainsSymbol(DataRefImpl DRI, DataRefImpl S,
                                           bool &Result) const;
  virtual relocation_iterator getSectionRelBegin(DataRefImpl Sec) const;
  virtual relocation_iterator getSectionRelEnd(DataRefImpl Sec) const;

  virtual error_code getRelocationNext(DataRefImpl Rel,
                                       RelocationRef &Res) const;
  virtual error_code getRelocationAddress(DataRefImpl Rel,
                                          uint64_t &Res) const;
  virtual error_code getRelocationOffset(DataRefImpl Rel,
                                         uint64_t &Res) const;
  virtual error_code getRelocationSymbol(DataRefImpl Rel,
                                         SymbolRef &Res) const;
  virtual error_code getRelocationType(DataRefImpl Rel,
                                       uint64_t &Res) const;
  virtual error_code getRelocationTypeName(DataRefImpl Rel,
                                           SmallVectorImpl<char> &Result) const;
  virtual error_code getRelocationAdditionalInfo(DataRefImpl Rel,
                                                 int64_t &Res) const;
  virtual error_code getRelocationValueString(DataRefImpl Rel,
                                           SmallVectorImpl<char> &Result) const;
  virtual error_code getRelocationHidden(DataRefImpl Rel, bool &Result) const;

  virtual error_code getLibraryNext(DataRefImpl LibData, LibraryRef &Res) const;
  virtual error_code getLibraryPath(DataRefImpl LibData, StringRef &Res) const;

private:
  MachOObject *MachOObj;
  mutable uint32_t RegisteredStringTable;
  typedef SmallVector<DataRefImpl, 1> SectionList;
  SectionList Sections;

  void moveToNextSection(DataRefImpl &DRI) const;
  void getSymbolTableEntry(DataRefImpl DRI,
                           InMemoryStruct<macho::SymbolTableEntry> &Res) const;
  void getSymbol64TableEntry(DataRefImpl DRI,
                          InMemoryStruct<macho::Symbol64TableEntry> &Res) const;
  void moveToNextSymbol(DataRefImpl &DRI) const;
  void getSection(DataRefImpl DRI, InMemoryStruct<macho::Section> &Res) const;
  void getSection64(DataRefImpl DRI,
                    InMemoryStruct<macho::Section64> &Res) const;
  void getRelocation(DataRefImpl Rel,
                     InMemoryStruct<macho::RelocationEntry> &Res) const;
  std::size_t getSectionIndex(DataRefImpl Sec) const;

  void printRelocationTargetName(InMemoryStruct<macho::RelocationEntry>& RE,
                                 raw_string_ostream &fmt) const;
};

}
}

#endif


text:
package br.com.objectos.core.system;

import static org.testng.Assert.assertEquals;

import org.testng.Assert;
import org.testng.annotations.Test;

public class LineSeparatorTest implements OperatingSystemVisitor<String, String[]> {

  @Test
  public void join() {
    assertEquals(LineSeparator.join(), "");

    assertEquals(LineSeparator.join("xpto"), "xpto");

    String[] value = {"ab", "cd", "ef"};

    assertEquals(
        LineSeparator.join(value),
        OperatingSystem.get().acceptOperatingSystemVisitor(this, value)
    );

    try {
      value = null;

      LineSeparator.join(value);

      Assert.fail("expected exception was not thrown");
    } catch (NullPointerException expected) {

    }

    try {
      value = new String[] {null};

      LineSeparator.join(value);

      Assert.fail("expected exception was not thrown");
    } catch (NullPointerException expected) {

    }

    try {
      value = new String[] {"a", null, "b"};

      LineSeparator.join(value);

      Assert.fail("expected exception was not thrown");
    } catch (NullPointerException expected) {

    }
  }

  @Override
  public final String visitLinux(Linux os, String[] p) {
    StringBuilder s;
    s = new StringBuilder();

    s.append(p[0]);

    for (int i = 1; i < p.length; i++) {
      s.append('\n');

      s.append(p[i]);
    }

    return s.toString();
  }

  @Override
  public final String visitUnsupportedOs(UnsupportedOperatingSystem os, String[] p) {
    throw new UnsupportedOperationException();
  }

}


text:
An R fixture that specifies packages using the `install.R` filename convention.

```r exec
# Test that we can import the `data.table` package
library(data.table)
```


text:
<?php

class ImageController extends PwBaseController
{
    public function run()
    {
        $id = (int) $this->getInput('id', 'get');
        if (! $id) {
            exit();
        }
        if (! ini_get('safe_mode')) {
            ignore_user_abort(true);
            set_time_limit(0);
        }
        $image = $this->_getImageService()->get($id);
        header('Cache-control: max-age=600');
        header('Location: '.$image);
        exit;
    }

    private function _getImageService()
    {
        return Wekit::load('design.srv.PwDesignAsynImageService');
    }
}


text:
echo off

set devenv=C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.com
set msbuild=C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\MSBuild.exe

"%msbuild%" /nologo /verbosity:minimal /t:Clean,Build /p:Configuration=Release /p:Platform="Any CPU" WixSharp.Suite.sln
"%msbuild%" /nologo /verbosity:minimal /t:Clean,Build /p:Configuration=Release /p:Platform="Any CPU" WixSharp.Suite.Lab.sln

pause


text:
/**
 * An extension of the capabilities in "heartbeat.h" to include monitoring
 * program accuracy.
 *
 * @author Hank Hoffmann
 * @author Connor Imes
 */
#ifndef _HEARTBEAT_ACCURACY_H_
#define _HEARTBEAT_ACCURACY_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "heartbeat-accuracy-types.h"
#include "heartbeat.h"

/**
 * Registers a heartbeat
 *
 * @param hb pointer to heartbeat_t
 * @param tag integer
 * @param accuracy double
 */
int64_t heartbeat_acc(heartbeat_t* hb,
                      int tag,
                      double accuracy);

/**
 * Returns the minimum desired accuracy
 *
 * @param hb pointer to heartbeat_t
 * @return the minimum desired accuracy (double)
 */
double hb_get_min_accuracy(heartbeat_t volatile * hb);

/**
 * Returns the maximum desired accuracy
 *
 * @param hb pointer to heartbeat_t
 * @return the maximum desired accuracy (double)
 */
double hb_get_max_accuracy(heartbeat_t volatile * hb);

/**
 * Returns the accuracy over the life of the entire application
 *
 * @param hb pointer to heartbeat_t
 * @return the accuracy (double) over the entire life of the application
 */
double hb_get_global_accuracy(heartbeat_t volatile * hb);

/**
 * Returns the accuracy over the last window (as specified to init)
 * heartbeats
 *
 * @param hb pointer to heartbeat_t
 * @return the accuracy (double) over the last window
 */
double hb_get_windowed_accuracy(heartbeat_t volatile * hb);

/**
 * Returns the accuracy for the last heartbeat.
 *
 * @param hb pointer to heartbeat_t
 * @return the accuracy (double) for the last heartbeat
 */
double hb_get_instant_accuracy(heartbeat_t volatile * hb);

/**
 * Returns the global accuracy recorded in this record.
 *
 * @param hbr
 */
double hbr_get_global_accuracy(heartbeat_record_t volatile * hbr);

/**
 * Returns the window accuracy recorded in this record.
 *
 * @param hbr
 */
double hbr_get_window_accuracy(heartbeat_record_t volatile * hbr);

/**
 * Returns the instant accuracy recorded in this record.
 *
 * @param hbr
 */
double hbr_get_instant_accuracy(heartbeat_record_t volatile * hbr);

#ifdef __cplusplus
}
#endif

#endif


text:
/********************************************************************************
** Form generated from reading UI file 'aboutdialog.ui'
**
** Created: Sun Dec 22 21:54:28 2013
**      by: Qt User Interface Compiler version 4.8.4
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_ABOUTDIALOG_H
#define UI_ABOUTDIALOG_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QDialog>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QSpacerItem>
#include <QtGui/QVBoxLayout>

QT_BEGIN_NAMESPACE

class Ui_AboutDialog
{
public:
    QHBoxLayout *horizontalLayout_2;
    QLabel *label_4;
    QVBoxLayout *verticalLayout_2;
    QSpacerItem *verticalSpacer_2;
    QHBoxLayout *horizontalLayout;
    QLabel *label;
    QLabel *versionLabel;
    QSpacerItem *horizontalSpacer;
    QLabel *label_2;
    QSpacerItem *verticalSpacer;
    QDialogButtonBox *buttonBox;

    void setupUi(QDialog *AboutDialog)
    {
        if (AboutDialog->objectName().isEmpty())
            AboutDialog->setObjectName(QString::fromUtf8("AboutDialog"));
        AboutDialog->resize(593, 331);
        horizontalLayout_2 = new QHBoxLayout(AboutDialog);
        horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
        label_4 = new QLabel(AboutDialog);
        label_4->setObjectName(QString::fromUtf8("label_4"));
        QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Ignored);
        sizePolicy.setHorizontalStretch(0);
        sizePolicy.setVerticalStretch(0);
        sizePolicy.setHeightForWidth(label_4->sizePolicy().hasHeightForWidth());
        label_4->setSizePolicy(sizePolicy);
        label_4->setPixmap(QPixmap(QString::fromUtf8(":/images/about")));

        horizontalLayout_2->addWidget(label_4);

        verticalLayout_2 = new QVBoxLayout();
        verticalLayout_2->setObjectName(QString::fromUtf8("verticalLayout_2"));
        verticalSpacer_2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);

        verticalLayout_2->addItem(verticalSpacer_2);

        horizontalLayout = new QHBoxLayout();
        horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
        label = new QLabel(AboutDialog);
        label->setObjectName(QString::fromUtf8("label"));
        label->setCursor(QCursor(Qt::IBeamCursor));
        label->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);

        horizontalLayout->addWidget(label);

        versionLabel = new QLabel(AboutDialog);
        versionLabel->setObjectName(QString::fromUtf8("versionLabel"));
        versionLabel->setCursor(QCursor(Qt::IBeamCursor));
        versionLabel->setText(QString::fromUtf8("0.3.666-beta"));
        versionLabel->setTextFormat(Qt::RichText);
        versionLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);

        horizontalLayout->addWidget(versionLabel);

        horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);

        horizontalLayout->addItem(horizontalSpacer);

        verticalLayout_2->addLayout(horizontalLayout);

        label_2 = new QLabel(AboutDialog);
        label_2->setObjectName(QString::fromUtf8("label_2"));
        label_2->setCursor(QCursor(Qt::IBeamCursor));
        label_2->setWordWrap(true);
        label_2->setTextInteractionFlags(Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse);

        verticalLayout_2->addWidget(label_2);

        verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);

        verticalLayout_2->addItem(verticalSpacer);

        buttonBox = new QDialogButtonBox(AboutDialog);
        buttonBox->setObjectName(QString::fromUtf8("buttonBox"));
        buttonBox->setOrientation(Qt::Horizontal);
        buttonBox->setStandardButtons(QDialogButtonBox::Ok);

        verticalLayout_2->addWidget(buttonBox);

        horizontalLayout_2->addLayout(verticalLayout_2);

        retranslateUi(AboutDialog);
        QObject::connect(buttonBox, SIGNAL(accepted()), AboutDialog, SLOT(accept()));
        QObject::connect(buttonBox, SIGNAL(rejected()), AboutDialog, SLOT(reject()));

        QMetaObject::connectSlotsByName(AboutDialog);
    } // setupUi

    void retranslateUi(QDialog *AboutDialog)
    {
        AboutDialog->setWindowTitle(QApplication::translate("AboutDialog", "About MintCoin", 0, QApplication::UnicodeUTF8));
        label->setText(QApplication::translate("AboutDialog", "<b>MintCoin</b> version", 0, QApplication::UnicodeUTF8));
        label_2->setText(QApplication::translate("AboutDialog", "\n"
"          Copyright \302\251 2009-2012 Mintcoin Developers\n"
"          Copyright \302\251 2011-2012 Litecoin Developers\n"
"          Copyright \302\251 2013 MintCoin Developers\n"
"\n"
"          This is experimental software.\n"
"\n"
"          Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.\n"
"\n"
"          This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.\n"
"\n"
"          Offical forum: not exist\n"
"        ", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class AboutDialog: public Ui_AboutDialog {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_ABOUTDIALOG_H


text:
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var srange = require( './srange.js' );
var ndarray = require( './ndarray.js' );

// MAIN //

setReadOnly( srange, 'ndarray', ndarray );

// EXPORTS //

module.exports = srange;


text:
{-# OPTIONS_HADDOCK hide, not-home #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}

module Control.Monad.TestFixture.TH.Internal.TypesQuasi (ts) where

import Control.Monad ((<=<))
import Language.Haskell.Exts.Lexer
import Language.Haskell.Exts.Parser
import Language.Haskell.Exts.SrcLoc
import Language.Haskell.Meta.Syntax.Translate (toType)
import Language.Haskell.TH.Instances ()
import Language.Haskell.TH.Syntax hiding (Loc)
import Language.Haskell.TH.Quote

-- | A quasi-quoter like the built-in @[t| ... |]@ quasi-quoter, but produces
-- a /list/ of types instead of a single type. Each type should be separated by
-- a comma.
--
-- >>> [ts| Bool, (), String |]
-- [ConT GHC.Types.Bool,ConT GHC.Tuple.(),ConT GHC.Base.String]
-- >>> [ts| Maybe Int, Monad m |]
-- [AppT (ConT GHC.Base.Maybe) (ConT GHC.Types.Int),AppT (ConT GHC.Base.Monad) (VarT m)]
ts :: QuasiQuoter
ts = QuasiQuoter
  { quoteExp = \str -> case parseTypesSplitOnCommas str of
      ParseOk tys -> lift =<< mapM resolveTypeNames tys
      ParseFailed _ msg -> fail msg
  , quotePat = error "ts can only be used in an expression context"
  , quoteType = error "ts can only be used in an expression context"
  , quoteDec = error "ts can only be used in an expression context"
  }

parseTypesSplitOnCommas :: String -> ParseResult [Type]
parseTypesSplitOnCommas = fmap (map toType) . mapM parseType <=< lexSplitOnCommas

lexSplitOnCommas :: String -> ParseResult [String]
lexSplitOnCommas str = splitOnSrcSpans str <$> lexSplittingCommas str

splitOnSrcSpans :: String -> [SrcSpan] -> [String]
splitOnSrcSpans str [] = [str]
splitOnSrcSpans str spans@(x:xs) = case x of
  SrcSpan { srcSpanStartLine = line, srcSpanStartColumn = col }
    | line > 1 ->
      let (l, _:ls) = break (== '\n') str
          (r:rs) = splitOnSrcSpans ls (map advanceLine spans)
      in (l ++ "\n" ++ r) : rs
    | col > 1 ->
      let (currentLs, nextLs) = span ((== line) . srcSpanStartLine) spans
          (c:cs) = str
          (r:rs) = splitOnSrcSpans cs (map advanceColumn currentLs ++ nextLs)
      in (c : r) : rs
    | otherwise ->
      let (currentLs, nextLs) = span ((== line) . srcSpanStartLine) xs
          (_:cs) = str
      in "" : splitOnSrcSpans cs (map advanceColumn currentLs ++ nextLs)

advanceLine :: SrcSpan -> SrcSpan
advanceLine s@SrcSpan { srcSpanStartLine = line } = s { srcSpanStartLine = line - 1 }

advanceColumn :: SrcSpan -> SrcSpan
advanceColumn s@SrcSpan { srcSpanStartColumn = col } = s { srcSpanStartColumn = col - 1 }

lexSplittingCommas :: String -> ParseResult [SrcSpan]
lexSplittingCommas = fmap splittingCommas . lexTokenStream

splittingCommas :: [Loc Token] -> [SrcSpan]
splittingCommas = map loc . go
  where go [] = []
        go (x@Loc{ unLoc = Comma }:xs) = x : go xs
        go (Loc{ unLoc = LeftParen }:xs) = go $ skipUntil RightParen xs
        go (Loc{ unLoc = LeftSquare }:xs) = go $ skipUntil RightSquare xs
        go (Loc{ unLoc = LeftCurly }:xs) = go $ skipUntil RightCurly xs
        go (_:xs) = go xs

        skipUntil _ [] = []
        skipUntil d (Loc{ unLoc = LeftParen }:xs) = skipUntil d $ skipUntil RightParen xs
        skipUntil d (Loc{ unLoc = LeftSquare }:xs) = skipUntil d $ skipUntil RightSquare xs
        skipUntil d (Loc{ unLoc = LeftCurly }:xs) = skipUntil d $ skipUntil RightCurly xs
        skipUntil d (Loc{ unLoc = t }:xs)
          | t == d    = xs
          | otherwise = skipUntil d xs

resolveTypeNames :: Type -> Q Type
resolveTypeNames (ConT nm) = ConT <$> resolveTypeName nm
resolveTypeNames (ForallT tyVars ctx t) = ForallT tyVars <$> mapM resolveTypeNames ctx <*> resolveTypeNames t
resolveTypeNames (AppT a b) = AppT <$> resolveTypeNames a <*> resolveTypeNames b
resolveTypeNames (SigT t k) = SigT <$> resolveTypeNames t <*> resolveTypeNames k
resolveTypeNames t@VarT{} = return t
resolveTypeNames t@PromotedT{} = return t
resolveTypeNames t@TupleT{} = return t
resolveTypeNames t@UnboxedTupleT{} = return t
resolveTypeNames t@ArrowT{} = return t
resolveTypeNames t@EqualityT = return t
resolveTypeNames t@ListT = return t
resolveTypeNames t@PromotedTupleT{} = return t
resolveTypeNames t@PromotedNilT = return t
resolveTypeNames t@PromotedConsT = return t
resolveTypeNames t@StarT = return t
resolveTypeNames t@ConstraintT = return t
resolveTypeNames t@LitT{} = return t
#if MIN_VERSION_template_haskell(2,11,0)
resolveTypeNames (InfixT a n b) = InfixT <$> resolveTypeNames a <*> resolveTypeName n <*> resolveTypeNames b
resolveTypeNames (UInfixT a n b) = UInfixT <$> resolveTypeNames a <*> resolveTypeName n <*> resolveTypeNames b
resolveTypeNames (ParensT t) = ParensT <$> resolveTypeNames t
resolveTypeNames t@WildCardT = return t
#endif
#if MIN_VERSION_template_haskell(2,12,0)
resolveTypeNames t@UnboxedSumT{} = return t
#endif

resolveTypeName :: Name -> Q Name
resolveTypeName (Name (OccName str) NameS) = lookupTypeName str >>= \case
  Just nm -> return nm
  Nothing -> fail $ "unbound type name '" ++ str ++ "'"
resolveTypeName nm = return nm


text:
import { Injectable } from '@angular/core';
import { Http, RequestOptions, Request, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class HttpClient {

  constructor(private http: Http) {
  }

  wynik: any;
  request(requestConfig: {method: string; url: string; queryParams?: any; data?: any;}): Observable<any> {
    let headers = new Headers();
    headers.append("Content-Type", 'application/json');
    headers.append("Accept", '*/*');
    let tempUrl = '/euslugi-app/rest/';
    let requestOptions = new RequestOptions({
      method: requestConfig.method,
      url: '/' + requestConfig.url,
      headers: headers,
      body: JSON.stringify(requestConfig.data),
      params: requestConfig.queryParams
    });
    return this.http.request(new Request(requestOptions));
  };
}


text:
<!DOCTYPE html>

    <meta charset='utf-8' />
    <meta http-equiv="X-UA-Compatible" content="chrome=1" />
    <meta name="description" content="Poopoo888888.github.io : " />

    <link rel="stylesheet" type="text/css" media="screen" href="stylesheets/bootstrap.min.css">

    <title>Poopoo888888.github.io</title>

揪團王 新建活動

              <form class="form-horizontal" role="form">

                  活動名稱

                    <input type="email" class="form-control" id="inputEmail3" placeholder="Email">

                  活動說明

                  <textarea class="form-control" rows="5"></textarea>

                  受邀人facebook帳號

                    <input type="email" class="form-control" id="inputEmail3" placeholder="Email">

                  選擇候選日期

                    <input type="email" class="form-control" id="inputEmail3" placeholder="Email">

                    <button type="submit" class="btn btn-primary btn-lg">確定</button>

              </form>