text:
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Control = GTA.Control;

namespace NativeUI
{
    /// <summary>
    /// Helper class that handles all of your Menus. After instatiating it, you will have to add your menu by using the Add method.
    /// </summary>
    public class MenuPool
    {
        public bool MouseEdgeEnabled { set { _menuList.ForEach(m => m.MouseEdgeEnabled = value); } }

        public bool ControlDisablingEnabled { set { _menuList.ForEach(m => m.ControlDisablingEnabled = value); } }

        public bool ResetCursorOnOpen { set { _menuList.ForEach(m => m.ResetCursorOnOpen = value); } }

        public bool UseCursor { set { _menuList.ForEach(m => m.UseCursor = value); } }

        public bool FormatDescriptions { set { _menuList.ForEach(m => m.FormatDescriptions = value); } }

        public string AUDIO_LIBRARY { set { _menuList.ForEach(m => m.AUDIO_LIBRARY = value); } }

        public string AUDIO_UPDOWN { set { _menuList.ForEach(m => m.AUDIO_UPDOWN = value); } }

        public string AUDIO_SELECT { set { _menuList.ForEach(m => m.AUDIO_SELECT = value); } }

        public string AUDIO_BACK { set { _menuList.ForEach(m => m.AUDIO_BACK = value); } }

        public string AUDIO_ERROR { set { _menuList.ForEach(m => m.AUDIO_ERROR = value); } }

        public int WidthOffset { set { _menuList.ForEach(m => m.SetMenuWidthOffset(value)); } }

        public string CounterPretext { set { _menuList.ForEach(m => m.CounterPretext = value); } }

        public bool DisableInstructionalButtons { set { _menuList.ForEach(m => m.DisableInstructionalButtons(value)); } }

        public bool BannerInheritance = true;

        public bool OffsetInheritance = true;

        private readonly List<UIMenu> _menuList = new List<UIMenu>();

        /// <summary>
        /// Add your menu to the menu pool.
        /// </summary>
        /// <param name="menu"></param>
        public void Add(UIMenu menu)
        {
            _menuList.Add(menu);
        }

        /// <summary>
        /// Create and add a submenu to the menu pool.
        /// Adds an item with the given text to the menu, creates a corresponding submenu, and binds the submenu to the item.
        /// The submenu inherits its title from the menu, and its subtitle from the item text.
        /// </summary>
        /// <param name="menu">The parent menu to which the submenu must be added.</param>
        /// <param name="text">The name of the submenu.</param>
        /// <returns>The newly created submenu.</returns>
        public UIMenu AddSubMenu(UIMenu menu, string text)
        {
            Point Offset = Point.Empty;
            if (OffsetInheritance)
                Offset = menu.Offset;
            return AddSubMenu(menu, text, "", Offset);
        }

        /// <summary>
        /// Create and add a submenu to the menu pool with a custom offset.
        /// Adds an item with the given text to the menu, creates a corresponding submenu, and binds the submenu to the item.
        /// The submenu inherits its title from the menu, and its subtitle from the item text.
        /// </summary>
        /// <param name="menu">The parent menu to which the submenu must be added.</param>
        /// <param name="text">The name of the submenu</param>
        /// <param name="offset">The offset of the menu</param>
        /// <returns>The newly created submenu.</returns>
        public UIMenu AddSubMenu(UIMenu menu, string text, Point offset)
        {
            return AddSubMenu(menu, text, "", offset);
        }

        /// <summary>
        /// Create and add a submenu to the menu pool.
        /// Adds an item with the given text and description to the menu, creates a corresponding submenu, and binds the submenu to the item.
        /// The submenu inherits its title from the menu, and its subtitle from the item text.
        /// </summary>
        /// <param name="menu">The parent menu to which the submenu must be added.</param>
        /// <param name="text">The name of the submenu.</param>
        /// <param name="description">The name of the submenu.</param>
        /// <returns>The newly created submenu.</returns>
        public UIMenu AddSubMenu(UIMenu menu, string text, string description)
        {
            Point Offset = Point.Empty;
            if (OffsetInheritance)
                Offset = menu.Offset;
            return AddSubMenu(menu, text, description, Offset);
        }

        /// <summary>
        /// Create and add a submenu to the menu pool.
        /// Adds an item with the given text and description to the menu, creates a corresponding submenu, and binds the submenu to the item.
        /// The submenu inherits its title from the menu, and its subtitle from the item text.
        /// </summary>
        /// <param name="menu">The parent menu to which the submenu must be added.</param>
        /// <param name="text">The name of the submenu.</param>
        /// <param name="description">The name of the submenu.</param>
        /// <returns>The newly created submenu.</returns>
        public UIMenu AddSubMenu(UIMenu menu, string text, string description, Point offset)
        {
            UIMenuItem item = new UIMenuItem(text, description);
            menu.AddItem(item);
            UIMenu submenu = new UIMenu(menu.Title.Caption, text, offset);
            if (BannerInheritance && menu.BannerTexture != null)
                submenu.SetBannerType(submenu.BannerTexture);
            else if (BannerInheritance && menu.BannerRectangle != null)
                submenu.SetBannerType(submenu.BannerRectangle);
            else if (BannerInheritance && menu.BannerSprite != null)
                submenu.SetBannerType(menu.BannerSprite);
            Add(submenu);
            menu.BindMenuToItem(submenu, item);
            return submenu;
        }

        /// <summary>
        /// Refresh index of every menu in the pool.
        /// Use this after you have finished constructing the entire menu pool.
        /// </summary>
        public void RefreshIndex()
        {
            foreach (UIMenu menu in _menuList) menu.RefreshIndex();
        }

        /// <summary>
        /// Returns all of your menus.
        /// </summary>
        /// <returns></returns>
        public List<UIMenu> ToList()
        {
            return _menuList;
        }

        /// <summary>
        /// Processes all of your visible menus' controls.
        /// </summary>
        public void ProcessControl()
        {
            /*foreach (var menu in _menuList.Where(menu => menu.Visible)) // foreach works slower with List. Also why make a new enumerable every tick
            {
                menu.ProcessControl();
            }*/

            int count = _menuList.Count; // Cache count
            for (int i = 0; i < count; i++)
            {
                if (_menuList[i].Visible)
                    _menuList[i].ProcessControl();
            }
        }

        /// <summary>
        /// Processes all of your visible menus' keys.
        /// </summary>
        /// <param name="key"></param>
        public void ProcessKey(Keys key)
        {
            /*foreach (var menu in _menuList.Where(menu => menu.Visible))
            {
                menu.ProcessKey(key);
            }*/

            int count = _menuList.Count;
            for (int i = 0; i < count; i++)
            {
                if (_menuList[i].Visible)
                    _menuList[i].ProcessKey(key);
            }
        }

        /// <summary>
        /// Processes all of your visible menus' mouses.
        /// </summary>
        public void ProcessMouse()
        {
            /*foreach (var menu in _menuList.Where(menu => menu.Visible))
            {
                menu.ProcessMouse();
            }*/

            int count = _menuList.Count;
            for (int i = 0; i < count; i++)
            {
                if (_menuList[i].Visible)
                    _menuList[i].ProcessMouse();
            }
        }

        /// <summary>
        /// Draws all visible menus.
        /// </summary>
        public void Draw()
        {
            /*foreach (var menu in _menuList.Where(menu => menu.Visible))
            {
                menu.Draw();
            }*/

            int count = _menuList.Count;
            for (int i = 0; i < count; i++)
            {
                if (_menuList[i].Visible)
                    _menuList[i].Draw();
            }
        }

        /// <summary>
        /// Checks if any menu is currently visible.
        /// </summary>
        /// <returns>true if at least one menu is visible, false if not.</returns>
        public bool IsAnyMenuOpen()
        {
            return _menuList.Any(menu => menu.Visible);
        }

        /// <summary>
        /// Process all of your menus' functions. Call this in a tick event.
        /// </summary>
        public void ProcessMenus()
        {
            ProcessControl();
            ProcessMouse();
            Draw();
        }

        /// <summary>
        /// Closes all of your menus.
        /// </summary>
        public void CloseAllMenus()
        {
            foreach (var menu in _menuList.Where(menu => menu.Visible))
            {
                menu.Visible = false;
            }
        }

        public void SetBannerType(Sprite bannerType)
        {
            _menuList.ForEach(m => m.SetBannerType(bannerType));
        }

        public void SetBannerType(UIResRectangle bannerType)
        {
            _menuList.ForEach(m => m.SetBannerType(bannerType));
        }

