text:
<!DOCTYPE html>

	<title>Alex</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat|Open+Sans" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="style.css">

My Work

About

Contact

Jane Smith

Travel Photographer

About Me

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

		          A Place

This is photograph of a place the I visited.

		        	Read More

		          A Place

This is photograph of a place the I visited.

		        	Read More

		          A Place

This is photograph of a place the I visited.

		        	Read More

		          A Place

This is photograph of a place the I visited.

		        	Read More

		          A Place

This is photograph of a place the I visited.

		        	Read More

		          A Place

This is photograph of a place the I visited.

		        	Read More

Blog

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Contact

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
const { errors } = require('arsenal');

const bucketShield = require('./apiUtils/bucket/bucketShield');
const collectCorsHeaders = require('../utilities/collectCorsHeaders');
const { isBucketAuthorized } = require('./apiUtils/authorization/aclChecks');
const metadata = require('../metadata/wrapper');
const { pushMetric } = require('../utapi/utilities');

const requestType = 'bucketOwnerAction';

function bucketDeleteWebsite(authInfo, request, log, callback) {
    const bucketName = request.bucketName;
    const canonicalID = authInfo.getCanonicalID();

    return metadata.getBucket(bucketName, log, (err, bucket) => {
        const corsHeaders = collectCorsHeaders(request.headers.origin,
            request.method, bucket);
        if (err) {
            log.debug('metadata getbucket failed', { error: err });
            return callback(err);
        }
        if (bucketShield(bucket, requestType)) {
            return callback(errors.NoSuchBucket);
        }
        log.trace('found bucket in metadata');

        if (!isBucketAuthorized(bucket, requestType, canonicalID)) {
            log.debug('access denied for user on bucket', {
                requestType,
                method: 'bucketDeleteWebsite',
            });
            return callback(errors.AccessDenied, corsHeaders);
        }

        const websiteConfig = bucket.getWebsiteConfiguration();
        if (!websiteConfig) {
            log.trace('no existing website configuration', {
                method: 'bucketDeleteWebsite',
            });
            pushMetric('deleteBucketWebsite', log, {
                authInfo,
                bucket: bucketName,
            });
            return callback(null, corsHeaders);
        }

        log.trace('deleting website configuration in metadata');
        bucket.setWebsiteConfiguration(null);
        return metadata.updateBucket(bucketName, bucket, log, err => {
            if (err) {
                return callback(err, corsHeaders);
            }
            pushMetric('deleteBucketWebsite', log, {
                authInfo,
                bucket: bucketName,
            });
            return callback(null, corsHeaders);
        });
    });
}

module.exports = bucketDeleteWebsite;

redpajama_set_name: RedPajamaGithub


text:
function index=as_axonlist_roi(axonlist,xrange,yrange)
% index=as_axonlist_roi(xrange,yrange)
% EXAMPLE: axonlist(as_axonlist_roi(axonlist,[1 100],[1 100]))

% Get the centroids from the axonlist
centroids=cat(1,axonlist.Centroid);
% Axons with centroids located inside the defined ROI are identified
% (logical 1)
index=centroids(:,1)>xrange(1) & centroids(:,1)<xrange(2) & centroids(:,2)>yrange(1) & centroids(:,2)<yrange(2);


text:
using namespace node;

namespace nodeairtunes {

  struct coreAudioObjects {
    AudioQueueRef audioQueue;

    unsigned int fillBufferIndex; // the index of the audioQueueBuffer that is being filled

    size_t bytesFilled; // how many bytes have been filled

    AudioQueueBufferRef audioQueueBuffer[NUMBER_OF_BUFFERS]; // audio queue buffers
    bool inuse[NUMBER_OF_BUFFERS]; // flags to indicate that a buffer is still in use

    bool isPlaying;
    unsigned int buffersUsed;

    OSStatus err;

    pthread_mutex_t queueBuffersMutex; // a mutex to protect the inuse flags
    pthread_cond_t queueBufferReadyCondition; // a condition varable for handling the inuse flags

  };

  // This will free the AudioQueue when the wraping JS object is released by the GC
  void coreAudio_weak_callback(v8::Persistent<v8::Value> wrapper, void *arg) {
    v8::HandleScope scope;
    struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) arg;
    AudioQueueDispose(coreAudio->audioQueue, true);
    wrapper.Dispose();
  }

  void OnAudioQueueBufferConsumed(void *inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) {
    struct coreAudioObjects* coreAudio;
    coreAudio = (struct coreAudioObjects*) inUserData;

    int bufIndex = -1;
    for (unsigned int i = 0; i < NUMBER_OF_BUFFERS; i++) {
      if (inBuffer == coreAudio->audioQueueBuffer[i]) {
        bufIndex = i;
        break;
      }
    }

    if (bufIndex == -1) {
      pthread_mutex_lock(&(coreAudio->queueBuffersMutex));
      pthread_cond_signal(&(coreAudio->queueBufferReadyCondition));
      pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
      //DEBUG_AUDIOMANAGER_ERROR("Buffer mismatch !");
      return;
    }
    // signal waiting thread that the buffer is free.
    pthread_mutex_lock(&(coreAudio->queueBuffersMutex));
    coreAudio->inuse[bufIndex] = false;
    coreAudio->buffersUsed--;
    pthread_cond_signal(&(coreAudio->queueBufferReadyCondition));
    pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
  }

  static void enqueueBuffer(struct coreAudioObjects *coreAudio) {

    OSStatus err = 0;

    // enqueue buffer
    pthread_mutex_lock(&(coreAudio->queueBuffersMutex));

    AudioQueueBufferRef fillBuf = coreAudio->audioQueueBuffer[coreAudio->fillBufferIndex];
    fillBuf->mAudioDataByteSize = coreAudio->bytesFilled;
    err = AudioQueueEnqueueBuffer(coreAudio->audioQueue, fillBuf, 0, NULL);
    if (err) {
      //DEBUG_AUDIOMANAGER_ERROR("enqueue failed !!!!! %d", coreAudio->fillBufferIndex);
      coreAudio->bytesFilled = 0;
      pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
      return;
    }

    coreAudio->inuse[coreAudio->fillBufferIndex] = true; // set in use flag
    coreAudio->buffersUsed++;

    // go to next buffer
    if (++(coreAudio->fillBufferIndex) >= NUMBER_OF_BUFFERS) coreAudio->fillBufferIndex = 0;

    coreAudio->bytesFilled = 0; // reset bytes filled

    // wait until next buffer is not in use
    while (coreAudio->inuse[coreAudio->fillBufferIndex]) {
      pthread_cond_wait(&(coreAudio->queueBufferReadyCondition), &(coreAudio->queueBuffersMutex));
    }

    pthread_mutex_unlock(&(coreAudio->queueBuffersMutex));
  }

  v8::Handle<v8::Value> NewCoreAudio(const v8::Arguments& args) {
    v8::HandleScope scope;

    struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) malloc(sizeof (*coreAudio));
    v8::Persistent<v8::ObjectTemplate> coreAudioClass = v8::Persistent<v8::ObjectTemplate>::New(v8::ObjectTemplate::New());
    coreAudioClass->SetInternalFieldCount(1);
    v8::Persistent<v8::Object> o = v8::Persistent<v8::Object>::New(coreAudioClass->NewInstance());
    o->SetPointerInInternalField(0, coreAudio);
    o.MakeWeak(coreAudio, coreAudio_weak_callback);

    coreAudio->isPlaying = false;
    coreAudio->buffersUsed = 0;
    coreAudio->bytesFilled = 0;
    coreAudio->fillBufferIndex = 0;
    // initialize a mutex and condition so that we can block on buffers in use.
    pthread_mutex_init(&(coreAudio->queueBuffersMutex), NULL);
    pthread_cond_init(&(coreAudio->queueBufferReadyCondition), NULL);

    AudioStreamBasicDescription LFormat;
    OSStatus LRet;

    LFormat.mSampleRate = 44100;
    LFormat.mFormatID = kAudioFormatLinearPCM;
    LFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger; // signed int
    LFormat.mFramesPerPacket = 1; // for uncompressed audio
    LFormat.mBytesPerFrame = 4; //AChannels * 2; // interleaved pcm datas (16bits per chan)
    LFormat.mBytesPerPacket = 4; // for pcm: a packet contains a single frame
    LFormat.mChannelsPerFrame = 2;
    LFormat.mBitsPerChannel = 16;

    // Allocating AudioQueue

    if ((LRet = AudioQueueNewOutput(&LFormat, OnAudioQueueBufferConsumed, coreAudio, NULL, NULL, 0, &(coreAudio->audioQueue)))) {
      return scope.Close(v8::Null());
    }

    OSStatus status = 0;

    // Allocate buffers for the AudioQueue
    for (int i = 0; i < NUMBER_OF_BUFFERS; ++i) {
      status = AudioQueueAllocateBuffer(coreAudio->audioQueue, BUFFER_SIZE, &(coreAudio->audioQueueBuffer[i]));
      coreAudio->inuse[i] = false;
    }

    return scope.Close(o);
  }

  v8::Handle<v8::Value> EnqueuePacket(const v8::Arguments& args) {
    v8::HandleScope scope;

    if (args.Length() < 3) {
      printf("expected: EnqueuePacket(coreAudio, pcmData, pcmSize)\n");
      return scope.Close(v8::Null());
    }

    v8::Local<v8::Object>wrapper = args[0]->ToObject();
    struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);

    v8::Local<v8::Value> pcmBuffer = args[1];
    unsigned char* pcmData = (unsigned char*) (Buffer::Data(pcmBuffer->ToObject()));

    int32_t pcmSize = args[2]->Int32Value();

    //We have all infos needed

    size_t offset = 0;
    while (pcmSize) {
      // if the space remaining in the buffer is not enough for this packet, then enqueue the buffer.
      size_t bufSpaceRemaining = BUFFER_SIZE - coreAudio->bytesFilled;
      if (bufSpaceRemaining < pcmSize) {
        //DEBUG_AUDIOMANAGER_VERBOSE("Before enqueue");
        enqueueBuffer(coreAudio);
        //DEBUG_AUDIOMANAGER_VERBOSE("After enqueue");
      }

      bufSpaceRemaining = BUFFER_SIZE - coreAudio->bytesFilled;
      size_t copySize;
      if (bufSpaceRemaining < pcmSize) {
        copySize = bufSpaceRemaining;
      } else {
        copySize = pcmSize;
      }

      // copy data to the audio queue buffer
      AudioQueueBufferRef fillBuf = coreAudio->audioQueueBuffer[coreAudio->fillBufferIndex];
      memcpy((char*) fillBuf->mAudioData + coreAudio->bytesFilled, (const char*) (pcmData + offset), copySize);

      // keep track of bytes filled and packets filled
      coreAudio->bytesFilled += copySize;

      pcmSize -= copySize;
      offset += copySize;
    }

    return scope.Close(v8::Null());
  }

  v8::Handle<v8::Value> Play(const v8::Arguments& args) {
    v8::HandleScope scope;

    if (args.Length() < 2) {
      printf("expected: Play(coreAudio, audioQueueTimeRef)\n");
      return scope.Close(v8::Null());
    }

    v8::Local<v8::Object>wrapper = args[0]->ToObject();
    struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);

    int64_t timeStamp = args[1]->IntegerValue();

    AudioTimeStamp myAudioQueueStartTime = {0};
    Float64 theNumberOfSecondsInTheFuture = timeStamp/44100.0;

    Float64 hostTimeFreq = CAHostTimeBase::GetFrequency();
    UInt64 startHostTime = CAHostTimeBase::GetCurrentTime() + theNumberOfSecondsInTheFuture * hostTimeFreq;

    myAudioQueueStartTime.mFlags = kAudioTimeStampHostTimeValid;
    myAudioQueueStartTime.mHostTime = startHostTime;

    if (coreAudio->isPlaying == false) {
      if (AudioQueueStart(coreAudio->audioQueue, &myAudioQueueStartTime)) {
        printf("AudioQueueStart() Failed!\n");
      } else {
        coreAudio->isPlaying = true;
      }
    }

    return scope.Close(v8::Null());
  }

  v8::Handle<v8::Value> Stop(const v8::Arguments& args) {
    v8::HandleScope scope;

    if (args.Length() < 1) {
      printf("expected: Play(coreAudio)\n");
      return scope.Close(v8::Null());
    }

    v8::Local<v8::Object>wrapper = args[0]->ToObject();
    struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);

    if (coreAudio->isPlaying) {
      if (AudioQueueStop(coreAudio->audioQueue, true)) {
        printf("AudioQueueStop() Failed!\n");
      } else {
        coreAudio->isPlaying = false;
      }
    }

    return scope.Close(v8::Null());
  }

  v8::Handle<v8::Value> SetVolume(const v8::Arguments& args) {
    v8::HandleScope scope;

    if (args.Length() < 1) {
      printf("expected: Play(coreAudio)\n");
      return scope.Close(v8::Null());
    }

    v8::Local<v8::Object>wrapper = args[0]->ToObject();
    struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);
    float volumeToSet=args[1]->IntegerValue()/100.0;

    if (coreAudio->isPlaying)
      AudioQueueSetParameter(coreAudio->audioQueue, kAudioQueueParam_Volume, volumeToSet);

    return scope.Close(v8::Null());
  }

  v8::Handle<v8::Value> GetBufferLevel(const v8::Arguments& args) {
    v8::HandleScope scope;
    v8::Local<v8::Object>wrapper = args[0]->ToObject();
    struct coreAudioObjects *coreAudio = (struct coreAudioObjects *) wrapper->GetPointerFromInternalField(0);
    v8::Handle<v8::Integer> o= v8::Integer::New((int)((coreAudio->buffersUsed/(float)NUMBER_OF_BUFFERS)*100));

    return scope.Close(o);
  }

  void InitCoreAudio(v8::Handle<v8::Object> target) {
    NODE_SET_METHOD(target, "enqueuePacket", EnqueuePacket);
    NODE_SET_METHOD(target, "newCoreAudio", NewCoreAudio);
    NODE_SET_METHOD(target, "play", Play);
    NODE_SET_METHOD(target, "stop", Stop);
    NODE_SET_METHOD(target, "setVolume", SetVolume);
    NODE_SET_METHOD(target, "getBufferLevel", GetBufferLevel);
  }

} // nodeairtunes namespace


