text:
<?xml version='1.0' encoding='UTF-8'?>
<rdf:RDF xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#'>

<rdf:Description rdf:about='/Volumes/Lacie2Big/images-work/rogerdigifoto/kalabsha/originals/isawi-201107061813531-original.jpg'
  xmlns:et='http://ns.exiftool.ca/1.0/' et:toolkit='Image::ExifTool 7.76'
  xmlns:ExifTool='http://ns.exiftool.ca/ExifTool/1.0/'
  xmlns:File='http://ns.exiftool.ca/File/1.0/'
  xmlns:IFD0='http://ns.exiftool.ca/EXIF/IFD0/1.0/'
  xmlns:ExifIFD='http://ns.exiftool.ca/EXIF/ExifIFD/1.0/'
  xmlns:Photoshop='http://ns.exiftool.ca/Photoshop/Photoshop/1.0/'
  xmlns:ICC-header='http://ns.exiftool.ca/ICC_Profile/ICC-header/1.0/'
  xmlns:ICC_Profile='http://ns.exiftool.ca/ICC_Profile/ICC_Profile/1.0/'
  xmlns:XMP-x='http://ns.exiftool.ca/XMP/XMP-x/1.0/'
  xmlns:XMP-tiff='http://ns.exiftool.ca/XMP/XMP-tiff/1.0/'
  xmlns:XMP-exif='http://ns.exiftool.ca/XMP/XMP-exif/1.0/'
  xmlns:XMP-xmp='http://ns.exiftool.ca/XMP/XMP-xmp/1.0/'
  xmlns:XMP-crs='http://ns.exiftool.ca/XMP/XMP-crs/1.0/'
  xmlns:Adobe='http://ns.exiftool.ca/APP14/Adobe/1.0/'
  xmlns:Composite='http://ns.exiftool.ca/Composite/1.0/'>
 <ExifTool:ExifToolVersion>7.76</ExifTool:ExifToolVersion>
 <File:FileName>isawi-201107061813531-original.jpg</File:FileName>
 <File:Directory>/Volumes/Lacie2Big/images-work/rogerdigifoto/kalabsha/originals</File:Directory>
 <File:FileSize>922 kB</File:FileSize>
 <File:FileModifyDate>2011:07:06 14:13:48-04:00</File:FileModifyDate>
 <File:FileType>JPEG</File:FileType>
 <File:MIMEType>image/jpeg</File:MIMEType>
 <File:ExifByteOrder>Little-endian (Intel, II)</File:ExifByteOrder>
 <File:ImageWidth>2836</File:ImageWidth>
 <File:ImageHeight>2071</File:ImageHeight>
 <File:EncodingProcess>Baseline DCT, Huffman coding</File:EncodingProcess>
 <File:BitsPerSample>8</File:BitsPerSample>
 <File:ColorComponents>3</File:ColorComponents>
 <File:YCbCrSubSampling>YCbCr4:4:4 (1 1)</File:YCbCrSubSampling>
 <IFD0:Make>SONY</IFD0:Make>
 <IFD0:Model>DSC-H7</IFD0:Model>
 <IFD0:XResolution>240</IFD0:XResolution>
 <IFD0:YResolution>240</IFD0:YResolution>
 <IFD0:ResolutionUnit>inches</IFD0:ResolutionUnit>
 <IFD0:ModifyDate>2011:03:24 16:08:38</IFD0:ModifyDate>
 <ExifIFD:ExposureTime>1/1600</ExifIFD:ExposureTime>
 <ExifIFD:FNumber>5.6</ExifIFD:FNumber>
 <ExifIFD:ExposureProgram>Not Defined</ExifIFD:ExposureProgram>
 <ExifIFD:ISO>100</ExifIFD:ISO>
 <ExifIFD:ExifVersion>0221</ExifIFD:ExifVersion>
 <ExifIFD:DateTimeOriginal>2009:02:27 09:17:48</ExifIFD:DateTimeOriginal>
 <ExifIFD:CreateDate>2009:02:27 09:17:48</ExifIFD:CreateDate>
 <ExifIFD:ShutterSpeedValue>1/1600</ExifIFD:ShutterSpeedValue>
 <ExifIFD:ApertureValue>5.6</ExifIFD:ApertureValue>
 <ExifIFD:ExposureCompensation>0</ExifIFD:ExposureCompensation>
 <ExifIFD:MaxApertureValue>2.7</ExifIFD:MaxApertureValue>
 <ExifIFD:MeteringMode>Multi-segment</ExifIFD:MeteringMode>
 <ExifIFD:LightSource>Unknown</ExifIFD:LightSource>
 <ExifIFD:Flash>Off, Did not fire</ExifIFD:Flash>
 <ExifIFD:FocalLength>5.5 mm</ExifIFD:FocalLength>
 <ExifIFD:UserComment>; original file name was: DSC09696_1.JPG</ExifIFD:UserComment>
 <ExifIFD:FileSource>Digital Camera</ExifIFD:FileSource>
 <ExifIFD:SceneType>Directly photographed</ExifIFD:SceneType>
 <ExifIFD:CustomRendered>Normal</ExifIFD:CustomRendered>
 <ExifIFD:ExposureMode>Auto</ExifIFD:ExposureMode>
 <ExifIFD:WhiteBalance>Auto</ExifIFD:WhiteBalance>
 <ExifIFD:SceneCaptureType>Night</ExifIFD:SceneCaptureType>
 <ExifIFD:Contrast>Normal</ExifIFD:Contrast>
 <ExifIFD:Saturation>Normal</ExifIFD:Saturation>
 <ExifIFD:Sharpness>Normal</ExifIFD:Sharpness>
 <Photoshop:XResolution>240</Photoshop:XResolution>
 <Photoshop:DisplayedUnitsX>inches</Photoshop:DisplayedUnitsX>
 <Photoshop:YResolution>240</Photoshop:YResolution>
 <Photoshop:DisplayedUnitsY>inches</Photoshop:DisplayedUnitsY>
 <Photoshop:PhotoshopThumbnail>(Binary data 9650 bytes, use -b option to extract)</Photoshop:PhotoshopThumbnail>
 <Photoshop:IPTCDigest>00000000000000000000000000000000</Photoshop:IPTCDigest>
 <ICC-header:ProfileCMMType>ADBE</ICC-header:ProfileCMMType>
 <ICC-header:ProfileVersion>2.1.0</ICC-header:ProfileVersion>
 <ICC-header:ProfileClass>Display Device Profile</ICC-header:ProfileClass>
 <ICC-header:ColorSpaceData>RGB </ICC-header:ColorSpaceData>
 <ICC-header:ProfileConnectionSpace>XYZ </ICC-header:ProfileConnectionSpace>
 <ICC-header:ProfileDateTime>1999:06:03 00:00:00</ICC-header:ProfileDateTime>
 <ICC-header:ProfileFileSignature>acsp</ICC-header:ProfileFileSignature>
 <ICC-header:PrimaryPlatform>Apple Computer Inc.</ICC-header:PrimaryPlatform>
 <ICC-header:CMMFlags>Not Embedded, Independent</ICC-header:CMMFlags>
 <ICC-header:DeviceManufacturer>none</ICC-header:DeviceManufacturer>
 <ICC-header:DeviceModel></ICC-header:DeviceModel>
 <ICC-header:DeviceAttributes>Reflective, Glossy, Positive, Color</ICC-header:DeviceAttributes>
 <ICC-header:RenderingIntent>Perceptual</ICC-header:RenderingIntent>
 <ICC-header:ConnectionSpaceIlluminant>0.9642 1 0.82491</ICC-header:ConnectionSpaceIlluminant>
 <ICC-header:ProfileCreator>ADBE</ICC-header:ProfileCreator>
 <ICC-header:ProfileID>0</ICC-header:ProfileID>
 <ICC_Profile:ProfileCopyright>Copyright 1999 Adobe Systems Incorporated</ICC_Profile:ProfileCopyright>
 <ICC_Profile:ProfileDescription>Adobe RGB (1998)</ICC_Profile:ProfileDescription>
 <ICC_Profile:MediaWhitePoint>0.95045 1 1.08905</ICC_Profile:MediaWhitePoint>
 <ICC_Profile:MediaBlackPoint>0 0 0</ICC_Profile:MediaBlackPoint>
 <ICC_Profile:RedTRC>(Binary data 14 bytes, use -b option to extract)</ICC_Profile:RedTRC>
 <ICC_Profile:GreenTRC>(Binary data 14 bytes, use -b option to extract)</ICC_Profile:GreenTRC>
 <ICC_Profile:BlueTRC>(Binary data 14 bytes, use -b option to extract)</ICC_Profile:BlueTRC>
 <ICC_Profile:RedMatrixColumn>0.60974 0.31111 0.01947</ICC_Profile:RedMatrixColumn>
 <ICC_Profile:GreenMatrixColumn>0.20528 0.62567 0.06087</ICC_Profile:GreenMatrixColumn>
 <ICC_Profile:BlueMatrixColumn>0.14919 0.06322 0.74457</ICC_Profile:BlueMatrixColumn>
 <XMP-x:XMPToolkit>Adobe XMP Core 4.2-c020 1.124078, Tue Sep 11 2007 23:21:40        </XMP-x:XMPToolkit>
 <XMP-tiff:Make>SONY</XMP-tiff:Make>
 <XMP-tiff:Model>DSC-H7</XMP-tiff:Model>
 <XMP-tiff:ImageWidth>2836</XMP-tiff:ImageWidth>
 <XMP-tiff:ImageHeight>2071</XMP-tiff:ImageHeight>
 <XMP-tiff:XResolution>240</XMP-tiff:XResolution>
 <XMP-tiff:YResolution>240</XMP-tiff:YResolution>
 <XMP-tiff:ResolutionUnit>inches</XMP-tiff:ResolutionUnit>
 <XMP-exif:ExifVersion>0221</XMP-exif:ExifVersion>
 <XMP-exif:ExposureTime>1/1600</XMP-exif:ExposureTime>
 <XMP-exif:ShutterSpeedValue>1/1600</XMP-exif:ShutterSpeedValue>
 <XMP-exif:FNumber>5.6</XMP-exif:FNumber>
 <XMP-exif:ApertureValue>5.6</XMP-exif:ApertureValue>
 <XMP-exif:ExposureProgram>Unknown (0)</XMP-exif:ExposureProgram>
 <XMP-exif:DateTimeOriginal>2009:02:27 09:17:48-05:00</XMP-exif:DateTimeOriginal>
 <XMP-exif:DateTimeDigitized>2009:02:27 09:17:48-05:00</XMP-exif:DateTimeDigitized>
 <XMP-exif:ExposureCompensation>0</XMP-exif:ExposureCompensation>
 <XMP-exif:MaxApertureValue>2.7</XMP-exif:MaxApertureValue>
 <XMP-exif:MeteringMode>Multi-segment</XMP-exif:MeteringMode>
 <XMP-exif:LightSource>Unknown</XMP-exif:LightSource>
 <XMP-exif:FocalLength>5.5 mm</XMP-exif:FocalLength>
 <XMP-exif:FileSource>Digital Camera</XMP-exif:FileSource>
 <XMP-exif:SceneType>Directly photographed</XMP-exif:SceneType>
 <XMP-exif:CustomRendered>Normal</XMP-exif:CustomRendered>
 <XMP-exif:ExposureMode>Auto</XMP-exif:ExposureMode>
 <XMP-exif:WhiteBalance>Auto</XMP-exif:WhiteBalance>
 <XMP-exif:SceneCaptureType>Night</XMP-exif:SceneCaptureType>
 <XMP-exif:Contrast>Normal</XMP-exif:Contrast>
 <XMP-exif:Saturation>Normal</XMP-exif:Saturation>
 <XMP-exif:Sharpness>Normal</XMP-exif:Sharpness>
 <XMP-exif:ExifImageWidth>2836</XMP-exif:ExifImageWidth>
 <XMP-exif:ExifImageHeight>2071</XMP-exif:ExifImageHeight>
 <XMP-exif:ISO>100</XMP-exif:ISO>
 <XMP-exif:FlashFired>False</XMP-exif:FlashFired>
 <XMP-exif:FlashReturn>No return detection</XMP-exif:FlashReturn>
 <XMP-exif:FlashMode>Off</XMP-exif:FlashMode>
 <XMP-exif:FlashFunction>False</XMP-exif:FlashFunction>
 <XMP-exif:FlashRedEyeMode>False</XMP-exif:FlashRedEyeMode>
 <XMP-xmp:ModifyDate>2011:03:24 16:08:38-04:00</XMP-xmp:ModifyDate>
 <XMP-xmp:CreateDate>2009:02:27 09:17:48-05:00</XMP-xmp:CreateDate>
 <XMP-crs:RawFileName>DSC09696.JPG</XMP-crs:RawFileName>
 <XMP-crs:Version>5.0</XMP-crs:Version>
 <XMP-crs:WhiteBalance>As Shot</XMP-crs:WhiteBalance>
 <XMP-crs:IncrementalTemperature>0</XMP-crs:IncrementalTemperature>
 <XMP-crs:IncrementalTint>0</XMP-crs:IncrementalTint>
 <XMP-crs:Exposure>+0.75</XMP-crs:Exposure>
 <XMP-crs:Shadows>0</XMP-crs:Shadows>
 <XMP-crs:Brightness>0</XMP-crs:Brightness>
 <XMP-crs:Contrast>+11</XMP-crs:Contrast>
 <XMP-crs:Saturation>0</XMP-crs:Saturation>
 <XMP-crs:Sharpness>0</XMP-crs:Sharpness>
 <XMP-crs:LuminanceSmoothing>0</XMP-crs:LuminanceSmoothing>
 <XMP-crs:ColorNoiseReduction>0</XMP-crs:ColorNoiseReduction>
 <XMP-crs:ChromaticAberrationR>0</XMP-crs:ChromaticAberrationR>
 <XMP-crs:ChromaticAberrationB>0</XMP-crs:ChromaticAberrationB>
 <XMP-crs:VignetteAmount>0</XMP-crs:VignetteAmount>
 <XMP-crs:ShadowTint>0</XMP-crs:ShadowTint>
 <XMP-crs:RedHue>0</XMP-crs:RedHue>
 <XMP-crs:RedSaturation>0</XMP-crs:RedSaturation>
 <XMP-crs:GreenHue>0</XMP-crs:GreenHue>
 <XMP-crs:GreenSaturation>0</XMP-crs:GreenSaturation>
 <XMP-crs:BlueHue>0</XMP-crs:BlueHue>
 <XMP-crs:BlueSaturation>0</XMP-crs:BlueSaturation>
 <XMP-crs:FillLight>0</XMP-crs:FillLight>
 <XMP-crs:Vibrance>+30</XMP-crs:Vibrance>
 <XMP-crs:HighlightRecovery>0</XMP-crs:HighlightRecovery>
 <XMP-crs:Clarity>0</XMP-crs:Clarity>
 <XMP-crs:Defringe>0</XMP-crs:Defringe>
 <XMP-crs:HueAdjustmentRed>0</XMP-crs:HueAdjustmentRed>
 <XMP-crs:HueAdjustmentOrange>0</XMP-crs:HueAdjustmentOrange>
 <XMP-crs:HueAdjustmentYellow>0</XMP-crs:HueAdjustmentYellow>
 <XMP-crs:HueAdjustmentGreen>0</XMP-crs:HueAdjustmentGreen>
 <XMP-crs:HueAdjustmentAqua>0</XMP-crs:HueAdjustmentAqua>
 <XMP-crs:HueAdjustmentBlue>0</XMP-crs:HueAdjustmentBlue>
 <XMP-crs:HueAdjustmentPurple>0</XMP-crs:HueAdjustmentPurple>
 <XMP-crs:HueAdjustmentMagenta>0</XMP-crs:HueAdjustmentMagenta>
 <XMP-crs:SaturationAdjustmentRed>0</XMP-crs:SaturationAdjustmentRed>
 <XMP-crs:SaturationAdjustmentOrange>0</XMP-crs:SaturationAdjustmentOrange>
 <XMP-crs:SaturationAdjustmentYellow>0</XMP-crs:SaturationAdjustmentYellow>
 <XMP-crs:SaturationAdjustmentGreen>0</XMP-crs:SaturationAdjustmentGreen>
 <XMP-crs:SaturationAdjustmentAqua>0</XMP-crs:SaturationAdjustmentAqua>
 <XMP-crs:SaturationAdjustmentBlue>0</XMP-crs:SaturationAdjustmentBlue>
 <XMP-crs:SaturationAdjustmentPurple>0</XMP-crs:SaturationAdjustmentPurple>
 <XMP-crs:SaturationAdjustmentMagenta>0</XMP-crs:SaturationAdjustmentMagenta>
 <XMP-crs:LuminanceAdjustmentRed>0</XMP-crs:LuminanceAdjustmentRed>
 <XMP-crs:LuminanceAdjustmentOrange>0</XMP-crs:LuminanceAdjustmentOrange>
 <XMP-crs:LuminanceAdjustmentYellow>0</XMP-crs:LuminanceAdjustmentYellow>
 <XMP-crs:LuminanceAdjustmentGreen>0</XMP-crs:LuminanceAdjustmentGreen>
 <XMP-crs:LuminanceAdjustmentAqua>0</XMP-crs:LuminanceAdjustmentAqua>
 <XMP-crs:LuminanceAdjustmentBlue>0</XMP-crs:LuminanceAdjustmentBlue>
 <XMP-crs:LuminanceAdjustmentPurple>0</XMP-crs:LuminanceAdjustmentPurple>
 <XMP-crs:LuminanceAdjustmentMagenta>0</XMP-crs:LuminanceAdjustmentMagenta>
 <XMP-crs:SplitToningShadowHue>0</XMP-crs:SplitToningShadowHue>
 <XMP-crs:SplitToningShadowSaturation>0</XMP-crs:SplitToningShadowSaturation>
 <XMP-crs:SplitToningHighlightHue>0</XMP-crs:SplitToningHighlightHue>
 <XMP-crs:SplitToningHighlightSaturation>0</XMP-crs:SplitToningHighlightSaturation>
 <XMP-crs:SplitToningBalance>0</XMP-crs:SplitToningBalance>
 <XMP-crs:ParametricShadows>0</XMP-crs:ParametricShadows>
 <XMP-crs:ParametricDarks>0</XMP-crs:ParametricDarks>
 <XMP-crs:ParametricLights>0</XMP-crs:ParametricLights>
 <XMP-crs:ParametricHighlights>0</XMP-crs:ParametricHighlights>
 <XMP-crs:ParametricShadowSplit>25</XMP-crs:ParametricShadowSplit>
 <XMP-crs:ParametricMidtoneSplit>50</XMP-crs:ParametricMidtoneSplit>
 <XMP-crs:ParametricHighlightSplit>75</XMP-crs:ParametricHighlightSplit>
 <XMP-crs:SharpenRadius>+1.0</XMP-crs:SharpenRadius>
 <XMP-crs:SharpenDetail>25</XMP-crs:SharpenDetail>
 <XMP-crs:SharpenEdgeMasking>0</XMP-crs:SharpenEdgeMasking>
 <XMP-crs:PostCropVignetteAmount>0</XMP-crs:PostCropVignetteAmount>
 <XMP-crs:ConvertToGrayscale>False</XMP-crs:ConvertToGrayscale>
 <XMP-crs:ToneCurveName>Linear</XMP-crs:ToneCurveName>
 <XMP-crs:CameraProfile>Embedded</XMP-crs:CameraProfile>
 <XMP-crs:CameraProfileDigest>54650A341B5B5CCAE8442D0B43A92BCE</XMP-crs:CameraProfileDigest>
 <XMP-crs:HasSettings>True</XMP-crs:HasSettings>
 <XMP-crs:CropTop>0.122023</XMP-crs:CropTop>
 <XMP-crs:CropLeft>0.048689</XMP-crs:CropLeft>
 <XMP-crs:CropBottom>0.953319</XMP-crs:CropBottom>
 <XMP-crs:CropRight>0.925637</XMP-crs:CropRight>
 <XMP-crs:CropAngle>-0.71835</XMP-crs:CropAngle>
 <XMP-crs:HasCrop>True</XMP-crs:HasCrop>
 <XMP-crs:AlreadyApplied>True</XMP-crs:AlreadyApplied>
 <XMP-crs:ToneCurve>
  <rdf:Bag>
   <rdf:li>0, 0</rdf:li>
   <rdf:li>255, 255</rdf:li>
  </rdf:Bag>
 </XMP-crs:ToneCurve>
 <Adobe:DCTEncodeVersion>100</Adobe:DCTEncodeVersion>
 <Adobe:APP14Flags0>[14]</Adobe:APP14Flags0>
 <Adobe:APP14Flags1>(none)</Adobe:APP14Flags1>
 <Adobe:ColorTransform>YCbCr</Adobe:ColorTransform>
 <Composite:Aperture>5.6</Composite:Aperture>
 <Composite:ImageSize>2836x2071</Composite:ImageSize>
 <Composite:ShutterSpeed>1/1600</Composite:ShutterSpeed>
 <Composite:FocalLength35efl>5.5 mm</Composite:FocalLength35efl>
 <Composite:LightValue>15.6</Composite:LightValue>