        public void SetBannerType(string bannerPath)
        {
            _menuList.ForEach(m => m.SetBannerType(bannerPath));
        }

        public void SetKey(UIMenu.MenuControls menuControl, Control control)
        {
            _menuList.ForEach(m => m.SetKey(menuControl, control));
        }

        public void SetKey(UIMenu.MenuControls menuControl, Control control, int controllerIndex)
        {
            _menuList.ForEach(m => m.SetKey(menuControl, control, controllerIndex));
        }

        public void SetKey(UIMenu.MenuControls menuControl, Keys control)
        {
            _menuList.ForEach(m => m.SetKey(menuControl, control));
        }

        public void ResetKey(UIMenu.MenuControls menuControl)
        {
            _menuList.ForEach(m => m.ResetKey(menuControl));
        }

    }
}


text:
package org.pac.games;
import java.awt.Graphics;

/**
 * An drawing function which gets invoked several times a second by
 * the GameComponent update thread.
 */
public interface GamePainter{
    /**
     * Once added to a GameComponent, this paint function will be invoked
     * several times a second to render the game's display window.
     * @param g The graphics of a GameComponent's buffer that will be drawn
     *          to the screen.
     */
    public void paint(Graphics g);
}

redpajama_set_name: RedPajamaGithub


text:
title: "Additional GM Info"
sort_order: 6
sections:
  classic_samurai:
  cyber_samurai:
  cyber_samurai_addition: |
    Augmentation

    They are intended as a way to bypass the Honor leveling system, at the cost of giving up parts of your "humanity". Generally, the cost of an augmentation varies between 5 to 10 koku, depending on social stability (when a society is destabilized, the costs of manufacturing augmentations increase). Some corporations may give out augmentations as a reward for "service rendered". A character with the Infusion move can also create augmentations.

---
Tags

Weapons, Monastic Arts, and Invocations generally have range tags of close, near, and far. Weapons may also have additional tags as well (ceremonial, holy, concealing, and wargear). These tags help guide the narrative.

Weapon Special Abilities

Each weapon has their own unique special ability, which is used when you equip it. Normally, you may only equip one weapon at a time, though you can equip two weapons if you have the Dual Wielding kata.

Advantages and Disadvantages

Some weapon abilities may give you an advantage on certain moves. The GM may also give players advantages or disadvantages based on the fiction.

If you have an advantage, you roll on the move twice, and then choose the higher roll. If you have a disadvantage, you roll on the movie twice, and then choose the lower roll.

Focus versus Vigilance

When you are using Focus, you are taking an active, blatant stance to respond to events. When you are using Vigilance, you are observing events as they occur and are subtly  manipulating them.


text:
/* GRANSYNTH - simple granular synthesis instrument

   Any parameter marked with '*' can receive updates from a real-time
   control source.

      p0  = output start time
      p1  = total duration
    * p2  = amplitude
      p3  = oscillator waveform (e.g., maketable("wave", ...))

      The following parameters determine the character of individual grains.

      p4  = grain envelope table

    * p5  = grain hop time (time between successive grains).  This is the
            inverse of grain density (grains per second); you can use
            "hoptime = 1 / density" to convert a table or real-time
            control source from density to hop time.

    * p6  = grain output time jitter
            Maximum randomly determined amount to add or subtract from the
            output start time for a grain, which is controlled by p5 (grain
            hop time).

    * p7  = grain duration minimum
    * p8  = grain duration maximum

    * p9  = grain amplitude multiplier minimum
    * p10 = grain amplitude multiplier maximum

    * p11 = grain pitch (linear octaves)

      p12 = grain transposition collection
            If this is a table, it contains a list of transpositions (in oct.pc)
            from which to select randomly.  If it's not a table, it's ignored.
            The table cannot be updated dynamically.  The values from the
            table are used to transpose p11 (pitch).
            [optional]

    * p13 = grain pitch jitter
            Maximum randomly determined amount to add or subtract from the
            current pitch (in linear octaves).  If p12 (transposition
            collection) is active, then jitter controls how much of the
            collection to choose from.  Note that jitter is still in linear
            octaves, although the transposition collection is in oct.pc.
            For example, if the collection is [0.00, 0.02, 0.05, 0.07], then a
            jitter value of octpch(0.05) will cause only the first three
            transpositions to be chosen, whereas a jitter value of octpch(0.07)
            would cause all four to be chosen.
            [optional; if missing, no pitch jitter]

      p14 = random seed (integer)
            [optional; if missing, uses system clock]

    * p15 = grain pan minimum (pctleft: 0-1)
    * p16 = grain pan maximum
            [optional, ignored if mono output; if both missing, min = 0 and
            min = 1; if max missing, max = min]

   John Gibson <johgibso at indiana dot edu>, 2/8/05
*/
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <ugens.h>
#include <PField.h>
#include <rt.h>
#include <rtdefs.h>
#include "GRANSYNTH.h"
#include "synthgrainstream.h"
//#define NDEBUG     // disable asserts
#include <assert.h>

#define DEBUG

#define USAGE_MESSAGE \
"Usage:\n" \
"  GRANSYNTH(start, dur, amp, waveform, grain_env, grain_hoptime,\n" \
"    grain_output_jitter, grain_dur_min, grain_dur_max, grain_amp_min,\n" \
"    grain_amp_max, grain_pitch, grain_transposition_collection,\n" \
"    grain_pitch_jitter, random_seed, grain_pan_min, grain_pan_max\n"

GRANSYNTH::GRANSYNTH()
	: _branch(0), _stream(NULL), _block(NULL)
{
}

GRANSYNTH::~GRANSYNTH()
{
   delete _stream;
   delete [] _block;
}

int GRANSYNTH::init(double p[], int n_args)
{
   _nargs = n_args;
   if (_nargs < 11 || _nargs > 17)
      return die("GRANSYNTH", USAGE_MESSAGE);
   const double outskip = p[0];
   const double dur = p[1];
   const int seed = _nargs > 14 ? int(p[14]) : 0;

   if (rtsetoutput(outskip, dur, this) == -1)
      return DONT_SCHEDULE;

   if (outputChannels() > 2)
      return die("GRANSYNTH", "You can have only mono or stereo output.");
   _stereoOut = (outputChannels() == 2);

   int length;
   double *table = (double *) getPFieldTable(3, &length);
   if (table == NULL)
      return die("GRANSYNTH", "You must create a table containing the "
                              "oscillator waveform.");
   _stream = new SynthGrainStream(SR, table, length, outputChannels(), seed);

   table = (double *) getPFieldTable(4, &length);
   if (table == NULL)
      return die("GRANSYNTH", "You must create a table containing the grain "
                              "envelope.");
   _stream->setGrainEnvelopeTable(table, length);

   if (_nargs > 12) {
      table = (double *) getPFieldTable(12, &length);
      if (table != NULL)
         _stream->setGrainTranspositionCollection(table, length);
   }

   return nSamps();
}

void GRANSYNTH::doupdate()
{
   double p[_nargs];
   update(p, _nargs, kAmp | kHopTime | kOutJitter | kMinDur | kMaxDur
         | kMinAmp | kMaxAmp | kPitch | kPitchJitter | kMinPan | kMaxPan);

   _amp = p[2];
   _stream->setGrainHop(p[5]);
   _stream->setOutputJitter(p[6]);
   _stream->setGrainDuration(p[7], p[8]);
   _stream->setGrainAmp(p[9], p[10]);
   _stream->setGrainPitch(p[11]);
   if (_nargs > 13)
      _stream->setGrainPitchJitter(p[13]);
   if (_nargs > 15 && _stereoOut) {
      const double min = p[15];
      const double max = _nargs > 16 ? p[16] : min;
      _stream->setGrainPan(min, max);
   }
}

int GRANSYNTH::configure()
{
   _block = new float [RTBUFSAMPS * outputChannels()];
   return _block ? 0 : -1;
}

inline const int min(const int a, const int b)
{
   return a < b ? a : b;
}

#if 0    // shows how to do single-frame I/O, but we use block I/O instead.

int GRANSYNTH::run()
{
   const int frames = framesToRun();
   const int outchans = outputChannels();
   int i;
   for (i = 0; i < frames; i++) {
      if (--_branch <= 0) {
         doupdate();
         _branch = getSkip();
      }

      _stream->prepare();

      float out[outchans];
      if (outchans == 2) {
         out[0] = _stream->lastL() * _amp;
         out[1] = _stream->lastR() * _amp;
      }
      else
         out[0] = _stream->lastL() * _amp;

      rtaddout(out);
      increment();
   }

   return i;
}