text:
SourceFile *createSourceFile(sds fileName) {
	SourceFile *sourceFile = malloc(sizeof(*sourceFile));
	sourceFile->fileName = fileName;
	sourceFile->name = getFileName(sourceFile->fileName);
	sourceFile->fileContents = readFile(fileName);
	sourceFile->tokens = NULL;
	sourceFile->ast = NULL;

	if (!sourceFile->fileContents) {
		errorMessage("Failed to read file %s", sourceFile->fileName);
		destroySourceFile(sourceFile);
		return NULL;
	}

	return sourceFile;
}

void destroySourceFile(SourceFile *sourceFile) {
	verboseModeMessage("Destroyed source file `%s`", sourceFile->name);

	if (sourceFile->tokens) destroyVector(sourceFile->tokens); // TODO destroy elements in tokens
	if (sourceFile->ast) destroyParseTree(sourceFile->ast);

	sdsfree(sourceFile->fileName);
	free(sourceFile->name);
	free(sourceFile->fileContents);
	free(sourceFile);
}


text:
import xlrd, json
from lxml import etree
from collections import OrderedDict

def xls2xml(xls_name):
    with xlrd.open_workbook(xls_name) as wb:
        ws = wb.sheet_by_index(0)
    table = OrderedDict()
    for i in range(ws.nrows):
        key = int(ws.row_values(i)[0])
        value = ws.row_values(i)[1]
        table[key] = value

    with open("city.xml", 'w') as f:
        root = etree.Element("root")
        e_root = etree.ElementTree(root)
        e_citys = etree.SubElement(root, 'citys')
        e_citys.text = '\n'+str(json.dumps(table, indent=4, ensure_ascii=False))+'\n'
        e_citys.append(etree.Comment('\n    城市信息\n'))
        f.write('<?xml version="1.0" encoding="UTF-8"?>'+etree.tounicode(e_root.getroot()))

if __name__=="__main__":
    xls2xml('city.xls')