</rdf:Description>
</rdf:RDF>


text:
namespace Xaye.Fred
{
    /// <summary>
    /// The type of search to perform. Defaults to FullText.
    /// </summary>
    /// <remarks></remarks>
    public enum SearchType
    {
        FullText,
        SeriesId
    }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2021 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.remote.grpc;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.collect.ImmutableList;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.observers.TestObserver;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link TokenBucket} */
@RunWith(JUnit4.class)
public class TokenBucketTest {

  @Test
  public void acquireToken_smoke() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    assertThat(bucket.size()).isEqualTo(0);
    bucket.addToken(0);
    assertThat(bucket.size()).isEqualTo(1);

    TestObserver<Integer> observer = bucket.acquireToken().test();

    observer.assertValue(0).assertComplete();
    assertThat(bucket.size()).isEqualTo(0);
  }

  @Test
  public void acquireToken_releaseInitialTokens() {
    TokenBucket<Integer> bucket = new TokenBucket<>(ImmutableList.of(0));
    assertThat(bucket.size()).isEqualTo(1);

    TestObserver<Integer> observer = bucket.acquireToken().test();

    observer.assertValue(0).assertComplete();
    assertThat(bucket.size()).isEqualTo(0);
  }

  @Test
  public void acquireToken_multipleInitialTokens_releaseFirstToken() {
    TokenBucket<Integer> bucket = new TokenBucket<>(ImmutableList.of(0, 1));
    assertThat(bucket.size()).isEqualTo(2);

    TestObserver<Integer> observer = bucket.acquireToken().test();

    observer.assertValue(0).assertComplete();
    assertThat(bucket.size()).isEqualTo(1);
  }

  @Test
  public void acquireToken_multipleInitialTokens_releaseSecondToken() {
    TokenBucket<Integer> bucket = new TokenBucket<>(ImmutableList.of(0, 1));
    assertThat(bucket.size()).isEqualTo(2);
    bucket.acquireToken().test().assertValue(0).assertComplete();

    TestObserver<Integer> observer = bucket.acquireToken().test();

    observer.assertValue(1).assertComplete();
    assertThat(bucket.size()).isEqualTo(0);
  }

  @Test
  public void acquireToken_releaseTokenToPreviousObserver() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    TestObserver<Integer> observer = bucket.acquireToken().test();
    observer.assertEmpty();

    bucket.addToken(0);

    observer.assertValue(0).assertComplete();
    assertThat(bucket.size()).isEqualTo(0);
  }

  @Test
  public void acquireToken_notReleaseTokenToDisposedObserver() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    TestObserver<Integer> observer = bucket.acquireToken().test();

    observer.dispose();
    bucket.addToken(0);

    observer.assertEmpty();
    assertThat(bucket.size()).isEqualTo(1);
  }

  @Test
  public void acquireToken_disposeAfterTokenAcquired() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    TestObserver<Integer> observer = bucket.acquireToken().test();

    bucket.addToken(0);
    bucket.addToken(1);

    observer.assertValue(0).assertComplete();
    assertThat(bucket.size()).isEqualTo(1);
  }

  @Test
  public void acquireToken_multipleObservers_onlyOneCanAcquire() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    TestObserver<Integer> observer1 = bucket.acquireToken().test();
    TestObserver<Integer> observer2 = bucket.acquireToken().test();

    bucket.addToken(0);

    if (!observer1.values().isEmpty()) {
      observer1.assertValue(0).assertComplete();
      observer2.assertEmpty();

      bucket.addToken(1);
      observer2.assertValue(1).assertComplete();
    } else {
      observer1.assertEmpty();
      observer2.assertValue(0).assertComplete();

      bucket.addToken(1);
      observer1.assertValue(1).assertComplete();
    }
  }

  @Test
  public void acquireToken_reSubscription_waitAvailableToken() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    bucket.addToken(0);
    Single<Integer> tokenSingle = bucket.acquireToken();

    TestObserver<Integer> observer1 = tokenSingle.test();
    TestObserver<Integer> observer2 = tokenSingle.test();

    observer1.assertValue(0).assertComplete();
    observer2.assertEmpty();
  }

  @Test
  public void acquireToken_reSubscription_acquireNewToken() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    bucket.addToken(0);
    Single<Integer> tokenSingle = bucket.acquireToken();
    TestObserver<Integer> observer1 = tokenSingle.test();
    TestObserver<Integer> observer2 = tokenSingle.test();

    bucket.addToken(1);

    observer1.assertValue(0).assertComplete();
    observer2.assertValue(1).assertComplete();
  }

  @Test
  public void acquireToken_reSubscription_acquireNextToken() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    bucket.addToken(0);
    bucket.addToken(1);
    Single<Integer> tokenSingle = bucket.acquireToken();

    TestObserver<Integer> observer1 = tokenSingle.test();
    TestObserver<Integer> observer2 = tokenSingle.test();

    observer1.assertValue(0).assertComplete();
    observer2.assertValue(1).assertComplete();
  }

  @Test
  public void acquireToken_disposed_tokenRemains() {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    TestObserver<Integer> observer = bucket.acquireToken().test();
    observer.assertEmpty();

    observer.dispose();
    bucket.addToken(0);

    assertThat(bucket.size()).isEqualTo(1);
  }

  @Test
  public void close_errorAfterClose() throws IOException {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    bucket.addToken(0);
    bucket.close();

    TestObserver<Integer> observer = bucket.acquireToken().test();

    observer.assertError(
        e -> e instanceof IllegalStateException && e.getMessage().contains("closed"));
  }

  @Test
  public void close_errorPreviousObservers() throws IOException {
    TokenBucket<Integer> bucket = new TokenBucket<>();
    TestObserver<Integer> observer = bucket.acquireToken().test();

    bucket.close();

    observer.assertError(
        e -> e instanceof IllegalStateException && e.getMessage().contains("closed"));
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>NaviPackType</title>
<meta name="date" content="2016-09-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

您的浏览器已禁用 JavaScript。

跳过导航链接

概览

程序包

类

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法

com.imscv.navipacksdk.constant

类 NaviPackType

java.lang.Object

com.imscv.navipacksdk.constant.NaviPackType

直接已知子类:

NaviPackSdk

public class NaviPackType
extends java.lang.Object

Created by dell on 2016/7/29.

字段概要

字段

限定符和类型
字段和说明

static int
CODE_ERROR_LIDAR_NOT_FOUND

雷达设备没有初始化 作为设备端的msgCode

static int
CODE_MAP_COLLISION

地图类型 碰撞传感器图层

static int
CODE_MAP_GROUND

地图类型 跌落传感器图层

static int
CODE_MAP_LIDAR

地图类型 激光雷达图层

static int
CODE_MAP_TOTAL

地图类型 总图

static int
CODE_MAP_ULTRASON

地图类型 超声波传感器图层

static int
CODE_SENSOR_COLLISION

碰撞传感器原始数据

static int
CODE_SENSOR_GROUND

跌落传感器原始数据

static int
CODE_SENSOR_ST_LIDAR2D

雷达传感器原始数据

static int
CODE_SENSOR_ULTRASON

超声波传感器原始数据

static int
CODE_TARGET_PATH_UPGRADE

路径有更新

static int
CODE_TARGET_REACH_POINT

到达运动点

static int
CODE_TARGET_TERMINAL

终止到点运动

static int
DEVICE_MSG_TYPE_ERROR_CODE

消息类型为错误码
  子类型可以为
      CODE_ERROR_LIDAR_NOT_FOUND

static int
DEVICE_MSG_TYPE_GET_NAVIPACK_VERSION

消息类型为获取navipack的版本信息
 子类型为版本代码

static int
DEVICE_MSG_TYPE_INIT_LOCATION_SUCCESS

消息类型为初始定位成功
 子类型暂时为O

protected static int
DEVICE_MSG_TYPE_MAX_VALUE

定义基本消息的最大值 不开放使用

static int
DEVICE_MSG_TYPE_NAVIGATION

消息类型为控制到点运动有更新
 子类型为:
 CODE_TARGET_REACH_POINT

static int
DEVICE_MSG_TYPE_SET_LOAD_MAP_FROME_LIST

消息类型为从地图列表中加载地图
 子类型为结果代号  小于零表示失败 否则表示加载的地图编号

static int
DEVICE_MSG_TYPE_SET_SAVE_CURRENT_MAP

消息类型为保存当前地图结果
 子类型为结果代号  小于零表示失败 否则表示地图编号

static int
DEVICE_MSG_TYPE_UPDATE_ALG_ATATUS_REG

消息类型为更新传感器数据
 子类型暂时为O

static int
DEVICE_MSG_TYPE_UPDATE_MAP

消息类型为地图更新
  子类型可以为 :
      CODE_MAP_TOTAL
      CODE_MAP_LIDAR
      CODE_MAP_ULTRASON
      CODE_MAP_COLLISION
      CODE_MAP_GROUND

static int
DEVICE_MSG_TYPE_UPGRADE_SENSOR_DATA

消息类型为更新传感器数据
 子类型可以为:
       CODE_SENSOR_ST_LIDAR2D
       CODE_SENSOR_ULTRASON
       CODE_SENSOR_COLLISION
       CODE_SENSOR_GROUND

构造器概要

构造器

构造器和说明

NaviPackType()

方法概要

从类继承的方法 java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

字段详细资料

DEVICE_MSG_TYPE_ERROR_CODE

public static final int DEVICE_MSG_TYPE_ERROR_CODE

消息类型为错误码
  子类型可以为
      CODE_ERROR_LIDAR_NOT_FOUND

另请参阅:

常量字段值

CODE_ERROR_LIDAR_NOT_FOUND

public static final int CODE_ERROR_LIDAR_NOT_FOUND

雷达设备没有初始化 作为设备端的msgCode

另请参阅:

常量字段值

DEVICE_MSG_TYPE_UPDATE_MAP

public static final int DEVICE_MSG_TYPE_UPDATE_MAP

消息类型为地图更新
  子类型可以为 :
      CODE_MAP_TOTAL
      CODE_MAP_LIDAR
      CODE_MAP_ULTRASON
      CODE_MAP_COLLISION
      CODE_MAP_GROUND

另请参阅:

常量字段值

CODE_MAP_TOTAL

public static final int CODE_MAP_TOTAL

地图类型 总图

另请参阅:

常量字段值

CODE_MAP_LIDAR

public static final int CODE_MAP_LIDAR

地图类型 激光雷达图层

另请参阅:

常量字段值

CODE_MAP_ULTRASON

public static final int CODE_MAP_ULTRASON

地图类型 超声波传感器图层

另请参阅:

常量字段值

CODE_MAP_COLLISION

public static final int CODE_MAP_COLLISION

地图类型 碰撞传感器图层

另请参阅:

常量字段值

CODE_MAP_GROUND

public static final int CODE_MAP_GROUND

地图类型 跌落传感器图层

另请参阅:

常量字段值

DEVICE_MSG_TYPE_UPGRADE_SENSOR_DATA

public static final int DEVICE_MSG_TYPE_UPGRADE_SENSOR_DATA

消息类型为更新传感器数据
 子类型可以为:
       CODE_SENSOR_ST_LIDAR2D
       CODE_SENSOR_ULTRASON
       CODE_SENSOR_COLLISION
       CODE_SENSOR_GROUND

另请参阅:

常量字段值

CODE_SENSOR_ST_LIDAR2D

public static final int CODE_SENSOR_ST_LIDAR2D

雷达传感器原始数据

另请参阅:

常量字段值

CODE_SENSOR_ULTRASON

public static final int CODE_SENSOR_ULTRASON

超声波传感器原始数据

另请参阅:

常量字段值

CODE_SENSOR_COLLISION

public static final int CODE_SENSOR_COLLISION

碰撞传感器原始数据

另请参阅:

常量字段值

CODE_SENSOR_GROUND

public static final int CODE_SENSOR_GROUND

跌落传感器原始数据

另请参阅:

常量字段值

DEVICE_MSG_TYPE_INIT_LOCATION_SUCCESS

public static final int DEVICE_MSG_TYPE_INIT_LOCATION_SUCCESS

消息类型为初始定位成功
 子类型暂时为O

另请参阅:

常量字段值

DEVICE_MSG_TYPE_UPDATE_ALG_ATATUS_REG

public static final int DEVICE_MSG_TYPE_UPDATE_ALG_ATATUS_REG

消息类型为更新传感器数据
 子类型暂时为O

另请参阅:

常量字段值

DEVICE_MSG_TYPE_NAVIGATION

public static final int DEVICE_MSG_TYPE_NAVIGATION

消息类型为控制到点运动有更新
 子类型为:
 CODE_TARGET_REACH_POINT

另请参阅:

常量字段值

CODE_TARGET_REACH_POINT

public static final int CODE_TARGET_REACH_POINT

到达运动点

另请参阅:

常量字段值

CODE_TARGET_TERMINAL

public static final int CODE_TARGET_TERMINAL

终止到点运动

另请参阅:

常量字段值

CODE_TARGET_PATH_UPGRADE

public static final int CODE_TARGET_PATH_UPGRADE

路径有更新

另请参阅:

常量字段值

DEVICE_MSG_TYPE_GET_NAVIPACK_VERSION

public static final int DEVICE_MSG_TYPE_GET_NAVIPACK_VERSION

消息类型为获取navipack的版本信息
 子类型为版本代码

另请参阅:

常量字段值

DEVICE_MSG_TYPE_SET_SAVE_CURRENT_MAP

public static final int DEVICE_MSG_TYPE_SET_SAVE_CURRENT_MAP

消息类型为保存当前地图结果
 子类型为结果代号  小于零表示失败 否则表示地图编号

另请参阅:

常量字段值

DEVICE_MSG_TYPE_SET_LOAD_MAP_FROME_LIST

public static final int DEVICE_MSG_TYPE_SET_LOAD_MAP_FROME_LIST

消息类型为从地图列表中加载地图
 子类型为结果代号  小于零表示失败 否则表示加载的地图编号

另请参阅:

常量字段值

DEVICE_MSG_TYPE_MAX_VALUE

protected static final int DEVICE_MSG_TYPE_MAX_VALUE

定义基本消息的最大值 不开放使用

另请参阅:

常量字段值

构造器详细资料

NaviPackType

public NaviPackType()

跳过导航链接

概览

程序包

类

树

已过时

索引

帮助

上一个类

下一个类

框架

无框架

所有类

概要:

嵌套 |

字段 |

构造器 |

方法

详细资料:

字段 |

构造器 |

方法


text:
#define __CUSTOMHTTPAPP_C

#include "TCPIPConfig.h"

#if defined(STACK_USE_HTTP2_SERVER)
#include "TCPIP Stack/TCPIP.h"
#include "TCPIP Stack/WFConsoleMsgHandler.h"
#include "MainDemo.h"        // Needed for SaveAppConfig() prototype
#include "mpu_i2c.h"         // header file for MPU 9150 tilt sensor
#ifndef PERIOD
#define PERIOD  3120        //  set 312 for get to timer interrupt every 2ms, 40MHz PBUS, div by 256
#endif

// Differences to wifi comm demo board (MRF24WB0MA) :
//        Wifi comm demo board is centered on variable CPElements.
//        Wifi G demo board is centered on variable AppConfig, since this is the generic approach adopted by
//        TCPIP demo/ezconsole/ezconfig apps.

extern APP_CONFIG AppConfig;

// user custom define
extern MOTOR_STATUS motor_status;
int num2str(int num_in, char *ptr);
int hex2str(BYTE *hex, char *ptr);
void UARTTxBuffer2(BYTE *buffer, UINT32 size, UART_MODULE UART_PORT);
void GetFeedBack(char *ptr, UART_MODULE UART_PORT);
char LST_CON[]={"Lost Connection"};

int offset;               // offset for ADC buffer
int canterior;            // all the variables
int cposterior;
int displock = 0;             // display lock, to prevent the data writing conflict
/****************************************************************************
  Section:
	Function Prototypes and Memory Globalizers
  ***************************************************************************/
#if defined(HTTP_USE_POST)
	#if defined(STACK_USE_EZ_CONFIG)
        #include "TCPIP Stack/WFEasyConfig.h"
	    static HTTP_IO_RESULT HTTPPostWifiConfig(void);
    #endif
#endif

// bss descriptor fetched from on-chip
static tWFScanResult bssDesc;
static BOOL bssDescIsValid = FALSE;

// RAM allocated for DDNS parameters
#if defined(STACK_USE_DYNAMICDNS_CLIENT)
	static BYTE DDNSData[100];
#endif

// Sticky status message variable.
// This is used to indicated whether or not the previous POST operation was
// successful.  The application uses these to store status messages when a
// POST operation redirects.  This lets the application provide status messages
// after a redirect, when connection instance data has already been lost.
static BOOL lastFailure = FALSE;

extern tWFScanResult preScanResult[50]; // WF_PRESCAN

/****************************************************************************
  Section:
	Authorization Handlers
  ***************************************************************************/

/*****************************************************************************
  Function:
	BYTE HTTPNeedsAuth(BYTE* cFile)

  Internal:
  	See documentation in the TCP/IP Stack API or HTTP2.h for details.
  ***************************************************************************/
#if defined(HTTP_USE_AUTHENTICATION)
BYTE HTTPNeedsAuth(BYTE* cFile)
{
	// If the filename begins with the folder "protect", then require auth
	if(memcmppgm2ram(cFile, (ROM void*)"protect", 7) == 0)
		return 0x00;		// Authentication will be needed later

	// If the filename begins with the folder "snmp", then require auth
	if(memcmppgm2ram(cFile, (ROM void*)"snmp", 4) == 0)
		return 0x00;		// Authentication will be needed later

	#if defined(HTTP_MPFS_UPLOAD_REQUIRES_AUTH)
	if(memcmppgm2ram(cFile, (ROM void*)"mpfsupload", 10) == 0)
		return 0x00;
	#endif

	// You can match additional strings here to password protect other files.
	// You could switch this and exclude files from authentication.
	// You could also always return 0x00 to require auth for all files.
	// You can return different values (0x00 to 0x79) to track "realms" for below.

	return 0x80;			// No authentication required
}
#endif

/*****************************************************************************
  Function:
	BYTE HTTPCheckAuth(BYTE* cUser, BYTE* cPass)

  Internal:
  	See documentation in the TCP/IP Stack API or HTTP2.h for details.
  ***************************************************************************/
#if defined(HTTP_USE_AUTHENTICATION)
BYTE HTTPCheckAuth(BYTE* cUser, BYTE* cPass)
{
	if(strcmppgm2ram((char *)cUser,(ROM char *)"admin") == 0
		&& strcmppgm2ram((char *)cPass, (ROM char *)"microchip") == 0)
		return 0x80;		// We accept this combination

	// You can add additional user/pass combos here.
	// If you return specific "realm" values above, you can base this
	//   decision on what specific file or folder is being accessed.
	// You could return different values (0x80 to 0xff) to indicate
	//   various users or groups, and base future processing decisions
	//   in HTTPExecuteGet/Post or HTTPPrint callbacks on this value.

	return 0x00;			// Provided user/pass is invalid
}
#endif

/****************************************************************************
  Section:
	GET Form Handlers
  ***************************************************************************/

/*****************************************************************************
  Function:
	HTTP_IO_RESULT HTTPExecuteGet(void)

  Internal:
  	See documentation in the TCP/IP Stack API or HTTP2.h for details.
  ***************************************************************************/
HTTP_IO_RESULT HTTPExecuteGet(void)
{
	BYTE *ptr, *ptr1;
	BYTE filename[20];

    BYTE bssIdx;
    WORD_VAL bssIdxStr;

	// Load the file name
	// Make sure BYTE filename[] above is large enough for your longest name
	MPFSGetFilename(curHTTP.file, filename, 20);

    /******************************************/
	// If it's the leds.cgi LED update file
    /******************************************/
	if(!memcmppgm2ram(filename, "leds.cgi", 8))
	{
		// Determine which LED to toggle
		ptr = HTTPGetROMArg(curHTTP.data, (ROM BYTE *)"led");

		// Toggle the specified LED
		switch(*ptr)
        {
			case '1':
				LED1_INV();
				break;
			case '2':
				LED2_INV();
				break;
            default:
                break;
		}

	}

    /******************************************/
	// If it's the mc.cgi motorcommand
    /******************************************/
	if(!memcmppgm2ram(filename, "mc.cgi", 6))
	{
            CloseTimer3();
            int query_flag=0;              // for decide the command is query command or normal command
            int pos_flag = 0;
            BYTE *ptr2,*ptr3,*ptr4;
            BYTE CR_LF[2]={'\r','\n'};    // end of command syntax of motor

		// Determine which LED to toggle
               UINT32 cmlen1=0;    // command length
               UINT32 cmlen2=0;    // command length
               UINT32 cmlen3=0;    // command length
               UINT32 cmlen4=0;    // command length

		ptr1 = HTTPGetROMArg(curHTTP.data, (ROM BYTE *)"motornum");
                ptr=ptr1;
                while(*(ptr++)!='\0')         // ATTENTION here,  the '&' mark submit by url request just automaticly change into '\0' by previous receiving
                    cmlen1++;       // calculate the command length

                ptr2 = HTTPGetROMArg(curHTTP.data, (ROM BYTE *)"motorcmd");
                ptr=ptr2;
                while(*(ptr++)!='\0')
                    cmlen2++;       // calculate the command length
                if (*ptr2=='?')
                    query_flag=1;   // detect whether this one is query command char or not

                ptr3 = HTTPGetROMArg(curHTTP.data, (ROM BYTE *)"operand");
                ptr=ptr3;
                while(*(ptr++)!='\0')
                    cmlen3++;       // calculate the command length
                if (*ptr3=='0')
                    pos_flag=1;   // detect whether this one is query command char or not

                ptr4 = HTTPGetROMArg(curHTTP.data, (ROM BYTE *)"run_repeat");
                ptr=ptr4;
                while(*(ptr++)!='\0')
                    cmlen4++;       // calculate the command length
		// Toggle the specified LED
                if (cmlen2==7)
                    LED2_INV();

                // section for send the motor command
                UARTTxBuffer2("/", 1, SENSOR_UART);
                 ptr=ptr1;
                UARTTxBuffer2(ptr, cmlen1, SENSOR_UART);
                 ptr=ptr2;
                UARTTxBuffer2(ptr, cmlen2, SENSOR_UART);
                 ptr=ptr3;
                UARTTxBuffer2(ptr, cmlen3, SENSOR_UART);
                 ptr=ptr4;
                UARTTxBuffer2(ptr, cmlen4, SENSOR_UART);
                 ptr=CR_LF;                        // end with character return and line feed
                UARTTxBuffer2(ptr, 2, SENSOR_UART);

                // get back the motor response
                if (query_flag==0)
                    GetFeedBack(motor_status.command_response, UART1);   // store in command_response
                else if(query_flag==1 && pos_flag == 1)
                    GetFeedBack(motor_status.motor_position, UART1);
                else if(query_flag==1 && pos_flag == 0)
                    GetFeedBack(motor_status.query_response, UART1);
          OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_256, PERIOD);
           INTEnable(INT_T3, INT_ENABLED);    // re-enable the interrupt
	}
    /******************************************/
    // If it's the  scan.cgi scan file
    /******************************************/
	if(!memcmppgm2ram(filename, "scan.cgi", 8))
	{
		ptr = HTTPGetROMArg(curHTTP.data, (ROM BYTE *)"scan");
		ptr1 = HTTPGetROMArg(curHTTP.data, (ROM BYTE *)"getBss");

		if ((ptr != NULL) && (ptr1 == NULL))
		{
			bssDescIsValid = FALSE;
			// scan request
			if (AppConfig.networkType == WF_SOFT_AP)
			{   // SoftAP: display pre-scan results before starting as SoftAP. SoftAP does not scan.
				SCAN_SET_DISPLAY(SCANCXT.scanState);
			}
			else
			{
				if (WFStartScan() == WF_SUCCESS)
				{
					SCAN_SET_DISPLAY(SCANCXT.scanState);
					SCANCXT.displayIdx = 0;
				}
			}
        }
        else if ((ptr == NULL) && (ptr1 != NULL))
        {
            // getBss request
            // use the value to get the nth bss stored on chip
            bssDescIsValid = FALSE;
            bssIdxStr.v[1] = *ptr1;
            bssIdxStr.v[0] = *(ptr1+1);
            bssIdx = hexatob(bssIdxStr);

            if (AppConfig.networkType == WF_SOFT_AP)
            {   // SoftAP: display pre-scan results before starting as SoftAP. SoftAP does not scan.
                bssDesc = preScanResult[bssIdx];
            }
            else
            {
            	WFRetrieveScanResult(bssIdx, &bssDesc);
            }

			// This is needed to ensure index.htm displays correct WLAN type.
			// Index.htm differs between EZConfig and wifi g demo in that index.htm
			// in wifi g demo displays BSS information of MRF24WG.
			if (++bssIdx == SCANCXT.numScanResults)
				SCAN_CLEAR_DISPLAY(SCANCXT.scanState);

            bssDescIsValid = TRUE;
        }
        else
        {
            // impossible to get here
        }

	}

	return HTTP_IO_DONE;
}

