text:
require 'smaak/crypto'

module Smaak
  class AuthMessage
    attr_reader :identifier
    attr_reader :route_info
    attr_reader :nonce
    attr_reader :recipient
    attr_reader :psk
    attr_reader :expires
    attr_reader :encrypt

    def self.create(recipient_public_key, psk, token_life, identifier, route_info = "", encrypt = false)
      nonce = Smaak::Crypto.generate_nonce
      expires = Time.now.to_i + token_life
      # Must obfuscate PSK. AuthMessage must always have an obfuscated PSK
      psk = Smaak::Crypto.obfuscate_psk(psk)
      AuthMessage.build(recipient_public_key, psk, expires, identifier, route_info, nonce, encrypt)
    end

    def self.build(recipient_public_key, psk, expires, identifier, route_info, nonce, encrypt = false)
      # No need to obfuscate PSK. Off the wire we should always expect an obfuscated PSK
      AuthMessage.new(identifier, route_info, nonce, expires, psk, recipient_public_key, encrypt)
    end

    def initialize(identifier, route_info, nonce, expires, psk, recipient_public_key, encrypt)
      set_and_validate_identifier(identifier)
      set_and_validate_route_info(route_info)
      set_and_validate_nonce(nonce)
      set_and_validate_expires(expires)
      set_recipient(recipient_public_key)
      set_psk(psk)
      set_encrypt(encrypt)
    end

    def set_and_validate_identifier(identifier)
      raise ArgumentError.new("Message must have a valid identifier set") if identifier.nil? or identifier.empty?
      @identifier = identifier
      @identifier.freeze
    end

    def set_and_validate_route_info(route_info)
      raise ArgumentError.new("Message must have a valid route information set") if route_info.nil?
      @route_info = route_info
      @route_info.freeze
    end

    def set_and_validate_nonce(nonce)
      raise ArgumentError.new("Message must have a valid nonce set") unless validate_nonce(nonce)
      @nonce = nonce
      @nonce.freeze
    end

    def set_and_validate_expires(expires)
      raise ArgumentError.new("Message must have a valid expiry set") unless validate_expiry(expires)
      @expires = expires
    end

    def set_recipient(recipient_public_key)
      @recipient = recipient_public_key
    end

    def set_psk(psk)
      @psk = psk
    end

    def set_encrypt(encrypt)
      @encrypt = false
      @encrypt = true if encrypt == "true" or encrypt == true
    end

    def expired?
      @expires.to_i < Time.now.to_i
    end

    def psk_match?(psk)
      return false if psk.nil?
      return false if @psk.nil?
      @psk == Smaak::Crypto.obfuscate_psk(psk)
    end

    def intended_for_recipient?(pubkey)
      return false if pubkey.nil?
      return false if @recipient.nil?
      @recipient == pubkey
    end

    def verify(psk)
      return false unless psk_match?(psk)
      true
    end

    private

    def validate_nonce(nonce)
      return false if nonce.nil?
      return false if nonce.to_i == 0
      true

      rescue
        false
    end

    def validate_expiry(expires)
      return false if expires.nil?
      return false unless (expires.to_i > 0)
      true

      rescue
        false
    end
  end
end


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0011_auto_20170610_1649'),
    ]

    operations = [
        migrations.RenameModel(
            old_name='DesktopApplicationProgramming',
            new_name='Programming',
        ),
        migrations.DeleteModel(
            name='AndroidApplicationProgramming',
        ),
        migrations.DeleteModel(
            name='NetworkProgramming',
        ),
    ]

redpajama_set_name: RedPajamaGithub


text:
namespace content {

SyntheticMouseDriver::SyntheticMouseDriver() : last_modifiers_(0) {
  mouse_event_.pointer_type = blink::WebPointerProperties::PointerType::kMouse;
}

SyntheticMouseDriver::~SyntheticMouseDriver() {}

void SyntheticMouseDriver::DispatchEvent(SyntheticGestureTarget* target,
                                         const base::TimeTicks& timestamp) {
  mouse_event_.SetTimeStamp(timestamp);
  if (mouse_event_.GetType() != blink::WebInputEvent::Type::kUndefined) {
    target->DispatchInputEventToPlatform(mouse_event_);
    mouse_event_.SetType(blink::WebInputEvent::Type::kUndefined);
  }
}

void SyntheticMouseDriver::Press(float x,
                                 float y,
                                 int index,
                                 SyntheticPointerActionParams::Button button,
                                 int key_modifiers,
                                 float width,
                                 float height,
                                 float rotation_angle,
                                 float force,
                                 float tangential_pressure,
                                 int tilt_x,
                                 int tilt_y,
                                 const base::TimeTicks& timestamp) {
  DCHECK_EQ(index, 0);
  blink::WebMouseEvent::Button pressed_button =
      SyntheticPointerActionParams::GetWebMouseEventButton(button);
  click_count_ = ComputeClickCount(timestamp, pressed_button, x, y);
  int modifiers =
      SyntheticPointerActionParams::GetWebMouseEventModifier(button);
  if (from_devtools_debugger_)
    key_modifiers |= blink::WebInputEvent::kFromDebugger;
  mouse_event_ = blink::SyntheticWebMouseEventBuilder::Build(
      blink::WebInputEvent::Type::kMouseDown, x, y,
      modifiers | key_modifiers | last_modifiers_, mouse_event_.pointer_type);
  mouse_event_.button = pressed_button;
  last_modifiers_ = modifiers | last_modifiers_;
  mouse_event_.click_count = click_count_;
  mouse_event_.force = force;
  mouse_event_.tangential_pressure = tangential_pressure;
  mouse_event_.twist = rotation_angle;
  mouse_event_.tilt_x = tilt_x;
  mouse_event_.tilt_y = tilt_y;
  last_mouse_click_time_ = timestamp;
  last_x_ = x;
  last_y_ = y;
}

void SyntheticMouseDriver::Move(float x,
                                float y,
                                int index,
                                int key_modifiers,
                                float width,
                                float height,
                                float rotation_angle,
                                float force,
                                float tangential_pressure,
                                int tilt_x,
                                int tilt_y,
                                SyntheticPointerActionParams::Button button) {
  DCHECK_EQ(index, 0);
  int button_modifiers =
      SyntheticPointerActionParams::GetWebMouseEventModifier(button);
  if (from_devtools_debugger_)
    key_modifiers |= blink::WebInputEvent::kFromDebugger;
  mouse_event_ = blink::SyntheticWebMouseEventBuilder::Build(
      blink::WebInputEvent::Type::kMouseMove, x, y,
      button_modifiers | key_modifiers | last_modifiers_,
      mouse_event_.pointer_type);
  if (button != SyntheticPointerActionParams::Button::NO_BUTTON) {
    // If the caller specified a pressed button for this move event, use that.
    mouse_event_.button =
        SyntheticPointerActionParams::GetWebMouseEventButton(button);
  } else {
    // Otherwise, infer pressed button from a previous press event (if any) in
    // the same pointer action sequence.
    mouse_event_.button =
        SyntheticPointerActionParams::GetWebMouseEventButtonFromModifier(
            last_modifiers_);
  }
  mouse_event_.click_count = 0;
  mouse_event_.force =
      mouse_event_.button == blink::WebMouseEvent::Button::kNoButton ? 0
                                                                     : force;
  mouse_event_.tangential_pressure = tangential_pressure;
  mouse_event_.twist = rotation_angle;
  mouse_event_.tilt_x = tilt_x;
  mouse_event_.tilt_y = tilt_y;
}

void SyntheticMouseDriver::Release(int index,
                                   SyntheticPointerActionParams::Button button,
                                   int key_modifiers) {
  DCHECK_EQ(index, 0);
  if (from_devtools_debugger_)
    key_modifiers |= blink::WebInputEvent::kFromDebugger;
  mouse_event_ = blink::SyntheticWebMouseEventBuilder::Build(
      blink::WebInputEvent::Type::kMouseUp, mouse_event_.PositionInWidget().x(),
      mouse_event_.PositionInWidget().y(), key_modifiers | last_modifiers_,
      mouse_event_.pointer_type);
  mouse_event_.button =
      SyntheticPointerActionParams::GetWebMouseEventButton(button);

  // Set click count to 1 to allow pointer release without pointer down. This
  // prevents MouseEvent::SetClickCount from throwing DCHECK error
  click_count_ == 0 ? mouse_event_.click_count = 1
                    : mouse_event_.click_count = click_count_;
  last_modifiers_ =
      last_modifiers_ &
      (~SyntheticPointerActionParams::GetWebMouseEventModifier(button));
}

void SyntheticMouseDriver::Cancel(int index,
                                  SyntheticPointerActionParams::Button button,
                                  int key_modifiers) {
  NOTIMPLEMENTED();
}

void SyntheticMouseDriver::Leave(int index) {
  NOTIMPLEMENTED();
}

bool SyntheticMouseDriver::UserInputCheck(
    const SyntheticPointerActionParams& params) const {
  if (params.pointer_action_type() ==
      SyntheticPointerActionParams::PointerActionType::NOT_INITIALIZED) {
    return false;
  }

  if (params.pointer_action_type() ==
      SyntheticPointerActionParams::PointerActionType::PRESS) {
    int modifiers =
        SyntheticPointerActionParams::GetWebMouseEventModifier(params.button());
    if (last_modifiers_ & modifiers)
      return false;
  }

  if (params.pointer_action_type() ==
      SyntheticPointerActionParams::PointerActionType::RELEASE) {
    int modifiers =
        SyntheticPointerActionParams::GetWebMouseEventModifier(params.button());
    if (!modifiers)
      return false;
  }

  return true;
}

int SyntheticMouseDriver::ComputeClickCount(
    const base::TimeTicks& timestamp,
    blink::WebMouseEvent::Button pressed_button,
    float x,
    float y) {
  const int kDoubleClickTimeMS = 500;
  const int kDoubleClickRange = 4;

  if (click_count_ == 0)
    return 1;

  base::TimeDelta time_difference = timestamp - last_mouse_click_time_;
  if (time_difference.InMilliseconds() > kDoubleClickTimeMS)
    return 1;

  if (std::abs(x - last_x_) > kDoubleClickRange / 2)
    return 1;

  if (std::abs(y - last_y_) > kDoubleClickRange / 2)
    return 1;

  if (mouse_event_.button != pressed_button)
    return 1;

  ++click_count_;
#if !defined(OS_MAC) && !defined(OS_WIN)
  // On Mac and Windows, we keep incresing the click count, but on the other
  // platforms, we reset the count to 1 when it is greater than 3.
  if (click_count_ > 3)
    click_count_ = 1;
#endif
  return click_count_;
}

}  // namespace content


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Chung-kuo Ti Chen-chun, [Fungi of China] 759 (1963)