text:
$(document).ready(function() {

  var menuToggle = $('#js-mobile-menu').unbind();
  $('#js-navigation-menu').removeClass("show");

  menuToggle.on('click', function(e) {
    e.preventDefault();
    $('#js-navigation-menu').slideToggle(function(){
      if($('#js-navigation-menu').is(':hidden')) {
        $('#js-navigation-menu').removeAttr('style');
      }
    });
  });

  $.ajax({
    url: "/en/latest/version.txt",
    cache: false,
    success: function(data) {
      v = $.trim(data)
      style = "font-family: sans-serif;font-size:20px;font-weight:bold;width:100%;height:60px;text-align: center;background-color: pink;color: firebrick;padding: 5px;padding-top:18px; padding-bottom:18px;position:fixed;top:0em; right:0em;z-index:1000000000000"
      loc = window.location.pathname;
      dev = /^\/en\/dev/
      if (dev.exec(loc)) {
        $("body").css({"padding-top":"60px"})
        content = $('
The documentation on this page refers to a DEVELOPMENT VERSION. For the latest release, go to https://bokeh.pydata.org/en/latest/
').attr('style', style);
        $('html:first').prepend(content);
      }
      else if (v != window._BOKEH_CURRENT_VERSION) {
        $("body").css({"padding-top":"60px"})
        content = $('
The documentation on this page refers to a PREVIOUS VERSION. For the latest release, go to https://bokeh.pydata.org/en/latest/
').attr('style', style);
        $('body').prepend(content);
      }
    }
  });

  var loc = window.location.pathname;

  // If index.html hide toc
  if (loc.split('docs/').length == 1 ) {
    $('.toc .toctree-l1').addClass('hide');
    $('.toc').addClass('obfuscate');

  }

  // If orphan page, dispense with toc, and manually add current under second nav
  else if ((loc.split('citation').length > 1) ||
           (loc.split('contact').length > 1) ||
           (loc.split('contribute').length > 1) ||
           (loc.split('gallery').length > 1) ||
           (loc.split('team').length > 1) ||
           (loc.split('vision').length > 1)) {

    $('.toc .toctree-l1').addClass('hide');
    $('.toc').addClass('obfuscate');
    $('.second-nav .nav-link a[href="#"]').addClass('current');

  }

  // Else, selectively hide toc
  else {
    var loc_part = loc.split('docs/')[1].split('.html')[0];

    if (loc_part.split('/').length > 1) {
      loc_part = loc_part.split('/')[0]
    }

    var l1_links = $('.toctree-l1');
    l1_links.each(function(i, l1_link) {
      if ( $(this).hasClass('current') ) {
        $(this).addClass('show');
      } else {
        var href = l1_link.childNodes[0].href;
        var href_part = href.split('docs/')[1].split('/')[0];
        if ( href_part.split('.html').length > 1 ) {
          href_part = href_part.split('.html')[0]
        }
        if (href_part == loc_part) {
          $(this).addClass('show');
        } else {
          $(this).addClass('hide');
        }
      }
    });

    // Add current class to the section of docs we're in
    var nav_links = $('.nav-link.doc-head a');
    nav_links.each(function(i, nav_link) {
      var href = nav_link.href;
      // skip links to external sites
      if (href.startsWith("https://bokeh.pydata.org")) {
        var href_part = href.split('docs/')[1].split('.html')[0];
        if (href_part.split('/').length > 1) {
          href_part = href_part.split('/')[0]
        }
        if (loc_part == href_part) {
          $(this).addClass('current');
        }
      }
    });
  }

  // Expander (used for collapsible code blocks)
  $('.expander-trigger').click(function(){
    $(this).toggleClass("expander-hidden");
  });

});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="domain.money.dao.PublicDebtMapper">

	<resultMap type="domain.money.model.PublicDebt" id="myResultMap">
		<constructor>
			<arg column="country_code" javaType="java.util.Locale" jdbcType="CHAR"
				typeHandler="paulkrause88.mybatis.jsr354.type.CountryCodeHandler" />
			<arg column="external_debt_usd" javaType="javax.money.MonetaryAmount"
				jdbcType="DECIMAL" typeHandler="paulkrause88.mybatis.jsr354.type.USDAmountHandler" />
			<arg column="as_of" javaType="java.time.LocalDate" jdbcType="DATE"
				typeHandler="paulkrause88.mybatis.jsr354.type.LocalDateHandler" />
			<arg column="per_capita_usd" javaType="javax.money.MonetaryAmount"
				jdbcType="DECIMAL" typeHandler="paulkrause88.mybatis.jsr354.type.USDAmountHandler" />
			<arg column="percent_gdp" javaType="_double" />
		</constructor>
	</resultMap>

	<select id="selectMostRecent" parameterType="string" resultMap="myResultMap">
		select country_code, external_debt_usd, as_of, per_capita_usd, percent_gdp
		from public_debt
		where country_code = #{param1}
		order by as_of desc
		limit 1
	</select>

</mapper>


text:
package org.guvnor.ala.wildfly.executor.tests;

import java.util.HashMap;
import java.util.Map;

import org.guvnor.ala.build.maven.model.MavenBinary;
import org.guvnor.ala.wildfly.config.WildflyRuntimeExecConfig;
import org.guvnor.ala.wildfly.config.impl.ContextAwareWildflyRuntimeExecConfig;
import org.guvnor.ala.wildfly.model.WildflyProvider;
import org.junit.Test;
import org.uberfire.java.nio.file.Path;

import static java.util.Collections.singletonMap;
import static org.guvnor.ala.util.VariableInterpolation.interpolate;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

public class ContextAwareWildflyRuntimeExecConfigTest {

    public static final String WAR_PATH_DEFAULT_EXPRESSION = "${input." + WildflyRuntimeExecConfig.WAR_PATH + "}";

    public static final String REDEPLOY_STRATEGY_DEFAULT_EXPRESSION = "${input." + WildflyRuntimeExecConfig.REDEPLOY_STRATEGY + "}";

    public static final String RUNTIME_NAME_DEFAULT_EXPRESSION = "${input." + WildflyRuntimeExecConfig.RUNTIME_NAME + "}";

    public static final String FILE_PATH = "/path/to/file.war";

    public static final String REDEPLOY_OPTION = "none";

    public static final String RUNTIME_NAME = "runtimeNameValue";

    @Test
    public void testDefaultExpression() {
        assertEquals(WAR_PATH_DEFAULT_EXPRESSION,
                     new ContextAwareWildflyRuntimeExecConfig().getWarPath());
        assertEquals(REDEPLOY_STRATEGY_DEFAULT_EXPRESSION,
                     new ContextAwareWildflyRuntimeExecConfig().getRedeployStrategy());
        assertEquals(RUNTIME_NAME_DEFAULT_EXPRESSION,
                     new ContextAwareWildflyRuntimeExecConfig().getRuntimeName());
    }

    @Test
    public void testContextUsingMavenBinary() {
        final ContextAwareWildflyRuntimeExecConfig config = new ContextAwareWildflyRuntimeExecConfig();
        final Map<String, Object> context = new HashMap<>();
        final WildflyProvider provider = mock(WildflyProvider.class);
        context.put("wildfly-provider",
                    provider);
        final MavenBinary binary = mock(MavenBinary.class);
        final Path path = mock(Path.class);
        when(binary.getPath()).thenReturn(path);
        when(path.toString()).thenReturn(FILE_PATH);
        context.put("binary",
                    binary);

        config.setContext(context);

        assertEquals(provider,
                     config.getProviderId());
        assertEquals(FILE_PATH,
                     config.getWarPath());

        final WildflyRuntimeExecConfig configClone = config.asNewClone(config);
        assertEquals(provider,
                     configClone.getProviderId());
        assertEquals(FILE_PATH,
                     configClone.getWarPath());
    }

    @Test
    public void testContextUsingPath() {
        final ContextAwareWildflyRuntimeExecConfig config = new ContextAwareWildflyRuntimeExecConfig();
        final WildflyProvider provider = mock(WildflyProvider.class);
        final Map<String, Object> context = singletonMap("wildfly-provider",
                                                         provider);

        config.setContext(context);

        assertEquals(provider,
                     config.getProviderId());
        assertEquals(WAR_PATH_DEFAULT_EXPRESSION,
                     config.getWarPath());

        final WildflyRuntimeExecConfig configClone = config.asNewClone(config);
        assertEquals(provider,
                     configClone.getProviderId());
        assertEquals(WAR_PATH_DEFAULT_EXPRESSION,
                     configClone.getWarPath());
    }

    @Test
    public void testVariablesResolution() {
        Map<String, String> values = new HashMap<>();
        values.put(ContextAwareWildflyRuntimeExecConfig.WAR_PATH,
                   FILE_PATH);
        values.put(ContextAwareWildflyRuntimeExecConfig.REDEPLOY_STRATEGY,
                   REDEPLOY_OPTION);
        values.put(ContextAwareWildflyRuntimeExecConfig.RUNTIME_NAME,
                   RUNTIME_NAME);

        final ContextAwareWildflyRuntimeExecConfig config = new ContextAwareWildflyRuntimeExecConfig();
        final ContextAwareWildflyRuntimeExecConfig varConfig = interpolate(singletonMap("input",
                                                                                values),
                                                                           config);
        assertEquals(FILE_PATH,
                     varConfig.getWarPath());
        assertEquals(REDEPLOY_OPTION,
                     varConfig.getRedeployStrategy());
        assertEquals(RUNTIME_NAME,
                     varConfig.getRuntimeName());
    }
}


text:
package org.apache.geode.management.internal.cli.commands;

import static org.apache.geode.management.internal.cli.remote.CommandExecutor.RUN_ON_MEMBER_CHANGE_NOT_PERSISTED;
import static org.apache.geode.management.internal.cli.remote.CommandExecutor.SERVICE_NOT_RUNNING_CHANGE_NOT_PERSISTED;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import joptsimple.internal.Strings;
import org.springframework.shell.core.annotation.CliCommand;
import org.springframework.shell.core.annotation.CliOption;

import org.apache.geode.annotations.Immutable;
import org.apache.geode.cache.configuration.RegionConfig;
import org.apache.geode.cache.query.IndexType;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.internal.InternalConfigurationPersistenceService;
import org.apache.geode.management.api.ClusterManagementService;
import org.apache.geode.management.cli.CliMetaData;
import org.apache.geode.management.cli.ConverterHint;
import org.apache.geode.management.cli.GfshCommand;
import org.apache.geode.management.configuration.RuntimeRegionConfig;
import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
import org.apache.geode.management.internal.cli.functions.CreateIndexFunction;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.result.model.InfoResultModel;
import org.apache.geode.management.internal.cli.result.model.ResultModel;
import org.apache.geode.management.internal.security.ResourceOperation;
import org.apache.geode.security.ResourcePermission;

public class CreateIndexCommand extends GfshCommand {
  @Immutable
  private static final CreateIndexFunction createIndexFunction = new CreateIndexFunction();

  @CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
  @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
  @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
      operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
  public ResultModel createIndex(@CliOption(key = CliStrings.CREATE_INDEX__NAME, mandatory = true,
      help = CliStrings.CREATE_INDEX__NAME__HELP) final String indexName,

      @CliOption(key = CliStrings.CREATE_INDEX__EXPRESSION, mandatory = true,
          help = CliStrings.CREATE_INDEX__EXPRESSION__HELP) final String indexedExpression,

      @CliOption(key = CliStrings.CREATE_INDEX__REGION, mandatory = true,
          optionContext = ConverterHint.REGION_PATH,
          help = CliStrings.CREATE_INDEX__REGION__HELP) String regionPath,

      @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
          optionContext = ConverterHint.MEMBERIDNAME,
          help = CliStrings.CREATE_INDEX__MEMBER__HELP) final String[] memberNameOrID,

      @CliOption(key = CliStrings.CREATE_INDEX__TYPE, unspecifiedDefaultValue = "range",
          optionContext = ConverterHint.INDEX_TYPE,
          help = CliStrings.CREATE_INDEX__TYPE__HELP) final IndexType indexType,

      @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
          optionContext = ConverterHint.MEMBERGROUP,
          help = CliStrings.CREATE_INDEX__GROUP__HELP) String[] groups) {

    // first find out what groups this region belongs to when using cluster configuration
    InternalConfigurationPersistenceService ccService = getConfigurationPersistenceService();
    ClusterManagementService cms = getClusterManagementService();
    final Set<DistributedMember> targetMembers;
    ResultModel resultModel = new ResultModel();
    InfoResultModel info = resultModel.addInfo();
    String regionName = null;
    // if cluster management service is enabled and user did not specify a member id, then
    // we will find the applicable members based on the what group this region is on
    if (ccService != null && memberNameOrID == null) {
      regionName = getValidRegionName(regionPath, cms);
      RuntimeRegionConfig config = getRuntimeRegionConfig(cms, regionName);
      if (config == null) {
        return ResultModel.createError("Region " + regionName + " does not exist.");
      }
      String[] calculatedGroups = config.getGroups().toArray(new String[0]);
      if (groups != null && !containsExactlyInAnyOrder(groups, calculatedGroups)) {
        info.addLine("--groups=" + Strings.join(groups, ",") + " is ignored.");
      }
      groups = calculatedGroups;
      targetMembers = findMembers(groups, null);
    }
    // otherwise use the group/members specified in the option to find the applicable members.
    else {
      targetMembers = findMembers(groups, memberNameOrID);
    }

    if (targetMembers.isEmpty()) {
      return ResultModel.createError(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
    }

    RegionConfig.Index index = new RegionConfig.Index();
    index.setName(indexName);
    index.setExpression(indexedExpression);
    index.setFromClause(regionPath);
    if (indexType == IndexType.PRIMARY_KEY) {
      index.setKeyIndex(true);
    } else {
      index.setKeyIndex(false);
      index.setType(indexType.getName());
    }

    List<CliFunctionResult> functionResults =
        executeAndGetFunctionResult(createIndexFunction, index, targetMembers);
    resultModel.addTableAndSetStatus("createIndex", functionResults, true, false);

    if (!resultModel.isSuccessful()) {
      return resultModel;
    }

    // update the cluster configuration. Can't use SingleGfshCommand to do the update since in some
    // cases
    // groups information is inferred by the region, and the --group option might have the wrong
    // group
    // information.
    if (ccService == null) {
      info.addLine(SERVICE_NOT_RUNNING_CHANGE_NOT_PERSISTED);
      return resultModel;
    }
    if (memberNameOrID != null) {
      info.addLine(RUN_ON_MEMBER_CHANGE_NOT_PERSISTED);
      return resultModel;
    }

    final InfoResultModel groupStatus = resultModel.addInfo("groupStatus");
    String finalRegionName = regionName;
    // at this point, groups should be the regionConfig's groups
    if (groups.length == 0) {
      groups = new String[] {"cluster"};
    }
    for (String group : groups) {
      ccService.updateCacheConfig(group, cacheConfig -> {
        RegionConfig regionConfig = cacheConfig.findRegionConfiguration(finalRegionName);
        regionConfig.getIndexes().add(index);
        groupStatus
            .addLine("Cluster configuration for group '" + group + "' is updated.");
        return cacheConfig;
      });
    }
    return resultModel;
  }

  private static boolean containsExactlyInAnyOrder(String[] a, String[] b) {
    return new HashSet(Arrays.asList(a)).equals(new HashSet(Arrays.asList(b)));
  }

  // find a valid regionName when regionPath passed in is in the form of
  // "/region1.fieldName.fieldName x"
  // this also handles the possibility when regionName has "." in it, like "/A.B". It's stripping
  // . part one by one and check if the remaining part is a valid region name or not. If we
  // could not find a region with any part of the name, (like, couldn't find A.B or A), then A is
  // returned.
  String getValidRegionName(String regionPath, ClusterManagementService cms) {
    // Check to see if the region path contains an alias e.g "/region1 r1"
    // Then the first string will be the regionPath
    String regionName = regionPath.trim().split(" ")[0];
    // check to see if the region path is in the form of "--region=region.entrySet() z"
    while (regionName.contains(".")) {
      RuntimeRegionConfig region = getRuntimeRegionConfig(cms, regionName);
      if (region != null) {
        break;
      }
      // otherwise, strip one more . part off the regionName
      else {
        regionName = regionName.substring(0, regionName.lastIndexOf("."));
      }
    }
    return regionName;
  }

  RuntimeRegionConfig getRuntimeRegionConfig(ClusterManagementService cms,
      String regionName) {
    RegionConfig regionConfig = new RegionConfig();
    regionConfig.setName(regionName);
    List<RuntimeRegionConfig> list = cms.list(regionConfig).getResult();
    if (list.isEmpty()) {
      return null;
    } else {
      return list.get(0);
    }
  }

}


text:
#include "WASAPI.h"
#include "User.h"
#include "Global.h"
#include "MainWindow.h"
#include "Timer.h"

// Now that Win7 is published, which includes public versions of these
// interfaces, we simply inherit from those but use the "old" IIDs.

MIDL_INTERFACE("33969B1D-D06F-4281-B837-7EAAFD21A9C0")
IVistaAudioSessionControl2 :
public IAudioSessionControl2 {
};

MIDL_INTERFACE("94BE9D30-53AC-4802-829C-F13E5AD34775")
IAudioSessionQuery :
public IUnknown {
	virtual HRESULT STDMETHODCALLTYPE GetQueryInterface(IAudioSessionEnumerator **) = 0;
};

class WASAPIInputRegistrar : public AudioInputRegistrar {
	public:
		WASAPIInputRegistrar();
		virtual AudioInput *create();
		virtual const QList<audioDevice> getDeviceChoices();
		virtual void setDeviceChoice(const QVariant &, Settings &);
		virtual bool canEcho(const QString &) const;
};

class WASAPIOutputRegistrar : public AudioOutputRegistrar {
	public:
		WASAPIOutputRegistrar();
		virtual AudioOutput *create();
		virtual const QList<audioDevice> getDeviceChoices();
		virtual void setDeviceChoice(const QVariant &, Settings &);
		bool canMuteOthers() const;
};

class WASAPIInit : public DeferInit {
		WASAPIInputRegistrar *wirReg;
		WASAPIOutputRegistrar *worReg;
	public:
		void initialize();
		void destroy();
};

static WASAPIInit wasapiinit;

void WASAPIInit::initialize() {
	wirReg = NULL;
	worReg = NULL;

	OSVERSIONINFOEXW ovi;
	memset(&ovi, 0, sizeof(ovi));

	ovi.dwOSVersionInfoSize=sizeof(ovi);
	GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi));

	if ((ovi.dwMajorVersion < 6) || (ovi.dwBuildNumber < 6001)) {
		qWarning("WASAPIInit: Requires Vista SP1");
		return;
	}

	HMODULE hLib = LoadLibrary(L"AVRT.DLL");
	if (hLib == NULL) {
		qWarning("WASAPIInit: Failed to load avrt.dll");
		return;
	}
	FreeLibrary(hLib);

	wirReg = new WASAPIInputRegistrar();
	worReg = new WASAPIOutputRegistrar();
}

void WASAPIInit::destroy() {
	if (wirReg)
		delete wirReg;
	if (worReg)
		delete worReg;
}

WASAPIInputRegistrar::WASAPIInputRegistrar() : AudioInputRegistrar(QLatin1String("WASAPI"), 10) {
}

AudioInput *WASAPIInputRegistrar::create() {
	return new WASAPIInput();
}

const QList<audioDevice> WASAPIInputRegistrar::getDeviceChoices() {
	return WASAPISystem::mapToDevice(WASAPISystem::getInputDevices(), g.s.qsWASAPIInput);
}

void WASAPIInputRegistrar::setDeviceChoice(const QVariant &choice, Settings &s) {
	s.qsWASAPIInput = choice.toString();
}

bool WASAPIInputRegistrar::canEcho(const QString &outputsys) const {
	return (outputsys == name);
}

WASAPIOutputRegistrar::WASAPIOutputRegistrar() : AudioOutputRegistrar(QLatin1String("WASAPI"), 10) {
}