/****************************************************************************
  Section:
	POST Form Handlers
  ***************************************************************************/
#if defined(HTTP_USE_POST)

/*****************************************************************************
  Function:
	HTTP_IO_RESULT HTTPExecutePost(void)

  Internal:
  	See documentation in the TCP/IP Stack API or HTTP2.h for details.
  ***************************************************************************/
HTTP_IO_RESULT HTTPExecutePost(void)
{
	// Resolve which function to use and pass along
	BYTE filename[20];

	// Load the file name
	// Make sure BYTE filename[] above is large enough for your longest name
	MPFSGetFilename(curHTTP.file, filename, sizeof(filename));

    /******************************************/
    // If it's the configure.htm page, use settings to reconfigure wifi settings
    /******************************************/
    #if defined(STACK_USE_EZ_CONFIG)
	if(!memcmppgm2ram(filename, "configure.htm", 13))
		return HTTPPostWifiConfig();
    #endif

	return HTTP_IO_DONE;
}

/*****************************************************************************
  Function:
	static HTTP_IO_RESULT HTTPPostWifiConfig(void)

  Summary:
	Processes the wifi config data

  Description:
	Accepts wireless configuration data from the www site and saves them to a
	structure to be applied by the wifi configuration manager.

    The following configurations are possible:
         i) Mode: Adhoc / infrastructure / softAP / wifi direct
        ii) Security:
               - None
               - WPA/WPA2 passphrase (passphrase between 8-63 characters)
               - WPA/WPA2 pre-calculated key
               - WEP 64-bit
               - WEP 128-bit
               - WPS Push Button
               - WPS PIN
       iii) Key material

	If an error occurs, such as data is invalid they will be redirected to a page
    informing the user of such results.

    NOTE: This code for modified originally from HTTPPostWifiConfig as distributed
          by Microchip.

  Precondition:
	None

  Parameters:
	None

  Return Values:
  	HTTP_IO_DONE - all parameters have been processed
  	HTTP_IO_NEED_DATA - data needed by this function has not yet arrived
  ***************************************************************************/
