text:
package com.github.stefanbirkner.jfortschritt;

import static com.github.stefanbirkner.fishbowl.Fishbowl.exceptionThrownBy;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import com.github.stefanbirkner.fishbowl.Statement;
import de.bechte.junit.runners.context.HierarchicalContextRunner;
import org.assertj.core.api.AbstractCharSequenceAssert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.SystemOutRule;
import org.junit.runner.RunWith;

@RunWith(HierarchicalContextRunner.class)
public class ProgressLineTest {
    private static final int ARBITRARY_NUMBER_OF_STEPS = 42;
    private static final int NUMBER_OF_STEPS_WITH_MULTIPLE_STEPS_PER_CHARACTER = 1_000;

    private ProgressLine progressLine;

    @Rule
    public final SystemOutRule systemOutRule = new SystemOutRule().enableLog().mute();

    public class every_progress_line {
        @Before
        public void useProgressLineWithoutCounter() {
            progressLine = new ProgressLine();
        }

        @Test
        public void progress_line_cannot_be_started_with_negative_number_of_steps() {
            Throwable e = exceptionThrownBy(new Statement() {
                @Override
                public void evaluate() throws Throwable {
                    startProgressLineWithNumberOfSteps(-1);
                }
            });
            assertThat(e).isInstanceOf(IllegalArgumentException.class);
        }

        public class after_started {
            @Test
            public void progress_bar_is_empty() {
                startProgressLineWithArbitraryNumberOfSteps();
                assertTextVisibleAtSystemOut().startsWith("[> ").endsWith(" ]");
            }

            @Test
            public void progress_line_is_72_chars_long() {
                startProgressLineWithArbitraryNumberOfSteps();
                assertTextVisibleAtSystemOut().hasSize(72);
            }

            @Test
            public void progress_line_cannot_be_started_again() {
                startProgressLineWithArbitraryNumberOfSteps();
                Throwable e = exceptionThrownBy(new Statement() {
                    @Override
                    public void evaluate() throws Throwable {
                        startProgressLineWithArbitraryNumberOfSteps();
                    }
                });
                assertThat(e).isInstanceOf(IllegalStateException.class);
            }
        }

        public class after_first_step {
            @Test
            public void progress_bar_shows_at_least_one_char_progress() {
                startProgressLineWithArbitraryNumberOfSteps();
                moveProgressLineNSteps(1);
                assertTextVisibleAtSystemOut().startsWith("[=");
            }

            @Test
            public void progress_bar_shows_single_char_progress_for_very_small_proportion() {
                startProgressLineWithNumberOfSteps(
                    NUMBER_OF_STEPS_WITH_MULTIPLE_STEPS_PER_CHARACTER);
                moveProgressLineNSteps(1);
                assertTextVisibleAtSystemOut().startsWith("[=> ");
            }

            @Test
            public void progress_line_is_72_chars_long() {
                startProgressLineWithArbitraryNumberOfSteps();
                moveProgressLineNSteps(1);
                assertTextVisibleAtSystemOut().hasSize(72);
            }
        }

        public class after_second_to_last_step {
            @Test
            public void progress_bar_is_not_completely_filled() {
                //use a very large number of steps so that a single character is
                //more than a single step
                moveProgressLineToSecondToLastStep();
                assertTextVisibleAtSystemOut().endsWith("=> ]");
            }

            @Test
            public void progress_line_is_72_chars_long() {
                moveProgressLineToSecondToLastStep();
                assertTextVisibleAtSystemOut().hasSize(72);
            }

            private void moveProgressLineToSecondToLastStep() {
                startProgressLineWithNumberOfSteps(
                    NUMBER_OF_STEPS_WITH_MULTIPLE_STEPS_PER_CHARACTER);
                moveProgressLineNSteps(
                    NUMBER_OF_STEPS_WITH_MULTIPLE_STEPS_PER_CHARACTER - 1);
            }
        }

        public class after_last_step {
            @Test
            public void progress_bar_is_completely_filled() {
                //use a very large number of steps so that a single character is
                //more than a single step
                startProgressLineWithNumberOfSteps(1);
                moveProgressLineNSteps(1);
                assertTextVisibleAtSystemOut().contains("=>]");
            }

            @Test
            public void progress_line_is_terminated_with_new_line() {
                startProgressLineWithNumberOfSteps(42);
                moveProgressLineNSteps(42);
                assertTextVisibleAtSystemOut().endsWith("\n");
            }

            @Test
            public void progress_line_is_72_chars_long() {
                startProgressLineWithNumberOfSteps(ARBITRARY_NUMBER_OF_STEPS);
                moveProgressLineNSteps(ARBITRARY_NUMBER_OF_STEPS);
                assertTextVisibleAtSystemOut()
                    .hasSize(72 + 1 /* new line character */);
            }

            @Test
            public void progress_line_cannot_be_moved_forward() {
                startProgressLineWithNumberOfSteps(ARBITRARY_NUMBER_OF_STEPS);
                moveProgressLineNSteps(ARBITRARY_NUMBER_OF_STEPS);
                Throwable e = exceptionThrownBy(new Statement() {
                    @Override
                    public void evaluate() throws Throwable {
                        moveProgressLineNSteps(1);
                    }
                });
                assertThat(e).isInstanceOf(IllegalStateException.class);
            }
        }
    }

    public class progress_line_with_additional_parts {
        private final ProgressLinePart firstPart = mock(ProgressLinePart.class);
        private final ProgressLinePart secondPart = mock(ProgressLinePart.class);

        @Before
        public void useProgressLineWithCounter() {
            progressLine = new ProgressLine(firstPart, secondPart);
        }

        @Test
        public void progress_line_rendesr_the_bar_and_the_parts_separated_by_a_space() {
            useCountersWithOutpoutForStep(0, "first", "second");
            startProgressLineWithArbitraryNumberOfSteps();
            assertTextVisibleAtSystemOut().contains("] first second");
        }

        @Test
        public void progress_line_renders_parts_for_current_number_of_steps() {
            useCountersWithOutpoutForStep(2, "first", "second");
            startProgressLineWithArbitraryNumberOfSteps();
            moveProgressLineNSteps(2);
            assertTextVisibleAtSystemOut().endsWith("first second");
        }

        @Test
        public void progress_line_informs_parts_about_start() {
            startProgressLineWithNumberOfSteps(ARBITRARY_NUMBER_OF_STEPS);
            verify(firstPart).progressLineStarted(ARBITRARY_NUMBER_OF_STEPS);
            verify(secondPart).progressLineStarted(ARBITRARY_NUMBER_OF_STEPS);
        }

        @Test
        public void progress_line_is_72_chars_long() {
            useCountersWithOutpoutForStep(0, "first", "second");
            startProgressLineWithArbitraryNumberOfSteps();
            assertTextVisibleAtSystemOut().hasSize(72);
        }

        private void useCountersWithOutpoutForStep(int step,
            String outputOfFirstCounter, String outputOfSecondCounter) {
            when(firstPart.getOutputForStep(step)).thenReturn(outputOfFirstCounter);
            when(secondPart.getOutputForStep(step)).thenReturn(outputOfSecondCounter);
        }
    }

    private void startProgressLineWithNumberOfSteps(int numberOfSteps) {
        progressLine.startWithNumberOfSteps(numberOfSteps);
    }

    private void startProgressLineWithArbitraryNumberOfSteps() {
        startProgressLineWithNumberOfSteps(ARBITRARY_NUMBER_OF_STEPS);
    }

    private void moveProgressLineNSteps(int n) {
        for (int i = 0; i < n; ++i)
            progressLine.moveForward();
    }

    private AbstractCharSequenceAssert<?, String> assertTextVisibleAtSystemOut() {
        String log = systemOutRule.getLogWithNormalizedLineSeparator();
        int posOfLastCr = log.lastIndexOf("\r");
        String visibleText = log.substring(posOfLastCr + 1);
        return assertThat(visibleText);
    }
}


text:
'''
NumericUtil.py

Library of efficient vectorized implementations of
 operations common to unsupervised machine learning

* inplaceExpAndNormalizeRows
* calcRlogR
* calcRlogRdotv
* calcRlogR_allpairs
* calcRlogR_specificpairs

'''

import os
import ConfigParser
import ctypes
import numpy as np
import scipy.sparse
import timeit

import LibRlogR

def readConfigFileIntoDict(confFile, targetSecName=None):
  ''' Read contents of a config file into a dictionary

      Returns
      --------
      dict
  '''
  print confFile
  config = ConfigParser.SafeConfigParser()
  config.optionxform = str
  config.read(confFile)
  for secName in config.sections():
    if secName.count("Help") > 0:
      continue
    if targetSecName is not None:
      if secName != targetSecName:
        continue
    BigSecDict = dict(config.items(secName))
  return BigSecDict

def LoadConfig():
  global Config, cfgfilepath
  root = os.path.sep.join(os.path.abspath(__file__).split(os.path.sep)[:-2])
  cfgfilepath = os.path.join(root, 'config', 'numeric.platform-config')
  Config = readConfigFileIntoDict(cfgfilepath, 'LibraryPrefs')

########################################################### inplace exp
###########################################################
def inplaceExp(R):
  ''' Calculate exp of each entry of input matrix, done in-place.
  '''
  if Config['inplaceExpAndNormalizeRows'] == "numexpr" and hasNumexpr:
    return inplaceExp_numexpr(R)
  else:
    return inplaceExp_numpy(R)

def inplaceExp_numpy(R):
  ''' Calculate exp of each entry of input matrix, done in-place.
  '''
  np.exp(R, out=R)

def inplaceExp_numexpr(R):
  ''' Calculate exp of each entry of input matrix, done in-place.
  '''
  ne.evaluate("exp(R)", out=R)

########################################################### exp and normalize
###########################################################
def inplaceExpAndNormalizeRows(R):
  ''' Calculate exp in numerically stable way (first subtract max),
       and normalize the rows, all done in-place on the input matrix.
  '''
  if Config['inplaceExpAndNormalizeRows'] == "numexpr" and hasNumexpr:
    return inplaceExpAndNormalizeRows_numexpr(R)
  else:
    return inplaceExpAndNormalizeRows_numpy(R)

def inplaceExpAndNormalizeRows_numpy(R):
  ''' Calculate exp in numerically stable way (first subtract max),
       and normalize the rows, all done in-place on the input matrix.
  '''
  R -= np.max(R, axis=1)[:,np.newaxis]
  np.exp(R, out=R)
  R /= R.sum(axis=1)[:,np.newaxis]

def inplaceExpAndNormalizeRows_numexpr(R):
  ''' Calculate exp in numerically stable way (first subtract max),
       and normalize the rows, all done in-place on the input matrix.
  '''
  R -= np.max(R, axis=1)[:,np.newaxis]
  ne.evaluate("exp(R)", out=R)
  R /= R.sum(axis=1)[:,np.newaxis]