#else

int GRANSYNTH::run()
{
   // NOTE: Without a lot more code, we can't guarantee that doupdate will
   // be called exactly every getSkip() samples, the way we can when not doing
   // block I/O.  But this seems worth sacrificing for the clear performance
   // improvement that block I/O offers.

   const int frames = framesToRun();
   int blockframes = min(frames, getSkip());
   int framesdone = 0;
   while (1) {
      if (_branch <= 0) {
         doupdate();
         _branch = getSkip();
      }
      _branch -= blockframes;

      _stream->processBlock(_block, blockframes, _amp);
      rtbaddout(_block, blockframes);
      increment(blockframes);
      framesdone += blockframes;
      if (framesdone == frames)
         break;
      assert(framesdone < frames);
      const int remaining = frames - framesdone;
      if (remaining < blockframes)
         blockframes = remaining;
   }
   return frames;
}

#endif

Instrument *makeGRANSYNTH()
{
   GRANSYNTH *inst;

   inst = new GRANSYNTH();
   inst->set_bus_config("GRANSYNTH");

   return inst;
}

#ifndef EMBEDDED
void rtprofile()
{
   RT_INTRO("GRANSYNTH", makeGRANSYNTH);
}
#endif


text:
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                BC Paranormal

						Home

                        About

                        Equiptment

                        Contact


text:
namespace mc {
  level_info::level_info() : coord() {
  }

  level_info::level_info(region_ptr _region, int x, int z) : _region(_region), coord(x, z) {
  }

  level_info::level_info(region_ptr _region, utils::level_coord coord) : _region(_region) {
    utils::level_coord rc = utils::path_to_region_coord(_region->get_path());
    this->coord = utils::level_coord(rc.get_x() + coord.get_x(),
                                     rc.get_z() + coord.get_z());
  }

  std::string level_info::get_path() {
    std::stringstream ss;
    ss << _region->get_path().string() << "(" << coord.get_x() << "," << coord.get_z() << ")";
    return ss.str();
  }

  time_t level_info::modification_time() {
    return _region->read_modification_time(coord.get_x(), coord.get_z());
  }

  region_ptr level_info::get_region() {
    return _region;
  }

  bool level_info::operator<(const level_info& other) const {
    return coord < other.coord;
  }

  level_info level_info::rotate(int degrees) {
    return level_info(_region, coord.rotate(degrees));
  }

  int level_info::get_x() {
    return coord.get_x();
  }

  int level_info::get_z() {
    return coord.get_z();
  }

  const utils::level_coord level_info::get_coord() {
    return coord;
  }
}


text:
#!/usr/bin/python
# -*- coding: utf-8 -*-

#------------------------------------------------------------------------------#
# Dataset download and installation in current directory                       #
# ============================================================================ #
# Developer:    Chavaillaz Johan                                               #
# Filename:     DatasetInstallation.py                                         #
# Version:      1.0                                                            #
#                                                                              #
# Licensed to the Apache Software Foundation (ASF) under one                   #
# or more contributor license agreements. See the NOTICE file                  #
# distributed with this work for additional information                        #
# regarding copyright ownership. The ASF licenses this file                    #
# to you under the Apache License, Version 2.0 (the                            #
# "License"); you may not use this file except in compliance                   #
# with the License. You may obtain a copy of the License at                    #
#                                                                              #
# http://www.apache.org/licenses/LICENSE-2.0                                   #
#                                                                              #
# Unless required by applicable law or agreed to in writing,                   #
# software distributed under the License is distributed on an                  #
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY                       #
# KIND, either express or implied. See the License for the                     #
# specific language governing permissions and limitations                      #
# under the License.                                                           #
#                                                                              #
#------------------------------------------------------------------------------#

#------------------------------------------------------------------------------#
#                                                                              #
#                               LIBRARIES IMPORT                               #
#                                                                              #
#------------------------------------------------------------------------------#

import os, sys
import tarfile
import argparse
import urllib.request
import shutil
import glob

#------------------------------------------------------------------------------#
#                                                                              #
#                             UTILITIES FUNCTIONS                              #
#                                                                              #
#------------------------------------------------------------------------------#

def downloadBinary(url, destination):
	with urllib.request.urlopen(url) as download:
		file = open(destination, 'wb')
		file.write(download.read())
		file.close()

def untar(path, extract_path):
	tar = tarfile.open(path, 'r')
	for item in tar:
		tar.extract(item, extract_path)
		if item.name.find(".tgz") != -1 or item.name.find(".tar") != -1:
			extract(item.name, "./" + item.name[:item.name.rfind('/')])

def renameIncremental(dir, pattern):
	i = 0
	for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
		i += 1
		# Get title and extension of the current file
		title, ext = os.path.splitext(os.path.basename(pathAndFilename))
		# Rename current file
		os.rename(pathAndFilename, os.path.join(dir, str(i) + ext))

#------------------------------------------------------------------------------#
#                                                                              #
#                                     MAIN                                     #
#                                                                              #
#------------------------------------------------------------------------------#

if __name__ == '__main__':

	# Create argument parser to help user
	parser = argparse.ArgumentParser(
		description='Dataset installation used to train neural network for optical character recognition.'
	)

	# Show help if one of the arguments is missing
	if len(sys.argv) != 1:
		parser.print_help()
		sys.exit()

	# Installer configuration
	datasetPath = r'Dataset/'
	datasetFile = r'Chars74k.tgz'

	# Delete dataset folder
	if os.path.exists(datasetPath):
		print("Deleting old dataset ...")
		shutil.rmtree('Dataset')

	# Create dataset folder
	os.makedirs(datasetPath)

	# Download dataset file
	print("Downloading dataset ...")
	downloadBinary('http://www.ee.surrey.ac.uk/CVSSP/demos/chars74k/EnglishFnt.tgz', datasetPath + datasetFile)

	# Untar dataset file
	print("Untaring dataset ...")
	untar(datasetPath + datasetFile, datasetPath)

	# Rename dataset file for each 62 datasets [1, 62]
	print("Preparing dataset ...")
	for i in range(1, 63):

		# Folder that contains samples
		sampleFolder = datasetPath + "English/Fnt/Sample"

		# Default folder name of the dataset
		folderPath = sampleFolder + str(i).zfill(3);

		# Rename each file in the folder to be accessed more easily
		renameIncremental(folderPath, r'*.png')

		# Rename folder to be accessed more easily
		os.rename(folderPath, sampleFolder + str(i));

	print("Dataset successfully installed !")


text:
package org.kie.server.api.marshalling;

import java.util.Set;

import org.kie.server.api.marshalling.jaxb.JaxbMarshaller;
import org.kie.server.api.marshalling.json.JSONMarshaller;
import org.kie.server.api.marshalling.xstream.XStreamMarshaller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Default implementation of marshaller builder
 */
public class BaseMarshallerBuilder implements MarshallerBuilder {
    private static final Logger logger = LoggerFactory.getLogger(BaseMarshallerBuilder.class);

    @Override
    public Marshaller build(Set<Class<?>> classes, MarshallingFormat format, ClassLoader classLoader) {
        switch ( format ) {
            case XSTREAM:
                logger.debug("About to build default instance of XStream marshaller with classes {} and class loader {}", classes, classLoader);
                return new XStreamMarshaller( classes, classLoader );
            case JAXB:
                logger.debug("About to build default instance of JAXB marshaller with classes {} and class loader {}", classes, classLoader);
                return new JaxbMarshaller(classes, classLoader);
            case JSON:
                logger.debug("About to build default instance of JSON marshaller with classes {} and class loader {}", classes, classLoader);
                return new JSONMarshaller(classes, classLoader);
            default:
                logger.error( "Unsupported marshalling format: " + format );
        }
        return null;
    }
}


text:
package router

import (
	"context"
	"fmt"
	"net"
	"time"

	g "github.com/onsi/ginkgo"
	o "github.com/onsi/gomega"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/util/wait"
	admissionapi "k8s.io/pod-security-admission/api"

	routeclientset "github.com/openshift/client-go/route/clientset/versioned"

	exutil "github.com/openshift/origin/test/extended/util"
	exurl "github.com/openshift/origin/test/extended/util/url"
)

