text:
package no._0d.smooze.data;

import java.util.List;

public class RegistrationRestModel {

    RegTypeEnum type;

    long time;

    public RegistrationRestModel(RegTypeEnum type, long time) {
        this.type = type;
        this.time = time;
    }

    public RegTypeEnum getType() {
        return type;
    }

    public long getTime() {
        return time;
    }
}


text:
#pragma once

#include <Param.hpp>
#include <common/dispatch.hpp>
#include <common/kernel_cache.hpp>
#include <debug_opencl.hpp>
#include <kernel/config.hpp>
#include <kernel_headers/gradient.hpp>
#include <math.hpp>
#include <traits.hpp>

#include <string>
#include <vector>

namespace opencl {
namespace kernel {

template<typename T>
void gradient(Param grad0, Param grad1, const Param in) {
    constexpr int TX = 32;
    constexpr int TY = 8;

    std::vector<TemplateArg> targs = {
        TemplateTypename<T>(),
    };
    std::vector<std::string> options = {
        DefineKeyValue(T, dtype_traits<T>::getName()),
        DefineValue(TX),
        DefineValue(TY),
        DefineKeyValue(ZERO, af::scalar_to_option(scalar<T>(0))),
        DefineKeyValue(CPLX, static_cast<int>(af::iscplx<T>())),
    };
    options.emplace_back(getTypeBuildDefinition<T>());

    auto gradOp =
        common::getKernel("gradient", {gradient_cl_src}, targs, options);

    cl::NDRange local(TX, TY, 1);

    int blocksPerMatX = divup(in.info.dims[0], TX);
    int blocksPerMatY = divup(in.info.dims[1], TY);
    cl::NDRange global(local[0] * blocksPerMatX * in.info.dims[2],
                       local[1] * blocksPerMatY * in.info.dims[3], 1);

    gradOp(cl::EnqueueArgs(getQueue(), global, local), *grad0.data, grad0.info,
           *grad1.data, grad1.info, *in.data, in.info, blocksPerMatX,
           blocksPerMatY);
    CL_DEBUG_FINISH(getQueue());
}
}  // namespace kernel
}  // namespace opencl

redpajama_set_name: RedPajamaGithub


text:
Images used for creating the favicon:

* https://openclipart.org/detail/227636/modern-minimalist-mobile-icon
* https://openclipart.org/detail/202776/person-icon
* https://pixabay.com/en/burgseeli-mountain-lake-switzerland-906639/

All licensed under Public Domain.