########################################################### standard RlogR
###########################################################
def calcRlogR(R):
  ''' Calculate sum across columns of element-wise product R*log(R),
        for NxD array R
      Uses faster numexpr library if available, but safely falls back
        to plain numpy otherwise.

      Returns
      --------
      S : K-len vector where S[k] = \sum_{n=1}^N r[n,k] log r[n,k]
  '''
  if Config['calcRlogR'] == "numexpr" and hasNumexpr:
    return calcRlogR_numexpr(R)
  else:
    return calcRlogR_numpy(R)

def calcRlogR_numpy(R):
  return np.sum(R * np.log(R), axis=0)

def calcRlogR_numexpr(R):
  return ne.evaluate("sum(R*log(R), axis=0)")

########################################################### standard RlogRdotv
###########################################################
def calcRlogRdotv(R, v):
  ''' Calculate dot product of (R * log R) and v,
        for NxD array R and vector v
      Uses faster numexpr library if available, but safely falls back
        to plain numpy otherwise.

      Returns
      --------
      S : K-len vector where S[k] = \sum_{n=1}^N v[n] (r[n,k] log r[n,k])
  '''
  if Config['calcRlogRdotv'] == "numexpr" and hasNumexpr:
    return calcRlogRdotv_numexpr(R, v)
  else:
    return calcRlogRdotv_numpy(R, v)

def calcRlogRdotv_numpy(R, v):
  return np.dot( v, R * np.log(R))

def calcRlogRdotv_numexpr(R, v):
  RlogR = ne.evaluate("R*log(R)")
  return np.dot(v, RlogR)

########################################################### all-pairs RlogR
###########################################################
def calcRlogR_allpairs(R):
  ''' Calculate column sums of element-wise product Rm*log(Rm)
        where Rm represents all pair-wise merges of columns of R.

      Uses faster numexpr library if available, but safely falls back
        to plain numpy otherwise.

      Returns
      --------
      Z : KxK matrix, where Z[a,b] = sum(Rab*log(Rab)), Rab = R[:,a] + R[:,b]
          only upper-diagonal entries of Z are non-zero,
          since we restrict potential pairs a,b to satisfy a < b
  '''
  if Config['calcRlogR'] == "numexpr" and hasNumexpr:
    return calcRlogR_allpairs_numexpr(R)
  else:
    return calcRlogR_allpairs_numpy(R)

def calcRlogR_allpairs_numpy(R):
  K = R.shape[1]
  Z = np.zeros((K,K))
  for jj in xrange(K-1):
    curR = R[:,jj][:,np.newaxis] + R[:, jj+1:]
    curR *= np.log(curR)
    Z[jj,jj+1:] = np.sum(curR, axis=0)
  return Z

def calcRlogR_allpairs_numexpr(R):
  K = R.shape[1]
  Z = np.zeros((K,K))
  for jj in xrange(K-1):
    curR = R[:,jj][:,np.newaxis] + R[:, jj+1:]
    curZ = ne.evaluate("sum(curR * log(curR), axis=0)")
    Z[jj,jj+1:] = curZ
  return Z

def calcRlogR_allpairs_c(R):
  return LibRlogR.calcRlogR_allpairs_c(R)

########################################################### all-pairs
###########################################################  RlogRdotv
def calcRlogRdotv_allpairs(R, v):
  ''' Calculate dot product dot(v, Rm * log(Rm)),
        where Rm represents all pair-wise merges of columns of R

      Uses faster numexpr library if available, but safely falls back
        to plain numpy otherwise.

      Args
      --------
      R : NxK matrix
      v : N-vector

      Returns
      --------
      Z : KxK matrix, where Z[a,b] = v dot (Rab*log(Rab)), Rab = R[:,a] + R[:,b]
          only upper-diagonal entries of Z are non-zero,
          since we restrict potential pairs a,b to satisfy a < b
  '''
  if Config['calcRlogRdotv'] == "numexpr" and hasNumexpr:
    return calcRlogRdotv_allpairs_numexpr(R, v)
  else:
    return calcRlogRdotv_allpairs_numpy(R, v)

def calcRlogRdotv_allpairs_numpy(R, v):
  K = R.shape[1]
  Z = np.zeros((K,K))
  for jj in range(K):
    curR = R[:,jj][:,np.newaxis] + R[:, jj+1:]
    curR *= np.log(curR)
    Z[jj,jj+1:] = np.dot(v,curR)
  return Z

def calcRlogRdotv_allpairs_numexpr(R, v):
  K = R.shape[1]
  Z = np.zeros((K,K))
  for jj in xrange(K-1):
    curR = R[:,jj][:,np.newaxis] + R[:, jj+1:]
    ne.evaluate("curR * log(curR)", out=curR)
    curZ = np.dot(v, curR)
    Z[jj,jj+1:] = curZ
  return Z

def calcRlogRdotv_allpairs_c(R, v):
  return LibRlogR.calcRlogRdotv_allpairs_c(R, v)

########################################################### specific-pairs
###########################################################  RlogRdotv
def calcRlogRdotv_specificpairs(R, v, mPairs):
  ''' Calculate dot product dot(v, Rm * log(Rm)),
        where Rm represents specific pair-wise merges of columns of R

      Uses faster numexpr library if available, but safely falls back
        to plain numpy otherwise.

      Args
      --------
      R : NxK matrix
      v : N-vector
      mPairs : list of possible merge pairs, where each pair is a tuple
                 [(a,b), (c,d), (e,f)]

      Returns
      --------
      Z : KxK matrix, where Z[a,b] = v dot (Rab*log(Rab)), Rab = R[:,a] + R[:,b]
          only upper-diagonal entries of Z specified by mPairs are non-zero,
          since we restrict potential pairs a,b to satisfy a < b
  '''
  if Config['calcRlogRdotv'] == "numexpr" and hasNumexpr:
    return calcRlogRdotv_specificpairs_numexpr(R, v, mPairs)
  else:
    return calcRlogRdotv_specificpairs_numpy(R, v, mPairs)

def calcRlogRdotv_specificpairs_numpy(R, v, mPairs):
  K = R.shape[1]
  ElogqZMat = np.zeros((K, K))
  if K == 1:
    return ElogqZMat
  for (kA, kB) in mPairs:
    curWV = R[:,kA] + R[:, kB]
    curWV *= np.log(curWV)
    ElogqZMat[kA,kB] = np.dot(v, curWV)
  return ElogqZMat

def calcRlogRdotv_specificpairs_numexpr(R, v, mPairs):
  K = R.shape[1]
  ElogqZMat = np.zeros((K, K))
  if K == 1:
    return ElogqZMat
  for (kA, kB) in mPairs:
    curR = R[:,kA] + R[:, kB]
    ne.evaluate("curR * log(curR)", out=curR)
    ElogqZMat[kA,kB] = np.dot(v, curR)
  return ElogqZMat

def calcRlogRdotv_specificpairs_numpyvec(R, v, mPairs):
  ''' Attempt to speed up by handling all partners of comp kA at once.
      Surprisingly seems to be much slower. Forget it.
  '''
  from collections import defaultdict
  PartnerDict = defaultdict(lambda: list())
  for kA, kB in mPairs:
    PartnerDict[kA].append(kB)
  K = R.shape[1]
  ElogqZMat = np.zeros((K, K))
  if K == 1:
    return ElogqZMat
  for kA in PartnerDict:
    curWV = R[:,kA][:,np.newaxis] + R[:, PartnerDict[kA]]
    curWV *= np.log(curWV)
    ElogqZMat[kA,PartnerDict[kA]] = np.dot(v, curWV)
  return ElogqZMat

def calcRlogRdotv_specificpairs_c(R, v, mPairs):
  return LibRlogR.calcRlogRdotv_specificpairs_c(R, v, mPairs)

########################################################### AutoConfigure
###########################################################
def autoconfigure():
  ''' Perform timing experiments on current hardware to assess which
       of various implementations is the fastest for each key routine
  '''
  config = ConfigParser.SafeConfigParser()
  config.optionxform = str
  config.read(cfgfilepath)
  methodNames = ['inplaceExpAndNormalizeRows', 'calcRlogR', 'calcRlogRdotv']
  for mName in methodNames:
    if mName == 'inplaceExpAndNormalizeRows':
      expectedGainFactor = runTimingExperiment_inplaceExpAndNormalizeRows()
    elif mName == 'calcRlogR':
      expectedGainFactor = runTimingExperiment_calcRlogR()
    elif mName == 'calcRlogRdotv':
      expectedGainFactor = runTimingExperiment_calcRlogRdotv()
    print mName,
    if expectedGainFactor > 1.05:
      config.set('LibraryPrefs', mName, 'numexpr')
      print "numexpr preferred: %.2f X faster" % (expectedGainFactor)
    else:
      config.set('LibraryPrefs', mName, 'numpy')
      print "numpy preferred: %.2f X faster" % (expectedGainFactor)
    with open(cfgfilepath,'w') as f:
      config.write(f)
  LoadConfig()

def runTimingExperiment_inplaceExpAndNormalizeRows(N=2e5, D=100, repeat=3):
  if not hasNumexpr:
    return 0
  setup = "import numpy as np; import numexpr as ne;"
  setup += "from bnpy.util import NumericUtil as N;"
  setup += "R = np.random.rand(%d, %d)" % (N, D)
  elapsedTimes_np = timeit.repeat("N.inplaceExpAndNormalizeRows_numpy(R)",
                    setup=setup, number=1, repeat=repeat)
  elapsedTimes_ne = timeit.repeat("N.inplaceExpAndNormalizeRows_numexpr(R)",
                    setup=setup, number=1, repeat=repeat)
  meanTime_np = np.mean(elapsedTimes_np)
  meanTime_ne = np.mean(elapsedTimes_ne)
  expectedGainFactor = meanTime_np / meanTime_ne
  return expectedGainFactor

def runTimingExperiment_calcRlogR(N=2e5, D=100, repeat=3):
  if not hasNumexpr:
    return 0
  setup = "import numpy as np; import numexpr as ne;"
  setup += "import bnpy.util.NumericUtil as N;"
  setup += "R = np.random.rand(%d, %d)" % (N, D)
  elapsedTimes_np = timeit.repeat("N.calcRlogR_numpy(R)",
                    setup=setup, number=1, repeat=repeat)
  elapsedTimes_ne = timeit.repeat("N.calcRlogR_numexpr(R)",
                    setup=setup, number=1, repeat=repeat)
  meanTime_np = np.mean(elapsedTimes_np)
  meanTime_ne = np.mean(elapsedTimes_ne)
  expectedGainFactor = meanTime_np / meanTime_ne
  return expectedGainFactor

def runTimingExperiment_calcRlogRdotv(N=2e5, D=100, repeat=3):
  if not hasNumexpr:
    return 0
  setup = "import numpy as np; import numexpr as ne;"
  setup += "import bnpy.util.NumericUtil as N;"
  setup += "R = np.random.rand(%d, %d);" % (N, D)
  setup += "v = np.random.rand(%d)" % (N)
  elapsedTimes_np = timeit.repeat("N.calcRlogRdotv_numpy(R, v)",
                    setup=setup, number=1, repeat=repeat)
  elapsedTimes_ne = timeit.repeat("N.calcRlogRdotv_numexpr(R, v)",
                    setup=setup, number=1, repeat=repeat)
  meanTime_np = np.mean(elapsedTimes_np)
  meanTime_ne = np.mean(elapsedTimes_ne)
  expectedGainFactor = meanTime_np / meanTime_ne
  return expectedGainFactor