var _ = g.Describe("[sig-network][Feature:Router][apigroup:route.openshift.io]", func() {
	defer g.GinkgoRecover()
	var (
		oc          *exutil.CLI
		ns          string
		routerImage string
		isFIPS      bool
	)
	const (
		pemData = `-----BEGIN CERTIFICATE-----
MIIDIjCCAgqgAwIBAgIBBjANBgkqhkiG9w0BAQUFADCBoTELMAkGA1UEBhMCVVMx
CzAJBgNVBAgMAlNDMRUwEwYDVQQHDAxEZWZhdWx0IENpdHkxHDAaBgNVBAoME0Rl
ZmF1bHQgQ29tcGFueSBMdGQxEDAOBgNVBAsMB1Rlc3QgQ0ExGjAYBgNVBAMMEXd3
dy5leGFtcGxlY2EuY29tMSIwIAYJKoZIhvcNAQkBFhNleGFtcGxlQGV4YW1wbGUu
Y29tMB4XDTE2MDExMzE5NDA1N1oXDTI2MDExMDE5NDA1N1owfDEYMBYGA1UEAxMP
d3d3LmV4YW1wbGUuY29tMQswCQYDVQQIEwJTQzELMAkGA1UEBhMCVVMxIjAgBgkq
hkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20xEDAOBgNVBAoTB0V4YW1wbGUx
EDAOBgNVBAsTB0V4YW1wbGUwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAM0B
u++oHV1wcphWRbMLUft8fD7nPG95xs7UeLPphFZuShIhhdAQMpvcsFeg+Bg9PWCu
v3jZljmk06MLvuWLfwjYfo9q/V+qOZVfTVHHbaIO5RTXJMC2Nn+ACF0kHBmNcbth
OOgF8L854a/P8tjm1iPR++vHnkex0NH7lyosVc/vAgMBAAGjDTALMAkGA1UdEwQC
MAAwDQYJKoZIhvcNAQEFBQADggEBADjFm5AlNH3DNT1Uzx3m66fFjqqrHEs25geT
yA3rvBuynflEHQO95M/8wCxYVyuAx4Z1i4YDC7tx0vmOn/2GXZHY9MAj1I8KCnwt
Jik7E2r1/yY0MrkawljOAxisXs821kJ+Z/51Ud2t5uhGxS6hJypbGspMS7OtBbw7
8oThK7cWtCXOldNF6ruqY1agWnhRdAq5qSMnuBXuicOP0Kbtx51a1ugE3SnvQenJ
nZxdtYUXvEsHZC/6bAtTfNh+/SwgxQJuL2ZM+VG3X2JIKY8xTDui+il7uTh422lq
wED8uwKl+bOj6xFDyw4gWoBxRobsbFaME8pkykP1+GnKDberyAM=
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDNAbvvqB1dcHKYVkWzC1H7fHw+5zxvecbO1Hiz6YRWbkoSIYXQ
EDKb3LBXoPgYPT1grr942ZY5pNOjC77li38I2H6Pav1fqjmVX01Rx22iDuUU1yTA
tjZ/gAhdJBwZjXG7YTjoBfC/OeGvz/LY5tYj0fvrx55HsdDR+5cqLFXP7wIDAQAB
AoGAfE7P4Zsj6zOzGPI/Izj7Bi5OvGnEeKfzyBiH9Dflue74VRQkqqwXs/DWsNv3
c+M2Y3iyu5ncgKmUduo5X8D9To2ymPRLGuCdfZTxnBMpIDKSJ0FTwVPkr6cYyyBk
5VCbc470pQPxTAAtl2eaO1sIrzR4PcgwqrSOjwBQQocsGAECQQD8QOra/mZmxPbt
bRh8U5lhgZmirImk5RY3QMPI/1/f4k+fyjkU5FRq/yqSyin75aSAXg8IupAFRgyZ
W7BT6zwBAkEA0A0ugAGorpCbuTa25SsIOMxkEzCiKYvh0O+GfGkzWG4lkSeJqGME
keuJGlXrZNKNoCYLluAKLPmnd72X2yTL7wJARM0kAXUP0wn324w8+HQIyqqBj/gF
Vt9Q7uMQQ3s72CGu3ANZDFS2nbRZFU5koxrggk6lRRk1fOq9NvrmHg10AQJABOea
pgfj+yGLmkUw8JwgGH6xCUbHO+WBUFSlPf+Y50fJeO+OrjqPXAVKeSV3ZCwWjKT4
9viXJNJJ4WfF0bO/XwJAOMB1wQnEOSZ4v+laMwNtMq6hre5K8woqteXICoGcIWe8
u3YLAbyW/lHhOCiZu2iAI8AbmXem9lW6Tr7p/97s0w==
-----END RSA PRIVATE KEY-----
`
	)

	g.AfterEach(func() {
		if g.CurrentGinkgoTestDescription().Failed {
			client := routeclientset.NewForConfigOrDie(oc.AdminConfig()).RouteV1().Routes(ns)
			if routes, _ := client.List(context.Background(), metav1.ListOptions{}); routes != nil {
				outputIngress(routes.Items...)
			}
			selector, err := labels.Parse("test=router-scoped")
			if err != nil {
				panic(err)
			}
			exutil.DumpPodsCommand(oc.AdminKubeClient(), ns, selector, "cat /etc/crypto-policies/back-ends/opensslcnf.config")
			exutil.DumpPodLogsStartingWith("router-", oc)
		}
	})

	oc = exutil.NewCLIWithPodSecurityLevel("router-certs", admissionapi.LevelBaseline)

	g.BeforeEach(func() {
		ns = oc.Namespace()

		var err error
		routerImage, err = exutil.FindRouterImage(oc)
		o.Expect(err).NotTo(o.HaveOccurred())

		isFIPS, err = exutil.IsFIPS(oc.AdminKubeClient().CoreV1())
		o.Expect(err).NotTo(o.HaveOccurred())

		configPath := exutil.FixturePath("testdata", "router", "router-common.yaml")
		err = oc.AsAdmin().Run("new-app").Args("-f", configPath).Execute()
		o.Expect(err).NotTo(o.HaveOccurred())
	})

	g.When("FIPS is enabled", func() {
		g.Describe("the HAProxy router", func() {
			g.It("should not work when configured with a 1024-bit RSA key [apigroup:template.openshift.io]", func() {
				if !isFIPS {
					g.Skip("skipping on non-FIPS cluster")
				}

				configPath := exutil.FixturePath("testdata", "router", "router-scoped.yaml")
				g.By(fmt.Sprintf("creating a router from a config file %q", configPath))
				err := oc.AsAdmin().Run("new-app").Args("-f", configPath,
					"-p=IMAGE="+routerImage,
					`-p=ROUTER_NAME=test-1024bit`,
					`-p=DEFAULT_CERTIFICATE=`+pemData,
				).Execute()
				o.Expect(err).NotTo(o.HaveOccurred())

				ns := oc.KubeFramework().Namespace.Name
				execPod := exutil.CreateExecPodOrFail(oc.AdminKubeClient(), ns, "execpod")
				defer func() {
					oc.AdminKubeClient().CoreV1().Pods(ns).Delete(context.Background(), execPod.Name, *metav1.NewDeleteOptions(1))
				}()

				var routerIP string
				err = wait.Poll(time.Second, changeTimeoutSeconds*time.Second, func() (bool, error) {
					pod, err := oc.KubeFramework().ClientSet.CoreV1().Pods(oc.KubeFramework().Namespace.Name).Get(context.Background(), "router-scoped", metav1.GetOptions{})
					if err != nil {
						return false, err
					}
					routerIP = pod.Status.PodIP
					podIsReady := podConditionStatus(pod, corev1.PodReady)

					return len(routerIP) != 0 && podIsReady == corev1.ConditionTrue, nil
				})
				o.Expect(err).To(o.HaveOccurred())
			})
		})
	})

	g.When("FIPS is disabled", func() {
		g.Describe("the HAProxy router", func() {
			g.It("should serve routes when configured with a 1024-bit RSA key [apigroup:template.openshift.io]", func() {
				if isFIPS {
					g.Skip("skipping on FIPS cluster")
				}

				configPath := exutil.FixturePath("testdata", "router", "router-scoped.yaml")
				g.By(fmt.Sprintf("creating a router from a config file %q", configPath))
				err := oc.AsAdmin().Run("new-app").Args("-f", configPath,
					"-p=IMAGE="+routerImage,
					`-p=ROUTER_NAME=test-1024bit`,
					`-p=DEFAULT_CERTIFICATE=`+pemData,
				).Execute()
				o.Expect(err).NotTo(o.HaveOccurred())

				ns := oc.KubeFramework().Namespace.Name
				execPod := exutil.CreateExecPodOrFail(oc.AdminKubeClient(), ns, "execpod")
				defer func() {
					oc.AdminKubeClient().CoreV1().Pods(ns).Delete(context.Background(), execPod.Name, *metav1.NewDeleteOptions(1))
				}()

				var routerIP string
				err = wait.Poll(time.Second, changeTimeoutSeconds*time.Second, func() (bool, error) {
					pod, err := oc.KubeFramework().ClientSet.CoreV1().Pods(oc.KubeFramework().Namespace.Name).Get(context.Background(), "router-scoped", metav1.GetOptions{})
					if err != nil {
						return false, err
					}
					routerIP = pod.Status.PodIP
					podIsReady := podConditionStatus(pod, corev1.PodReady)

					return len(routerIP) != 0 && podIsReady == corev1.ConditionTrue, nil
				})
				o.Expect(err).NotTo(o.HaveOccurred())

				g.By("waiting for the router's healthz endpoint to respond")
				healthzURI := fmt.Sprintf("http://%s/healthz", net.JoinHostPort(routerIP, "1936"))
				healthzt := exurl.NewTester(oc.AdminKubeClient(), ns).WithErrorPassthrough(true)
				defer healthzt.Close()
				healthzt.Within(
					time.Minute,
					exurl.Expect("GET", healthzURI).SkipTLSVerification().HasStatusCode(200),
				)

				g.By("waiting for the route to respond")
				url := "https://first.example.com/Letter"
				t := exurl.NewTester(oc.AdminKubeClient(), ns).WithErrorPassthrough(true)
				defer t.Close()
				t.Within(
					time.Minute,
					exurl.Expect("GET", url).Through(routerIP).SkipTLSVerification().HasStatusCode(200),
				)
			})
		})
	})
})