AudioOutput *WASAPIOutputRegistrar::create() {
	return new WASAPIOutput();
}

const QList<audioDevice> WASAPIOutputRegistrar::getDeviceChoices() {
	return WASAPISystem::mapToDevice(WASAPISystem::getOutputDevices(), g.s.qsWASAPIOutput);
}

void WASAPIOutputRegistrar::setDeviceChoice(const QVariant &choice, Settings &s) {
	s.qsWASAPIOutput = choice.toString();
}

bool WASAPIOutputRegistrar::canMuteOthers() const {
	return true;
}

const QHash<QString, QString> WASAPISystem::getInputDevices() {
	return getDevices(eCapture);
}

const QHash<QString, QString> WASAPISystem::getOutputDevices() {
	return getDevices(eRender);
}

const QHash<QString, QString> WASAPISystem::getDevices(EDataFlow dataflow) {
	QHash<QString, QString> devices;

	HRESULT hr;

	IMMDeviceEnumerator *pEnumerator = NULL;
	IMMDeviceCollection *pCollection = NULL;

	hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), reinterpret_cast<void **>(&pEnumerator));

	if (! pEnumerator || FAILED(hr)) {
		qWarning("WASAPI: Failed to instatiate enumerator");
	} else {
		hr = pEnumerator->EnumAudioEndpoints(dataflow, DEVICE_STATE_ACTIVE, &pCollection);
		if (! pCollection || FAILED(hr)) {
			qWarning("WASAPI: Failed to enumerate");
		} else {
			devices.insert(QString(), tr("Default Device"));

			UINT ndev = 0;
			pCollection->GetCount(&ndev);
			for (unsigned int idx=0;idx<ndev;++idx) {
				IMMDevice *pDevice = NULL;
				IPropertyStore *pStore = NULL;

				pCollection->Item(idx, &pDevice);
				pDevice->OpenPropertyStore(STGM_READ, &pStore);

				LPWSTR strid = NULL;
				pDevice->GetId(&strid);

				PROPVARIANT varName;
				PropVariantInit(&varName);

				pStore->GetValue(PKEY_Device_FriendlyName, &varName);

				devices.insert(QString::fromWCharArray(strid), QString::fromWCharArray(varName.pwszVal));

				PropVariantClear(&varName);
				CoTaskMemFree(strid);

				pStore->Release();
				pDevice->Release();
			}
			pCollection->Release();
		}
		pEnumerator->Release();
	}

	return devices;
}

const QList<audioDevice> WASAPISystem::mapToDevice(const QHash<QString, QString> devs, const QString &match) {
	QList<audioDevice> qlReturn;

	QStringList qlDevices = devs.keys();
	qSort(qlDevices);

	if (qlDevices.contains(match)) {
		qlDevices.removeAll(match);
		qlDevices.prepend(match);
	}

	foreach(const QString &dev, qlDevices) {
		qlReturn << audioDevice(devs.value(dev), dev);
	}
	return qlReturn;
}

WASAPIInput::WASAPIInput() {
	bRunning = true;
};

WASAPIInput::~WASAPIInput() {
	bRunning = false;
	wait();
}

void WASAPIInput::run() {
	HRESULT hr;
	IMMDeviceEnumerator *pEnumerator = NULL;
	IMMDevice *pMicDevice = NULL;
	IAudioClient *pMicAudioClient = NULL;
	IAudioCaptureClient *pMicCaptureClient = NULL;
	IMMDevice *pEchoDevice = NULL;
	IAudioClient *pEchoAudioClient = NULL;
	IAudioCaptureClient *pEchoCaptureClient = NULL;
	WAVEFORMATEX *micpwfx = NULL, *echopwfx = NULL;
	WAVEFORMATEXTENSIBLE *micpwfxe = NULL, *echopwfxe = NULL;
	UINT32 bufferFrameCount;
	UINT32 numFramesAvailable;
	UINT32 numFramesLeft;
	UINT32 micPacketLength = 0, echoPacketLength = 0;
	UINT32 allocLength;
	UINT64 devicePosition;
	UINT64 qpcPosition;
	HANDLE hEvent;
	BYTE *pData;
	DWORD flags;
	DWORD dwTaskIndex = 0;
	HANDLE hMmThread;
	float *tbuff = NULL;
	bool doecho = g.s.doEcho();

	CoInitialize(NULL);

	hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

	hMmThread = AvSetMmThreadCharacteristics(L"Pro Audio", &dwTaskIndex);
	if (hMmThread == NULL) {
		qWarning("WASAPIInput: Failed to set Pro Audio thread priority");
	}

	hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), reinterpret_cast<void **>(&pEnumerator));

	if (! pEnumerator || FAILED(hr)) {
		qWarning("WASAPIInput: Failed to instatiate enumerator");
		return;
	}

	if (! g.s.qsWASAPIInput.isEmpty()) {
		STACKVAR(wchar_t, devname, g.s.qsWASAPIInput.length() + 1);
		int len = g.s.qsWASAPIInput.toWCharArray(devname);
		devname[len] = 0;
		hr = pEnumerator->GetDevice(devname, &pMicDevice);
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Failed to open selected input device %s %ls, falling back to default", qPrintable(g.s.qsWASAPIInput), devname);
		}
	}

	if (! pMicDevice) {
		hr = pEnumerator->GetDefaultAudioEndpoint(eCapture, eCommunications, &pMicDevice);
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Failed to open input device");
			goto cleanup;
		}
		wchar_t *devname = NULL;
		hr = pMicDevice->GetId(&devname);
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Failed to query input device");
			goto cleanup;
		}
		pMicDevice->Release();
		hr = pEnumerator->GetDevice(devname, &pMicDevice);
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Failed to reopen default input device");
			goto cleanup;
		}
		CoTaskMemFree(devname);
	}

	if (doecho) {
		if (! g.s.qsWASAPIOutput.isEmpty()) {
			STACKVAR(wchar_t, devname, g.s.qsWASAPIOutput.length());
			g.s.qsWASAPIOutput.toWCharArray(devname);
			hr = pEnumerator->GetDevice(devname, &pEchoDevice);
			if (FAILED(hr)) {
				qWarning("WASAPIInput: Failed to open selected echo device, falling back to default");
			}
		}

		if (! pEchoDevice) {
			hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eCommunications, &pEchoDevice);
			if (FAILED(hr)) {
				qWarning("WASAPIInput: Failed to open echo device");
				goto cleanup;
			}
			wchar_t *devname = NULL;
			hr = pEchoDevice->GetId(&devname);
			if (FAILED(hr)) {
				qWarning("WASAPIInput: Failed to query echo device");
				goto cleanup;
			}
			pEchoDevice->Release();
			hr = pEnumerator->GetDevice(devname, &pEchoDevice);
			if (FAILED(hr)) {
				qWarning("WASAPIInput: Failed to reopen default echo device");
				goto cleanup;
			}
			CoTaskMemFree(devname);
		}
	}

	pEnumerator->Release();
	pEnumerator = NULL;

	hr = pMicDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void **) &pMicAudioClient);
	if (FAILED(hr)) {
		qWarning("WASAPIInput: Activate Mic AudioClient failed");
		goto cleanup;
	}

	hr = pMicAudioClient->GetMixFormat(&micpwfx);
	micpwfxe = reinterpret_cast<WAVEFORMATEXTENSIBLE *>(micpwfx);

	if (FAILED(hr) || (micpwfx->wBitsPerSample != (sizeof(float) * 8)) || (micpwfxe->SubFormat != KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
		qWarning("WASAPIInput: Mic Subformat is not IEEE Float");
		goto cleanup;
	}

	hr = pMicAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, micpwfx, NULL);
	if (FAILED(hr)) {
		qWarning("WASAPIInput: Mic Initialize failed");
		goto cleanup;
	}

	hr = pMicAudioClient->GetBufferSize(&bufferFrameCount);
	hr = pMicAudioClient->GetService(__uuidof(IAudioCaptureClient), (void**)&pMicCaptureClient);
	if (FAILED(hr)) {
		qWarning("WASAPIInput: Mic GetService failed");
		goto cleanup;
	}

	pMicAudioClient->SetEventHandle(hEvent);
	if (FAILED(hr)) {
		qWarning("WASAPIInput: Failed to set mic event");
		goto cleanup;
	}

	hr = pMicAudioClient->Start();
	if (FAILED(hr)) {
		qWarning("WASAPIInput: Failed to start mic");
		goto cleanup;
	}

	iMicChannels = micpwfx->nChannels;
	iMicFreq = micpwfx->nSamplesPerSec;

	if (doecho) {
		hr = pEchoDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void **) &pEchoAudioClient);
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Activate Echo AudioClient failed");
			goto cleanup;
		}

		hr = pEchoAudioClient->GetMixFormat(&echopwfx);
		echopwfxe = reinterpret_cast<WAVEFORMATEXTENSIBLE *>(echopwfx);

		if (FAILED(hr) || (echopwfx->wBitsPerSample != (sizeof(float) * 8)) || (echopwfxe->SubFormat != KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
			qWarning("WASAPIInput: Echo Subformat is not IEEE Float");
			goto cleanup;
		}

		hr = pEchoAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_LOOPBACK, 0, 0, echopwfx, NULL);
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Echo Initialize failed");
			goto cleanup;
		}

		hr = pEchoAudioClient->GetBufferSize(&bufferFrameCount);
		hr = pEchoAudioClient->GetService(__uuidof(IAudioCaptureClient), (void**)&pEchoCaptureClient);
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Echo GetService failed");
			goto cleanup;
		}

		pEchoAudioClient->SetEventHandle(hEvent);
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Failed to set echo event");
			goto cleanup;
		}

		hr = pEchoAudioClient->Start();
		if (FAILED(hr)) {
			qWarning("WASAPIInput: Failed to start Echo");
			goto cleanup;
		}

		iEchoChannels = echopwfx->nChannels;
		iEchoFreq = echopwfx->nSamplesPerSec;
	}

	initializeMixer();

	allocLength = (iMicLength / 2) * micpwfx->nChannels;
	tbuff = new float[allocLength];

	while (bRunning && ! FAILED(hr)) {
		hr = pMicCaptureClient->GetNextPacketSize(&micPacketLength);
		if (! FAILED(hr) && iEchoChannels)
			hr = pEchoCaptureClient->GetNextPacketSize(&echoPacketLength);
		if (FAILED(hr))
			goto cleanup;

		while ((micPacketLength > 0) || (echoPacketLength > 0)) {
			if (echoPacketLength > 0) {
				hr = pEchoCaptureClient->GetBuffer(&pData, &numFramesAvailable, &flags, &devicePosition, &qpcPosition);
				numFramesLeft = numFramesAvailable;
				if (FAILED(hr))
					goto cleanup;

				UINT32 nFrames = numFramesAvailable * echopwfx->nChannels;
				if (nFrames > allocLength) {
					delete [] tbuff;
					allocLength = nFrames;
					tbuff = new float[allocLength];
				}
				memcpy(tbuff, pData, nFrames * sizeof(float));
				hr = pEchoCaptureClient->ReleaseBuffer(numFramesAvailable);
				if (FAILED(hr))
					goto cleanup;
				addEcho(tbuff, numFramesAvailable);
			} else if (micPacketLength > 0) {
				hr = pMicCaptureClient->GetBuffer(&pData, &numFramesAvailable, &flags, &devicePosition, &qpcPosition);
				numFramesLeft = numFramesAvailable;
				if (FAILED(hr))
					goto cleanup;

				UINT32 nFrames = numFramesAvailable * micpwfx->nChannels;
				if (nFrames > allocLength) {
					delete [] tbuff;
					allocLength = nFrames;
					tbuff = new float[allocLength];
				}
				memcpy(tbuff, pData, nFrames * sizeof(float));
				hr = pMicCaptureClient->ReleaseBuffer(numFramesAvailable);
				if (FAILED(hr))
					goto cleanup;
				addMic(tbuff, numFramesAvailable);
			}
			hr = pMicCaptureClient->GetNextPacketSize(&micPacketLength);
			if (! FAILED(hr) && iEchoChannels)
				hr = pEchoCaptureClient->GetNextPacketSize(&echoPacketLength);
		}
		if (! FAILED(hr))
			WaitForSingleObject(hEvent, 2000);
	}