#### Original name
Polyporus pruinatus Berk.

### Remarks
null


text:
package io.flic.lib;

/**
 * Represents possible values of {@link FlicIntentExtras#VALUE}.
 */
class FlicIntentValues {
	/**
	 * Indicates that the button was released.
	 * Possible value for {@link FlicIntentExtras#VALUE} when {@link FlicIntentExtras#TYPE} is {@link FlicIntentTypes#UP_OR_DOWN}.
	 */
	public static final String UP = "UP";

	/**
	 * Indicates that the button was pressed.
	 * Possible value for {@link FlicIntentExtras#VALUE} when {@link FlicIntentExtras#TYPE} is {@link FlicIntentTypes#UP_OR_DOWN}.
	 */
	public static final String DOWN = "DOWN";

	/**
	 * Indicates that the button was clicked.
	 * Possible value for {@link FlicIntentExtras#VALUE} when {@link FlicIntentExtras#TYPE} is {@link FlicIntentTypes#CLICK_OR_HOLD}.
	 */
	public static final String CLICK = "CLICK";

	/**
	 * Indicates that the button was hold for half a second.
	 * Possible value for {@link FlicIntentExtras#VALUE} when {@link FlicIntentExtras#TYPE} is {@link FlicIntentTypes#CLICK_OR_HOLD} or {@link FlicIntentTypes#SINGLE_OR_DOUBLE_CLICK_OR_HOLD}.
	 */
	public static final String HOLD = "HOLD";

	/**
	 * Indicates that the button was single clicked.
	 * Possible value for {@link FlicIntentExtras#VALUE} when {@link FlicIntentExtras#TYPE} is {@link FlicIntentTypes#SINGLE_OR_DOUBLE_CLICK} or {@link FlicIntentTypes#SINGLE_OR_DOUBLE_CLICK_OR_HOLD}.
	 */
	public static final String SINGLE_CLICK = "SINGLE_CLICK";

	/**
	 * Indicates that the button was double clicked.
	 * Possible value for {@link FlicIntentExtras#VALUE} when {@link FlicIntentExtras#TYPE} is {@link FlicIntentTypes#SINGLE_OR_DOUBLE_CLICK} or {@link FlicIntentTypes#SINGLE_OR_DOUBLE_CLICK_OR_HOLD}.
	 */
	public static final String DOUBLE_CLICK = "DOUBLE_CLICK";
}


text:
\documentclass[a4paper,11pt,oneside]{article}

\author{ J.R. Leeman}
\title{Python Biax Data Reader: biaxread}

\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{setspace}
\usepackage{indentfirst}
\usepackage{fullpage}
\usepackage{epstopdf}
\usepackage{listings}
\usepackage{color}
\usepackage{caption}
\usepackage{colortbl}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{frame=tb,
  language=Python,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\small\ttfamily},
  numbers=left,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{blue},
  commentstyle=\color{dkgreen},
  stringstyle=\color{mauve},
  breaklines=true,
  breakatwhitespace=true
  tabsize=3
}

\begin{document}
\maketitle
\newpage

\section{Purpose}
This script was designed to read data into an easy to use format from xlook output in ASCII or binary form.  Data is read, the header parsed for column names, lengths, etc., and a rec array or Pandas dataframe object returned that is easy to access and call from within a script.  Column names are used to call the data columns, so as long as consistent naming is used the column order in the file is irrelevant.

\section{Description}
\subsection{ASCII Files}
The function ReadAscii first opens the text file with a standard open command.  We know that each column in the data is written as 12 characters wide.  The first line of the header is the number of records, the second is the column number, the third the column headings, the fourth the column units, and the fifth the number of records in each column.  This information if parsed and stored.  Numerical data is read into an array.  A rec array is created with the numpy package and the labels of the column names that were parsed or the data is converted into a dataframe object.

\subsection{Binary Files}
The function ReadBin opens the binary file in 'read binary' mode.  The initial file information is stored as follows (in big-endian format):

\begin{table}[h]
	\begin{center}
	\begin{tabular}{| l | l | l |}
		\hline
                  \rowcolor[gray]{.85}
		Information & Format & Bytes\\
		\hline
		Name & 20 characters &  20\\
		\hline
		Number of Columns & int & 4 \\
		\hline
		Sweep & int & 4\\
		\hline
		Date/Time & int & 4\\
		\hline
	\end{tabular}
	\end{center}
	\label{BinaryFileHeadFormat}
\end{table}

For each possible column there are 84 bytes of information.  There are 32 possible columns.  We read the information for each column and store information for columns that have data.  Blank columns are identified by the first 6 characters of the name `no\_val'.

\begin{table}[h]
	\begin{center}
	\begin{tabular}{| l | l | l |}
		\hline
                  \rowcolor[gray]{.85}
		Information & Format & Bytes\\
		\hline
		Name & 13 characters &  13\\
		\hline
		Units & 13 characters &  13 \\
		\hline
		Gain & int & 4\\
		\hline
		Comment & 50 characters & 50\\
		\hline
		Number of Elements & int & 4\\
		\hline
	\end{tabular}
	\end{center}
	\label{BinaryColHeadFormat}
\end{table}

Data is stored as the default machine format, which for modern Intel based computers in little-endian.  This is the default for the module, but big-endian can be specified.  Each column is written out as a sequence of doubles that are $n_elem$ long.  Doubles are read and stored in a numpy array.  The array is then combined with datatype information collected from the headers and stored as a rec array.

To find the default machine binay format run: \emph{python -c "import struct; print 'little' if ord(struct.pack('L', 1)[0]) else 'big'"}

\section{Cautions}
A few cautions should be observed when using the biaxread script:

\begin{enumerate}
\item The empty array is shaped by row number information from the header.  If a datafile is cut, but the header is left unmodified there will be many extra zero data pairs at the end of the array.
\end{enumerate}

\section{Usage}

\subsection{Return Formats}
By default data will be returned as a Numpy record array (recarray).  Data can also be returned as a Pandas dataframe object that is indexed on the row number of the data.  To do this, set \emph{pandas=True} in the function call to either ReadAscii or ReadBin.

\subsection{ASCII Files}
First process the experimental data in xlook and output a text file with headers.  To do this input \emph{type 0 -1 1 12 pxxxx\_data.txt} at the xlook command line or add it to the data reduction file.  Be sure to correct any column or row number specifications here.  Start IPython or open your own Python script.  Import biaxread and pass the function ReadAscii the name of the text output file from xlook.  The array is now returned and ready to use.

\subsection{Binary Files}
Process the experimental data in xlook and ouput a binary file.  This is done with the `write' command with the syntax \emph{write filename}.  In IPython or your Python script import biaxread and pass the function ReadBin the name of the binary file.  The array is returned and ready to use.

Files that were written in a big-endian format by setting dataendianness to 'big'.  The function call would look like \emph{ReadBin(filename,dataendianness='big')}.

\section{Acknowledgements}
Thank you to Marco Scuderi for using the code and being patient as little issues were worked out.  Please send any bug reports to kd5wxb@gmail.com or as an issue in the github repository.

\newpage

\section{Code}
\begin{lstlisting}

import numpy as np
import struct
import pandas as pd

def ReadAscii(filename,pandas=False):
    """
    Takes a filename containing the text output (with headers) from xlook and
    reads the columns into a rec array or dataframe object for easy data
    processing and access.
    """

    try:
        f = open(filename,'r')
    except:
        print "Error Opening %s" %filename
        return 0

    col_width = 12 # Columns are 12 char wide in header

    # First line of the file is the number of records
    num_recs = f.readline()
    num_recs = int(num_recs.strip('number of records = '))
    print "\nNumber of records: %d" %num_recs

    # Second line is column numbers, we don't care so just count them
    num_cols = f.readline()
    num_cols = num_cols.split('col')
    num_cols = len(num_cols)
    print "Number of columns: %d" %num_cols

    # Third line is the column headings
    col_headings_str = f.readline()
    col_headings_str = col_headings_str[5:-1]
    col_headings = ['row_num'] # Row number the the first (unlabeled) column
    for i in xrange(len(col_headings_str)/12):
        heading = col_headings_str[12*i:12*i+12].strip()
        col_headings.append(heading)

    # Fourth line is column units
    col_units_str = f.readline()
    col_units_str = col_units_str[5:-1]
    col_units=[]
    for i in xrange(len(col_units_str)/12):
        heading = col_units_str[12*i:12*i+12].strip()
        col_units.append(heading)
    col_units = [x for x in col_units if x != '\n']  #Remove newlines

    # Fifth line is number of records per column
    col_recs = f.readline()
    col_recs = col_recs.split('recs')
    col_recs = [int(x) for x in col_recs if x != '\n']

    # Show column units and headings
    print "\n\n-------------------------------------------------"
    print "|%15s|%15s|%15s|" %('Name','Unit','Records')
    print "-------------------------------------------------"
    for column in zip(col_headings,col_units,col_recs):
        print "|%15s|%15s|%15s|" %(column[0],column[1],column[2])
    print "-------------------------------------------------"

    # Read the data into a numpy recarray
    dtype=[]
    #dtype.append(('row_num','float'))
    for name in col_headings:
        dtype.append((name,'float'))
    dtype = np.dtype(dtype)

    data = np.zeros([num_recs,num_cols])

    i=0
    for row in f:
        row_data = row.split()
        for j in xrange(num_cols):
            data[i,j] = row_data[j]
        i+=1

    f.close()

    if pandas==True:
        # If a pandas object is requested, make a data frame
        # indexed on row number and return it
        dfo  = pd.DataFrame(data,columns=col_headings)
        dfo = dfo.set_index('row_num')
        return dfo

    else:
        # Otherwise return the default (Numpy Recarray)
        data_rec = np.rec.array(data,dtype=dtype)
        return data_rec

