text:
__title__ = 'latinpigsay'
__license__ = 'MIT'
__author__ = 'Steven Cutting'
__author_email__ = 'steven.c.projects@gmail.com'
__created_on__ = '12/3/2014'

from data.pigs import piggies

import generalfunctions as gfunc

import logging
_LOG = logging.getLogger(__name__)

class Piggyprint(object):
    """Prints an ASCII pig with a speech bubble above it.
    The speech bubble contains the string provided when creating an instance of
    this class.
    Using the initiation argument 'character', a different ASCII character can
    be provided.
    """
    def __init__(self, string=' ', character=piggies.pig):
        # ASCII character printed bellow the speech bubble.
        self.character = character # Not private because it's OK to change.
        # Metadata about the ASCII character.
        self.__minlinelen = gfunc.findlongeststing(self.character.splitlines())

        # List made up of lines from the supplied string.
        self.__listofstrings = string.replace('\t', ' '*4).splitlines()
        # Metadata about the above list used to make the Speech Bubble.
        self.__longeststring = gfunc.findlongeststing(self.__listofstrings,
                                                      self.__minlinelen)
        self.__lenoflist = len(self.__listofstrings)
        # Parts of the Speech Bubble
        self.__bubbletop = ' {}'.format('_' * (self.__longeststring + 2))
        self.__bubblebody = self.__bubblebodyiter
        self.__bubblebottom = ' {}'.format('-' * (self.__longeststring + 2))

    def __str__(self):
        pass

    def __bubblebodyiter(self):
        for n, string_n in enumerate(self.__listofstrings):
            stringn = string_n.replace('\t', ' '*4)

            length = len(stringn)
            gap = 0
            if length is 0:
                gap = self.__longeststring
                spacers = " " * gap
                newstring = spacers
            else:
                gap = self.__longeststring - length
                spacers = " " * gap
                newstring = "{}{}".format(stringn, spacers)
            if self.__lenoflist is 1:
                yield gfunc.stringframer(newstring)
            elif not n:
                yield gfunc.stringframer(newstring, spacers, '/', '\\')
            elif n is self.__lenoflist - 1:
                yield gfunc.stringframer(newstring, spacers, '\\', '/')
            else:
                yield gfunc.stringframer(newstring, spacers, '|', '|')

    @property
    def __printbubble(self):
        print self.__bubbletop
        body = self.__bubblebody()
        for line in body:
            print line
        print self.__bubblebottom

    @property
    def printall(self):
        self.__printbubble
        print self.character


text:
All URIs are relative to *https://api.twilio.com*