text:
<?php

namespace Google\Service\Contentwarehouse;

class AppsPeopleOzExternalMergedpeopleapiGender extends \Google\Model
{
  /**
   * @var string
   */
  public $addressMeAs;
  /**
   * @var string
   */
  public $customType;
  /**
   * @var string
   */
  public $formattedType;
  protected $metadataType = AppsPeopleOzExternalMergedpeopleapiPersonFieldMetadata::class;
  protected $metadataDataType = '';
  /**
   * @var string
   */
  public $type;

  /**
   * @param string
   */
  public function setAddressMeAs($addressMeAs)
  {
    $this->addressMeAs = $addressMeAs;
  }
  /**
   * @return string
   */
  public function getAddressMeAs()
  {
    return $this->addressMeAs;
  }
  /**
   * @param string
   */
  public function setCustomType($customType)
  {
    $this->customType = $customType;
  }
  /**
   * @return string
   */
  public function getCustomType()
  {
    return $this->customType;
  }
  /**
   * @param string
   */
  public function setFormattedType($formattedType)
  {
    $this->formattedType = $formattedType;
  }
  /**
   * @return string
   */
  public function getFormattedType()
  {
    return $this->formattedType;
  }
  /**
   * @param AppsPeopleOzExternalMergedpeopleapiPersonFieldMetadata
   */
  public function setMetadata(AppsPeopleOzExternalMergedpeopleapiPersonFieldMetadata $metadata)
  {
    $this->metadata = $metadata;
  }
  /**
   * @return AppsPeopleOzExternalMergedpeopleapiPersonFieldMetadata
   */
  public function getMetadata()
  {
    return $this->metadata;
  }
  /**
   * @param string
   */
  public function setType($type)
  {
    $this->type = $type;
  }
  /**
   * @return string
   */
  public function getType()
  {
    return $this->type;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AppsPeopleOzExternalMergedpeopleapiGender::class, 'Google_Service_Contentwarehouse_AppsPeopleOzExternalMergedpeopleapiGender');


text:
Puppet::Type.type(:neutron_sfc_service_config).provide(
  :openstackconfig,
  :parent => Puppet::Type.type(:openstack_config).provider(:ruby)
) do

  def self.file_path
    '/etc/neutron/conf.d/neutron-server/networking-sfc.conf'
  end

  # added for backwards compatibility with older versions of inifile
  def file_path
    self.class.file_path
  end

end


text:
The selected phases provide no relevant data.

Participants' emails ({{vm.submittedEmails.length}} submitted)

                    {{email}}

<analysis-bar></analysis-bar>


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "OnlineFriendsInterface.h"
#include "OnlineSharingFacebook.h"
#include "OnlineSubsystemFacebookPackage.h"
#include "OnlinePresenceInterface.h"

/**
 * Info associated with an online friend on the facebook service
 */
class FOnlineFriendFacebook :
	public FOnlineFriend
{
public:

	// FOnlineUser

	virtual TSharedRef<const FUniqueNetId> GetUserId() const override;
	virtual FString GetRealName() const override;
	virtual FString GetDisplayName() const override;
	virtual bool GetUserAttribute(const FString& AttrName, FString& OutAttrValue) const override;

	// FOnlineFriend

	virtual EInviteStatus::Type GetInviteStatus() const override;
	virtual const FOnlineUserPresence& GetPresence() const override;

	// FOnlineFriendMcp

	/**
	 * Init/default constructor
	 */
	FOnlineFriendFacebook(const FString& InUserId=TEXT(""))
		: UserId(new FUniqueNetIdString(InUserId))
	{
	}

	/**
	 * Destructor
	 */
	virtual ~FOnlineFriendFacebook()
	{
	}

	/**
	 * Get account data attribute
	 *
	 * @param Key account data entry key
	 * @param OutVal [out] value that was found
	 *
	 * @return true if entry was found
	 */
	inline bool GetAccountData(const FString& Key, FString& OutVal) const
	{
		const FString* FoundVal = AccountData.Find(Key);
		if (FoundVal != NULL)
		{
			OutVal = *FoundVal;
			return true;
		}
		return false;
	}

	/** User Id represented as a FUniqueNetId */
	TSharedRef<const FUniqueNetId> UserId;
	/** Any addition account data associated with the friend */
	TMap<FString, FString> AccountData;
	/** @temp presence info */
	FOnlineUserPresence Presence;
};

/**
 * Facebook service implementation of the online friends interface
 */
class FOnlineFriendsFacebook :
	public IOnlineFriends
{

public:

	// IOnlineFriends

	virtual bool ReadFriendsList(int32 LocalUserNum, const FString& ListName, const FOnReadFriendsListComplete& Delegate = FOnReadFriendsListComplete()) override;
	virtual bool DeleteFriendsList(int32 LocalUserNum, const FString& ListName, const FOnDeleteFriendsListComplete& Delegate = FOnDeleteFriendsListComplete()) override;
	virtual bool SendInvite(int32 LocalUserNum, const FUniqueNetId& FriendId, const FString& ListName,  const FOnSendInviteComplete& Delegate = FOnSendInviteComplete()) override;
	virtual bool AcceptInvite(int32 LocalUserNum, const FUniqueNetId& FriendId, const FString& ListName, const FOnAcceptInviteComplete& Delegate = FOnAcceptInviteComplete()) override;
 	virtual bool RejectInvite(int32 LocalUserNum, const FUniqueNetId& FriendId, const FString& ListName) override;
 	virtual bool DeleteFriend(int32 LocalUserNum, const FUniqueNetId& FriendId, const FString& ListName) override;
	virtual bool GetFriendsList(int32 LocalUserNum, const FString& ListName, TArray< TSharedRef<FOnlineFriend> >& OutFriends) override;
	virtual TSharedPtr<FOnlineFriend> GetFriend(int32 LocalUserNum, const FUniqueNetId& FriendId, const FString& ListName) override;
	virtual bool IsFriend(int32 LocalUserNum, const FUniqueNetId& FriendId, const FString& ListName) override;
	virtual bool QueryRecentPlayers(const FUniqueNetId& UserId, const FString& Namespace) override;
	virtual bool GetRecentPlayers(const FUniqueNetId& UserId, const FString& Namespace, TArray< TSharedRef<FOnlineRecentPlayer> >& OutRecentPlayers) override;

	// FOnlineFriendsFacebook

PACKAGE_SCOPE:

	/**
	 * Constructor
	 *
	 * @param InSubsystem Facebook subsystem being used
	 */
	FOnlineFriendsFacebook(class FOnlineSubsystemFacebook* InSubsystem);

public:

	/**
	 * Destructor
	 */
	virtual ~FOnlineFriendsFacebook();

private:

	/**
	 * Should use the OSS param constructor instead
	 */
	FOnlineFriendsFacebook();

private:

	/**
	 * Delegate fired when we have a response after we have requested read permissions of the users friends list
	 *
	 * @param LocalUserNum		- The local player number the friends were read for
	 * @param bWasSuccessful	- Whether the permissions were updated successfully
	 */
	void OnReadFriendsPermissionsUpdated(int32 LocalUserNum, bool bWasSuccessful);

	/**
	 * Using the open graph for fb to read friends list, called when we have ensured correct permissions
	 *
	 * @param LocalUserNum - The local player number the friends were read for
	 * @param ListName - named list to read
	 */
	void ReadFriendsUsingGraphPath(int32 LocalUserNum, const FString& ListName);

	/** Handle to delegate used to notify this interface that permissions are updated, and that we can now read the friends list */
	FDelegateHandle RequestFriendsReadPermissionsDelegateHandle;

	/** Delegate called when reading the friends list is completed */
	FOnReadFriendsListComplete OnReadFriendsListCompleteDelegate;

private:

	/** Reference to the main facebook identity */
	IOnlineIdentityPtr IdentityInterface;

	/** Reference to the main facebook sharing interface */
	IOnlineSharingPtr SharingInterface;

	/** The collection of facebook friends received through the fb callbacks in ReadFriendsList */
	TArray< TSharedRef<FOnlineFriendFacebook> > CachedFriends;

	/** Config based list of fields to use when querying friends list */
	TArray<FString> FriendsFields;
};

typedef TSharedPtr<FOnlineFriendsFacebook, ESPMode::ThreadSafe> FOnlineFriendsFacebookPtr;


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
//using Microsoft.Build.Exceptions;
using NuGet.Common;
using NuGet.Resolver;
using NuGet.Versioning;
using NewPackageAction = NuGet.Client.Resolution.PackageAction;
using NuGet.Client;
using NuGet.Client.Installation;
using System.Threading;
using Newtonsoft.Json.Linq;
using NuGet.Client.Interop;
using System.Diagnostics;

namespace NuGet.Commands
{
    [Command(typeof(NuGetCommandResourceType), "restore", "RestoreCommandDescription",
        MinArgs = 0, MaxArgs = 1, UsageSummaryResourceName = "RestoreCommandUsageSummary",
        UsageDescriptionResourceName = "RestoreCommandUsageDescription",
        UsageExampleResourceName = "RestoreCommandUsageExamples")]
    public class RestoreCommand : DownloadCommandBase
    {
        // True means we're restoring for a solution; False means we're restoring packages
        // listed in a packages.config file.
        private bool _restoringForSolution;