static HTTP_IO_RESULT HTTPPostWifiConfig(void)
{
	// Check to see if the browser is attempting to submit more data than we
	// can parse at once.  This function needs to receive all updated
	// parameters and validate them all before committing them to memory so that
	// orphaned configuration parameters do not get written (for example, if a
	// static IP address is given, but the subnet mask fails parsing, we
	// should not use the static IP address).  Everything needs to be processed
	// in a single transaction.  If this is impossible, fail and notify the user.
	// As a web devloper, if you add parameters to AppConfig and run into this
	// problem, you could fix this by to splitting your update web page into two
	// seperate web pages (causing two transactional writes).  Alternatively,
	// you could fix it by storing a static shadow copy of AppConfig someplace
	// in memory and using it instead of newAppConfig.  Lastly, you could
	// increase the TCP RX FIFO size for the HTTP server.  This will allow more
	// data to be POSTed by the web browser before hitting this limit.

    //  UINT8 ConnectionProfileID;
    //  UINT8 ConnectionState;
    UINT8 ssidLen;

   // Comments: Using WF_CMGetConnectionState causes redirection issues when using iPhone iOS6.1, even though
   //                  redirection on laptop is functional.
   //                  Customers are encouraged to use 1 profile ID for MRF24W based on v5 stack SW.
   //                  In v6 stack SW, we are keeping to 1 profile ID for MRF24W but stack will have
   //                  capability to handle multiple profiles.
   // WF_CMGetConnectionState(&ConnectionState, &ConnectionProfileID);

	if(curHTTP.byteCount > TCPIsGetReady(sktHTTP) + TCPGetRxFIFOFree(sktHTTP))
		goto ConfigFailure;

	// Ensure that all data is waiting to be parsed.  If not, keep waiting for
	// all of it to arrive.
	if(TCPIsGetReady(sktHTTP) < curHTTP.byteCount)
		return HTTP_IO_NEED_DATA;

    //**************************************
	// Read all browser POST data
    //**************************************
	while(curHTTP.byteCount)
	{
		// Read a form field name
		if(HTTPReadPostName(curHTTP.data, 6) != HTTP_READ_OK)
			goto ConfigFailure;

		// Read a form field value
		if(HTTPReadPostValue(curHTTP.data + 6, sizeof(curHTTP.data)-6-2) != HTTP_READ_OK)
			goto ConfigFailure;

		// Parse the values that were read
        //**************************************
        // Read security type
        //**************************************
		if(!strcmppgm2ram((char*)curHTTP.data, "sec"))
		{
            char   security_type[7];

            if (strlen((char*)(curHTTP.data+6)) > 6) /* Sanity check */
                goto ConfigFailure;

            memcpy(security_type, (void*)(curHTTP.data+6), strlen((char*)(curHTTP.data+6)));
            security_type[strlen((char*)(curHTTP.data+6))] = 0; /* Terminate string */

            printf("\r\nSecurity Mode: ");
		    if (!strcmppgm2ram((char*)security_type, "no"))
            {
                CFGCXT.security = WF_SECURITY_OPEN;
                printf("OPEN");
            }
		    else if(!strcmppgm2ram((char*)security_type, "wpa"))
            {
                CFGCXT.security = WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE;
                printf("WPA w/PASSPHRASE");
            }
		    else if(!strcmppgm2ram((char*)security_type, "calc"))
            {   /* Pre-calculated key */
                CFGCXT.security = WF_SECURITY_WPA_AUTO_WITH_KEY;
                printf("WPA w/AUTO Key");
            }
		    else if(!strcmppgm2ram((char*)security_type, "wep40"))
            {
                CFGCXT.security = WF_SECURITY_WEP_40;
                printf("WEP 64-bit");
            }
		    else if(!strcmppgm2ram((char*)security_type, "wep104"))
            {
                CFGCXT.security = WF_SECURITY_WEP_104;
                printf("WEP 128-bit");
            }
			else if(!strcmppgm2ram((char*)security_type, "wps_button"))
            {
                CFGCXT.security = WF_SECURITY_WPS_PUSH_BUTTON;
                printf("WPS Push-Button");
            }
            else if(!strcmppgm2ram((char*)security_type, "wps_pin"))
            {
                CFGCXT.security = WF_SECURITY_WPS_PIN;
                printf("WPS PIN");
            }
		    else
            {   //Security type no good  :-(
                printf("\r\nUnknown key type!");
                goto ConfigFailure;
            }
		}

        //**************************************
        // Read new Security Key
        //**************************************
		else if(!strcmppgm2ram((char*)curHTTP.data, "key"))
		{
            BYTE key_size = 0, ascii_key = 0;

            switch ((BYTE)CFGCXT.security)
            {
                case WF_SECURITY_OPEN:   //keep compiler happy, nothing to do here!
                    break;

                case WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:  //wpa passphrase
                    printf("\r\nPassphrase type of key! ");
                    ascii_key = 1;
                    key_size = strlen((char *)(curHTTP.data+6));
                    //between 8-63 characters, passphrase
                    if ((key_size < 8 ) || (key_size > 63))
                          goto ConfigFailure;
                    break;

                case WF_SECURITY_WPA_AUTO_WITH_KEY: //wpa pre-calculated key!!!
                    key_size = 64;
                    break;

                case WF_SECURITY_WEP_40:
                    key_size = 10; /* Assume hex size */
                    if (strlen((char *)(curHTTP.data+6)) == 5) {
                        key_size = 5;  /* ASCII key support */
                        ascii_key = 1;
                     }
                    CFGCXT.defaultWepKey = 0; /* Example uses only key idx 0 (sometimes called 1) */
                    break;

                case WF_SECURITY_WEP_104:
                    key_size = 26; /* Assume hex size */
                    if (strlen((char *)(curHTTP.data+6)) == 13) {
                        key_size = 13;  /* ASCII key support */
                        ascii_key = 1;
                    }
                    CFGCXT.defaultWepKey = 0; /* Example uses only key idx 0 (sometimes called 1) */
                    break;

                default:
                    break;
            }

			if (strlen((char *)(curHTTP.data+6)) != key_size)
            {
                printf("\r\nIncomplete key received! ");
                goto ConfigFailure;
            }
            memcpy(CFGCXT.key, (void*)(curHTTP.data+6), key_size);
            CFGCXT.key[key_size] = 0; /* terminate string */
            if (!ascii_key)
            {
                //if ((cfg.security == sec_wep64) || (cfg.security == sec_wep128))
                    key_size /= 2;
                if (!convertAsciiToHexInPlace((INT8 *)&CFGCXT.key[0], key_size))
                {
                    printf("\r\nFailed to convert ASCII to hex! ");
                    goto ConfigFailure;
                }
            }
		}

        //**************************************
        // Get new SSID and make sure it is valid
        //**************************************
		else if(!strcmppgm2ram((char*)curHTTP.data, "ssid"))
		{
			if(strlen((char*)(curHTTP.data+6)) < 33u)
			{
                memcpy(CFGCXT.ssid, (void*)(curHTTP.data+6), strlen((char*)(curHTTP.data+6)));
                CFGCXT.ssid[strlen((char*)(curHTTP.data+6))] = 0; /* Terminate string */

                /* save current profile SSID for displaying later */
                WF_CPGetSsid(1, (UINT8*)&CFGCXT.prevSSID, &ssidLen);
                // WF_CPGetSsid(ConnectionProfileID, (UINT8*)&CFGCXT.prevSSID, &ssidLen);

                CFGCXT.prevSSID[ssidLen] = 0;
                printf("\r\nSSID: %s",CFGCXT.ssid);
			}
			else
			{   //Invalid SSID... fail :-(
                printf("\r\nInvalid SSID...! ");
				goto ConfigFailure;
			}
		}

        //*************************************************************
        // Get the WLAN Mode: Adhoc / Infrastructure / SoftAP / Wifi Direct
        //*************************************************************
        else if(!strcmppgm2ram((char*)curHTTP.data, (ROM char*)"wlan"))
        {
            char mode[6];

            if (strlen((char*)(curHTTP.data+6)) > 5) /* Sanity check */
                goto ConfigFailure;

            memcpy(mode, (void*)(curHTTP.data+6), strlen((char*)(curHTTP.data+6)));
            mode[strlen((char*)(curHTTP.data+6))] = 0; /* Terminate string */
            if(!strcmppgm2ram((char*)mode, (ROM char*)"infra"))
            {
                printf("\r\nSetting mode to infrastructure! ");
                CFGCXT.type = WF_INFRASTRUCTURE;
            }
            else if(!strcmppgm2ram((char*)mode, "adhoc"))
            {
                printf("\r\nSetting mode to adhoc! ");
                CFGCXT.type = WF_ADHOC;

                // Always setup adhoc to attempt to connect first, then start
                WF_CPSetAdHocBehavior(1, WF_ADHOC_CONNECT_THEN_START);
                //WF_CPSetAdHocBehavior(ConnectionProfileID, WF_ADHOC_CONNECT_THEN_START);
            }
            else if(!strcmppgm2ram((char*)mode, "wfp2p"))
            {
                printf("\r\nSetting mode to wifi-direct! ");
                CFGCXT.type = WF_P2P;
            }
            else if(!strcmppgm2ram((char*)mode, "sofap"))
            {
                printf("\r\nSetting mode to softap! ");
                CFGCXT.type = WF_SOFT_AP;
            }
            else
            {   //Mode type no good  :-(
                printf("\r\nConfig WLAN Mode Failure! ");
                goto ConfigFailure;
            }

            // save old WLAN mode
            // WF_CPGetNetworkType(ConnectionProfileID, &CFGCXT.prevWLAN);
            WF_CPGetNetworkType(1, &CFGCXT.prevWLAN);
            }
	}

    /* Check if WPA hasn't been selected with adhoc, if it has we choke! */
	/* Adhoc : Support only OPEN and WEP                                           */
	/* SoftAP: Support only OPEN and WEP (0x3107)                             */

    if (((CFGCXT.type == WF_ADHOC) &&
               ((CFGCXT.security == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE) || (CFGCXT.security == WF_SECURITY_WPA_AUTO_WITH_KEY)))
     ||((CFGCXT.type == WF_SOFT_AP) &&
	           ((CFGCXT.security == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE) || (CFGCXT.security == WF_SECURITY_WPA_AUTO_WITH_KEY))))
        goto ConfigFailure;

    /*  All parsing complete!  If we have got to here all data has been validated and
            we can handle what is necessary to start the reconfigure process of the WiFi device   */

    // Copy wifi cfg data to be committed
#if defined ( EZ_CONFIG_STORE )
    strcpy((char *)AppConfig.MySSID, (char *)CFGCXT.ssid);
    AppConfig.SsidLength = strlen((char*)(CFGCXT.ssid));

	/* Going to set security type */
    AppConfig.SecurityMode =  CFGCXT.security;

    /* Going to save the key, if required */
    if (CFGCXT.security != WF_SECURITY_OPEN)
    {
        BYTE  key_size =0;

        switch ((BYTE)CFGCXT.security)
        {
            case WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:  //wpa passphrase
                key_size = strlen((char*)(CFGCXT.key)); //ascii so use strlen
                break;
            case WF_SECURITY_WPA_AUTO_WITH_KEY: //wpa pre-calculated key!!!
                key_size = 32;
                break;
            case WF_SECURITY_WEP_40:
                key_size = 5;
                break;
            case WF_SECURITY_WEP_104:
                key_size = 13;
                break;

        }
        memcpy(AppConfig.SecurityKey, CFGCXT.key, key_size);
        AppConfig.SecurityKey[strlen((char*)(CFGCXT.key))] = 0;

    }

    /* Going to save the network type */
    AppConfig.networkType = CFGCXT.type;
	AppConfig.dataValid = 1; /* Validate wifi configuration */

#endif // EZ_CONFIG_STORE

	// Set the board to reboot and display reconnecting information
	strcpypgm2ram((char*)curHTTP.data, "/reconnect.htm");
	curHTTP.httpStatus = HTTP_REDIRECT;

    /*
         * Set state here to inform that the Wifi device has config data and it is ready
         * to be acted upon.
         */
    printf("\r\nFlagging to start config change!\r\n");

	WF_START_EASY_CONFIG();

	return HTTP_IO_DONE;

ConfigFailure:
	lastFailure = TRUE;
	strcpypgm2ram((char*)curHTTP.data, "/error.htm");
	curHTTP.httpStatus = HTTP_REDIRECT;

	return HTTP_IO_DONE;
}