########################################################### MAIN
###########################################################

hasNumexpr = True
try:
  import numexpr as ne
  if 'OMP_NUM_THREADS' in os.environ:
    ne.set_num_threads(os.environ['OMP_NUM_THREADS'])
except:
  hasNumexpr = False

LoadConfig()

redpajama_set_name: RedPajamaGithub


text:
// SimulatableAPI
// File: _StorageSink.cs
//
// Copyright 2011, Arlo Belshee. All rights reserved. See LICENSE.txt for usage.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JetBrains.Annotations;

namespace Simulated._Fs
{
	internal abstract class _StorageSink
	{
		public virtual bool IsTrackingChanges
		{
			get { return false; }
		}

		[NotNull]
		public virtual _StorageSink Next
		{
			get { throw new NotImplementedException(); }
		}

		[NotNull]
		public virtual Task CommitAll()
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task RevertAll()
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task<bool> DirExists([NotNull] FsPath path)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task<bool> FileExists([NotNull] FsPath path)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task<string> TextContents([NotNull] FsPath path)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task<byte[]> RawContents([NotNull] FsPath path)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task CreateDir([NotNull] FsPath path)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task Overwrite([NotNull] FsPath path, [NotNull] string newContents)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task Overwrite([NotNull] FsPath path, [NotNull] byte[] newContents)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task DeleteDir([NotNull] FsPath path)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task DeleteFile([NotNull] FsPath path)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task MoveFile([NotNull] FsPath src, [NotNull] FsPath dest)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task MoveDir([NotNull] FsPath src, [NotNull] FsPath dest)
		{
			throw new NotImplementedException();
		}

		[NotNull]
		public virtual Task<IEnumerable<FsPath>> FindFiles([NotNull] FsPath path, [NotNull] string searchPattern)
		{
			throw new NotImplementedException();
		}

		[NotNull] internal static readonly Task CompletedTask = true.AsImmediateTask();
	}
}


text:
module.exports = {
  options: {
    map: true, // inline sourcemaps

    // or
    map: {
        inline: false, // save all sourcemaps as separate files...
        annotation: 'dist/stylesheets/maps/' // ...to the specified directory
    },

    processors: [
      require('pixrem')(), // add fallbacks for rem units
      require('autoprefixer')({browsers: 'last 2 versions'}), // add vendor prefixes
      require('cssnano')() // minify the result
    ]
  },
  dist: {
    src: 'dist/stylesheets/*.css'
  }
};


text:
class DXCore
{
public:
	DXCore(
		HINSTANCE hInstance,		// The application's handle
		char* titleBarText,			// Text for the window's title bar
		bool debugTitleBarStats);	// Show extra stats (fps) in title bar?
	~DXCore();

	// Static requirements for OS-level message processing
	static DXCore* DXCoreInstance;
	static LRESULT CALLBACK WindowProc(
		HWND hWnd,		// Window handle
		UINT uMsg,		// Message
		WPARAM wParam,	// Message's first parameter
		LPARAM lParam	// Message's second parameter
		);

	// Internal method for message handling
	LRESULT ProcessMessage(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);

	// Initialization and game-loop related methods
	HRESULT InitWindow();
	HRESULT InitDirectX();
	HRESULT Run();
	void Quit();
	virtual void OnResize();

	// Pure virtual methods for setup and game functionality
	virtual void Init()										= 0;
	virtual void Update(float deltaTime, float totalTime)	= 0;
	//virtual void Draw(float deltaTime, float totalTime)		= 0;

	// Convenience methods for handling mouse input, since we
	// can easily grab mouse input from OS-level messages
	virtual void OnMouseDown (WPARAM buttonState, int x, int y) { }
	virtual void OnMouseUp	 (WPARAM buttonState, int x, int y) { }
	virtual void OnMouseMove (WPARAM buttonState, int x, int y) { }
	virtual void OnMouseWheel(float wheelDelta,   int x, int y) { }
	unsigned int GetWidth();
	unsigned int GetHeight();

protected:
	HINSTANCE	hInstance;		// The handle to the application
	HWND		hWnd;			// The handle to the window itself
	std::string titleBarText;	// Custom text in window's title bar
	bool		titleBarStats;	// Show extra stats in title bar?

	// Size of the window's client area
	unsigned int width;
	unsigned int height;

	// DirectX related objects and variables
	D3D_FEATURE_LEVEL		dxFeatureLevel;
	IDXGISwapChain*			m_swapChain;
	ID3D11Device*			m_device;
	ID3D11DeviceContext*	m_context;

	ID3D11RenderTargetView* m_backBufferRTV;
	ID3D11DepthStencilView* m_depthStencilView;

	// Helper function for allocating a console window
	void CreateConsoleWindow(int bufferLines, int bufferColumns, int windowLines, int windowColumns);

	void virtual UpdateTitleBarForGame(std::string in) = 0;

private:
	// Timing related data
	double perfCounterSeconds;
	float totalTime;
	float deltaTime;
	__int64 startTime;
	__int64 currentTime;
	__int64 previousTime;

	// FPS calculation
	int fpsFrameCount;
	float fpsTimeElapsed;

	void UpdateTimer();			// Updates the timer for this frame
	void UpdateTitleBarStats();	// Puts debug info in the title bar
};


text:
from .async_client import AutoSuggestionServiceAsyncClient
from .client import AutoSuggestionServiceClient

__all__ = (
    "AutoSuggestionServiceClient",
    "AutoSuggestionServiceAsyncClient",
)


text:
//
//  RISCVCtx.h
//  RISCV
//
//  Created by Makigumo on 2016/12/04.
//  Copyright © 2016年 Makigumo. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <Hopper/Hopper.h>
#import <Hopper/DisasmStruct.h>
#import "RISCVCPU.h"

@class RISCVCPU;

@interface RISCVCtx : NSObject <CPUContext>

- (instancetype)initWithCPU:(RISCVCPU *)cpu andFile:(NSObject <HPDisassembledFile> *)file;

@end

extern NSString *getCsrName(uint64_t csr);

#define OPCODE_MASK     0x0000007f
#define DEST_MASK       0x00000f80
#define SRC1_MASK       0x000F8000
#define SRC2_MASK       0x01F00000
#define FUNCT3_MASK     0x00007000
#define FUNCT5_MASK     0xf8000000
#define FUNCT7_MASK     0xfe000000
#define FUNCT6_MASK     0xfc000000
#define IMM_MASK        0xfffff000
#define SHAMT4_MASK     0x01F00000
#define SHAMT5_MASK     0x03F00000
#define SHAMT6_MASK     0x07F00000
#define PRED_MASK       0x0f000000
#define SUCC_MASK       0x00f00000
#define FMT_MASK        0x06000000
#define ROUNDING_MODE_MASK          0x00007000

#define OPCODE_OPIMM    (uint8_t) 0b0010011
#define OPCODE_OPIMM32  OPCODE_OPIMM
#define OPCODE_OPIMM64  (uint8_t) 0b0011011
#define OPCODE_OPIMM128 (uint8_t) 0b1011011
#define OPCODE_LOAD     (uint8_t) 0b0000011
#define OPCODE_STORE    (uint8_t) 0b0100011
#define OPCODE_OP       (uint8_t) 0b0110011
#define OPCODE_OP32     (uint8_t) 0b0111011
#define OPCODE_OP128    (uint8_t) 0b1111011
#define OPCODE_AUIPC    (uint8_t) 0b0010111
#define OPCODE_LUI      (uint8_t) 0b0110111
#define OPCODE_BRANCH   (uint8_t) 0b1100011
#define OPCODE_JALR     (uint8_t) 0b1100111
#define OPCODE_JAL      (uint8_t) 0b1101111
#define OPCODE_MISC_MEM (uint8_t) 0b0001111
#define OPCODE_SYSTEM   (uint8_t) 0b1110011
#define OPCODE_AMO      (uint8_t) 0b0101111
#define OPCODE_LOADFP   (uint8_t) 0b0000111
#define OPCODE_STOREFP  (uint8_t) 0b0100111
#define OPCODE_FMADD    (uint8_t) 0b1000011
#define OPCODE_FMSUB    (uint8_t) 0b1000111
#define OPCODE_FNMSUB   (uint8_t) 0b1001011
#define OPCODE_FNMADD   (uint8_t) 0b1001111
#define OPCODE_FP       (uint8_t) 0b1010011

#define DISASM_OPERAND_ROUNDING_MODE    0x0001000000000000llu
#define DISASM_OPERAND_FENCE    0x0002000000000000llu

enum INSN_TYPE {
    ITYPE,
    RTYPE,
    UTYPE,
    STYPE,
    SBTYPE,
    UJTYPE
};

struct itype_insn {
    uint8_t opcode; /* bits 6..0 */
    uint8_t reg_dest; /* bits 11..7 */
    uint8_t funct3; /* bits 14..12 */
    uint8_t reg_src1; /* bits 19..15 */
    uint16_t imm; /* bits 31..20 */
};

struct rtype_insn {
    uint8_t opcode; /* bits 6..0 */
    uint8_t reg_dest; /* bits 11..7 */
    uint8_t funct3; /* bits 14..12 */
    uint8_t reg_src1; /* bits 19..15 */
    uint8_t reg_src2; /* bits 31..20 */
    uint8_t funct7; /* bits 31..25 */
};

struct stype_insn {
    uint8_t opcode; /* bits 6..0 */
    uint8_t funct3; /* bits 14..12 */
    uint8_t reg_src1; /* bits 19..15 */
    uint8_t reg_src2; /* bits 31..20 */
    uint16_t imm; /* bits 31..25 11..7 */
};

struct utype_insn {
    uint8_t opcode; /* bits 6..0 */
    uint8_t reg_dest; /* bits 11..7 */
    uint16_t imm; /* bits 31..12 */
};

struct insn {
    uint8_t opcode;
    enum INSN_TYPE type;
    union {
        struct itype_insn itype;
        struct rtype_insn rtype;
        struct stype_insn stype;
        struct utype_insn utype;
    };
};

enum FpuFormat {
    FPU_FMT_SINGLE = 0b00,
    FPU_FMT_DOUBLE = 0b01,
    FPU_FMT_INVALID = 0b10,
    FPU_FMT_QUAD = 0b11,
};

enum FpuRoundingMode {
    FPU_RM_RNE = 0b000,
    FPU_RM_RTZ = 0b001,
    FPU_RM_RDN = 0b010,
    FPU_RM_RUP = 0b011,
    FPU_RM_RMM = 0b100,
    FPU_RM_DYNAMIC = 0b111,
};

// return the 7-bit opcode, bits 6..0
static inline uint8_t getOpcode(uint32_t insn) {
    return (uint8_t) (((uint8_t) insn) & OPCODE_MASK);
}