        private string _solutionFileFullPath;
        private string _packagesConfigFileFullPath;

        // A flag indicating if the opt-out message should be displayed.
        private bool _outputOptOutMessage;

        // lock used to access _outputOptOutMessage.
        private readonly object _outputOptOutMessageLock = new object();

        [Option(typeof(NuGetCommandResourceType), "RestoreCommandRequireConsent")]
        public bool RequireConsent { get; set; }

        [Option(typeof(NuGetCommandResourceType), "RestoreCommandPackagesDirectory", AltName = "OutputDirectory")]
        public string PackagesDirectory { get; set; }

        [Option(typeof(NuGetCommandResourceType), "RestoreCommandSolutionDirectory")]
        public string SolutionDirectory { get; set; }

        /// <remarks>
        /// Meant for unit testing.
        /// </remarks>
        internal bool RestoringForSolution
        {
            get { return _restoringForSolution; }
        }

        /// <remarks>
        /// Meant for unit testing.
        /// </remarks>
        internal string SolutionFileFullPath
        {
            get { return _solutionFileFullPath; }
        }

        /// <remarks>
        /// Meant for unit testing.
        /// </remarks>
        internal string PackagesConfigFileFullPath
        {
            get { return _packagesConfigFileFullPath; }
        }

        [ImportingConstructor]
        public RestoreCommand()
            : this(MachineCache.Default)
        {
        }

        protected internal RestoreCommand(IPackageRepository cacheRepository) :
            base(cacheRepository)
        {
            _outputOptOutMessage = true;
        }

        internal void DetermineRestoreMode()
        {
            if (Arguments.Count == 0)
            {
                // look for solution files first
                _solutionFileFullPath = GetSolutionFile("");
                if (_solutionFileFullPath != null)
                {
                    _restoringForSolution = true;
                    if (Verbosity == Verbosity.Detailed)
                    {
                        Console.WriteLine(LocalizedResourceManager.GetString("RestoreCommandRestoringPackagesForSolution"), _solutionFileFullPath);
                    }

                    return;
                }

                // look for packages.config file
                if (FileSystem.FileExists(Constants.PackageReferenceFile))
                {
                    _restoringForSolution = false;
                    _packagesConfigFileFullPath = FileSystem.GetFullPath(Constants.PackageReferenceFile);
                    if (Verbosity == NuGet.Verbosity.Detailed)
                    {
                        Console.WriteLine(LocalizedResourceManager.GetString("RestoreCommandRestoringPackagesFromPackagesConfigFile"));
                    }

                    return;
                }

                throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_NoSolutionFileNorePackagesConfigFile"));
            }
            else
            {
                if (Path.GetFileName(Arguments[0]).Equals(Constants.PackageReferenceFile, StringComparison.OrdinalIgnoreCase))
                {
                    // restoring from packages.config file
                    _restoringForSolution = false;
                    _packagesConfigFileFullPath = FileSystem.GetFullPath(Arguments[0]);
                }
                else
                {
                    _restoringForSolution = true;
                    _solutionFileFullPath = GetSolutionFile(Arguments[0]);
                    if (_solutionFileFullPath == null)
                    {
                        throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_CannotLocateSolutionFile"));
                    }
                }
            }
        }

        /// <summary>
        /// Gets the solution file, in full path format. If <paramref name="solutionFileOrDirectory"/> is a file,
        /// that file is returned. Otherwise, searches for a *.sln file in
        /// directory <paramref name="solutionFileOrDirectory"/>. If exactly one sln file is found,
        /// that file is returned. If multiple sln files are found, an exception is thrown.
        /// If no sln files are found, returns null.
        /// </summary>
        /// <param name="solutionFileOrDirectory">The solution file or directory to search for solution files.</param>
        /// <returns>The full path of the solution file. Or null if no solution file can be found.</returns>
        private string GetSolutionFile(string solutionFileOrDirectory)
        {
            if (FileSystem.FileExists(solutionFileOrDirectory))
            {
                return FileSystem.GetFullPath(solutionFileOrDirectory);
            }

            // look for solution files
            var slnFiles = FileSystem.GetFiles(solutionFileOrDirectory, "*.sln").ToArray();
            if (slnFiles.Length > 1)
            {
                throw new InvalidOperationException(LocalizedResourceManager.GetString("Error_MultipleSolutions"));
            }

            if (slnFiles.Length == 1)
            {
                return FileSystem.GetFullPath(slnFiles[0]);
            }

            return null;
        }

        protected internal virtual IFileSystem CreateFileSystem(string path)
        {
            path = FileSystem.GetFullPath(path);
            return new PhysicalFileSystem(path);
        }

        private void ReadSettings()
        {
            if (_restoringForSolution || !String.IsNullOrEmpty(SolutionDirectory))
            {
                var solutionDirectory = _restoringForSolution ?
                    Path.GetDirectoryName(_solutionFileFullPath) :
                    SolutionDirectory;

                // Read the solution-level settings
                var solutionSettingsFile = Path.Combine(
                    solutionDirectory,
                    NuGetConstants.NuGetSolutionSettingsFolder);
                var fileSystem = CreateFileSystem(solutionSettingsFile);

                if (ConfigFile != null)
                {
                    ConfigFile = FileSystem.GetFullPath(ConfigFile);
                }

                Settings = NuGet.Settings.LoadDefaultSettings(
                    fileSystem: fileSystem,
                    configFileName: ConfigFile,
                    machineWideSettings: MachineWideSettings);

                // Recreate the source provider and credential provider
                SourceProvider = PackageSourceBuilder.CreateSourceProvider(Settings);
                HttpClient.DefaultCredentialProvider = new SettingsCredentialProvider(new ConsoleCredentialProvider(Console), SourceProvider, Console);
            }
        }