#endif //(HTTP_USE_POST)

/****************************************************************************
  Section:
	Dynamic Variable Callback Functions
  ***************************************************************************/

/*****************************************************************************
  Function:
	void HTTPPrint_varname(void)

  Internal:
  	See documentation in the TCP/IP Stack API or HTTP2.h for details.
  ***************************************************************************/

// ======================================
// = Sends the State of SW0             =
// ======================================
ROM BYTE HTML_UP_ARROW[] = "up";
ROM BYTE HTML_DOWN_ARROW[] = "dn";
void HTTPPrint_btn(WORD num)
{
    // Determine which button
    switch(num)
    {
        case 0:
            num = SW0_IO;
            break;
        default:
            num = 0;
    }

    // Print the output
    TCPPutROMString(sktHTTP, (num?HTML_UP_ARROW:HTML_DOWN_ARROW));
    return;
}

// ======================================
// = Sends the Requested LED's State    =
// ======================================
void HTTPPrint_led(WORD num)
{
    // Determine which LED requested
    switch(num)
    {
        case 0:
            num = LED0_IO;
            break;
        case 1:
            num = LED1_IO;
            break;
        case 2:
            num = LED2_IO;
            break;
        default:
            num = 0;
    }

    // Print the output
    TCPPut(sktHTTP, (num?'1':'0'));
    return;
}

// ======================================
// = Sends the MAC Address    =
// ======================================
void HTTPPrint_macaddr(void)
{
    char macAddr[18];

    sprintf(macAddr,"%02X:%02X:%02X:%02X:%02X:%02X",AppConfig.MyMACAddr.v[0], AppConfig.MyMACAddr.v[1], AppConfig.MyMACAddr.v[2], AppConfig.MyMACAddr.v[3], AppConfig.MyMACAddr.v[4], AppConfig.MyMACAddr.v[5]);
    TCPPutString(sktHTTP, (BYTE *)macAddr);
}

// ======================================
// = Sends the IP Address    =
// ======================================
void HTTPPrint_ipaddr(void)
{
    char ipAddr[16];

    sprintf(ipAddr,"%u.%u.%u.%u",AppConfig.MyIPAddr.v[0], AppConfig.MyIPAddr.v[1],AppConfig.MyIPAddr.v[2],AppConfig.MyIPAddr.v[3]);
    TCPPutString(sktHTTP, (BYTE *)ipAddr);
}

// ================================
// = Kick-off a WiFi Scan Process =
// ================================
void HTTPPrint_scan(void)
{
    BYTE scanInProgressString[4];

    uitoa(IS_SCAN_IN_PROGRESS(SCANCXT.scanState), scanInProgressString);
    TCPPutString(sktHTTP, scanInProgressString);
}

// ======================================
// = Sends the FW version     =
// ======================================
void HTTPPrint_fwver(void)
{
    static BOOL firstTime = TRUE;
    static tWFDeviceInfo deviceInfo;
    BYTE fwVerString[8];
    int temp1;

    if (firstTime)
    {
        firstTime = FALSE;
        WF_GetDeviceInfo(&deviceInfo);  // only call this once, not continually
    }

	temp1 = sprintf((char *)fwVerString,"%02x%02x", deviceInfo.romVersion , deviceInfo.patchVersion);
	TCPPutString(sktHTTP, fwVerString);
}

// ======================================
// = Sends the new/current SSID setting =
// ======================================
void HTTPPrint_ssid(void)
{
    TCPPutArray(sktHTTP, AppConfig.MySSID, AppConfig.SsidLength);
}

// =====================================================
// = Sends the number of BSS entries found from a scan =
// =====================================================
void HTTPPrint_bssCount(void)
{
    BYTE bssCountString[4];

    uitoa(SCANCXT.numScanResults, bssCountString);
    TCPPutString(sktHTTP, bssCountString);
}

void HTTPPrint_valid(void)
{
    BYTE bssDescIsValidString[4];

    uitoa((BYTE)bssDescIsValid, bssDescIsValidString);
    TCPPutString(sktHTTP, bssDescIsValidString);
}

void HTTPPrint_name(void)
{
    if (bssDescIsValid)
    {
        //TCPPutString(sktHTTP, bssDesc.ssid);
        if(strlen((const char*)bssDesc.ssid)<32)
            TCPPutString(sktHTTP, bssDesc.ssid);
        else
        {
            unsigned char buf_tmp[33];
            int i;
            for(i=0;i<32;i++) buf_tmp[i] = bssDesc.ssid[i];
            buf_tmp[32] = 0;
            TCPPutString(sktHTTP, buf_tmp);
        }
    }
    else
    {
        TCPPutROMString(sktHTTP, (ROM BYTE *)"0");
    }
}

// ======================================
// = Sends the Current Security Setting =
// ======================================

void HTTPPrint_privacy(void)
{
    BYTE security = (bssDesc.apConfig & 0xd0) >> 4;
    BYTE secString[4];

    if (bssDescIsValid)
    {
        uitoa(security, secString);
        TCPPutString(sktHTTP, secString);
    }
    else
    {
        TCPPutROMString(sktHTTP, (ROM BYTE*)"0");
    }
}

void HTTPPrint_curPrivacy(void)
{
    BYTE security = AppConfig.SecurityMode;

    if (bssDescIsValid)
    {
        switch (security)
        {
            case 0:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"None");
                break;
            case 1:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WEP");
                break;
            case 2:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WEP");
                break;
            case 3:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WPA");
                break;
            case 4:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WPA");
                break;
            case 5:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WPA2");
                break;
            case 6:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WPA2");
                break;
            case 7:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WPA-AUTO");
                break;
            case 8:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WPA-AUTO");
                break;
            case 13:
                TCPPutROMString(sktHTTP, (ROM BYTE*)"WPA");
                break;
            default:
                // impossible to get here!
            break;
        }
    }
    else
    {
        TCPPutROMString(sktHTTP, (ROM BYTE*)"None");
    }
}