cleanup:
	if (micpwfx)
		CoTaskMemFree(micpwfx);
	if (echopwfx)
		CoTaskMemFree(echopwfx);

	if (pMicAudioClient) {
		pMicAudioClient->Stop();
		pMicAudioClient->Release();
	}
	if (pMicCaptureClient)
		pMicCaptureClient->Release();
	if (pMicDevice)
		pMicDevice->Release();

	if (pEchoAudioClient) {
		pEchoAudioClient->Stop();
		pEchoAudioClient->Release();
	}
	if (pEchoCaptureClient)
		pEchoCaptureClient->Release();
	if (pEchoDevice)
		pEchoDevice->Release();

	if (pEnumerator)
		pEnumerator->Release();

	if (hMmThread != NULL)
		AvRevertMmThreadCharacteristics(hMmThread);

	if (hEvent != NULL)
		CloseHandle(hEvent);

	if (tbuff)
		delete [] tbuff;
}

WASAPIOutput::WASAPIOutput() {
	bRunning = true;
}

WASAPIOutput::~WASAPIOutput() {
	bRunning = false;
	wait();
}

void WASAPIOutput::setVolumes(IMMDevice *pDevice, bool talking) {
	HRESULT hr;

	if (! talking) {
		QMap<ISimpleAudioVolume *, VolumePair>::const_iterator i;
		for (i=qmVolumes.constBegin(); i != qmVolumes.constEnd(); ++i) {
			float fVolume = 1.0f;
			hr = i.key()->GetMasterVolume(&fVolume);
			if (qFuzzyCompare(i.value().second, fVolume))
				hr = i.key()->SetMasterVolume(i.value().first, NULL);
			i.key()->Release();
		}
		qmVolumes.clear();
		return;
	}

	IAudioSessionManager2 *pAudioSessionManager = NULL;
	int max = 0;
	DWORD dwMumble = GetCurrentProcessId();

	static int version = -1;
	if (version == -1) {
		OSVERSIONINFOEXW ovi;
		memset(&ovi, 0, sizeof(ovi));

		ovi.dwOSVersionInfoSize=sizeof(ovi);
		GetVersionEx(reinterpret_cast<OSVERSIONINFOW *>(&ovi));

		if ((ovi.dwMajorVersion <= 6) && (ovi.dwBuildNumber < 7100))
			version = 0;
		else
			version = 1;
	}

	qmVolumes.clear();
	if (qFuzzyCompare(g.s.fOtherVolume, 1.0f))
		return;

	// FIXME: Try to keep the session object around when returning volume.

	if (SUCCEEDED(hr = pDevice->Activate(version ? __uuidof(IAudioSessionManager2) : __uuidof(IAudioSessionManager), CLSCTX_ALL, NULL, (void **) &pAudioSessionManager))) {
		IAudioSessionEnumerator *pEnumerator = NULL;
		IAudioSessionQuery *pMysticQuery = NULL;
		if (version == 0) {
			if (SUCCEEDED(hr = pAudioSessionManager->QueryInterface(__uuidof(IAudioSessionQuery), (void **) &pMysticQuery))) {
				hr = pMysticQuery->GetQueryInterface(&pEnumerator);
			}
		} else {
			hr = pAudioSessionManager->GetSessionEnumerator(&pEnumerator);
		}

		QSet<QUuid> seen;

		if (SUCCEEDED(hr)) {
			if (SUCCEEDED(hr = pEnumerator->GetCount(&max))) {
				for (int i=0;i<max;++i) {
					IAudioSessionControl *pControl = NULL;
					if (SUCCEEDED(hr = pEnumerator->GetSession(i, &pControl))) {
						IAudioSessionControl2 *pControl2 = NULL;
						if (SUCCEEDED(hr = pControl->QueryInterface(version ? __uuidof(IAudioSessionControl2) : __uuidof(IVistaAudioSessionControl2), (void **) &pControl2)))  {
							DWORD pid;
							if (SUCCEEDED(hr = pControl2->GetProcessId(&pid)) && (pid != dwMumble)) {
								AudioSessionState ass;
								if (SUCCEEDED(hr = pControl2->GetState(&ass)) && (ass != AudioSessionStateExpired)) {
									GUID group;
									if (SUCCEEDED(hr = pControl2->GetGroupingParam(&group))) {
										QUuid quuid(group);
										if (! seen.contains(quuid)) {
											seen.insert(quuid);
											ISimpleAudioVolume *pVolume = NULL;
											if (SUCCEEDED(hr = pControl2->QueryInterface(__uuidof(ISimpleAudioVolume), (void **) &pVolume))) {
												BOOL bMute = TRUE;
												bool keep = false;
												if (SUCCEEDED(hr = pVolume->GetMute(&bMute)) && ! bMute) {
													float fVolume = 1.0f;
													if (SUCCEEDED(hr = pVolume->GetMasterVolume(&fVolume)) && ! qFuzzyCompare(fVolume,0.0f)) {
														float fSetVolume = fVolume * g.s.fOtherVolume;
														if (SUCCEEDED(hr = pVolume->SetMasterVolume(fSetVolume, NULL))) {
															hr = pVolume->GetMasterVolume(&fSetVolume);
															qmVolumes.insert(pVolume, VolumePair(fVolume,fSetVolume));
															keep = true;
														}
													}
												}
												if (! keep)
													pVolume->Release();
											}
										}
									}
								}
							}
							pControl2->Release();
						}
						pControl->Release();
					}
				}
			}
			pEnumerator->Release();
		}
		if (pMysticQuery)
			pMysticQuery->Release();
		pAudioSessionManager->Release();
	}
}

void WASAPIOutput::run() {
	HRESULT hr;
	IMMDeviceEnumerator *pEnumerator = NULL;
	IMMDevice *pDevice = NULL;
	IAudioClient *pAudioClient = NULL;
	IAudioRenderClient *pRenderClient = NULL;
	WAVEFORMATEX *pwfx = NULL;
	WAVEFORMATEXTENSIBLE *pwfxe = NULL;
	UINT32 bufferFrameCount;
	REFERENCE_TIME def, min, latency;
	UINT32 numFramesAvailable;
	UINT32 packetLength = 0;
	UINT32 wantLength;
	HANDLE hEvent;
	BYTE *pData;
	DWORD dwTaskIndex = 0;
	HANDLE hMmThread;
	int ns = 0;
	unsigned int chanmasks[32];
	QMap<DWORD, float> qmVolumes;
	bool lastspoke = false;
	REFERENCE_TIME bufferDuration = (g.s.iOutputDelay > 1) ? (g.s.iOutputDelay + 1) * 100000 : 0;

	CoInitialize(NULL);

	hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

	hMmThread = AvSetMmThreadCharacteristics(L"Pro Audio", &dwTaskIndex);
	if (hMmThread == NULL) {
		qWarning("WASAPIOutput: Failed to set Pro Audio thread priority");
	}

	hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), reinterpret_cast<void **>(&pEnumerator));

	if (! pEnumerator || FAILED(hr)) {
		qWarning("WASAPIOutput: Failed to instatiate enumerator");
		return;
	}

	if (! g.s.qsWASAPIOutput.isEmpty()) {
		STACKVAR(wchar_t, devname, g.s.qsWASAPIOutput.length() + 1);
		int len = g.s.qsWASAPIOutput.toWCharArray(devname);
		devname[len] = 0;
		hr = pEnumerator->GetDevice(devname, &pDevice);
		if (FAILED(hr)) {
			qWarning("WASAPIOutput: Failed to open selected input device, falling back to default");
		}
	}

	if (! pDevice) {
		hr = pEnumerator->GetDefaultAudioEndpoint(eRender, eCommunications, &pDevice);
		if (FAILED(hr)) {
			qWarning("WASAPIOutput: Failed to open output device");
			goto cleanup;
		}
		wchar_t *devname = NULL;
		hr = pDevice->GetId(&devname);
		if (FAILED(hr)) {
			qWarning("WASAPIOutput: Failed to query output device");
			goto cleanup;
		}
		pDevice->Release();
		hr = pEnumerator->GetDevice(devname, &pDevice);
		if (FAILED(hr)) {
			qWarning("WASAPIOutput: Failed to reopen default output device");
			goto cleanup;
		}
		CoTaskMemFree(devname);
	}

	pEnumerator->Release();
	pEnumerator = NULL;

	hr = pDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void **) &pAudioClient);
	if (FAILED(hr)) {
		qWarning("WASAPIOutput: Activate AudioClient failed");
		goto cleanup;
	}

	hr = pAudioClient->GetMixFormat(&pwfx);
	if (FAILED(hr)) {
		qWarning("WASAPIOutput: GetMixFormat failed: %llx", hr);
		goto cleanup;
	}
	pwfxe = reinterpret_cast<WAVEFORMATEXTENSIBLE *>(pwfx);

	if (FAILED(hr) || (pwfx->wBitsPerSample != (sizeof(float) * 8)) || (pwfxe->SubFormat != KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
		qWarning("WASAPIOutput: Subformat is not IEEE Float");
		goto cleanup;
	}

	iMixerFreq = pwfx->nSamplesPerSec;

	hr = pAudioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, bufferDuration, 0, pwfx, NULL);
	if (FAILED(hr)) {
		qWarning("WASAPIOutput: Initialize failed");
		goto cleanup;
	}

	pAudioClient->GetDevicePeriod(&def, &min);
	pAudioClient->GetBufferSize(&bufferFrameCount);
	pAudioClient->GetStreamLatency(&latency);

	qWarning("WASAPIOutput: Periods %lldus %lldus (latency %lldus)", def / 10LL, min / 10LL, latency / 10LL);
	qWarning("WASAPIOutput: Buffer is %dus (%d)", (bufferFrameCount * 1000000) / iMixerFreq, g.s.iOutputDelay);

	hr = pAudioClient->GetService(__uuidof(IAudioRenderClient), (void**)&pRenderClient);
	if (FAILED(hr)) {
		qWarning("WASAPIOutput: GetService failed");
		goto cleanup;
	}

	wantLength = lroundf(ceilf((iFrameSize * pwfx->nSamplesPerSec) / (SAMPLE_RATE * 1.0f)));

	pAudioClient->SetEventHandle(hEvent);
	if (FAILED(hr)) {
		qWarning("WASAPIOutput: Failed to set event");
		goto cleanup;
	}

	hr = pAudioClient->Start();
	if (FAILED(hr)) {
		qWarning("WASAPIOutput: Failed to start");
		goto cleanup;
	}

	for (int i=0;i<32;i++) {
		if (pwfxe->dwChannelMask & (1 << i)) {
			chanmasks[ns++] = 1 << i;
		}
	}
	if (ns != pwfx->nChannels) {
		qWarning("WASAPIOutput: Chanmask bits doesn't match number of channels.");
	}

	iChannels = pwfx->nChannels;
	initializeMixer(chanmasks);

	bool mixed = false;
	while (bRunning && ! FAILED(hr)) {
		hr = pAudioClient->GetCurrentPadding(&numFramesAvailable);
		if (FAILED(hr))
			goto cleanup;

		packetLength = bufferFrameCount - numFramesAvailable;

		if (lastspoke != (g.bAttenuateOthers || mixed)) {
			lastspoke = g.bAttenuateOthers || mixed;
			setVolumes(pDevice, lastspoke);
		}

		while (packetLength > 0) {
			hr = pRenderClient->GetBuffer(packetLength, &pData);
			if (FAILED(hr))
				goto cleanup;

			mixed = mix(reinterpret_cast<float *>(pData), packetLength);
			if (mixed)
				hr = pRenderClient->ReleaseBuffer(packetLength, 0);
			else
				hr = pRenderClient->ReleaseBuffer(packetLength, AUDCLNT_BUFFERFLAGS_SILENT);
			if (FAILED(hr))
				goto cleanup;

			if (!g.s.bAttenuateOthers && !g.bAttenuateOthers) {
				mixed = false;
			}

			if (lastspoke != (g.bAttenuateOthers || mixed)) {
				lastspoke = g.bAttenuateOthers || mixed;
				setVolumes(pDevice, lastspoke);
			}

			hr = pAudioClient->GetCurrentPadding(&numFramesAvailable);
			if (FAILED(hr))
				goto cleanup;

			packetLength = bufferFrameCount - numFramesAvailable;
		}
		if (! FAILED(hr))
			WaitForSingleObject(hEvent, 2000);
	}