        private string GetPackagesFolder()
        {
            if (!String.IsNullOrEmpty(PackagesDirectory))
            {
                return PackagesDirectory;
            }

            var repositoryPath = Settings.GetRepositoryPath();
            if (!String.IsNullOrEmpty(repositoryPath))
            {
                return repositoryPath;
            }

            if (!String.IsNullOrEmpty(SolutionDirectory))
            {
                return Path.Combine(SolutionDirectory, CommandLineConstants.PackagesDirectoryName);
            }

            if (_restoringForSolution)
            {
                return Path.Combine(Path.GetDirectoryName(_solutionFileFullPath), CommandLineConstants.PackagesDirectoryName);
            }

            throw new InvalidOperationException(LocalizedResourceManager.GetString("RestoreCommandCannotDeterminePackagesFolder"));
        }

        // BUGBUG: NEED to use NuGet.Versioning.NuGetVersion and not the old SemanticVersion
        // Do a very quick check of whether a package in installed by checking whether the nupkg file exists
        private static bool IsPackageInstalled(IPackageRepository repository, IFileSystem packagesFolderFileSystem, PackageIdentity packageIdentity)
        {
            if (packageIdentity.Version != null)
            {
                // If we know exactly what package to lookup, check if it's already installed locally.
                // We'll do this by checking if the package directory exists on disk.
                var localRepository = (LocalPackageRepository)repository;
                var packagePaths = localRepository.GetPackageLookupPaths(packageIdentity.Id, new SemanticVersion(packageIdentity.Version.ToString()));
                return packagePaths.Any(packagesFolderFileSystem.FileExists);
            }
            return false;
        }