// the J-immediate encodes a signed offset in multiples of 2 bytes
static inline int32_t getUJtypeImmediate(uint32_t insn) {
    return ((int32_t) (insn & 0x7FE00000) >> 20 /* bits 30..21 */ |
            (int32_t) (insn & 0x00100000) >> 9  /* bit 20 */ |
            (int32_t) (insn & 0x000ff000)       /* bits 19..12 */ |
            (int32_t) (insn & 0x80000000) >> 11 /* bit 31 */);
}

// the 12-bit B-immediate encodes signed offsets in multiples of 2
static inline int32_t getBtypeImmediate(uint32_t insn) {
    return (((int32_t) (insn & 0x00000080) << 4  /* bit 7 -> 11 */ |
            (int32_t) (insn & 0x7E000000) >> 20 /* bits 30..25 -> 10..5 */ |
            (int32_t) (insn & 0x00000f00) >> 7  /* bit 11..8 -> 4..1 */ |
            (int32_t) (-((insn >> 31) & 1)) << 12 /* bits 31 -> 12 */)
    ) & ~1;
}

// returns 12 bit signed I-immediate with LSB cleared
static inline int32_t getItypeImmediateLSBcleared(uint32_t insn) {
    return ((int32_t) (insn & 0xfff00000) >> 20) & ~1 /* bits 31..20 */;
}

static inline int32_t getItypeImmediate(uint32_t insn) {
    return ((int32_t) (insn & 0xfff00000) >> 20) /* bits 31..20 */;
}

static inline int32_t getStypeImmediate(uint32_t insn) {
    return ((int32_t) (insn & 0x00000f80) >> 7) /* bits 11..7 -> 4..0 */ |
            ((int32_t) (insn & 0xfe000000) >> 20) /* bits 31..25 -> 11..5 */;
}

static inline int32_t getUtypeImmediate(uint32_t insn) {
    return ((insn & 0xfffff000) >> 12) /* bits 31..12 */;
}

static inline uint32_t getCsr(uint32_t insn) {
    return ((insn & 0xfff00000) >> 20) /* bits 31..20 */;
}

// get funct3
static inline uint8_t getFunct3(uint32_t insncode) {
    return (uint8_t) ((insncode & FUNCT3_MASK) >> 12);
}

// get funct5
static inline uint8_t getFunct5(uint32_t insncode) {
    return (uint8_t) ((insncode & FUNCT5_MASK) >> 27);
}

// get funct7
static inline uint8_t getFunct7(uint32_t insncode) {
    return (uint8_t) ((insncode & FUNCT7_MASK) >> 25);
}

// get funct7 64 bit extension
static inline uint8_t getFunct6(uint32_t insncode) {
    return (uint8_t) ((insncode & FUNCT6_MASK) >> 26);
}

// get source register 2
static inline uint8_t getRS2(uint32_t insncode) {
    return (uint8_t) ((insncode & SRC2_MASK) >> 20);
}

// get source register 3
static inline uint8_t getRS3(uint32_t insncode) {
    return (uint8_t) (insncode >> 27);
}

// get source register 1
static inline uint8_t getRS1(uint32_t insncode) {
    return (uint8_t) ((insncode & SRC1_MASK) >> 15);
}

// get destination register
static inline uint8_t getRD(uint32_t insncode) {
    return (uint8_t) ((insncode & DEST_MASK) >> 7);
}

// get shift amount
static inline uint8_t getShamt4(uint32_t insncode) {
    return (uint8_t) (((uint32_t) (insncode & SHAMT4_MASK)) >> 20);
}

// get shift amount 64 bit extension
static inline uint8_t getShamt5(uint32_t insncode) {
    return (uint8_t) (((uint32_t) (insncode & SHAMT5_MASK)) >> 20);
}

// get shift amount 64 bit extension
static inline uint8_t getShamt6(uint32_t insncode) {
    return (uint8_t) (((uint32_t) (insncode & SHAMT6_MASK)) >> 20);
}

// get predecessor for fence instruction bits 27..24
static inline uint8_t getPredecessor(uint32_t insncode) {
    return (uint8_t) (((uint32_t) (insncode & PRED_MASK)) >> 24);
}

// get predecessor for fence instruction bits 23..20
static inline uint8_t getSuccessor(uint32_t insncode) {
    return (uint8_t) (((uint32_t) (insncode & SUCC_MASK)) >> 20);
}

// get rounding mode for fp instruction bits 14..12
static inline enum FpuRoundingMode getRoundingMode(uint32_t insncode) {
    return (enum FpuRoundingMode) ((insncode >> 12) & 0b111);
}

// get format field, bits 26..25
static inline enum FpuFormat getFmt(uint32_t insncode) {
    return (enum FpuFormat) ((insncode >> 25) & 0b11);
}

static inline NSString *getIorw(uint8_t insncode) {
    NSString *res = @"";
    if (insncode & 0b1000) res = [res stringByAppendingString:@"i"];
    if (insncode & 0b0100) res = [res stringByAppendingString:@"o"];
    if (insncode & 0b0010) res = [res stringByAppendingString:@"r"];
    if (insncode & 0b0001) res = [res stringByAppendingString:@"w"];
    return res;
}

static inline void populateOperandReg(DisasmOperand *op, uint8_t reg, DisasmAccessMode accessMode) {
    op->type = DISASM_OPERAND_REGISTER_TYPE;
    op->type |= getRegMask(reg);
    op->accessMode = accessMode;
}

static inline void populateOperandFpuReg(DisasmOperand *op, uint8_t reg, DisasmAccessMode accessMode) {
    op->type = DISASM_OPERAND_REGISTER_TYPE;
    op->type |= getFpuRegMask(reg);
    op->accessMode = accessMode;
}

static inline void populateOP(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    populateOperandReg(&disasm->operand[1], getRS1(insn), DISASM_ACCESS_READ);
    populateOperandReg(&disasm->operand[2], getRS2(insn), DISASM_ACCESS_READ);
}

static inline void populateOPIMM(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    populateOperandReg(&disasm->operand[1], getRS1(insn), DISASM_ACCESS_READ);
    disasm->operand[2].type = DISASM_OPERAND_CONSTANT_TYPE;
    disasm->operand[2].immediateValue = getItypeImmediate(insn);
    disasm->operand[2].accessMode = DISASM_ACCESS_READ;
}

static inline void populateOPIMMShift(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    populateOperandReg(&disasm->operand[1], getRS1(insn), DISASM_ACCESS_READ);
    disasm->operand[2].type = DISASM_OPERAND_CONSTANT_TYPE;
    disasm->operand[2].immediateValue = getShamt4(insn);
    disasm->operand[2].size = 4;
    disasm->operand[2].accessMode = DISASM_ACCESS_READ;
}

static inline void populateOPIMMShift64(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    populateOperandReg(&disasm->operand[1], getRS1(insn), DISASM_ACCESS_READ);
    disasm->operand[2].type = DISASM_OPERAND_CONSTANT_TYPE;
    disasm->operand[2].immediateValue = getShamt5(insn);
    disasm->operand[2].size = 5;
    disasm->operand[2].accessMode = DISASM_ACCESS_READ;
}

static inline void populateOPIMMShift128(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    populateOperandReg(&disasm->operand[1], getRS1(insn), DISASM_ACCESS_READ);
    disasm->operand[2].type = DISASM_OPERAND_CONSTANT_TYPE;
    disasm->operand[2].immediateValue = getShamt5(insn);
    disasm->operand[2].size = 6;
    disasm->operand[2].accessMode = DISASM_ACCESS_READ;
}

static inline void populateLOAD(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    disasm->operand[1].type = DISASM_OPERAND_MEMORY_TYPE;
    disasm->operand[1].type |= getRegMask(getRS1(insn));
    disasm->operand[1].memory.baseRegistersMask = getRegMask(getRS1(insn));
    disasm->operand[1].memory.displacement = getItypeImmediate(insn);
    disasm->operand[1].memory.scale = 1;
    disasm->operand[1].accessMode = DISASM_ACCESS_READ;
}

static inline void populateSTORE(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    disasm->operand[1].type = DISASM_OPERAND_MEMORY_TYPE;
    disasm->operand[1].type |= getRegMask(getRS1(insn));
    disasm->operand[1].memory.baseRegistersMask = getRegMask(getRS1(insn));
    disasm->operand[1].memory.displacement = getStypeImmediate(insn);
    disasm->operand[1].memory.scale = 1;
    disasm->operand[1].accessMode = DISASM_ACCESS_READ;
}

static inline void populateLR(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    disasm->operand[1].type = DISASM_OPERAND_MEMORY_TYPE;
    disasm->operand[1].type |= getRegMask(getRS1(insn));
    disasm->operand[1].memory.baseRegistersMask = getRegMask(getRS1(insn));
    disasm->operand[1].memory.displacement = 0;
    disasm->operand[1].accessMode = DISASM_ACCESS_READ;
}

static inline void populateAMO(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    populateOperandReg(&disasm->operand[1], getRS2(insn), DISASM_ACCESS_READ);
    disasm->operand[2].type = DISASM_OPERAND_MEMORY_TYPE;
    disasm->operand[2].type |= getRegMask(getRS1(insn));
    disasm->operand[2].memory.baseRegistersMask = getRegMask(getRS1(insn));
    disasm->operand[2].memory.displacement = 0;
    disasm->operand[2].accessMode = DISASM_ACCESS_READ;
}

static inline void populateFP_2reg(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    disasm->operand[1].type = DISASM_OPERAND_REGISTER_TYPE;
    disasm->operand[1].type |= getFpuRegMask(getRS1(insn));
    disasm->operand[1].accessMode = DISASM_ACCESS_READ;
}

static inline void populateFp_gp_fp(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    populateOperandReg(&disasm->operand[0], getRD(insn), DISASM_ACCESS_WRITE);
    disasm->operand[1].type = DISASM_OPERAND_REGISTER_TYPE;
    disasm->operand[1].type |= getFpuRegMask(getRS1(insn));
    disasm->operand[1].accessMode = DISASM_ACCESS_READ;
}

static inline void populateFp_gp_fp_with_rm(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    populateFp_gp_fp(disasm, insn, mnemonic);
    if (getRoundingMode(insn) < 0b111) {
        disasm->operand[2].type = DISASM_OPERAND_CONSTANT_TYPE | DISASM_OPERAND_ROUNDING_MODE;
        disasm->operand[2].immediateValue = getRoundingMode(insn);
        disasm->operand[2].accessMode = DISASM_ACCESS_READ;
    }
}

static inline void populateFp_fp_gp(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    strcpy(disasm->instruction.mnemonic, mnemonic);
    disasm->operand[0].type = DISASM_OPERAND_REGISTER_TYPE;
    disasm->operand[0].type |= getFpuRegMask(getRD(insn));
    disasm->operand[0].accessMode = DISASM_ACCESS_WRITE;
    populateOperandReg(&disasm->operand[1], getRS1(insn), DISASM_ACCESS_READ);
}