cleanup:
	if (pwfx)
		CoTaskMemFree(pwfx);

	setVolumes(pDevice, false);

	if (pAudioClient) {
		pAudioClient->Stop();
		pAudioClient->Release();
	}
	if (pRenderClient)
		pRenderClient->Release();
	if (pDevice)
		pDevice->Release();

	if (pEnumerator)
		pEnumerator->Release();

	if (hMmThread != NULL)
		AvRevertMmThreadCharacteristics(hMmThread);

	if (hEvent != NULL)
		CloseHandle(hEvent);
}


text:
package com.irurueta.server.commons.email;

import com.irurueta.server.commons.configuration.ConfigurationException;

/**
 * Base class for Apache and JavaMail senders.
 */
public abstract class CommonEmailSender extends EmailSender {
    /**
     * Minimum allowed port value to connect to SMTP server.
     */
    private static final int MIN_PORT_VALUE = 0;

    /**
     * Maximum allowed port value to connect to SMTP server.
     */
    private static final int MAX_PORT_VALUE = 65535;

    /**
     * SMTP server host to connect to.
     */
    protected String mMailHost;

    /**
     * SMTP server port to connect to.
     */
    protected int mMailPort;

    /**
     * User id to log into SMTP server. If none is provided no authentication
     * will be used.
     */
    protected String mMailId;

    /**
     * User password to log into SMTP server. If none is provided no
     * authentication will be used.
     */
    protected String mMailPassword;

    /**
     * Address to send emails from.
     */
    protected String mMailFromAddress;

    /**
     * Indicates if mail sending is enabled.
     */
    protected boolean mEnabled;

    /**
     * Constructors.
     * Loads mail configuration, and if it fails for some reason, mail sending
     * becomes disabled.
     */
    protected CommonEmailSender() {
        try {
            final MailConfiguration cfg = MailConfigurationFactory.getInstance().
                    configure();
            mMailHost = cfg.getMailHost();
            mMailPort = cfg.getMailPort();
            mMailId = cfg.getMailId();
            mMailPassword = cfg.getMailPassword();
            mMailFromAddress = cfg.getMailFromAddress();

            mEnabled = isValidConfiguration(mMailHost, mMailPort,
                    mMailFromAddress) && cfg.isMailSendingEnabled();
        } catch (final ConfigurationException e) {
            mEnabled = false;
        }
    }

    /**
     * Returns SMTP server host.
     *
     * @return SMTP server host.
     */
    public String getMailHost() {
        return mMailHost;
    }

    /**
     * Returns SMTP server port.
     *
     * @return SMTP server port.
     */
    public int getMailPort() {
        return mMailPort;
    }

    /**
     * Returns user id to log into SMTP server. If this value is null server
     * authentication will be disabled.
     *
     * @return user id to log into SMTP server.
     */
    public String getMailId() {
        return mMailId;
    }

    /**
     * Returns user password to log into SMTP server. If this value is null
     * server authentication will be disabled.
     *
     * @return user password to log into SMTP server.
     */
    public String getMailPassword() {
        return mMailPassword;
    }

    /**
     * Email address to send emails from.
     *
     * @return email address to send emails from.
     */
    public String getMailFromAddress() {
        return mMailFromAddress;
    }

    /**
     * Indicates if this mail sender controller is enabled.
     *
     * @return true if enabled, false otherwise.
     */
    public boolean isEnabled() {
        return mEnabled;
    }

    /**
     * Indicates if provided configuration is valid by checking that SMTP server
     * and mail from address are not null, and server port is valid.
     *
     * @param mailHost        SMTP server host.
     * @param mailPort        SMTP server port.
     * @param mailFromAddress email address to send emails from.
     * @return true if configuration is valid, false otherwise.
     */
    private boolean isValidConfiguration(final String mailHost, final int mailPort,
                                         final String mailFromAddress) {
        return mailHost != null && mailPort >= MIN_PORT_VALUE &&
                mailPort <= MAX_PORT_VALUE && mailFromAddress != null &&
                isValidEmailAddress(mailFromAddress);
    }
}


text:
>

### How/when does this error happen? login?:
>

### Is there an error in the console? Use pastebin.com. Is there a kick message?:
>


text:
package org.apache.velocity.runtime.directive;

import java.io.Writer;
import java.io.IOException;

import org.apache.velocity.runtime.RuntimeServices;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.runtime.parser.node.Node;

import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.TemplateInitException;

/**
 * Base class for all directives used in Velocity.
 *
 * @author Jason van Zyl
 * @version $Id$
 */
public abstract class Directive implements DirectiveConstants, Cloneable
{
    private int line = 0;
    private int column = 0;
    private String templateName;

    /**
     *
     */
    protected RuntimeServices rsvc = null;

    /**
     * Return the name of this directive.
     * @return The name of this directive.
     */
    public abstract String getName();

    /**
     * Get the directive type BLOCK/LINE.
     * @return The directive type BLOCK/LINE.
     */
    public abstract int getType();

    /**
     * Allows the template location to be set.
     * @param line
     * @param column
     */
    public void setLocation( int line, int column )
    {
        this.line = line;
        this.column = column;
    }

    /**
     * Allows the template location to be set.
     * @param line
     * @param column
     */
    public void setLocation(int line, int column, String templateName)
    {
        setLocation(line, column);
        this.templateName = templateName;
    }

    /**
     * for log msg purposes
     * @return The current line for log msg purposes.
     */
    public int getLine()
    {
        return line;
    }

    /**
     * for log msg purposes
     * @return The current column for log msg purposes.
     */
    public int getColumn()
    {
        return column;
    }

    /**
     * @return The template file name this directive was defined in, or null if not
     * defined in a file.
     */
    public String getTemplateName()
    {
      return templateName;
    }

    /**
     * How this directive is to be initialized.
     * @param rs
     * @param context
     * @param node
     * @throws TemplateInitException
     */
    public void init( RuntimeServices rs, InternalContextAdapter context,
                      Node node)
        throws TemplateInitException
    {
        rsvc = rs;

        //        int i, k = node.jjtGetNumChildren();

        //for (i = 0; i < k; i++)
        //    node.jjtGetChild(i).init(context, rs);
    }

    /**
     * How this directive is to be rendered
     * @param context
     * @param writer
     * @param node
     * @return True if the directive rendered successfully.
     * @throws IOException
     * @throws ResourceNotFoundException
     * @throws ParseErrorException
     * @throws MethodInvocationException
     */
    public abstract boolean render( InternalContextAdapter context,
                                    Writer writer, Node node )
           throws IOException, ResourceNotFoundException, ParseErrorException,
                MethodInvocationException;
}


text:
package test

type typeForTest [4]uint8


text:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import { NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import { AlertService, EventManager } from 'ng-jhipster';

import { UserModalService } from './user-modal.service';
import {  User, UserService } from '../../shared';

@Component({
    selector: 'jhi-user-mgmt-dialog',
    templateUrl: './user-management-dialog.component.html'
})
export class UserMgmtDialogComponent implements OnInit {

    user: User;
    languages: any[];
    authorities: any[];
    isSaving: Boolean;

    constructor(
        public activeModal: NgbActiveModal,
        private userService: UserService,
        private alertService: AlertService,
        private eventManager: EventManager
    ) {}

    ngOnInit() {
        this.isSaving = false;
        this.authorities = [];
        this.userService.authorities().subscribe((authorities) => {
            this.authorities = authorities;
        });
    }

    clear() {
        this.activeModal.dismiss('cancel');
    }

    save() {
        this.isSaving = true;
        if (this.user.id !== null) {
            this.userService.update(this.user).subscribe((response) => this.onSaveSuccess(response, false), () => this.onSaveError());
        } else {
            this.user.langKey = 'en';
            this.userService.create(this.user).subscribe((response) => this.onSaveSuccess(response, true), () => this.onSaveError());
        }
    }

    private onSaveSuccess(result, isCreated: boolean) {
        this.alertService.success(
            isCreated ? `A new user is created with identifier ${result.json.login}`
            : `An user is updated with identifier ${result.json.login}`,
            null, null);
        this.eventManager.broadcast({ name: 'userListModification', content: 'OK' });
        this.isSaving = false;
        this.activeModal.dismiss(result);
    }

    private onSaveError() {
        this.isSaving = false;
    }
}

@Component({
    selector: 'jhi-user-dialog',
    template: ''
})
export class UserDialogComponent implements OnInit, OnDestroy {

    modalRef: NgbModalRef;
    routeSub: any;

    constructor(
        private route: ActivatedRoute,
        private userModalService: UserModalService
    ) {}

    ngOnInit() {
        this.routeSub = this.route.params.subscribe((params) => {
            if ( params['login'] ) {
                this.modalRef = this.userModalService.open(UserMgmtDialogComponent, params['login']);
            } else {
                this.modalRef = this.userModalService.open(UserMgmtDialogComponent);
            }
        });
    }

    ngOnDestroy() {
        this.routeSub.unsubscribe();
    }
}


text:
.frankenslide-slider,.frankenslide-slider .items {
  position: relative;
}
.frankenslide-slider .items {
  left: 0;
  width: 100000px;
}
.frankenslide-slider-touch {
  -webkit-transform: translate3d(0, 0, 0);
}
.frankenslide-slider-touch .items {
  -webkit-transition-timing-function: cubic-bezier(0, 0, 0.2, 1);
  -webkit-font-smoothing: antialiased;
}
.frankenslide-slider-touch .item {
  -webkit-transform: translate3d(0, 0, 0);
}


text:
``max_hit_ratio_k``
-------------------

- Available in: GBM, DRF, Deep Learning
- Hyperparameter: no

Description
~~~~~~~~~~~
Hit ratios can be used to evaluate the performance of a model. The hit ratio is the percentage of instances where the model correctly predicts the actual class of an observation. The ``max_hit_ratio_k`` option specifies the maximum number of predictions to consider for the hit ratio computation.

Note that this option is available for multiclass problems only and is set to 0 (disabled) by default.

Example
~~~~~~~

.. example-code::
   .. code-block:: r

	library(h2o)
	h2o.init()

	# import the covtype dataset:
	# this dataset is used to classify the correct forest cover type
	# original dataset can be found at https://archive.ics.uci.edu/ml/datasets/Covertype
	covtype <- h2o.importFile("https://s3.amazonaws.com/h2o-public-test-data/smalldata/covtype/covtype.20k.data")

	# convert response column to a factor
	covtype[,55] <- as.factor(covtype[,55])

	# set the predictor names and the response column name
	predictors <- colnames(covtype[1:54])
	response <- 'C55'

	# split into train and validation sets
	covtype.splits <- h2o.splitFrame(data =  covtype, ratios = .8, seed = 1234)
	train <- covtype.splits[[1]]
	valid <- covtype.splits[[2]]

	# try using the max_hit_ratio_k parameter:
	# max_hit_ratio_k does not affect the actual model fit, and is for information
	# and inner-H2O calculations
	cov_gbm <- h2o.gbm(x = predictors, y = response, training_frame = train,
	                   validation_frame = valid, max_hit_ratio_k = 3, seed = 1234)

	# print out model results to see the max_hite_ratio_k table
	cov_gbm

   .. code-block:: python

	import h2o
	from h2o.estimators.gbm import H2OGradientBoostingEstimator
	h2o.init(strict_version_check=False)
	h2o.cluster().show_status()

	# import the covtype dataset:
	# this dataset is used to classify the correct forest cover type
	# original dataset can be found at https://archive.ics.uci.edu/ml/datasets/Covertype
	covtype = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/covtype/covtype.20k.data")

	# convert response column to a factor
	covtype[54] = covtype[54].asfactor()

	# set the predictor names and the response column name
	predictors = covtype.columns[0:54]
	response = 'C55'

	# split into train and validation sets
	train, valid = covtype.split_frame(ratios = [.8], seed = 1234)

	# try using the max_hit_ratio_k parameter:
	# max_hit_ratio_k does not affect the actual model fit, and is for information
	# and inner-H2O calculations
	cov_gbm = H2OGradientBoostingEstimator(max_hit_ratio_k = 3, seed = 1234)

	cov_gbm.train(x = predictors, y = response, training_frame = train, validation_frame = valid)

	# print out model results to see the max_hite_ratio_k table
	cov_gbm.show()


text:
// Get an XmlHttpRequest Object
function getXmlHttpRequestObject() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else {
        alert("Your browser doesn't support search on this site - please upgrade to a newer one");
    }
}