// ===========================================
// = Sends the new/current WLAN setting type =
// ===========================================
void HTTPPrint_wlan(void)
{
	BYTE bssTypeString[4];

	// Index.htm differs between EZConfig and wifi g demo in that index.htm
	// in wifi g demo displays BSS information of MRF24WG.

	if (bssDescIsValid)
	{
		if(IS_SCAN_STATE_DISPLAY(SCANCXT.scanState))
		{
			uitoa(bssDesc.bssType, bssTypeString);
			TCPPutString(sktHTTP, bssTypeString);
		}
		else
		{
			if(AppConfig.networkType == WF_ADHOC)
				TCPPutROMString(sktHTTP, (ROM BYTE*)"AdHoc (IBSS)");
			else if (AppConfig.networkType == WF_INFRASTRUCTURE)
				TCPPutROMString(sktHTTP, (ROM BYTE*)"Infrastructure (BSS)");
			else if (AppConfig.networkType == WF_SOFT_AP)
				TCPPutROMString(sktHTTP, (ROM BYTE*)"SoftAP (BSS)");
			else if (AppConfig.networkType == WF_P2P)
				TCPPutROMString(sktHTTP, (ROM BYTE*)"WiFi Direct P2P (BSS)");
			else
				TCPPutROMString(sktHTTP, (ROM BYTE*)"Unknown BSS");
		}
	}
	else
	{
		if(AppConfig.networkType == WF_ADHOC)
			TCPPutROMString(sktHTTP, (ROM BYTE*)"AdHoc (IBSS)");
		else if (AppConfig.networkType == WF_INFRASTRUCTURE)
			TCPPutROMString(sktHTTP, (ROM BYTE*)"Infrastructure (BSS)");
		else if (AppConfig.networkType == WF_SOFT_AP)
			TCPPutROMString(sktHTTP, (ROM BYTE*)"SoftAP (BSS)");
		else if (AppConfig.networkType == WF_P2P)
			TCPPutROMString(sktHTTP, (ROM BYTE*)"WiFi Direct P2P (BSS)");
		else
			TCPPutROMString(sktHTTP, (ROM BYTE*)"Unknown BSS");
	}

}

void HTTPPrint_strength(void)
{
    BYTE strVal;
    BYTE strString[4];

    if (bssDescIsValid)
    {
        if (bssDesc.rssi < 121)
        {
            strVal = 1;
        }
        else if (bssDesc.rssi < 141)
        {
            strVal = 2;
        }
        else if (bssDesc.rssi < 161)
        {
            strVal = 3;
        }
        else
        {
            strVal = 4;
        }

        uitoa(strVal, strString);
        TCPPutString(sktHTTP, strString);
    }
    else
    {
        TCPPutROMString(sktHTTP, (ROM BYTE*)"0");
    }
}

void HTTPPrint_nextSSID(void)
{
    TCPPutString(sktHTTP, (BYTE*)CFGCXT.ssid);
}

// ==============================
// = Sends the old SSID setting =
// ==============================
void HTTPPrint_prevSSID(void)
{
    TCPPutString(sktHTTP, (BYTE*)CFGCXT.prevSSID);
}

// ===================================
// = Sends the old WLAN setting type =
// ===================================
void HTTPPrint_prevWLAN(void)
{
    if (CFGCXT.prevWLAN == WF_INFRASTRUCTURE)
        TCPPutROMString(sktHTTP, (ROM BYTE*)"Infrastructure (BSS)");
    else if (CFGCXT.prevWLAN == WF_SOFT_AP)
        TCPPutROMString(sktHTTP, (ROM BYTE*)"SoftAP (BSS)");
    else if (CFGCXT.prevWLAN == WF_ADHOC)
        TCPPutROMString(sktHTTP, (ROM BYTE*)"Adhoc (IBSS)");
    else if (CFGCXT.prevWLAN == WF_P2P)
        TCPPutROMString(sktHTTP, (ROM BYTE*)"WiFi Direct P2P (BSS)");
    else
        TCPPutROMString(sktHTTP, (ROM BYTE*)"Unknown BSS");
}

void HTTPPrint_nextWLAN(void)
{
    if (CFGCXT.type == WF_INFRASTRUCTURE)
    {
        TCPPutROMString(sktHTTP, (ROM BYTE*)"Infrastructure (BSS)");
    }
    else if (CFGCXT.type == WF_ADHOC)
    {
        TCPPutROMString(sktHTTP, (ROM BYTE*)"Adhoc (IBSS)");
    }
    else if (CFGCXT.type == WF_SOFT_AP)
    {
        TCPPutROMString(sktHTTP, (ROM BYTE*)"SoftAP (BSS)");
    }
    else
    {
        TCPPutROMString(sktHTTP, (ROM BYTE*)"unknown");
    }
}

// ==========================
// = Sends the Demo Version =
// ==========================
void HTTPPrint_Demoversion(void)
{
    TCPPutROMString(sktHTTP, (ROM void*)DEMO_VERSION);
}

// ==============================================
// = Provides the XML list of WiFi Scan Results =
// ==============================================
void HTTPPrint_aplist(void)
{
    int x;
    BYTE security;
    BYTE secString[4];
    BYTE bssTypeString[4];
    BYTE strVal;
    BYTE strString[4];

    for(x=0; x < SCANCXT.numScanResults; x++)
    {
        WFRetrieveScanResult(x, &bssDesc);

        TCPPutROMString(sktHTTP, (ROM BYTE*)"<bss>\n");
        TCPPutROMString(sktHTTP, (ROM BYTE*)"<name>");
        TCPPutString(sktHTTP, bssDesc.ssid);
        TCPPutROMString(sktHTTP, (ROM BYTE*)"</name>\n");
        TCPPutROMString(sktHTTP, (ROM BYTE*)"<privacy>");
        security = (bssDesc.apConfig & 0xd0) >> 4;
        uitoa(security, secString);
        TCPPutString(sktHTTP, secString);
        TCPPutROMString(sktHTTP, (ROM BYTE*)"</privacy>\n");
        TCPPutROMString(sktHTTP, (ROM BYTE*)"<wlan>");
        uitoa(bssDesc.bssType, bssTypeString);
        TCPPutString(sktHTTP, bssTypeString);
        TCPPutROMString(sktHTTP, (ROM BYTE*)"</wlan>\n");
        TCPPutROMString(sktHTTP, (ROM BYTE*)"<strength>");
        if (bssDesc.rssi < 121)
        {
            strVal = 1;
        }
        else if (bssDesc.rssi < 141)
        {
            strVal = 2;
        }
        else if (bssDesc.rssi < 161)
        {
            strVal = 3;
        }
        else
        {
            strVal = 4;
        }

        uitoa(strVal, strString);
        TCPPutString(sktHTTP, strString);
        TCPPutROMString(sktHTTP, (ROM BYTE*)"</strength>\n");
        TCPPutROMString(sktHTTP, (ROM BYTE*)"</bss>\n");
    }
}
/* Dynamic variables corresponding functions here
 *
 * Attention one thing, when send request command from web browser or Matlab, the request get executed first
 * and then send the response from here
 *
 */
void HTTPPrint_motorcom(void)
{
   //TCPPutString(sktHTTP, "test");
}

void HTTPPrint_anterior(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.canterior);
    displock = 0;
}

void HTTPPrint_posterior(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.cposterior);
    displock = 0;
}

void HTTPPrint_command_response(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.command_response);
    displock = 0;
}

void HTTPPrint_motor_position(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.motor_position);
    displock = 0;
}

void HTTPPrint_query_response(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.query_response);
    displock = 0;
}

void HTTPPrint_gyro_x(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.cgyro_x);
    displock = 0;
}

void HTTPPrint_gyro_y(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.cgyro_y);
    displock = 0;
}

void HTTPPrint_gyro_z(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.cgyro_z);
    displock = 0;
}

void HTTPPrint_accel_x(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.caccel_x);
    displock = 0;
}

void HTTPPrint_accel_y(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.caccel_y);
    displock = 0;
}

void HTTPPrint_accel_z(void){
    displock = 1;
    TCPPutString(sktHTTP, motor_status.caccel_z);
    displock = 0;
}

/*------------------------------------------------------------*/
// UART send command
void UARTTxBuffer2(BYTE *buffer, UINT32 size, UART_MODULE UART_PORT)
{
    while(size)
    {
        while(!UARTTransmitterIsReady(UART_PORT))
            ;

        UARTSendDataByte(UART_PORT, *buffer);

        buffer++;
        size--;
    }

    while(!UARTTransmissionHasCompleted(UART_PORT));
}

//  function for get the feedback from motor, the feedback store in motor_status.command_response
void GetFeedBack(char *ptr, UART_MODULE UART_PORT){

    int i=0;    // 3 bytes that need to loop
    //int timeout = 1;      // 1 means timeout, no feedback from motor, connection lost, 0 means feedback detected
                      // set to 1 everytime comes in
    INTClearFlag(INT_T4);
    OpenTimer4(T4_ON | T4_SOURCE_INT | T4_PS_1_256, 156*10);       // 156 means 1ms for count, here is 5ms set into period
    // Don't need to let Timer 4 interrrupt enable, we just use the flag

    for (i=0;i<20;i++)
    {
        while(!UARTReceivedDataIsAvailable(UART_PORT))  //ATTENTION!!!! When disconnect with motor, a spike will come up and represent as a char,
            //then stuck here infinite loop cause no '\n' after that spike char
            // the way to fix the problem is to set every singal char a timer 4, check every char timeout comming here
            if (INTGetFlag(INT_T4)) break;         // if flag set, means timeout, no UART response

        CloseTimer4();   // turn timer off

        if (INTGetFlag(INT_T4)) break;   // if already enter the interrupt, means time out, break the loop;

        *(ptr+i) = UARTGetDataByte(UART_PORT);

        if (*(ptr+i)=='\n')     // if the line feed feedback detected, means end of feedback, break
            break;

        OpenTimer4(T4_ON | T4_SOURCE_INT | T4_PS_1_256, 156*10);  // turn on the Timer 4 once again, just for overcome the spike
        // the way to do it here is to check the timeout of every char sent back to here
    }
    *(ptr+i)='\0';      // end of string, change \n to \0
    CloseTimer4();      // close timer

    if (INTGetFlag(INT_T4))                    // if no response, change string to "Lost Connection"
    {
        char *ptr2 = LST_CON;
        for(i=0;i<16;i++)
            *(ptr+i) = *(ptr2+i);
    }

    INTClearFlag(INT_T4);
}

 /** function of number to string **/
int num2str(int num_in, char *ptr){
    char *ptr_ori;
    int num_wei;         // number bits
    ptr_ori=ptr;
    if ((num_in / 10000) % 10 == 0)
        if ((num_in / 1000) % 10 == 0)
            if ((num_in / 100) % 10 == 0)
                if ((num_in / 10) % 10 == 0) {
                    *ptr_ori++ = num_in + '0';
                    num_wei = 1;
                }
                else {
                    *ptr_ori++ = num_in / 10 + '0';
                    *ptr_ori++ = num_in % 10 + '0';
                    num_wei = 2;
                }
            else {
                *ptr_ori++ = num_in / 100 + '0';
                *ptr_ori++ = (num_in / 10) % 10 + '0';
                *ptr_ori++ = num_in % 10 + '0';
                num_wei = 3;
            }
        else {
            *ptr_ori++ = num_in / 1000 + '0';
            *ptr_ori++ = (num_in / 100) % 10 + '0';
            *ptr_ori++ = (num_in / 10) % 10 + '0';
            *ptr_ori++ = num_in % 10 + '0';
            num_wei = 4;
        }
    else {
        *ptr_ori++ = num_in / 10000 + '0';
        * ptr_ori++ = (num_in / 1000)%10 + '0';
        *ptr_ori++ = (num_in / 100) % 10 + '0';
        *ptr_ori++ = (num_in / 10) % 10 + '0';
        *ptr_ori++ = num_in % 10 + '0';
        num_wei = 5;
    }
    *ptr_ori='\0';

    return num_wei+1;
}

 /** function of hex to string , used on tilt sensor**/
int hex2str(BYTE *hex, char *ptr){

    //

    return 2;
}