def ReadBin(filename,dataendianness='little',pandas=False):
    """
    Takes a filename containing the binary output from xlook and
    reads the columns into a rec array or dataframe object for easy
    data processing and access.

    The data section of the file is written in the native format of the machine
    used to produce the file.  Endianness of data is little by default, but may
    be changed to 'big' to accomodate older files or files written on power pc
    chips.
    """

    try:
        f = open(filename,'rb')
    except:
        print "Error Opening %s" %filename
        return 0

    col_headings = []
    col_recs     = []
    col_units    = []

    # Unpack information at the top of the file about the experiment
    name = struct.unpack('20c',f.read(20))
    name = ''.join(str(i) for i in name)
    name = name.split("\0")[0]
    print "\nName: ",name

    # The rest of the header information is written in big endian format

    # Number of records (int)
    num_recs = struct.unpack('>i',f.read(4))
    num_recs = int(num_recs[0])
    print "Number of records: %d" %num_recs

    # Number of columns (int)
    num_cols =  struct.unpack('>i',f.read(4))
    num_cols = int(num_cols[0])
    print "Number of columns: %d" %num_cols

    # Sweep (int) - No longer used
    swp =  struct.unpack('>i',f.read(4))[0]
    print "Swp: ",swp

    # Date/time(int) - No longer used
    dtime =  struct.unpack('>i',f.read(4))[0]
    print "dtime: ",dtime

    # For each possible column (32 maximum columns) unpack its header
    # information and store it.  Only store column headers of columns
    # that contain data.  Use termination at first NUL.
    for i in range(32):

        # Channel name (13 characters)
        chname = struct.unpack('13c',f.read(13))
        chname = ''.join(str(i) for i in chname)
        chname = chname.split("\0")[0]

        # Channel units (13 characters)
        chunits = struct.unpack('13c',f.read(13))
        chunits = ''.join(str(i) for i in chunits)
        chunits = chunits.split("\0")[0]

        # This field is now unused, so we just read past it (int)
        gain = struct.unpack('>i',f.read(4))

        # This field is now unused, so we just read past it (50 characters)
        comment = struct.unpack('50c',f.read(50))

        # Number of elements (int)
        nelem = struct.unpack('>i',f.read(4))
        nelem = int(nelem[0])

        if chname[0:6] == 'no_val':
            continue # Skip Blank Channels
        else:
            col_headings.append(chname)
            col_recs.append(nelem)
            col_units.append(chunits)

    # Show column units and headings
    print "\n\n-------------------------------------------------"
    print "|%15s|%15s|%15s|" %('Name','Unit','Records')
    print "-------------------------------------------------"
    for column in zip(col_headings,col_units,col_recs):
        print "|%15s|%15s|%15s|" %(column[0],column[1],column[2])
    print "-------------------------------------------------"

    # Read the data into a numpy recarray
    dtype=[]
    for name in col_headings:
        dtype.append((name,'double'))
    dtype = np.dtype(dtype)

    data = np.zeros([num_recs,num_cols])

    for col in range(num_cols):
        for row in range(col_recs[col]):
            if dataendianness == 'little':
                data[row,col] = struct.unpack('<d',f.read(8))[0]
            elif dataendianness == 'big':
                data[row,col] = struct.unpack('>d',f.read(8))[0]
            else:
                print "Data endian setting invalid, please check and retry"
                return 0

    data_rec = np.rec.array(data,dtype=dtype)

    f.close()

    if pandas==True:
        # If a pandas object is requested, make a data frame
        # indexed on row number and return it
        dfo  = pd.DataFrame(data,columns=col_headings)
        # Binary didn't give us a row number, so we just let
        # pandas do that and name the index column
        dfo.index.name = 'row_num'
        return dfo

    else:
        # Otherwise return the default (Numpy Recarray)
        data_rec = np.rec.array(data,dtype=dtype)
        return data_rec

\end{lstlisting}

\end{document}


text:
using namespace IdiomMatcher;

DumpDisassemblerAPI::DumpDisassemblerAPI(const std::string &path) : DumpDisassemblerAPI(readDocumentFromFilePath(path),path) { }

DumpDisassemblerAPI::DumpDisassemblerAPI(const IdiomMatcher::DisassemblyDocument &document, const std::string &documentPath) : DisassemblerAPI(InvalidEA, InvalidInstruction), _path(documentPath), _document(document) {
    for (auto line : _document.getDisassemblyLines()) {
        _eaToLineMap.emplace(line->getEA(),line);
    }
}

EA DumpDisassemblerAPI::minEA() const {
    return _document.getMinEA();
}

EA DumpDisassemblerAPI::maxEA() const {
    return _document.getMaxEA();
}

EA DumpDisassemblerAPI::nextEA(const EA &ea) const {
	// returns the first ea that is bigger then ea
	auto iterator = _eaToLineMap.upper_bound(ea);
	if (iterator != _eaToLineMap.end()) {
		return iterator->first;
	}
	return InvalidEA;
}

IdiomMatcher::EA DumpDisassemblerAPI::minInstructionEA() const {
	if (_eaToLineMap.begin() == _eaToLineMap.end()) {
		return InvalidEA;
	} else {
		auto it = _eaToLineMap.begin();
		return it->first;
	}
}

IdiomMatcher::EA DumpDisassemblerAPI::maxInstructionEA() const {
	if (_eaToLineMap.rbegin() == _eaToLineMap.rend()) {
		return InvalidEA;
	} else {
		auto it = _eaToLineMap.rbegin();
		return it->first;
	}
}

Instruction DumpDisassemblerAPI::instructionForEA(const EA &instructionEA) const {
    auto line = lineForEA(instructionEA);
    return line ? *(line->getInstruction()) : InvalidInstruction;
}

std::string DumpDisassemblerAPI::commentForEA(const EA &instructionEA) const {
    auto line = lineForEA(instructionEA);
    return line ? line->getComment() : "";
}

std::string DumpDisassemblerAPI::executableName() const {
    return _document.getBinaryName();
}

std::string DumpDisassemblerAPI::executablePath() const {
    return _path;
}

std::string DumpDisassemblerAPI::executableArchitecture() const {
    return _document.getArchitectureName();
}

std::string DumpDisassemblerAPI::getDisassemblerName() const {
    return _document.getDissassembler();
}

DisassemblyLine_Ref DumpDisassemblerAPI::lineForEA(const EA &ea) const {
    auto iterator = _eaToLineMap.find(ea);
    DisassemblyLine_Ref lineRef = nullptr;
    if (iterator != _eaToLineMap.end()) {
        return iterator->second;
    }
    return lineRef;
}

void DumpDisassemblerAPI::setCurrentEAAndDecodeInstruction(const IdiomMatcher::EA ea) {
    auto line = lineForEA(ea);
	_currentEA = ea;
    _currentInstruction = line ? *(line->getInstruction()) : InvalidInstruction;
    _currentComment = line ? line->getComment() : "";
}


text:
package org.jabref.logic.util;

import java.util.Locale;

/***
 * Operating system (OS) detection
 */
public class OS {
    // https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SystemUtils.html
    private static final String OS_NAME = System.getProperty("os.name", "unknown").toLowerCase(Locale.ROOT);

    public static final boolean LINUX = OS_NAME.startsWith("linux");
    public static final boolean WINDOWS = OS_NAME.startsWith("win");
    public static final boolean OS_X = OS_NAME.startsWith("mac");

    // File separator obtained from system
    public static final String FILE_SEPARATOR = System.getProperty("file.separator");

    // Newlines
    // will be overridden in initialization due to feature #857 @ JabRef.java
    public static String NEWLINE = System.lineSeparator();
}


text:
devel = node[:apps][:devel]

# Google Web Designer
install_app 'webdesigner' do
  profile devel['profiles']['webdesigner']
end

webdesigner_source = "#{node[:apt][:sources_path]}/google-webdesigner.list"

file webdesigner_source do
  action :delete
  only_if { ::File.exist? webdesigner_source }
end


text:
Just a demo for a dashboard programmed with Angular and Material.

## Installation

Install Bower dependencies with

```
npm install
```

Then start the local server with

```console
cd ./app; live-server;
```


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>Matahi</title>

  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/hyde.css">
  <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-144-precomposed.png">
                                 <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

        Home

              Projects

              Publications

              Resume

              Teaching

CIMP analysis

  22 Jul 2015

Introduction

This page contains the pipeline analysis for the "CIMP analysis". Source code is available here. The whole analysis can be computed by running the run_all.R after data processing.

Data processing

Data processing is done by running the run_all.R located in data/src. The procedure is standard (see report).

Data analysis

Part A: Analysis of average CGI+SS patterns

DiseaseList <- c(('BLCA','BRCA','COAD','LUAD','STAD')

1) We first assess CIMP in each tissue using the same methodology on genome-wide methylation profiles by performing hierarchical clustering on the top 5% most variant probes in each disease.

source('fun/analyze_CIMP_all_CGIs.R')
for (DiseaseName in DiseaseList)
{
        print(DiseaseName)
        out <- analyze_CIMP_all_CGIs(DiseaseName=DiseaseName,CIMP.Number = 2, calc.Var= T)
}

2) We assess the robustness of the clusters by varying the number of CGIs considered from 1 to 10 percent. At the same time, we also look at the stability of 3 clusters to assess the existence of a CIMP-low phenotype.

var.list <- c(1,2,5,10)
CIMP.list <- c(2,3)
source('fun/analyze_CIMP_all_CGIs.R')
for (CIMP.Number in CIMP.list)
{
        for (var.thresh in var.list)
        {
                for (DiseaseName in DiseaseList)
                {
                        print(paste0('Analyzing ',DiseaseName,'...', ' with var=',var.thresh,'% and CIMP.number=',CIMP.Number))
                        out <- analyze_CIMP_all_CGIs(DiseaseName=DiseaseName,CIMP.Number = CIMP.Number, calc.Var= F, var.thresh = var.thresh)
                }
        }
}

### 2.A) Look at cluster robustness
source('fun/cluster_analysis.R')
out <- cluster_analysis(DiseaseList=DiseaseList, var.thresh=var.thresh)

### 2.B) Look at cluster robustness given the var.thresh
source('fun/cluster_analysis_var.R')
var.list <- c(1,2,5,10)

for (Disease in DiseaseList)
{
        out <- cluster_analysis_var(DiseaseName=Disease, CIMP.Number=3, var.list= var.list)
}

3) We fix the top 5% CGIs to define the CIMP-signature instead of another cutoff as a tradeoff between relevant probes and having a wide enough coverage. We then analyze whether there is a common panel of probes between the tissue-specific CIMP-signature.

var.thresh <- 5
source('fun/compare_panel_all_CGIs.R')
DiseaseList <- c('BRCA','BLCA','COAD','LUAD','STAD')
out <- compare_panel_all_CGIs(DiseaseList, var.thresh=var.thresh)

We obtain a subset of 89 CGIs common between all the CIMP-signatures.

4) By combining the samples from the different tissues, we then perform clustering on this common CIMP-signature:

source('fun/analyze_CIMP_all_CGIs_bis.R')
out <- analyze_CIMP_all_CGIs_bis(DiseaseList,CIMP.Number = 2)

4) We then analyze whether the methylation aberrations can be associated with transcriptomic or genetic variations:

4.A) Can we assess CIMP from gene expression variations i.e CIMP=f(Gene Expression)?

We propose to tackle this problem using a sparse logistic regression with different formulations:

i. In the first case we predict the CIMP status for each tissue separately:

source('fun/predict_CIMP_GE_glmnet.R')
for (DiseaseName in DiseaseList)
{
        print(DiseaseName)
        out <- predict_CIMP_GE(DiseaseName, var.thresh=var.thresh, CIMP.Number=2, centered=T, scaled=T, intercept=T, n.folds=3, bootstrap=100, cores=10, log_exp=T, balanced=T)
}

ii. In the second case we compute a single classifier for all datasets:

source('fun/predict_CIMP_GE_all.R')
out <- predict_CIMP_GE_all(DiseaseList, var.thresh=var.thresh, CIMP.Number=2, centered=T, scaled=T, intercept=T, n.folds=3, bootstrap=100, cores=10, log_exp=T, balanced=T)

iii. Finally, in the last case we relax the previous constraint (single classifier) by forcing each tissue-specific predictor to have the same non-zero coefficients but allowing the coefficients to vary:

source('fun/predict_CIMP_GE_MT_par.R')
out <- predict_CIMP_GE_MT(DiseaseList, var.thresh=var.thresh, CIMP.Number=2, centered=T, scaled=T, intercept=T,  n.folds=3, bootstrap=100, cores=10, balanced=T)

iv. Summary of the results:

source('fun/analyze_predict_CIMP_GE_MT.R')

4.B) Analysis of the mutations associated with CIMP:

i) We analyzed the the association between CIMP and known reported mutations associated with tissue-specific CIMPs (e.g BRAF, KRAS, IDH1, IDH2, TET2).

source('fun/analyze_mutations.R')
Mutation.List <- c('BRAF','KRAS','IDH1','IDH2','TET2')

analyze_mutations(DiseaseList, Mutation.List=Mutation.List)

ii) We then also searched for other mutations significantly associated with CIMP in all diseases:
{r}
source('fun/analyze_mutations.R')
analyze_mutations(DiseaseList, Mutation.List=Mutation.List)

5) Survival analysis

source('fun/compare_clinical.R')
for (DiseaseName in DiseaseList)
{
        print(DiseaseName)
        out <- compare_clinical(DiseaseName=DiseaseName, var.thresh=var.thresh, CIMP.Number= CIMP.Number)
}


text:
using System.Diagnostics;
using System.Security.Cryptography.Apple;
using Internal.Cryptography;

namespace System.Security.Cryptography
{
    internal sealed class EccSecurityTransforms : IDisposable
    {
        private SecKeyPair _keys;

        public void Dispose()
        {
            _keys?.Dispose();
            _keys = null;
        }

        internal int GenerateKey(ECCurve curve)
        {
            curve.Validate();

            if (!curve.IsNamed)
            {
                throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
            }

            int keySize;

            switch (curve.Oid.Value)
            {
                // secp256r1 / nistp256
                case "1.2.840.10045.3.1.7":
                    keySize = 256;
                    break;
                // secp384r1 / nistp384
                case "1.3.132.0.34":
                    keySize = 384;
                    break;
                // secp521r1 / nistp521
                case "1.3.132.0.35":
                    keySize = 521;
                    break;
                default:
                    throw new PlatformNotSupportedException(
                        SR.Format(SR.Cryptography_CurveNotSupported, curve.Oid.Value));
            }

            GenerateKey(keySize);
            return keySize;
        }

        private SecKeyPair GenerateKey(int keySizeInBits)
        {
            SafeSecKeyRefHandle publicKey;
            SafeSecKeyRefHandle privateKey;

            Interop.AppleCrypto.EccGenerateKey(keySizeInBits, out publicKey, out privateKey);

            SecKeyPair newPair = SecKeyPair.PublicPrivatePair(publicKey, privateKey);
            SetKey(newPair);
            return newPair;
        }

        internal SecKeyPair GetOrGenerateKeys(int keySizeInBits)
        {
            SecKeyPair current = _keys;

            if (current != null)
            {
                return current;
            }

            return GenerateKey(keySizeInBits);
        }

        internal int SetKeyAndGetSize(SecKeyPair keyPair)
        {
            int size = GetKeySize(keyPair);
            SetKey(keyPair);
            return size;
        }

        private void SetKey(SecKeyPair keyPair)
        {
            SecKeyPair current = _keys;
            _keys = keyPair;
            current?.Dispose();
        }

        internal ECParameters ExportParameters(bool includePrivateParameters, int keySizeInBIts)
        {
            SecKeyPair keys = GetOrGenerateKeys(keySizeInBIts);

            SafeSecKeyRefHandle keyHandle = includePrivateParameters ? keys.PrivateKey : keys.PublicKey;

            if (keyHandle == null)
            {
                throw new CryptographicException(SR.Cryptography_OpenInvalidHandle);
            }

            DerSequenceReader keyReader = Interop.AppleCrypto.SecKeyExport(keyHandle, includePrivateParameters);
            ECParameters parameters = new ECParameters();

            if (includePrivateParameters)
            {
                keyReader.ReadPkcs8Blob(ref parameters);
            }
            else
            {
                keyReader.ReadSubjectPublicKeyInfo(ref parameters);
            }

            int size = AsymmetricAlgorithmHelpers.BitsToBytes(keySizeInBIts);

            KeyBlobHelpers.PadOrTrim(ref parameters.Q.X, size);
            KeyBlobHelpers.PadOrTrim(ref parameters.Q.Y, size);

            if (includePrivateParameters)
            {
                KeyBlobHelpers.PadOrTrim(ref parameters.D, size);
            }

            return parameters;
        }

        public int ImportParameters(ECParameters parameters)
        {
            parameters.Validate();

            bool isPrivateKey = parameters.D != null;
            SecKeyPair newKeys;

            if (isPrivateKey)
            {
                // Start with the private key, in case some of the private key fields don't
                // match the public key fields and the system determines an integrity failure.
                //
                // Public import should go off without a hitch.
                SafeSecKeyRefHandle privateKey = ImportKey(parameters);

                ECParameters publicOnly = parameters;
                publicOnly.D = null;

                SafeSecKeyRefHandle publicKey;
                try
                {
                    publicKey = ImportKey(publicOnly);
                }
                catch
                {
                    privateKey.Dispose();
                    throw;
                }

                newKeys = SecKeyPair.PublicPrivatePair(publicKey, privateKey);
            }
            else
            {
                SafeSecKeyRefHandle publicKey = ImportKey(parameters);
                newKeys = SecKeyPair.PublicOnly(publicKey);
            }

            int size = GetKeySize(newKeys);
            SetKey(newKeys);

            return size;
        }

        private static int GetKeySize(SecKeyPair newKeys)
        {
            long size = Interop.AppleCrypto.EccGetKeySizeInBits(newKeys.PublicKey);
            Debug.Assert(size == 256 || size == 384 || size == 521, $"Unknown keysize ({size})");
            return (int)size;
        }

        private static SafeSecKeyRefHandle ImportKey(ECParameters parameters)
        {
            bool isPrivateKey = parameters.D != null;
            byte[] blob = isPrivateKey ? parameters.ToPrivateKeyBlob() : parameters.ToSubjectPublicKeyInfo();

            return Interop.AppleCrypto.ImportEphemeralKey(blob, isPrivateKey);
        }
    }

    internal static class EcKeyBlobHelpers
    {
        private static readonly byte[] s_version1 = { 1 };
        private static readonly byte[][] s_encodedVersion1 = DerEncoder.SegmentedEncodeUnsignedInteger(s_version1);

        private static readonly Oid s_idEcPublicKey = new Oid("1.2.840.10045.2.1", null);
        private static readonly byte[][] s_encodedIdEcPublicKey = DerEncoder.SegmentedEncodeOid(s_idEcPublicKey);

        internal static void ReadPkcs8Blob(this DerSequenceReader reader, ref ECParameters parameters)
        {
            // OneAsymmetricKey ::= SEQUENCE {
            //   version                   Version,
            //   privateKeyAlgorithm       PrivateKeyAlgorithmIdentifier,
            //   privateKey                PrivateKey,
            //   attributes            [0] Attributes OPTIONAL,
            //   ...,
            //   [[2: publicKey        [1] PublicKey OPTIONAL ]],
            //   ...
            // }
            //
            // PrivateKeyInfo ::= OneAsymmetricKey
            //
            // PrivateKey ::= OCTET STRING

            int version = reader.ReadInteger();

            // We understand both version 0 and 1 formats,
            // which are now known as v1 and v2, respectively.
            if (version > 1)
            {
                throw new CryptographicException();
            }

            {
                // Ensure we're reading EC Public Key (well, Private, but the OID says Public)
                DerSequenceReader algorithm = reader.ReadSequence();

                string algorithmOid = algorithm.ReadOidAsString();

                if (algorithmOid != s_idEcPublicKey.Value)
                {
                    throw new CryptographicException();
                }
            }

            byte[] privateKeyBlob = reader.ReadOctetString();

            try
            {
                // ECPrivateKey{CURVES:IOSet} ::= SEQUENCE {
                //   version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
                //   privateKey OCTET STRING,
                //   parameters [0] Parameters{{IOSet}} OPTIONAL,
                //   publicKey  [1] BIT STRING OPTIONAL
                // }
                DerSequenceReader keyReader = new DerSequenceReader(privateKeyBlob);
                version = keyReader.ReadInteger();

                // We understand the version 1 format
                if (version > 1)
                {
                    throw new CryptographicException();
                }

                parameters.D = keyReader.ReadOctetString();

                // Check for context specific 0
                const byte ConstructedContextSpecific =
                    DerSequenceReader.ContextSpecificTagFlag | DerSequenceReader.ConstructedFlag;

                const byte ConstructedContextSpecific0 = (ConstructedContextSpecific | 0);
                const byte ConstructedContextSpecific1 = (ConstructedContextSpecific | 1);

                if (keyReader.PeekTag() != ConstructedContextSpecific0)
                {
                    throw new CryptographicException();
                }

                // Parameters ::= CHOICE {
                //   ecParameters ECParameters,
                //   namedCurve CURVES.&id({ CurveNames}),
                //   implicitlyCA  NULL
                // }
                DerSequenceReader parametersReader = keyReader.ReadSequence();

                if (parametersReader.PeekTag() != (int)DerSequenceReader.DerTag.ObjectIdentifier)
                {
                    throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
                }

                parameters.Curve = ECCurve.CreateFromValue(parametersReader.ReadOidAsString());

                // Check for context specific 1
                if (keyReader.PeekTag() != ConstructedContextSpecific1)
                {
                    throw new CryptographicException();
                }

                keyReader = keyReader.ReadSequence();
                byte[] encodedPoint = keyReader.ReadBitString();
                ReadEncodedPoint(encodedPoint, ref parameters);

                // We don't care about the rest of the blob here, but it's expected to not exist.
            }
            finally
            {
                Array.Clear(privateKeyBlob, 0, privateKeyBlob.Length);
            }
        }