static inline void populateFpRoundingMode(DisasmOperand *op, uint32_t insn) {
    uint8_t roundingMode = getRoundingMode(insn);
    if (roundingMode < 0b111 /* dynamic */) {
        op->type = DISASM_OPERAND_CONSTANT_TYPE | DISASM_OPERAND_ROUNDING_MODE;
        op->immediateValue = roundingMode;
        op->accessMode = DISASM_ACCESS_READ;
    }
}

static inline void populateFp_fp_gp_with_rm(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    populateFp_fp_gp(disasm, insn, mnemonic);
    populateFpRoundingMode(&disasm->operand[2], insn);
}

static inline void populateFp_3reg(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    populateFP_2reg(disasm, insn, mnemonic);
    disasm->operand[2].type = DISASM_OPERAND_REGISTER_TYPE;
    disasm->operand[2].type |= getFpuRegMask(getRS2(insn));
    disasm->operand[2].accessMode = DISASM_ACCESS_READ;
}

static inline void populateFp_3reg_with_rm(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    populateFp_3reg(disasm, insn, mnemonic);
    populateFpRoundingMode(&disasm->operand[3], insn);
}

static inline void populateFp_R4(DisasmStruct *disasm, uint32_t insn, const char *mnemonic) {
    populateFp_3reg(disasm, insn, mnemonic);
    disasm->operand[3].type = DISASM_OPERAND_REGISTER_TYPE;
    disasm->operand[3].type |= getFpuRegMask(getRS3(insn));
    disasm->operand[3].accessMode = DISASM_ACCESS_READ;
    populateFpRoundingMode(&disasm->operand[4], insn);
}