// Called when keyup happens in the search box, starts the API request
function searchSuggest(searchBox) {
    var str = escape(document.getElementById(searchBox).value);
    API.GET
}


text:
package galvin.swing.tree;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;

public class DraggableTreeNode
    extends DefaultMutableTreeNode
{

    private boolean draggable = true;
    private boolean allowMoreChildren = true;
    private boolean canBeReparented = true;

    public DraggableTreeNode()
    {
        super();
    }

    public DraggableTreeNode( Object userObject )
    {
        super( userObject );
    }

    public DraggableTreeNode( Object userObject, boolean draggable )
    {
        super( userObject );
        this.draggable = draggable;
    }

    public DraggableTreeNode( Object userObject,
                              boolean draggable,
                              boolean allowsChildren )
    {
        this( userObject, draggable, allowsChildren, true );
    }

    public DraggableTreeNode( Object userObject,
                              boolean draggable,
                              boolean allowsChildren,
                              boolean allowsMoreChildren )
    {
        this( userObject, draggable, allowsChildren, true, true );
    }

    public DraggableTreeNode( Object userObject,
                              boolean draggable,
                              boolean allowsChildren,
                              boolean allowsMoreChildren,
                              boolean canBeReparented)
    {
        setDraggable( draggable );
        setAllowsChildren( allowsChildren );
        setAllowMoreChildren( allowsMoreChildren );
        setCanBeReparented( canBeReparented );
    }

    public boolean isDraggable()
    {
        return draggable;
    }

    public void setDraggable( boolean draggable )
    {
        this.draggable = draggable;
    }

    public boolean getAllowsMoreChildren()
    {
        return allowMoreChildren;
    }

    public void setAllowMoreChildren( boolean allowMoreChildren )
    {
        this.allowMoreChildren = allowMoreChildren;
    }

    public boolean canBeReparented()
    {
        return canBeReparented;
    }

    public void setCanBeReparented( boolean canBeReparented )
    {
        this.canBeReparented = canBeReparented;
    }

    @Override
    public void add( MutableTreeNode newChild )
    {
        if( newChild instanceof DraggableTreeNode )
        {
            super.add( newChild );
        }
        else
        {
            throw new IllegalArgumentException( "Node " + newChild + " is not of type DraggableTreeNode." );
        }
    }

    @Override
    public void insert( MutableTreeNode newChild, int index )
    {
        if( newChild instanceof DraggableTreeNode )
        {
            super.insert( newChild, index );
        }
        else
        {
            throw new IllegalArgumentException( "Node " + newChild + " is not of type DraggableTreeNode." );
        }
    }
}


text:
namespace AjTalk.Language
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using AjTalk.Compiler;

    public class EnumerableBehavior : NativeBehavior
    {
        public EnumerableBehavior(IBehavior behavior, IBehavior superclass, Machine machine)
            : base(behavior, superclass, machine, typeof(IEnumerable))
        {
            string dosource = @"
do: aBlock
    | enumerator |

    enumerator := self !GetEnumerator.

    [enumerator !MoveNext] whileTrue:
		[ aBlock value: enumerator !Current ]
            ";
            string selectsource = @"
select: aBlock
    | enumerator list |

    enumerator := self !GetEnumerator.
    list := @System.Collections.ArrayList !new.

    [enumerator !MoveNext] whileTrue:
		[ | item |
          item := enumerator !Current.
            (aBlock value: item) ifTrue:  [ list add: item ]
        ].
    ^list
            ";

            Parser parser = new Parser(dosource);
            this.DefineInstanceMethod(parser.CompileInstanceMethod(this));
            parser = new Parser(selectsource);
            this.DefineInstanceMethod(parser.CompileInstanceMethod(this));
            this.DefineInstanceMethod(new FunctionalMethod("includes:", this, this.IncludesMethod));
        }

        private object IncludesMethod(Machine machine, object obj, object[] arguments)
        {
            var list = obj as IList;
            var argument = arguments[0];

            if (list != null)
                return list.Contains(argument);

            foreach (var element in (IEnumerable)obj)
            {
                if (element == null && argument == null)
                    return true;
                if (element != null && element.Equals(argument))
                    return true;
            }

            return false;
        }
    }
}


text:
/**
 * Import common SimpleTest methods so that they're usable in this window.
 */
var imports = [ "SimpleTest", "is", "isnot", "ise", "ok", "onerror", "todo",
  "todo_is", "todo_isnot" ];
for each (var name in imports) {
  window[name] = window.opener.wrappedJSObject[name];
}

/**
 * Define global constants and variables.
 */
const NAV_NONE = 0;
const NAV_BACK = 1;
const NAV_FORWARD = 2;
const NAV_URI = 3;
const NAV_RELOAD = 4;

var gExpectedEvents;          // an array of events which are expected to
                              // be triggered by this navigation
var gUnexpectedEvents;        // an array of event names which are NOT expected
                              // to be triggered by this navigation
var gFinalEvent;              // true if the last expected event has fired
var gUrisNotInBFCache = [];   // an array of uri's which shouldn't be stored
                              // in the bfcache
var gNavType = NAV_NONE;      // defines the most recent navigation type
                              // executed by doPageNavigation
var gOrigMaxTotalViewers =    // original value of max_total_viewers,
  undefined;                  // to be restored at end of test

var gExtractedPath = null;    //used to cache file path for extracting files from a .jar file

/**
 * The doPageNavigation() function performs page navigations asynchronously,
 * listens for specified events, and compares actual events with a list of
 * expected events.  When all expected events have occurred, an optional
 * callback can be notified. The parameter passed to this function is an
 * object with the following properties:
 *
 *                uri: if !undefined, the browser will navigate to this uri
 *
 *               back: if true, the browser will execute goBack()
 *
 *            forward: if true, the browser will execute goForward()
 *
 *             reload: if true, the browser will execute reload()
 *
 *  eventsToListenFor: an array containing one or more of the following event
 *                     types to listen for:  "pageshow", "pagehide", "onload",
 *                     "onunload".  If this property is undefined, only a
 *                     single "pageshow" events will be listened for.  If this
 *                     property is explicitly empty, [], then no events will
 *                     be listened for.
 *
 *     expectedEvents: an array of one or more expectedEvent objects,
 *                     corresponding to the events which are expected to be
 *                     fired for this navigation.  Each object has the
 *                     following properties:
 *
 *                          type: one of the event type strings
 *                          title (optional): the title of the window the
 *                              event belongs to
 *                          persisted (optional): the event's expected
 *                              .persisted attribute
 *
 *                     This function will verify that events with the
 *                     specified properties are fired in the same order as
 *                     specified in the array.  If .title or .persisted
 *                     properties for an expectedEvent are undefined, those
 *                     properties will not be verified for that particular
 *                     event.
 *
 *                     This property is ignored if eventsToListenFor is
 *                     undefined or [].
 *
 *     preventBFCache: if true, an unload handler will be added to the loaded
 *                     page to prevent it from being bfcached.  This property
 *                     has no effect when eventsToListenFor is [].
 *
 *      onNavComplete: a callback which is notified after all expected events
 *                     have occurred, or after a timeout has elapsed.  This
 *                     callback is not notified if eventsToListenFor is [].
 *
 * There must be an expectedEvent object for each event of the types in
 * eventsToListenFor which is triggered by this navigation.  For example, if
 * eventsToListenFor = [ "pagehide", "pageshow" ], then expectedEvents
 * must contain an object for each pagehide and pageshow event which occurs as
 * a result of this navigation.
 */
function doPageNavigation(params) {
  // Parse the parameters.
  let back = params.back ? params.back : false;
  let forward = params.forward ? params.forward : false;
  let reload = params.reload ? params.reload : false;
  let uri = params.uri ? params.uri : false;
  let eventsToListenFor = typeof(params.eventsToListenFor) != "undefined" ?
    params.eventsToListenFor : ["pageshow"];
  gExpectedEvents = typeof(params.eventsToListenFor) == "undefined" ||
    eventsToListenFor.length == 0 ? undefined : params.expectedEvents;
  gUnexpectedEvents = typeof(params.eventsToListenFor) == "undefined" ||
    eventsToListenFor.length == 0 ? undefined : params.unexpectedEvents;
  let preventBFCache = (typeof[params.preventBFCache] == "undefined") ?
    false : params.preventBFCache;
  let waitOnly = (typeof(params.waitForEventsOnly) == "boolean"
    && params.waitForEventsOnly);

  // Do some sanity checking on arguments.
  if (back && forward)
    throw "Can't specify both back and forward";
  if (back && uri)
    throw "Can't specify both back and a uri";
  if (forward && uri)
    throw "Can't specify both forward and a uri";
  if (reload && (forward || back || uri))
    throw "Can't specify reload and another navigation type";
  if (!back && !forward && !uri && !reload && !waitOnly)
    throw "Must specify back or foward or reload or uri";
  if (params.onNavComplete && eventsToListenFor.length == 0)
    throw "Can't use onNavComplete when eventsToListenFor == []";
  if (params.preventBFCache && eventsToListenFor.length == 0)
    throw "Can't use preventBFCache when eventsToListenFor == []";
  if (params.preventBFCache && waitOnly)
    throw "Can't prevent bfcaching when only waiting for events";
  if (waitOnly && typeof(params.onNavComplete) == "undefined")
    throw "Must specify onNavComplete when specifying waitForEventsOnly";
  if (waitOnly && (back || forward || reload || uri))
    throw "Can't specify a navigation type when using waitForEventsOnly";
  for each (let anEventType in eventsToListenFor) {
    let eventFound = false;
    if ( (anEventType == "pageshow") && (!gExpectedEvents) )
      eventFound = true;
    for each (let anExpectedEvent in gExpectedEvents) {
      if (anExpectedEvent.type == anEventType)
        eventFound = true;
    }
    for each (let anExpectedEventType in gUnexpectedEvents) {
      if (anExpectedEventType == anEventType)
        eventFound = true;
    }
    if (!eventFound)
      throw "Event type " + anEventType + " is specified in " +
        "eventsToListenFor, but not in expectedEvents";
  }

  // If the test explicitly sets .eventsToListenFor to [], don't wait for any
  // events.
  gFinalEvent = eventsToListenFor.length == 0 ? true : false;

  // Add an event listener for each type of event in the .eventsToListenFor
  // property of the input parameters.
  for each (let eventType in eventsToListenFor) {
    dump("TEST: registering a listener for " + eventType + " events\n");
    TestWindow.getBrowser().addEventListener(eventType, pageEventListener,
      true);
  }

  // Perform the specified navigation.
  if (back) {
    gNavType = NAV_BACK;
    TestWindow.getBrowser().goBack();
  }
  else if (forward) {
    gNavType = NAV_FORWARD;
    TestWindow.getBrowser().goForward();
  }
  else if (uri) {
    gNavType = NAV_URI;
    TestWindow.getBrowser().loadURI(uri);
  }
  else if (reload) {
    gNavType = NAV_RELOAD;
    TestWindow.getBrowser().reload();
  }
  else if (waitOnly) {
    gNavType = NAV_NONE;
  }
  else {
    throw "No valid navigation type passed to doPageNavigation!";
  }

  // If we're listening for events and there is an .onNavComplete callback,
  // wait for all events to occur, and then call doPageNavigation_complete().
  if (eventsToListenFor.length > 0 && params.onNavComplete)
  {
    waitForTrue(
      function() { return gFinalEvent; },
      function() {
        doPageNavigation_complete(eventsToListenFor, params.onNavComplete,
          preventBFCache);
      } );
  }
}