        internal static void ReadSubjectPublicKeyInfo(this DerSequenceReader keyInfo, ref ECParameters parameters)
        {
            // SubjectPublicKeyInfo::= SEQUENCE  {
            //    algorithm AlgorithmIdentifier,
            //    subjectPublicKey     BIT STRING  }
            DerSequenceReader algorithm = keyInfo.ReadSequence();
            string algorithmOid = algorithm.ReadOidAsString();

            // EC Public Key
            if (algorithmOid != s_idEcPublicKey.Value)
            {
                throw new CryptographicException();
            }

            if (algorithm.PeekTag() != (int)DerSequenceReader.DerTag.ObjectIdentifier)
            {
                throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
            }

            parameters.Curve = ECCurve.CreateFromValue(algorithm.ReadOidAsString());

            byte[] encodedPoint = keyInfo.ReadBitString();
            ReadEncodedPoint(encodedPoint, ref parameters);

            // We don't care about the rest of the blob here, but it's expected to not exist.
        }

        internal static byte[] ToSubjectPublicKeyInfo(this ECParameters parameters)
        {
            parameters.Validate();

            if (!parameters.Curve.IsNamed)
            {
                throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
            }

            byte[] pointBlob = GetPointBlob(ref parameters);

            return DerEncoder.ConstructSequence(
                DerEncoder.ConstructSegmentedSequence(
                    s_encodedIdEcPublicKey,
                    DerEncoder.SegmentedEncodeOid(parameters.Curve.Oid)),
                DerEncoder.SegmentedEncodeBitString(pointBlob));
        }

        private static byte[] GetPointBlob(ref ECParameters parameters)
        {
            byte[] pointBlob = new byte[parameters.Q.X.Length + parameters.Q.Y.Length + 1];

            // Uncompressed point
            pointBlob[0] = 0x04;
            Buffer.BlockCopy(parameters.Q.X, 0, pointBlob, 1, parameters.Q.X.Length);
            Buffer.BlockCopy(parameters.Q.Y, 0, pointBlob, 1 + parameters.Q.X.Length, parameters.Q.Y.Length);
            return pointBlob;
        }

        internal static byte[] ToPrivateKeyBlob(this ECParameters parameters)
        {
            parameters.Validate();

            if (!parameters.Curve.IsNamed)
            {
                throw new PlatformNotSupportedException(SR.Cryptography_ECC_NamedCurvesOnly);
            }

            byte[] pointBlob = GetPointBlob(ref parameters);

            // ECPrivateKey{CURVES:IOSet} ::= SEQUENCE {
            //   version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
            //   privateKey OCTET STRING,
            //   parameters [0] Parameters{{IOSet}} OPTIONAL,
            //   publicKey  [1] BIT STRING OPTIONAL
            // }
            return DerEncoder.ConstructSequence(
                s_encodedVersion1,
                DerEncoder.SegmentedEncodeOctetString(parameters.D),
                DerEncoder.ConstructSegmentedContextSpecificValue(
                    0,
                    DerEncoder.SegmentedEncodeOid(parameters.Curve.Oid)),
                DerEncoder.ConstructSegmentedContextSpecificValue(
                    1,
                    DerEncoder.SegmentedEncodeBitString(pointBlob)));
        }

        private static void ReadEncodedPoint(byte[] encodedPoint, ref ECParameters parameters)
        {
            if (encodedPoint == null || encodedPoint.Length < 1)
            {
                throw new CryptographicException();
            }

            byte encoding = encodedPoint[0];

            switch (encoding)
            {
                // Uncompressed encoding (04 xbytes ybytes)
                case 0x04:
                // Hybrid encoding, ~yp == 0 (06 xbytes ybytes)
                case 0x06:
                // Hybrid encoding, ~yp == 1 (07 xbytes ybytes)
                case 0x07:
                    break;
                default:
                    Debug.Fail($"Don't know how to read point encoding {encoding}");
                    throw new CryptographicException();
            }

            // For formats 04, 06, and 07 the X and Y points are equal length, and they should
            // already be left-padded with zeros in cases where they're short.
            int pointEncodingSize = (encodedPoint.Length - 1) / 2;
            byte[] encodedX = new byte[pointEncodingSize];
            byte[] encodedY = new byte[pointEncodingSize];
            Buffer.BlockCopy(encodedPoint, 1, encodedX, 0, pointEncodingSize);
            Buffer.BlockCopy(encodedPoint, 1 + pointEncodingSize, encodedY, 0, pointEncodingSize);
            parameters.Q.X = encodedX;
            parameters.Q.Y = encodedY;
        }
    }
}


text:
import contextlib

import mock

from oslo_config import cfg

from neutron.agent.l3 import config as l3_config
from neutron.agent.metadata import driver as metadata_driver
from neutron.openstack.common import uuidutils
from neutron.tests import base

_uuid = uuidutils.generate_uuid

class TestMetadataDriver(base.BaseTestCase):

    EUID = 123
    EGID = 456

    def setUp(self):
        super(TestMetadataDriver, self).setUp()
        cfg.CONF.register_opts(l3_config.OPTS)
        cfg.CONF.register_opts(metadata_driver.MetadataDriver.OPTS)

    def test_metadata_nat_rules(self):
        rules = ('PREROUTING', '-s 0.0.0.0/0 -d 169.254.169.254/32 '
                 '-p tcp -m tcp --dport 80 -j REDIRECT --to-port 8775')
        self.assertEqual(
            [rules],
            metadata_driver.MetadataDriver.metadata_nat_rules(8775))

    def test_metadata_filter_rules(self):
        rules = [('INPUT', '-m mark --mark 0x1 -j ACCEPT'),
                 ('INPUT', '-s 0.0.0.0/0 -p tcp -m tcp --dport 8775 -j DROP')]
        self.assertEqual(
            rules,
            metadata_driver.MetadataDriver.metadata_filter_rules(8775, '0x1'))

    def test_metadata_mangle_rules(self):
        rule = ('PREROUTING', '-s 0.0.0.0/0 -d 169.254.169.254/32 '
                '-p tcp -m tcp --dport 80 '
                '-j MARK --set-xmark 0x1/%s' %
                metadata_driver.METADATA_ACCESS_MARK_MASK)
        self.assertEqual(
            [rule],
            metadata_driver.MetadataDriver.metadata_mangle_rules('0x1'))

    def _test_spawn_metadata_proxy(self, expected_user, expected_group,
                                   user='', group=''):
        router_id = _uuid()
        router_ns = 'qrouter-%s' % router_id
        metadata_port = 8080
        ip_class_path = 'neutron.agent.linux.ip_lib.IPWrapper'

        cfg.CONF.set_override('metadata_port', metadata_port)
        cfg.CONF.set_override('metadata_proxy_user', user)
        cfg.CONF.set_override('metadata_proxy_group', group)
        cfg.CONF.set_override('log_file', 'test.log')
        cfg.CONF.set_override('debug', True)

        driver = metadata_driver.MetadataDriver
        with contextlib.nested(
                mock.patch('os.geteuid', return_value=self.EUID),
                mock.patch('os.getegid', return_value=self.EGID),
                mock.patch(ip_class_path)) as (geteuid, getegid, ip_mock):
            driver._spawn_metadata_proxy(router_id, router_ns, cfg.CONF)
            ip_mock.assert_has_calls([
                mock.call(namespace=router_ns),
                mock.call().netns.execute([
                    'neutron-ns-metadata-proxy',
                    mock.ANY,
                    mock.ANY,
                    '--router_id=%s' % router_id,
                    mock.ANY,
                    '--metadata_port=%s' % metadata_port,
                    '--metadata_proxy_user=%s' % expected_user,
                    '--metadata_proxy_group=%s' % expected_group,
                    '--debug',
                    '--verbose',
                    '--log-file=neutron-ns-metadata-proxy-%s.log' %
                    router_id
                ], addl_env=None)
            ])

    def test_spawn_metadata_proxy_with_user(self):
        self._test_spawn_metadata_proxy('user', self.EGID, user='user')

    def test_spawn_metadata_proxy_with_uid(self):
        self._test_spawn_metadata_proxy('321', self.EGID, user='321')

    def test_spawn_metadata_proxy_with_group(self):
        self._test_spawn_metadata_proxy(self.EUID, 'group', group='group')

    def test_spawn_metadata_proxy_with_gid(self):
        self._test_spawn_metadata_proxy(self.EUID, '654', group='654')

    def test_spawn_metadata_proxy(self):
        self._test_spawn_metadata_proxy(self.EUID, self.EGID)


text:
@interface NSNumberFormatter_VOKAL_Tests : XCTestCase

@end

@implementation NSNumberFormatter_VOKAL_Tests

- (void)testFormatterIsASingleton
{
    NSNumberFormatter *one = [NSNumberFormatter vok_autoUpdatingCurrencyFormatter];
    NSNumberFormatter *two = [NSNumberFormatter vok_autoUpdatingCurrencyFormatter];

    XCTAssertEqual(one, two);
}

- (void)testIfInUSFormatsProperly
{
    if ([[NSLocale autoupdatingCurrentLocale].localeIdentifier isEqualToString:@"en-US"]) {
        NSNumberFormatter *formatter = [NSNumberFormatter vok_autoUpdatingCurrencyFormatter];
        NSString *threeNinetyNine = [formatter stringFromNumber:@3.99];
        XCTAssertEqual(threeNinetyNine, @"$3.99");
    } //else nothing to test...for now.

    //TODO: Add more schemes testing in different locales if possible.
}

@end


text:
using System;

public class Car
{
    private const double maxFuel = 160;
    private double fuelAmount;

    public Car(int hp, double fuelAmount, Tyre tyre)
    {
        this.Hp = hp;
        this.FuelAmount = fuelAmount;
        this.Tyre = tyre;
    }

    public int Hp { get; }

    public double FuelAmount
    {
        get => fuelAmount;
        private set
        {
            if (value < 0)
            {
                throw new ArgumentException("Out of fuel");
            }

            this.fuelAmount = Math.Min(value, maxFuel);
        }
    }

    public Tyre Tyre { get; private set; }