static inline NSString *getRoundingModeName(enum FpuRoundingMode rm) {
    switch (rm) {
        case FPU_RM_RNE:
            return @"rne";
        case FPU_RM_RTZ:
            return @"rtz";
        case FPU_RM_RDN:
            return @"rdn";
        case FPU_RM_RUP:
            return @"rup";
        case FPU_RM_RMM:
            return @"rmm";
        case FPU_RM_DYNAMIC:
            return NULL;
            //return @"dyn";

        default:
            return @"invalid/reserved";
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Web.UI.WebControls
{
    using Telerik.Charting;
    using Telerik.Charting.Styles;

    public class DnnChartSeries : ChartSeries
    {
        public DnnChartSeries()
        {
        }

        public DnnChartSeries(string name)
            : base(name)
        {
        }

        public DnnChartSeries(string name, ChartSeriesType type)
            : base(name, type)
        {
        }

        public DnnChartSeries(string name, ChartSeriesType type, ChartSeriesCollection parent)
            : base(name, type, parent)
        {
        }

        public DnnChartSeries(string seriesName, ChartSeriesType chartSeriesType, ChartSeriesCollection parent, ChartYAxisType yAxisType, StyleSeries style)
            : base(seriesName, chartSeriesType, parent, yAxisType, style)
        {
        }

        public DnnChartSeries(string seriesName, ChartSeriesType chartSeriesType, ChartSeriesCollection parent, ChartYAxisType yAxisType, StyleSeries style, string dataYColumn, string dataXColumn,
                              string dataYColumn2, string dataXColumn2, string dataYColumn3, string dataYColumn4, string dataLabelsColumn)
            : base(seriesName, chartSeriesType, parent, yAxisType, style, dataYColumn, dataXColumn, dataYColumn2, dataXColumn2, dataYColumn3, dataYColumn4, dataLabelsColumn)
        {
        }

        public DnnChartSeries(ChartSeriesCollection parent)
            : base(parent)
        {
        }
    }
}


text:
require File.dirname(__FILE__) + "/../spec_helper"

describe FixtureReplacement do
  it "should have the method attributes_for" do
    FixtureReplacement.should respond_to(:attributes_for)
  end
end

describe FixtureReplacement, "attributes_for" do
  before :each do
    @fixture_attribute = mock "FixtureAttribute"
    @fixture_attribute.stub!(:new)

    @attributes_proc = lambda {}
    Kernel.stub!(:lambda).and_return @attributes_proc
  end

  it "should take a fixture name" do
    FixtureReplacement.attributes_for(:foo) {}
  end

  it "should take a fixture name along with a hash of attributes" do
    FixtureReplacement.attributes_for(:foo, :bar => :baz, :baz => :zed) {}
  end

  it "should create a new FixtureAttribute with the name given" do
    @fixture_attribute.should_receive(:new).with(:foo, {:class => nil, :from => nil, :attributes => @attributes_proc})
    FixtureReplacement.attributes_for(:foo, {}, @fixture_attribute, &@attributes_proc)
  end

  it "should create a new FixtureAttribute with the name given and class given" do
    @fixture_attribute.should_receive(:new).with(:foo, {:class => Object, :from => nil, :attributes => @attributes_proc})
    FixtureReplacement.attributes_for(:foo, {:class => Object}, @fixture_attribute, &@attributes_proc)
  end

  it "should create a new FixtureAttribute with the name given and the attributes from" do
    @fixture_attribute.should_receive(:new).with(:foo, {:class => nil, :from => :bar, :attributes => @attributes_proc})
    FixtureReplacement.attributes_for(:foo, {:from => :bar}, @fixture_attribute, &@attributes_proc)
  end

  it "should create a new FixtureAttribute with the name and block given" do
    @fixture_attribute.should_receive(:new).with(:foo, {:class => nil, :from => nil, :attributes => @attributes_proc})
    FixtureReplacement.attributes_for(:foo, {}, @fixture_attribute, &@attributes_proc)
  end
end

describe "FixtureReplacement.attributes_for" do
  it "should yield an OpenStruct" do
    FixtureReplacement.attributes_for :user do |u|
      u.should be_a_kind_of(OpenStruct)
    end
  end

  it "should not raise an error if no block is given" do
    lambda {
      FixtureReplacement.attributes_for :scott, :from => :user
    }.should_not raise_error
  end

  it "should create a new Attribute with the class, attributes_from, and the attributes as a lambda" do
    @proc = lambda { |os| }
    Kernel.stub!(:lambda).and_return @proc
    FixtureReplacementController::AttributeCollection.stub!(:new)
    FixtureReplacementController::AttributeCollection.should_receive(:new).with(:scott, {
      :class => User,
      :from => :user,
      :attributes => @proc
    })

    FixtureReplacement.attributes_for(:scott, :from => :user, :class => User, &@proc)
  end
end


text:
/* (1) Create a database, say, named "CustomMembershipWithRoles"
 * (2) Run this sql script to create the tables required for this project
 * (3) Change the connection string "UsersContext" in the "Web.config" file, if required.
 *
 */

/*  Users table */
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Users](
	[UserId] [int] IDENTITY(1,1) NOT NULL,
	[CompanyId] [int] NOT NULL,
	[RoleId] [int] NOT NULL,
	[UserName] [nvarchar](50) NOT NULL,
	[Password] [nvarchar](50) NOT NULL,
	[FirstName] [nvarchar](50) NULL,
	[LastName] [nvarchar](50) NULL,
	[LastLogin] [datetime] NULL,
	[CreatedBy] [nvarchar](50) NULL,
	[EmailAddress] [nvarchar](50) NULL,
	[PhoneNumber] [nchar](10) NULL,
 CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
	[UserId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[Users]  WITH CHECK ADD  CONSTRAINT [FK_Users_Companies] FOREIGN KEY([CompanyId])
REFERENCES [dbo].[Companies] ([CompanyId])
GO

ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_Users_Companies]
GO

ALTER TABLE [dbo].[Users]  WITH CHECK ADD  CONSTRAINT [FK_Users_Roles] FOREIGN KEY([RoleId])
REFERENCES [dbo].[Roles] ([RoleId])
GO

ALTER TABLE [dbo].[Users] CHECK CONSTRAINT [FK_Users_Roles]
GO

/* Insert default user - password: "administrator" */
INSERT INTO dbo.Users VALUES('administrator','200ceb26807d6bf99fd6f4f0d1ca54d4','test@mail.com');

/* Roles table */
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Roles](
	[RoleId] [int] IDENTITY(0,1) NOT NULL,
	[RoleName] [nvarchar](50) NULL,
	[RoleDescription] [nvarchar](50) NULL,
 CONSTRAINT [PK_Roles] PRIMARY KEY CLUSTERED
(
	[RoleId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

/* Roles table entries */
INSERT INTO dbo.Roles VALUES(0,'SuperAdmin','Vendita Admin');
INSERT INTO dbo.Roles VALUES(1, 'Admin', 'Company Admin');
INSERT INTO dbo.Roles VALUES(2, 'Author', 'Companuy User');

/* Company table */
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Companies](
	[CompanyId] [int] IDENTITY(1,1) NOT NULL,
	[CompanyName] [nvarchar](50) NULL,
	[CompanyAddress] [nvarchar](50) NULL,
	[CompanyCity] [nvarchar](50) NULL,
	[CompanyState] [nvarchar](50) NULL,
	[CompanyZip] [nvarchar](50) NULL,
 CONSTRAINT [PK_Companies] PRIMARY KEY CLUSTERED
(
	[CompanyId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


text:
<!doctype html>

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300,400,600' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/icon?family=Material+Icons' rel='stylesheet'>

Kickstartr v2

{{m.message}}


text:
using DC = Mono.Debugging.Client;
using Mono.Debugging.Evaluation;

namespace Mono.Debugging.Win32
{
	public class VariableReference: ValueReference
	{
		readonly CorValRef var;
		readonly DC.ObjectValueFlags flags;
		readonly string name;

		public VariableReference (EvaluationContext ctx, CorValRef var, string name, DC.ObjectValueFlags flags)
			: base (ctx)
		{
			this.flags = flags;
			this.var = var;
			this.name = name;
		}

		public override object Value {
			get {
				return var;
			}
			set {
				var.SetValue (Context, (CorValRef) value);
			}
		}

		public override string Name {
			get {
				return name;
			}
		}

		public override object Type {
			get {
				return var.Val.ExactType;
			}
		}

		public override DC.ObjectValueFlags Flags {
			get {
				return flags;
			}
		}
	}
}


text:
#include <src/Engine/Platform/sdl2/SDL2Timer.h>

#include <SDL.h>

namespace OSRE {
namespace Platform {

SDL2Timer::SDL2Timer()
: AbstractTimer( "platform/sdl2timer" )
, m_lasttick( 0 ){
    // empty
}

SDL2Timer::~SDL2Timer( ) {
    // empty
}

i64 SDL2Timer::getMilliCurrentSeconds( ) {
    i64 ticks =  static_cast<i64>( SDL_GetTicks() / 1000U );
    return ticks;
}

i64 SDL2Timer::getTimeDiff( ) {
    i64 currentTime = getMilliCurrentSeconds();
    if ( m_lasttick == 0 ) {
        m_lasttick = currentTime;
        return 0;
    } else {
        i64 diff( currentTime - m_lasttick );
        if( diff > 1000 ) {
            diff = AbstractTimer::getRequestedTimeStep();
        }
        m_lasttick = currentTime;

        return diff;
    }
}

} // Namespace Platform
} // Namespace OSRE


text:
package com.sevenbridges.apiclient.volume;

/**
 * Represents an attempt to create a new {@link Volume} record in Seven Bridges.
 *
 * @see CreateVolumeRequestBuilder
 */
public interface CreateVolumeRequest {

  /**
   * Returns the Volume instance for which a new record will be created in Seven Bridges.
   *
   * @return the Volume instance for which a new record will be created in Seven Bridges.
   */
  Volume getVolume();
}


text:
import argparse
import binascii
import datetime
import getpass
import hashlib
import json
import logging
import os
import random
import select
import signal
import socket
import struct
import sys
import time

from threading import Timer
import controller.framework.ipoplib as ipoplib

ipopVerMjr = "16";
ipopVerMnr = "01";
ipopVerRev = "0";
ipopVerRel = "{0}.{1}.{2}".format(ipopVerMjr, ipopVerMnr, ipopVerRev)

# set default config values
CONFIG = {
    "CFx": {
        "ip4_mask": 24,
        "ip6_mask": 64,
        "subnet_mask": 32,
        "contr_port": 5801,
        "local_uid": "",
        "uid_size": 40,
        "tincan_logging": 1,
        "router_mode": False,
        "trim_enabled": False,
        "ipopVerRel" : ipopVerRel
    },
    "Logger": {
        "controller_logging": "ERROR"
    },
    "TincanListener": {
        "buf_size": 65507,
        "socket_read_wait_time": 15,
        "dependencies": ["Logger"]
    },
    "TincanSender": {
        "stun": ["stun.l.google.com:19302", "stun1.l.google.com:19302",
                 "stun2.l.google.com:19302", "stun3.l.google.com:19302",
                 "stun4.l.google.com:19302"],
        "turn": [],
        "ip6_prefix": "fd50:0dbc:41f2:4a3c",
        "switchmode": 0,
        "localhost": "127.0.0.1",
        "svpn_port": 5800,
        "localhost6": "::1",
        "dependencies": ["Logger"]
     },
    "LinkManager": {
        "dependencies": ["Logger"]
    }
}

def gen_ip6(uid, ip6=None):
    if ip6 is None:
        ip6 = CONFIG["TincanSender"]["ip6_prefix"]
    for i in range(0, 16, 4):
        ip6 += ":" + uid[i:i+4]
    return ip6

def gen_uid(ip4):
    return hashlib.sha1(ip4.encode('utf-8')).hexdigest()[:CONFIG["CFx"]["uid_size"]]

def make_call(sock, payload=None, **params):
    if socket.has_ipv6:
        dest = (CONFIG["TincanSender"]["localhost6"],
                CONFIG["TincanSender"]["svpn_port"])
    else:
        dest = (CONFIG["TincanSender"]["localhost"],
                CONFIG["TincanSender"]["svpn_port"])
    if payload is None:
        return sock.sendto(ipoplib.ipop_ver + ipoplib.tincan_control + bytes(json.dumps(params).encode('utf-8')), dest)
    else:
        return sock.sendto(bytes((ipoplib.ipop_ver + ipoplib.tincan_packet + payload).encode('utf-8')), dest)

def do_set_logging(sock, logging):
    return make_call(sock, m="set_logging", logging=logging)

def do_set_translation(sock, translate):
    return make_call(sock, m="set_translation", translate=translate)

def do_set_switchmode(sock, switchmode):
    return make_call(sock, m="set_switchmode", switchmode=switchmode)

def do_set_cb_endpoint(sock, addr):
    return make_call(sock, m="set_cb_endpoint", ip=addr[0], port=addr[1])

def do_set_local_ip(sock, uid, ip4, ip6, ip4_mask, ip6_mask, subnet_mask,
                    switchmode):
    return make_call(sock, m="set_local_ip", uid=uid, ip4=ip4, ip6=ip6,
                     ip4_mask=ip4_mask, ip6_mask=ip6_mask,
                     subnet_mask=subnet_mask, switchmode=switchmode)

def do_register_service(sock, username, password, host, port):
    return make_call(sock, m="register_svc", username=username,
                     password=password, host=host, port=port)

def do_set_trimpolicy(sock, trim_enabled):
    return make_call(sock, m="set_trimpolicy", trim_enabled=trim_enabled)

def do_get_state(sock, peer_uid="", stats=True):
    return make_call(sock, m="get_state", uid=peer_uid, stats=stats)

def load_peer_ip_config(ip_config):
    with open(ip_config) as f:
        ip_cfg = json.load(f)

    for peer_ip in ip_cfg:
        uid = peer_ip["uid"]
        ip = peer_ip["ipv4"]
        IP_MAP[uid] = ip
        logging.debug("MAP %s -> %s" % (ip, uid))


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Lophostachys uxpanapensis Acosta

### Remarks
null


text:
CGFloat const LGAlertViewPaddingWidth = 10.0;
CGFloat const LGAlertViewPaddingHeight = 8.0;
CGFloat const LGAlertViewButtonImageOffsetFromTitle = 8.0;

#pragma mark - Implementation

@implementation LGAlertViewHelper

+ (void)animateWithAnimations:(void(^)())animations completion:(void(^)(BOOL finished))completion {
    [UIView animateWithDuration:0.5
                          delay:0.0
         usingSpringWithDamping:1.0
          initialSpringVelocity:0.5
                        options:0
                     animations:animations
                     completion:completion];
}

+ (void)keyboardAnimateWithNotificationUserInfo:(NSDictionary *)notificationUserInfo animations:(void(^)(CGFloat keyboardHeight))animations {
    CGFloat keyboardHeight = (notificationUserInfo[UIKeyboardFrameEndUserInfoKey] ? CGRectGetHeight([notificationUserInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue]) : 0.0);

    if (!keyboardHeight) return;

    NSTimeInterval animationDuration = [notificationUserInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    int animationCurve = [notificationUserInfo[UIKeyboardAnimationCurveUserInfoKey] intValue];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];

    if (animations) {
        animations(keyboardHeight);
    }

    [UIView commitAnimations];
}

+ (UIImage *)image1x1WithColor:(UIColor *)color {
    if (!color) return nil;

    CGRect rect = CGRectMake(0.0, 0.0, 1.0, 1.0);

    UIGraphicsBeginImageContext(rect.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

+ (BOOL)isNotRetina {
    static BOOL isNotRetina;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        isNotRetina = (UIScreen.mainScreen.scale == 1.0);
    });

    return isNotRetina;
}

+ (BOOL)isPad {
    return UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad;
}

+ (CGFloat)statusBarHeight {
    UIApplication *sharedApplication = [UIApplication sharedApplication];
    return sharedApplication.isStatusBarHidden ? 0.0 : CGRectGetHeight(sharedApplication.statusBarFrame);
}

+ (CGFloat)separatorHeight {
    return self.isNotRetina ? 1.0 : 0.5;
}

+ (BOOL)isPadAndNotForce:(LGAlertView *)alertView {
    return self.isPad && !alertView.isPadShowsActionSheetFromBottom;
}

+ (BOOL)isCancelButtonSeparate:(LGAlertView *)alertView {
    return alertView.style == LGAlertViewStyleActionSheet && alertView.cancelButtonOffsetY != NSNotFound && alertView.cancelButtonOffsetY > 0.0 && ![self isPadAndNotForce:alertView];
}

+ (CGFloat)systemVersion {
    return [UIDevice currentDevice].systemVersion.floatValue;
}

+ (UIWindow *)appWindow {
    return [UIApplication sharedApplication].windows[0];
}

+ (UIWindow *)keyWindow {
    return [UIApplication sharedApplication].keyWindow;
}

+ (BOOL)isViewControllerBasedStatusBarAppearance {
    static BOOL isViewControllerBasedStatusBarAppearance;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        if (UIDevice.currentDevice.systemVersion.floatValue >= 9.0) {
            isViewControllerBasedStatusBarAppearance = YES;
        }
        else {
            NSNumber *viewControllerBasedStatusBarAppearance = [NSBundle.mainBundle objectForInfoDictionaryKey:@"UIViewControllerBasedStatusBarAppearance"];
            isViewControllerBasedStatusBarAppearance = (viewControllerBasedStatusBarAppearance == nil ? YES : viewControllerBasedStatusBarAppearance.boolValue);
        }
    });

    return isViewControllerBasedStatusBarAppearance;
}

@end


text:
package com.evolveum.midpoint.schema;

import static com.evolveum.midpoint.prism.util.PrismTestUtil.*;
import static org.testng.AssertJUnit.*;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.xml.namespace.QName;

import com.evolveum.midpoint.prism.util.PrismTestUtil;

import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.evolveum.midpoint.prism.PrismConstants;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.PrismReferenceValue;
import com.evolveum.midpoint.prism.PrismValue;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.AndFilter;
import com.evolveum.midpoint.prism.query.EqualFilter;
import com.evolveum.midpoint.prism.query.LogicalFilter;
import com.evolveum.midpoint.prism.query.NaryLogicalFilter;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectPaging;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.OrFilter;
import com.evolveum.midpoint.prism.query.QueryJaxbConvertor;
import com.evolveum.midpoint.prism.query.RefFilter;
import com.evolveum.midpoint.prism.query.TypeFilter;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.xnode.ListXNode;
import com.evolveum.midpoint.prism.xnode.MapXNode;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.DomAsserts;
import com.evolveum.midpoint.util.PrettyPrinter;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.FailedOperationTypeType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.GenericObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType;
import com.evolveum.prism.xml.ns._public.query_3.PagingType;
import com.evolveum.prism.xml.ns._public.query_3.QueryType;
import com.evolveum.prism.xml.ns._public.query_3.SearchFilterType;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;

public class TestQueryConvertor {

	private static final Trace LOGGER = TraceManager.getTrace(TestQueryConvertor.class);

	private static final File TEST_DIR = new File("src/test/resources/queryconvertor");

	private static final String NS_EXTENSION = "http://midpoint.evolveum.com/xml/ns/test/extension";
	private static final String NS_ICFS = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3";
	private static final String NS_BLA = "http://midpoint.evolveum.com/blabla";

	private static final QName intExtensionDefinition = new QName(NS_EXTENSION, "intType");
	private static final QName stringExtensionDefinition = new QName(NS_EXTENSION, "stringType");
	private static final QName fooBlaDefinition = new QName(NS_BLA, "foo");
	private static final QName ICF_NAME = new QName(NS_ICFS, "name");

	private static final QName FAILED_OPERATION_TYPE_QNAME = new QName(SchemaConstantsGenerated.NS_COMMON,
			"FailedOperationTypeType");

	private static final File FILTER_AND_GENERIC_FILE = new File(TEST_DIR, "filter-and-generic.xml");
	private static final File FILTER_ACCOUNT_FILE = new File(TEST_DIR, "filter-account.xml");
	private static final File FILTER_ACCOUNT_ATTRIBUTES_RESOURCE_REF_FILE = new File(TEST_DIR,
			"filter-account-by-attributes-and-resource-ref.xml");
	private static final File FILTER_OR_COMPOSITE = new File(TEST_DIR, "filter-or-composite.xml");
	private static final File FILTER_CONNECTOR_BY_TYPE_FILE = new File(TEST_DIR, "filter-connector-by-type.xml");
	private static final File FILTER_BY_TYPE_FILE = new File(TEST_DIR, "filter-by-type.xml");

	@BeforeSuite
	public void setup() throws SchemaException, SAXException, IOException {
		PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
		resetPrismContext(MidPointPrismContextFactory.FACTORY);
	}

	@Test
	public void testAccountFilter() throws Exception {
		displayTestTitle("testAccountFilter");

		SearchFilterType filterType = unmarshalFilter(FILTER_ACCOUNT_FILE);
		ObjectQuery query = toObjectQuery(ShadowType.class, filterType);
		displayQuery(query);

		assertNotNull(query);

		ObjectFilter filter = query.getFilter();
		PrismAsserts.assertAndFilter(filter, 2);

		ObjectFilter first = getFilterCondition(filter, 0);
		PrismAsserts.assertEqualsFilter(first, ShadowType.F_FAILED_OPERATION_TYPE, FAILED_OPERATION_TYPE_QNAME,
				new ItemPath(ShadowType.F_FAILED_OPERATION_TYPE));
		PrismAsserts.assertEqualsFilterValue((EqualFilter) first, FailedOperationTypeType.ADD);

		ObjectFilter second = getFilterCondition(filter, 1);
		PrismAsserts.assertEqualsFilter(second, ShadowType.F_NAME, PolyStringType.COMPLEX_TYPE, new ItemPath(
				ShadowType.F_NAME));
		PrismAsserts.assertEqualsFilterValue((EqualFilter) second, createPolyString("someName"));

		QueryType convertedQueryType = toQueryType(query);
		System.out.println("Re-converted query type");
		System.out.println(convertedQueryType.debugDump());

		SearchFilterType convertedFilterType = convertedQueryType.getFilter();
		MapXNode xFilter = convertedFilterType.serializeToXNode(getPrismContext());
		PrismAsserts.assertSize(xFilter, 1);
		PrismAsserts.assertSubnode(xFilter, AndFilter.ELEMENT_NAME, MapXNode.class);
		MapXNode xandmap = (MapXNode) xFilter.get(AndFilter.ELEMENT_NAME);
		PrismAsserts.assertSize(xandmap, 1);
		PrismAsserts.assertSubnode(xandmap, EqualFilter.ELEMENT_NAME, ListXNode.class);
		ListXNode xequalsList = (ListXNode) xandmap.get(EqualFilter.ELEMENT_NAME);
		PrismAsserts.assertSize(xequalsList, 2);

		Element filterClauseElement = convertedFilterType.getFilterClause();
		System.out.println("Serialized filter (JAXB->DOM)");
		System.out.println(DOMUtil.serializeDOMToString(filterClauseElement));

		DomAsserts.assertElementQName(filterClauseElement, AndFilter.ELEMENT_NAME);
		DomAsserts.assertSubElements(filterClauseElement, 2);

		Element firstSubelement = DOMUtil.getChildElement(filterClauseElement, 0);
		DomAsserts.assertElementQName(firstSubelement, EqualFilter.ELEMENT_NAME);
		Element firstValueElement = DOMUtil.getChildElement(firstSubelement, PrismConstants.Q_VALUE);
		DomAsserts.assertTextContent(firstValueElement, "add");

		Element secondSubelement = DOMUtil.getChildElement(filterClauseElement, 1);
		DomAsserts.assertElementQName(secondSubelement, EqualFilter.ELEMENT_NAME);
		Element secondValueElement = DOMUtil.getChildElement(secondSubelement, PrismConstants.Q_VALUE);
		DomAsserts.assertTextContent(secondValueElement, "someName");
	}

	@Test
	public void testAccountQueryAttributesAndResource() throws Exception {
		displayTestTitle("testAccountQueryAttributesAndResource");

		SearchFilterType filterType = unmarshalFilter(FILTER_ACCOUNT_ATTRIBUTES_RESOURCE_REF_FILE);
		ObjectQuery query = toObjectQuery(ShadowType.class, filterType);
		displayQuery(query);

		assertNotNull(query);

		ObjectFilter filter = query.getFilter();
		PrismAsserts.assertAndFilter(filter, 2);

		ObjectFilter first = getFilterCondition(filter, 0);
		PrismAsserts.assertRefFilter(first, ShadowType.F_RESOURCE_REF, ObjectReferenceType.COMPLEX_TYPE, new ItemPath(
				ShadowType.F_RESOURCE_REF));
		assertRefFilterValue((RefFilter) first, "aae7be60-df56-11df-8608-0002a5d5c51b");

		ObjectFilter second = getFilterCondition(filter, 1);
		PrismAsserts.assertEqualsFilter(second, ICF_NAME, DOMUtil.XSD_STRING, new ItemPath(ShadowType.F_ATTRIBUTES,
				ICF_NAME));
		PrismAsserts.assertEqualsFilterValue((EqualFilter) second, "uid=jbond,ou=People,dc=example,dc=com");

		QueryType convertedQueryType = toQueryType(query);
		LOGGER.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClause()));

		// TODO: add some asserts
	}

	@Test
	public void testAccountQueryCompositeOr() throws Exception {
		displayTestTitle("testAccountQueryCompositeOr");

		SearchFilterType filterType = unmarshalFilter(FILTER_OR_COMPOSITE);
		ObjectQuery query = toObjectQuery(ShadowType.class, filterType);
		displayQuery(query);

		assertNotNull(query);

		ObjectFilter filter = query.getFilter();
		PrismAsserts.assertOrFilter(filter, 4);

		ObjectFilter first = getFilterCondition(filter, 0);
		PrismAsserts.assertEqualsFilter(first, ShadowType.F_INTENT, DOMUtil.XSD_STRING, new ItemPath(ShadowType.F_INTENT));
		PrismAsserts.assertEqualsFilterValue((EqualFilter) first, "some account type");

		ObjectFilter second = getFilterCondition(filter, 1);
		PrismAsserts.assertEqualsFilter(second, fooBlaDefinition, DOMUtil.XSD_STRING, new ItemPath(
				ShadowType.F_ATTRIBUTES, fooBlaDefinition));
		PrismAsserts.assertEqualsFilterValue((EqualFilter) second, "foo value");

		ObjectFilter third = getFilterCondition(filter, 2);
		PrismAsserts.assertEqualsFilter(third, stringExtensionDefinition, DOMUtil.XSD_STRING, new ItemPath(
				ShadowType.F_EXTENSION, stringExtensionDefinition));
		PrismAsserts.assertEqualsFilterValue((EqualFilter) third, "uid=test,dc=example,dc=com");

		ObjectFilter forth = getFilterCondition(filter, 3);
		PrismAsserts.assertRefFilter(forth, ShadowType.F_RESOURCE_REF, ObjectReferenceType.COMPLEX_TYPE, new ItemPath(
				ShadowType.F_RESOURCE_REF));
		assertRefFilterValue((RefFilter) forth, "d0db5be9-cb93-401f-b6c1-86ffffe4cd5e");

		QueryType convertedQueryType = toQueryType(query);
		LOGGER.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClause()));

		// TODO: add some asserts
	}

	@Test
	public void testConnectorQuery() throws Exception {
		displayTestTitle("testConnectorQuery");
		SearchFilterType filterType = PrismTestUtil.parseAtomicValue(FILTER_CONNECTOR_BY_TYPE_FILE, SearchFilterType.COMPLEX_TYPE);
		ObjectQuery query = null;
		try {
			query = QueryJaxbConvertor.createObjectQuery(ConnectorType.class, filterType, getPrismContext());
			displayQuery(query);

			assertNotNull(query);
			ObjectFilter filter = query.getFilter();
			PrismAsserts.assertEqualsFilter(query.getFilter(), ConnectorType.F_CONNECTOR_TYPE, DOMUtil.XSD_STRING,
					new ItemPath(ConnectorType.F_CONNECTOR_TYPE));
			PrismAsserts.assertEqualsFilterValue((EqualFilter) filter, "org.identityconnectors.ldap.LdapConnector");

			QueryType convertedQueryType = toQueryType(query);
			displayQueryType(convertedQueryType);
		} catch (SchemaException ex) {
			LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
			throw ex;
		} catch (RuntimeException ex) {
			LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
			throw ex;
		} catch (Exception ex) {
			LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
			throw ex;
		}

	}

	@Test
	public void testTypeFilterQuery() throws Exception {
		displayTestTitle("testConnectorQuery");
		SearchFilterType filterType = PrismTestUtil.parseAtomicValue(FILTER_BY_TYPE_FILE, SearchFilterType.COMPLEX_TYPE);
		ObjectQuery query = null;
		try {
			query = QueryJaxbConvertor.createObjectQuery(ConnectorType.class, filterType, getPrismContext());
			displayQuery(query);

			assertNotNull(query);
			ObjectFilter filter = query.getFilter();
			assertTrue("filter is not an instance of type filter", filter instanceof TypeFilter);

			TypeFilter typeFilter = (TypeFilter) filter;
			assertEquals(typeFilter.getType(), UserType.COMPLEX_TYPE);
			assertNotNull("filter in type filter must not be null", typeFilter.getFilter());
			PrismAsserts.assertEqualsFilter(typeFilter.getFilter(), UserType.COMPLEX_TYPE, DOMUtil.XSD_QNAME, new ItemPath(UserType.F_NAME));
			PrismAsserts.assertEqualsFilterValue((EqualFilter) typeFilter.getFilter(), "some name identificator");
//			PrismAsserts.assertEqualsFilter(query.getFilter(), ConnectorType.F_CONNECTOR_TYPE, DOMUtil.XSD_STRING,
//					new ItemPath(ConnectorType.F_CONNECTOR_TYPE));
//			PrismAsserts.assertEqualsFilterValue((EqualsFilter) filter, "org.identityconnectors.ldap.LdapConnector");

			QueryType convertedQueryType = toQueryType(query);
			displayQueryType(convertedQueryType);
		} catch (SchemaException ex) {
			LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
			throw ex;
		} catch (RuntimeException ex) {
			LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
			throw ex;
		} catch (Exception ex) {
			LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
			throw ex;
		}

	}

	private void assertRefFilterValue(RefFilter filter, String oid) {
		List<? extends PrismValue> values = filter.getValues();
		assertEquals(1, values.size());
		assertEquals(PrismReferenceValue.class, values.get(0).getClass());
		PrismReferenceValue val = (PrismReferenceValue) values.get(0);

		assertEquals(oid, val.getOid());
		// TODO: maybe some more asserts for type, relation and other reference
		// values
	}

	private ObjectQuery toObjectQuery(Class type, QueryType queryType) throws Exception {
		ObjectQuery query = QueryJaxbConvertor.createObjectQuery(type, queryType,
				getPrismContext());
		return query;
	}

	private ObjectQuery toObjectQuery(Class type, SearchFilterType filterType) throws Exception {
		ObjectQuery query = QueryJaxbConvertor.createObjectQuery(type, filterType,
				getPrismContext());
		return query;
	}

	private QueryType toQueryType(ObjectQuery query) throws Exception {
		return QueryJaxbConvertor.createQueryType(query, getPrismContext());
	}

	@Test
	public void testGenericQuery() throws Exception {
		displayTestTitle("testGenericQuery");

		SearchFilterType queryType = unmarshalFilter(FILTER_AND_GENERIC_FILE);
		ObjectQuery query = toObjectQuery(GenericObjectType.class, queryType);

		displayQuery(query);

		// check parent filter
		assertNotNull(query);
		ObjectFilter filter = query.getFilter();
		PrismAsserts.assertAndFilter(filter, 2);
		// check first condition
		ObjectFilter first = getFilterCondition(filter, 0);
		PrismAsserts.assertEqualsFilter(first, GenericObjectType.F_NAME, PolyStringType.COMPLEX_TYPE, new ItemPath(
				GenericObjectType.F_NAME));
		PrismAsserts.assertEqualsFilterValue((EqualFilter) first, createPolyString("generic object"));
		// check second condition
		ObjectFilter second = getFilterCondition(filter, 1);
		PrismAsserts.assertEqualsFilter(second, intExtensionDefinition, DOMUtil.XSD_INT, new ItemPath(
				ObjectType.F_EXTENSION, new QName(NS_EXTENSION, "intType")));
		PrismAsserts.assertEqualsFilterValue((EqualFilter) second, 123);

		QueryType convertedQueryType = toQueryType(query);
		assertNotNull("Re-serialized query is null ", convertedQueryType);
		assertNotNull("Filter in re-serialized query must not be null.", convertedQueryType.getFilter());

		displayQueryType(convertedQueryType);
	}

	@Test
	public void testUserQuery() throws Exception {
		displayTestTitle("testUserQuery");

		File[] userQueriesToTest = new File[] { new File(TEST_DIR, "filter-user-by-fullName.xml"),
				new File(TEST_DIR, "filter-user-by-name.xml"),
				new File(TEST_DIR, "filter-user-substring-fullName.xml") };
		// prismContext.silentMarshalObject(queryTypeNew, LOGGER);
		for (File file : userQueriesToTest) {
			SearchFilterType filterType = PrismTestUtil.parseAtomicValue(file, SearchFilterType.COMPLEX_TYPE);
			LOGGER.info("===[ query type parsed ]===");
			ObjectQuery query = null;
			try {
				query = QueryJaxbConvertor.createObjectQuery(UserType.class, filterType, getPrismContext());
				LOGGER.info("query converted: ");

				LOGGER.info("QUERY DUMP: {}", query.debugDump());
				LOGGER.info("QUERY Pretty print: {}", query.toString());
				System.out.println("QUERY Pretty print: " + query.toString());

				QueryType convertedQueryType = QueryJaxbConvertor.createQueryType(query, getPrismContext());
				LOGGER.info(DOMUtil.serializeDOMToString(convertedQueryType.getFilter().getFilterClause()));
			} catch (SchemaException ex) {
				LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
				throw ex;
			} catch (RuntimeException ex) {
				LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
				throw ex;
			} catch (Exception ex) {
				LOGGER.error("Error while converting query: {}", ex.getMessage(), ex);
				throw ex;
			}
		}
	}

	@Test
	public void testConvertQueryNullFilter() throws Exception {
		ObjectQuery query = ObjectQuery.createObjectQuery(ObjectPaging.createPaging(0, 10));
		QueryType queryType = QueryJaxbConvertor.createQueryType(query, getPrismContext());

		assertNotNull(queryType);
		assertNull(queryType.getFilter());
		PagingType paging = queryType.getPaging();
		assertNotNull(paging);
		assertEquals(new Integer(0), paging.getOffset());
		assertEquals(new Integer(10), paging.getMaxSize());

	}
}