        private void EnsurePackageRestoreConsent(bool packageRestoreConsent)
        {
            if (RequireConsent && !packageRestoreConsent)
            {
                string message = string.Format(
                    CultureInfo.CurrentCulture,
                    LocalizedResourceManager.GetString("InstallCommandPackageRestoreConsentNotFound"),
                    NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
                throw new InvalidOperationException(message);
            }
        }

        private bool RestorePackage(
            IFileSystem packagesFolderFileSystem,
            PackageIdentity packageIdentity,
            bool packageRestoreConsent,
            ConcurrentQueue<JObject> satellitePackages)
        {
            // BUGBUG: Looks like we are creating PackageManager for every single restore. This is likely done to support execution in parallel
            var packageManager = CreatePackageManager(packagesFolderFileSystem, useSideBySidePaths: true);
            if (IsPackageInstalled(packageManager.LocalRepository, packagesFolderFileSystem, packageIdentity))
            {
                return false;
            }

            // BUGBUG: Investigate if the following lock is needed
            EnsurePackageRestoreConsent(packageRestoreConsent);
            if (RequireConsent && _outputOptOutMessage)
            {
                lock (_outputOptOutMessageLock)
                {
                    if (_outputOptOutMessage)
                    {
                        string message = String.Format(
                            CultureInfo.CurrentCulture,
                            LocalizedResourceManager.GetString("RestoreCommandPackageRestoreOptOutMessage"),
                            NuGet.Resources.NuGetResources.PackageRestoreConsentCheckBoxText.Replace("&", ""));
                        Console.WriteLine(message);
                        _outputOptOutMessage = false;
                    }
                }
            }

            SourceRepository = SourceRepositoryHelper.CreateSourceRepository(SourceProvider, Source);

            // BUGBUG: TO BE REMOVED AFTER INVESTIGATION
            using (packageManager.SourceRepository.StartOperation(
                RepositoryOperationNames.Restore,
                packageIdentity.Id,
                packageIdentity.Version == null ? null : packageIdentity.Version.ToString()))
            {
                // BUGBUG: Satellite packages should only be restored at the end. Find out Why first??
                //         And, then, handle it here

                var filesystemInstallationTarget = new FilesystemInstallationTarget(packageManager);

                // BUGBUG: Should consider using async method and await
                var task = SourceRepository.GetPackageMetadata(packageIdentity.Id, packageIdentity.Version);
                task.Wait();
                var packageJSON = task.Result;

                if (IsSatellitePackage(packageJSON))
                {
                    // Satellite packages would necessarily have to be installed later than the corresponding package.
                    // We'll collect them in a list to keep track and then install them later.
                    satellitePackages.Enqueue(packageJSON);
                    return true;
                }

                var packageAction = new NewPackageAction(NuGet.Client.PackageActionType.Download,
                    packageIdentity, packageJSON, filesystemInstallationTarget, SourceRepository, null);

                // BUGBUG: See PackageExtractor.cs for locking mechanism used to handle concurrency
                NuGet.Client.Installation.ActionExecutor actionExecutor = new Client.Installation.ActionExecutor();

                // BUGBUG: This is likely inefficient. Consider collecting all actions first and executing them in 1 shot
                var packageActions = new List<NewPackageAction>() { packageAction };
                actionExecutor.ExecuteActions(packageActions, Console);
                return true;
            }
        }

        private bool IsSatellitePackage(JObject packageJSON)
        {
            if (!String.IsNullOrEmpty(packageJSON[Properties.PackageId].ToString()) &&
                    packageJSON[Properties.PackageId].ToString().EndsWith('.' + packageJSON[Properties.Language].ToString(), StringComparison.OrdinalIgnoreCase))
            {
                // The satellite pack's Id is of the format <Core-Package-Id>.<Language>. Extract the core package id using this.
                // Additionally satellite packages have a strict dependency on the core package
                IEnumerable <PackageDependencySet> depEnum;
                var deps = packageJSON.Value<JArray>(Properties.DependencyGroups);
                if (deps == null)
                {
                    depEnum = Enumerable.Empty<PackageDependencySet>();
                }
                else
                {
                    depEnum = deps.Select(t => PackageJsonLd.DependencySetFromJson((JObject)t));
                }
                string corePackageId = packageJSON[Properties.PackageId].ToString().Substring(0, packageJSON[Properties.PackageId].ToString().Length - packageJSON[Properties.Language].ToString().Length - 1);
                return depEnum.SelectMany(s => s.Dependencies).Any(
                       d => d.Id.Equals(corePackageId, StringComparison.OrdinalIgnoreCase) &&
                       d.VersionSpec != null &&
                       d.VersionSpec.MaxVersion == d.VersionSpec.MinVersion && d.VersionSpec.IsMaxInclusive && d.VersionSpec.IsMinInclusive);
            }
            return false;
        }

        /// <returns>True if one or more packages are installed.</returns>
        private bool ExecuteInParallel(IFileSystem fileSystem, ICollection<InstalledPackageReference> installedPackageReferences)
        {
            bool packageRestoreConsent = new PackageRestoreConsent(Settings).IsGranted;
            int defaultConnectionLimit = ServicePointManager.DefaultConnectionLimit;
            if (installedPackageReferences.Count > defaultConnectionLimit)
            {
                ServicePointManager.DefaultConnectionLimit = Math.Min(10, installedPackageReferences.Count);
            }

            // The PackageSourceProvider reads from the underlying ISettings multiple times. One of the fields it reads is the password which is consequently decrypted
            // once for each package being installed. Per work item 2345, a couple of users are running into an issue where this results in an exception in native
            // code. Instead, we'll use a cached set of sources. This should solve the issue and also give us some perf boost.
            SourceProvider = new CachedPackageSourceProvider(SourceProvider);

            var satellitePackages = new ConcurrentQueue<JObject>();
            if (DisableParallelProcessing)
            {
                foreach (var package in installedPackageReferences)
                {
                    RestorePackage(fileSystem, package.Identity, packageRestoreConsent, satellitePackages);
                }

                InstallSatellitePackages(fileSystem, satellitePackages);

                return true;
            }

            var tasks = installedPackageReferences.Select(installedPackageReference =>
                            Task.Factory.StartNew(() => RestorePackage(fileSystem, installedPackageReference.Identity, packageRestoreConsent, satellitePackages))).ToArray();

            Task.WaitAll(tasks);
            // Return true if we installed any satellite packages or if any of our install tasks succeeded.
            // TODO: Satellite packages
            InstallSatellitePackages(fileSystem, satellitePackages);

            return true;
        }

        private bool InstallSatellitePackages(IFileSystem packagesFolderFileSystem, ConcurrentQueue<JObject> satellitePackages)
        {
            if (satellitePackages.Count == 0)
            {
                return false;
            }

            var packageManager = CreatePackageManager(packagesFolderFileSystem, useSideBySidePaths: true);
            var filesystemInstallationTarget = new FilesystemInstallationTarget(packageManager);
            var packageActions = satellitePackages.Select(packageJSON => new NewPackageAction(NuGet.Client.PackageActionType.Download,
                    new PackageIdentity(packageJSON[Properties.PackageId].ToString(), new NuGetVersion (packageJSON[Properties.Version].ToString())), packageJSON, filesystemInstallationTarget, SourceRepository, null));

            // BUGBUG: See PackageExtractor.cs for locking mechanism used to handle concurrency
            NuGet.Client.Installation.ActionExecutor actionExecutor = new Client.Installation.ActionExecutor();
            actionExecutor.ExecuteActions(packageActions, Console);

            return true;
        }

        private void InstallPackages(IFileSystem packagesFolderFileSystem, ICollection<InstalledPackageReference> installedPackageReferences)
        {
            bool installedAny = ExecuteInParallel(packagesFolderFileSystem, installedPackageReferences);
            if (!installedAny && installedPackageReferences.Count > 0)
            {
                Console.WriteLine(LocalizedResourceManager.GetString("InstallCommandNothingToInstall"), Constants.PackageReferenceFile);
            }
        }

        private void RestorePackagesFromConfigFile(string packageReferenceFilePath, IFileSystem packagesFolderFileSystem)
        {
            if (FileSystem.FileExists(packageReferenceFilePath))
            {
                if (Console.Verbosity == NuGet.Verbosity.Detailed)
                {
                    Console.WriteLine(LocalizedResourceManager.GetString("RestoreCommandRestoringPackagesListedInFile"), packageReferenceFilePath);
                }

                InstallPackages(packagesFolderFileSystem, GetInstalledPackageReferences(packageReferenceFilePath, projectName: null));
            }
        }

        private void RestorePackagesForSolution(IFileSystem packagesFolderFileSystem, string solutionFileFullPath)
        {
            var solutionDirectory = Path.GetDirectoryName(solutionFileFullPath);

            // restore packages for the solution
            var solutionConfigFilePath = Path.Combine(
                solutionDirectory,
                NuGetConstants.NuGetSolutionSettingsFolder,
                Constants.PackageReferenceFile);
            RestorePackagesFromConfigFile(solutionConfigFilePath, packagesFolderFileSystem);

            // restore packages for projects
            var installedPackageReferences = GetInstalledPackageReferencesFromSolutionFile(solutionFileFullPath);
            InstallPackages(packagesFolderFileSystem, installedPackageReferences);
        }

        private ICollection<InstalledPackageReference> GetInstalledPackageReferencesFromSolutionFile(string solutionFileFullPath)
        {
            ISolutionParser solutionParser;
            if (EnvironmentUtility.IsMonoRuntime)
            {
                solutionParser = new XBuildSolutionParser();
            }
            else
            {
                solutionParser = new MSBuildSolutionParser();
            }

            var installedPackageReferences = new HashSet<InstalledPackageReference>();
            IEnumerable<string> projectFiles = Enumerable.Empty<string>();
            try
            {
                projectFiles = solutionParser.GetAllProjectFileNames(FileSystem, solutionFileFullPath);
            }
            catch (System.Reflection.TargetInvocationException ex)
            {
                //if (ex.InnerException is InvalidProjectFileException)
                //{
                //    return GetPackageReferencesInDirectory(Path.GetDirectoryName(solutionFileFullPath));
                //}

                throw;
            }

            foreach (var projectFile in projectFiles)
            {
                if (!FileSystem.FileExists(projectFile))
                {
                    Console.WriteWarning(LocalizedResourceManager.GetString("RestoreCommandProjectNotFound"), projectFile);
                    continue;
                }

                string projectConfigFilePath = Path.Combine(
                    Path.GetDirectoryName(projectFile),
                    Constants.PackageReferenceFile);

                string projectName = Path.GetFileNameWithoutExtension(projectFile);

                installedPackageReferences.AddRange(GetInstalledPackageReferences(projectConfigFilePath, projectName));
            }

            return installedPackageReferences;
        }

        private static ICollection<InstalledPackageReference> GetInstalledPackageReferencesInDirectory(string directory)
        {
            var installedPackageReferences = new HashSet<InstalledPackageReference>();
            var configFiles = Directory.GetFiles(directory, "packages*.config", SearchOption.AllDirectories)
                .Where(f => Path.GetFileName(f).StartsWith("packages.", StringComparison.OrdinalIgnoreCase));
            foreach (var configFile in configFiles)
            {
                PackageReferenceFile file = new PackageReferenceFile(configFile);
                try
                {
                    installedPackageReferences.AddRange(CommandLineUtility.GetInstalledPackageReferences(file, requireVersion: true));
                }
                catch (InvalidOperationException)
                {
                    // Skip the file if it is not a valid xml file.
                }
            }

            return installedPackageReferences;
        }

        private static ICollection<InstalledPackageReference> GetInstalledPackageReferences(string fullConfigFilePath, string projectName)
        {
            var projectFileSystem = new PhysicalFileSystem(Path.GetDirectoryName(fullConfigFilePath));
            string configFileName = Path.GetFileName(fullConfigFilePath);

            PackageReferenceFile packageReferenceFile = new PackageReferenceFile(projectFileSystem, configFileName, projectName);
            return CommandLineUtility.GetInstalledPackageReferences(packageReferenceFile, requireVersion: true);
        }

        public override void ExecuteCommand()
        {
            CalculateEffectivePackageSaveMode();
            DetermineRestoreMode();
            if (_restoringForSolution && !String.IsNullOrEmpty(SolutionDirectory))
            {
                // option -SolutionDirectory is not valid when we are restoring packages for a solution
                throw new InvalidOperationException(LocalizedResourceManager.GetString("RestoreCommandOptionSolutionDirectoryIsInvalid"));
            }

            ReadSettings();
            string packagesFolder = GetPackagesFolder();
            IFileSystem packagesFolderFileSystem = CreateFileSystem(packagesFolder);

            if (_restoringForSolution)
            {
                RestorePackagesForSolution(packagesFolderFileSystem, _solutionFileFullPath);
            }
            else
            {
                // By default the PackageReferenceFile does not throw if the file does not exist at the specified path.
                // So we'll need to verify that the file exists.
                if (!FileSystem.FileExists(_packagesConfigFileFullPath))
                {
                    string message = String.Format(CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("RestoreCommandFileNotFound"), _packagesConfigFileFullPath);
                    throw new InvalidOperationException(message);
                }

                Stopwatch watch = new Stopwatch();
                watch.Start();
                var installedPackageReferences = GetInstalledPackageReferences(_packagesConfigFileFullPath, projectName: null);
                watch.Stop();
                DisplayExecutedTime(watch.Elapsed, "GetInstalledPackageReferences");

                watch.Restart();
                InstallPackages(packagesFolderFileSystem, installedPackageReferences);
                watch.Stop();
                DisplayExecutedTime(watch.Elapsed, "RestoringPackages");
            }
        }
    }
}


text:
<pronoun>
	<label>il</label>
	<gender>masculine</gender>
    <applicability>
		<multiplicity>singular</multiplicity>
	    <person>third</person>
	    <subject/>
	</applicability>
</pronoun>


text:
layout: page
title: Curriculum Vitae
permalink: /curriculum-vitae/
---

{% for section in site.data.cv %}

{{ section.heading }}

    {% for item in section.items %}

        {{ item.time }}

        {{ item.position }}

        {{ item.organization }}

        {{ item.url }}

    {% endfor %}

{% endfor %}


text:
<?xml version="1.0"?>
<project
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
	xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.yirendai.infra</groupId>
		<artifactId>cicada-demo</artifactId>
		<version>2.0.1</version>
	</parent>
	<artifactId>cicada-demo-provider-api</artifactId>
	<name>cicada-demo-provider-api</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
package org.wildfly.swarm.jaxrs.ejb.test;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

@Path("/hello")
@Stateless
public class GreeterResource {
    @EJB
    private SimpleService simpleService;

    @GET
    public String hello(@QueryParam("name") String name, @Context HttpServletRequest request) throws NamingException {
        HttpSession session = request.getSession();
        GreeterService greeter = (GreeterService) session.getAttribute(GreeterService.class.getName());
        if (greeter == null) {
            greeter = InitialContext.doLookup("java:module/" + GreeterService.class.getSimpleName());
            session.setAttribute(GreeterService.class.getName(), greeter);
        }

        return simpleService.yay() + greeter.hello(name);
    }
}