/**
 * Finish doPageNavigation(), by removing event listeners, adding an unload
 * handler if appropriate, and calling the onNavComplete callback.  This
 * function is called after all the expected events for this navigation have
 * occurred.
 */
function doPageNavigation_complete(eventsToListenFor, onNavComplete,
  preventBFCache) {
  // Unregister our event listeners.
  dump("TEST: removing event listeners\n");
  for each (let eventType in eventsToListenFor) {
    TestWindow.getBrowser().removeEventListener(eventType, pageEventListener,
      true);
  }

  // If the .preventBFCache property was set, add an empty unload handler to
  // prevent the page from being bfcached.
  let uri = TestWindow.getBrowser().currentURI.spec;
  if (preventBFCache) {
    TestWindow.getWindow().addEventListener("unload", function() {
        dump("TEST: Called dummy unload function to prevent page from " +
          "being bfcached.\n");
      }, true);

    // Save the current uri in an array of uri's which shouldn't be
    // stored in the bfcache, for later verification.
    if (!(uri in gUrisNotInBFCache)) {
      gUrisNotInBFCache.push(uri);
    }
  } else if (gNavType == NAV_URI) {
    // If we're navigating to a uri and .preventBFCache was not
    // specified, splice it out of gUrisNotInBFCache if it's there.
    gUrisNotInBFCache.forEach(
      function(element, index, array) {
        if (element == uri) {
          array.splice(index, 1);
        }
      }, this);
  }

  // Notify the callback now that we're done.
  onNavComplete.call();
}

/**
 * Allows a test to wait for page navigation events, and notify a
 * callback when they've all been received.  This works exactly the
 * same as doPageNavigation(), except that no navigation is initiated.
 */
function waitForPageEvents(params) {
  params.waitForEventsOnly = true;
  doPageNavigation(params);
}

/**
 * The event listener which listens for expectedEvents.
 */
function pageEventListener(event) {
  try {
    dump("TEST: eventListener received a " + event.type + " event for page " +
      event.originalTarget.title + ", persisted=" + event.persisted + "\n");
  } catch(e) {
    // Ignore any exception.
  }

  // If this page shouldn't be in the bfcache because it was previously
  // loaded with .preventBFCache, make sure that its pageshow event
  // has .persisted = false, even if the test doesn't explicitly test
  // for .persisted.
  if ( (event.type == "pageshow") &&
    (gNavType == NAV_BACK || gNavType == NAV_FORWARD) ) {
    let uri = TestWindow.getBrowser().currentURI.spec;
    if (uri in gUrisNotInBFCache) {
      ok(!event.persisted, "pageshow event has .persisted = false, even " +
       "though it was loaded with .preventBFCache previously\n");
    }
  }

  if (typeof(gUnexpectedEvents) != "undefined") {
    is(gUnexpectedEvents.indexOf(event.type), -1,
       "Should not get unexpected event " + event.type);
  }

  // If no expected events were specified, mark the final event as having been
  // triggered when a pageshow event is fired; this will allow
  // doPageNavigation() to return.
  if ((typeof(gExpectedEvents) == "undefined") && event.type == "pageshow")
  {
    setTimeout(function() { gFinalEvent = true; }, 0);
    return;
  }

  // If there are explicitly no expected events, but we receive one, it's an
  // error.
  if (gExpectedEvents.length == 0) {
    ok(false, "Unexpected event (" + event.type + ") occurred");
    return;
  }

  // Grab the next expected event, and compare its attributes against the
  // actual event.
  let expected = gExpectedEvents.shift();

  is(event.type, expected.type,
    "A " + expected.type + " event was expected, but a " +
    event.type + " event occurred");

  if (typeof(expected.title) != "undefined") {
    ok(event.originalTarget instanceof HTMLDocument,
       "originalTarget for last " + event.type +
       " event not an HTMLDocument");
    is(event.originalTarget.title, expected.title,
      "A " + event.type + " event was expected for page " +
      expected.title + ", but was fired for page " +
      event.originalTarget.title);
  }

  if (typeof(expected.persisted) != "undefined") {
    is(event.persisted, expected.persisted,
      "The persisted property of the " + event.type + " event on page " +
      event.originalTarget.location + " had an unexpected value");
  }

  if ("visibilityState" in expected) {
    is(event.originalTarget.mozVisibilityState, expected.visibilityState,
       "The visibilityState property of the document on page " +
       event.originalTarget.location + " had an unexpected value");
  }

  if ("hidden" in expected) {
    is(event.originalTarget.mozHidden, expected.hidden,
       "The hidden property of the document on page " +
       event.originalTarget.location + " had an unexpected value");
  }

  // If we're out of expected events, let doPageNavigation() return.
  if (gExpectedEvents.length == 0)
    setTimeout(function() { gFinalEvent = true; }, 0);
}

/**
 * End a test.
 */
function finish() {
  // Work around bug 467960.
  var history = TestWindow.getBrowser().webNavigation.sessionHistory;
  history.PurgeHistory(history.count);

  // If the test changed the value of max_total_viewers via a call to
  // enableBFCache(), then restore it now.
  if (typeof(gOrigMaxTotalViewers) != "undefined") {
    var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                .getService(Components.interfaces.nsIPrefBranch);
    prefs.setIntPref("browser.sessionhistory.max_total_viewers",
      gOrigMaxTotalViewers);
  }

  // Close the test window and signal the framework that the test is done.
  let opener = window.opener;
  let SimpleTest = opener.wrappedJSObject.SimpleTest;

  // Wait for the window to be closed before finishing the test
  let ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
	             .getService(Components.interfaces.nsIWindowWatcher);
  ww.registerNotification(function(subject, topic, data) {
    if (topic == "domwindowclosed") {
      ww.unregisterNotification(arguments.callee);
      SimpleTest.waitForFocus(function() {
        SimpleTest.finish();
      }, opener);
    }
  });

  window.close();
}

/**
 * Helper function which waits until another function returns true, or until a
 * timeout occurs, and then notifies a callback.
 *
 * Parameters:
 *
 *    fn: a function which is evaluated repeatedly, and when it turns true,
 *        the onWaitComplete callback is notified.
 *
 *    onWaitComplete:  a callback which will be notified when fn() returns
 *        true, or when a timeout occurs.
 *
 *    timeout: a timeout, in seconds or ms, after which waitForTrue() will
 *        fail an assertion and then return, even if the fn function never
 *        returns true.  If timeout is undefined, waitForTrue() will never
 *        time out.
 */
function waitForTrue(fn, onWaitComplete, timeout) {
  var start = new Date().valueOf();
  if (typeof(timeout) != "undefined") {
    // If timeoutWait is less than 500, assume it represents seconds, and
    // convert to ms.
    if (timeout < 500)
      timeout *= 1000;
  }

  // Loop until the test function returns true, or until a timeout occurs,
  // if a timeout is defined.
  var intervalid;
  intervalid =
    setInterval(
      function() {
        var timeoutHit = false;
        if (typeof(timeout) != "undefined") {
          timeoutHit = new Date().valueOf() - start >=
            timeout ? true : false;
          if (timeoutHit) {
            ok(false, "Timed out waiting for condition");
          }
        }
        if (timeoutHit || fn.call()) {
          // Stop calling the test function and notify the callback.
          clearInterval(intervalid);
          onWaitComplete.call();
        }
      }, 20);
}

/**
 * Enable or disable the bfcache.
 *
 * Parameters:
 *
 *   enable: if true, set max_total_viewers to -1 (the default); if false, set
 *           to 0 (disabled), if a number, set it to that specific number
 */
function enableBFCache(enable) {
  var prefs = Components.classes["@mozilla.org/preferences-service;1"]
              .getService(Components.interfaces.nsIPrefBranch);

  // If this is the first time the test called enableBFCache(),
  // store the original value of max_total_viewers, so it can
  // be restored at the end of the test.
  if (typeof(gOrigMaxTotalViewers) == "undefined") {
    gOrigMaxTotalViewers =
      prefs.getIntPref("browser.sessionhistory.max_total_viewers");
  }

  if (typeof(enable) == "boolean") {
    if (enable)
      prefs.setIntPref("browser.sessionhistory.max_total_viewers", -1);
    else
      prefs.setIntPref("browser.sessionhistory.max_total_viewers", 0);
  }
  else if (typeof(enable) == "number") {
    prefs.setIntPref("browser.sessionhistory.max_total_viewers", enable);
  }
}

/*
 * get http root for local tests.  Use a single extractJarToTmp instead of
 * extracting for each test.
 * Returns a file://path if we have a .jar file
 */
function getHttpRoot() {
  var location = window.location.href;
  location = getRootDirectory(location);
  var jar = getJar(location);
  if (jar != null) {
    if (gExtractedPath == null) {
      var resolved = extractJarToTmp(jar);
      gExtractedPath = resolved.path;
    }
  } else {
    return null;
  }
  return "file://" + gExtractedPath + '/';
}

/**
 * Returns the full HTTP url for a file in the mochitest docshell test
 * directory.
 */
function getHttpUrl(filename) {
  var root = getHttpRoot();
  if (root == null) {
    root = "http://mochi.test:8888/chrome/docshell/test/chrome/";
  }
  return root + filename;
}

/**
 * A convenience object with methods that return the current test window,
 * browser, and document.
 */
var TestWindow = {};
TestWindow.getWindow = function () {
  return document.getElementById("content").contentWindow;
}
TestWindow.getBrowser = function () {
  return document.getElementById("content");
}
TestWindow.getDocument = function () {
  return document.getElementById("content").contentDocument;
}


text:
{% load i18n daguerre %}{% if display_image %}

{% endif %}

{% if value.url %}{% trans "Currently:" %} {{ value }}
{% if not required %}
<input type="checkbox" name="{{ checkbox_name }}" id="{{ checkbox_id }}">
{% trans "Clear" %}
{% endif %}

{% trans "Change:" %}
{% endif %}
<input type="{{ type }}" name="{{ name }}"{% if required %} required{% endif %}{% include "floppyforms/attrs.html" %}>


text:
using System;

namespace AutoProxy
{
    [Serializable]
    public class ProxyRule
    {
        private bool _enabled;
        private bool _default;
        private string _ssid;
        private ProxyHost _proxy;
        public ProxyHost Proxy
        {
            get { return _proxy; }
            set { _proxy = value; }
        }

        public bool Enabled
        {
            get { return _enabled; }
            set { _enabled = value; }
        }

        public bool Default
        {
            get { return _default; }
            set { _default = value; }
        }

        public string SSID
        {
            get { return _ssid; }
            set { _ssid = value; }
        }

        public ProxyRule (ProxyHost Proxy, string SSID)
        {
            this.Proxy = Proxy;
            this.SSID = SSID;
            this.Enabled = !Proxy.Host.StartsWith(":"); //Disabled if no proxy specified
            this.Default = SSID != ""; //Default if no SSID specified
        }

        public ProxyRule (string ProxyIP, int ProxyPort, string SSID)
        {
            this.Proxy = new ProxyHost(ProxyIP, ProxyPort);
            this.SSID = SSID;
            this.Enabled = !Proxy.Host.StartsWith(":");
            this.Default = SSID != "";
        }
    }
}


text:
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;

namespace FHSDK.Services.Hash
{
    internal class HashService : IHashService
    {
        public string GenerateSha1Hash(string str)
        {
            var hashProvider = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Sha1);
            var hash = hashProvider.HashData(CryptographicBuffer.ConvertStringToBinary(str, BinaryStringEncoding.Utf8));
            return CryptographicBuffer.EncodeToHexString(hash);
        }
    }
}


text:
require 'spec_helper'

RSpec.describe ChainedValidation::Rules::IsDate do
  let(:valid_params) {{ object: '10/10/2010' }}
  let(:invalid_params) {{ object: 'foo' }}

  context 'when validation is valid' do
    subject { described_class.new(valid_params) }
    it 'set attributes' do
      expect(subject.perform).to have_attributes(result: { is_date: { object: valid_params[:object], result: true }})
    end
  end

  context 'when validation is not valid' do
    subject { described_class.new(invalid_params) }
    it 'set attributes' do
      expect(subject.perform).to have_attributes(result: { is_date: { object: invalid_params[:object], result: false }})
    end
  end
end