text:
 using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using biz.dfch.CS.Osram.Lightify.Client.Model;
using biz.dfch.CS.Web.Utilities.Rest;
using Telerik.JustMock;

namespace biz.dfch.CS.Osram.Lightify.Client.Tests
{
    [TestClass]
    public class ClientGetGatewayTest
    {
        [TestMethod]
        public void GetGatewaySucceedsAndReturnsGateway()
        {
            // Arrange
            var gateway = new Gateway()
            {
                Version = TestConstants.GATEWAY_VERSION,
                SerialNumber = TestConstants.SERIAL_NUMBER,
                Online = true
            };

            var client = new Client(TestConstants.OSRAM_LIGHTIFY_BASE_URI);

            client.UserInformation = new UserInformation()
            {
                UserId = TestConstants.USER_ID,
                Username = TestConstants.USERNAME,
                Password = TestConstants.PASSWORD,
                SerialNumber = TestConstants.SERIAL_NUMBER,
                SecurityToken = TestConstants.SECURITY_TOKEN
            };

            var restCallExecutor = Mock.Create<RestCallExecutor>();
            Mock.Arrange(() => restCallExecutor.Invoke(HttpMethod.Get, Arg.Matches<string>(s => s.Contains(Constants.ApiOperation.GATEWAY)), Arg.IsAny<Dictionary<string, string>>(), Arg.AnyString))
                .IgnoreInstance()
                .Returns(gateway.SerializeObject())
                .OccursOnce();

            // Act
            var result = client.GetGateway();

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(TestConstants.GATEWAY_VERSION, result.Version);
            Assert.AreEqual(TestConstants.SERIAL_NUMBER, result.SerialNumber);
            Assert.IsTrue(result.Online);

            Mock.Assert(restCallExecutor);
        }
    }
}