    public void SetTyre(Tyre tyre)
    {
        this.Tyre = tyre;
    }

    public void Refuel(double amount)
    {
        this.FuelAmount += amount;
    }

    public void BurnFuel(double amount)
    {
        this.FuelAmount -= amount;
    }
}


text:
package com.dropbox.core.v2;

import com.dropbox.core.DbxException;
import com.dropbox.core.DbxDownloader;
import com.dropbox.core.DbxStreamReader;
import com.dropbox.core.NoThrowInputStream;
import com.dropbox.core.util.IOUtil;

import java.io.IOException;
import java.io.OutputStream;

/**
 * The common interface for all builders associated with upload style
 * methods. Use the {@link #start} method to get a {@link DbxDownloader}
 * object, use {@link #run(DbxStreamReader)} for a callback style or
 * use {@link #run(OutputStream)} to directly copy the downloaded data
 * to an output stream.
 *
 * @param <R> The return type of the {@link DbxDownloader}
 */
public abstract class DbxDownloadStyleBuilder<R>
{

    public abstract DbxDownloader<R> start() throws DbxException;

    public R run(OutputStream out) throws DbxException, IOException
    {
        DbxDownloader<R> downloader = null;
        try {
            downloader = start();
            IOUtil.copyStreamToStream(downloader.body, out);
            return downloader.result;
        } finally {
            if (downloader != null) {
                downloader.close();
            }
        }
    }