The favicon.ico, favicon.svg and all derivates of it are licensed under [CC-BY 3.0](https://creativecommons.org/licenses/by/3.0/) by rugk.


text:
namespace Client.Logic.Menus
{
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Text;

    using Client.Logic.Graphics;

    using SdlDotNet.Widgets;
    using Client.Logic.Missions;
    using Client.Logic.Network;

    class mnuJobDescription : Logic.Widgets.BorderedPanel, Core.IMenu
    {
        #region Fields

        Label lblDescription;
        PictureBox picCreator;
        Label lblCreatorName;
        Label lblNullTitle;
        Label lblTitle;
        Label lblSummary;
        Label lblObjective;
        Label lblGoal;
        Label lblDifficulty;
        PictureBox picReward;
        Label lblReward;
        Label lblPressEnter;

        #endregion Fields

        #region Constructors

        public mnuJobDescription(string name, Job job, bool missionBoardView)
            : base(name) {

            base.Size = new Size(300, 460);
            base.MenuDirection = Enums.MenuDirection.Vertical;
            if (missionBoardView) {
                base.Location = new Point(305, 10);
            } else {
                base.Location = new Point(160, 10);
            }

            lblDescription = new Label("lblDescription");
            lblDescription.Font = FontManager.LoadFont("PMU", 48);
            lblDescription.AutoSize = true;
            lblDescription.Text = "Description";
            lblDescription.ForeColor = Color.WhiteSmoke;
            lblDescription.Location = new Point(20, 0);

            lblNullTitle = new Label("lblNullTitle");
            lblNullTitle.Font = FontManager.LoadFont("PMU", 32);
            lblNullTitle.Size = new Size(this.Width - 20, 40);
            lblNullTitle.ForeColor = Color.Gray;
            lblNullTitle.Text = "-----";
            lblNullTitle.Location = new Point(20, 50);

            picCreator = new PictureBox("picCreator");
            picCreator.Size = new Size(40, 40);
            picCreator.Location = new Point(30, 50);
            picCreator.BorderStyle = SdlDotNet.Widgets.BorderStyle.FixedSingle;
            picCreator.BorderWidth = 1;

            lblTitle = new Label("lblTitle");
            lblTitle.Font = FontManager.LoadFont("PMU", 16);
            lblTitle.AutoSize = true;
            lblTitle.ForeColor = Color.WhiteSmoke;
            lblTitle.Location = new Point(picCreator.X + picCreator.Width + 10, picCreator.Y);

            lblCreatorName = new Label("lblCreatorName");
            lblCreatorName.Font = FontManager.LoadFont("PMU", 16);
            lblCreatorName.AutoSize = true;
            lblCreatorName.ForeColor = Color.WhiteSmoke;
            lblCreatorName.Location = new Point(picCreator.X + picCreator.Width + 10, picCreator.Y + 20);

            lblSummary = new Label("lblSummary");
            lblSummary.Font = FontManager.LoadFont("PMU", 16);
            lblSummary.Size = new Size(this.Width - 50, 120);
            lblSummary.ForeColor = Color.WhiteSmoke;
            lblSummary.Location = new Point(lblNullTitle.X, picCreator.Y + picCreator.Height + 4);

            lblObjective = new Label("lblObjective");
            lblObjective.Font = FontManager.LoadFont("PMU", 16);
            lblObjective.Size = new Size(this.Width - 20, 40);
            lblObjective.ForeColor = Color.WhiteSmoke;
            lblObjective.Location = new Point(lblNullTitle.X, lblNullTitle.Y + lblNullTitle.Height + 5);

            lblGoal = new Label("lblGoal");
            lblGoal.Font = FontManager.LoadFont("PMU", 16);
            lblGoal.Size = new Size(this.Width - 20, 40);
            lblGoal.ForeColor = Color.WhiteSmoke;
            lblGoal.Location = new Point(lblNullTitle.X, lblSummary.Y + lblSummary.Height + 5);

            lblDifficulty = new Label("lblDifficulty");
            lblDifficulty.Font = FontManager.LoadFont("PMU", 16);
            lblDifficulty.AutoSize = true;
            lblDifficulty.ForeColor = Color.WhiteSmoke;
            lblDifficulty.Location = new Point(lblNullTitle.X, lblGoal.Y + 20);

            picReward = new PictureBox("picReward");
            picReward.Size = new Size(32, 32);
            picReward.BackColor = Color.Transparent;
            picReward.Location = new Point(lblNullTitle.X, lblDifficulty.Y + 24);

            lblReward = new Label("lblMissionReward");
            lblReward.Font = FontManager.LoadFont("PMU", 16);
            lblReward.Size = new Size(this.Width - 20, 40);
            lblReward.ForeColor = Color.WhiteSmoke;
            lblReward.Location = new Point(lblNullTitle.X + 32, lblDifficulty.Y + 20);

            lblPressEnter = new Label("lblPressEnter");
            lblPressEnter.Font = FontManager.LoadFont("PMU", 32);
            lblPressEnter.Size = new Size(this.Width - 20, 40);
            lblPressEnter.ForeColor = Color.WhiteSmoke;
            lblPressEnter.Text = "Press Enter to take this job.";
            lblPressEnter.Location = new Point(lblNullTitle.X, this.Height - 50);

            this.AddWidget(lblDescription);
            this.AddWidget(picCreator);
            this.AddWidget(lblTitle);
            this.AddWidget(lblCreatorName);
            this.AddWidget(lblNullTitle);
            this.AddWidget(lblSummary);
            //this.AddWidget(lblObjective);
            this.AddWidget(lblGoal);
            this.AddWidget(lblDifficulty);
            this.AddWidget(picReward);
            this.AddWidget(lblReward);
            if (missionBoardView) {
                this.AddWidget(lblPressEnter);
            }

            UpdateJob(job);
        }

        #endregion Constructors

        #region Properties

        public Logic.Widgets.BorderedPanel MenuPanel {
            get { return this; }
        }

        public bool Modal {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        public void UpdateJob(Job job) {
            if (job == null) {
                lblDifficulty.Visible = false;
                picCreator.Visible = false;
                lblCreatorName.Visible = false;
                lblNullTitle.Visible = true;
                lblTitle.Visible = false;
                lblSummary.Visible = false;
                lblGoal.Visible = false;
                picReward.Visible = false;
                lblReward.Visible = false;
                lblPressEnter.Visible = false;
            } else {
                lblDifficulty.Visible = true;
                lblDifficulty.Text = "Difficulty: " + MissionManager.DifficultyToString(job.Difficulty) + " (" + MissionManager.DetermineMissionExpReward(job.Difficulty) + " Explorer Points)";
                picCreator.Visible = true;
                picCreator.Image = Logic.Graphics.GraphicsManager.GetMugshot(job.ClientSpecies, job.ClientForm, 0, 0).GetEmote(0);//Tools.CropImage(Logic.Graphics.GraphicsManager.Speakers, new Rectangle((this.creatorMugshot % 15) * 40, (this.creatorMugshot / 15) * 40, 40, 40));
                lblTitle.Visible = true;
                lblTitle.Text = "Title: " + job.Title;
                lblCreatorName.Visible = true;
                lblCreatorName.Text = "From: " + Pokedex.PokemonHelper.Pokemon[job.ClientSpecies-1].Name;
                lblNullTitle.Visible = false;
                lblSummary.Visible = true;
                lblSummary.Text = "Summary: \n" + job.Summary;

                lblGoal.Visible = true;
                lblGoal.Text = "Place: " + job.GoalName;
                picReward.Visible = true;
                picReward.Image = Tools.CropImage(GraphicsManager.Items, new Rectangle((Items.ItemHelper.Items[job.RewardNum].Pic - (int)(Items.ItemHelper.Items[job.RewardNum].Pic / 6) * 6) * Constants.TILE_WIDTH, (int)(Items.ItemHelper.Items[job.RewardNum].Pic / 6) * Constants.TILE_WIDTH, Constants.TILE_WIDTH, Constants.TILE_HEIGHT));
                lblReward.Visible = true;
                if (Items.ItemHelper.Items[job.RewardNum].StackCap > 0) {
                    lblReward.Text = "Reward:\n" + job.RewardAmount + " " + Items.ItemHelper.Items[job.RewardNum].Name;
                } else {
                    lblReward.Text = "Reward:\n" + Items.ItemHelper.Items[job.RewardNum].Name;
                }
                lblPressEnter.Visible = true;
            }
        }

        public override void OnKeyboardDown(SdlDotNet.Input.KeyboardEventArgs e) {
            base.OnKeyboardDown(e);
            switch (e.Key) {
                case SdlDotNet.Input.Key.Backspace: {
                        Menus.MenuSwitcher.ShowJobListMenu();
                        Music.Music.AudioPlayer.PlaySoundEffect("beep3.wav");
                    }
                    break;
                case SdlDotNet.Input.Key.Return: {
                        Menus.MenuSwitcher.ShowJobListMenu();
                        Music.Music.AudioPlayer.PlaySoundEffect("beep3.wav");
                    }
                    break;
            }
        }

        #endregion Methods
    }
}


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

<title>KeyRange (apache-cassandra API)</title>
<meta name="date" content="2015-06-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.thrift

Class KeyRange

java.lang.Object

org.apache.cassandra.thrift.KeyRange

All Implemented Interfaces:

java.io.Serializable, java.lang.Cloneable, java.lang.Comparable<KeyRange>, org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

public class KeyRange
extends java.lang.Object
implements org.apache.thrift.TBase<KeyRange,KeyRange._Fields>, java.io.Serializable, java.lang.Cloneable, java.lang.Comparable<KeyRange>

The semantics of start keys and tokens are slightly different.
 Keys are start-inclusive; tokens are start-exclusive.  Token
 ranges may also wrap -- that is, the end token may be less
 than the start one.  Thus, a range from keyX to keyX is a
 one-element range, but a range from tokenY to tokenY is the
 full ring.

See Also:

Serialized Form

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
KeyRange._Fields

The set of fields this struct contains, along with convenience methods for finding and manipulating them.

Field Summary

Fields

Modifier and Type
Field and Description

int
count

java.nio.ByteBuffer
end_key

java.lang.String
end_token

static java.util.Map<KeyRange._Fields,org.apache.thrift.meta_data.FieldMetaData>
metaDataMap

java.util.List<IndexExpression>
row_filter

java.nio.ByteBuffer
start_key

java.lang.String
start_token

Constructor Summary

Constructors

Constructor and Description

KeyRange()

KeyRange(int count)

KeyRange(KeyRange other)

Performs a deep copy on other.

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
addToRow_filter(IndexExpression elem)

java.nio.ByteBuffer
bufferForEnd_key()

java.nio.ByteBuffer
bufferForStart_key()

void
clear()

int
compareTo(KeyRange other)

KeyRange
deepCopy()

boolean
equals(KeyRange that)

boolean
equals(java.lang.Object that)

KeyRange._Fields
fieldForId(int fieldId)

int
getCount()

byte[]
getEnd_key()

java.lang.String
getEnd_token()

java.lang.Object
getFieldValue(KeyRange._Fields field)

java.util.List<IndexExpression>
getRow_filter()

java.util.Iterator<IndexExpression>
getRow_filterIterator()

int
getRow_filterSize()

byte[]
getStart_key()

java.lang.String
getStart_token()

int
hashCode()

boolean
isSet(KeyRange._Fields field)

Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise

boolean
isSetCount()

Returns true if field count is set (has been assigned a value) and false otherwise

boolean
isSetEnd_key()

Returns true if field end_key is set (has been assigned a value) and false otherwise

boolean
isSetEnd_token()

Returns true if field end_token is set (has been assigned a value) and false otherwise

boolean
isSetRow_filter()

Returns true if field row_filter is set (has been assigned a value) and false otherwise

boolean
isSetStart_key()

Returns true if field start_key is set (has been assigned a value) and false otherwise

boolean
isSetStart_token()

Returns true if field start_token is set (has been assigned a value) and false otherwise

void
read(org.apache.thrift.protocol.TProtocol iprot)

KeyRange
setCount(int count)

void
setCountIsSet(boolean value)

KeyRange
setEnd_key(byte[] end_key)

KeyRange
setEnd_key(java.nio.ByteBuffer end_key)

void
setEnd_keyIsSet(boolean value)

KeyRange
setEnd_token(java.lang.String end_token)

void
setEnd_tokenIsSet(boolean value)

void
setFieldValue(KeyRange._Fields field,
             java.lang.Object value)

KeyRange
setRow_filter(java.util.List<IndexExpression> row_filter)

void
setRow_filterIsSet(boolean value)

KeyRange
setStart_key(byte[] start_key)

KeyRange
setStart_key(java.nio.ByteBuffer start_key)

void
setStart_keyIsSet(boolean value)

KeyRange
setStart_token(java.lang.String start_token)

void
setStart_tokenIsSet(boolean value)

java.lang.String
toString()

void
unsetCount()

void
unsetEnd_key()

void
unsetEnd_token()

void
unsetRow_filter()

void
unsetStart_key()

void
unsetStart_token()

void
validate()

void
write(org.apache.thrift.protocol.TProtocol oprot)

Methods inherited from class java.lang.Object

clone, finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

start_key

public java.nio.ByteBuffer start_key

end_key

public java.nio.ByteBuffer end_key

start_token

public java.lang.String start_token

end_token

public java.lang.String end_token

row_filter

public java.util.List<IndexExpression> row_filter

count

public int count

metaDataMap

public static final java.util.Map<KeyRange._Fields,org.apache.thrift.meta_data.FieldMetaData> metaDataMap

Constructor Detail

KeyRange

public KeyRange()

KeyRange

public KeyRange(int count)

KeyRange

public KeyRange(KeyRange other)

Performs a deep copy on other.

Method Detail

deepCopy

public KeyRange deepCopy()

Specified by:

deepCopy in interface org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

clear

public void clear()

Specified by:

clear in interface org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

getStart_key

public byte[] getStart_key()

bufferForStart_key

public java.nio.ByteBuffer bufferForStart_key()

setStart_key

public KeyRange setStart_key(byte[] start_key)

setStart_key

public KeyRange setStart_key(java.nio.ByteBuffer start_key)

unsetStart_key

public void unsetStart_key()

isSetStart_key

public boolean isSetStart_key()

Returns true if field start_key is set (has been assigned a value) and false otherwise

setStart_keyIsSet

public void setStart_keyIsSet(boolean value)

getEnd_key

public byte[] getEnd_key()

bufferForEnd_key

public java.nio.ByteBuffer bufferForEnd_key()

setEnd_key

public KeyRange setEnd_key(byte[] end_key)

setEnd_key

public KeyRange setEnd_key(java.nio.ByteBuffer end_key)

unsetEnd_key

public void unsetEnd_key()

isSetEnd_key

public boolean isSetEnd_key()

Returns true if field end_key is set (has been assigned a value) and false otherwise

setEnd_keyIsSet

public void setEnd_keyIsSet(boolean value)

getStart_token

public java.lang.String getStart_token()

setStart_token

public KeyRange setStart_token(java.lang.String start_token)

unsetStart_token

public void unsetStart_token()

isSetStart_token

public boolean isSetStart_token()

Returns true if field start_token is set (has been assigned a value) and false otherwise

setStart_tokenIsSet

public void setStart_tokenIsSet(boolean value)

getEnd_token

public java.lang.String getEnd_token()

setEnd_token

public KeyRange setEnd_token(java.lang.String end_token)

unsetEnd_token

public void unsetEnd_token()

isSetEnd_token

public boolean isSetEnd_token()

Returns true if field end_token is set (has been assigned a value) and false otherwise

setEnd_tokenIsSet

public void setEnd_tokenIsSet(boolean value)

getRow_filterSize

public int getRow_filterSize()

getRow_filterIterator

public java.util.Iterator<IndexExpression> getRow_filterIterator()

addToRow_filter

public void addToRow_filter(IndexExpression elem)

getRow_filter

public java.util.List<IndexExpression> getRow_filter()

setRow_filter

public KeyRange setRow_filter(java.util.List<IndexExpression> row_filter)

unsetRow_filter

public void unsetRow_filter()

isSetRow_filter

public boolean isSetRow_filter()

Returns true if field row_filter is set (has been assigned a value) and false otherwise

setRow_filterIsSet

public void setRow_filterIsSet(boolean value)

getCount

public int getCount()

setCount

public KeyRange setCount(int count)

unsetCount

public void unsetCount()

isSetCount

public boolean isSetCount()

Returns true if field count is set (has been assigned a value) and false otherwise

setCountIsSet

public void setCountIsSet(boolean value)

setFieldValue

public void setFieldValue(KeyRange._Fields field,
                          java.lang.Object value)

Specified by:

setFieldValue in interface org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

getFieldValue

public java.lang.Object getFieldValue(KeyRange._Fields field)

Specified by:

getFieldValue in interface org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

isSet

public boolean isSet(KeyRange._Fields field)

Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise

Specified by:

isSet in interface org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

equals

public boolean equals(java.lang.Object that)

Overrides:

equals in class java.lang.Object

equals

public boolean equals(KeyRange that)

hashCode

public int hashCode()

Overrides:

hashCode in class java.lang.Object

compareTo

public int compareTo(KeyRange other)

Specified by:

compareTo in interface java.lang.Comparable<KeyRange>

fieldForId

public KeyRange._Fields fieldForId(int fieldId)

Specified by:

fieldForId in interface org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

read

public void read(org.apache.thrift.protocol.TProtocol iprot)
          throws org.apache.thrift.TException

Specified by:

read in interface org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

Throws:

org.apache.thrift.TException

write

public void write(org.apache.thrift.protocol.TProtocol oprot)
           throws org.apache.thrift.TException

Specified by:

write in interface org.apache.thrift.TBase<KeyRange,KeyRange._Fields>

Throws:

org.apache.thrift.TException

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

validate

public void validate()
              throws org.apache.thrift.TException

Throws:

org.apache.thrift.TException

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2015 The Apache Software Foundation


text:
/*
 * http://www.cs.bham.ac.uk/~exr/lectures/opsys/10_11/lectures/os-dev.pdf
 */

unsigned char port_byte_in(unsigned short port);
void port_byte_out(unsigned short port, unsigned char data);


text:
'use strict'

const decamelize = require('decamelize')
const amenities = [ 'tent', 'rv', 'tables', 'toilets', 'water', 'accessible', 'boat ramp', 'parking' ]
const percent = 100.0 / amenities.length
const cols = amenities.map(x => `<col width="${percent}%" />`).join('')

function renderSummaryKey(k) {
  const s = decamelize(k, ' ')
  return s[0].toUpperCase() + s.slice(1)
}

function _renderSummary(summary) {
  if (!summary) return ''
  const rows = Object.keys(summary).reduce(onkey, '')
  function onkey(acc, k) {
    const val = summary[k]
    if (val === null) return acc
    return acc + `<tr><td>${renderSummaryKey(k)}</td><td>${val}</td></tr>`
  }

  return `

Summary

      ${rows}

    `
}

function _renderAmenities(xs, type) {
  // we can assume that tents are allowed if it's a campsite ;)
  if (type === 'camping') xs = xs.concat('tent')
  function toAmenityCell(html, x) {
    // signal missing anemity via lighter empty cell
    const clazz = ~xs.indexOf(x) ? '' : 'disabled'
    return html +
      `
        <img class="${clazz}" src="img/amenities-${x.replace(/ /g, '-')}.png" alt="${x}"
      	`
  }

  const cells = amenities.reduce(toAmenityCell, '')

  return `

      ${cols}

${cells}

    `
}

exports.renderAmenities = function renderAmenities(info) {
  // TODO: do this during scraping step and make this a bit
  // less hacky and more deterministic ;)
  // fix the unknown spelling error during data analysis as well
  const type = (/cabin/i).test(info.title)
    ? 'cabin'
    : info.type === 'unkown'
      ? 'camping'
      : info.type
  return _renderAmenities(info.amenities || [], type)
}

exports.renderSummary = function renderSummary(info) {
  return _renderSummary(info.summary || {})
}


text:
package jetbrains.buildServer.nuget.common;

import jetbrains.buildServer.ArtifactsConstants;
import jetbrains.buildServer.agent.Constants;

/**
 * Created by Eugene Petrenko (eugene.petrenko@gmail.com)
 * Date: 07.07.11 13:56
 */
public interface PackagesConstants {
  public static final String INSTALL_RUN_TYPE = "jb.nuget.installer"; //no more than 30 chars
  public static final String PUBLISH_RUN_TYPE = "jb.nuget.publish"; //run-type could never exceed 30 chars
  public static final String PACK_RUN_TYPE = "jb.nuget.pack"; //run-type could never exceed 30 chars
  public static final String ATHU_FEATURE_TYPE = "jb.nuget.auth"; //run-type could never exceed 30 chars

  public static final String[] ALL_NUGET_RUN_TYPES = {INSTALL_RUN_TYPE, PUBLISH_RUN_TYPE, PACK_RUN_TYPE};

  public static final String NUGET_PATH = "nuget.path";
  public static final String NUGET_SOURCES = "nuget.sources";
  public static final String NUGET_EXCLUDE_VERSION = "nuget.excludeVersion";
  public static final String NUGET_USE_RESTORE_COMMAND = "nuget.use.restore";
  public static final String NUGET_NO_CACHE = "nuget.noCache";
  public static final String NUGET_RESTORE_CUSOM_COMMANDLINE= "nuget.restore.commandline";

  public static final String NUGET_UPDATE_PACKAGES = "nuget.updatePackages";
  public static final String NUGET_UPDATE_PACKAGES_SAFE = "nuget.updatePackages.safe";
  public static final String NUGET_UPDATE_PACKAGES_PRERELEASE = "nuget.updatePackages.include.prerelease";
  public static final String NUGET_UPDATE_PACKAGE_IDS = "nuget.updatePackages.ids";
  public static final String NUGET_UPDATE_MODE = "nuget.updatePackages.mode";
  public static final String NUGET_UPDATE_CUSOM_COMMANDLINE= "nuget.update.commandline";

  public static final String SLN_PATH = "sln.path";

  public static final String NUGET_USED_PACKAGES_DIR = ArtifactsConstants.TEAMCITY_ARTIFACTS_DIR + "/nuget";
  public static final String NUGET_USED_PACKAGES_FILE = "nuget.xml";

  public static final String NUGET_PUBLISH_CREATE_ONLY = "nuget.publish.create.only";
  public static final String NUGET_PUBLISH_FILES = "nuget.publish.files";
  public static final String NUGET_PUBLISH_SOURCE = "nuget.publish.source";
  public static final String NUGET_API_KEY = Constants.SECURE_PROPERTY_PREFIX + "nuget.api.key";

  public static final String NUGET_TOOL_NAME_PREFIX = "nuget-commnadline-";
  public static final String NUGET_TOOL_REL_PATH = "tools/NuGet.exe";

  public static final String NUGET_PACK_OUTPUT_CLEAR = "nuget.pack.output.clean";
  public static final String NUGET_PACK_OUTPUT_DIR = "nuget.pack.output.directory";
  public static final String NUGET_PACK_PUBLISH_ARTIFACT = "nuget.pack.as.artifact";
  public static final String NUGET_PACK_PREFER_PROJECT = "nuget.pack.prefer.project";
  public static final String NUGET_PACK_BASE_DIRECTORY_MODE = "nuget.pack.project.dir";
  public static final String NUGET_PACK_BASE_DIR = "nuget.pack.base.directory";
  public static final String NUGET_PACK_VERSION = "nuget.pack.version";
  public static final String NUGET_PACK_SPEC_FILE = "nuget.pack.specFile";
  public static final String NUGET_PACK_EXCLUDE_FILES = "nuget.pack.excludes";
  public static final String NUGET_PACK_PROPERTIES = "nuget.pack.properties";
  public static final String NUGET_PACK_CUSOM_COMMANDLINE= "nuget.pack.commandline";
  public static final String NUGET_PACK_AS_TOOL= "nuget.pack.pack.mode.tool";
  public static final String NUGET_PACK_INCLUDE_SOURCES = "nuget.pack.include.sources" ;

  public static final String NUGET_AUTH_FEED = "nuget.auth.feed";
  public static final String NUGET_AUTH_USERNAME = "nuget.auth.username";
  public static final String NUGET_AUTH_PASSWORD = Constants.SECURE_PROPERTY_PREFIX + "nuget.auth.password";
}


text:
var assert = require("assert");

var app = require('../src/app');

describe("testApp", function(){
	it("should have a 'testValue' defined", function(){
		assert.equal( app.testValue, "test" );
	});
});

describe("global objects", function(){
	describe("window", function(){
		it("should exist", function(){
			assert( window );
		});
	});

	describe("document", function(){
		it("should exist", function(){
			assert( document );
		});
	});

	describe("navigator", function(){
		it("should exist", function(){
			assert( navigator );
		});
	});
});


text:
require 'spec_helper'

describe PivotalTracker do
  describe "default attributes" do
    it "includes HTTParty" do
      expect(subject.class.ancestors).to include(HTTParty)
    end

    it "has the base url set" do
      expect(subject.class.base_uri).to eq('https://www.pivotaltracker.com/services/v5')
    end
  end

  describe "GET me" do
    before do
      PivotalTracker::Client.token = ENV['PIVOTAL_TOKEN_ID']
      VCR.insert_cassette 'profile', :record => :new_episodes
    end

    after do
      VCR.eject_cassette
    end

    it "records the fixture" do
      PivotalTracker.get('/me')
    end
  end
end


text:
def solve(max):
    '''
    If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

    Find the sum of all the multiples of 3 or 5 below 1000.
    '''

    n = 0
    for i in range(1, max):
        if not i % 5 or not i % 3:
            n = n + i

    return n


text:
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.gbm import H2OGradientBoostingEstimator

def test_gbm_train_segments():
    prostate = h2o.import_file(path=pyunit_utils.locate("smalldata/logreg/prostate.csv"))
    prostate["CAPSULE"] = prostate["CAPSULE"].asfactor()

    # model will be built for each segment
    segment_col = "RACE"
    # segment 0 is too small, will not produce a model
    bad_segment = 0

    segments = prostate[segment_col].unique()
    segments.rename({'C1':segment_col})

    params = {
        "min_rows": 2,
        "ntrees": 4,
        "seed": 42
    }
    prostate_gbm = H2OGradientBoostingEstimator(**params)
    models = prostate_gbm.train_segments(y="CAPSULE", ignored_columns=["ID"], training_frame=prostate,
                                         segments=segments)
    models_list = models.as_frame()

    assert models_list.names == [u'RACE', u'model', u'status', u'errors', u'warnings']
    assert models_list.nrow == 3

    # Check failed models
    expected_error = 'ERRR on field: _min_rows: The dataset size is too small to split for min_rows=2.0: ' \
                     'must have at least 4.0 (weighted) rows, but have only 3.0.\n'
    assert (models_list["errors"][models_list[segment_col] == bad_segment]).as_data_frame()["errors"][0] == expected_error

    mp = models_list.as_data_frame()
    # Check built models
    for i in range(mp.shape[0]):
        segment = int(mp.iloc[i][segment_col])
        if segment != bad_segment:
            model_id = mp.iloc[i]["model"]
            model = h2o.get_model(model_id)
            prostate_segment = prostate[prostate[segment_col] == segment]
            prostate_gbm_segment = H2OGradientBoostingEstimator(**params)
            prostate_gbm_segment.train(y="CAPSULE", ignored_columns=["ID"], training_frame=prostate_segment)
            pyunit_utils.check_models(model, prostate_gbm_segment)

if __name__ == "__main__":
    pyunit_utils.standalone_test(test_gbm_train_segments)
else:
    test_gbm_train_segments()


text:
<?php

namespace PowerTools\Command\Generate;

use PowerTools\Console\GenerateCommand;
use PowerTools\Console\Question;
use PowerTools\Parsers\ClassNamespace;
use PowerTools\Template\Template;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;

class ContentNodeCommand extends GenerateCommand
{
	public $classNamespace = '';
	public $className = '';

	public $appDir = '';
	public $module = '';

	public $databaseTable = '';
	public $databasePrefix = '';
	public $databaseColumnId = '';
	public $databaseColumnOrder = '';
	public $databaseColumnParent = '';

	public $itemClass = '';

	public $title = '';

	protected function configure()
	{
		$this
			->setName('generate:content-node')
			->setDescription('Generates a Content Node boilerplate class')
			->addArgument(
				'namespace',
				InputArgument::REQUIRED,
				'The namespace for the desired content node class'
			)
		;
	}

	protected function execute(InputInterface $input, OutputInterface $output)
	{
		$question = $this->getHelper('question');
		$this->assignNamespaceAttributes( new ClassNamespace( $input->getArgument('namespace') ) );

		// Database information
		$this->databaseTable = $question->ask(
				$input, $output,
				new Question('Database table', "{$this->appDir}_categories")
		);
		$this->databasePrefix = $question->ask(
				$input, $output,
				new Question('Database prefix', '')
		);
		$this->databaseColumnId = $question->ask(
				$input, $output,
				new Question('Database column ID', 'id')
		);
		$this->databaseColumnOrder = $question->ask(
			$input, $output,
			new Question('Database column order')
		);
		$this->databaseColumnParent = $question->ask(
			$input, $output,
			new Question('Database column parent')
		);

		// Class information
		$this->itemClass = $question->ask(
				$input, $output,
				new Question('Item class')
		);

		$this->title = $question->ask(
				$input, $output,
				new Question('Title')
		);

		$template = $this->generateTemplate( 'content/node.php' );
		$this->writeTemplate( $template );
	}
}


text:
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using HtcSharp.HttpModule.Http.Abstractions;
using HtcSharp.HttpModule.Http.Abstractions.Extensions;
using MoonSharp.Interpreter;

namespace HtcPlugin.Lua.Processor.Utils {
    public static class LuaExceptionHandler {

        public static void ErrorHeaderAlreadySent(HttpContext httpContext) {
            httpContext.Response.WriteAsync(GenerateMessage("Failed to set the header, it has already been sent to the client!")).GetAwaiter().GetResult();
        }

        public static void ErrorScriptRuntimeException(HttpContext httpContext, ScriptRuntimeException ex, string filepath) {
            if (ex.DecoratedMessage.Length <= 0) {
                httpContext.Response.WriteAsync(GenerateMessage(ex.Message, "Fatal Error:")).GetAwaiter().GetResult();
            } else {
                string fileName = Path.GetFileName(filepath);
                httpContext.Response.WriteAsync(GenerateMessage(ex.DecoratedMessage.Replace(filepath, fileName), "Fatal Error:")).GetAwaiter().GetResult();
            }
        }

        public static void ErrorUnknown(HttpContext httpContext, Exception ex) {
            httpContext.Response.WriteAsync(GenerateMessage(ex.Message, "Fatal Error:")).GetAwaiter().GetResult();
        }

        public static string GenerateMessage(string message, string type = "Error:") {
            return $"
{type} {message}
";
        }
    }
}


text:
package org.jboss.weld.tests.contexts.weld1159;

import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.weld.test.util.Utils;
import org.jboss.weld.tests.category.Integration;
import org.junit.After;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import com.gargoylesoftware.htmlunit.WebClient;

/**
 *
 * Reproduces deadlock between creation locks in the application and session context.
 *
 * Two pairs of beans are constructed in parallel:
 *
 * SessionScopedFoo -> ApplicationScopedFoo
 * ApplicationScopedBar -> SessionScopedBar
 *
 * We use a {@link CountDownLatch} to simulate that both threads get into state when the first bean of the pair
 * (SessionScopedFoo and ApplicationScopedFoo) is created and before the dependency is created. This causes deadlock
 * because the first thread
 *
 * - owns the session lock
 * - waits for application lock
 *
 *  whereas the second thread
 *
 * - owns the application lock
 * - waits for the session lock
 *
 * @author Jozef Hartinger
 *
 */
@RunWith(Arquillian.class)
@Category(Integration.class)
public class ContextDeadlockTest {

    @ArquillianResource
    private volatile URL url;

    private final WebClient client = new WebClient();

    private final ExecutorService executor = Executors.newCachedThreadPool();

    @Deployment(testable = false)
    public static Archive<?> getDeployment() {
        return ShrinkWrap.create(WebArchive.class, Utils.getDeploymentNameAsHash(ContextDeadlockTest.class, Utils.ARCHIVE_TYPE.WAR))
                .addClasses(AbstractBean.class, ApplicationScopedFoo.class, ApplicationScopedBar.class, SessionScopedFoo.class, SessionScopedBar.class,
                        TestServlet.class)
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
    }

    @Test
    public void test() throws Exception {
        client.setTimeout(15000);

        List<Callable<Void>> requests = new LinkedList<Callable<Void>>();
        requests.add(new ConcurrentRequest(url.toString() + "/foo"));
        requests.add(new ConcurrentRequest(url.toString() + "/bar"));

        for (Future<Void> result : executor.invokeAll(requests)) {
            result.get();
        }
    }

    @After
    public void shutdown() {
        executor.shutdownNow();
    }

    private class ConcurrentRequest implements Callable<Void> {

        private final String url;

        public ConcurrentRequest(String url) {
            this.url = url;
        }

        public Void call() throws Exception {
            try {
                client.getPage(url);
            } catch (SocketTimeoutException e) {
                throw new RuntimeException("The request for " + url + " timed out. It is very likely that a deadlock occured.");
            }
            return null;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>DEAD-box RNA Helicases: metabolism on My BioBits</title>
    <link>http://lpantano.github.io/tags/dead-box-rna-helicases-metabolism/</link>
    <description>Recent content in DEAD-box RNA Helicases: metabolism on My BioBits</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator>
    <language>en-us</language>
    <lastBuildDate>Tue, 01 Jan 2013 00:00:00 +0000</lastBuildDate>

	    <atom:link href="http://lpantano.github.io/tags/dead-box-rna-helicases-metabolism/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>A highly expressed miR-101 isomiR is a functional silencing small RNA.</title>
      <link>http://lpantano.github.io/publication/llorens-2013/</link>
      <pubDate>Tue, 01 Jan 2013 00:00:00 +0000</pubDate>

      <guid>http://lpantano.github.io/publication/llorens-2013/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
package org.apache.zookeeper.server.quorum;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.server.SessionTracker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A session tracker that supports upgradeable local sessions.
 */
public abstract class UpgradeableSessionTracker implements SessionTracker {
    private static final Logger LOG = LoggerFactory.getLogger(UpgradeableSessionTracker.class);

    private ConcurrentMap<Long, Integer> localSessionsWithTimeouts;
    protected LocalSessionTracker localSessionTracker;

    public void start() {}

    public void createLocalSessionTracker(SessionExpirer expirer,
            int tickTime, long id) {
        this.localSessionsWithTimeouts =
            new ConcurrentHashMap<Long, Integer>();
        this.localSessionTracker = new LocalSessionTracker(
            expirer, this.localSessionsWithTimeouts, tickTime, id);
    }

    public boolean isTrackingSession(long sessionId) {
        return isLocalSession(sessionId) || isGlobalSession(sessionId);
    }

    public boolean isLocalSession(long sessionId) {
        return localSessionTracker != null &&
            localSessionTracker.isTrackingSession(sessionId);
    }

    abstract public boolean isGlobalSession(long sessionId);

    /**
     * Upgrades the session to a global session.
     * This simply removes the session from the local tracker and marks
     * it as global.  It is up to the caller to actually
     * queue up a transaction for the session.
     *
     * @param sessionId
     * @return session timeout (-1 if not a local session)
     */
    public int upgradeSession(long sessionId) {
        if (localSessionsWithTimeouts == null) {
            return -1;
        }
        // We won't race another upgrade attempt because only one thread
        // will get the timeout from the map
        Integer timeout = localSessionsWithTimeouts.remove(sessionId);
        if (timeout != null) {
            LOG.info("Upgrading session 0x" + Long.toHexString(sessionId));
            // Add as global before removing as local
            addGlobalSession(sessionId, timeout);
            localSessionTracker.removeSession(sessionId);
            return timeout;
        }
        return -1;
    }

    public void checkGlobalSession(long sessionId, Object owner)
            throws KeeperException.SessionExpiredException,
            KeeperException.SessionMovedException {
        throw new UnsupportedOperationException();
    }
}


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

<title>Uses of Class pb.locationintelligence.model.IndexVariable</title>
<meta name="date" content="2020-04-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
pb.locationintelligence.model.IndexVariable

Packages that use IndexVariable

Package
Description

pb.locationintelligence.model

Uses of IndexVariable in pb.locationintelligence.model

Methods in pb.locationintelligence.model that return IndexVariable

Modifier and Type
Method and Description

IndexVariable
IndexVariable.category(java.lang.String category)

IndexVariable
IndexVariable.name(java.lang.String name)

IndexVariable
IndexVariable.percentile(java.lang.String percentile)

IndexVariable
IndexVariable.score(java.lang.String score)

IndexVariable
IndexVariable.stateScore(java.lang.String stateScore)

Methods in pb.locationintelligence.model that return types with arguments of type IndexVariable

Modifier and Type
Method and Description

java.util.List<IndexVariable>
CrimeIndexTheme.getIndexVariable()

Get indexVariable

Method parameters in pb.locationintelligence.model with type arguments of type IndexVariable

Modifier and Type
Method and Description

CrimeIndexTheme
CrimeIndexTheme.indexVariable(java.util.List<IndexVariable> indexVariable)

void
CrimeIndexTheme.setIndexVariable(java.util.List<IndexVariable> indexVariable)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
import pytest
from pytest_lazyfixture import sorted_by_dependency, lazy_fixture, _sorted_argnames

try:
    import numpy
except ImportError:
    numpy = None

def test_fixture_in_parametrize_with_params(testdir):
    items = testdir.getitems("""
        import pytest
        @pytest.fixture(params=[1,2])
        def one(request):
            return request.param
        @pytest.mark.parametrize('arg1,arg2', [
            ('val1', pytest.lazy_fixture('one')),
            ('val1', 'val2')
        ])
        def test_func(arg1, arg2):
            pass
    """)
    assert len(items) == 3
    assert items[0].callspec.params['one'] == 1
    assert items[1].callspec.params['one'] == 2

def test_several_fixtures_in_parametrize_with_params(testdir):
    items = testdir.getitems("""
        import pytest
        @pytest.fixture(params=[1,2])
        def one(request):
            return request.param
        @pytest.fixture(params=[3,4])
        def two(request):
            return request.param
        @pytest.mark.parametrize('arg1,arg2,arg3', [
            ('val1', pytest.lazy_fixture('one'), pytest.lazy_fixture('two')),
        ])
        def test_func(arg1, arg2, arg3):
            pass
    """)
    assert len(items) == 4
    expected_results = [
        {'one': 1, 'two': 3},
        {'one': 1, 'two': 4},
        {'one': 2, 'two': 3},
        {'one': 2, 'two': 4}
    ]

    def is_subset(subset, superset):
        return all(superset[k] == subset[k] for k in subset)
    for item in items:
        assert any(is_subset(result, item.callspec.params) for result in expected_results)

def test_fixtures_in_parametrize_with_indirect(testdir):
    items = testdir.getitems("""
        import pytest
        @pytest.fixture
        def one():
            pass
        @pytest.fixture
        def two():
            pass
        @pytest.mark.parametrize('arg1,one', [
            ('val1', pytest.lazy_fixture('two')),
        ], indirect=['one'])
        def test_func(arg1, one):
            pass
    """)
    assert len(items) == 1
    assert items[0].callspec.params['one'].name == 'two'

def test_fixtures_with_params_in_parametrize_with_indirect(testdir):
    items = testdir.getitems("""
        import pytest
        @pytest.fixture
        def one():
            pass
        @pytest.fixture(params=[1,2])
        def two(request):
            return request.param
        @pytest.mark.parametrize('arg1,one', [
            ('val1', pytest.lazy_fixture('two')),
        ], indirect=['one'])
        def test_func(arg1, one):
            pass
    """)
    assert len(items) == 2
    assert items[0].callspec.params['two'] == 1
    assert items[1].callspec.params['two'] == 2

def test_lazy_fixture_is_value_in_parametrize(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture
        def one():
            return 1
        @pytest.fixture
        def two():
            return 2
        @pytest.mark.parametrize('arg1,arg2', [
            pytest.lazy_fixture(('one', 'two'))
        ])
        def test_func(arg1, arg2):
            assert arg1 == 1
            assert arg2 == 2
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=1)

def test_lazy_fixture_as_funcarg_in_parametrize_with_indirect(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture
        def one():
            return 1
        @pytest.fixture
        def two():
            return 2
        @pytest.fixture
        def three(request):
            return request.param
        @pytest.mark.parametrize('arg1,arg2,three', [
            (pytest.lazy_fixture('one'), pytest.lazy_fixture('two'), '3')
        ], indirect=['three'])
        def test_func(arg1, arg2, three):
            assert arg1 == 1
            assert arg2 == 2
            assert three == '3'
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=1)

def test_lazy_fixture_is_value_in_parametrize_with_indirect(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture
        def one(request):
            return request.param
        @pytest.fixture
        def two():
            return 2
        @pytest.mark.parametrize('one', [
            pytest.lazy_fixture('two')
        ], indirect=True)
        def test_func(one):
            assert one == 2
    """)
    reprec = testdir.inline_run()
    reprec.assertoutcome(passed=1)

def test_lazy_fixture_as_param_of_fixture(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture(params=[
            pytest.lazy_fixture('one'),
            pytest.lazy_fixture('two')
        ])
        def some(request):
            return request.param
        @pytest.fixture
        def one():
            return 1
        @pytest.fixture
        def two():
            return 2
        def test_func(some):
            assert some in [1, 2]
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=2)

def test_lazy_fixture_in_params_which_has_params(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture(params=[1, 2, 3])
        def one(request):
            return str(request.param)
        @pytest.fixture
        def two():
            return 4
        @pytest.fixture(params=[
            pytest.lazy_fixture('one'),
            pytest.lazy_fixture('two')
        ])
        def some(request):
            return request.param
        def test_func(some):
            assert some in {'1', '2', '3', 4}
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=4)

def test_lazy_fixture_three_times_nested(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture(params=[
            1, 2, pytest.lazy_fixture('three')])
        def one(request):
            return str(request.param)
        @pytest.fixture
        def two():
            return 4
        @pytest.fixture
        def three():
            return 3
        @pytest.fixture(params=[
            pytest.lazy_fixture('one'),
            pytest.lazy_fixture('two')
        ])
        def some(request):
            return request.param
        def test_func(some):
            assert some in {'1', '2', '3', 4}
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=4)

def test_lazy_fixture_three_times_nested_with_one_failed(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture(params=[
            1, 2, pytest.lazy_fixture('three')
        ])
        def one(request):
            return str(request.param)
        @pytest.fixture
        def two():
            return 4
        @pytest.fixture
        def three():
            return 5
        @pytest.fixture(params=[
            pytest.lazy_fixture('one'),
            pytest.lazy_fixture('two')
        ])
        def some(request):
            return request.param
        def test_func(some):
            assert some in {'1', '2', '3', 4}
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=3, failed=1)

def test_lazy_fixture_common_dependency(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture(params=[1, 2, 3])
        def one(request):
            return request.param
        @pytest.fixture(params=[pytest.lazy_fixture('one')])
        def as_str(request):
            return str(request.param)
        @pytest.fixture(params=[pytest.lazy_fixture('one')])
        def as_hex(request):
            return hex(request.param)

        def test_as_str(as_str):
            assert as_str in {'1', '2', '3'}
        def test_as_hex(as_hex):
            assert as_hex in {'0x1', '0x2', '0x3'}

        def test_as_hex_vs_as_str(as_str, as_hex):
            assert int(as_hex, 16) == int(as_str)
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=9)

def test_lazy_fixture_common_dependency_with_getfixturevalue(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture(params=[1, 2, 3])
        def one(request):
            return request.param
        @pytest.fixture(params=[pytest.lazy_fixture('one')])
        def as_str(request):
            return str(request.getfixturevalue('one'))
        @pytest.fixture(params=[pytest.lazy_fixture('one')])
        def as_hex(request):
            return hex(request.getfixturevalue('one'))
        def test_as_str(as_str):
            assert as_str in {'1', '2', '3'}
        def test_as_hex(as_hex):
            assert as_hex in {'0x1', '0x2', '0x3'}
        def test_as_hex_vs_as_str(as_str, as_hex):
            assert int(as_hex, 16) == int(as_str)
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=9)

def test_issues2(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture(params=[1, 2, 3])
        def one(request):
            return request.param

        @pytest.fixture(params=[pytest.lazy_fixture('one')])
        def as_str(request):
            return str(request.getfixturevalue('one'))

        @pytest.mark.parametrize('val', ('a', 'b', 'c'))
        def test_as_str(val, as_str):
            combined = ''.join((val, as_str))
            assert combined in {'a1', 'a2', 'a3', 'b1', 'b2', 'b3', 'c1', 'c2', 'c3'}
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=9)

def test_issues2_2(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture(params=[1, 2, 3])
        def one(request):
            return request.param

        @pytest.fixture(params=[pytest.lazy_fixture('one')])
        def as_str(request):
            return str(request.getfixturevalue('one'))

        @pytest.mark.parametrize('val, one', (
            ('a', '1'), ('b', '2'), ('c', '3')
        ), indirect=['one'])
        def test_as_str(val, one, as_str):
            combined = ''.join((val, as_str))
            assert combined in {'a1', 'b2', 'c3'}
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=3)

def test_issues3_autouse_fixtures_should_run_first(testdir):
    testdir.makepyfile("""
        import pytest
        gl = False
        @pytest.fixture(autouse=True)
        def auto_one():
            global gl
            gl = True

        @pytest.fixture
        def one():
            return 1 if gl is True else -1

        @pytest.mark.parametrize('arg1', [
            pytest.lazy_fixture('one')
        ])
        def test_some(arg1):
            assert arg1 == 1
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=1)

def test_issues10_xfail(testdir):
    testdir.makepyfile("""
        import pytest
        def division(a, b):
            return a / b

        @pytest.fixture(params=[0])
        def zero(request):
            return request.param

        @pytest.mark.parametrize(('a', 'b'), [
            pytest.param(1, pytest.lazy_fixture('zero'), marks=pytest.mark.xfail(reason=ZeroDivisionError))
        ])
        def test_division(a, b):
            division(a, b)
    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(skipped=1)

def test_issues11_autouse_fixture_in_test_class(testdir):
    testdir.makepyfile("""
        import pytest

        class TestModels(object):
            @pytest.fixture(autouse=True)
            def setup(self):
                self.var = 15

            def test_model_a(self):
                assert self.var == 15

            def test_model_b(self):
                assert self.var == 15

    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(passed=2)

def test_issues12_skip_test_function(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture
        def one():
            return 1

        @pytest.mark.parametrize('a', [
            pytest.param(pytest.lazy_fixture('one'), marks=pytest.mark.skip(reason='skip'))
        ])
        def test_skip1(a):
            assert a == 1

        @pytest.mark.skip(reason='skip')
        @pytest.mark.parametrize('a', [
            pytest.lazy_fixture('one')
        ])
        def test_skip2(a):
            assert a == 1

        def test_after_skip(one):
            assert one == 1
    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(skipped=2, passed=1)

def test_issues12_skip_test_method(testdir):
    testdir.makepyfile("""
        import pytest

        class TestModels:
            @pytest.fixture
            def one(self):
                return 1

            @pytest.mark.skip(reason='skip this')
            @pytest.mark.parametrize('a', [
                pytest.lazy_fixture('one')
            ])
            def test_model_a(self, a):
                assert a == 1

            @pytest.mark.parametrize('a', [
                pytest.param(pytest.lazy_fixture('one'), marks=pytest.mark.skip(reason='skip this'))
            ])
            def test_model_b(self, a):
                assert a == 1

            def test_after_skip(self, one):
                assert one == 1
    """)
    reprec = testdir.runpytest('-s', '-v')
    reprec.assert_outcomes(skipped=2, passed=1)

def test_issues12_lf_as_method_of_test_class(testdir):
    testdir.makepyfile("""
        import pytest

        class TestModels:
            @pytest.fixture
            def one(self):
                return 1

            @pytest.mark.parametrize('a', [
                pytest.lazy_fixture('one')
            ])
            def test_lf(self, a):
                assert a == 1
    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(passed=1)

def test_issues13_unittest_testcase_class_should_not_fail(testdir):
    testdir.makepyfile("""
        import unittest
        import pytest

        class TestModels(unittest.TestCase):
            def test_models(self):
                assert True

            def test_models_fail(self):
                assert False
    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(passed=1, failed=1)

def test_argnames_initialized_in_right_order(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture
        def one():
            return [1]

        @pytest.fixture
        def plus_two(a):
            a[0] = a[0] + 2

        @pytest.mark.parametrize('a,b', [
            (pytest.lazy_fixture('one'), pytest.lazy_fixture('plus_two'))
        ])
        def test_skip1(a, b):
            assert a == [3]
    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(passed=1)

# https://github.com/TvoroG/pytest-lazy-fixture/pull/19
def test_argnames_initialized_in_right_order2(testdir):
    testdir.makepyfile("""
        import pytest
        @pytest.fixture
        def one():
            return [1]

        @pytest.fixture
        def plus_two(a):
            a[0] = a[0] + 2
        def test_skip1(a):
            assert a == [3]

        def pytest_generate_tests(metafunc):
            metafunc.fixturenames = ['a', 'b']
            metafunc.parametrize(argnames=['a', 'b'],
                                 argvalues=[(pytest.lazy_fixture('one'), pytest.lazy_fixture('plus_two'))],
                                 indirect=['b'])

    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(passed=1)

def lf(fname):
    return lazy_fixture(fname)

@pytest.mark.parametrize('params,expected_paths', [
    (
        {'some': lf('one'), 'one': lf('three')},
        ['one>some'],
    ),
    (
        {'grand1': lf('parent1_1'), 'parent1_1': lf('child1'),
         'grand2': lf('parent1_2'), 'parent1_2': lf('child1'),
         'child1': lf('none')},
        ['child1>parent1_1>grand1>parent1_2>grand2', 'child1>parent1_2>grand2>parent1_1>grand1']
    ),
    (
        {'param1': 'val1', 'param2': 'val2'},
        ['param1>param2', 'param2>param1']
    ),
    ({}, ['']),
    ({'param1': 'val1'}, ['param1']),
    ({'param1': lf('some')}, ['param1']),
    (
        {'one': 1, 'as_str': lf('one'), 'as_hex': lf('one')},
        ['one>as_str>as_hex', 'one>as_hex>as_str']
    )
])
def test_sorted_by_dependency(params, expected_paths):
    sp = sorted_by_dependency(params, [])
    path = '>'.join(param for param, _ in sp)

    assert path in expected_paths

@pytest.mark.parametrize('params,fixturenames,expect_keys', [
    ({'b': 1, 'a': 0}, ['c', 'a', 'd', 'b'], ['c', 'a', 'd', 'b']),
    ({'b': 1, 'a': 0}, ['c', 'b'], ['c', 'b', 'a'])
])
def test_sorted_argnames(params, fixturenames, expect_keys):
    assert list(_sorted_argnames(params, fixturenames)) == expect_keys

def test_lazy_fixtures_with_subfixtures(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(params=["a", "A"])
        def a(request):
            return request.param

        @pytest.fixture(params=["b", "B"])
        def b(a, request):
            return request.param + a

        @pytest.fixture
        def c(a):
            return "c" + a

        @pytest.fixture(params=[pytest.lazy_fixture('a'), pytest.lazy_fixture('b'), pytest.lazy_fixture('c')])
        def d(request):
            return "d" + request.param

        @pytest.fixture(params=[pytest.lazy_fixture('a'), pytest.lazy_fixture('d'), ""])
        def e(request):
            return "e" + request.param

        def test_one(d):
            assert d in ("da", "dA", "dba", "dbA", "dBa", "dBA", "dca", "dcA")

        def test_two(e):
            assert e in ("ea", "eA", "eda", "edA", "edba", "edbA", "edBa", "edBA", "edca", "edcA", "e")
    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(passed=19)

def test_lazy_fixtures_in_subfixture(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture
        def a():
            return "a"

        @pytest.fixture
        def b():
            return "b"

        @pytest.fixture(params=[pytest.lazy_fixture('a'), pytest.lazy_fixture('b')])
        def c(request):
            return "c" + request.param

        @pytest.fixture
        def d(c):
            return "d" + c

        def test_one(d):
            assert d in ("dca", "dcb")
    """)
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(passed=2)

@pytest.mark.parametrize('autouse', [False, True])
def test_issues23(testdir, autouse):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture(params=[0, 1], autouse={})
        def zero(request):
            return request.param

        @pytest.fixture(params=[1])
        def one(request, zero):
            return zero * request.param

        @pytest.fixture(params=[
            pytest.lazy_fixture('one'),
        ])
        def some(request):
            return request.param

        def test_func(some):
            assert some in [0, 1]

    """.format(autouse))
    reprec = testdir.inline_run('-s', '-v')
    reprec.assertoutcome(passed=2)

def test_lazy_fixture_nested_fixtures(testdir):
    testdir.makepyfile("""
        import pytest

        @pytest.fixture
        def one(request):
            return "SOME_VALUE"

        @pytest.fixture
        def two(request):
            return "SOME_VALUE2"

        @pytest.fixture(params=[
            pytest.lazy_fixture("one"),
            pytest.lazy_fixture("two"),
        ])
        def some_fixture1(request):
            return request.param

        @pytest.fixture
        def some_fixture2(some_fixture1):
            return "NEW_" + some_fixture1

        def test_func(some_fixture2):
            assert ((some_fixture2 == "NEW_SOME_VALUE") or (some_fixture2 == "NEW_SOME_VALUE2"))
    """)
    reprec = testdir.inline_run('-s')
    reprec.assertoutcome(passed=2)

# https://github.com/TvoroG/pytest-lazy-fixture/issues/39
def test_usefixture_runs_before_function_fixtures(testdir):
    testdir.makepyfile("""
        import pytest
        from pytest_lazyfixture import lazy_fixture

        invocation_order = []

        @pytest.fixture
        def module_fixture():
            invocation_order.append('using module fixture')

        @pytest.fixture
        def fixture1():
            invocation_order.append('using fixture1')
            return 'fixture1'

        @pytest.fixture
        def fixture2():
            invocation_order.append('using fixture2')
            return 'fixture2'

        @pytest.mark.usefixtures("module_fixture")
        @pytest.mark.parametrize("fixt", [lazy_fixture("fixture1"), lazy_fixture("fixture2")])
        def test_test(fixt):
            if fixt == 'fixture2':
                print(' '.join(invocation_order))
    """)
    result = testdir.runpytest('-s')
    stdout = result.stdout.str()
    assert (
        'using module fixture using fixture1 using module fixture using fixture2' in stdout
    )

# https://github.com/TvoroG/pytest-lazy-fixture/issues/39
def test_autouse_and_usefixture_module_scope_runs_before_function_fixtures(testdir):
    testdir.makepyfile("""
        import pytest
        from pytest_lazyfixture import lazy_fixture

        invocation_order = []

        @pytest.fixture(autouse=True)
        def autouse_fixture():
            invocation_order.append('using autouse_fixture')

        @pytest.fixture(scope='module')
        def module_fixture():
            invocation_order.append('using module fixture')

        @pytest.fixture
        def fixture1():
            invocation_order.append('using fixture1')
            return 'fixture1'

        @pytest.fixture
        def fixture2():
            invocation_order.append('using fixture2')
            return 'fixture2'

        @pytest.mark.usefixtures("module_fixture")
        @pytest.mark.parametrize("fixt", [lazy_fixture("fixture1"), lazy_fixture("fixture2")])
        def test_test(fixt):
            if fixt == 'fixture2':
                print(' '.join(invocation_order))
    """)
    result = testdir.runpytest('-s')
    stdout = result.stdout.str()
    assert (
        # pytest==3.2.5
        'using autouse_fixture using module fixture using fixture1 using autouse_fixture using fixture2' in stdout
        or
        'using module fixture using autouse_fixture using fixture1 using autouse_fixture using fixture2' in stdout
    )

@pytest.mark.parametrize('autouse_scope', [
    'session',
    'module',
    pytest.param('function', marks=pytest.mark.xfail)
])
def test_session_autouse_and_usefixture_module_scope_runs_before_function_fixtures(testdir, autouse_scope):
    testdir.makepyfile("""
        import pytest
        from pytest_lazyfixture import lazy_fixture

        invocation_order = []

        @pytest.fixture(autouse=True, scope='{autouse_scope}')
        def autouse_fixture():
            invocation_order.append('using autouse_fixture')

        @pytest.fixture(scope='module')
        def module_fixture():
            invocation_order.append('using module fixture')

        @pytest.fixture
        def fixture1():
            invocation_order.append("using fixture1")
            return 'fixture1'

        @pytest.fixture
        def fixture2():
            invocation_order.append("using fixture2")
            return 'fixture2'

        @pytest.mark.usefixtures("module_fixture")
        @pytest.mark.parametrize("fixt", [lazy_fixture("fixture1"), lazy_fixture("fixture2")])
        def test_test(fixt):
            if fixt == 'fixture2':
                print(' '.join(invocation_order))
    """.format(autouse_scope=autouse_scope))
    result = testdir.runpytest('-s')
    assert 'using autouse_fixture using module fixture using fixture1 using fixture2' in result.stdout.str()

# https://github.com/TvoroG/pytest-lazy-fixture/issues/39
def test_module_scope_runs_before_function_fixtures(testdir):
    testdir.makepyfile("""
        import pytest
        from pytest_lazyfixture import lazy_fixture

        invocation_order = []

        @pytest.fixture(scope='module')
        def module_fixture():
            invocation_order.append('using module fixture')

        @pytest.fixture
        def fixture1():
            invocation_order.append("using fixture1")
            return 'fixture1'

        @pytest.fixture
        def fixture2():
            invocation_order.append("using fixture2")
            return 'fixture2'

        @pytest.mark.parametrize("fixt", [lazy_fixture("fixture1"), lazy_fixture("fixture2")])
        def test_test(fixt, module_fixture):
            if fixt == 'fixture2':
                print(' '.join(invocation_order))
    """)
    result = testdir.runpytest('-s')
    stdout = result.stdout.str()
    assert (
        # pytest==3.2.5
        'using fixture1 using module fixture using fixture2' in stdout
        or
        'using module fixture using fixture1 using fixture2' in stdout
    )

# https://github.com/TvoroG/pytest-lazy-fixture/issues/42
@pytest.mark.skipif(numpy is None, reason='numpy is not installed')
def test_numpy_array_as_value(testdir):
    testdir.makepyfile("""
        import pytest
        import numpy as np

        @pytest.mark.parametrize(
            'value',
            [
                np.arange(10, dtype=np.int64),
                np.arange(10, dtype=np.int32),
            ]
        )
        def test_bug(value):
            assert isinstance(value, np.ndarray)
    """)
    result = testdir.inline_run('-s')
    result.assertoutcome(passed=2)

# https://github.com/TvoroG/pytest-lazy-fixture/issues/46
def test_lazy_fixture_ids(testdir):
    testdir.makepyfile("""
        import pytest
        from pytest_lazyfixture import lazy_fixture

        @pytest.fixture()
        def foo():
            return "foo"

        @pytest.fixture(params=['spam', 'eggs'])
        def bar(request):
            return "bar-{}".format(request.param)

        @pytest.mark.parametrize("data", [lazy_fixture("foo"),
                                          lazy_fixture("bar")])
        def test_the_thing(data):
            assert False
    """)
    result = testdir.runpytest('--collect-only')
    stdout = result.stdout.str()
    assert 'test_the_thing[foo]' in stdout
    assert 'test_the_thing[bar-spam]' in stdout
    assert 'test_the_thing[bar-eggs]' in stdout

def test_eq():
    assert lazy_fixture("Lol") == lazy_fixture("Lol")
    assert lazy_fixture("Lol") != lazy_fixture("Wut")
    assert lazy_fixture("Lol") != 123


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">

        <title>File I/O (Featuring NIO.2) (The Java™ Tutorials >
            Essential Classes > Basic I/O)
</title>

     <meta name="description" content="This Java tutorial describes exceptions, basic input/output, concurrency, regular expressions, and the platform environment" />
     <meta name="keywords" content="java programming, learn java, java sample code, java exception, java input output, java threads, java regex, regular expressions, path, classpath, environment variable" />

A browser with JavaScript enabled is required for this page to operate properly.

                            Download
                                the JDK

                            Search the
                                Tutorials

                            Hide the TOC

        Trail: Essential Classes

Lesson: Basic I/O

Basic I/O

I/O Streams

Byte Streams

Character Streams

Buffered Streams

Scanning and Formatting

Scanning

Formatting

I/O from the Command Line

Data Streams

Object Streams

File I/O (Featuring NIO.2)

What Is a Path? (And Other File System Facts)

The Path Class

Path Operations

File Operations

Checking a File or Directory

Deleting a File or Directory

Copying a File or Directory

Moving a File or Directory

Managing Metadata (File and File Store Attributes)

Reading, Writing, and Creating Files

Random Access Files

Creating and Reading Directories

Links, Symbolic or Otherwise

Walking the File Tree

Finding Files

Watching a Directory for Changes

Other Useful Methods

Legacy File I/O Code

Summary

Questions and Exercises

                Home Page
                >
                Essential Classes
                >
                Basic I/O

                « Previous • Trail • Next »

File I/O (Featuring NIO.2)

Note: This tutorial reflects the file I/O
mechanism introduced in the JDK 7 release.
The Java SE 6 version of the File I/O tutorial was brief,
but you can download the
Java SE Tutorial 2008-03-14 version of the tutorial which contains the earlier File I/O content.

The java.nio.file package and its related package,
java.nio.file.attribute, provide comprehensive support
for file I/O and for accessing the default file system.
Though the API has many classes,
you need to focus on only a few entry points. You will see that
this API is very intuitive and easy to use.

The tutorial starts by asking
what is a path? Then, the
Path class, the primary entry point for the package, is introduced.
Methods in the Path class relating to
syntactic operations are explained.  The tutorial then moves on to the other primary
class in the package, the Files class, which contains
methods that deal with file operations.  First, some concepts common to many
file operations are introduced. The tutorial then covers methods for
checking,
deleting,
copying, and
moving files.

The tutorial shows how
metadata is managed, before moving on to
file I/O and
directory I/O.
Random access files are explained and issues specific to
symbolic and hard links are examined.

Next, some of the very powerful, but more advanced, topics are covered.
First, the capability to
recursively walk the file tree is demonstrated, followed by information about how to
search for files using wild cards. Next, how to
watch a directory for changes is explained and demonstrated.  Then,
methods that didn't fit elsewhere are given some attention.

Finally, if you have file I/O code written prior to the Java SE 7 release,
there is a
map from the old API to the new API, as well as important information about the File.toPath
method for developers who would like to
leverage the new API without rewriting existing code.

            « Previous
            •
            Trail
            •
            Next »

Problems with the examples? Try Compiling and Running
        the Examples: FAQs.

    Complaints? Compliments? Suggestions? Give
    us your feedback.

Your use of this page and all the material on pages under "The Java Tutorials" banner,
and all the material on pages under "The Java Tutorials" banner is subject to the Java SE Tutorial Copyright
and License.
Additionally, any example code contained in any of these Java
Tutorials pages is licensed under the
Code
Sample License.

About Oracle | Oracle Technology Network | Terms of Service

Copyright © 1995, 2011 Oracle and/or its affiliates. All rights reserved.

        Previous page: Object Streams

Next page: What Is a Path? (And Other File System Facts)

A browser with JavaScript enabled is required for this page to operate properly.


text:
package org.agmip.ace.io;

public class AceVersion {
    public static final byte ACEB_MAJOR_VERSION = 2;
    public static final byte ACEB_MINOR_VERSION = 0;
    public static final byte ACEB_REVISION_VERSION = 0;
}


text:
package org.elasticsearch.index.query;

import org.elasticsearch.common.xcontent.XContentBuilder;

import java.io.IOException;

/**
 * Builder for the 'has_parent' filter.
 */
public class HasParentFilterBuilder extends BaseFilterBuilder {

    private final QueryBuilder queryBuilder;
    private final FilterBuilder filterBuilder;
    private final String parentType;
    private String filterName;

    /**
     * @param parentType  The parent type
     * @param parentQuery The query that will be matched with parent documents
     */
    public HasParentFilterBuilder(String parentType, QueryBuilder parentQuery) {
        this.parentType = parentType;
        this.queryBuilder = parentQuery;
        this.filterBuilder = null;
    }

    /**
     * @param parentType   The parent type
     * @param parentFilter The filter that will be matched with parent documents
     */
    public HasParentFilterBuilder(String parentType, FilterBuilder parentFilter) {
        this.parentType = parentType;
        this.queryBuilder = null;
        this.filterBuilder = parentFilter;
    }

    public HasParentFilterBuilder filterName(String filterName) {
        this.filterName = filterName;
        return this;
    }

    @Override
    protected void doXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(HasParentFilterParser.NAME);
        if (queryBuilder != null) {
            builder.field("query");
            queryBuilder.toXContent(builder, params);
        } else if (filterBuilder != null) {
            builder.field("filter");
            filterBuilder.toXContent(builder, params);
        }
        builder.field("parent_type", parentType);
        if (filterName != null) {
            builder.field("_name", filterName);
        }
        builder.endObject();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.Management.ServiceBus;
using Microsoft.WindowsAzure.Management.ServiceBus.Models;

namespace Microsoft.WindowsAzure.Management.ServiceBus.Models
{
    /// <summary>
    /// A response to a request for a list of namespaces.
    /// </summary>
    public partial class ServiceBusNamespaceDescriptionResponse : OperationResponse, IEnumerable<NamespaceDescription>
    {
        private IList<NamespaceDescription> _namespaceDescriptions;

        /// <summary>
        /// The descriptions for the namespace.
        /// </summary>
        public IList<NamespaceDescription> NamespaceDescriptions
        {
            get { return this._namespaceDescriptions; }
            set { this._namespaceDescriptions = value; }
        }

        /// <summary>
        /// Initializes a new instance of the
        /// ServiceBusNamespaceDescriptionResponse class.
        /// </summary>
        public ServiceBusNamespaceDescriptionResponse()
        {
            this._namespaceDescriptions = new List<NamespaceDescription>();
        }

        /// <summary>
        /// Gets the sequence of NamespaceDescriptions.
        /// </summary>
        public IEnumerator<NamespaceDescription> GetEnumerator()
        {
            return this.NamespaceDescriptions.GetEnumerator();
        }

        /// <summary>
        /// Gets the sequence of NamespaceDescriptions.
        /// </summary>
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}


text:
<!doctype html>

<meta charset="utf-8">

<?php

require("functions.php");

error_reporting(config_error_reporting_level);

if(session_id() == '') {

    session_start();

}

date_default_timezone_set(config_default_timezone);

$user=get_user_data($_SESSION['login'],$_SESSION['password']);

if ($_GET['action']=='change')

{

	set_user_settings($user['id'],'auth_mechanism',$_POST['auth_mechanism']);

	set_user_settings($user['id'],'phone',$_POST['phone']);

	$user=get_user_data($_SESSION['login'],$_SESSION['password']);

}

if ($_GET['action']=='new_secret')

	{

		$time = floor(time() / 30);

		$g = new GoogleAuthenticator();

		$secret=$g->generateSecret();

		echo 'getURL('googlowy',$_SERVER['HTTP_HOST'],$secret); <- "proper" way of use doesn't work

		echo "https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/PHPSEC:".$user['login']."@".$_SERVER['HTTP_HOST']."?secret=".$secret;

		echo '" target="_blank" rel = "noreferrer">LINK';

		set_user_settings('gauth_secret',$secret);

	}

echo '

<form method="POST" action="user_settings.php?action=change">

Settings

 Authentication method

 <select name="auth_mechanism">

  <option value="email" ';

  if ($user['auth_mechanism']=="email") echo "selected";

echo '>Email</option>

	<option value="sms"';

	if ($user['auth_mechanism']=="sms") echo "selected";

	echo '>SMS</option>

	<option value="image"';

	if ($user['auth_mechanism']=="image") echo "selected";

	echo '>Image password</option>

	<option value="gauth"';

	if ($user['auth_mechanism']=="gauth") echo "selected";

	echo '>Google authenticator</option>

	</select>

 Additional info

	Phone (with country code (e.g. +44736525532): <input type="text" name="phone" value="'.$user['phone'].'" size="45">

	 Generate new Google Authenticator Secret to pair with your app

<input type="submit" value="SAVE">

</form>

';

?>


text:
"""Tests for the text file event formatter."""

import unittest

from plaso.formatters import text

from tests.formatters import test_lib

class TextEntryFormatterTest(test_lib.EventFormatterTestCase):
  """Tests for the text file entry event formatter."""

  def testInitialization(self):
    """Tests the initialization."""
    event_formatter = text.TextEntryFormatter()
    self.assertNotEqual(event_formatter, None)

  def testGetFormatStringAttributeNames(self):
    """Tests the GetFormatStringAttributeNames function."""
    event_formatter = text.TextEntryFormatter()

    expected_attribute_names = [u'text']

    self._TestGetFormatStringAttributeNames(
        event_formatter, expected_attribute_names)

  # TODO: add test for GetMessages.

if __name__ == '__main__':
  unittest.main()


text:
package fr.ourten.teabeans.value.specific;

import fr.ourten.teabeans.binding.specific.DoubleExpression;
import fr.ourten.teabeans.binding.specific.FloatBinding;
import fr.ourten.teabeans.binding.specific.FloatExpression;
import fr.ourten.teabeans.binding.specific.IntBinding;
import fr.ourten.teabeans.binding.specific.IntExpression;
import fr.ourten.teabeans.value.ObservableValue;

public interface FloatValue extends ObservableValue<Number>
{
    float get();

    default ObservableValue<Number> add(int term)
    {
        return FloatExpression.getExpression(() -> get() + term);
    }

    default ObservableValue<Number> add(long term)
    {
        return FloatExpression.getExpression(() -> get() + term);
    }

    default ObservableValue<Number> add(float term)
    {
        return FloatExpression.getExpression(() -> get() + term);
    }

    default ObservableValue<Number> add(double term)
    {
        return DoubleExpression.getExpression(() -> get() + term);
    }

    default ObservableValue<Number> subtract(int term)
    {
        return FloatExpression.getExpression(() -> get() - term);
    }

    default ObservableValue<Number> subtract(long term)
    {
        return FloatExpression.getExpression(() -> get() - term);
    }

    default ObservableValue<Number> subtract(float term)
    {
        return FloatExpression.getExpression(() -> get() - term);
    }

    default ObservableValue<Number> subtract(double term)
    {
        return DoubleExpression.getExpression(() -> get() - term);
    }

    default ObservableValue<Number> multiply(int term)
    {
        return FloatExpression.getExpression(() -> get() * term);
    }

    default ObservableValue<Number> multiply(long term)
    {
        return FloatExpression.getExpression(() -> get() * term);
    }

    default ObservableValue<Number> multiply(float term)
    {
        return FloatExpression.getExpression(() -> get() * term);
    }

    default ObservableValue<Number> multiply(double term)
    {
        return DoubleExpression.getExpression(() -> get() * term);
    }

    default ObservableValue<Number> divide(int term)
    {
        return FloatExpression.getExpression(() -> get() / term);
    }

    default ObservableValue<Number> divide(long term)
    {
        return FloatExpression.getExpression(() -> get() / term);
    }

    default ObservableValue<Number> divide(float term)
    {
        return FloatExpression.getExpression(() -> get() / term);
    }

    default ObservableValue<Number> divide(double term)
    {
        return DoubleExpression.getExpression(() -> get() / term);
    }

    default ObservableValue<Number> add(ObservableValue<? extends Number> term)
    {
        if (term instanceof FloatValue)
            return FloatExpression.getExpression(() -> get() + ((FloatValue) term).get(), term, this);

        return combine(term, (a, b) ->
        {
            if (b instanceof Integer)
                return (float) a + (Integer) b;
            if (b instanceof Float)
                return (float) a + (Float) b;
            if (b instanceof Double)
                return (float) a + (Double) b;
            if (b instanceof Long)
                return (float) a + (Long) b;
            if (b instanceof Short)
                return (float) a + (Short) b;
            if (b instanceof Byte)
                return (float) a + (Byte) b;
            return 0;
        });
    }

    default ObservableValue<Number> subtract(ObservableValue<? extends Number> term)
    {
        if (term instanceof FloatValue)
            return FloatExpression.getExpression(() -> get() - ((FloatValue) term).get(), term, this);

        return combine(term, (a, b) ->
        {
            if (b instanceof Integer)
                return (float) a - (Integer) b;
            if (b instanceof Float)
                return (float) a - (Float) b;
            if (b instanceof Double)
                return (float) a - (Double) b;
            if (b instanceof Long)
                return (float) a - (Long) b;
            if (b instanceof Short)
                return (float) a - (Short) b;
            if (b instanceof Byte)
                return (float) a - (Byte) b;
            return 0;
        });
    }

    default ObservableValue<Number> multiply(ObservableValue<? extends Number> factor)
    {
        if (factor instanceof FloatValue)
            return FloatExpression.getExpression(() -> get() * ((FloatValue) factor).get(), factor, this);

        return combine(factor, (a, b) ->
        {
            if (b instanceof Integer)
                return (float) a * (Integer) b;
            if (b instanceof Float)
                return (float) a * (Float) b;
            if (b instanceof Double)
                return (float) a * (Double) b;
            if (b instanceof Long)
                return (float) a * (Long) b;
            if (b instanceof Short)
                return (float) a * (Short) b;
            if (b instanceof Byte)
                return (float) a * (Byte) b;
            return 0;
        });
    }

    default ObservableValue<Number> divide(ObservableValue<? extends Number> divisor)
    {
        if (divisor instanceof FloatValue)
            return FloatExpression.getExpression(() -> get() / ((FloatValue) divisor).get(), divisor, this);

        return combine(divisor, (a, b) ->
        {
            if (b instanceof Integer)
                return (float) a / (Integer) b;
            if (b instanceof Float)
                return (float) a / (Float) b;
            if (b instanceof Double)
                return (float) a / (Double) b;
            if (b instanceof Long)
                return (float) a / (Long) b;
            if (b instanceof Short)
                return (float) a / (Short) b;
            if (b instanceof Byte)
                return (float) a / (Byte) b;
            return 0;
        });
    }

    default ObservableValue<Number> max(ObservableValue<? extends Number> toCompare)
    {
        if (toCompare instanceof FloatValue)
            return FloatExpression.getExpression(() -> Math.max(get(), ((FloatValue) toCompare).get()), toCompare, this);

        return combine(toCompare, (a, b) ->
        {
            if (b instanceof Integer)
                return Math.max((float) a, (Integer) b);
            if (b instanceof Float)
                return Math.max((float) a, (Float) b);
            if (b instanceof Double)
                return Math.max((float) a, (Double) b);
            if (b instanceof Long)
                return Math.max((float) a, (Long) b);
            if (b instanceof Short)
                return Math.max((float) a, (Short) b);
            if (b instanceof Byte)
                return Math.max((float) a, (Byte) b);
            return 0;
        });
    }

    default ObservableValue<Number> min(ObservableValue<? extends Number> toCompare)
    {
        if (toCompare instanceof FloatValue)
            return FloatExpression.getExpression(() -> Math.min(get(), ((FloatValue) toCompare).get()), toCompare, this);

        return combine(toCompare, (a, b) ->
        {
            if (b instanceof Integer)
                return Math.min((float) a, (Integer) b);
            if (b instanceof Float)
                return Math.min((float) a, (Float) b);
            if (b instanceof Double)
                return Math.min((float) a, (Double) b);
            if (b instanceof Long)
                return Math.min((float) a, (Long) b);
            if (b instanceof Short)
                return Math.min((float) a, (Short) b);
            if (b instanceof Byte)
                return Math.min((float) a, (Byte) b);
            return 0;
        });
    }

    default FloatBinding negate()
    {
        return FloatExpression.getExpression(() -> -get(), this);
    }

    default FloatBinding abs()
    {
        return FloatExpression.getExpression(() -> Math.abs(get()), this);
    }

    default IntBinding ceil()
    {
        return IntExpression.getExpression(() -> (int) Math.ceil(get()), this);
    }

    default IntBinding floor()
    {
        return IntExpression.getExpression(() -> (int) Math.floor(get()), this);
    }

    default IntBinding round()
    {
        return IntExpression.getExpression(() -> Math.round(get()), this);
    }
}


text:
import os

# 3p
from mock import Mock, MagicMock
from pyVmomi import vim  # pylint: disable=E0611
import simplejson as json

# datadog
from tests.checks.common import AgentCheckTest, Fixtures

FIXTURE_DIR = os.path.join(os.path.dirname(__file__), 'ci')

class MockedMOR(Mock):
    """
    Helper, generate a mocked Managed Object Reference (MOR) from the given attributes.
    """
    def __init__(self, **kwargs):
        # Deserialize `spec`
        if 'spec' in kwargs:
            kwargs['spec'] = getattr(vim, kwargs['spec'])

        # Mocking
        super(MockedMOR, self).__init__(**kwargs)

        # Handle special attributes
        name = kwargs.get('name')
        is_labeled = kwargs.get('label', False)

        self.name = name
        self.parent = None
        self.customValue = []

        if is_labeled:
            self.customValue.append(Mock(value="DatadogMonitored"))

class MockedContainer(Mock):
    TYPES = [vim.Datacenter, vim.Datastore, vim.HostSystem, vim.VirtualMachine]

    def __init__(self, **kwargs):
        # Mocking
        super(MockedContainer, self).__init__(**kwargs)

        self.topology = kwargs.get('topology')
        self.view_idx = 0

    def container_view(self, topology_node, vimtype):
        view = []

        def get_child_topology(attribute):
            entity = getattr(topology_node, attribute)
            try:
                for child in entity:
                    child_topology = self.container_view(child, vimtype)
                    view.extend(child_topology)
            except TypeError:
                child_topology = self.container_view(entity, vimtype)
                view.extend(child_topology)

        if isinstance(topology_node, vimtype):
            view = [topology_node]

        if hasattr(topology_node, 'childEntity'):
            get_child_topology('childEntity')
        elif hasattr(topology_node, 'hostFolder'):
            get_child_topology('hostFolder')
        elif hasattr(topology_node, 'host'):
            get_child_topology('host')
        elif hasattr(topology_node, 'vm'):
            get_child_topology('vm')

        return view

    @property
    def view(self):
        view = self.container_view(self.topology, self.TYPES[self.view_idx])
        self.view_idx += 1
        self.view_idx = self.view_idx % len(self.TYPES)
        return view

def create_topology(topology_json):
    """
    Helper, recursively generate a vCenter topology from a JSON description.
    Return a `MockedMOR` object.

    Examples:
      ```
      topology_desc = "
        {
          "childEntity": [
            {
              "hostFolder": {
                "childEntity": [
                  {
                    "spec": "ClusterComputeResource",
                    "name": "compute_resource1"
                  }
                ]
              },
              "spec": "Datacenter",
              "name": "datacenter1"
            }
          ],
          "spec": "Folder",
          "name": "rootFolder"
        }
      "

      topo = create_topology(topology_desc)

      assert isinstance(topo, Folder)
      assert isinstance(topo.childEntity[0].name) == "compute_resource1"
      ```
    """
    def rec_build(topology_desc):
        """
        Build MORs recursively.
        """
        parsed_topology = {}

        for field, value in topology_desc.iteritems():
            parsed_value = value
            if isinstance(value, dict):
                parsed_value = rec_build(value)
            elif isinstance(value, list):
                parsed_value = [rec_build(obj) for obj in value]
            else:
                parsed_value = value
            parsed_topology[field] = parsed_value

        mor = MockedMOR(**parsed_topology)

        # set parent
        for field, value in topology_desc.iteritems():
            if isinstance(parsed_topology[field], list):
                for m in parsed_topology[field]:
                    if isinstance(m, MockedMOR):
                        m.parent = mor
            elif isinstance(parsed_topology[field], MockedMOR):
                parsed_topology[field].parent = mor

        return mor

    return rec_build(json.loads(Fixtures.read_file(topology_json, sdk_dir=FIXTURE_DIR)))

class TestvSphereUnit(AgentCheckTest):
    """
    Unit tests for vSphere AgentCheck.
    """
    CHECK_NAME = "vsphere"

    def assertMOR(self, instance, name=None, spec=None, tags=None, count=None, subset=False):
        """
        Helper, assertion on vCenter Manage Object References.
        """
        instance_name = instance['name']
        candidates = []

        if spec:
            mor_list = self.check.morlist_raw[instance_name][spec]
        else:
            mor_list = [mor for _, mors in self.check.morlist_raw[instance_name].iteritems() for mor in mors]

        for mor in mor_list:
            if name is not None and name != mor['hostname']:
                continue

            if spec is not None and spec != mor['mor_type']:
                continue

            if tags is not None:
                if subset:
                    if not set(tags).issubset(set(mor['tags'])):
                        continue
                elif set(tags) != set(mor['tags']):
                    continue

            candidates.append(mor)

        # Assertions
        if count:
            self.assertEquals(len(candidates), count)
        else:
            self.assertTrue(len(candidates))

    def setUp(self):
        """
        Initialize and patch the check, i.e.
        * disable threading
        * create a unique container for MORs independent of the instance key
        """
        # Initialize
        config = {}
        self.load_check(config)

        # Disable threading
        self.check.pool = Mock(apply_async=lambda func, args: func(*args))

        # Create a container for MORs
        self.check.morlist_raw = {}

    def test_exclude_host(self):
        """
        Exclude hosts/vms not compliant with the user's `*_include` configuration.
        """
        # Method to test
        is_excluded = self.check._is_excluded

        # Sample(s)
        include_regexes = {
            'host_include': "f[o]+",
            'vm_include': "f[o]+",
        }

        # OK
        included_host = MockedMOR(spec="HostSystem", name="foo")
        included_vm = MockedMOR(spec="VirtualMachine", name="foo")

        self.assertFalse(is_excluded(included_host, include_regexes, None))
        self.assertFalse(is_excluded(included_vm, include_regexes, None))

        # Not OK!
        excluded_host = MockedMOR(spec="HostSystem", name="bar")
        excluded_vm = MockedMOR(spec="VirtualMachine", name="bar")

        self.assertTrue(is_excluded(excluded_host, include_regexes, None))
        self.assertTrue(is_excluded(excluded_vm, include_regexes, None))

    def test_exclude_non_labeled_vm(self):
        """
        Exclude "non-labeled" virtual machines when the user configuration instructs to.
        """
        # Method to test
        is_excluded = self.check._is_excluded

        # Sample(s)
        include_regexes = None
        include_only_marked = True

        # OK
        included_vm = MockedMOR(spec="VirtualMachine", name="foo", label=True)
        self.assertFalse(is_excluded(included_vm, include_regexes, include_only_marked))

        # Not OK
        included_vm = MockedMOR(spec="VirtualMachine", name="foo")
        self.assertTrue(is_excluded(included_vm, include_regexes, include_only_marked))

    def test_mor_discovery(self):
        """
        Explore the vCenter infrastructure to discover hosts, virtual machines.

        Input topology:
            ```
            rootFolder
                - datacenter1
                  - compute_resource1
                      - host1                   # Filtered out
                      - host2
                - folder1
                    - datacenter2
                      - compute_resource2
                          - host3
                            - vm1               # Not labeled
                            - vm2               # Filtered out
                            - vm3               # Powered off
                            - vm4
            ```
        """
        # Method to test
        discover_mor = self.check._discover_mor

        # Samples
        instance = {'name': 'vsphere_mock'}
        vcenter_topology = create_topology('vsphere_topology.json')
        tags = [u"toto"]
        include_regexes = {
            'host_include': "host[2-9]",
            'vm_include': "vm[^2]",
        }
        include_only_marked = True

        # mock pyvmomi stuff
        view_mock = MockedContainer(topology=vcenter_topology)
        viewmanager_mock = MagicMock(**{'CreateContainerView.return_value': view_mock})
        content_mock = MagicMock(viewManager=viewmanager_mock)
        server_mock = MagicMock()
        server_mock.configure_mock(**{'RetrieveContent.return_value': content_mock})
        self.check._get_server_instance = MagicMock(return_value=server_mock)

        # Discover hosts and virtual machines
        discover_mor(instance, tags, include_regexes, include_only_marked)

        # Assertions: 1 labaled+monitored VM + 2 hosts + 2 datacenters.
        self.assertMOR(instance, count=5)

        # ... on hosts
        self.assertMOR(instance, spec="host", count=2)
        self.assertMOR(
            instance,
            name="host2", spec="host",
            tags=[
                u"toto", u"vsphere_folder:rootFolder", u"vsphere_datacenter:datacenter1",
                u"vsphere_compute:compute_resource1", u"vsphere_cluster:compute_resource1",
                u"vsphere_type:host"
            ]
        )
        self.assertMOR(
            instance,
            name="host3", spec="host",
            tags=[
                u"toto", u"vsphere_folder:rootFolder", u"vsphere_folder:folder1",
                u"vsphere_datacenter:datacenter2", u"vsphere_compute:compute_resource2",
                u"vsphere_cluster:compute_resource2", u"vsphere_type:host"
            ]
        )

        # ...on VMs
        self.assertMOR(instance, spec="vm", count=1)
        self.assertMOR(
            instance,
            name="vm4", spec="vm", subset=True,
            tags=[
                u"toto", u"vsphere_folder:folder1", u"vsphere_datacenter:datacenter2",
                u"vsphere_compute:compute_resource2",u"vsphere_cluster:compute_resource2",
                u"vsphere_host:host3", u"vsphere_type:vm"
            ]
        )