// Interrupt
// Configure the Timer 3 interrupt handler, used for update sensors and motor information, enter every 1 ms
void __ISR(_TIMER_3_VECTOR, ipl2) Timer3Handler(void)
{
    // Clear the timer3 interrupt flag and enable
    INTClearFlag(INT_T3);
     CloseTimer3();

    // Update all the sensors and motor information below

    // set the SAMP bit to open the ADC acquisition of analog signals
    // need certain time to finish sample of analog signals, the time is unknow because I can't find the time information needed to be wait.
 /*   AcquireADC10();

    // do the motor position requirement(or can do inside the request part, not in interrupt part)
    //UARTTxBuffer2("/1?0\r\n", 6, UART1);     // send to position query command, here 1 is fixed, should be modified in the future
   // GetFeedBack(motor_status.query_response, UART1);

    //DO_MOTOR_POSITION()
    int i;
    for (i=0; i<1000; i++)
        _nop();                           // wait for a certain time, here is for 1/4k sec.

    // clear the SAMP bit to start the ADC convertion of analog signals
    ConvertADC10();

    while(!BusyADC10())    // just wait for the convertion complete  */
        ;
            // Determine which buffer is idle and create an offset
        while(!mAD1GetIntFlag());
        offset = 0;//8 * ((~ReadActiveBufferADC10() & 0x01));

        // Read the result of temperature sensor conversion from the idle buffer
        canterior = ReadADC10(offset);
        cposterior = ReadADC10(offset+1);
        num2str(canterior,motor_status.canterior);
        num2str(cposterior,motor_status.cposterior);

        mAD1ClearIntFlag();

  // below is for the MPU 9150 tilt sensor data reading process

     if(Mpu_I2c_SetReg(int_enable, 0x01, I2C_NUM)==I2C_SUCCESS)      // 0x01 means generate interrupt when sensor data is ready
     {
     while (Mpu_INT != 1)        // wait 4 the sample and conversion done
         _nop();
     Mpu_I2c_SetReg(int_enable, 0x00, I2C_NUM);      // 0x00 means disable interrupt when sensor data is ready
     Mpu_I2c_ReadGyro_x(motor_status.gyro_x, I2C_NUM);
     Mpu_I2c_ReadGyro_y(motor_status.gyro_y, I2C_NUM);
     Mpu_I2c_ReadGyro_z(motor_status.gyro_z, I2C_NUM);
     Mpu_I2c_ReadAccel_x(motor_status.accel_x, I2C_NUM);
     Mpu_I2c_ReadAccel_y(motor_status.accel_y, I2C_NUM);
     Mpu_I2c_ReadAccel_z(motor_status.accel_z, I2C_NUM);

    // the step above is for requesting the data ready signal from MPU 9150, below is actual read
    // the step below is number to string conversion
     if (displock==0){
     num2str((int)motor_status.gyro_x[0]*256 + (int)motor_status.gyro_x[1] , motor_status.cgyro_x);
     num2str((int)motor_status.gyro_y[0]*256 + (int)motor_status.gyro_y[1] , motor_status.cgyro_y);
     num2str((int)motor_status.gyro_z[0]*256 + (int)motor_status.gyro_z[1] , motor_status.cgyro_z);
     num2str((int)motor_status.accel_x[0]*256 + (int)motor_status.accel_x[1] , motor_status.caccel_x);
     num2str((int)motor_status.accel_y[0]*256 + (int)motor_status.accel_y[1] , motor_status.caccel_y);
     num2str((int)motor_status.accel_z[0]*256 + (int)motor_status.accel_z[1] , motor_status.caccel_z);
     }
     }
    OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_256, PERIOD);
    INTEnable(INT_T3, INT_ENABLED);    // re-enable the interrupt
}

#endif


text:
<!DOCTYPE html>

    <title>Istanbul Convention – Sebastian Köhnken – Some young one's thoughts</title>

        <meta charset="utf-8" />
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>

    <meta name="description" content="Latvia isn't gonna sign a new convention combating violence against women and domestic violence interesting. The reasoning is a bit weird for me, but not unreasonable. What's really odd, is the convention itself. I'm just gonna pick out some parts that strike me as strange, not everything in the 37 pages.

" />
    <meta property="og:description" content="Latvia isn't gonna sign a new convention combating violence against women and domestic violence interesting. The reasoning is a bit weird for me, but not unreasonable. What's really odd, is the convention itself. I'm just gonna pick out some parts that strike me as strange, not everything in the 37 pages.

" />

    <meta name="author" content="Sebastian Köhnken" />

    <meta property="og:title" content="Istanbul Convention" />
    <meta property="twitter:title" content="Istanbul Convention" />

    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title="Sebastian Köhnken - Some young one's thoughts" href="/feed.xml" />

Sebastian Köhnken

Some young one's thoughts

            Blog
            About

Istanbul Convention

Latvia isn't gonna sign a new convention combating violence against women and domestic violence interesting. The reasoning is a bit weird for me, but not unreasonable. What's really odd, is the convention itself. I'm just gonna pick out some parts that strike me as strange, not everything in the 37 pages.

1 The purposes of this Convention are to:
a protect women against all forms of violence, and prevent, prosecute and eliminate violence against women and domestic violence;
b contribute to the elimination of all forms of discrimination against women and promote substantive equality between women and men, including by empowering women;
c design a comprehensive framework, policies and measures for the protection of and assistance to all victims of violence against women and domestic violence;
d promote international co-operation with a view to eliminating violence against women and domestic violence;
e provide support and assistance to organisations and law enforcement agencies to effectively co-operate in order to adopt an integrated approach to eliminating violence against women and domestic violence.

Most notably, every purpose of this convention has women (in this case broader used for everyone female) as primary victims and not men. Domestic violence isn't an issue that needs to be tackled for one sex specifically. It doesn't matter if you're male or female or your partner is male or female, as soon as it happens, whoever is attacked is the victim. You might as well say "we'll help anyone who experiences domestic violence in their family" and the outcome wouldn't change much for women. Why not address everyone affected? Why not help everyone?

1 Parties shall take the necessary measures to promote changes in the social and cultural patterns of behaviour of women and men with a view to eradicating prejudices, customs, traditions and all other practices which are based on the idea of the inferiority of women or on stereotyped roles for women and men.

It's almost hilarious how this comes soon after the purpose of the convention. I'm all in for tearing down some stereotypes. Let's start with "men are inherently more violent" that this convention indirectly promotes.
Sadly it's not that easy. Through having testosterone in their body, men are in fact more aggressive. But not every man is aggressive or violent.

On top of that, you can't just change stereotypes like that. It's a social progress that spans over generations. Personally I think, I grew up in a very equal environment. I, just like others around me, don't think of women as inferior. That's what we're gonna tell our daughters: Do what you want!
But you can't change the opinion of a grown adult through legislation. As much as some would like to do that, that's hardly possible.

2 Parties shall take the necessary legislative and other measures to prevent all forms of violence covered by the scope of this Convention by any natural or legal person.

Prevent violence? How? You can't punish anyone who didn't commit a crime in our legal systems. If they are violent, they've already commited the crime and you can't prevent it. To prevent something, you have to take actions to not let it happen, like using a condom during intercourse. That however is impossible in case of violence, because it is actively conducted by someone.
You can't prevent an attack, be it in a family, between nations in forms of the declaration of war or in virtual space via hacking. You also can't build a wall of some sorts between the two parties in a familiar relationship.

4 Parties shall take the necessary measures to encourage all members of society, especially men and boys, to contribute actively to preventing all forms of violence covered by the scope of this Convention.
5 Parties shall ensure that culture, custom, religion, tradition or so-called "honour" shall not be considered as justification for any acts of violence covered by the scope of this Convention.

Yes, we have the human rights, they already cover all forms of violence. Furthermore the 5th paragraph is pretty much moot in the same sense as these human rights, among pretty much every democratic constitution or whatever acts as their substitute, outlaw violence.

1 Parties shall take, where appropriate, the necessary steps to include teaching material on issues such as equality between women and men, non-stereotyped gender roles, mutual respect, non-violent conflict resolution in interpersonal relationships, gender-based violence against women and the right to personal integrity, adapted to the evolving capacity of learners, in formal curricula and at all levels of education.

Finally something sensible. It isn't really odd, but I still wanted to highlight it. This should be at the core of our actions. Buildung an understanding, fighting violence, tear down social stigmas. But please also don't replace them with new ones. If a woman decides to work to feed her family or be the breadwinner in the family, fine. If the woman decides to be a simple housewife, because the earnings of the man are enough, fine. Don't condemn women who feel comfortable in traditional gender roles, it's their decision.

2 Parties shall provide or arrange for specialist women's support services to all women victims of violence and their children.

Where's the man's support? Just because men experience it way less doesn't mean they don't need it. In fact, they're currently in more need than women, because they lack these kinds of services.

Interestingly enough, the occurance rate of "woman" in this convention thins out quickly after the a few pages. They're still indirectly mentioned by the term "scope of this Convention" though.

I don't really see the point of this convention though. Domestic violence has been an issue even 20 years ago. At least in Germany, a lot has been done to help women who experienced violence. It's nothing new. It may be new in Asian countries, basically those east of Istanbul, but not so much in the West. I can really see Latvia's point, as it condemn men more than it help women in most european countries.

    Written on June 10, 2017


text:
function ConfigManager() {
    throw new Error('This is a static class');
}

ConfigManager.alwaysDash        = false;
ConfigManager.commandRemember   = false;

Object.defineProperty(ConfigManager, 'bgmVolume', {
    get: function() {
        return AudioManager._bgmVolume;
    },
    set: function(value) {
        AudioManager.bgmVolume = value;
    },
    configurable: true
});

Object.defineProperty(ConfigManager, 'bgsVolume', {
    get: function() {
        return AudioManager.bgsVolume;
    },
    set: function(value) {
        AudioManager.bgsVolume = value;
    },
    configurable: true
});

Object.defineProperty(ConfigManager, 'meVolume', {
    get: function() {
        return AudioManager.meVolume;
    },
    set: function(value) {
        AudioManager.meVolume = value;
    },
    configurable: true
});

Object.defineProperty(ConfigManager, 'seVolume', {
    get: function() {
        return AudioManager.seVolume;
    },
    set: function(value) {
        AudioManager.seVolume = value;
    },
    configurable: true
});

ConfigManager.load = function() {
    var json;
    var config = {};
    try {
        json = StorageManager.load(-1);
    } catch (e) {
        console.error(e);
    }
    if (json) {
        config = JSON.parse(json);
    }
    this.applyData(config);
};

ConfigManager.save = function() {
    StorageManager.save(-1, JSON.stringify(this.makeData()));
};

ConfigManager.makeData = function() {
    var config = {};
    config.alwaysDash = this.alwaysDash;
    config.commandRemember = this.commandRemember;
    config.bgmVolume = this.bgmVolume;
    config.bgsVolume = this.bgsVolume;
    config.meVolume = this.meVolume;
    config.seVolume = this.seVolume;
    return config;
};

ConfigManager.applyData = function(config) {
    this.alwaysDash = this.readFlag(config, 'alwaysDash');
    this.commandRemember = this.readFlag(config, 'commandRemember');
    this.bgmVolume = this.readVolume(config, 'bgmVolume');
    this.bgsVolume = this.readVolume(config, 'bgsVolume');
    this.meVolume = this.readVolume(config, 'meVolume');
    this.seVolume = this.readVolume(config, 'seVolume');
};

ConfigManager.readFlag = function(config, name) {
    return !!config[name];
};

ConfigManager.readVolume = function(config, name) {
    var value = config[name];
    if (value !== undefined) {
        return Number(value).clamp(0, 100);
    } else {
        return 100;
    }
};


text:
package org.apache.geode.cache.query.cq.internal;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.Set;

import org.apache.logging.log4j.Logger;

import org.apache.geode.DataSerializable;
import org.apache.geode.DataSerializer;
import org.apache.geode.annotations.VisibleForTesting;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.EvictionAction;
import org.apache.geode.cache.query.CqAttributes;
import org.apache.geode.cache.query.CqAttributesMutator;
import org.apache.geode.cache.query.CqClosedException;
import org.apache.geode.cache.query.CqException;
import org.apache.geode.cache.query.CqExistsException;
import org.apache.geode.cache.query.CqResults;
import org.apache.geode.cache.query.Query;
import org.apache.geode.cache.query.RegionNotFoundException;
import org.apache.geode.cache.query.internal.CompiledBindArgument;
import org.apache.geode.cache.query.internal.CompiledIteratorDef;
import org.apache.geode.cache.query.internal.CompiledRegion;
import org.apache.geode.cache.query.internal.CompiledSelect;
import org.apache.geode.cache.query.internal.CqStateImpl;
import org.apache.geode.cache.query.internal.DefaultQuery;
import org.apache.geode.cache.query.internal.cq.CqServiceProvider;
import org.apache.geode.cache.query.internal.cq.ServerCQ;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.LocalRegion;
import org.apache.geode.internal.cache.tier.sockets.CacheClientNotifier;
import org.apache.geode.internal.cache.tier.sockets.CacheClientProxy;
import org.apache.geode.internal.cache.tier.sockets.ClientProxyMembershipID;
import org.apache.geode.logging.internal.log4j.api.LogService;

public class ServerCQImpl extends CqQueryImpl implements DataSerializable, ServerCQ {
  private static final Logger logger = LogService.getLogger();
  private static final ServerCQResultsCache NO_OP_CACHE = new ServerCQResultsCacheNoOpImpl();

  /**
   * NOTE: In case of Replicated Regions this cache is populated and used as intended. In case of
   * Partition Regions this cache will not be populated. If executeCQ happens after update
   * operations this cache will remain empty.
   */
  private volatile ServerCQResultsCache serverCQResultsCache = NO_OP_CACHE;

  /** Boolean flag to see if the CQ is on Partitioned Region */
  volatile boolean isPR = false;

  private ClientProxyMembershipID clientProxyId = null;

  private CacheClientNotifier ccn = null;

  private String serverCqName;

  /** identifier assigned to this query for FilterRoutingInfos */
  private Long filterID;

  public ServerCQImpl(CqServiceImpl cqService, String cqName, String queryString, boolean isDurable,
      String serverCqName) {
    super(cqService, cqName, queryString, isDurable);
    this.serverCqName = serverCqName; // On Client Side serverCqName and cqName will be same.
  }