    public<X extends Throwable> R run(DbxStreamReader<X> handler) throws DbxException, X, IOException
    {
        DbxDownloader<R> downloader = null;
        try {
            downloader = start();
            NoThrowInputStream noThrow = new NoThrowInputStream(downloader.body);
            handler.read(noThrow);
            return downloader.result;
        } catch (NoThrowInputStream.HiddenException ex) {
            throw new DbxException.NetworkIO(ex.underlying);
        } finally {
            if (downloader != null) {
                downloader.close();
            }
        }
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<solver xmlns="https://www.optaplanner.org/xsd/solver" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://www.optaplanner.org/xsd/solver https://www.optaplanner.org/xsd/solver/solver.xsd">
  <!-- To slowly prove there are no bugs in this code -->
  <!--<environmentMode>FULL_ASSERT</environmentMode>-->
  <!-- To solve faster by saturating multiple CPU cores -->
  <!--<moveThreadCount>AUTO</moveThreadCount>-->

  <solutionClass>org.optaplanner.examples.vehiclerouting.domain.VehicleRoutingSolution</solutionClass>
  <entityClass>org.optaplanner.examples.vehiclerouting.domain.Vehicle</entityClass>
  <entityClass>org.optaplanner.examples.vehiclerouting.domain.Customer</entityClass>
  <entityClass>org.optaplanner.examples.vehiclerouting.domain.timewindowed.TimeWindowedCustomer</entityClass>

  <scoreDirectorFactory>
    <!--<easyScoreCalculatorClass>org.optaplanner.examples.vehiclerouting.optional.score.VehicleRoutingEasyScoreCalculator</easyScoreCalculatorClass>-->
    <constraintProviderClass>org.optaplanner.examples.vehiclerouting.score.VehicleRoutingConstraintProvider</constraintProviderClass>
    <!--<incrementalScoreCalculatorClass>org.optaplanner.examples.vehiclerouting.optional.score.VehicleRoutingIncrementalScoreCalculator</incrementalScoreCalculatorClass>-->
    <!--<scoreDrl>org/optaplanner/examples/vehiclerouting/optional/score/vehicleRoutingConstraints.drl</scoreDrl>-->
    <!--<assertionScoreDirectorFactory>-->
      <!--<easyScoreCalculatorClass>org.optaplanner.examples.vehiclerouting.optional.score.VehicleRoutingEasyScoreCalculator</easyScoreCalculatorClass>-->
    <!--</assertionScoreDirectorFactory>-->
    <initializingScoreTrend>ONLY_DOWN</initializingScoreTrend>
  </scoreDirectorFactory>

  <termination>
    <minutesSpentLimit>5</minutesSpentLimit>
  </termination>
  <constructionHeuristic>
  </constructionHeuristic>
  <localSearch>
    <unionMoveSelector>
      <changeMoveSelector/>
      <swapMoveSelector/>
      <subListChangeMoveSelector>
        <selectReversingMoveToo>true</selectReversingMoveToo>
      </subListChangeMoveSelector>
      <subListSwapMoveSelector>
        <selectReversingMoveToo>true</selectReversingMoveToo>
      </subListSwapMoveSelector>
      <!-- TODO use nearby selection to scale out -->
    </unionMoveSelector>
    <acceptor>
      <lateAcceptanceSize>200</lateAcceptanceSize>
    </acceptor>
    <forager>
      <acceptedCountLimit>1</acceptedCountLimit>
    </forager>
  </localSearch>
</solver>


text:
package com.newrelic.servicebroker;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class AbstractDeserializationTest<T> {

    private final ObjectMapper objectMapper = new ObjectMapper();

    private final Class<T> type;

    protected AbstractDeserializationTest(Class<T> type) {
        this.type = type;
    }

    @Test
    public final void deSerialization() throws IOException {
        assertContents(roundTrip(getMap()));
    }

    protected final T roundTrip(Map m) throws IOException {
        String s = this.objectMapper.writeValueAsString(m);
        return this.objectMapper.readValue(s, this.type);
    }

    protected abstract void assertContents(T instance);

    protected abstract Map getMap();

}


text:
package dx.compiler

import java.nio.file.{Path, Paths}

import dx.api._
import dx.compiler.Main.SuccessIR
import dx.core.util.MainUtils.Failure
import org.scalatest.Inside._
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import wdlTools.util.Logger

// These tests involve compilation -without- access to the platform.
//
class InputFileTest extends AnyFlatSpec with Matchers {
  private val dxApi = DxApi(Logger.Quiet)

  private def pathFromBasename(dirname: String, basename: String): Path = {
    val p = getClass.getResource(s"/${dirname}/${basename}").getPath
    Paths.get(p)
  }

  private val dxProject = {
    val p = dxApi.currentProject
    if (p == null)
      throw new Exception("Must be logged in to run this test")
    p
  }

  val cFlags = List("--compileMode", "ir", "-quiet", "--project", dxProject.id)

  // make sure we are logged in

  it should "handle one task and two inputs" in {
    val wdlCode = pathFromBasename("input_file", "add.wdl")
    val inputs = pathFromBasename("input_file", "add_inputs.json")
    Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    ) shouldBe a[SuccessIR]
  }

  it should "deal with a locked workflow" in {
    val wdlCode = pathFromBasename("input_file", "math.wdl")
    val inputs = pathFromBasename("input_file", "math_inputs.json")
    Main.compile(
        List(wdlCode.toString,
             "-inputs",
             inputs.toString,
             "--locked"
             //, "--verbose", "--verboseKey", "GenerateIR"
        ) ++ cFlags
    ) shouldBe a[SuccessIR]
  }

  it should "not compile for several applets without a workflow" in {
    val wdlCode = pathFromBasename("input_file", "several_tasks.wdl")
    val inputs = pathFromBasename("input_file", "several_tasks_inputs.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    )
    inside(retval) {
      case Failure(_, Some(e)) =>
        e.getMessage should include("Cannot generate one input file for 2 tasks")
    }
  }

  it should "one input too many" in {
    val wdlCode = pathFromBasename("input_file", "math.wdl")
    val inputs = pathFromBasename("input_file", "math_inputs2.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString, "--locked")
          ++ cFlags
    )
    inside(retval) {
      case Failure(_, Some(e)) =>
        e.getMessage should include("Could not map all input fields")
    }
  }

  it should "build defaults into applet underneath workflow" in {
    val wdlCode = pathFromBasename("input_file", "population.wdl")
    val defaults = pathFromBasename("input_file", "population_inputs.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-defaults", defaults.toString)
          ++ cFlags
    )
    retval shouldBe a[SuccessIR]
  }

  it should "handle inputs specified in the json file, but missing in the workflow" in {
    val wdlCode = pathFromBasename("input_file", "missing_args.wdl")
    val inputs = pathFromBasename("input_file", "missing_args_inputs.json")

    Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    ) shouldBe a[SuccessIR]

    // inputs as defaults
    Main.compile(
        List(wdlCode.toString, "-defaults", inputs.toString)
          ++ cFlags
    ) shouldBe a[SuccessIR]

    // Input to an applet.
    // Missing argument in a locked workflow should throw an exception.
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString, "--locked")
          ++ cFlags
    )
    inside(retval) {
      case Failure(_, Some(e)) =>
        e.getMessage should include("Could not map all input fields")
    }

    // Missing arguments are legal in an unlocked workflow
    Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    ) shouldBe a[SuccessIR]
  }

  it should "support struct inputs" in {
    val wdlCode = pathFromBasename("struct", "Person.wdl")
    val inputs = pathFromBasename("struct", "Person_input.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    )
    retval shouldBe a[SuccessIR]
  }

  it should "support array of pairs" taggedAs EdgeTest in {
    val wdlCode = pathFromBasename("input_file", "echo_pairs.wdl")
    val inputs = pathFromBasename("input_file", "echo_pairs.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
//        ++ List("--verbose", "--verboseKey", "GenerateIR")
          ++ cFlags
    )
    retval shouldBe a[SuccessIR]
  }

  it should "array of structs" in {
    val wdlCode = pathFromBasename("struct", "array_of_structs.wdl")
    val inputs = pathFromBasename("struct", "array_of_structs_input.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    )
    retval shouldBe a[SuccessIR]
  }

  it should "override default values in input file" in {
    val wdlCode = pathFromBasename("input_file", "override.wdl")
    val inputs = pathFromBasename("input_file", "override_input.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    )
    retval shouldBe a[SuccessIR]
  }

  it should "WDL map input" in {
    val wdlCode = pathFromBasename("input_file", "map_argument.wdl")
    val inputs = pathFromBasename("input_file", "map_argument_input.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    )
    retval shouldBe a[SuccessIR]
  }

  it should "allow file as WDL map key" in {
    val wdlCode = pathFromBasename("input_file", "no_file_key.wdl")
    val inputs = pathFromBasename("input_file", "no_file_key_input.json")
    val retval = Main.compile(
        List(wdlCode.toString, "-inputs", inputs.toString)
          ++ cFlags
    )
    retval shouldBe a[SuccessIR]
  }
}


text:
from azure.cli.testsdk import ScenarioTest, record_only, ResourceGroupPreparer

class TestLogAnalyticsQueryPackScenarios(ScenarioTest):

    @ResourceGroupPreparer(name_prefix='test_log_analytics_query_pack_crud', location="eastus2")
    def test_log_analytics_query_pack_crud(self, resource_group):
        self.kwargs.update({
            'rg': resource_group,
            'name': self.create_random_name('clitest', 20),
        })

        response = self.cmd('monitor log-analytics query-pack create -g {rg} -n {name} -l eastus2', checks=[
            self.check('name', "{name}"),
        ]).get_output_in_json()
        self.kwargs['id'] = response['id']

        self.cmd('monitor log-analytics query-pack show -g {rg} -n {name}', checks=[
            self.check('name', "{name}")
        ])

        self.cmd('monitor log-analytics query-pack show --ids {id}', checks=[
            self.check('name', "{name}")
        ])

        self.cmd("monitor log-analytics query-pack update -g {rg} -n {name} --tags flag1=v1", checks=[
            self.check('tags.flag1', 'v1')
        ])

        self.cmd("monitor log-analytics query-pack list", checks=[
            self.check('length(@)', 1)
        ])

        self.cmd("monitor log-analytics query-pack list -g {rg}", checks=[
            self.check('length(@)', 1)
        ])

        self.cmd("monitor log-analytics query-pack delete -g {rg} -n {name} --yes")

        self.cmd("monitor log-analytics query-pack list -g {rg}", checks=[
            self.check('length(@)', 0)
        ])

    @ResourceGroupPreparer(name_prefix='test_log_analytics_query_pack_query_crud', location="eastus2")
    def test_log_analytics_query_pack_query_crud(self, resource_group):
        self.kwargs.update({
            'rg': resource_group,
            'pack_name': self.create_random_name('clitest', 20),
            'query_id': '5865fd70-3d2c-4c83-9423-7d204c3b3f90'
        })

        response = self.cmd('monitor log-analytics query-pack create -g {rg} -n {pack_name} -l eastus2', checks=[
            self.check('name', "{pack_name}"),
        ]).get_output_in_json()
        self.kwargs['pack_id'] = response['id']

        response = self.cmd('monitor log-analytics query-pack query create --query-id {query_id} -g {rg} '
                            '--query-pack-name {pack_name} --display-name query-test '
                            '--body "let newExceptionsTimeRange = 1d;let timeRangeToCheckBefore = 7d;exceptions | where timestamp < ago(timeRangeToCheckBefore) | summarize count() by problemId | join kind= rightanti (exceptions | where timestamp >= ago(newExceptionsTimeRange) | extend stack = tostring(details[0].rawStack) | summarize count(), dcount(user_AuthenticatedId), min(timestamp), max(timestamp), any(stack) by problemId) on problemId | order by  count_ desc" '
                            '--description "this is for test" '
                            '--categories "[network,monitor]" '
                            '--resource-types "[microsoft.network/loadbalancers,microsoft.insights/autoscalesettings]" '
                            '--solutions "[networkmonitoring]" '
                            '--tags "{{version:[v2022-01-01,v2021-12-01]}}"', checks=[
            self.check('properties.id', '{query_id}'),
            self.check('properties.related.categories', ['network', 'monitor']),
            self.check('properties.related.resourceTypes', ['microsoft.network/loadbalancers', 'microsoft.insights/autoscalesettings']),
            self.check('properties.related.solutions', ['networkmonitoring']),
            self.check('properties.tags', {"version": ["v2022-01-01", "v2021-12-01"]}),
        ]).get_output_in_json()
        self.kwargs['id'] = response['id']

        self.cmd('monitor log-analytics query-pack query show --ids {id}', checks=[self.check('properties.id', '{query_id}'),
            self.check('properties.related.categories', ['network', 'monitor']),
            self.check('properties.related.resourceTypes', ['microsoft.network/loadbalancers', 'microsoft.insights/autoscalesettings']),
            self.check('properties.related.solutions', ['networkmonitoring']),
            self.check('properties.tags', {"version": ["v2022-01-01", "v2021-12-01"]}),
        ])

        self.cmd('monitor log-analytics query-pack query show --query-id {query_id} -g {rg} --query-pack-name {pack_name}', checks=[self.check('properties.id', '{query_id}'),
            self.check('properties.related.categories', ['network', 'monitor']),
            self.check('properties.related.resourceTypes', ['microsoft.network/loadbalancers', 'microsoft.insights/autoscalesettings']),
            self.check('properties.related.solutions', ['networkmonitoring']),
            self.check('properties.tags', {"version": ["v2022-01-01", "v2021-12-01"]}),
        ])

        self.cmd(
            'monitor log-analytics query-pack query update --query-id {query_id} -g {rg} --body "heartbeat | take 10" --query-pack-name {pack_name} --categories [2]=databases --tags version[0]=null',
            checks=[self.check('properties.id', '{query_id}'),
                    self.check('properties.related.categories', ['network', 'monitor', 'databases']),
                    self.check('properties.related.resourceTypes',
                               ['microsoft.network/loadbalancers', 'microsoft.insights/autoscalesettings']),
                    self.check('properties.related.solutions', ['networkmonitoring']),
                    self.check('properties.tags', {"version": ["v2021-12-01"]}),
                    self.check('properties.body', "heartbeat | take 10")
                    ])

        self.cmd('monitor log-analytics query-pack query list -g {rg} --query-pack-name {pack_name}', checks=[
            self.check('length(@)', 1),
            self.check('[0].properties.body', "heartbeat | take 10")
        ])

        self.cmd('monitor log-analytics query-pack query list -g {rg} --query-pack-name {pack_name} --include-body false', checks=[
            self.check('length(@)', 1),
            self.check('[0].properties.body', None)
        ])

        self.cmd('monitor log-analytics query-pack query search -g {rg} --query-pack-name {pack_name} '
                 '--categories network', checks=[
            self.check('length(@)', 1),
            self.check('[0].properties.id', '{query_id}'),
            self.check('[0].properties.related.categories', ['network', 'monitor', 'databases']),
            self.check('[0].properties.related.resourceTypes',
                       ['microsoft.network/loadbalancers', 'microsoft.insights/autoscalesettings']),
            self.check('[0].properties.related.solutions', ['networkmonitoring']),
            self.check('[0].properties.tags', {"version": ["v2021-12-01"]}),
            self.check('[0].properties.body', "heartbeat | take 10")
        ])

        self.cmd('monitor log-analytics query-pack query search -g {rg} --query-pack-name {pack_name} '
                 '--resource-types microsoft.insights/autoscalesettings microsoft.network/loadbalancers ', checks=[
            self.check('length(@)', 1),
            self.check('[0].properties.id', '{query_id}'),
            self.check('[0].properties.related.categories', ['network', 'monitor', 'databases']),
            self.check('[0].properties.related.resourceTypes',
                       ['microsoft.network/loadbalancers', 'microsoft.insights/autoscalesettings']),
            self.check('[0].properties.related.solutions', ['networkmonitoring']),
            self.check('[0].properties.tags', {"version": ["v2021-12-01"]}),
            self.check('[0].properties.body', "heartbeat | take 10")
        ])

        self.cmd('monitor log-analytics query-pack query search -g {rg} --query-pack-name {pack_name} '
                 '--solutions "[networkmonitoring]"', checks=[
            self.check('length(@)', 1),
            self.check('[0].properties.id', '{query_id}'),
            self.check('[0].properties.related.categories', ['network', 'monitor', 'databases']),
            self.check('[0].properties.related.resourceTypes',
                       ['microsoft.network/loadbalancers', 'microsoft.insights/autoscalesettings']),
            self.check('[0].properties.related.solutions', ['networkmonitoring']),
            self.check('[0].properties.tags', {"version": ["v2021-12-01"]}),
            self.check('[0].properties.body', "heartbeat | take 10")
        ])

        self.cmd('monitor log-analytics query-pack query search -g {rg} --query-pack-name {pack_name} '
                 '--tags version="[v2021-12-01]"', checks=[
            self.check('length(@)', 1),
            self.check('[0].properties.id', '{query_id}'),
            self.check('[0].properties.related.categories', ['network', 'monitor', 'databases']),
            self.check('[0].properties.related.resourceTypes',
                       ['microsoft.network/loadbalancers', 'microsoft.insights/autoscalesettings']),
            self.check('[0].properties.related.solutions', ['networkmonitoring']),
            self.check('[0].properties.tags', {"version": ["v2021-12-01"]}),
            self.check('[0].properties.body', "heartbeat | take 10")
        ])

        self.cmd('monitor log-analytics query-pack query delete --ids {id} --yes')
        self.cmd('monitor log-analytics query-pack query list -g {rg} --query-pack-name {pack_name}', checks=[
            self.check('length(@)', 0),
        ])


text:
package com.dslplatform.json;

import com.dslplatform.json.runtime.ArrayFormatDescription;
import com.dslplatform.json.runtime.Settings;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

public class ArrayChecksTest {

	static class MyClass {
		public int x;
		public String s;
		public long y;
	}

	private final DslJson dslJson = new DslJson();

	public ArrayChecksTest() {
		ArrayFormatDescription<MyClass, MyClass> description = ArrayFormatDescription.create(
				MyClass.class,
				MyClass::new,
				new JsonWriter.WriteObject[] {
						Settings.<MyClass, Integer>createArrayEncoder(c -> c.x, dslJson, int.class),
						Settings.<MyClass, String>createArrayEncoder(c -> c.s, dslJson, String.class),
						Settings.<MyClass, Long>createArrayEncoder(c -> c.y, NumberConverter.LONG_WRITER)
				},
				new JsonReader.BindObject[] {
						Settings.<MyClass, Integer>createArrayDecoder((c, v) -> c.x = v, NumberConverter.INT_READER),
						Settings.<MyClass, String>createArrayDecoder((c, v) -> c.s = v, dslJson, String.class),
						Settings.<MyClass, Long>createArrayDecoder((c, v) -> c.y = v, dslJson, long.class)
				}
		);
		dslJson.registerBinder(MyClass.class, description);
		dslJson.registerReader(MyClass.class, description);
	}

	@Test
	public void propertyMissing() {
		try {
			dslJson.deserialize(MyClass.class, "[]".getBytes(), 2);
			Assert.fail("Expecting exception");
		} catch (IOException ex) {
			Assert.assertTrue(ex.getMessage().contains("Error parsing number at position: 1"));
		}
	}

	@Test
	public void extraProperties() {
		try {
			byte[] bytes = "[1,\"t\",3,4]".getBytes("UTF-8");
			dslJson.deserialize(MyClass.class, bytes, bytes.length);
			Assert.fail("Expecting exception");
		} catch (IOException ex) {
			Assert.assertEquals("Expecting ']' to end decoding com.dslplatform.json.ArrayChecksTest$MyClass. Found 4 at position: 9, following: `[1,\"t\",3,`, before: `4]`", ex.getMessage());
		}
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/Graham.iml" filepath="$PROJECT_DIR$/Graham.iml" />
    </modules>
  </component>
</project>


text:
import React from 'react'
import { Card } from 'semantic-ui-react'

const items = [
  {
    header: 'Project Report - April',
    description: 'Leverage agile frameworks to provide a robust synopsis for high level overviews.',
    meta: 'ROI: 30%',
  },
  {
    header: 'Project Report - May',
    description: 'Bring to the table win-win survival strategies to ensure proactive domination.',
    meta: 'ROI: 34%',
  },
  {
    header: 'Project Report - June',
    description: 'Capitalise on low hanging fruit to identify a ballpark value added activity to beta test.',
    meta: 'ROI: 27%',
  },
]

const CardExampleGroupProps = () => (
  <Card.Group items={items} />
)

export default CardExampleGroupProps


text:
drain
=====

|image0| |image1| |image2| |image4|

Drain is a lightweight framework for writing reproducible data science workflows in Python. The core features are:

* Turn a Python workflow (`DAG <https://en.wikipedia.org/wiki/Directed_acyclic_graph#Data_processing_networks>`_) into steps that can be run by a tool like `make`.

* Transparently pass the results of one step as the input to another, handling any caching that the user requests using efficient tools like `HDF <http://www.pytables.org/>`_ and `joblib <https://pythonhosted.org/joblib/generated/joblib.dump.html>`_.

* Enable easy *parallel* execution of workflows.

* Execute only those steps that are determined to be necessary based on timestamps (both source code and data) and dependencies, virtually guaranteeing *reproducibility* of results and efficient development.

Drain is designed around these principles:

* *Simplicity*: drain is very lightweight and easy to use. The core is just a few hundred lines of code. The steps you write in drain get executed with minimal overhead, making drain workflows easy to debug and manage.

* *Reusability*: Drain leverages mature tools `drake <https://github.com/Factual/drake/>`_ to execute workflows. Drain provides a library of steps for data science workflows including feature generation and selection, model fitting and comparison.

* *Generality*: Virtually any workflow can be realized in drain. The core was written with extensibility in mind so new storage backends and job schedulers, for example, will be easy to incorporate.

.. |image0| image:: https://img.shields.io/pypi/v/drain.svg
   :target: https://pypi.python.org/pypi/drain
.. |image1| image:: https://api.travis-ci.org/potash/drain.svg
   :target: https://travis-ci.org/potash/drain
.. |image2| image:: https://readthedocs.org/projects/drain/badge/?version=latest
   :target: https://drain.readthedocs.io/en/latest/?badge=latest
.. |image4| image:: https://img.shields.io/badge/License-MIT-yellow.svg
   :target: https://opensource.org/licenses/MIT


text:
<?php

declare(strict_types=1);

namespace spec\Sylius\Bundle\CoreBundle\Doctrine\ORM\Handler;

use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\ResourceBundle\Controller\ResourceDeleteHandlerInterface;
use Sylius\Component\Resource\Exception\DeleteHandlingException;
use Sylius\Component\Resource\Model\ResourceInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;

final class ResourceDeleteHandlerSpec extends ObjectBehavior
{
    function let(ResourceDeleteHandlerInterface $decoratedHandler, EntityManagerInterface $entityManager): void
    {
        $this->beConstructedWith($decoratedHandler, $entityManager);
    }

    function it_implements_resource_delete_handler_interface(): void
    {
        $this->shouldImplement(ResourceDeleteHandlerInterface::class);
    }

    function it_uses_decorated_handler_to_handle_resource_deletion(
        ResourceDeleteHandlerInterface $decoratedHandler,
        EntityManagerInterface $entityManager,
        RepositoryInterface $repository,
        ResourceInterface $resource,
    ): void {
        $entityManager->beginTransaction()->shouldBeCalled();
        $decoratedHandler->handle($resource, $repository)->shouldBeCalled();
        $entityManager->commit()->shouldBeCalled();

        $this->handle($resource, $repository);
    }

    function it_throws_delete_handling_exception_if_foreign_key_constraint_violation_exception_occurs_while_deleting_resource(
        ResourceDeleteHandlerInterface $decoratedHandler,
        EntityManagerInterface $entityManager,
        RepositoryInterface $repository,
        ResourceInterface $resource,
    ): void {
        $entityManager->beginTransaction()->shouldBeCalled();
        $decoratedHandler->handle($resource, $repository)->willThrow(ForeignKeyConstraintViolationException::class);
        $entityManager->commit()->shouldNotBeCalled();
        $entityManager->rollback()->shouldBeCalled();

        $this->shouldThrow(DeleteHandlingException::class)->during('handle', [$resource, $repository]);
    }

    function it_throws_delete_handling_exception_if_something_gone_wrong_with_orm_while_deleting_resource(
        ResourceDeleteHandlerInterface $decoratedHandler,
        EntityManagerInterface $entityManager,
        RepositoryInterface $repository,
        ResourceInterface $resource,
    ): void {
        $entityManager->beginTransaction()->shouldBeCalled();
        $decoratedHandler->handle($resource, $repository)->willThrow(ORMException::class);
        $entityManager->commit()->shouldNotBeCalled();
        $entityManager->rollback()->shouldBeCalled();

        $this->shouldThrow(DeleteHandlingException::class)->during('handle', [$resource, $repository]);
    }
}


text:
#include <QHBoxLayout>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPushButton>
#include <qwinwidget.h>

#include <windows.h>

HWND winId = 0;

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_LBUTTONUP:
	{
	    QWinWidget w(hWnd, 0, 0);
	    w.showCentered();
	    QMessageBox mb("Qt on Win32 - modal",
		"Is this dialog modal?",
		QMessageBox::NoIcon,
		QMessageBox::Yes | QMessageBox::Default,
		QMessageBox::No  | QMessageBox::Escape,
		QMessageBox::NoButton, &w);
	    int result = mb.exec();
	    Q_UNUSED(result);
	}
	break;

    case WM_RBUTTONUP:
	{
	    QWinWidget *w = new QWinWidget(hWnd, 0, 0);
	    w->showCentered();
	    QMessageBox *mb = new QMessageBox("Qt on Win32 - modeless",
		"Is this dialog modal?",
		QMessageBox::NoIcon,
		QMessageBox::Yes | QMessageBox::Default,
		QMessageBox::No  | QMessageBox::Escape,
		QMessageBox::NoButton, w);
            mb->setModal(false);
            mb->setAttribute(Qt::WA_DeleteOnClose);
	    mb->show();
	}
	break;

    case WM_KEYDOWN:
        if (wParam != VK_TAB)
            return DefWindowProc(hWnd, message, wParam, lParam);

        SetFocus(winId);

        break;

    case WM_SETFOCUS:
        {
            QString str("Got focus");
            QWidget *widget = QWidget::find((WId)HWND(wParam));
            if (widget)
                str += QString(" from %1 (%2)").arg(widget->objectName()).arg(widget->metaObject()->className());
            str += "\n";
            OutputDebugStringA(str.toLocal8Bit().data());
        }
        break;

    case WM_KILLFOCUS:
        {
            QString str("Lost focus");
            QWidget *widget = QWidget::find((WId)HWND(wParam));
            if (widget)
                str += QString(" to %1 (%2)").arg(widget->objectName()).arg(widget->metaObject()->className());
            str += "\n";

            OutputDebugStringA(str.toLocal8Bit().data());
        }
        break;

    case WM_DESTROY:
	PostQuitMessage(0);
	break;

    default:
	return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}

int APIENTRY wWinMain(HINSTANCE hInstance,
		      HINSTANCE /*hPrevInstance*/,
		      LPTSTR    /*lpCmdLine*/,
		      int       nCmdShow)
{
    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);

    wcex.style		= CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc	= (WNDPROC)WndProc;
    wcex.cbClsExtra	= 0;
    wcex.cbWndExtra	= 0;
    wcex.hInstance	= hInstance;
    wcex.hIcon		= NULL;
    wcex.hCursor	= LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName	= NULL;
    wcex.lpszClassName	= L"qtest";
    wcex.hIconSm	= NULL;

    ATOM windowClass = RegisterClassEx(&wcex);

    HWND hWnd = CreateWindow((TCHAR*)windowClass, L"Windows Migration Framework Example",
	WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, 0, 0, hInstance, 0);
    if (!hWnd)
	return FALSE;

    int argc = 0;
    QApplication a(argc, 0);

    QWinWidget win(hWnd);
    winId = (HWND)win.winId();
    QHBoxLayout hbox(&win);
    hbox.setSpacing(5);
    hbox.setMargin(0);
    QPushButton *pb = new QPushButton("Qt command button", &win);
    pb->setObjectName("pb");
    hbox.addWidget(pb);
    QLabel *label = new QLabel("Some label", &win);
    label->setObjectName("label");
    hbox.addWidget(label);
    QLineEdit *le1 = new QLineEdit(&win);
    le1->setObjectName("le1");
    hbox.addWidget(le1);
    QLineEdit *le2 = new QLineEdit(&win);
    le1->setObjectName("le2");
    hbox.addWidget(le2);
    QLineEdit *le3 = new QLineEdit(&win);
    le1->setObjectName("le3");
    hbox.addWidget(le3);

    win.move(0, 0);
    win.show();

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    return a.exec();
}


text:
package com.intellij.ide.actions;

import com.intellij.ide.IdeBundle;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Caret;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
import com.intellij.openapi.editor.actions.TextComponentEditorAction;
import com.intellij.openapi.project.DumbAware;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class SelectAllAction extends TextComponentEditorAction implements DumbAware {
  public SelectAllAction() {
    super(new Handler());
  }

  private static class Handler extends EditorActionHandler {
    @Override
    public void doExecute(@NotNull Editor editor, @Nullable Caret caret, DataContext dataContext) {
      CommandProcessor processor = CommandProcessor.getInstance();
      processor.executeCommand(CommonDataKeys.PROJECT.getData(dataContext),
                               () -> editor.getSelectionModel().setSelection(0, editor.getDocument().getTextLength()), IdeBundle.message("command.select.all"), null);
    }
  }

  @Override
  public void update(@NotNull AnActionEvent event){
    Presentation presentation = event.getPresentation();
    Editor editor = TextComponentEditorAction.getEditorFromContext(event.getDataContext());
    presentation.setEnabled(editor != null);
  }
}