text:
package torrent

import (
	"fmt"

	"github.com/cenkalti/rain/internal/peerprotocol"
	"github.com/cenkalti/rain/internal/verifier"
)

func (t *torrent) handleVerifyCommand() {
	t.log.Info("verifying")
	t.doVerify = true
	if t.status() == Stopped {
		t.bitfield = nil
		t.start()
	} else {
		t.stop(nil)
	}
}

func (t *torrent) handleVerificationDone(ve *verifier.Verifier) {
	if t.verifier != ve {
		panic("invalid verifier")
	}
	t.verifier = nil

	if ve.Error != nil {
		t.stop(fmt.Errorf("file verification error: %s", ve.Error))
		return
	}

	// Now we have a constructed and verified bitfield.
	t.mBitfield.Lock()
	t.bitfield = ve.Bitfield
	t.mBitfield.Unlock()

	// Save the bitfield to resume db.
	err := t.writeBitfield()
	if err != nil {
		t.stop(err)
		return
	}

	var haveMessages []peerprotocol.HaveMessage

	// Mark downloaded pieces.
	for i := uint32(0); i < t.bitfield.Len(); i++ {
		if t.bitfield.Test(i) {
			t.pieces[i].Done = true
			haveMessages = append(haveMessages, peerprotocol.HaveMessage{Index: i})
		}
	}

	// We may detect missing pieces after verification. Then, status must be set from Seeding to Downloading.
	if !t.bitfield.All() {
		t.completed = false
		if t.completeC == nil {
			t.completeC = make(chan struct{})
		}
	}

	if t.doVerify {
		// Stop after manual verification command.
		t.doVerify = false
		t.stop(nil)
		return
	}

	// Tell connected peers that pieces we have.
	for pe := range t.peers {
		for _, msg := range haveMessages {
			pe.SendMessage(msg)
		}
		t.updateInterestedState(pe)
	}

	if t.checkCompletion() && t.stopAfterDownload {
		t.stopAndSetStoppedOnComplete()
		return
	}
	t.processQueuedMessages()
	t.addFixedPeers()
	t.startAcceptor()
	t.startAnnouncers()
	t.startPieceDownloaders()
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#88CFC2"
    android:orientation="vertical" >

    <Button
        android:id="@+id/bildButton"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="27dp"
        android:textColor="#000000"
        android:background="@drawable/custom_button"
        android:text="Bild" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/bildButton"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/bildButton"
        android:layout_marginRight="28dp"
        android:textColor="#000000"
        android:background="@drawable/custom_button"
        android:text="Profilbild" />

    <EditText
        android:id="@+id/persischesTextfeld"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/bildButton"
        android:layout_alignRight="@+id/bildButton"
        android:layout_centerVertical="true"
        android:ems="10" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/persischesTextfeld"
        android:layout_alignRight="@+id/persischesTextfeld"
        android:layout_below="@+id/persischesTextfeld"
        android:layout_marginTop="29dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignRight="@+id/button3"
        android:layout_alignTop="@+id/editText2"
        android:textColor="#000000"
        android:background="@drawable/custom_button"
        android:text="M" />

    <Button
        android:id="@+id/button5"
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button3"
        android:layout_alignRight="@+id/button1"
        android:layout_alignTop="@+id/button3"
        android:textColor="#000000"
        android:background="@drawable/custom_button"
        android:text="L" />

    <Button
        android:id="@+id/button3"
        android:layout_width="40dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/persischesTextfeld"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignTop="@+id/persischesTextfeld"
        android:textColor="#000000"
        android:background="@drawable/custom_button"
        android:text="M" />

    <Button
        android:id="@+id/button6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button4"
        android:layout_alignLeft="@+id/button5"
        android:layout_alignRight="@+id/button5"
        android:layout_alignTop="@+id/button4"
        android:textColor="#000000"
        android:background="@drawable/custom_button"
        android:text="L" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="48dp"
        android:textColor="#000000"
        android:background="@drawable/custom_button"
        android:text="Wort hinzufügen" />

</RelativeLayout>


text:
template <class CharT>
class testbuf
    : public std::basic_streambuf<CharT>
{
    typedef std::basic_streambuf<CharT> base;
    std::basic_string<CharT> str_;
public:
    testbuf()
    {
    }
    testbuf(const std::basic_string<CharT>& str)
        : str_(str)
    {
        base::setg(const_cast<CharT*>(str_.data()),
                   const_cast<CharT*>(str_.data()),
                   const_cast<CharT*>(str_.data() + str_.size()));
    }

    std::basic_string<CharT> str() const
        {return std::basic_string<CharT>(base::pbase(), base::pptr());}

protected:

    virtual typename base::int_type
        overflow(typename base::int_type ch = base::traits_type::eof())
        {
            if (ch != base::traits_type::eof())
            {
                std::size_t n = str_.size();
                str_.push_back(static_cast<CharT>(ch));
                str_.resize(str_.capacity());
                base::setp(const_cast<CharT*>(str_.data()),
                           const_cast<CharT*>(str_.data() + str_.size()));
                base::pbump(static_cast<int>(n+1));
            }
            return ch;
        }
};

int main()
{
    {
        testbuf<char> sb("testing...");
        std::istream is(&sb);
        testbuf<char> sb2;
        is >> &sb2;
        assert(sb2.str() == "testing...");
        assert(is.gcount() == 10);
    }
}