Method | HTTP request | Description
------------- | ------------- | -------------
[**CreateSipAuthRegistrationsCredentialListMapping**](AccountsSIPDomainsAuthRegistrationsCredentialListMappingsApi.md#CreateSipAuthRegistrationsCredentialListMapping) | **Post** /2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings.json |
[**DeleteSipAuthRegistrationsCredentialListMapping**](AccountsSIPDomainsAuthRegistrationsCredentialListMappingsApi.md#DeleteSipAuthRegistrationsCredentialListMapping) | **Delete** /2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings/{Sid}.json |
[**FetchSipAuthRegistrationsCredentialListMapping**](AccountsSIPDomainsAuthRegistrationsCredentialListMappingsApi.md#FetchSipAuthRegistrationsCredentialListMapping) | **Get** /2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings/{Sid}.json |
[**ListSipAuthRegistrationsCredentialListMapping**](AccountsSIPDomainsAuthRegistrationsCredentialListMappingsApi.md#ListSipAuthRegistrationsCredentialListMapping) | **Get** /2010-04-01/Accounts/{AccountSid}/SIP/Domains/{DomainSid}/Auth/Registrations/CredentialListMappings.json |

## CreateSipAuthRegistrationsCredentialListMapping

> ApiV2010SipAuthRegistrationsCredentialListMapping CreateSipAuthRegistrationsCredentialListMapping(ctx, DomainSidoptional)

Create a new credential list mapping resource

### Path Parameters

Name | Type | Description
------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**DomainSid** | **string** | The SID of the SIP domain that will contain the new resource.

### Other Parameters

Other parameters are passed through a pointer to a CreateSipAuthRegistrationsCredentialListMappingParams struct

Name | Type | Description
------------- | ------------- | -------------
**PathAccountSid** | **string** | The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will create the resource.
**CredentialListSid** | **string** | The SID of the CredentialList resource to map to the SIP domain.

### Return type

[**ApiV2010SipAuthRegistrationsCredentialListMapping**](ApiV2010SipAuthRegistrationsCredentialListMapping.md)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

## DeleteSipAuthRegistrationsCredentialListMapping

> DeleteSipAuthRegistrationsCredentialListMapping(ctx, DomainSidSidoptional)

Delete a credential list mapping from the requested domain

### Path Parameters

Name | Type | Description
------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**DomainSid** | **string** | The SID of the SIP domain that contains the resources to delete.
**Sid** | **string** | The Twilio-provided string that uniquely identifies the CredentialListMapping resource to delete.

### Other Parameters

Other parameters are passed through a pointer to a DeleteSipAuthRegistrationsCredentialListMappingParams struct

Name | Type | Description
------------- | ------------- | -------------
**PathAccountSid** | **string** | The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resources to delete.

### Return type

 (empty response body)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: Not defined
- **Accept**: Not defined

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

## FetchSipAuthRegistrationsCredentialListMapping

> ApiV2010SipAuthRegistrationsCredentialListMapping FetchSipAuthRegistrationsCredentialListMapping(ctx, DomainSidSidoptional)

Fetch a specific instance of a credential list mapping

### Path Parameters

Name | Type | Description
------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**DomainSid** | **string** | The SID of the SIP domain that contains the resource to fetch.
**Sid** | **string** | The Twilio-provided string that uniquely identifies the CredentialListMapping resource to fetch.

### Other Parameters

Other parameters are passed through a pointer to a FetchSipAuthRegistrationsCredentialListMappingParams struct

Name | Type | Description
------------- | ------------- | -------------
**PathAccountSid** | **string** | The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resource to fetch.

### Return type

[**ApiV2010SipAuthRegistrationsCredentialListMapping**](ApiV2010SipAuthRegistrationsCredentialListMapping.md)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: Not defined
- **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

## ListSipAuthRegistrationsCredentialListMapping

> []ApiV2010SipAuthRegistrationsCredentialListMapping ListSipAuthRegistrationsCredentialListMapping(ctx, DomainSidoptional)

Retrieve a list of credential list mappings belonging to the domain used in the request

### Path Parameters

Name | Type | Description
------------- | ------------- | -------------
**ctx** | **context.Context** | context for authentication, logging, cancellation, deadlines, tracing, etc.
**DomainSid** | **string** | The SID of the SIP domain that contains the resources to read.

### Other Parameters

Other parameters are passed through a pointer to a ListSipAuthRegistrationsCredentialListMappingParams struct

Name | Type | Description
------------- | ------------- | -------------
**PathAccountSid** | **string** | The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping resources to read.
**PageSize** | **int** | How many resources to return in each list page. The default is 50, and the maximum is 1000.
**Limit** | **int** | Max number of records to return.

### Return type

[**[]ApiV2010SipAuthRegistrationsCredentialListMapping**](ApiV2010SipAuthRegistrationsCredentialListMapping.md)

### Authorization

[accountSid_authToken](../README.md#accountSid_authToken)

### HTTP request headers

- **Content-Type**: Not defined
- **Accept**: application/json

[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints)
[[Back to Model list]](../README.md#documentation-for-models)
[[Back to README]](../README.md)

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<install version="1.5" type="plugin" group="content" method="upgrade">
  <name>AllVideos (by JoomlaWorks)</name>
  <author>JoomlaWorks</author>
  <authorEmail>contact@joomlaworks.gr</authorEmail>
  <authorUrl>www.joomlaworks.gr</authorUrl>
  <copyright>Copyright (c) 2006-2010 JoomlaWorks Ltd. All rights reserved.</copyright>
  <creationDate>February 18th, 2010</creationDate>
  <license>http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL</license>
  <version>3.3</version>
  <description>Thank you for installing the JoomlaWorks AllVideos Plugin for Joomla! 1.5</description>
  <params addpath="/plugins/content/jw_allvideos/includes/elements">
    <param name="gzipScripts" type="radio" default="0" label="Compress player scripts using PHP" description="Improve your site's performance when using AllVideos by enabling this option. It will compress and combine the javascript code required to make the various players supported by AllVideos work. This option may not be supported however by your hosting company, so in case you stumble onto any issues, you can safely turn it back to 'No'.">
      <option value="0">No</option>
      <option value="1">Yes</option>
    </param>
    <param name="" type="header" default="Video parameters" label="" description="" />
    <param name="vfolder" type="text" default="images/stories/videos" size="40" label="Local Video Folder" description="This is the folder where you store all the video files that you want to stream/play from YOUR website. It is better if this folder is inside the 'images/stories' folder, so that you won't stumble into any permission issues. In this 'Local Video Folder' you can then upload video files of the following type: .flv, .swf, .mov, .mp4, .wmv, .divx" />
    <param name="vwidth" type="text" default="400" size="4" label="Default width (in px) for videos" description="The preselected width of the video in pixels to show inside your content, it should be smaller than the width of the surrounding box -if any- in order not to break your layout!" />
    <param name="vheight" type="text" default="300" size="4" label="Default height (in px) for videos" description="The preselected height of the video in pixels to show inside your content." />
    <param name="transparency" type="radio" default="transparent" label="Player transparency for Flash based media" description="Should Flash based media be transparent or not? If you use any lightbox galleries, it's best to leave this option to 'Yes'.">
      <option value="opaque">No</option>
      <option value="transparent">Yes</option>
    </param>
    <param name="background" type="text" default="#010101" size="6" label="Player background color for Flash based media" description="Set the background color of the player, only if the transparency is set to 'No'. Values should be given in hexadecimal format, e.g. #000000 for black." />
		<param name="backgroundQT" type="list" default="black" label="Player background color for QuickTime based media" description="Set the background color of the player for QuickTime based media like MOV, MP4 and 3GP.">
			<option value="black">black (#000000)</option>
			<option value="green">green (#008000)</option>
			<option value="silver">silver (#c0c0c0)</option>
			<option value="lime">lime (#00ff00)</option>
			<option value="gray">gray (#808080)</option>
			<option value="olive">olive (#808000)</option>
			<option value="white">white (#ffffff)</option>
			<option value="yellow">yellow (#ffff00)</option>
			<option value="maroon">maroon (#800000)</option>
			<option value="navy">navy (#000080)</option>
			<option value="red">red (#ff0000)</option>
			<option value="blue">blue (#0000ff)</option>
			<option value="purple">purple (#800080)</option>
			<option value="teal">teal (#008080)</option>
			<option value="fuchsia">fuchsia (#ff00ff)</option>
			<option value="aqua">aqua (#00ffff)</option>
		</param>
    <param name="controlBarLocation" type="radio" default="bottom" label="FLV video player control bar location" description="Define where you want the controlbar of the player to appear.">
      <option value="bottom">Bottom</option>
      <option value="over">Over</option>
    </param>
    <param name="lightboxLink" type="radio" default="1" label="Enable lightbox popup ('dim lights' option) for all browsers except IE" description="Open videos in a lightbox popup. Set the width and height of the popup below. This option cannot currently work with IE browsers due to their lack of supporting web standards. An update with workarounds is planned for the next release of AllVideos.">
      <option value="0">No</option>
      <option value="1">Yes</option>
    </param>
    <param name="lightboxWidth" type="text" default="800" size="4" label="Popup width (in px)" description="" />
    <param name="lightboxHeight" type="text" default="600" size="4" label="Popup height (in px)" description="" />
    <param name="" type="header" default="Audio parameters" label="" description="" />
    <param name="afolder" type="text" default="images/stories/audio" size="40" label="Local Audio Folder" description="This is the folder where you store all the audio (sound) files that you want to stream/play from YOUR website. It is better if this folder is inside the 'images/stories' folder, so that you won't stumble into any permission issues. In this 'Local Audio Folder' you can then upload .mp3 and .wma audio file types!" />
    <param name="awidth" type="text" default="300" size="4" label="Default width (in px) for audio player" description="The preselected width of the audio player in pixels to show inside your content, it should be smaller than the width of the surrounding box -if any- in order not to break your layout!" />
    <param name="aheight" type="text" default="20" size="4" label="Default height (in px) for audio player" description="The preselected height of the audio player in pixels to show inside your content." />
    <param name="" type="header" default="General parameters" label="" description="" />
    <param name="autoplay" type="radio" default="0" label="Autoplay" description="Control audio/video autoplay when the page loads.">
      <option value="0">No</option>
      <option value="1">Yes</option>
    </param>
    <param name="downloadLink" type="radio" default="1" label="Display download link" description="Allow users to download media.">
      <option value="0">No</option>
      <option value="1">Yes</option>
    </param>
    <param name="embedForm" type="radio" default="1" label="Display embed box" description="Allow users to embed media to other websites. This option works for all media except local or remote Windows Media formats.">
      <option value="0">No</option>
      <option value="1">Yes</option>
    </param>
  </params>
  <params group="advanced">
  	<param name="debugMode" type="radio" default="0" label="Debug mode" description="Enable this option to display possible errors or other warnings. Useful for debugging.">
      <option value="0">Disabled</option>
      <option value="1">Enabled</option>
    </param>
  </params>
  <files>
    <filename plugin="jw_allvideos">jw_allvideos.php</filename>
    <folder>jw_allvideos</folder>
  </files>
  <languages>
    <language tag="en-GB">en-GB.plg_content_jw_allvideos.ini</language>
  </languages>
</install>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Lobivia argentea Backeb.

### Remarks
null


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Monograph of Cercospora 62 (1954)

#### Original name
Cercospora clavigera Ellis & Everh. ex Chupp

### Remarks
null


text:
package sorcer.core.monitor;

import java.io.Serializable;
import java.rmi.RemoteException;

import sorcer.core.context.StrategyContext;
import sorcer.service.Context;
import sorcer.service.MonitorException;
import sorcer.service.Monitorable;

import net.jini.core.lease.Lease;
import net.jini.core.transaction.server.TransactionConstants;

/**
 * An interface for controlling the session in the server. The session is
 * activated in server by lazy mechanism. ie, The broker should call on this
 * session init(monitorable, duration, timeout). From this moment, the Manager
 * will require that the monitorable renew the leases for the specified
 * duration. If the task is not complete for the specified duration, the monitor
 * will send stop signal to the monitorable and notify the Broker via
 * RemoteEventListener.notify().
 *
 * For Space based programming, since we don't know who will execute the job,
 * broker calls init(space, timeout, duration). This means that the monitor is
 * going to mark the timeout and duration of this session. Note that from this
 * moment, the session is not activated. It waits till the timeout period for
 * some monitorable provider to pick up and call init(monitorable). From this
 * moment on, the session is activated and leases have to be renewed.
 *
 * Once providers revieves the session (which is normally sent inside the
 * exertion) They may call update() stop() getLease() or getState(). The
 * getState is actually delegated to the SessionManager remotely.
 *
 **/

public interface MonitoringSession extends Serializable {

	/**
	 * Makes this an active session. The monitorable decides the lease duration
	 * and the timeout after which the monitor will call on the monitorable that
	 * its monitored exertion failed and report back to the exertion dispatcher
	 * listener that the exertion of this session has failed.
	 *
	 * @param mntrbl
	 *            The monitorable to which this task is dispatched.
	 * @param duration
	 *            Requested lease duration for the session.
	 * @param timeout
	 *            Timeout for execution of this task.
	 *
	 * @throws MonitorException
	 *             1) If this session is already active 2) If there is no such
	 *             session
	 *
	 * @throws RemoteException
	 *             if there is a communication error
	 *
	 * @see TransactionConstants
	 */

	public void init(Monitorable mntrbl, long duration, long timeout)
			throws RemoteException, MonitorException;

	/**
	 *
	 * If the Broker wants to drop the exertion to space, then the Broker has no
	 * idea who will pick up this exertion. In that case, it doesn't make sense
	 * for the broker to force leasing. However, it may activate the the session
	 * with the timeout marked and the lease duration specified so that if no
	 * provider picks out and the task gets timed out, then the Monitor can
	 * clean up the entry from space and notify the broker.
	 *
	 * If the provider picks up before it timesout, then the provider must
	 * initialize this session by calling init(Monitorable) so that the monitor
	 * will now make sure that the leases are renewed properly for this session.
	 *
	 * @param duration
	 *            Requested lease duration for the session.
	 * @param timeout
	 *            Timeout for execution of this task wich includes idle time in
	 *            space.
	 *
	 * @throws MonitorException
	 *             1) If this session is already active 2) If there is no such
	 *             session
	 *
	 * @throws RemoteException
	 *             if there is a communication error
	 *
	 * */

	public void init(long duration, long timeout) throws RemoteException,
			MonitorException;

	/**
	 *
	 * If the Broker wants to drop the exertion to space, then the Broker has no
	 * idea who will pick up this exertion. In that case, the broker would have
	 * already set the lease duration and timeout.
	 *
	 * The provider who picks up the entry must initialize this session by
	 * calling init(Monitorable) so that the monitor will now know that the task
	 * with the monitorable and also will make sure that the leases are renewed
	 * properly for this session.
	 *
	 * @param mntrbl
	 *            The monitorable who picked this up.
	 *
	 * @throws MonitorException
	 *             1) If there is no such session 2) The execution has been
	 *             inited by some one else.
	 *
	 * @throws RemoteException
	 *             if there is a communication error
	 *
	 * */

	public void init(Monitorable mntrbl) throws RemoteException,
			MonitorException;

	/**
	 * Providers use this method to update the monitoring session
	 *
	 * @param ctx
	 *            The service context changed.
	 *
	 *  * @param aspect
	 *            The aspect of context change.
	 *
	 * @throws MonitorException
	 *             1) If there is no such session 2) The context does not
	 *             belong to this session
	 *
	 * @throws RemoteException
	 *             if there is a communication error
	 **/

	public void changed(Context ctx, StrategyContext controlContext, int aspect) throws RemoteException,
			MonitorException;

	/**
	 * The lease for this session
	 **/
	public Lease getLease();

	public int getState() throws RemoteException, MonitorException;

}


text:
#pragma once

#include <inviwo/core/common/inviwocoredefine.h>
#include <inviwo/core/datastructures/data.h>
#include <inviwo/core/datastructures/spatialdata.h>
#include <inviwo/core/datastructures/image/imagetypes.h>
#include <inviwo/core/datastructures/image/layerrepresentation.h>

#include <inviwo/core/io/datareader.h>
#include <inviwo/core/io/datawriter.h>

namespace inviwo {

class DataFormatBase;

/**
 * \ingroup datastructures
 */
class IVW_CORE_API Layer : public Data<Layer, LayerRepresentation>, public StructuredGridEntity<2> {
public:
    explicit Layer(size2_t defaultDimensions = size2_t(8, 8),
                   const DataFormatBase* defaultFormat = DataVec4UInt8::get(),
                   LayerType type = LayerType::Color,
                   const SwizzleMask& defaultSwizzleMask = swizzlemasks::rgba,
                   InterpolationType interpolation = InterpolationType::Linear,
                   const Wrapping2D& wrapping = wrapping2d::clampAll);
    explicit Layer(std::shared_ptr<LayerRepresentation>);
    Layer(const Layer&) = default;
    Layer& operator=(const Layer& that) = default;
    virtual Layer* clone() const override;
    virtual ~Layer() = default;

    LayerType getLayerType() const;

    /**
     * Resize to dimension. This is destructive, the data will not be
     * preserved. Use copyRepresentationsTo to update the data.
     * @note Resizes the last valid representation and erases all other representations.
     * Last valid representation will remain valid after changing the dimension.
     */
    virtual void setDimensions(const size2_t& dim);
    virtual size2_t getDimensions() const override;

    /**
     * Set the format of the data.
     * @see DataFormatBase
     * @param format The format of the data.
     */
    // clang-format off
    [[ deprecated("use LayerRepresentation::setDataFormat() instead (deprecated since 2019-06-26)")]]
    void setDataFormat(const DataFormatBase* format);
    const DataFormatBase* getDataFormat() const;
    // clang-format on

    /**
     * \brief update the swizzle mask of the channels for sampling color layers
     * The swizzle mask is only affecting Color layers.
     *
     * @param mask new swizzle mask
     */
    void setSwizzleMask(const SwizzleMask& mask);
    SwizzleMask getSwizzleMask() const;

    void setInterpolation(InterpolationType interpolation);
    InterpolationType getInterpolation() const;

    void setWrapping(const Wrapping2D& wrapping);
    Wrapping2D getWrapping() const;

    /**
     * \brief encode the layer contents to a buffer considering the requested image format
     *
     * @param fileExtension   file extension of the requested image format
     * @return encoded layer contents as std::vector
     */
    std::unique_ptr<std::vector<unsigned char>> getAsCodedBuffer(
        const std::string& fileExtension) const;

private:
    friend class LayerRepresentation;

    LayerType defaultLayerType_;
    size2_t defaultDimensions_;
    const DataFormatBase* defaultDataFormat_;
    SwizzleMask defaultSwizzleMask_;
    InterpolationType defaultInterpolation_;
    Wrapping2D defaultWrapping_;
};

// https://docs.microsoft.com/en-us/cpp/cpp/general-rules-and-limitations?view=vs-2017
extern template class IVW_CORE_TMPL_EXP DataReaderType<Layer>;
extern template class IVW_CORE_TMPL_EXP DataWriterType<Layer>;

}  // namespace inviwo


text:
// angular modules
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from "@angular/router";

// custom services
import { AuthenticationService } from "../services/authentication.service";
import { ErrorHandlingService } from "../services/errorhandling.service";
import { LinkService } from "../services/link.service";
import { VideoFilterService } from "../services/videofilter.service";
import { FloorInputCheckerService } from "../services/floor-input-checker.service";
import { CanDeactivateGuard } from "../services/can-deactivate-guard.service";

// main components
import { AppComponent } from './app.component';
import { FrontpageComponent } from "./components/frontpage/frontpage.component";
import { ItemsComponent } from "./components/items/items.component";
import { VideoOverviewComponent } from "./components/videos/video-overview.component";
import { VideoComponent } from "./components/video/video.component";
import { ItemComponent } from "./components/item/item.component";
import { ItemsourceComponent } from "./components/itemsource/itemsource.component";
import { ItemsourcesComponent } from "./components/itemsources/itemsources.component";
import { BossesComponent } from "./components/bosses/bosses.component";
import { BossComponent } from "./components/boss/boss.component";
import { TransformationsComponent } from "./components/transformations/transformations.component";
import { TransformationComponent } from "./components/transformation/transformation.component";
import { QuotesComponent } from "./components/quotes/quotes.component";
import { CharactersComponent } from "./components/characters/characters.component";
import { CharacterComponent } from "./components/character/character.component";
import { CharacterVideosComponent } from "./components/charactervideos/charactervideos.component";
import { FloorsComponent } from "./components/floors/floors.component";
import { FloorComponent } from "./components/floor/floor.component";
import { ItemCombosComponent } from "./components/itemcombo/itemcombos.component";
import { AddEpisodeComponent } from "./components/addepisode/add-episode.component";
import { ManageQuotesComponent } from "./components/managequotes/manage-quotes.component";
import { EditQuoteComponent } from "./components/editquote/edit-quote.component";
import { AddVideoComponent } from "./components/addvideo/add-video.component";
import { FanVideosComponent } from "./components/fanvideos/fanvideos.component";
import { RandomEpisodeComponent } from "./components/randomepisode/random-episode.component";

// sub components
import { FooterLinkComponent } from "./components/frontpage/footer-link/footer-link.component";
import { MaintopicComponent } from "./components/frontpage/maintopic/maintopic.component";
import { ItemImageComponent } from "./components/global/itemimage/itemimage.component";
import { ItemsFilterComponent } from "./components/items/filter/items-filter.component";
import { ItemImageNolinkComponent } from "./components/global/itemimage/itemimage-nolink.component";
import { OverviewItemComponent } from "./components/global/itemimage/overview-item.component";
import { OverviewItemCondensedComponent } from "./components/global/itemimage/overview-item-condensed.component";
import { VideolistComponent } from "./components/global/videolist/videolist.component";
import { VideoRatingsComponent } from "./components/video/ratings/video-ratings.component";
import { VideoItemsComponent } from "./components/video/items/video-items.component";
import { ItemSourceImageNolinkComponent } from "./components/global/itemsourceimage/itemsourceimage-nolink.component";
import { ItemSourceImageComponent } from "./components/global/itemsourceimage/itemsourceimage.component";
import { VideoInfoComponent } from "./components/video/videoinfo/videoinfo.component";
import { VideoItemSourcesComponent } from "./components/video/itemsources/video-itemsources.component";
import { VideoTimelineComponent } from "./components/video/timeline/video-timeline.component";
import { BossimageComponent } from "./components/global/bossimage/bossimage.component";
import { BossimageNolinkComponent } from "./components/global/bossimage/bossimage-nolink.component";
import { DeathImageNolinkComponent } from "./components/global/deathimage/deathimage-nolink.component";
import { VideoTransformationsComponent } from "./components/video/transformations/video-transformations.component";
import { TransformationImageComponent } from "./components/global/transformationimage/transformation-image.component";
import { TransformationDetailsPopupComponent } from "./components/tooltips/transformationdetails/transformationdetails-popup.component";
import { CharacterImageComponent } from "./components/global/characterimage/character-image.component";
import { VideoCharactersComponent } from "./components/video/characters/video-characters.component";
import { ThroughoutTheLetsPlayComponent } from "./components/global/throughouttheletsplay/throughout-the-letsplay.component";
import { ItemsourceDistributionComponent } from "./components/global/distribution/itemsource-distribution.component";
import { CharacterDistributionComponent } from "./components/global/distribution/character-distribution.component";
import { CurseDistributionComponent } from "./components/global/distribution/curse-distribution.component";
import { GenericFilterComponent } from "./components/global/genericfilter/generic-filter.component";
import { OverviewItemsourceComponent } from "./components/global/itemsourceimage/overview-itemsource.component";
import { TopItempickupsComponent } from "./components/global/topitempickups/topitempickups.component";
import { FloorDistributionComponent } from "./components/global/distribution/floor-distribution.component";
import { OverviewBossComponent } from "./components/global/bossimage/overview-boss.component";
import { TransformationImageNolinkComponent } from "./components/global/transformationimage/transformation-image-nolink.component";
import { OverviewTransformationComponent } from "./components/global/transformationimage/overview-transformation.component";
import { TransformationRankingComponent } from "./components/transformations/transformation-ranking.component";
import { TransformationItemsComponent } from "./components/transformation/items/transformation-items.component";
import { NumberOfTransformationItemsFoundComponent } from "./components/transformation/items/numberofitemsfound.component";
import { QuoteComponent } from "./components/global/quote/quote.component";
import { CharacterImageNolinkComponent } from "./components/global/characterimage/character-image-nolink.component";
import { CharacterOverviewImage } from "./components/global/characterimage/overview-character.component";
import { MainMenuComponent } from "./components/global/mainmenu/mainmenu.component";
import { CharacterWinratioComponent } from "./components/characters/winratios/winratio.component";
import { FloorButtonsComponent } from "./components/addepisode/floorbuttons/floorbuttons.component";
import { CollectedItemsComponent } from "./components/addepisode/collected-items/collected-items.component";
import { BossfightListComponent } from "./components/addepisode/bossfights/bossfight-list.component";
import { CollectedDataComponent } from "./components/addepisode/collected-data/collected-data.component";
import { ItemDescriptionComponent } from "./components/item/description/item-description.component";
import { AddSeedComponent } from "./components/addepisode/seed/add-seed.component";

// tooltips
import { ItemPickupTooltipComponent } from "./components/tooltips/item/itempickup-tooltip.component";
import { TimelinePopupComponent } from "./components/tooltips/timeline/timeline-popup.component";
import { ItemsourceDetailTooltipComponent } from "./components/tooltips/item/itemsource-detail.component";
import { ItemCharacterDetailTooltipComponent } from "./components/tooltips/character/item-character-detail-tooltip.component";
import { TopItemsTooltipComponent } from "./components/tooltips/item/topitems-tooltip.component";

// apis
import { FrontpageRequests } from "../services/apiRequests/frontpage";
import { ItemApiRequests } from "../services/apiRequests/items";
import { VideoApiRequests } from "../services/apiRequests/videos";
import { VisitedFloorsApiRequests } from "../services/apiRequests/visitedfloors";
import { WatchedVideosApiRequests } from "../services/apiRequests/watchedvideos";
import { BossApiRequests } from "../services/apiRequests/bosses";
import { TransformationApiRequests } from "../services/apiRequests/transformations";
import { CharacterApiRequests } from "../services/apiRequests/characters";
import { ItemsourceApiRequests } from "../services/apiRequests/itemsources";
import { QuoteApiRequests } from "../services/apiRequests/quotes";
import { FloorApiRequests } from "../services/apiRequests/floors";
import { CurseApiRequests } from "../services/apiRequests/curses";
import { DeathApiRequests } from "../services/apiRequests/deaths";
import { CreateEpisode } from "../services/apiRequests/createepisode";
import { CheckLoginApiRequest } from "../services/apiRequests/checklogin";
import { FanVideoApiRequests } from "../services/apiRequests/fanvideos";
import { RandomEpisodeApiRequests } from "../services/apiRequests/randomepisode";

// pipes
import { ReversePipe } from "../pipes/reverse";
import { ExtractTransformationItemsPipe } from "../pipes/extracttransformationitems";
import { RemoveTransformationDuplicates } from "../pipes/removeduplicates";
import { SecondsToMinutesPipe } from "../pipes/secondstominutes";
import { EliminateNonRelevantBosses, EliminateDoubleBosses, EliminateSingleBosses } from "../pipes/filterbosses";
import { FormatSeedPipe } from "../pipes/format-seed";

// dropdown menus
import { ItemsourceDropdownComponent } from "./components/global/dropdown/itemsource/itemsource-dd.component";
import { ItemDropdownComponent } from "./components/global/dropdown/item/item-dd.component";
import { BossDropdownComponent } from "./components/global/dropdown/boss/boss-dd.component";
import { FloorDropdownComponent } from "./components/global/dropdown/floor/floor-dd.component";
import { CurseDropdownComponent } from "./components/global/dropdown/curse/curse-dd.component";
import { CharacterDropdownComponent } from "./components/global/dropdown/character/character-dd.component";
import { DeathDropdownComponent } from "./components/global/dropdown/death/death-dd.component";

const routes: Routes = [
    { path: "", component: FrontpageComponent },
    { path: "Items", component: ItemsComponent },
    { path: "Videos", component: VideoOverviewComponent },
    { path: "Video/:id", component: VideoComponent },
    { path: "Item/:id", component: ItemComponent },
    { path: "ItemSource/:id", component: ItemsourceComponent },
    { path: "ItemSources", component: ItemsourcesComponent },
    { path: "Bosses", component: BossesComponent },
    { path: "Boss/:id", component: BossComponent },
    { path: "Transformations", component: TransformationsComponent },
    { path: "Transformation/:id", component: TransformationComponent },
    { path: "Quotes", component: QuotesComponent },
    { path: "Characters", component: CharactersComponent },
    { path: "Character/:id", component: CharacterComponent },
    { path: "Character/:char/Videos/:type/:era", component: CharacterVideosComponent },
    { path: "Floors", component: FloorsComponent },
    { path: "Floor/:id", component: FloorComponent },
    { path: "ItemCombos", component: ItemCombosComponent },
    { path: "AddEpisode/:id", component: AddEpisodeComponent, canDeactivate: [CanDeactivateGuard] },
    { path: "Quotes/Manage", component: ManageQuotesComponent },
    { path: "Quote/Edit/:id", component: EditQuoteComponent },
    { path: "AddVideo", component: AddVideoComponent },
    { path: "Fanvideos", component: FanVideosComponent },
    { path: "RandomEpisode", component: RandomEpisodeComponent }
];

@NgModule({
    declarations: [
        AppComponent,
        FrontpageComponent,
        FooterLinkComponent,
        MaintopicComponent,
        ItemImageComponent,
        ItemsComponent,
        ItemsFilterComponent,
        ItemImageNolinkComponent,
        OverviewItemComponent,
        VideolistComponent,
        VideoOverviewComponent,
        VideoComponent,
        VideoRatingsComponent,
        VideoItemsComponent,
        ItemSourceImageNolinkComponent,
        ItemSourceImageComponent,
        ItemPickupTooltipComponent,
        VideoInfoComponent,
        VideoItemSourcesComponent,
        VideoTimelineComponent,
        BossimageComponent,
        TimelinePopupComponent,
        BossimageNolinkComponent,
        DeathImageNolinkComponent,
        ReversePipe,
        VideoTransformationsComponent,
        ExtractTransformationItemsPipe,
        TransformationImageComponent,
        TransformationDetailsPopupComponent,
        RemoveTransformationDuplicates,
        SecondsToMinutesPipe,
        CharacterImageComponent,
        VideoCharactersComponent,
        ItemComponent,
        ThroughoutTheLetsPlayComponent,
        ItemsourceDistributionComponent,
        CharacterDistributionComponent,
        ItemsourceDetailTooltipComponent,
        ItemCharacterDetailTooltipComponent,
        CurseDistributionComponent,
        GenericFilterComponent,
        ItemsourceComponent,
        ItemsourcesComponent,
        OverviewItemsourceComponent,
        TopItempickupsComponent,
        TopItemsTooltipComponent,
        FloorDistributionComponent,
        OverviewBossComponent,
        BossesComponent,
        EliminateNonRelevantBosses,
        EliminateDoubleBosses,
        EliminateSingleBosses,
        BossComponent,
        TransformationsComponent,
        TransformationImageNolinkComponent,
        OverviewTransformationComponent,
        TransformationRankingComponent,
        TransformationComponent,
        TransformationItemsComponent,
        NumberOfTransformationItemsFoundComponent,
        QuotesComponent,
        QuoteComponent,
        CharactersComponent,
        CharacterImageNolinkComponent,
        CharacterOverviewImage,
        CharacterComponent,
        MainMenuComponent,
        CharacterWinratioComponent,
        CharacterVideosComponent,
        FloorsComponent,
        FloorComponent,
        ItemsourceDropdownComponent,
        ItemDropdownComponent,
        BossDropdownComponent,
        FloorDropdownComponent,
        CurseDropdownComponent,
        ItemCombosComponent,
        AddEpisodeComponent,
        FloorButtonsComponent,
        CharacterDropdownComponent,
        CollectedItemsComponent,
        BossfightListComponent,
        DeathDropdownComponent,
        CollectedDataComponent,
        ManageQuotesComponent,
        EditQuoteComponent,
        AddVideoComponent,
        FormatSeedPipe,
        ItemDescriptionComponent,
        AddSeedComponent,
        FanVideosComponent,
        RandomEpisodeComponent,
        OverviewItemCondensedComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        RouterModule.forRoot(routes),
        ReactiveFormsModule
    ],
    providers: [
        AuthenticationService,
        ErrorHandlingService,
        LinkService,
        FrontpageRequests,
        ItemApiRequests,
        VideoFilterService,
        VideoApiRequests,
        VisitedFloorsApiRequests,
        WatchedVideosApiRequests,
        BossApiRequests,
        CharacterApiRequests,
        TransformationApiRequests,
        ItemsourceApiRequests,
        QuoteApiRequests,
        FloorApiRequests,
        CurseApiRequests,
        FloorInputCheckerService,
        DeathApiRequests,
        CreateEpisode,
        CanDeactivateGuard,
        CheckLoginApiRequest,
        FanVideoApiRequests,
        RandomEpisodeApiRequests
    ],

    bootstrap: [AppComponent]
})
export class AppModule { }


text:
"""
Management class for basic VM operations.
"""
import functools
import os

from oslo.config import cfg

from nova.api.metadata import base as instance_metadata
from nova import exception
from nova.openstack.common import excutils
from nova.openstack.common.gettextutils import _
from nova.openstack.common import importutils
from nova.openstack.common import log as logging
from nova.openstack.common import processutils
from nova import unit
from nova import utils
from nova.virt import configdrive
from nova.virt.hyperv import constants
from nova.virt.hyperv import imagecache
from nova.virt.hyperv import utilsfactory
from nova.virt.hyperv import vhdutilsv2
from nova.virt.hyperv import vmutils
from nova.virt.hyperv import volumeops

LOG = logging.getLogger(__name__)

hyperv_opts = [
    cfg.BoolOpt('limit_cpu_features',
                default=False,
                help='Required for live migration among '
                     'hosts with different CPU features'),
    cfg.BoolOpt('config_drive_inject_password',
                default=False,
                help='Sets the admin password in the config drive image'),
    cfg.StrOpt('qemu_img_cmd',
               default="qemu-img.exe",
               help='qemu-img is used to convert between '
                    'different image types'),
    cfg.BoolOpt('config_drive_cdrom',
                default=False,
                help='Attaches the Config Drive image as a cdrom drive '
                     'instead of a disk drive'),
    cfg.BoolOpt('enable_instance_metrics_collection',
                default=False,
                help='Enables metrics collections for an instance by using '
                     'Hyper-V\'s metric APIs. Collected data can by retrieved '
                     'by other apps and services, e.g.: Ceilometer. '
                     'Requires Hyper-V / Windows Server 2012 and above'),
    cfg.FloatOpt('dynamic_memory_ratio',
                 default=1.0,
                 help='Enables dynamic memory allocation (ballooning) when '
                      'set to a value greater than 1. The value expresses '
                      'the ratio between the total RAM assigned to an '
                      'instance and its startup RAM amount. For example a '
                      'ratio of 2.0 for an instance with 1024MB of RAM '
                      'implies 512MB of RAM allocated at startup')
]

CONF = cfg.CONF
CONF.register_opts(hyperv_opts, 'hyperv')
CONF.import_opt('use_cow_images', 'nova.virt.driver')
CONF.import_opt('network_api_class', 'nova.network')

def check_admin_permissions(function):
    @functools.wraps(function)
    def wrapper(self, *args, **kwds):

        # Make sure the windows account has the required admin permissions.
        self._vmutils.check_admin_permissions()
        return function(self, *args, **kwds)
    return wrapper

class VMOps(object):
    _vif_driver_class_map = {
        'nova.network.neutronv2.api.API':
        'nova.virt.hyperv.vif.HyperVNeutronVIFDriver',
        'nova.network.api.API':
        'nova.virt.hyperv.vif.HyperVNovaNetworkVIFDriver',
    }

    def __init__(self):
        self._vmutils = utilsfactory.get_vmutils()
        self._vhdutils = utilsfactory.get_vhdutils()
        self._pathutils = utilsfactory.get_pathutils()
        self._volumeops = volumeops.VolumeOps()
        self._imagecache = imagecache.ImageCache()
        self._vif_driver = None
        self._load_vif_driver_class()

    def _load_vif_driver_class(self):
        try:
            class_name = self._vif_driver_class_map[CONF.network_api_class]
            self._vif_driver = importutils.import_object(class_name)
        except KeyError:
            raise TypeError(_("VIF driver not found for "
                              "network_api_class: %s") %
                            CONF.network_api_class)

    def list_instances(self):
        return self._vmutils.list_instances()

    def get_info(self, instance):
        """Get information about the VM."""
        LOG.debug(_("get_info called for instance"), instance=instance)

        instance_name = instance['name']
        if not self._vmutils.vm_exists(instance_name):
            raise exception.InstanceNotFound(instance_id=instance['uuid'])

        info = self._vmutils.get_vm_summary_info(instance_name)

        state = constants.HYPERV_POWER_STATE[info['EnabledState']]
        return {'state': state,
                'max_mem': info['MemoryUsage'],
                'mem': info['MemoryUsage'],
                'num_cpu': info['NumberOfProcessors'],
                'cpu_time': info['UpTime']}

    def _create_root_vhd(self, context, instance):
        base_vhd_path = self._imagecache.get_cached_image(context, instance)
        format_ext = base_vhd_path.split('.')[-1]
        root_vhd_path = self._pathutils.get_root_vhd_path(instance['name'],
                                                          format_ext)

        try:
            if CONF.use_cow_images:
                LOG.debug(_("Creating differencing VHD. Parent: "
                            "%(base_vhd_path)s, Target: %(root_vhd_path)s"),
                          {'base_vhd_path': base_vhd_path,
                           'root_vhd_path': root_vhd_path})
                self._vhdutils.create_differencing_vhd(root_vhd_path,
                                                       base_vhd_path)
            else:
                LOG.debug(_("Copying VHD image %(base_vhd_path)s to target: "
                            "%(root_vhd_path)s"),
                          {'base_vhd_path': base_vhd_path,
                           'root_vhd_path': root_vhd_path})
                self._pathutils.copyfile(base_vhd_path, root_vhd_path)

                base_vhd_info = self._vhdutils.get_vhd_info(base_vhd_path)
                base_vhd_size = base_vhd_info['MaxInternalSize']
                root_vhd_size = instance['root_gb'] * unit.Gi

                # NOTE(lpetrut): Checking the namespace is needed as the
                # following method is not yet implemented in vhdutilsv2.
                if not isinstance(self._vhdutils, vhdutilsv2.VHDUtilsV2):
                    root_vhd_internal_size = (
                        self._vhdutils.get_internal_vhd_size_by_file_size(
                            root_vhd_path, root_vhd_size))
                else:
                    root_vhd_internal_size = root_vhd_size

                if root_vhd_internal_size < base_vhd_size:
                    error_msg = _("Cannot resize a VHD to a smaller size, the"
                                  " original size is %(base_vhd_size)s, the"
                                  " newer size is %(root_vhd_size)s"
                                  ) % {'base_vhd_size': base_vhd_size,
                                       'root_vhd_size': root_vhd_size}
                    raise vmutils.HyperVException(error_msg)
                elif root_vhd_internal_size > base_vhd_size:
                    LOG.debug(_("Resizing VHD %(root_vhd_path)s to new "
                                "size %(root_vhd_size)s"),
                              {'base_vhd_path': base_vhd_path,
                               'root_vhd_path': root_vhd_path})
                    self._vhdutils.resize_vhd(root_vhd_path, root_vhd_size)
        except Exception:
            with excutils.save_and_reraise_exception():
                if self._pathutils.exists(root_vhd_path):
                    self._pathutils.remove(root_vhd_path)

        return root_vhd_path

    def create_ephemeral_vhd(self, instance):
        eph_vhd_size = instance.get('ephemeral_gb', 0) * unit.Gi
        if eph_vhd_size:
            vhd_format = self._vhdutils.get_best_supported_vhd_format()

            eph_vhd_path = self._pathutils.get_ephemeral_vhd_path(
                instance['name'], vhd_format)
            self._vhdutils.create_dynamic_vhd(eph_vhd_path, eph_vhd_size,
                                              vhd_format)
            return eph_vhd_path

    @check_admin_permissions
    def spawn(self, context, instance, image_meta, injected_files,
              admin_password, network_info, block_device_info=None):
        """Create a new VM and start it."""
        LOG.info(_("Spawning new instance"), instance=instance)

        instance_name = instance['name']
        if self._vmutils.vm_exists(instance_name):
            raise exception.InstanceExists(name=instance_name)

        # Make sure we're starting with a clean slate.
        self._delete_disk_files(instance_name)

        if self._volumeops.ebs_root_in_block_devices(block_device_info):
            root_vhd_path = None
        else:
            root_vhd_path = self._create_root_vhd(context, instance)

        eph_vhd_path = self.create_ephemeral_vhd(instance)

        try:
            self.create_instance(instance, network_info, block_device_info,
                                 root_vhd_path, eph_vhd_path)

            if configdrive.required_by(instance):
                self._create_config_drive(instance, injected_files,
                                          admin_password)

            self.power_on(instance)
        except Exception as ex:
            LOG.exception(ex)
            self.destroy(instance)
            raise vmutils.HyperVException(_('Spawn instance failed'))

    def create_instance(self, instance, network_info, block_device_info,
                        root_vhd_path, eph_vhd_path):
        instance_name = instance['name']

        self._vmutils.create_vm(instance_name,
                                instance['memory_mb'],
                                instance['vcpus'],
                                CONF.hyperv.limit_cpu_features,
                                CONF.hyperv.dynamic_memory_ratio)

        ctrl_disk_addr = 0
        if root_vhd_path:
            self._vmutils.attach_ide_drive(instance_name,
                                           root_vhd_path,
                                           0,
                                           ctrl_disk_addr,
                                           constants.IDE_DISK)
            ctrl_disk_addr += 1

        if eph_vhd_path:
            self._vmutils.attach_ide_drive(instance_name,
                                           eph_vhd_path,
                                           0,
                                           ctrl_disk_addr,
                                           constants.IDE_DISK)

        self._vmutils.create_scsi_controller(instance_name)

        self._volumeops.attach_volumes(block_device_info,
                                       instance_name,
                                       root_vhd_path is None)

        for vif in network_info:
            LOG.debug(_('Creating nic for instance: %s'), instance_name)
            self._vmutils.create_nic(instance_name,
                                     vif['id'],
                                     vif['address'])
            self._vif_driver.plug(instance, vif)

        if CONF.hyperv.enable_instance_metrics_collection:
            self._vmutils.enable_vm_metrics_collection(instance_name)

    def _create_config_drive(self, instance, injected_files, admin_password):
        if CONF.config_drive_format != 'iso9660':
            vmutils.HyperVException(_('Invalid config_drive_format "%s"') %
                                    CONF.config_drive_format)

        LOG.info(_('Using config drive for instance: %s'), instance=instance)

        extra_md = {}
        if admin_password and CONF.hyperv.config_drive_inject_password:
            extra_md['admin_pass'] = admin_password

        inst_md = instance_metadata.InstanceMetadata(instance,
                                                     content=injected_files,
                                                     extra_md=extra_md)

        instance_path = self._pathutils.get_instance_dir(
            instance['name'])
        configdrive_path_iso = os.path.join(instance_path, 'configdrive.iso')
        LOG.info(_('Creating config drive at %(path)s'),
                 {'path': configdrive_path_iso}, instance=instance)

        with configdrive.ConfigDriveBuilder(instance_md=inst_md) as cdb:
            try:
                cdb.make_drive(configdrive_path_iso)
            except processutils.ProcessExecutionError as e:
                with excutils.save_and_reraise_exception():
                    LOG.error(_('Creating config drive failed with error: %s'),
                              e, instance=instance)

        if not CONF.hyperv.config_drive_cdrom:
            drive_type = constants.IDE_DISK
            configdrive_path = os.path.join(instance_path,
                                            'configdrive.vhd')
            utils.execute(CONF.hyperv.qemu_img_cmd,
                          'convert',
                          '-f',
                          'raw',
                          '-O',
                          'vpc',
                          configdrive_path_iso,
                          configdrive_path,
                          attempts=1)
            self._pathutils.remove(configdrive_path_iso)
        else:
            drive_type = constants.IDE_DVD
            configdrive_path = configdrive_path_iso

        self._vmutils.attach_ide_drive(instance['name'], configdrive_path,
                                       1, 0, drive_type)

    def _disconnect_volumes(self, volume_drives):
        for volume_drive in volume_drives:
            self._volumeops.disconnect_volume(volume_drive)

    def _delete_disk_files(self, instance_name):
        self._pathutils.get_instance_dir(instance_name,
                                         create_dir=False,
                                         remove_dir=True)

    def destroy(self, instance, network_info=None, block_device_info=None,
                destroy_disks=True):
        instance_name = instance['name']
        LOG.info(_("Got request to destroy instance: %s"), instance_name)
        try:
            if self._vmutils.vm_exists(instance_name):

                #Stop the VM first.
                self.power_off(instance)

                storage = self._vmutils.get_vm_storage_paths(instance_name)
                (disk_files, volume_drives) = storage

                self._vmutils.destroy_vm(instance_name)
                self._disconnect_volumes(volume_drives)
            else:
                LOG.debug(_("Instance not found: %s"), instance_name)

            if destroy_disks:
                self._delete_disk_files(instance_name)
        except Exception as ex:
            LOG.exception(ex)
            raise vmutils.HyperVException(_('Failed to destroy instance: %s') %
                                          instance_name)

    def reboot(self, instance, network_info, reboot_type):
        """Reboot the specified instance."""
        LOG.debug(_("reboot instance"), instance=instance)
        self._set_vm_state(instance['name'],
                           constants.HYPERV_VM_STATE_REBOOT)

    def pause(self, instance):
        """Pause VM instance."""
        LOG.debug(_("Pause instance"), instance=instance)
        self._set_vm_state(instance["name"],
                           constants.HYPERV_VM_STATE_PAUSED)

    def unpause(self, instance):
        """Unpause paused VM instance."""
        LOG.debug(_("Unpause instance"), instance=instance)
        self._set_vm_state(instance["name"],
                           constants.HYPERV_VM_STATE_ENABLED)

    def suspend(self, instance):
        """Suspend the specified instance."""
        LOG.debug(_("Suspend instance"), instance=instance)
        self._set_vm_state(instance["name"],
                           constants.HYPERV_VM_STATE_SUSPENDED)

    def resume(self, instance):
        """Resume the suspended VM instance."""
        LOG.debug(_("Resume instance"), instance=instance)
        self._set_vm_state(instance["name"],
                           constants.HYPERV_VM_STATE_ENABLED)

    def power_off(self, instance):
        """Power off the specified instance."""
        LOG.debug(_("Power off instance"), instance=instance)
        self._set_vm_state(instance["name"],
                           constants.HYPERV_VM_STATE_DISABLED)

    def power_on(self, instance):
        """Power on the specified instance."""
        LOG.debug(_("Power on instance"), instance=instance)
        self._set_vm_state(instance["name"],
                           constants.HYPERV_VM_STATE_ENABLED)

    def _set_vm_state(self, vm_name, req_state):
        try:
            self._vmutils.set_vm_state(vm_name, req_state)
            LOG.debug(_("Successfully changed state of VM %(vm_name)s"
                        " to: %(req_state)s"),
                      {'vm_name': vm_name, 'req_state': req_state})
        except Exception as ex:
            LOG.exception(ex)
            msg = (_("Failed to change vm state of %(vm_name)s"
                     " to %(req_state)s") %
                   {'vm_name': vm_name, 'req_state': req_state})
            raise vmutils.HyperVException(msg)


text:
local utils = require'vanilla.v.libs.utils'

local app_waf_conf = utils.lpcall(function() return require('config.waf') end)
local waf_conf = utils.lpcall(function() return LoadV('vanilla.sys.waf.config') end)
if app_waf_conf ~= nil then
    for k,v in pairs(app_waf_conf) do
        waf_conf[k] = app_waf_conf[k]
    end
end

local match = string.match
local ngxmatch=ngx.re.match
local unescape=ngx.unescape_uri
local get_headers = ngx.req.get_headers
local optionIsOn = function (options) return options == "on" and true or false end
local logpath = waf_conf.logdir
local rulepath = waf_conf.RulePath
local ipWhitelist = waf_conf.ipWhitelist
local ipBlocklist = waf_conf.ipBlocklist
local UrlDeny = optionIsOn(waf_conf.UrlDeny)
local PostCheck = optionIsOn(waf_conf.postMatch)
local CookieCheck = optionIsOn(waf_conf.cookieMatch)
local WhiteCheck = optionIsOn(waf_conf.whiteModule)
local PathInfoFix = optionIsOn(waf_conf.PathInfoFix)
local attacklog = optionIsOn(waf_conf.attacklog)
local CCDeny = optionIsOn(waf_conf.CCDeny)
local Redirect=optionIsOn(waf_conf.Redirect)

local function getClientIp()
        IP = ngx.req.get_headers()["X-Real-IP"]
        if IP == nil then
                IP  = ngx.var.remote_addr
        end
        if IP == nil then
                IP  = "unknown"
        end
        return IP
end

local function write(logfile,msg)
    local fd = io.open(logfile,"ab")
    if fd == nil then return end
    fd:write(msg)
    fd:flush()
    fd:close()
end

local function log(method,url,data,ruletag)
    if attacklog then
        local realIp = getClientIp()
        local ua = ngx.var.http_user_agent
        local servername=ngx.var.server_name
        local time=ngx.localtime()
        if ua  then
            line = realIp.." ["..time.."] \""..method.." "..servername..url.."\" \""..data.."\"  \""..ua.."\" \""..ruletag.."\"\n"
        else
            line = realIp.." ["..time.."] \""..method.." "..servername..url.."\" \""..data.."\" - \""..ruletag.."\"\n"
        end
        local filename = logpath..'/'..servername.."_"..ngx.today().."_sec.log"
        write(filename,line)
    end
end

local function read_rule(var)
    file = io.open(rulepath..'/'..var,"r")
    if file==nil then
        return
    end
    t = {}
    for line in file:lines() do
        table.insert(t,line)
    end
    file:close()
    return(t)
end

local urlrules=read_rule('url')
local argsrules=read_rule('args')
local uarules=read_rule('user-agent')
local wturlrules=read_rule('whiteurl')
local postrules=read_rule('post')
local ckrules=read_rule('cookie')

local function whiteurl()
    if WhiteCheck then
        if wturlrules ~=nil then
            for _,rule in pairs(wturlrules) do
                if ngxmatch(ngx.var.uri,rule,"isjo") then
                    return true
                 end
            end
        end
    end
    return false
end

local function fileExtCheck(ext)
    local items = Set(black_fileExt)
    ext=string.lower(ext)
    if ext then
        for rule in pairs(items) do
            if ngx.re.match(ext,rule,"isjo") then
            log('POST',ngx.var.request_uri,"-","file attack with ext "..ext)
            say_html()
            end
        end
    end
    return false
end

local function Set (list)
  local set = {}
  for _, l in ipairs(list) do set[l] = true end
  return set
end

local function say_html()
    if Redirect then
        ngx.header.content_type = "text/html"
        ngx.header.Power_by = "Vanilla-idevz/vanilla"
        ngx.status = ngx.HTTP_FORBIDDEN
        ngx.say(waf_conf.html)
        ngx.eof()
        -- ngx.exit(ngx.status)
    end
end

local function args()
    for _,rule in pairs(argsrules) do
        local args = ngx.req.get_uri_args()
        for key, val in pairs(args) do
            if type(val)=='table' then
                if val ~= false then
                    data=table.concat(val, " ")
                end
            else
                data=val
            end
            if data and type(data) ~= "boolean" and rule ~="" and ngxmatch(unescape(data),rule,"isjo") then
                log('GET',ngx.var.request_uri,"-",rule)
                say_html()
                return true
            end
        end
    end
    return false
end

local function url()
    if UrlDeny then
        for _,rule in pairs(urlrules) do
            if rule ~="" and ngxmatch(ngx.var.request_uri,rule,"isjo") then
                log('GET',ngx.var.request_uri,"-",rule)
                say_html()
                return true
            end
        end
    end
    return false
end

local function ua()
    local ua = ngx.var.http_user_agent
    if ua ~= nil then
        for _,rule in pairs(uarules) do
            if rule ~="" and ngxmatch(ua,rule,"isjo") then
                log('UA',ngx.var.request_uri,"-",rule)
                say_html()
            return true
            end
        end
    end
    return false
end

local function body(data)
    for _,rule in pairs(postrules) do
        if rule ~="" and data~="" and ngxmatch(unescape(data),rule,"isjo") then
            log('POST',ngx.var.request_uri,data,rule)
            say_html()
            return true
        end
    end
    return false
end

local function cookie()
    local ck = ngx.var.http_cookie
    if CookieCheck and ck then
        for _,rule in pairs(ckrules) do
            if rule ~="" and ngxmatch(ck,rule,"isjo") then
                log('Cookie',ngx.var.request_uri,"-",rule)
                say_html()
            return true
            end
        end
    end
    return false
end

local function denycc()
    if CCDeny then
        local uri=ngx.var.uri
        CCcount=tonumber(string.match(CCrate,'(.*)/'))
        CCseconds=tonumber(string.match(CCrate,'/(.*)'))
        local token = getClientIp()..uri
        local limit = ngx.shared.limit
        local req,_=limit:get(token)
        if req then
            if req > CCcount then
                 ngx.exit(503)
                return true
            else
                 limit:incr(token,1)
            end
        else
            limit:set(token,1,CCseconds)
        end
    end
    return false
end

local function get_boundary()
    local header = get_headers()["content-type"]
    if not header then
        return nil
    end

    if type(header) == "table" then
        header = header[1]
    end

    local m = match(header, ";%s*boundary=\"([^\"]+)\"")
    if m then
        return m
    end

    return match(header, ";%s*boundary=([^\",;]+)")
end

local function whiteip()
    if next(ipWhitelist) ~= nil then
        for _,ip in pairs(ipWhitelist) do
            if getClientIp()==ip then
                return true
            end
        end
    end
        return false
end

local function blockip()
     if next(ipBlocklist) ~= nil then
         for _,ip in pairs(ipBlocklist) do
             if getClientIp()==ip then
                 ngx.exit(403)
                 return true
             end
         end
     end
         return false
end

local content_length=tonumber(ngx.req.get_headers()['content-length'])
local method=ngx.req.get_method()
local ngxmatch=ngx.re.match

local Acc = {}

function Acc:check()
    if whiteip() then
    elseif blockip() then
    elseif denycc() then
    elseif ngx.var.http_Acunetix_Aspect then
        ngx.exit(444)
    elseif ngx.var.http_X_Scan_Memo then
        ngx.exit(444)
    elseif whiteurl() then
    elseif ua() then
    elseif url() then
    elseif args() then
    elseif cookie() then
    elseif PostCheck then
        if method=="POST" then
                local boundary = get_boundary()
            if boundary then
            local len = string.len
                local sock, err = ngx.req.socket()
                if not sock then
                        return
                end
            ngx.req.init_body(128 * 1024)
                sock:settimeout(0)
            local content_length = nil
                content_length=tonumber(ngx.req.get_headers()['content-length'])
                local chunk_size = 4096
                if content_length < chunk_size then
                        chunk_size = content_length
            end
                local size = 0
            while size < content_length do
            local data, err, partial = sock:receive(chunk_size)
            data = data or partial
            if not data then
                return
            end
            ngx.req.append_body(data)
                if body(data) then
                    return true
                    end
            size = size + len(data)
            local m = ngxmatch(data,[[Content-Disposition: form-data;(.+)filename="(.+)\\.(.*)"]],'ijo')
                if m then
                        fileExtCheck(m[3])
                        filetranslate = true
                else
                        if ngxmatch(data,"Content-Disposition:",'isjo') then
                            filetranslate = false
                        end
                        if filetranslate==false then
                            if body(data) then
                                    return true
                            end
                        end
                end
            local less = content_length - size
            if less < chunk_size then
                chunk_size = less
            end
         end
         ngx.req.finish_body()
        else
                ngx.req.read_body()
                local args = ngx.req.get_post_args()
                if not args then
                    return
                end
                for key, val in pairs(args) do
                    if type(val) == "table" then
                        data=table.concat(val, ", ")
                    else
                        data=val
                    end
                    if data and type(data) ~= "boolean" and body(data) then
                                return true
                    end
                end
            end
        end
    else
        return
    end
end

return Acc


text:
package org.apache.jena.tdb.index;

import java.util.Iterator ;

import org.apache.jena.tdb.base.record.Record ;
import org.apache.jena.tdb.base.record.RecordFactory ;

public class IndexWrapper implements Index
{
    private final Index index ;

    public IndexWrapper(Index idx) { this.index = idx ; }

    @Override
    public Record find(Record record)
    { return index.find(record) ; }

    @Override
    public boolean contains(Record record)
    { return index.contains(record) ; }

    @Override
    public boolean add(Record record)
    { return index.add(record) ; }

    @Override
    public boolean delete(Record record)
    { return index.delete(record) ; }

    @Override
    public Iterator<Record> iterator()
    { return index.iterator() ; }

    @Override
    public boolean isEmpty()
    { return index.isEmpty() ; }

    @Override
    public void clear()
    { index.clear() ; }

    @Override
    public void sync()
    { index.sync() ; }

    @Override
    public void close()
    { index.close() ; }

    @Override
    public RecordFactory getRecordFactory()
    { return index.getRecordFactory() ; }

    @Override
    public void check()
    { index.check() ; }

    @Override
    public long size()
    { return index.size() ; }
}


text:
@interface PriceUtil : NSObject

/// Converts given convertedCurrentPrice attributes to a string
+ (NSString *)stringFromConvertedCurrentPrice:(NSNumber *)value currency:(NSString *)currencyID;

/// Converts given attributes to a string
+ (NSString *)stringFromValue:(NSNumber *)value currency:(NSString *)currencyID;

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Chime</title>
    <link rel="stylesheet" href="build/admin-bundle.min.css" />
    <link rel="icon" type="image/png" href="images/favicon.ico">

              <button class="btn btn-navbar dashboard-small dashboard-navbar-button">Log Out</button>

ORGANIZATION INFO

          <form class="dashboard-ping-form col-xs-10 col-xs-push-1 col-md-8 col-md-push-2 col-lg-6 col-lg-push-3">

              Organization Name:
              <input type="email" class="dashboard-input form-control dashboard-small" id="your-name">

              Logo (URL):
              <input type="text" class="dashboard-input form-control dashboard-small" id="your-message">

              Welcome Message:
              <input type="text" class="dashboard-input form-control dashboard-small" id="your-message">

              <button type="submit" class="btn btn-default dashboard-medium dashboard-button-medium">Submit</button>

              <button type="submit" class="btn btn-default dashboard-medium dashboard-button-medium">Cancel</button>

              <button type="submit" class="btn btn-default dashboard-medium dashboard-button-medium dashboard-button-red">Delete Organization</button>

          </form>


text:
package xlog

// FilterFunc
type FilterFunc func(r *Record) bool

// Pipe returns a *Filter that writes to Sink using FilterFunc
func (f FilterFunc) Pipe(s Sink) *Filter {
	return &Filter{
		f:    f,
		next: s,
	}
}

// Filter is a Sink to write records by condition to the next sink.
type Filter struct {
	f    FilterFunc
	next Sink
}

// Write implements `Sink#Write`
func (f *Filter) Write(r *Record) error {
	if f.f(r) {
		return f.next.Write(r)
	}
	return nil
}

// LevelFilter is FilterFunc that filter records whose level is under the given level.
var LevelFilter = func(min Level) FilterFunc {
	return func(r *Record) bool {
		return r.Level >= min
	}
}

// KeyLevelFilter is like LevelFilter but more flexible by key matching.
// If key is not found in `keyLevels`, default level l is used as fallback.
var KeyLevelFilter = func(keyLevels map[interface{}]Level, l Level) FilterFunc {
	return func(r *Record) bool {
		if lvl, ok := keyLevels[r.LoggerKey]; ok {
			return r.Level >= lvl
		}
		return r.Level >= l
	}
}


text:
using AdfToArm.Core.Models.Common;
using Newtonsoft.Json;
using System.Collections.Generic;

namespace AdfToArm.Core.Models.Pipelines.ActivityProperties
{
    [JsonObject]
    public class MlBatchExecutorTypeProperties : IActivityTypeProperties
    {
        /// <summary>
        /// Datasets that are referenced by the webServiceInput property must also be included in the Activity inputs.
        /// </summary>
        [ArmParameter]
        [JsonProperty("webServiceInput", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
        public string WebServiceInput { get; set; }

        /// <summary>
        /// If the web service takes multiple inputs, use the webServiceInputs property instead of using webServiceInput
        ///
        /// Datasets that are referenced by the webServiceInputs property must also be included in the Activity inputs.
        /// </summary>
        [ArmParameter("object")]
        [JsonConverter(typeof(PairConverter))]
        [JsonProperty("webServiceInputs", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
        public KeyValuePair<string, string>[] WebServiceInputs { get; set; }

        /// <summary>
        /// Datasets that are referenced by the webServiceOutputs property must also be included in the Activity outputs.
        /// </summary>
        [ArmParameter("object")]
        [JsonConverter(typeof(PairConverter))]
        [JsonProperty("webServiceOutputs", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
        public KeyValuePair<string, string>[] WebServiceOutputs { get; set; }

        /// <summary>
        /// </summary>
        [ArmParameter("object")]
        [JsonConverter(typeof(PairConverter))]
        [JsonProperty("globalParameters", Required = Required.Default, NullValueHandling = NullValueHandling.Ignore)]
        public KeyValuePair<string, string>[] GlobalParameters { get; set; }
    }
}


text:
package encoding

import (
	"encoding/base64"
	"fmt"
	"math"
	"reflect"
	"time"
)

// newTypeEncoder constructs an encoderFunc for a type.
// The returned encoder only checks CanAddr when allowAddr is true.
func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc {
	if t.Implements(marshalerType) {
		return marshalerEncoder
	}
	if t.Kind() != reflect.Ptr && allowAddr {
		if reflect.PtrTo(t).Implements(marshalerType) {
			return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false))
		}
	}

	// Check for psuedo-types first
	switch t {
	case timeType:
		return timePseudoTypeEncoder
	}

	switch t.Kind() {
	case reflect.Bool:
		return boolEncoder
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return intEncoder
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return uintEncoder
	case reflect.Float32, reflect.Float64:
		return floatEncoder
	case reflect.String:
		return stringEncoder
	case reflect.Interface:
		return interfaceEncoder
	case reflect.Struct:
		return newStructEncoder(t)
	case reflect.Map:
		return newMapEncoder(t)
	case reflect.Slice:
		return newSliceEncoder(t)
	case reflect.Array:
		return newArrayEncoder(t)
	case reflect.Ptr:
		return newPtrEncoder(t)
	case reflect.Func:
		// functions are a special case as they can be used internally for
		// optional arguments. Just return the raw function, if somebody tries
		// to pass a function to the database the JSON marshaller will catch this
		// anyway.
		return funcEncoder
	default:
		return unsupportedTypeEncoder
	}
}

func invalidValueEncoder(v reflect.Value) interface{} {
	return nil
}

func doNothingEncoder(v reflect.Value) interface{} {
	return v.Interface()
}

func marshalerEncoder(v reflect.Value) interface{} {
	if v.Kind() == reflect.Ptr && v.IsNil() {
		return nil
	}
	m := v.Interface().(Marshaler)
	ev, err := m.MarshalRQL()
	if err != nil {
		panic(&MarshalerError{v.Type(), err})
	}

	return ev
}

func addrMarshalerEncoder(v reflect.Value) interface{} {
	va := v.Addr()
	if va.IsNil() {
		return nil
	}
	m := va.Interface().(Marshaler)
	ev, err := m.MarshalRQL()
	if err != nil {
		panic(&MarshalerError{v.Type(), err})
	}

	return ev
}

func boolEncoder(v reflect.Value) interface{} {
	if v.Bool() {
		return true
	} else {
		return false
	}
}

func intEncoder(v reflect.Value) interface{} {
	return v.Int()
}

func uintEncoder(v reflect.Value) interface{} {
	return v.Uint()
}

func floatEncoder(v reflect.Value) interface{} {
	return v.Float()
}

func stringEncoder(v reflect.Value) interface{} {
	return v.String()
}

func interfaceEncoder(v reflect.Value) interface{} {
	if v.IsNil() {
		return nil
	}
	return encode(v.Elem())
}

func funcEncoder(v reflect.Value) interface{} {
	if v.IsNil() {
		return nil
	}
	return v.Interface()
}

func asStringEncoder(v reflect.Value) interface{} {
	return fmt.Sprintf("%v", v.Interface())
}

func unsupportedTypeEncoder(v reflect.Value) interface{} {
	panic(&UnsupportedTypeError{v.Type()})
}

type structEncoder struct {
	fields    []field
	fieldEncs []encoderFunc
}

func (se *structEncoder) encode(v reflect.Value) interface{} {
	m := make(map[string]interface{})
	for i, f := range se.fields {
		fv := fieldByIndex(v, f.index)
		if !fv.IsValid() || f.omitEmpty && se.isEmptyValue(fv) {
			continue
		}

		encField := se.fieldEncs[i](fv)

		// If this field is a referenced field then attempt to extract the value.
		if f.reference {
			// Override the encoded field with the referenced field
			encField = getReferenceField(f, v, encField)
		}

		m[f.name] = encField
	}

	return m
}

func getReferenceField(f field, v reflect.Value, encField interface{}) interface{} {
	refName := f.name
	if f.refName != "" {
		refName = f.refName
	}

	encFields, isArray := encField.([]interface{})
	if isArray {
		refVals := make([]interface{}, len(encFields))
		for i, e := range encFields {
			refVals[i] = extractValue(e, v, f.name, refName)
		}
		return refVals
	}
	refVal := extractValue(encField, v, f.name, refName)
	return refVal
}

func extractValue(encField interface{}, v reflect.Value, name string, refName string) interface{} {
	// referenced fields can only handle maps so return an error if the
	// encoded field is of a different type
	m, ok := encField.(map[string]interface{})
	if !ok {
		err := fmt.Errorf("Error refing field %s in %s, expected object but got %t", refName, name, encField)
		panic(&MarshalerError{v.Type(), err})
	}
	refVal, ok := m[refName]
	if !ok {
		err := fmt.Errorf("Error refing field %s in %s, could not find referenced field", refName, name)
		panic(&MarshalerError{v.Type(), err})
	}
	return refVal
}

func (se *structEncoder) isEmptyValue(v reflect.Value) bool {
	if v.Type() == timeType {
		return v.Interface().(time.Time) == time.Time{}
	}

	return isEmptyValue(v)
}

func newStructEncoder(t reflect.Type) encoderFunc {
	fields := cachedTypeFields(t)
	se := &structEncoder{
		fields:    fields,
		fieldEncs: make([]encoderFunc, len(fields)),
	}
	for i, f := range fields {
		se.fieldEncs[i] = typeEncoder(typeByIndex(t, f.index))
	}
	return se.encode
}

type mapEncoder struct {
	keyEnc, elemEnc encoderFunc
}

func (me *mapEncoder) encode(v reflect.Value) interface{} {
	if v.IsNil() {
		return nil
	}

	m := make(map[string]interface{})

	for _, k := range v.MapKeys() {
		m[me.keyEnc(k).(string)] = me.elemEnc(v.MapIndex(k))
	}

	return m
}

func newMapEncoder(t reflect.Type) encoderFunc {
	var keyEnc encoderFunc
	switch t.Key().Kind() {
	case reflect.Bool:
		keyEnc = asStringEncoder
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		keyEnc = asStringEncoder
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		keyEnc = asStringEncoder
	case reflect.Float32, reflect.Float64:
		keyEnc = asStringEncoder
	case reflect.String:
		keyEnc = stringEncoder
	case reflect.Interface:
		keyEnc = asStringEncoder
	default:
		return unsupportedTypeEncoder
	}

	me := &mapEncoder{keyEnc, typeEncoder(t.Elem())}
	return me.encode
}

// sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil.
type sliceEncoder struct {
	arrayEnc encoderFunc
}

func (se *sliceEncoder) encode(v reflect.Value) interface{} {
	if v.IsNil() {
		return []interface{}{}
	}
	return se.arrayEnc(v)
}

func newSliceEncoder(t reflect.Type) encoderFunc {
	// Byte slices get special treatment; arrays don't.
	if t.Elem().Kind() == reflect.Uint8 {
		return encodeByteSlice
	}
	enc := &sliceEncoder{newArrayEncoder(t)}
	return enc.encode
}

type arrayEncoder struct {
	elemEnc encoderFunc
}

func (ae *arrayEncoder) encode(v reflect.Value) interface{} {
	n := v.Len()

	a := make([]interface{}, n)
	for i := 0; i < n; i++ {
		a[i] = ae.elemEnc(v.Index(i))
	}

	return a
}

func newArrayEncoder(t reflect.Type) encoderFunc {
	enc := &arrayEncoder{typeEncoder(t.Elem())}
	return enc.encode
}

type ptrEncoder struct {
	elemEnc encoderFunc
}

func (pe *ptrEncoder) encode(v reflect.Value) interface{} {
	if v.IsNil() {
		return nil
	}
	return pe.elemEnc(v.Elem())
}

func newPtrEncoder(t reflect.Type) encoderFunc {
	enc := &ptrEncoder{typeEncoder(t.Elem())}
	return enc.encode
}

type condAddrEncoder struct {
	canAddrEnc, elseEnc encoderFunc
}

func (ce *condAddrEncoder) encode(v reflect.Value) interface{} {
	if v.CanAddr() {
		return ce.canAddrEnc(v)
	} else {
		return ce.elseEnc(v)
	}
}

// newCondAddrEncoder returns an encoder that checks whether its value
// CanAddr and delegates to canAddrEnc if so, else to elseEnc.
func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
	enc := &condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
	return enc.encode
}

// Pseudo-type encoders

// Encode a time.Time value to the TIME RQL type
func timePseudoTypeEncoder(v reflect.Value) interface{} {
	t := v.Interface().(time.Time)

	timeVal := float64(t.UnixNano()) / float64(time.Second)

	// use seconds-since-epoch precision if time.Time `t`
	// is before the oldest nanosecond time
	if t.Before(time.Unix(0, math.MinInt64)) {
		timeVal = float64(t.Unix())
	}

	return map[string]interface{}{
		"$reql_type$": "TIME",
		"epoch_time":  timeVal,
		"timezone":    t.Format("-07:00"),
	}
}

// Encode a byte slice to the BINARY RQL type
func encodeByteSlice(v reflect.Value) interface{} {
	var b []byte
	if !v.IsNil() {
		b = v.Bytes()
	}

	dst := make([]byte, base64.StdEncoding.EncodedLen(len(b)))
	base64.StdEncoding.Encode(dst, b)

	return map[string]interface{}{
		"$reql_type$": "BINARY",
		"data":        string(dst),
	}
}


text:
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
 Copyright (C) 2003 Neil Firth
 Copyright (C) 2000, 2001, 2002, 2003 RiskMap srl
 Copyright (C) 2007 StatPro Italia srl
 Copyright (C) 2007 Joseph Wang

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it
 under the terms of the QuantLib license.  You should have received a
 copy of the license along with this program; if not, please email
 <quantlib-dev@lists.sf.net>. The license is also available online at
 <http://quantlib.org/license.shtml>.

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

#include <ql/instruments/basketoption.hpp>

namespace QuantLib {

    BasketOption::BasketOption(
        const boost::shared_ptr<BasketPayoff>& payoff,
        const boost::shared_ptr<Exercise>& exercise)
    : MultiAssetOption(payoff, exercise) {}

}


text:
angular.module('callCenter').factory('Incident', ['$resource',
   function($resource) {
   		return $resource('/callCenter/incident/:incidentId' , {incidentId : '@_id'} , {update: {method: 'PUT'}} );
   		//generate url endpoint by retrieving the _id field of the document
	}
]);


text:
@class BCMonitorEventStream;

@interface BCMonitor : NSObject {
    NSInteger keystrokes;
    NSDate *lastActive;
    NSTimer *timer;
    BCMonitorEventStream *eventStream;
    NSUInteger modifierFlags;
    id eventMonitor;
}

@property (nonatomic) float keysPerSecond;
@property (nonatomic) NSInteger totalKeystrokes;

- (void)saveEventStream;

@end


text:
package com.esperia09.rssnewsbook.compat;

import org.bukkit.plugin.Plugin;

/**
 * Created by esperia on 2016/06/18.
 */
public class CompatManager {

    private final String version;
    private final ICompat compat;

    public CompatManager(Plugin plugin) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        String packageName = plugin.getServer().getClass().getPackage().getName();
        version = packageName.substring(packageName.lastIndexOf('.') + 1);

        // Call Compat
        Class<?> compatClass = Class.forName("com.esperia09.rssnewsbook.compat." + version + ".Compat");
        compat = (ICompat) compatClass.newInstance();
    }

    public String getVersion() {
        return version;
    }

    public ICompat getCompat() {
        return compat;
    }
}


text:
(function ($) {
    var ModalBox, linkHandler, closeHandler, scrollHandler;

    ModalBox = function (el) {
        this.el = $(el);
    }

    ModalBox.prototype.center = function () {
        var $el = this.el,
            $modalBox = $el.find('.modal-box'),
            parentHeight = $el.height(),
            childHeight = $modalBox.outerHeight(),
            offsetTop;

        if ( !$modalBox.is('.top') && !$modalBox.is('.bottom') ) {
            offsetTop = (parentHeight - childHeight) / 2;
            $modalBox.css('top', offsetTop);
        }

        if ( $modalBox.is('.bottom') ) {
            offsetTop = (parentHeight - childHeight);
            $modalBox.css('top', offsetTop);
        }
    };

    ModalBox.prototype.show = function () {
        var $el = this.el,
            id = $el.data('modal'),
            animation = $el.find('.modal-box').data('animation'),
            $iframe = $el.find('iframe');

        if ( $('[data-modal].open').length ) $('[data-modal].open').modalBox('hide');

        if ( $iframe.length ) $iframe.attr('src', $iframe.data('iframeSrc'));

        $el.addClass('open');

        if ( animation == 'none' ) {
            $el.show();

        }else {
            $el.fadeIn(250);

        }

        this.center();
    };

    ModalBox.prototype.hide = function() {
        var $el = this.el,
            animation = $el.find('.modal-box').data('animation'),
            $iframe = $el.find('iframe');

        $el.removeClass('open');

        if ( animation && animation == 'none' ) {
            $el.hide();

            if ( $iframe.length ) $iframe.attr('src', '');

        }else {
            $el.fadeOut(250);

            setTimeout(function () {
                if ( $iframe.length ) $iframe.attr('src', '');
            }, 250);

        }
    };

    $.fn.modalBox = function (option) {
        return this.each(function () {
            var $this = $(this),
                data = $this.data('modalBox');

            if ( !data ) {
                data = new ModalBox(this);
                $this.data('modalBox', data);
            }

            if (typeof option == 'string') {
                data[option]();
            }
        });
    };

    linkHandler = function (event) {
        event.preventDefault();

        var modalId = $(this).data('modalLink'),
            $modalBox = $('[data-modal=' + modalId + ']');

        $modalBox.modalBox('show');
    };

    clickHandler = function (event) {
        var $target = $(event.target);

        if ( !$target.closest('.modal-box').length ) {
            $(this).modalBox('hide');
        }
    };

    closeHandler = function () {
        $(this).closest('[data-modal]').modalBox('hide');
    };

    resizeHandler = function () {
        if ( $('[data-modal].open').length ) $('[data-modal].open').modalBox('center');
    };

    scrollHandler = function (event) {
        event.preventDefault();

        var e0 = event.originalEvent,
            delta = e0.wheelDelta || -e0.detail,
            $modalBox = $(event.target).closest('.modal-box');

        if ( $modalBox.length ) {
            $modalBox.get(0).scrollTop -= delta;
        }
    };

    $('.modal-window').each(function () {
        var $modal = $(this),
            $modalBox = $modal.find('.modal-box'),
            id = $(this).data('modal'),
            time = $modal.data('timeout'),
            scroll = $modal.data('scroll');

        if ( $modal.find('iframe').length ) {
            var iframe = $modal.find('iframe'),
                src = iframe.attr('src');

            $modalBox.addClass('iframe-box');
            iframe.attr('src', '');
            iframe.data('iframeSrc', src);
        }

        if ( time ) {
            setTimeout(function () {
                $modal.modalBox('show');
            }, time);
        }

        if ( scroll ) {
            $(window).on('scroll.modalBox' + id, function () {
                if ( $(this).scrollTop() >= scroll ) {
                    $modal.modalBox('show');

                    $(window).off('.modalBox' + id);
                }
            });
        }
    });

    $(document)
        .on('click.modalBox', '[data-modal-link]', linkHandler)
        .on('mousedown.modalBox', '[data-modal]', clickHandler)
        .on('click.modalBox', '[data-modal] .close-btn', closeHandler)
        .on('mousewheel.modalBox DOMMouseScroll.modalBox', '[data-modal]', scrollHandler);

    $(window).on('resize.modalBox', resizeHandler);

})(jQuery);


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<FlowCallout async="false" continueOnError="false" enabled="true" name="FC-ValidateRequestParams-Metrics">
    <DisplayName>FC-ValidateRequestParams-Metrics</DisplayName>
    <FaultRules/>
    <Properties/>
    <Parameters ignoreUnresolvedVariables="false">
        <Parameter name="validateParamConfig">{ "QueryParams": [
            {"period": {"ValueList": ["CURRENT","ALL"]}}
          ]
        }</Parameter>
    </Parameters>
    <SharedFlowBundle>validate-request-params</SharedFlowBundle>
</FlowCallout>


text:
package client

import (
	"fmt"
	"net/url"
	"strings"

	"github.com/hyperhq/hyper/engine"
	"github.com/hyperhq/runv/hypervisor/types"

	gflag "github.com/jessevdk/go-flags"
)

func (cli *HyperClient) HyperCmdStop(args ...string) error {

	var opts struct {
		Novm bool `long:"onlypod" default:"false" value-name:"false" description:"Stop a Pod, but left the VM running"`
	}
	var parser = gflag.NewParser(&opts, gflag.Default)
	parser.Usage = "stop POD_ID\n\nStop a running pod"
	args, err := parser.Parse()
	if err != nil {
		if !strings.Contains(err.Error(), "Usage") {
			return err
		} else {
			return nil
		}
	}
	if len(args) == 1 {
		return fmt.Errorf("\"stop\" requires a minimum of 1 argument, please provide POD ID.\n")
	}

	podID := args[1]
	stopVm := "yes"
	if opts.Novm {
		stopVm = "no"
	}
	code, cause, err := cli.StopPod(podID, stopVm)
	if err != nil {
		return err
	}
	if code != types.E_POD_STOPPED && code != types.E_VM_SHUTDOWN {
		return fmt.Errorf("Error code is %d, cause is %s", code, cause)
	}
	fmt.Printf("Successfully shutdown the POD: %s!\n", podID)
	return nil
}

func (cli *HyperClient) StopPod(podId, stopVm string) (int, string, error) {
	v := url.Values{}
	v.Set("podId", podId)
	v.Set("stopVm", stopVm)
	body, _, err := readBody(cli.call("POST", "/pod/stop?"+v.Encode(), nil, nil))
	if err != nil {
		if strings.Contains(err.Error(), "leveldb: not found") {
			return -1, "", fmt.Errorf("Can not find that POD ID to stop, please check your POD ID!")
		}
		return -1, "", err
	}
	out := engine.NewOutput()
	remoteInfo, err := out.AddEnv()
	if err != nil {
		return -1, "", err
	}

	if _, err := out.Write(body); err != nil {
		return -1, "", err
	}
	out.Close()
	// This 'ID' stands for pod ID
	// This 'Code' should be E_SHUTDOWN
	// THis 'Cause' ..
	if remoteInfo.Exists("ID") {
		// TODO ...
	}
	return remoteInfo.GetInt("Code"), remoteInfo.Get("Cause"), nil
}