  public ServerCQImpl() {
    // For deserialization
  }

  @Override
  public Long getFilterID() {
    return this.filterID;
  }

  @Override
  public void setFilterID(Long filterID) {
    this.filterID = filterID;
  }

  @Override
  public void setName(String cqName) {
    this.cqName = this.serverCqName = cqName;
  }

  @Override
  public String getServerCqName() {
    return this.serverCqName;
  }

  @Override
  public void registerCq(ClientProxyMembershipID p_clientProxyId, CacheClientNotifier p_ccn,
      int p_cqState) throws CqException, RegionNotFoundException {

    CacheClientProxy clientProxy = null;
    this.clientProxyId = p_clientProxyId;

    if (p_ccn != null) {
      this.ccn = p_ccn;
      clientProxy = p_ccn.getClientProxy(p_clientProxyId, true);
    }

    validateCq();

    final boolean isDebugEnabled = logger.isDebugEnabled();
    String msg = "%s";
    Throwable t = null;
    try {
      this.query = constructServerSideQuery();
      if (isDebugEnabled) {
        logger.debug("Server side query for the cq: {} is: {}", cqName,
            this.query.getQueryString());
      }
    } catch (Exception ex) {
      t = ex;
      if (ex instanceof ClassNotFoundException) {
        msg =
            "Class not found exception. The antlr.jar or the spcified class may be missing from server side classpath. Error : %s";
      } else {
        msg = "Error while parsing the query. Error : %s";
      }
    } finally {
      if (t != null) {
        String s = String.format(msg, t);
        if (isDebugEnabled) {
          logger.debug(s, t);
        }

        throw new CqException(s);
      }
    }

    // Update Regions Book keeping.
    // TODO replace getRegion() with getRegionByPathForProcessing() so this doesn't block
    // if the region is still being initialized
    this.cqBaseRegion = (LocalRegion) cqService.getCache().getRegion(regionName);
    if (this.cqBaseRegion == null) {
      throw new RegionNotFoundException(
          String.format("Region : %s specified with cq not found. CqName: %s", regionName,
              this.cqName));
    }

    // Make sure that the region is partitioned or
    // replicated with distributed ack or global.
    DataPolicy dp = this.cqBaseRegion.getDataPolicy();
    this.isPR = dp.withPartitioning();
    if (!(this.isPR || dp.withReplication())) {
      String errMsg;
      // replicated regions with eviction set to local destroy get turned into preloaded
      if (dp.withPreloaded() && cqBaseRegion.getAttributes().getEvictionAttributes() != null
          && cqBaseRegion.getAttributes().getEvictionAttributes().getAction()
              .equals(EvictionAction.LOCAL_DESTROY)) {
        errMsg =
            String.format("CQ is not supported for replicated region: %s with eviction action: %s",
                this.regionName, cqBaseRegion.getAttributes().getEvictionAttributes().getAction());
      } else {
        errMsg = "The region " + this.regionName
            + "  specified in CQ creation is neither replicated nor partitioned; "
            + "only replicated or partitioned regions are allowed in CQ creation.";
      }
      if (isDebugEnabled) {
        logger.debug(errMsg);
      }
      throw new CqException(errMsg);
    }
    if ((dp.withReplication() && (!(cqBaseRegion.getAttributes().getScope().isDistributedAck()
        || cqBaseRegion.getAttributes().getScope().isGlobal())))) {
      String errMsg = "The replicated region " + this.regionName
          + " specified in CQ creation does not have scope supported by CQ."
          + " The CQ supported scopes are DISTRIBUTED_ACK and GLOBAL.";
      if (isDebugEnabled) {
        logger.debug(errMsg);
      }
      throw new CqException(errMsg);
    }

    // Can be null by the time we are here
    if (clientProxy != null) {
      clientProxy.incCqCount();
      if (clientProxy.hasOneCq()) {
        cqService.stats().incClientsWithCqs();
      }
      if (isDebugEnabled) {
        logger.debug("Added CQ to the base region: {} With key as: {}", cqBaseRegion.getFullPath(),
            serverCqName);
      }
    }

    this.updateCqCreateStats();

    // Initialize the state of CQ.
    if (this.cqState.getState() != p_cqState) {
      setCqState(p_cqState);
    }

    // Register is called from both filter profile and cqService
    // In either case, if we are trying to start/run the cq, we need to add
    // it to other matching cqs for performance reasons
    if (p_cqState == CqStateImpl.RUNNING) {
      // Add to the matchedCqMap.
      cqService.addToMatchingCqMap(this);
    }

    // Initialize CQ results (key) cache.
    if (CqServiceProvider.MAINTAIN_KEYS) {
      // Currently the CQ Result keys are not cached for the Partitioned
      // Regions. Supporting this with PR needs more work like forcing
      // query execution on primary buckets only; and handling the bucket
      // re-balancing. Once this is added remove the check with PR region.
      // Only the events which are seen during event processing is
      // added to the results cache (not from the CQ Results).
      if (this.isPR) {
        serverCQResultsCache = new ServerCQResultsCachePartitionRegionImpl();
        setCqResultsCacheInitialized();
      } else {
        serverCQResultsCache = new ServerCQResultsCacheReplicateRegionImpl();
      }
    }

    if (p_ccn != null) {
      try {
        cqService.addToCqMap(this);
      } catch (CqExistsException cqe) {
        // Should not happen.
        throw new CqException(
            String.format("Unable to create cq %s Error : %s", cqName, cqe.getMessage()));
      }

      this.cqBaseRegion.getFilterProfile().registerCq(this);
    }
  }

  /**
   * For Test use only.
   *
   * @return CQ Results Cache.
   */
  @VisibleForTesting
  public Set<Object> getCqResultKeyCache() {
    return serverCQResultsCache.getKeys();
  }

  /**
   * Returns parameterized query used by the server. This method replaces Region name with $1 and if
   * type is not specified in the query, looks for type from cqattributes and appends into the
   * query.
   *
   * @return String modified query.
   */
  Query constructServerSideQuery() {
    InternalCache cache = cqService.getInternalCache();
    DefaultQuery locQuery = (DefaultQuery) cache.getLocalQueryService().newQuery(this.queryString);
    CompiledSelect select = locQuery.getSimpleSelect();
    CompiledIteratorDef from = (CompiledIteratorDef) select.getIterators().get(0);
    // WARNING: ASSUMES QUERY WAS ALREADY VALIDATED FOR PROPER "FORM" ON CLIENT;
    // THIS VALIDATION WILL NEED TO BE DONE ON THE SERVER FOR NATIVE CLIENTS,
    // BUT IS NOT DONE HERE FOR JAVA CLIENTS.
    // The query was already checked on the client that the sole iterator is a
    // CompiledRegion
    this.regionName = ((CompiledRegion) from.getCollectionExpr()).getRegionPath();
    from.setCollectionExpr(new CompiledBindArgument(1));

    return locQuery;
  }

  /**
   * Returns if the passed key is part of the CQs result set. This method needs to be called once
   * the CQ result key caching is completed (cqResultsCacheInitialized is true).
   *
   * @return true if key is in the Results Cache.
   */
  public boolean isPartOfCqResult(Object key) {
    return serverCQResultsCache.contains(key);
  }

  @Override
  public void addToCqResultKeys(Object key) {
    serverCQResultsCache.add(key);
  }

  @Override
  public void removeFromCqResultKeys(Object key, boolean isTokenMode) {
    serverCQResultsCache.remove(key, isTokenMode);
  }

  @Override
  public void invalidateCqResultKeys() {
    serverCQResultsCache.invalidate();
  }

  /**
   * Marks the key as destroyed in the CQ Results key cache.
   */
  void markAsDestroyedInCqResultKeys(Object key) {
    serverCQResultsCache.markAsDestroyed(key);
  }

  @Override
  public void setCqResultsCacheInitialized() {
    serverCQResultsCache.setInitialized();
  }

  @Override
  public boolean isCqResultsCacheInitialized() {
    return serverCQResultsCache.isInitialized();
  }

  /**
   * Returns the size of the CQ Result key cache.
   *
   * @return size of CQ Result key cache.
   */
  public int getCqResultKeysSize() {
    return serverCQResultsCache.size();
  }

  @Override
  public boolean isOldValueRequiredForQueryProcessing(Object key) {
    return serverCQResultsCache.isOldValueRequiredForQueryProcessing(key);
  }

  @Override
  public boolean isKeyDestroyed(Object key) {
    if (!serverCQResultsCache.contains(key)) {
      return false;
    }
    return serverCQResultsCache.isKeyDestroyed(key);
  }

  /**
   * Closes the Query. On Client side, sends the cq close request to server. On Server side, takes
   * care of repository cleanup.
   */
  @Override
  public void close() throws CqClosedException, CqException {
    close(true);
  }

  @Override
  public void close(boolean sendRequestToServer) throws CqClosedException, CqException {
    final boolean isDebugEnabled = logger.isDebugEnabled();
    if (isDebugEnabled) {
      logger.debug("Started closing CQ CqName: {} SendRequestToServer: {}", cqName,
          sendRequestToServer);
    }
    // Synchronize with stop and execute CQ commands
    synchronized (this.cqState) {
      // Check if the cq is already closed.
      if (this.isClosed()) {
        // throw new CqClosedException("CQ is already closed, CqName : " + this.cqName);
        if (isDebugEnabled) {
          logger.debug("CQ is already closed, CqName: {}", this.cqName);
        }
        return;
      }

      int stateBeforeClosing = this.cqState.getState();
      this.cqState.setState(CqStateImpl.CLOSING);

      // Cleanup the resource used by cq.
      this.removeFromCqMap();

      // Stat update.
      if (stateBeforeClosing == CqStateImpl.RUNNING) {
        cqService.stats().decCqsActive();
      } else if (stateBeforeClosing == CqStateImpl.STOPPED) {
        cqService.stats().decCqsStopped();
      }

      // Clean-up the CQ Results Cache.
      serverCQResultsCache.clear();

      // Set the state to close, and update stats
      this.cqState.setState(CqStateImpl.CLOSED);
      cqService.stats().incCqsClosed();
      cqService.stats().decCqsOnClient();
      if (this.stats != null)
        this.stats.close();
    }

    if (isDebugEnabled) {
      logger.debug("Successfully closed the CQ. {}", cqName);
    }
  }

  @Override
  public ClientProxyMembershipID getClientProxyId() {
    return this.clientProxyId;
  }

  /**
   * Get CacheClientNotifier of this CqQuery.
   *
   */
  public CacheClientNotifier getCacheClientNotifier() {
    return this.ccn;
  }

  /**
   * Clears the resource used by CQ.
   */
  @Override
  protected void cleanup() {
    // CqBaseRegion
    try {
      if (this.cqBaseRegion != null && !this.cqBaseRegion.isDestroyed()) {
        this.cqBaseRegion.getFilterProfile().closeCq(this);
        CacheClientProxy clientProxy = ccn.getClientProxy(clientProxyId);
        clientProxy.decCqCount();
        if (clientProxy.hasNoCq()) {
          cqService.stats().decClientsWithCqs();
        }
      }
    } catch (Exception ex) {
      // May be cache is being shutdown
      if (logger.isDebugEnabled()) {
        logger.debug("Failed to remove CQ from the base region. CqName :{}", cqName);
      }
    }
  }

  /**
   * Stop or pause executing the query.
   */
  @Override
  public void stop() throws CqClosedException {
    synchronized (this.cqState) {
      if (this.isClosed()) {
        throw new CqClosedException(
            String.format("CQ is closed, CqName : %s", this.cqName));
      }

      if (!(this.isRunning())) {
        throw new IllegalStateException(
            String.format("CQ is not in running state, stop CQ does not apply, CqName : %s",
                this.cqName));
      }

      // Change state and stats on the client side
      this.cqState.setState(CqStateImpl.STOPPED);
      this.cqService.stats().incCqsStopped();
      this.cqService.stats().decCqsActive();
      if (logger.isDebugEnabled()) {
        logger.debug("Successfully stopped the CQ. {}", cqName);
      }
    }
  }

  @Override
  public void fromData(DataInput in) throws IOException {
    synchronized (cqState) {
      this.cqState.setState(DataSerializer.readInteger(in));
    }
    this.isDurable = DataSerializer.readBoolean(in);
    this.queryString = DataSerializer.readString(in);
    this.filterID = in.readLong();
  }

  @Override
  public void toData(DataOutput out) throws IOException {
    DataSerializer.writeInteger(this.cqState.getState(), out);
    DataSerializer.writeBoolean(this.isDurable, out);
    DataSerializer.writeString(this.queryString, out);
    out.writeLong(this.filterID);
  }

  @Override
  public boolean isPR() {
    return isPR;
  }

  @Override
  public CqAttributes getCqAttributes() {
    throw new IllegalStateException("CQ attributes are not available on the server");
  }

  @Override
  public CqAttributesMutator getCqAttributesMutator() {
    throw new IllegalStateException("CQ attributes are not available on the server");
  }

  @Override
  public <E> CqResults<E> executeWithInitialResults() throws CqClosedException {
    throw new IllegalStateException("Execute cannot be called on a CQ on the server");
  }

  @Override
  public void execute() throws CqClosedException {
    throw new IllegalStateException("Execute cannot be called on a CQ on the server");
  }
}