text:
#ifndef _DMUSICC_
#define _DMUSICC_

#include <windows.h>

#define COM_NO_WINDOWS_H
#include <objbase.h>

#include <mmsystem.h>

#include "dls1.h"
#include "dmerror.h"
#include "dmdls.h"
#include "dsound.h"
#include "dmusbuff.h"

#include <pshpack8.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef ULONGLONG    SAMPLE_TIME;
typedef ULONGLONG    SAMPLE_POSITION;
typedef SAMPLE_TIME *LPSAMPLE_TIME;

#define DMUS_MAX_DESCRIPTION 128
#define DMUS_MAX_DRIVER 128

typedef struct _DMUS_BUFFERDESC *LPDMUS_BUFFERDESC;
typedef struct _DMUS_BUFFERDESC
{
    DWORD dwSize;
    DWORD dwFlags;
    GUID guidBufferFormat;
    DWORD cbBuffer;
} DMUS_BUFFERDESC;

/* DMUS_EFFECT_ flags are used in the dwEffectFlags fields of both DMUS_PORTCAPS
 * and DMUS_PORTPARAMS.
 */
#define DMUS_EFFECT_NONE             0x00000000
#define DMUS_EFFECT_REVERB           0x00000001
#define DMUS_EFFECT_CHORUS           0x00000002
#define DMUS_EFFECT_DELAY            0x00000004

/* For DMUS_PORTCAPS dwClass
 */
#define DMUS_PC_INPUTCLASS       (0)
#define DMUS_PC_OUTPUTCLASS      (1)

/* For DMUS_PORTCAPS dwFlags
 */
#define DMUS_PC_DLS              (0x00000001)   // Supports DLS downloading and DLS level 1.
#define DMUS_PC_EXTERNAL         (0x00000002)   // External MIDI module.
#define DMUS_PC_SOFTWARESYNTH    (0x00000004)   // Software synthesizer.
#define DMUS_PC_MEMORYSIZEFIXED  (0x00000008)   // Memory size is fixed.
#define DMUS_PC_GMINHARDWARE     (0x00000010)   // GM sound set is built in, no need to download.
#define DMUS_PC_GSINHARDWARE     (0x00000020)   // GS sound set is built in.
#define DMUS_PC_XGINHARDWARE     (0x00000040)   // XG sound set is built in.
#define DMUS_PC_DIRECTSOUND      (0x00000080)   // Connects to DirectSound via a DSound buffer.
#define DMUS_PC_SHAREABLE        (0x00000100)   // Synth can be actively shared by multiple apps at once.
#define DMUS_PC_DLS2             (0x00000200)   // Supports DLS2 instruments.
#define DMUS_PC_AUDIOPATH        (0x00000400)   // Multiple outputs can be connected to DirectSound for audiopaths.
#define DMUS_PC_WAVE             (0x00000800)   // Supports streaming and one shot waves.

#define DMUS_PC_SYSTEMMEMORY     (0x7FFFFFFF)   // Sample memory is system memory.

typedef struct _DMUS_PORTCAPS
{
    DWORD   dwSize;
    DWORD   dwFlags;
    GUID    guidPort;
    DWORD   dwClass;
    DWORD   dwType;
    DWORD   dwMemorySize;
    DWORD   dwMaxChannelGroups;
    DWORD   dwMaxVoices;
    DWORD   dwMaxAudioChannels;
    DWORD   dwEffectFlags;
    WCHAR   wszDescription[DMUS_MAX_DESCRIPTION];
} DMUS_PORTCAPS;

typedef DMUS_PORTCAPS *LPDMUS_PORTCAPS;

/* Values for DMUS_PORTCAPS dwType. This field indicates the underlying
 * driver type of the port.
 */
#define DMUS_PORT_WINMM_DRIVER      (0)
#define DMUS_PORT_USER_MODE_SYNTH   (1)
#define DMUS_PORT_KERNEL_MODE       (2)

/* These flags (set in dwValidParams) indicate which other members of the */
/* DMUS_PORTPARAMS are valid. */
/* */
#define DMUS_PORTPARAMS_VOICES           0x00000001
#define DMUS_PORTPARAMS_CHANNELGROUPS    0x00000002
#define DMUS_PORTPARAMS_AUDIOCHANNELS    0x00000004
#define DMUS_PORTPARAMS_SAMPLERATE       0x00000008
#define DMUS_PORTPARAMS_EFFECTS          0x00000020
#define DMUS_PORTPARAMS_SHARE            0x00000040
#define DMUS_PORTPARAMS_FEATURES         0x00000080     /* DirectX 8.0 and above */

typedef struct _DMUS_PORTPARAMS
{
    DWORD   dwSize;
    DWORD   dwValidParams;
    DWORD   dwVoices;
    DWORD   dwChannelGroups;
    DWORD   dwAudioChannels;
    DWORD   dwSampleRate;
    DWORD   dwEffectFlags;
    BOOL    fShare;
} DMUS_PORTPARAMS7;

typedef struct _DMUS_PORTPARAMS8
{
    DWORD   dwSize;
    DWORD   dwValidParams;
    DWORD   dwVoices;
    DWORD   dwChannelGroups;
    DWORD   dwAudioChannels;
    DWORD   dwSampleRate;
    DWORD   dwEffectFlags;
    BOOL    fShare;
    DWORD   dwFeatures;
} DMUS_PORTPARAMS8;

#define DMUS_PORT_FEATURE_AUDIOPATH     0x00000001	/* Supports audiopath connection to DSound buffers. */
#define DMUS_PORT_FEATURE_STREAMING     0x00000002	/* Supports streaming waves through the synth. */

typedef DMUS_PORTPARAMS8 DMUS_PORTPARAMS;
typedef DMUS_PORTPARAMS *LPDMUS_PORTPARAMS;

typedef struct _DMUS_SYNTHSTATS *LPDMUS_SYNTHSTATS;
typedef struct _DMUS_SYNTHSTATS8 *LPDMUS_SYNTHSTATS8;
typedef struct _DMUS_SYNTHSTATS
{
    DWORD   dwSize;             /* Size in bytes of the structure */
    DWORD   dwValidStats;       /* Flags indicating which fields below are valid. */
    DWORD   dwVoices;           /* Average number of voices playing. */
    DWORD   dwTotalCPU;         /* Total CPU usage as percent * 100. */
    DWORD   dwCPUPerVoice;      /* CPU per voice as percent * 100. */
    DWORD   dwLostNotes;        /* Number of notes lost in 1 second. */
    DWORD   dwFreeMemory;       /* Free memory in bytes */
    long    lPeakVolume;        /* Decibel level * 100. */
} DMUS_SYNTHSTATS;

typedef struct _DMUS_SYNTHSTATS8
{
    DWORD   dwSize;             /* Size in bytes of the structure */
    DWORD   dwValidStats;       /* Flags indicating which fields below are valid. */
    DWORD   dwVoices;           /* Average number of voices playing. */
    DWORD   dwTotalCPU;         /* Total CPU usage as percent * 100. */
    DWORD   dwCPUPerVoice;      /* CPU per voice as percent * 100. */
    DWORD   dwLostNotes;        /* Number of notes lost in 1 second. */
    DWORD   dwFreeMemory;       /* Free memory in bytes */
    long    lPeakVolume;        /* Decibel level * 100. */
	DWORD   dwSynthMemUse;		/* Memory used by synth wave data */
} DMUS_SYNTHSTATS8;

#define DMUS_SYNTHSTATS_VOICES          (1 << 0)
#define DMUS_SYNTHSTATS_TOTAL_CPU       (1 << 1)
#define DMUS_SYNTHSTATS_CPU_PER_VOICE   (1 << 2)
#define DMUS_SYNTHSTATS_LOST_NOTES      (1 << 3)
#define DMUS_SYNTHSTATS_PEAK_VOLUME     (1 << 4)
#define DMUS_SYNTHSTATS_FREE_MEMORY     (1 << 5)

#define DMUS_SYNTHSTATS_SYSTEMMEMORY    DMUS_PC_SYSTEMMEMORY

typedef struct _DMUS_WAVES_REVERB_PARAMS
{
    float   fInGain;        /* Input gain in dB (to avoid output overflows) */
    float   fReverbMix;     /* Reverb mix in dB. 0dB means 100% wet reverb (no direct signal)
                            Negative values gives less wet signal.
                            The coeficients are calculated so that the overall output level stays
                            (approximately) constant regardless of the ammount of reverb mix. */
    float   fReverbTime;    /* The reverb decay time, in milliseconds. */
    float   fHighFreqRTRatio; /* The ratio of the high frequencies to the global reverb time.
                            Unless very 'splashy-bright' reverbs are wanted, this should be set to
                            a value < 1.0.
                            For example if dRevTime==1000ms and dHighFreqRTRatio=0.1 than the
                            decay time for high frequencies will be 100ms.*/

} DMUS_WAVES_REVERB_PARAMS;

/*  Note: Default values for Reverb are:
    fInGain             = 0.0dB   (no change in level)
    fReverbMix          = -10.0dB   (a reasonable reverb mix)
    fReverbTime         = 1000.0ms (one second global reverb time)
    fHighFreqRTRatio    = 0.001    (the ratio of the high frequencies to the global reverb time)
*/

typedef enum
{
    DMUS_CLOCK_SYSTEM = 0,
    DMUS_CLOCK_WAVE = 1
} DMUS_CLOCKTYPE;

#define DMUS_CLOCKF_GLOBAL              0x00000001

typedef struct _DMUS_CLOCKINFO7 *LPDMUS_CLOCKINFO7;
typedef struct _DMUS_CLOCKINFO7
{
    DWORD           dwSize;
    DMUS_CLOCKTYPE  ctType;
    GUID            guidClock;          /* Identifies this time source */
    WCHAR           wszDescription[DMUS_MAX_DESCRIPTION];
} DMUS_CLOCKINFO7;

typedef struct _DMUS_CLOCKINFO8 *LPDMUS_CLOCKINFO8;
typedef struct _DMUS_CLOCKINFO8
{
    DWORD           dwSize;
    DMUS_CLOCKTYPE  ctType;
    GUID            guidClock;          /* Identifies this time source */
    WCHAR           wszDescription[DMUS_MAX_DESCRIPTION];
    DWORD           dwFlags;
} DMUS_CLOCKINFO8;

typedef DMUS_CLOCKINFO8 DMUS_CLOCKINFO;
typedef DMUS_CLOCKINFO *LPDMUS_CLOCKINFO;

/* Default bus identifiers
 *
 * The first 17 are direct mappings to the destinations defined in both
 * the MMA DLS Level 2 specification and the Microsoft Multi-Channel audio
 * specification.
 */
#define DSBUSID_FIRST_SPKR_LOC              0
#define DSBUSID_FRONT_LEFT                  0
#define DSBUSID_LEFT                        0   /* Front left is also just left */
#define DSBUSID_FRONT_RIGHT                 1
#define DSBUSID_RIGHT                       1   /* Ditto front right */
#define DSBUSID_FRONT_CENTER                2
#define DSBUSID_LOW_FREQUENCY               3
#define DSBUSID_BACK_LEFT                   4
#define DSBUSID_BACK_RIGHT                  5
#define DSBUSID_FRONT_LEFT_OF_CENTER        6
#define DSBUSID_FRONT_RIGHT_OF_CENTER       7
#define DSBUSID_BACK_CENTER                 8
#define DSBUSID_SIDE_LEFT                   9
#define DSBUSID_SIDE_RIGHT                 10
#define DSBUSID_TOP_CENTER                 11
#define DSBUSID_TOP_FRONT_LEFT             12
#define DSBUSID_TOP_FRONT_CENTER           13
#define DSBUSID_TOP_FRONT_RIGHT            14
#define DSBUSID_TOP_BACK_LEFT              15
#define DSBUSID_TOP_BACK_CENTER            16
#define DSBUSID_TOP_BACK_RIGHT             17
#define DSBUSID_LAST_SPKR_LOC              17

#define DSBUSID_IS_SPKR_LOC(id) ( ((id) >= DSBUSID_FIRST_SPKR_LOC) && ((id) <= DSBUSID_LAST_SPKR_LOC) )

/* These bus identifiers are for the standard DLS effect sends
 */
#define DSBUSID_REVERB_SEND                64
#define DSBUSID_CHORUS_SEND                65

/* Dynamic bus identifiers start here. See the documentation for how
 * synthesizers map the output of voices to static and dynamic
 * bus identifiers.
 */
#define DSBUSID_DYNAMIC_0                 512

/* Null bus, used to identify busses that have no function mapping.
*/
#define DSBUSID_NULL			   0xFFFFFFFF

interface IDirectMusic;
interface IDirectMusic8;
interface IDirectMusicBuffer;
interface IDirectMusicPort;
interface IDirectMusicThru;
interface IReferenceClock;

#ifndef __cplusplus

typedef interface IDirectMusic IDirectMusic;
typedef interface IDirectMusic8 IDirectMusic8;
typedef interface IDirectMusicPort IDirectMusicPort;
typedef interface IDirectMusicBuffer IDirectMusicBuffer;
typedef interface IDirectMusicThru IDirectMusicThru;
typedef interface IReferenceClock IReferenceClock;

#endif  /* C++ */

typedef IDirectMusic *LPDIRECTMUSIC;
typedef IDirectMusic8 *LPDIRECTMUSIC8;
typedef IDirectMusicPort *LPDIRECTMUSICPORT;
typedef IDirectMusicBuffer *LPDIRECTMUSICBUFFER;

#undef  INTERFACE
#define INTERFACE  IDirectMusic
DECLARE_INTERFACE_(IDirectMusic, IUnknown)
{
    /*  IUnknown */
    STDMETHOD(QueryInterface)       (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)        (THIS) PURE;
    STDMETHOD_(ULONG,Release)       (THIS) PURE;

    /*  IDirectMusic */
    STDMETHOD(EnumPort)             (THIS_ DWORD dwIndex,
                                           LPDMUS_PORTCAPS pPortCaps) PURE;
    STDMETHOD(CreateMusicBuffer)    (THIS_ LPDMUS_BUFFERDESC pBufferDesc,
                                           LPDIRECTMUSICBUFFER *ppBuffer,
                                           LPUNKNOWN pUnkOuter) PURE;
    STDMETHOD(CreatePort)           (THIS_ REFCLSID rclsidPort,
                                           LPDMUS_PORTPARAMS pPortParams,
                                           LPDIRECTMUSICPORT *ppPort,
                                           LPUNKNOWN pUnkOuter) PURE;
    STDMETHOD(EnumMasterClock)      (THIS_ DWORD dwIndex,
                                           LPDMUS_CLOCKINFO lpClockInfo) PURE;
    STDMETHOD(GetMasterClock)       (THIS_ LPGUID pguidClock,
                                           IReferenceClock **ppReferenceClock) PURE;
    STDMETHOD(SetMasterClock)       (THIS_ REFGUID rguidClock) PURE;
    STDMETHOD(Activate)             (THIS_ BOOL fEnable) PURE;
    STDMETHOD(GetDefaultPort)       (THIS_ LPGUID pguidPort) PURE;
    STDMETHOD(SetDirectSound)       (THIS_ LPDIRECTSOUND pDirectSound,
                                           HWND hWnd) PURE;
};

#undef  INTERFACE
#define INTERFACE  IDirectMusic8
DECLARE_INTERFACE_(IDirectMusic8, IDirectMusic)
{
    /*  IUnknown */
    STDMETHOD(QueryInterface)       (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)        (THIS) PURE;
    STDMETHOD_(ULONG,Release)       (THIS) PURE;

    /*  IDirectMusic */
    STDMETHOD(EnumPort)             (THIS_ DWORD dwIndex,
                                           LPDMUS_PORTCAPS pPortCaps) PURE;
    STDMETHOD(CreateMusicBuffer)    (THIS_ LPDMUS_BUFFERDESC pBufferDesc,
                                           LPDIRECTMUSICBUFFER *ppBuffer,
                                           LPUNKNOWN pUnkOuter) PURE;
    STDMETHOD(CreatePort)           (THIS_ REFCLSID rclsidPort,
                                           LPDMUS_PORTPARAMS pPortParams,
                                           LPDIRECTMUSICPORT *ppPort,
                                           LPUNKNOWN pUnkOuter) PURE;
    STDMETHOD(EnumMasterClock)      (THIS_ DWORD dwIndex,
                                           LPDMUS_CLOCKINFO lpClockInfo) PURE;
    STDMETHOD(GetMasterClock)       (THIS_ LPGUID pguidClock,
                                           IReferenceClock **ppReferenceClock) PURE;
    STDMETHOD(SetMasterClock)       (THIS_ REFGUID rguidClock) PURE;
    STDMETHOD(Activate)             (THIS_ BOOL fEnable) PURE;
    STDMETHOD(GetDefaultPort)       (THIS_ LPGUID pguidPort) PURE;
    STDMETHOD(SetDirectSound)       (THIS_ LPDIRECTSOUND pDirectSound,
                                           HWND hWnd) PURE;
    /*  IDirectMusic8 */
    STDMETHOD(SetExternalMasterClock)
                                    (THIS_ IReferenceClock *pClock) PURE;
};

#undef  INTERFACE
#define INTERFACE  IDirectMusicBuffer
DECLARE_INTERFACE_(IDirectMusicBuffer, IUnknown)
{
    /*  IUnknown */
    STDMETHOD(QueryInterface)       (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)        (THIS) PURE;
    STDMETHOD_(ULONG,Release)       (THIS) PURE;

    /*  IDirectMusicBuffer */
    STDMETHOD(Flush)                (THIS) PURE;
    STDMETHOD(TotalTime)            (THIS_ LPREFERENCE_TIME prtTime) PURE;

    STDMETHOD(PackStructured)       (THIS_ REFERENCE_TIME rt,
                                           DWORD dwChannelGroup,
                                           DWORD dwChannelMessage) PURE;

    STDMETHOD(PackUnstructured)     (THIS_ REFERENCE_TIME rt,
                                           DWORD dwChannelGroup,
                                           DWORD cb,
                                           LPBYTE lpb) PURE;

    STDMETHOD(ResetReadPtr)         (THIS) PURE;
    STDMETHOD(GetNextEvent)         (THIS_ LPREFERENCE_TIME prt,
                                           LPDWORD pdwChannelGroup,
                                           LPDWORD pdwLength,
                                           LPBYTE *ppData) PURE;

    STDMETHOD(GetRawBufferPtr)      (THIS_ LPBYTE *ppData) PURE;
    STDMETHOD(GetStartTime)         (THIS_ LPREFERENCE_TIME prt) PURE;
    STDMETHOD(GetUsedBytes)         (THIS_ LPDWORD pcb) PURE;
    STDMETHOD(GetMaxBytes)          (THIS_ LPDWORD pcb) PURE;
    STDMETHOD(GetBufferFormat)      (THIS_ LPGUID pGuidFormat) PURE;

    STDMETHOD(SetStartTime)         (THIS_ REFERENCE_TIME rt) PURE;
    STDMETHOD(SetUsedBytes)         (THIS_ DWORD cb) PURE;
};

typedef IDirectMusicBuffer IDirectMusicBuffer8;
typedef IDirectMusicBuffer8 *LPDIRECTMUSICBUFFER8;

#undef  INTERFACE
#define INTERFACE  IDirectMusicInstrument
DECLARE_INTERFACE_(IDirectMusicInstrument, IUnknown)
{
    /* IUnknown */
    STDMETHOD(QueryInterface)           (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)            (THIS) PURE;
    STDMETHOD_(ULONG,Release)           (THIS) PURE;

    /* IDirectMusicInstrument */
    STDMETHOD(GetPatch)                 (THIS_ DWORD* pdwPatch) PURE;
    STDMETHOD(SetPatch)                 (THIS_ DWORD dwPatch) PURE;
};

typedef IDirectMusicInstrument IDirectMusicInstrument8;
typedef IDirectMusicInstrument8 *LPDIRECTMUSICINSTRUMENT8;

#undef  INTERFACE
#define INTERFACE  IDirectMusicDownloadedInstrument
DECLARE_INTERFACE_(IDirectMusicDownloadedInstrument, IUnknown)
{
    /* IUnknown */
    STDMETHOD(QueryInterface)           (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)            (THIS) PURE;
    STDMETHOD_(ULONG,Release)           (THIS) PURE;

    /* IDirectMusicDownloadedInstrument */
    /* None at this time */
};

typedef IDirectMusicDownloadedInstrument IDirectMusicDownloadedInstrument8;
typedef IDirectMusicDownloadedInstrument8 *LPDIRECTMUSICDOWNLOADEDINSTRUMENT8;

#undef  INTERFACE
#define INTERFACE  IDirectMusicCollection
DECLARE_INTERFACE_(IDirectMusicCollection, IUnknown)
{
    /* IUnknown */
    STDMETHOD(QueryInterface)           (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)            (THIS) PURE;
    STDMETHOD_(ULONG,Release)           (THIS) PURE;

    /* IDirectMusicCollection */
    STDMETHOD(GetInstrument)            (THIS_ DWORD dwPatch,
                                               IDirectMusicInstrument** ppInstrument) PURE;
    STDMETHOD(EnumInstrument)           (THIS_ DWORD dwIndex,
                                               DWORD* pdwPatch,
                                               LPWSTR pwszName,
                                               DWORD dwNameLen) PURE;
};

typedef IDirectMusicCollection IDirectMusicCollection8;
typedef IDirectMusicCollection8 *LPDIRECTMUSICCOLLECTION8;

#undef  INTERFACE
#define INTERFACE  IDirectMusicDownload
DECLARE_INTERFACE_(IDirectMusicDownload , IUnknown)
{
    /* IUnknown */
    STDMETHOD(QueryInterface)       (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)        (THIS) PURE;
    STDMETHOD_(ULONG,Release)       (THIS) PURE;

    /* IDirectMusicDownload */
    STDMETHOD(GetBuffer)            (THIS_ void** ppvBuffer,
                                           DWORD* pdwSize) PURE;
};

typedef IDirectMusicDownload IDirectMusicDownload8;
typedef IDirectMusicDownload8 *LPDIRECTMUSICDOWNLOAD8;

#undef  INTERFACE
#define INTERFACE  IDirectMusicPortDownload
DECLARE_INTERFACE_(IDirectMusicPortDownload, IUnknown)
{
    /* IUnknown */
    STDMETHOD(QueryInterface)       (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)        (THIS) PURE;
    STDMETHOD_(ULONG,Release)       (THIS) PURE;

    /* IDirectMusicPortDownload */
    STDMETHOD(GetBuffer)            (THIS_ DWORD dwDLId,
                                           IDirectMusicDownload** ppIDMDownload) PURE;
    STDMETHOD(AllocateBuffer)       (THIS_ DWORD dwSize,
                                           IDirectMusicDownload** ppIDMDownload) PURE;
    STDMETHOD(GetDLId)              (THIS_ DWORD* pdwStartDLId,
                                           DWORD dwCount) PURE;
    STDMETHOD(GetAppend)            (THIS_ DWORD* pdwAppend) PURE;
    STDMETHOD(Download)             (THIS_ IDirectMusicDownload* pIDMDownload) PURE;
    STDMETHOD(Unload)               (THIS_ IDirectMusicDownload* pIDMDownload) PURE;
};

typedef IDirectMusicPortDownload IDirectMusicPortDownload8;
typedef IDirectMusicPortDownload8 *LPDIRECTMUSICPORTDOWNLOAD8;

/* Standard values for voice priorities. Numerically higher priorities are higher in priority.
 * These priorities are used to set the voice priority for all voices on a channel. They are
 * used in the dwPriority parameter of IDirectMusicPort::GetPriority and returned in the
 * lpwPriority parameter of pdwPriority.
 *
 * These priorities are shared with DirectSound.
 */

#ifndef _DIRECTAUDIO_PRIORITIES_DEFINED_
#define _DIRECTAUDIO_PRIORITIES_DEFINED_

#define DAUD_CRITICAL_VOICE_PRIORITY    (0xF0000000)
#define DAUD_HIGH_VOICE_PRIORITY        (0xC0000000)
#define DAUD_STANDARD_VOICE_PRIORITY    (0x80000000)
#define DAUD_LOW_VOICE_PRIORITY         (0x40000000)
#define DAUD_PERSIST_VOICE_PRIORITY     (0x10000000)

/* These are the default priorities assigned if not overridden. By default priorities are
 * equal across channel groups (e.g. channel 5 on channel group 1 has the same priority as
 * channel 5 on channel group 2).
 *
 * In accordance with DLS level 1, channel 10 has the highest priority, followed by 1 through 16
 * except for 10.
 */
#define DAUD_CHAN1_VOICE_PRIORITY_OFFSET    (0x0000000E)
#define DAUD_CHAN2_VOICE_PRIORITY_OFFSET    (0x0000000D)
#define DAUD_CHAN3_VOICE_PRIORITY_OFFSET    (0x0000000C)
#define DAUD_CHAN4_VOICE_PRIORITY_OFFSET    (0x0000000B)
#define DAUD_CHAN5_VOICE_PRIORITY_OFFSET    (0x0000000A)
#define DAUD_CHAN6_VOICE_PRIORITY_OFFSET    (0x00000009)
#define DAUD_CHAN7_VOICE_PRIORITY_OFFSET    (0x00000008)
#define DAUD_CHAN8_VOICE_PRIORITY_OFFSET    (0x00000007)
#define DAUD_CHAN9_VOICE_PRIORITY_OFFSET    (0x00000006)
#define DAUD_CHAN10_VOICE_PRIORITY_OFFSET   (0x0000000F)
#define DAUD_CHAN11_VOICE_PRIORITY_OFFSET   (0x00000005)
#define DAUD_CHAN12_VOICE_PRIORITY_OFFSET   (0x00000004)
#define DAUD_CHAN13_VOICE_PRIORITY_OFFSET   (0x00000003)
#define DAUD_CHAN14_VOICE_PRIORITY_OFFSET   (0x00000002)
#define DAUD_CHAN15_VOICE_PRIORITY_OFFSET   (0x00000001)
#define DAUD_CHAN16_VOICE_PRIORITY_OFFSET   (0x00000000)

#define DAUD_CHAN1_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN1_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN2_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN2_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN3_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN3_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN4_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN4_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN5_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN5_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN6_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN6_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN7_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN7_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN8_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN8_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN9_DEF_VOICE_PRIORITY   (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN9_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN10_DEF_VOICE_PRIORITY  (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN10_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN11_DEF_VOICE_PRIORITY  (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN11_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN12_DEF_VOICE_PRIORITY  (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN12_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN13_DEF_VOICE_PRIORITY  (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN13_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN14_DEF_VOICE_PRIORITY  (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN14_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN15_DEF_VOICE_PRIORITY  (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN15_VOICE_PRIORITY_OFFSET)
#define DAUD_CHAN16_DEF_VOICE_PRIORITY  (DAUD_STANDARD_VOICE_PRIORITY | DAUD_CHAN16_VOICE_PRIORITY_OFFSET)

#endif  /* _DIRECTAUDIO_PRIORITIES_DEFINED_ */

#undef  INTERFACE
#define INTERFACE  IDirectMusicPort
DECLARE_INTERFACE_(IDirectMusicPort, IUnknown)
{
    /*  IUnknown */
    STDMETHOD(QueryInterface)       (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)        (THIS) PURE;
    STDMETHOD_(ULONG,Release)       (THIS) PURE;

    /*  IDirectMusicPort */
    /*  */
    STDMETHOD(PlayBuffer)           (THIS_ LPDIRECTMUSICBUFFER pBuffer) PURE;
    STDMETHOD(SetReadNotificationHandle) (THIS_ HANDLE hEvent) PURE;
    STDMETHOD(Read)                 (THIS_ LPDIRECTMUSICBUFFER pBuffer) PURE;
    STDMETHOD(DownloadInstrument)   (THIS_ IDirectMusicInstrument *pInstrument,
                                     IDirectMusicDownloadedInstrument **ppDownloadedInstrument,
                                     DMUS_NOTERANGE *pNoteRanges,
                                     DWORD dwNumNoteRanges) PURE;
    STDMETHOD(UnloadInstrument)     (THIS_ IDirectMusicDownloadedInstrument *pDownloadedInstrument) PURE;
    STDMETHOD(GetLatencyClock)      (THIS_ IReferenceClock **ppClock) PURE;
    STDMETHOD(GetRunningStats)      (THIS_ LPDMUS_SYNTHSTATS pStats) PURE;
    STDMETHOD(Compact)              (THIS) PURE;
    STDMETHOD(GetCaps)              (THIS_ LPDMUS_PORTCAPS pPortCaps) PURE;
    STDMETHOD(DeviceIoControl)      (THIS_ DWORD dwIoControlCode,
                                           LPVOID lpInBuffer,
                                           DWORD nInBufferSize,
                                           LPVOID lpOutBuffer,
                                           DWORD nOutBufferSize,
                                           LPDWORD lpBytesReturned,
                                           LPOVERLAPPED lpOverlapped) PURE;
    STDMETHOD(SetNumChannelGroups)  (THIS_ DWORD dwChannelGroups) PURE;
    STDMETHOD(GetNumChannelGroups)  (THIS_ LPDWORD pdwChannelGroups) PURE;
    STDMETHOD(Activate)             (THIS_ BOOL fActive) PURE;
    STDMETHOD(SetChannelPriority)   (THIS_ DWORD dwChannelGroup, DWORD dwChannel, DWORD dwPriority) PURE;
    STDMETHOD(GetChannelPriority)   (THIS_ DWORD dwChannelGroup, DWORD dwChannel, LPDWORD pdwPriority) PURE;
    STDMETHOD(SetDirectSound)       (THIS_ LPDIRECTSOUND pDirectSound, LPDIRECTSOUNDBUFFER pDirectSoundBuffer) PURE;
    STDMETHOD(GetFormat)            (THIS_ LPWAVEFORMATEX pWaveFormatEx, LPDWORD pdwWaveFormatExSize, LPDWORD pdwBufferSize) PURE;
};

typedef IDirectMusicPort IDirectMusicPort8;
typedef IDirectMusicPort8 *LPDIRECTMUSICPORT8;

#undef  INTERFACE
#define INTERFACE  IDirectMusicThru
DECLARE_INTERFACE_(IDirectMusicThru, IUnknown)
{
    /*  IUnknown */
    STDMETHOD(QueryInterface)       (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)        (THIS) PURE;
    STDMETHOD_(ULONG,Release)       (THIS) PURE;

    /* IDirectMusicThru
     */
    STDMETHOD(ThruChannel)          (THIS_ DWORD dwSourceChannelGroup,
                                           DWORD dwSourceChannel,
                                           DWORD dwDestinationChannelGroup,
                                           DWORD dwDestinationChannel,
                                           LPDIRECTMUSICPORT pDestinationPort) PURE;
};

typedef IDirectMusicThru IDirectMusicThru8;
typedef IDirectMusicThru8 *LPDIRECTMUSICTHRU8;

#ifndef __IReferenceClock_INTERFACE_DEFINED__
#define __IReferenceClock_INTERFACE_DEFINED__

DEFINE_GUID(IID_IReferenceClock,0x56a86897,0x0ad4,0x11ce,0xb0,0x3a,0x00,0x20,0xaf,0x0b,0xa7,0x70);

#undef  INTERFACE
#define INTERFACE  IReferenceClock
DECLARE_INTERFACE_(IReferenceClock, IUnknown)
{
    /*  IUnknown */
    STDMETHOD(QueryInterface)           (THIS_ REFIID, LPVOID FAR *) PURE;
    STDMETHOD_(ULONG,AddRef)            (THIS) PURE;
    STDMETHOD_(ULONG,Release)           (THIS) PURE;

    /*  IReferenceClock */
    /*  */

    /*  get the time now */
    STDMETHOD(GetTime)                  (THIS_ REFERENCE_TIME *pTime) PURE;

    /*  ask for an async notification that a time has elapsed */
    STDMETHOD(AdviseTime)               (THIS_ REFERENCE_TIME baseTime,         /*  base time */
                                               REFERENCE_TIME streamTime,       /*  stream offset time */
                                               HANDLE hEvent,                   /*  advise via this event */
                                               DWORD * pdwAdviseCookie) PURE;   /*  where your cookie goes */

    /*  ask for an async periodic notification that a time has elapsed */
    STDMETHOD(AdvisePeriodic)           (THIS_ REFERENCE_TIME startTime,        /*  starting at this time */
                                               REFERENCE_TIME periodTime,       /*  time between notifications */
                                               HANDLE hSemaphore,               /*  advise via a semaphore */
                                               DWORD * pdwAdviseCookie) PURE;   /*  where your cookie goes */

    /*  cancel a request for notification */
    STDMETHOD(Unadvise)                 (THIS_ DWORD dwAdviseCookie) PURE;
};

#endif /* __IReferenceClock_INTERFACE_DEFINED__ */

DEFINE_GUID(CLSID_DirectMusic,0x636b9f10,0x0c7d,0x11d1,0x95,0xb2,0x00,0x20,0xaf,0xdc,0x74,0x21);
DEFINE_GUID(CLSID_DirectMusicCollection,0x480ff4b0, 0x28b2, 0x11d1, 0xbe, 0xf7, 0x0, 0xc0, 0x4f, 0xbf, 0x8f, 0xef);
DEFINE_GUID(CLSID_DirectMusicSynth,0x58C2B4D0,0x46E7,0x11D1,0x89,0xAC,0x00,0xA0,0xC9,0x05,0x41,0x29);

DEFINE_GUID(IID_IDirectMusic,0x6536115a,0x7b2d,0x11d2,0xba,0x18,0x00,0x00,0xf8,0x75,0xac,0x12);
DEFINE_GUID(IID_IDirectMusicBuffer,0xd2ac2878, 0xb39b, 0x11d1, 0x87, 0x4, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);
DEFINE_GUID(IID_IDirectMusicPort, 0x08f2d8c9,0x37c2,0x11d2,0xb9,0xf9,0x00,0x00,0xf8,0x75,0xac,0x12);
DEFINE_GUID(IID_IDirectMusicThru, 0xced153e7, 0x3606, 0x11d2, 0xb9, 0xf9, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);
DEFINE_GUID(IID_IDirectMusicPortDownload,0xd2ac287a, 0xb39b, 0x11d1, 0x87, 0x4, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);
DEFINE_GUID(IID_IDirectMusicDownload,0xd2ac287b, 0xb39b, 0x11d1, 0x87, 0x4, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);
DEFINE_GUID(IID_IDirectMusicCollection,0xd2ac287c, 0xb39b, 0x11d1, 0x87, 0x4, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);
DEFINE_GUID(IID_IDirectMusicInstrument,0xd2ac287d, 0xb39b, 0x11d1, 0x87, 0x4, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);
DEFINE_GUID(IID_IDirectMusicDownloadedInstrument,0xd2ac287e, 0xb39b, 0x11d1, 0x87, 0x4, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);

/* Alternate interface ID for IID_IDirectMusic, available in DX7 release and after. */
DEFINE_GUID(IID_IDirectMusic2,0x6fc2cae1, 0xbc78, 0x11d2, 0xaf, 0xa6, 0x0, 0xaa, 0x0, 0x24, 0xd8, 0xb6);

DEFINE_GUID(IID_IDirectMusic8,0x2d3629f7,0x813d,0x4939,0x85,0x08,0xf0,0x5c,0x6b,0x75,0xfd,0x97);

#define IID_IDirectMusicThru8 IID_IDirectMusicThru
#define IID_IDirectMusicPortDownload8 IID_IDirectMusicPortDownload
#define IID_IDirectMusicDownload8 IID_IDirectMusicDownload
#define IID_IDirectMusicCollection8 IID_IDirectMusicCollection
#define IID_IDirectMusicInstrument8 IID_IDirectMusicInstrument
#define IID_IDirectMusicDownloadedInstrument8 IID_IDirectMusicDownloadedInstrument
#define IID_IDirectMusicPort8 IID_IDirectMusicPort

/* Property Query GUID_DMUS_PROP_GM_Hardware - Local GM set, no need to download
 * Property Query GUID_DMUS_PROP_GS_Hardware - Local GS set, no need to download
 * Property Query GUID_DMUS_PROP_XG_Hardware - Local XG set, no need to download
 * Property Query GUID_DMUS_PROP_DLS1        - Support DLS level 1
 * Property Query GUID_DMUS_PROP_INSTRUMENT2 - Support new INSTRUMENT2 download format
 * Property Query GUID_DMUS_PROP_XG_Capable  - Support minimum requirements of XG
 * Property Query GUID_DMUS_PROP_GS_Capable  - Support minimum requirements of GS
 * Property Query GUID_DMUS_PROP_SynthSink_DSOUND - Synthsink talks to DSound
 * Property Query GUID_DMUS_PROP_SynthSink_WAVE - Synthsink talks to Wave device
 *
 * Item 0: Supported
 * Returns a DWORD which is non-zero if the feature is supported
 */
DEFINE_GUID(GUID_DMUS_PROP_GM_Hardware, 0x178f2f24, 0xc364, 0x11d1, 0xa7, 0x60, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);
DEFINE_GUID(GUID_DMUS_PROP_GS_Hardware, 0x178f2f25, 0xc364, 0x11d1, 0xa7, 0x60, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);
DEFINE_GUID(GUID_DMUS_PROP_XG_Hardware, 0x178f2f26, 0xc364, 0x11d1, 0xa7, 0x60, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);
DEFINE_GUID(GUID_DMUS_PROP_XG_Capable,  0x6496aba1, 0x61b0, 0x11d2, 0xaf, 0xa6, 0x0, 0xaa, 0x0, 0x24, 0xd8, 0xb6);
DEFINE_GUID(GUID_DMUS_PROP_GS_Capable,  0x6496aba2, 0x61b0, 0x11d2, 0xaf, 0xa6, 0x0, 0xaa, 0x0, 0x24, 0xd8, 0xb6);
DEFINE_GUID(GUID_DMUS_PROP_DLS1,        0x178f2f27, 0xc364, 0x11d1, 0xa7, 0x60, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);
DEFINE_GUID(GUID_DMUS_PROP_DLS2,        0xf14599e5, 0x4689, 0x11d2, 0xaf, 0xa6, 0x0, 0xaa, 0x0, 0x24, 0xd8, 0xb6);
DEFINE_GUID(GUID_DMUS_PROP_INSTRUMENT2, 0x865fd372, 0x9f67, 0x11d2, 0x87, 0x2a, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);
DEFINE_GUID(GUID_DMUS_PROP_SynthSink_DSOUND,0xaa97844, 0xc877, 0x11d1, 0x87, 0xc, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);
DEFINE_GUID(GUID_DMUS_PROP_SynthSink_WAVE,0xaa97845, 0xc877, 0x11d1, 0x87, 0xc, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);
DEFINE_GUID(GUID_DMUS_PROP_SampleMemorySize, 0x178f2f28, 0xc364, 0x11d1, 0xa7, 0x60, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);
DEFINE_GUID(GUID_DMUS_PROP_SamplePlaybackRate, 0x2a91f713, 0xa4bf, 0x11d2, 0xbb, 0xdf, 0x0, 0x60, 0x8, 0x33, 0xdb, 0xd8);

/* Property Get/Set GUID_DMUS_PROP_WriteLatency
 *
 * Item 0: Synth buffer write latency, in milliseconds
 * Get/Set SynthSink latency, the average time after the play head that the next buffer gets written.
 */
DEFINE_GUID(GUID_DMUS_PROP_WriteLatency,0x268a0fa0, 0x60f2, 0x11d2, 0xaf, 0xa6, 0x0, 0xaa, 0x0, 0x24, 0xd8, 0xb6);

/* Property Get/Set GUID_DMUS_PROP_WritePeriod
 *
 * Item 0: Synth buffer write period, in milliseconds
 * Get/Set SynthSink buffer write period, time span between successive writes.
 */
DEFINE_GUID(GUID_DMUS_PROP_WritePeriod,0x268a0fa1, 0x60f2, 0x11d2, 0xaf, 0xa6, 0x0, 0xaa, 0x0, 0x24, 0xd8, 0xb6);

/* Property Get GUID_DMUS_PROP_MemorySize
 *
 * Item 0: Memory size
 * Returns a DWORD containing the total number of bytes of sample RAM
 */
DEFINE_GUID(GUID_DMUS_PROP_MemorySize,  0x178f2f28, 0xc364, 0x11d1, 0xa7, 0x60, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);

/* Property Set GUID_DMUS_PROP_WavesReverb
 *
 * Item 0: DMUS_WAVES_REVERB structure
 * Sets reverb parameters
 */
DEFINE_GUID(GUID_DMUS_PROP_WavesReverb,0x4cb5622, 0x32e5, 0x11d2, 0xaf, 0xa6, 0x0, 0xaa, 0x0, 0x24, 0xd8, 0xb6);

/* Property Set GUID_DMUS_PROP_Effects
 *
 * Item 0: DWORD with effects flags.
 * Get/Set effects bits, same as dwEffectFlags in DMUS_PORTPARAMS and DMUS_PORTCAPS:
 * DMUS_EFFECT_NONE
 * DMUS_EFFECT_REVERB
 * DMUS_EFFECT_CHORUS
 */
DEFINE_GUID(GUID_DMUS_PROP_Effects, 0xcda8d611, 0x684a, 0x11d2, 0x87, 0x1e, 0x0, 0x60, 0x8, 0x93, 0xb1, 0xbd);

/* Property Set GUID_DMUS_PROP_LegacyCaps
 *
 * Item 0: The MIDINCAPS or MIDIOUTCAPS which describes the port's underlying WinMM device. This property is only supported
 * by ports which wrap WinMM devices.
 */

DEFINE_GUID(GUID_DMUS_PROP_LegacyCaps,0xcfa7cdc2, 0x00a1, 0x11d2, 0xaa, 0xd5, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);

/* Property Set GUID_DMUS_PROP_Volume
 *
 * Item 0: A long which contains an offset, in 1/100 dB, to be added to the final volume
 *
 */
DEFINE_GUID(GUID_DMUS_PROP_Volume, 0xfedfae25L, 0xe46e, 0x11d1, 0xaa, 0xce, 0x00, 0x00, 0xf8, 0x75, 0xac, 0x12);

/* Min and Max values for setting volume with GUID_DMUS_PROP_Volume */

#define DMUS_VOLUME_MAX     2000        /* +20 dB */
#define DMUS_VOLUME_MIN   -20000        /* -200 dB */

#ifdef __cplusplus
}; /* extern "C" */
#endif

#include <poppack.h>

#endif /* #ifndef _DMUSICC_ */


text:
package com.manning.hip.ch6;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.*;

public class IdentityJob {

  public static void main(String... args) throws Exception {

    JobConf job = new JobConf();
    job.setJarByClass(IdentityJob.class);
    Path input = new Path(args[0]);
    Path output = new Path(args[1]);

    output.getFileSystem(job).delete(output, true);

    FileInputFormat.setInputPaths(job, input);
    FileOutputFormat.setOutputPath(job, output);

    JobClient.runJob(job);
  }
}

redpajama_set_name: RedPajamaGithub


text:
/** API helpers */

"use strict";

var ARRAY = require('nor-array');
var debug = require('nor-debug');
var URL = require('url');

var helpers = module.exports = {};

/** */
helpers.parse_both_params = function parse_both_params(req, keys) {
	keys = keys || [];
	var url_params = URL.parse(req.url, true).query;
	var params;
	ARRAY(keys).forEach(function(key) {
		if(req.body && req.body[key] !== undefined) {
			if(!params) { params = {}; }
			params[key] = req.body[key];
			return;
		}
		if(url_params && url_params[key] !== undefined) {
			if(!params) { params = {}; }
			params[key] = url_params[key];
			return;
		}
	});
	return params;
};

/** */
helpers.parse_body_params = function parse_body_params(req, keys) {
	debug.assert(req.body).typeOf('object');

	var data = {};
	ARRAY(keys).forEach(function(key) {
		if(req.body[key] !== undefined) {
			data[key] = req.body[key];
		}
	});
	//debug.log("data = ", data);
	return data;
};

/* */
helpers.get_param = function get_param(req, key) {
	debug.assert(req.params).typeOf('object');
	debug.assert(req.params[key]).typeOf('string');
	return req.params[key];
};

/** Returns an object with all items in the array mapped by their property $id */
helpers.map_by_id = function map_by_id(list) {
	debug.assert(list).is('array');
	var map = {};
	ARRAY(list).forEach(function(item) {
		debug.assert(item).is('object');
		debug.assert(item.$id).is('uuid');
		map[item.$id] = item;
	});
	return map;
};

/** Map an array into object by one property */
helpers.map_by_key = function map_by_key(list, key) {
	debug.assert(list).is('array');
	debug.assert(key).is('string');
	var obj = {};
	ARRAY(list).filter(function(i) {
		return i[key] !== undefined;
	}).forEach(function(i) {
		obj[ i[key] ] = i;
	});
	return obj;
};

/* EOF */


text:
import numpy as np
import pandas as pd
import uuid

METHODS = [
    'add', 'sub', 'mul', 'floordiv', 'div', 'truediv', 'mod',
    'divmod', 'pow', 'lshift', 'rshift', 'and', 'or', 'xor'
]

_df = pd.DataFrame()
_se = pd.Series()

PANDAS_DATAFRAME_OBJECTS = [
    attr for attr in dir(_df)
    if not attr.startswith('_')
]

PANDAS_DATAFRAME_ATTRIBUTES = [
    attr for attr in PANDAS_DATAFRAME_OBJECTS
    if not callable(getattr(_df, attr))
]

PANDAS_DATAFRAME_METHODS = [
    attr for attr in PANDAS_DATAFRAME_OBJECTS
    if callable(getattr(_df, attr))
]

PANDAS_SERIES_OBJECTS = [
    attr for attr in dir(_se)
    if not attr.startswith('_')
]

PANDAS_SERIES_ATTRIBUTES = [
    attr for attr in PANDAS_SERIES_OBJECTS
    if not callable(getattr(_se, attr))
]

PANDAS_SERIES_METHODS = [
    attr for attr in PANDAS_SERIES_OBJECTS
    if callable(getattr(_se, attr))
]

def overload_public_attribute(instance, name):
    """
    Overload public attribute of SkDataObject (SkDataFrame or SkDataSeries).

    The overload occurs on __new__ method.
    """

    @property
    def __target__(self, *args, **kwargs):
        """

        """
        return getattr(self.data, name)

    setattr(instance, name, __target__)

def overload_public_method(instance, name):
    """
    Overload public methods of SkDataObject (SkDataFrame or SkDataSeries).

    The overload occurs on __new__ method.
    """

    def __target__(self, *args, **kwargs):
        """

        """
        step_prefix = (
             '' if isinstance(self.data, pd.DataFrame) else
             '%s.' % self.data.name
        )
        step = (
            uuid.uuid4().hex,
            '%s%s(*%s, **%s)' % (step_prefix, name, args, kwargs)
        )
        result = getattr(self.data, name)(*args, **kwargs)

        if 'inplace' not in kwargs or not kwargs['inplace']:
            if isinstance(result, pd.DataFrame):
                _SkDataObject = SkDataFrame
            elif isinstance(result, pd.Series):
                _SkDataObject = SkDataSeries
            else:
                raise Exception('Data Type not supported yet.')

            return _SkDataObject(
                result, list(self.steps) + [step]
            )
        else:
            # inplace
            self.steps.append(step)
            if hasattr(self, 'parent_steps') and self.parent_steps is not None:
                self.parent_steps.append(step)
            return None

    setattr(instance, name, __target__)

def overload_private_method(instance, name, register_step=True):
    """
    Overload private operation methods of SkDataObject
    (SkDataFrame or SkDataSeries).

    The overload occurs on __new__ method.
    """

    def __target__(self, *args, **kwargs):
        """

        """
        # change from SkDataObject to data (DataFrame or Series)
        if args and isinstance(args[0], SkDataObject):
            args = list(args)
            args[0] = args[0].data
            args = tuple(args)

        step_prefix = (
            '' if isinstance(self.data, pd.DataFrame) else
            '%s.' % self.data.name
        )
        step = (
            uuid.uuid4().hex,
            '%s%s(*%s, **%s)' % (step_prefix, name, args, kwargs)
        )
        result = getattr(self.data, name)(*args, **kwargs)

        if not register_step:
            return result

        if isinstance(result, pd.DataFrame):
            _SkDataObject = SkDataFrame
        elif isinstance(result, pd.Series):
            _SkDataObject = SkDataSeries
        else:
            raise Exception('Data Type not supported yet.')

        return _SkDataObject(
            result, list(self.steps) + [step]
        )

    setattr(instance, name, __target__)

def overload_private_imethod(instance, name):
    """
    Overload private inplace operation methods of SkDataObject
    (SkDataFrame or SkDataSeries).

    The overload occurs on __new__ method.
    """

    def __target__(self, *args, **kwargs):
        """

        """
        # change from SkDataObject to data (DataFrame or Series)
        if args and isinstance(args[0], SkDataObject):
            args = list(args)
            args[0] = args[0].data
            args = tuple(args)

        step_prefix = (
            '' if isinstance(self.data, pd.DataFrame) else
            '%s.' % self.data.name
        )
        step = (
            uuid.uuid4().hex,
            '%s%s(*%s, **%s)' % (step_prefix, name, args, kwargs)
        )

        getattr(self.data, name)(*args, **kwargs)
        self.steps.append(step)

        if hasattr(self, 'parent_steps') and self.parent_steps is not None:
            self.parent_steps.append(step)

        return self

    setattr(instance, name, __target__)

class SkDataObject:
    """

    """
    data = None
    steps = []

class SkDataFrame(SkDataObject):
    """

    """
    series = {}

    def __getitem__(self, item):
        """
        Access to series from DataFrame

        :param item:
        :return:
        """
        if item not in self.series:
            self.series[item] = SkDataSeries(
                self.data[item], parent_steps=self.steps
            )
        return self.series[item]

    def __setitem__(self, key, value):
        """
        Set a series to the  DataFrame

        :param key:
        :param value:
        :return:
        """
        if key not in self.series:
            self.series[key] = SkDataSeries(
                self.data[key], parent_steps=self.steps
            )

        if not isinstance(value, SkDataSeries):
            self.data[key] = value
            series = SkDataSeries(self.data[key], parent_steps=self.steps)
        else:
            series = value
            series.parent_steps = self.steps

            # insert steps from series when needed
            for step_series in series.steps:
                insert_step = True
                for step_df in self.steps:
                    if step_series[0] == step_df[0]:
                        insert_step = False
                        break
                if insert_step:
                    step_series = (
                        step_series[0],
                        '%s = %s' % (key, step_series[1])
                    )
                    self.steps.append(step_series)

        self.series[key] = series

    def __new__(cls, *args, **kwargs):
        """

        """
        overload_public_attribute(cls, 'values')
        overload_private_method(cls, '__repr__', register_step=False)
        overload_private_method(cls, '_repr_html_', register_step=False)

        for method in METHODS:
            overload_private_method(cls, '__%s__' % method)
            overload_private_method(cls, '__r%s__' % method)
            overload_private_imethod(cls, '__i%s__' % method)

        for method in PANDAS_DATAFRAME_METHODS:
            overload_public_method(cls, method)

        return super(SkDataFrame, cls).__new__(cls)

    def __init__(self, *args, **kwargs):
        if args and isinstance(args[0], pd.DataFrame):
            self.data = args[0]
            if len(args) > 1:
                self.steps = list(args[1])
        else:
            self.data = pd.DataFrame(*args, **kwargs)

    def summary(self):
        return summary(self.data)

class SkDataSeries(SkDataObject):
    """

    """
    parent_steps = None

    def __new__(cls, *args, **kwargs):
        """

        """
        overload_public_attribute(cls, 'values')
        overload_private_method(cls, '__repr__', register_step=False)
        # overload_private_method(cls, '_repr_html_', register_step=False)

        for method in METHODS:
            overload_private_method(cls, '__%s__' % method)
            overload_private_method(cls, '__r%s__' % method)
            overload_private_imethod(cls, '__i%s__' % method)

        for method in PANDAS_DATAFRAME_METHODS:
            overload_public_method(cls, method)

        return super(SkDataSeries, cls).__new__(cls)

    def __init__(self, *args, **kwargs):
        # internal parameter
        if 'parent_steps' in kwargs:
            self.parent_steps = kwargs.pop('parent_steps')

        if args and isinstance(args[0], pd.Series):
            self.data = args[0]
            if len(args) > 1:
                self.steps = list(args[1])
            else:
                self.steps = []
        else:
            self.data = pd.Series(*args, **kwargs)

def summary(data: pd.DataFrame) -> pd.DataFrame:
    """

    :param data:
    :return:
    """
    # types
    df = pd.DataFrame(data.dtypes).rename(columns={0: 'Types'})

    # set
    df = pd.merge(
        df, pd.DataFrame(
            data.apply(lambda se: str(sorted(set(se.dropna())))[:1000])
        ).rename(columns={0: 'Set Values'}),
        left_index=True, right_index=True
    )

    # count set
    df = pd.merge(
        df, pd.DataFrame(
            data.apply(lambda se: se.dropna().unique().shape[0])
        ).rename(columns={0: 'Count Set'}),
        left_index=True, right_index=True
    )

    # total observations
    df = pd.merge(
        df, pd.DataFrame(
            data.count()
        ).rename(columns={0: '# Observations'}),
        left_index=True, right_index=True
    )

    # total of nan
    df = pd.merge(
        df, pd.DataFrame(data.isnull().sum()).rename(columns={0: '# NaN'}),
        left_index=True, right_index=True
    )
    return df

def cross_fields(
    data: pd.DataFrame,
    y: str,
    xs: [str],
    bins: int
) -> pd.DataFrame:
    """

    :param data:
    :param y:
    :param xs:
    :param bins:
    :return:
    """
    if not (xs and y):
        return data

    d = data[list(xs)+[y]].copy()
    for x in list(xs)+[y]:
        try:
            # if the data is not a number type() will raise an exception
            if isinstance(data[x].dtype.type(), np.number):
                d[x], _ = pd.cut(data[x].copy(), bins=bins, retbins=True)
        except:
            pass

    return pd.crosstab([d[f] for f in xs], d[y])


text:
import entity.Chunk;
import entity.FileChunkInfo;
import entity.Peer;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by ankur on 18.06.2016.
 */
public class TorrentParserTest {
    public static void main(String [] args){
        TorrentParser torrentParser = new TorrentParser("D:\\torrents\\a.mp3.torrent");
        List<Chunk> chunks = new LinkedList<Chunk>();
        List<Peer> peers = new LinkedList<Peer>();
        try {
            FileChunkInfo f = torrentParser.fileParser();
            System.out.println(f.FileName);
            System.out.println(f.size);
            System.out.println(f.chunkCount);
            System.out.println(f.chunkSize);
            chunks = f.chunkInfo;
            for(int i=0;i<chunks.size();i++){
                System.out.print(chunks.get(i).offset + " ");
                System.out.print(chunks.get(i).length + " ");
                System.out.print(chunks.get(i).isDownloaded + " ");
                peers = chunks.get(i).peerList;
                for(int j = 0; j<peers.size();j++){
                    System.out.print(peers.get(j).address + " ");
                    System.out.print(peers.get(j).port + " ");

                }
            System.out.println();

            }

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <title>Projects</title>

  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="shortcut icon" href="img/projects.png"/>

directions_boat

About

Projects

Github

Navbar Link

Projects

          Glow Cloud

 Github

          The Glow Cloud

An infinite, omniprescent, sentient, and perfect cloud storage provider.  ALL HAIL.

          Blue Sun Computer Co.

             Github

          Blue Sun Computer Co.

A computer company that does not exist, yet expects to upset the industry by being perfect and awesome.

          Spanish II Third Quarter Project

 Github

          Timeline of my life

A completely fake, very pretty timeline of my life, on the Web, that I made for my Spanish II class.  Hopefully less confusing than the one in the picture.

          Browser Shamer

 Github

	  &copyIan Smithh. All rights reserved.
      Made with Materialize.


text:
@interface ViewController : QMBParallaxScrollViewController<QMBParallaxScrollViewControllerDelegate>

@end


text:
feature-matching
================
1. SIFT interest points and Harris corner detection
2. feature matching

Author: Yu Wang


text:
{% extends "base_run.html" %}

{% block title %}Détails de la sortie{% end %}
{% block title_h1 %}Détails de la sortie{% end %}

{% block subcontent %}
{% set latitude=corresponding_ids['latitude'] %}
{% set longitude=corresponding_ids['longitude'] %}
{% set altitude=corresponding_ids['altitude'] %}
{% set time=corresponding_ids['time'] %}
{% set datetime=corresponding_ids['datetime'] %}
{% set distance=corresponding_ids['distance'] %}

    {% if previous_run %}

{{ previous_run[1] }}

    {% else %}

←

    {% end %}
    {% if next_run %}

{{ next_run[1] }}

    {% else %}

→

    {% end %}

        Marqueurs kilométriques (pas 0,5km) :
        <input type="text" id="amount_markers_num_km" readonly style="border:0; color:#f6931f; font-weight:bold;" />

Départ

{{ details['start'] }}

Temps

{{ details['time'] }}

Distance

{{ details['distance'] }}

Calories brûlées

{{ details['calories'] }}

Vitesse moyenne

{{ details['speed'] }}

          {% for hs in high_scores %}
            {% set hs_id = hs["id"] %}

              {% if hs_id == 1 %}Cooper (12min)
                  {% elif hs_id == 2 %}Course d'une heure
                  {% elif hs_id == 6 %}Semi-marathon
                  {% elif hs_id == 7 %}Marathon
                  {% elif hs["is_distance"] %}{{ hs["value"]/1000 }} km
                  {% else %}{{ hs["value"]/60 }} minutes{% end %}
              {{ hs["score"] }}

          {% end %}

    <canvas id="perfchart" width="500" height="75" style="margin-top: 10px;"></canvas>

{% end %}


text:
<?php
$key = "Tool Panel";
$pageTitle = "AngularJS Angular Grid Tool Panel";
$pageDescription = "The tool panel allows you to work with the columns at run time, but showing and hiding, and grouping.";
$pageKeyboards = "AngularJS Angular Grid Show Hide Column Tool Panel";
include '../documentation_header.php';
?>

Tool Panel

        The tool panel is where you can change the state of the columns. This includes show / hide, move and group.

        The tool panel panel can be shown be default by setting 'showToolPanel=showToolPanel' in the gridOptions,
        or after the grid is initialised by calling the api function showToolPanel(show). You can query if
        the tool panel is showing with the api isToolPanelShowing().

Show & Hide Columns

        All columns are visible by default. To hide a column when first displaying the grid, mark
        the column definition with hide = true.

        To hide a column using the tool panel, click the icon beside teh columns name.

        To group by a column, drag the column down to the pivit GUI.

        To reorder the groups (either the displayed groups, or the pivoted groups),
        drag the column to a new location in the list.

        To show and hide columns via the API, use the methods:

hideColumn(colId, hide): To show / hide a specific column, where colId = the id of the
            column you want to show / hide and hide = true to hide, false to show.

hideColumns(colIds, hide): Same as above, but you pass a list of column id's in.

    <show-example example="toolPanelExample"></show-example>

<?php include '../documentation_footer.php';?>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace ConsoleApplication8
{

    class Program
    {
        static void Main()
        {
            Regex validation = new Regex(@"(\d+)([a-zA-Z]+)([^a-zA-Z\s]+)?");
            Dictionary<string,string> decripted = new Dictionary<string, string>();
            while (true)
            {
                //validation
                var line = Console.ReadLine();
                if (line == "Over!")
                {
                    break;
                }
                var match = validation.Match(line);
                if (!match.Success || match.Value.Length != line.Length)
                {
                    continue;
                }
                var m = int.Parse(Console.ReadLine());
                if (m != match.Groups[2].Value.Length)
                {
                    continue;
                }

                //decrypting
                Regex nums = new Regex(@"\d");
                var fPattern = match.Groups[1].Value;
                var sPattern = match.Groups[3].Value;
                var dMatches = nums.Matches(sPattern);
                sPattern = string.Empty;
                foreach (Match item in dMatches)
                {
                    sPattern += item.Value;
                }
                var text = match.Groups[2].Value;
                StringBuilder decryptedText = new StringBuilder();
                foreach (var index in fPattern)
                {
                    var i = index - '0';
                    if (i<0 || i>=text.Length)
                    {
                        decryptedText.Append(" ");
                    }
                    else
                    {
                        decryptedText.Append(text[i]);
                    }
                }
                if (sPattern.Length !=0)
                {
                    foreach (var index in sPattern)
                    {
                        var i = index - '0';
                        if (i < 0 || i >= text.Length)
                        {
                            decryptedText.Append(" ");
                        }
                        else
                        {
                            decryptedText.Append(text[i]);
                        }
                    }
                }

                decripted.Add(text, decryptedText.ToString());

            }
            foreach (var item in decripted)
            {
                Console.WriteLine($"{item.Key} == {item.Value}");
            }
        }
    }
}


text:
<?php
/**
 * Looks up a set of coordinates and return normalized data such as
 * location name, country and local timezone.
 *
 * @author Martin Lindhe, 2010-2014 <martin@ubique.se>
 */

//STATUS: wip

namespace cd;

require_once('GeonamesClient.php');
require_once('GoogleMapsGeocode.php');
require_once('TempStore.php');

class GeoLookupResult  //XXX FIXME merge with GeoCodeResult from GoogleMapsClient
{
    var $description;   ///< description of the location
    var $country_code;  ///< 2 letter code, such as "SE"
    var $country_name;
    var $timezone;
    var $sunrise;
    var $sunset;

    var $accuracy; ///< numeric 0-9 where 9 is best accuracy
}

class GeoLookupClient  //XXXX rename class to something like ReverseLookupClient, CoordinateLookupClient ?
{
    public static function get($latitude, $longitude)
    {
/*
        $temp = TempStore::getInstance();
        $key = 'GeoLookupClient//'.$latitude.'/'.$longitude;

        $data = $temp->get($key);
        if ($data)
            return unserialize($data);
*/
        $geonames = GeonamesClient::reverse($latitude, $longitude);

        // $google = GoogleMapsClient::reverse($latitude, $longitude);

        // return a combination of data from both sources because neither returns all we want alone
        $res = new GeoLookupResult();
        // $res->description  = $google->description;
        // $res->accuracy     = $google->accuracy;
        $res->country_code = $geonames->country_code;
        $res->country_name = $geonames->country_name;
        $res->timezone     = $geonames->timezone;
        $res->sunrise      = $geonames->sunrise;
        $res->sunset       = $geonames->sunset;

//        $temp->set($key, serialize($res), '1h');

        return $res;
    }
}


text:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:fragment="common-header">
    <title>fullStack</title>

    <!-- Bootstrap core CSS -->
    <link th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}" rel="stylesheet" media="screen"/>

    <!-- Custom styles template -->
    <link th:href="@{/css/styles.css}" rel="stylesheet" media="screen"/>
</head>
    <div th:fragment="before-body-scripts">
        <!-- Placed at the end of the document so the pages load faster -->
        <script th:src="@{webjars/jquery/3.2.1/jquery.min.js}"></script>
        <script th:src="@{webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script>
        <script th:src="@{/js/fullstack.js}"></script>
    </div>
</html>


text:
public class D
{
    object AutoProp { get; set; }

    object trivialPropField;
    object TrivialProp
    {
        get { return this.trivialPropField; }
        set { this.trivialPropField = value; }
    }

    object ComplexProp
    {
        get { return this.trivialPropField; }
        set { this.TrivialProp = value; }
    }

    static D Create(object o1, object o2, object o3)
    {
        var ret = new D();
        ret.AutoProp = o1;
        ret.TrivialProp = o2;
        ret.ComplexProp = o3;
        return ret;
    }

    private void M()
    {
        var o = Source<object>(1);

        var d = Create(o, null, null);
        Sink(d.AutoProp); // $ hasValueFlow=1
        Sink(d.TrivialProp); // no flow
        Sink(d.trivialPropField); // no flow
        Sink(d.ComplexProp); // no flow

        d = Create(null, Source<object>(2), null);
        Sink(d.AutoProp); // no flow
        Sink(d.TrivialProp); // $ hasValueFlow=2
        Sink(d.trivialPropField); // $ hasValueFlow=2
        Sink(d.ComplexProp); // $ hasValueFlow=2

        d = Create(null, null, Source<object>(3));
        Sink(d.AutoProp); // no flow
        Sink(d.TrivialProp); // $ hasValueFlow=3
        Sink(d.trivialPropField); // $ hasValueFlow=3
        Sink(d.ComplexProp); // $ hasValueFlow=3
    }

    public static void Sink(object o) { }

    static T Source<T>(object source) => throw null;
}


text:
'''
This module defines :class:`ChannelIndex`, a container for multiple
data channels.

:class:`ChannelIndex` derives from :class:`Container`,
from :module:`neo.core.container`.
'''

# needed for Python 3 compatibility
from __future__ import absolute_import, division, print_function

import numpy as np
import quantities as pq

from neo.core.container import Container

class ChannelIndex(Container):
    '''
    A container for indexing/grouping data channels.

    This container has several purposes:

      * Grouping all :class:`AnalogSignal`\s inside a :class:`Block`
        across :class:`Segment`\s;
      * Indexing a subset of the channels within an :class:`AnalogSignal`;
      * Container of :class:`Unit`\s. A neuron discharge (:class:`Unit`)
        can be seen by several electrodes (e.g. 4 for tetrodes).

    *Usage 1* multi :class:`Segment` recording with 2 electrode arrays::

        >>> from neo.core import (Block, Segment, ChannelIndex,
        ...                       AnalogSignal)
        >>> from quantities import nA, kHz
        >>> import numpy as np
        >>>
        >>> # create a Block with 3 Segment and 2 ChannelIndex objects
        ... blk = Block()
        >>> for ind in range(3):
        ...     seg = Segment(name='segment %d' % ind, index=ind)
        ...     blk.segments.append(seg)
        ...
        >>> for ind in range(2):
        ...     chx = ChannelIndex(name='Array probe %d' % ind,
        ...                        index=np.arange(64))
        ...     blk.channel_indexes.append(chx)
        ...
        >>> # Populate the Block with AnalogSignal objects
        ... for seg in blk.segments:
        ...     for chx in blk.channel_indexes:
        ...         a = AnalogSignal(np.random.randn(10000, 64)*nA,
        ...                          sampling_rate=10*kHz)
        ...         chx.analogsignals.append(a)
        ...         seg.analogsignals.append(a)

    *Usage 2* grouping channels::

        >>> from neo.core import Block, ChannelIndex
        >>> import numpy as np
        >>>
        >>> # Create a Block
        ... blk = Block()
        >>> blk.segments.append(Segment())
        >>>
        >>> # Create a signal with 8 channels
        ... sig = AnalogSignal(np.random.randn(1000, 8)*mV, sampling_rate=10*kHz)
        ... blk.segments[0].append(sig)
        ...
        >>> # Create a new ChannelIndex which groups three channels from the signal
        ... chx = ChannelIndex(channel_names=np.array(['ch1', 'ch4', 'ch6']),
        ...                    channel_indexes = np.array([0, 3, 5])
        >>> chx.analogsignals.append(sig)
        >>> blk.channel_indexes.append(chx)

    *Usage 3* dealing with :class:`Unit` objects::

        >>> from neo.core import Block, ChannelIndex, Unit
        >>>
        >>> # Create a Block
        >>> blk = Block()
        >>>
        >>> # Create a new ChannelIndex and add it to the Block
        >>> chx = ChannelIndex(name='octotrode A')
        >>> blk.channel_indexes.append(chx)
        >>>
        >>> # create several Unit objects and add them to the
        >>> # ChannelIndex
        ... for ind in range(5):
        ...     unit = Unit(name = 'unit %d' % ind,
        ...                 description='after a long and hard spike sorting')
        ...     chx.units.append(unit)

    *Required attributes/properties*:
        :channel_indexes: (numpy.array 1D dtype='i')
            Index of each channel in the attached signals.

    *Recommended attributes/properties*:
        :name: (str) A label for the dataset.
        :description: (str) Text description.
        :file_origin: (str) Filesystem path or URL of the original data file.
        :channel_names: (numpy.array 1D dtype='S')
            Names for each recording channel.
        :coordinates: (quantity array 2D (x, y, z))
            Physical or logical coordinates of all channels.

    Note: Any other additional arguments are assumed to be user-specific
    metadata and stored in :attr:`annotations`.

    *Container of*:
        :class:`AnalogSignal`
        :class:`IrregularlySampledSignal`
        :class:`Unit`

    '''

    _container_child_objects = ('Unit',)
    _data_child_objects = ('AnalogSignal', 'IrregularlySampledSignal')
    _single_parent_objects = ('Block',)
    _necessary_attrs = (('index', np.ndarray, 1, np.dtype('i')),)
    _recommended_attrs = ((('channel_names', np.ndarray, 1, np.dtype('S')),
                           ('channel_ids', np.ndarray, 1, np.dtype('i')),
                           ('coordinates', pq.Quantity, 2)) +
                          Container._recommended_attrs)

    def __init__(self, index, channel_names=None, channel_ids=None,
                 name=None, description=None, file_origin=None,
                 coordinates=None, **annotations):
        '''
        Initialize a new :class:`ChannelIndex` instance.
        '''
        # Inherited initialization
        # Sets universally recommended attributes, and places all others
        # in annotations
        super(ChannelIndex, self).__init__(name=name,
                                           description=description,
                                           file_origin=file_origin,
                                           **annotations)

        # Defaults
        if channel_names is None:
            channel_names = np.array([], dtype='S')
        if channel_ids is None:
            channel_ids = np.array([], dtype='i')

        # Store recommended attributes
        self.channel_names = channel_names
        self.channel_ids = channel_ids
        self.index = index
        self.coordinates = coordinates


text:
package water;

// Helper to fetch class IDs from class Strings from the leader
public class FetchId extends DTask<FetchId> {
  final String _clazz;
  int _id;
  private FetchId(String s) { _clazz=s; }
  static public int fetchId(String s) { return RPC.call(H2O.CLOUD.leader(), new FetchId(s)).get()._id; }
  @Override public void compute2() { _id = TypeMap.onIce(_clazz); tryComplete(); }
  @Override public byte priority() { return H2O.ACK_ACK_PRIORITY; }
}


text:
#include "nullDeviceHelper.h"
#include "testUtils.h"

#include <boost/make_shared.hpp>
#include <folly/executors/ManualExecutor.h>
#include <gtest/gtest.h>

#include <tuple>

#include <boost/algorithm/string.hpp>
#include <folly/String.h>

using namespace ::testing;
using namespace one;
using namespace one::helpers;
using namespace one::testing;

struct NullDeviceHelperTest : public ::testing::Test {
    NullDeviceHelperTest() { }

    ~NullDeviceHelperTest() { }

    void SetUp() override { }

    void TearDown() override { }

    std::shared_ptr<folly::ManualExecutor> m_executor =
        std::make_shared<folly::ManualExecutor>();
};

TEST_F(NullDeviceHelperTest, nullDeviceHelperFactoryShouldParseStringParams)
{
    NullDeviceHelperFactory factory{
        std::make_shared<folly::IOThreadPoolExecutor>(
            1, std::make_shared<StorageWorkerFactory>("null_t"))};

    Params empty;

    auto defaultNullHelper =
        factory.createStorageHelper(empty, ExecutionContext::ONECLIENT);

    Params p1;
    p1.emplace("type", "nulldevice");
    p1.emplace("name", "someNullDevice");
    p1.emplace("latencyMin", "0");
    p1.emplace("latencyMax", "0");
    p1.emplace("timeoutProbability", "0.0");
    p1.emplace("filter", "*");
    p1.emplace("simulatedFilesystemParameters", "");
    p1.emplace("simulatedFilesystemGrowSpeed", "0.0");

    auto nullHelper1 =
        factory.createStorageHelper(p1, ExecutionContext::ONECLIENT);
}

TEST_F(NullDeviceHelperTest, timeoutWithZeroProbabilityShouldAlwaysBeFalse)
{
    NullDeviceHelper helper(0, 0, 0.0, "*", {}, 0.0, 1024,
        std::make_shared<folly::ManualExecutor>());

    for (int i = 0; i < 1000; i++)
        EXPECT_FALSE(helper.randomTimeout());
}

TEST_F(NullDeviceHelperTest, timeoutWithOneProbabilityShouldAlwaysBeTrue)
{
    NullDeviceHelper helper(0, 0, 1.0, "*", {}, 0.0, 1024,
        std::make_shared<folly::ManualExecutor>());

    for (int i = 0; i < 1000; i++)
        EXPECT_TRUE(helper.randomTimeout());
}

TEST_F(NullDeviceHelperTest, latencyShouldBeAlwaysInDefinedRange)
{
    NullDeviceHelper helper(250, 750, 1.0, "*", {}, 0.0, 1024,
        std::make_shared<folly::ManualExecutor>());

    for (int i = 0; i < 1000; i++) {
        auto latency = helper.randomLatency();
        EXPECT_TRUE(latency > 100);
        EXPECT_TRUE(latency < 1000);
    }
}

TEST_F(NullDeviceHelperTest, latencyWithZeroRangeShouldBeAlwaysReturnZero)
{
    NullDeviceHelper helper(0, 0, 1.0, "*", {}, 0.0, 1024,
        std::make_shared<folly::ManualExecutor>());

    for (int i = 0; i < 1000; i++)
        EXPECT_EQ(helper.randomLatency(), 0);
}

TEST_F(NullDeviceHelperTest, emptyFilterShouldAllowAnyOperation)
{
    NullDeviceHelper helper(100, 1000, 1.0, "", {}, 0.0, 1024,
        std::make_shared<folly::ManualExecutor>());

    EXPECT_TRUE(helper.applies("whatever"));
}

TEST_F(NullDeviceHelperTest, wildcardFilterShouldAllowAnyOperation)
{
    NullDeviceHelper helper(100, 1000, 1.0, "*", {}, 0.0, 1024,
        std::make_shared<folly::ManualExecutor>());

    EXPECT_TRUE(helper.applies("whatever"));
}

TEST_F(NullDeviceHelperTest, singleWordFileterShouldAllowOnlyOneOperations)
{
    NullDeviceHelper helper(100, 1000, 1.0, "truncate", {}, 0.0, 1024,
        std::make_shared<folly::ManualExecutor>());

    EXPECT_FALSE(helper.applies("whatever"));
    EXPECT_FALSE(helper.applies(""));
    EXPECT_TRUE(helper.applies("truncate"));
}

TEST_F(NullDeviceHelperTest, multipleOpsShouldAllowOnlyTheseOperations)
{
    NullDeviceHelper helper(100, 1000, 1.0, "truncate,read,write", {}, 0.0,
        1024, std::make_shared<folly::ManualExecutor>());

    EXPECT_FALSE(helper.applies("whatever"));
    EXPECT_FALSE(helper.applies(""));
    EXPECT_TRUE(helper.applies("truncate"));
    EXPECT_TRUE(helper.applies("read"));
    EXPECT_TRUE(helper.applies("write"));
}

TEST_F(
    NullDeviceHelperTest, multipleOpsWithSpacesShouldAllowOnlyTheseOperations)
{
    NullDeviceHelper helper(100, 1000, 1.0,
        "\t\t\ntruncate,\nread,\n   write  ", {}, 0.0, 1024,
        std::make_shared<folly::ManualExecutor>());

    EXPECT_FALSE(helper.applies("whatever"));
    EXPECT_FALSE(helper.applies(""));
    EXPECT_TRUE(helper.applies("truncate"));
    EXPECT_TRUE(helper.applies("read"));
    EXPECT_TRUE(helper.applies("write"));
}

TEST_F(NullDeviceHelperTest, readReturnsRequestedNumberOfBytes)
{
    auto helper = std::make_shared<NullDeviceHelper>(0, 0, 0.0, "*",
        std::vector<std::pair<long int, long int>>{}, 0.0, 1024, m_executor);

    auto handle = helper->open("whatever", O_RDWR, {}).getVia(m_executor.get());

    EXPECT_EQ(
        handle->read(1000, 100).getVia(m_executor.get()).chainLength(), 100);
}

TEST_F(NullDeviceHelperTest, writeReturnsWrittenNumberOfBytes)
{
    auto helper = std::make_shared<NullDeviceHelper>(0, 0, 0.0, "*",
        std::vector<std::pair<long int, long int>>{}, 0.0, 1024, m_executor);

    auto handle = helper->open("whatever", O_RDWR, {}).getVia(m_executor.get());

    std::size_t size = 10 * 1024 * 1024;
    std::string stmp(size, 'y');
    std::string tmp;

    folly::IOBufQueue writeBuf{folly::IOBufQueue::cacheChainLength()};
    writeBuf.append(stmp);

    auto bytesWritten =
        handle->write(0, std::move(writeBuf), {}).getVia(m_executor.get());

    EXPECT_EQ(bytesWritten, size);
}

TEST_F(NullDeviceHelperTest, readTimesAreInLatencyBoundaries)
{
    auto helper = std::make_shared<NullDeviceHelper>(25, 75, 0.0, "*",
        std::vector<std::pair<long int, long int>>{}, 0.0, 1024, m_executor);

    auto handle = helper->open("whatever", O_RDWR, {}).getVia(m_executor.get());

    for (int i = 0; i < 50; i++) {
        auto start = std::chrono::steady_clock::now();

        handle->read(1000, 100).getVia(m_executor.get());

        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::steady_clock::now() - start);

        EXPECT_TRUE(duration.count() >= 25);
        EXPECT_TRUE(duration.count() <= 75 + 10);
    }
}

TEST_F(NullDeviceHelperTest,
    nullHelperFactoryShouldParseSimulatedFilesystemParameters)
{
    auto empty = "";

    auto simulatedFilesystemParams =
        NullDeviceHelperFactory::parseSimulatedFilesystemParameters(empty);
    EXPECT_TRUE(std::get<0>(simulatedFilesystemParams).empty());
    EXPECT_FALSE(std::get<1>(simulatedFilesystemParams));

    auto oneLevelStr = "10-0";
    auto oneLevel =
        std::vector<std::pair<long int, long int>>{std::make_pair(10, 0)};
    auto oneLevelResult =
        std::get<0>(NullDeviceHelperFactory::parseSimulatedFilesystemParameters(
            oneLevelStr));

    EXPECT_EQ(std::get<0>(oneLevel[0]), 10);
    EXPECT_EQ(std::get<1>(oneLevel[0]), 0);

    auto twoLevelsStr = "10-5:1-20";
    auto twoLevels = std::vector<std::pair<long int, long int>>{
        std::make_pair(10, 5), std::make_pair(1, 20)};
    auto twoLevelsResult =
        std::get<0>(NullDeviceHelperFactory::parseSimulatedFilesystemParameters(
            twoLevelsStr));

    EXPECT_EQ(std::get<0>(twoLevels[0]), 10);
    EXPECT_EQ(std::get<1>(twoLevels[0]), 5);
    EXPECT_EQ(std::get<0>(twoLevels[1]), 1);
    EXPECT_EQ(std::get<1>(twoLevels[1]), 20);

    auto invalidFormat = "10:1-20";
    EXPECT_THROW(NullDeviceHelperFactory::parseSimulatedFilesystemParameters(
                     invalidFormat),
        std::invalid_argument);

    auto invalidNumbers = "a10-1";
    EXPECT_THROW(NullDeviceHelperFactory::parseSimulatedFilesystemParameters(
                     invalidNumbers),
        std::invalid_argument);
}

TEST_F(NullDeviceHelperTest, simulatedFilesystemEntryCountShouldWork)
{
    auto simulatedFilesystemParamsStr = "2-2:2-2:0-3";
    auto simulatedFilesystemParams =
        NullDeviceHelperFactory::parseSimulatedFilesystemParameters(
            simulatedFilesystemParamsStr);

    NullDeviceHelper helper(0, 0, 0.0, "*",
        std::get<0>(simulatedFilesystemParams), 0.0,
        std::get<1>(simulatedFilesystemParams).value_or(1024),
        std::make_shared<folly::ManualExecutor>());

    EXPECT_EQ(helper.simulatedFilesystemLevelEntryCount(0), 2 + 2);
    EXPECT_EQ(helper.simulatedFilesystemLevelEntryCount(1), 2 * (2 + 2));
    EXPECT_EQ(helper.simulatedFilesystemLevelEntryCount(2), 2 * 2 * (0 + 3));

    EXPECT_EQ(helper.simulatedFilesystemEntryCount(), 4 + 8 + 12);
}

TEST_F(NullDeviceHelperTest, simulatedFilesystemFileDistShouldWork)
{
    auto simulatedFilesystemParamsStr = "10-20:10-20:8-1:0-100:1000000000";
    auto simulatedFilesystemParams =
        NullDeviceHelperFactory::parseSimulatedFilesystemParameters(
            simulatedFilesystemParamsStr);

    NullDeviceHelper helper(0, 0, 0.0, "*",
        std::get<0>(simulatedFilesystemParams), 0.0,
        std::get<1>(simulatedFilesystemParams).value_or(1024),
        std::make_shared<folly::ManualExecutor>());

    EXPECT_EQ(helper.simulatedFilesystemFileDist({"1"}), 1);
    EXPECT_EQ(helper.simulatedFilesystemFileDist({"25"}), 25);
    EXPECT_EQ(helper.simulatedFilesystemFileDist({"1", "1"}), 31);
    EXPECT_EQ(helper.simulatedFileSize(), 1'000'000'000);
}


text:
describe 'Matcher::Change' do
  class TestClass
    attr_reader :counter
    def initialize
      @counter = 0
    end

    def add
      @counter += 1
    end

    def dont_add; end
  end

  before { @test_object = TestClass.new }

  context 'when the expected block changes the argument block' do
    it 'passes' do
      expect { @test_object.add }.to change { @test_object.counter }
    end
  end

  context "when the expected block doesn't change the argument block" do
    it 'fails' do
      expect_failure('Block expected to change value') do
        expect { @test_object.dont_add }.to change { @test_object.counter }
      end
    end

    it 'passes when asked not_to' do
      expect { @test_object.dont_add }.not_to change { @test_object.counter }
    end
  end

  context "when specified 'by'" do
    it 'passes when changes are by the given amount' do
      expect do
        @test_object.add
        @test_object.add
      end.to change { @test_object.counter }.by(2)
    end

    it 'fails when changes are by a different amount' do
      expect_failure('Block expected to change value by 6 but changed by 2') do
        expect do
          @test_object.add
          @test_object.add
        end.to change { @test_object.counter }.by(6)
      end
    end

    it 'fails when changes are by the given amount but asked not to' do
      expect_failure('Block not expected to change value by 2') do
        expect do
          @test_object.add
          @test_object.add
        end.not_to change { @test_object.counter }.by(2)
      end
    end
  end
end


text:
import React from 'react';
import { Flex, Box } from 'rebass';
import img from '~/resources/images/agent-registration-details.png';

export default () => (
    <Flex>
        <Box><img src={img}/></Box>
    </Flex>
)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Installation — OpenVD  documentation</title>
    <link rel="stylesheet" href="_static/cloud.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noticia+Text|Open+Sans|Droid+Sans+Mono" type="text/css" />

    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="Overview" href="overview.html" />
    <link rel="prev" title="OpenVD: Open Vehicle Dynamics" href="index.html" />
        <meta name="viewport" content="width=device-width, initial-scale=1">

Navigation

          index

          modules

          next

          previous

OpenVD  documentation »

Installation¶

Octave users¶

Download the OpenVD package by clicking here.

Save the zip file in your package path.

Open Octave, go to your package path and run (For more details see pkg function.):

pkg install openvd-master.zip

Load the OpenVD package with:

pkg load openvd

To check the installation, change the current path with:

cd openvd-0.0.0/docs/examples/TemplateSimple/

and run the Template Simple example with:

TemplateSimple

Matlab users¶

Download the OpenVD package by clicking here.

Unzip the openvd-master.zip file in your current directory.

Open Matlab and add the inst directory to the paths list with (For more details see help path.):

addpath('openvd-master/inst')

To check the installation, change the current path with:

cd openvd-master/docs/examples/TemplateSimple/

and run the Template Simple example with:

TemplateSimple

Dependencies¶

To run the functions of the package Octave > 4.0 or Matlab > v8.5 is required.

Page contents

Installation

Octave users

Matlab users

Dependencies

Previous page

← OpenVD: Open Vehicle Dynamics

Next page

→ Overview

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">

<input type="text" name="q" />

<input type="submit" value="Go" />

      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

            <button class="sidebar-toggle" id="sidebar-hide" title="Hide the sidebar menu">
                 «
                hide menu

            </button>
            <button class="sidebar-toggle" id="sidebar-show" title="Show the sidebar menu">

                menu
                sidebar
                 »
            </button>

Navigation

          index

          modules

          next

          previous

OpenVD  documentation »

        © Copyright 2017, BSD 3-clause.
      Created using Sphinx 1.6.4.


text:
import VMBuilder.plugins

class Frontend(VMBuilder.plugins.Plugin):
    def __init__(self):
        self._setting_groups = []
        self._config = {}
        self.context = self

#        self.settings = []

#    def setting_group(self, help=None):
#        return self.SettingsGroup(help)
#
#    def add_setting_group(self, group):
#        self.settings.append(group)
#
#    def add_setting(self, **kwargs):
#        self.settings.append(Setting(**kwargs))
#
#    setting_types =  ['store', 'store']
#    class Setting(object):
#        def __init__(self, **kwargs):
#            self.shortarg = kwargs.get('shortarg', None)
#            self.longarg = kwargs.get('shortarg', None)
#            self.default = kwargs.get('default', None)
#            self.help = kwargs.get('help', None)
#            type = kwargs.get('type', 'store')
#            if type not in setting_types:
#                raise VMBuilderException("Invalid option type: %s" % type)
#
#    class SettingsGroup(Setting):
#        pass


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.github.dynamicextensionsalfresco</groupId>
    <artifactId>annotations-runtime</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>Dynamic Extensions Alfresco Annotations-Runtime</name>
    <packaging>amp</packaging>

    <parent>
        <groupId>com.github.dynamicextensionsalfresco</groupId>
        <artifactId>dynamic-extensions-alfresco</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <dependencies>
        <dependency>
            <groupId>${alfresco.groupId}</groupId>
            <artifactId>alfresco-repository</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.dynamicextensionsalfresco</groupId>
            <artifactId>annotations</artifactId>
            <version>${com.github.dynamicextensionsalfresco.version}</version>
            <type>amp</type>
        </dependency>
        <dependency>
            <groupId>com.github.dynamicextensionsalfresco</groupId>
            <artifactId>webscripts</artifactId>
            <version>${com.github.dynamicextensionsalfresco.version}</version>
            <type>amp</type>
        </dependency>
        <dependency>
            <groupId>com.github.dynamicextensionsalfresco</groupId>
            <artifactId>annotations</artifactId>
            <version>${com.github.dynamicextensionsalfresco.version}</version>
            <classifier>classes</classifier>
        </dependency>
        <dependency>
            <groupId>com.github.dynamicextensionsalfresco</groupId>
            <artifactId>webscripts</artifactId>
            <version>${com.github.dynamicextensionsalfresco.version}</version>
            <classifier>classes</classifier>
        </dependency>
    </dependencies>
</project>


text:
using System;
using MarieCurie.DoIt.Domain;

namespace MarieCurie.DoIt.RestClient.Request
{
    public class OpportunityUpdateRequest : OpportunityCreateRequest
    {
        public OpportunityUpdateRequest(Opportunity opportunity) : base(opportunity)
        {
            Uuid = opportunity.Id;
        }

        public Guid Uuid { get; set; }
    }
}


text:
from django.contrib.auth.decorators import login_required, permission_required
from django.utils.decorators import method_decorator
from django.template.loader import render_to_string
from django.template import RequestContext
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.views.generic import DetailView, ListView, CreateView, UpdateView, View
from django.views.generic.edit import ModelFormMixin

import StringIO
import ho.pisa as pisa
from excel_response3 import ExcelResponse

from django_xhtml2pdf.utils import render_to_pdf_response, generate_pdf
#from utils import  render_to_pdf_response

from models import *
from forms import *

# import the logging library
import logging

# Get an instance of a logger
logger = logging.getLogger(__name__)

def ver(request, pk):
	registration = get_object_or_404(Registration, id=pk)
	payload = {'registration': registration, 'request': request}
	file_data = render_to_string('hobetuz/detalle.html', payload, RequestContext(request))
	myfile = StringIO.StringIO()
	return HttpResponse( file_data )

def imprimir(registration,request):
	payload = {'registration': registration}
	#response_pdf = render_to_pdf_response('hobetuz/matricula_imprimir.html',payload, pdfname='hobetuz-%s.pdf'%registration.id)
	#response_pdf = render_to_pdf_response('hobetuz/detalle.html',payload, pdfname='hobetuz-%s.pdf'%registration.id)
	response_html = render_to_response('hobetuz/detalle.html',payload, RequestContext(request))
	#return response_pdf
	return response_html

@login_required
def imprimir_hobetuz(request, pk):
	registration = Registration.objects.get(id=pk)
	return imprimir(registration,request)

@login_required
class RegistrationListView(ListView):
	model=Registration
	template_name='hobetuz/lista.html'

	@method_decorator(login_required)
	def dispatch(self, *args, **kwargs):
		return super().dispatch(*args, **kwargs)

class RegistrationUpdateView(UpdateView):
	model=Registration
	success_url = '/hobetuz/list'
	form_class = RegistrationForm
	template_name='hobetuz/registration_edit.html'

class RegistrationCreateView(CreateView):
	model = Registration
	form_class = RegistrationForm
	template_name='hobetuz/registration_form.html'
	def get_success_url(self):
		## FIXME usar un reverse o lazy_reverse
		return '/hobetuz/thanks/'

class Registration2019ListView(ListView):
	model=Registration2019
	template_name='hobetuz/lista2019.html'

class Registration2019DetailView(DetailView):
	model=Registration2019
	template_name='hobetuz/detalle2019.html'
        context_object_name = "registration"

class Registration2019CreateView(CreateView):
	model = Registration2019
	form_class = Registration2019Form
	template_name='hobetuz/registration_form.html'
	def get_success_url(self):
		## FIXME usar un reverse o lazy_reverse
		return '/hobetuz/thanks/'

@login_required
def RegistrationExcelView(request):
    objs = Registration.objects.all()
    return ExcelResponse(objs)

class CursoList(ListView):
    queryset=Curso.objects.all()
    template_name='hobetuz/curso_list.html'

class HobetuzPortada(ListView):
    queryset=Curso.objects.filter(matricula_abierta=True)
    template_name='hobetuz/portada.html'


text:
<?php

namespace OC\PlatformBundle\Controller;

use OC\PlatformBundle\Entity\Advert;
use OC\PlatformBundle\Entity\Image;
use OC\PlatformBundle\Entity\Application;
use OC\PlatformBundle\Entity\AdvertSkill;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class AdvertController extends Controller
{
    public function indexAction($page)
    {
        // On ne sait pas combien de pages il y a
        // Mais on sait qu'une page doit être supérieure ou égale à 1
        if ($page < 1) {
            // On déclenche une exception NotFoundHttpException, cela va afficher
            // une page d'erreur 404 (qu'on pourra personnaliser plus tard d'ailleurs)
            throw new NotFoundHttpException('Page "'.$page.'" inexistante.');
        }

        // Ici, on récupérera la liste des annonces, puis on la passera au template

        $listAdverts = array(
            array(
                'title'   => 'Recherche développpeur Symfony2',
                'id'      => 1,
                'author'  => 'Alexandre',
                'content' => 'Nous recherchons un développeur Symfony2 débutant sur Lyon. Blabla…',
                'date'    => new \Datetime()),
            array(
                'title'   => 'Mission de webmaster',
                'id'      => 2,
                'author'  => 'Hugo',
                'content' => 'Nous recherchons un webmaster capable de maintenir notre site internet. Blabla…',
                'date'    => new \Datetime()),
            array(
                'title'   => 'Offre de stage webdesigner',
                'id'      => 3,
                'author'  => 'Mathieu',
                'content' => 'Nous proposons un poste pour webdesigner. Blabla…',
                'date'    => new \Datetime())
        );

        // Et modifiez le 2nd argument pour injecter notre liste
        return $this->render('OCPlatformBundle:Advert:index.html.twig', array(
            'listAdverts' => $listAdverts
        ));
    }

    public function viewAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        // On récupère l'annonce $id
        $advert = $em
            ->getRepository('OCPlatformBundle:Advert')
            ->find($id)
        ;

        if (null === $advert) {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        // On récupère la liste des candidatures de cette annonce
        $listApplications = $em
            ->getRepository('OCPlatformBundle:Application')
            ->findBy(array('advert' => $advert))
        ;

        // On récupère maintenant la liste des AdvertSkill
        $listAdvertSkills = $em
            ->getRepository('OCPlatformBundle:AdvertSkill')
            ->findBy(array('advert' => $advert))
        ;

        return $this->render('OCPlatformBundle:Advert:view.html.twig', array(
            'advert'           => $advert,
            'listApplications' => $listApplications,
            'listAdvertSkills' => $listAdvertSkills,
        ));
    }

    public function addAction(Request $request)
    {
        // On récupère l'EntityManager
        $em = $this->getDoctrine()->getManager();

        //Création de l'entité
        $advert = new Advert();
        $advert->setTitle('Recherche développeur Symfony2.');
        $advert->setAuthor('Alexandre');
        $advert->setContent("Nous recherchons un développeur Symfony2 débutant sur Lyon. Blabla...");

        // Création de l'entité Image
        $image = new Image();
        $image->setUrl('http://sdz-upload.s3.amazonaws.com/prod/upload/job-de-reve.jpg');
        $image->setAlt('Job de rêve');

        // On lie l'image à l'annonce
        $advert->setImage($image);

        // Création d'une première candidature
        $application1 = new Application();
        $application1->setAuthor('Marine');
        $application1->setContent("J'ai toutes les qualités requises.");

        // Création d'une deuxième candidature par exemple
        $application2 = new Application();
        $application2->setAuthor('Pierre');
        $application2->setContent("Je suis très motivé.");

        // On lie les candidatures à l'annonce
        $application1->setAdvert($advert);
        $application2->setAdvert($advert);

        // On récupère toutes les compétences possibles
        $listSkills = $em->getRepository('OCPlatformBundle:Skill')->findAll();

        // Pour chaque compétence
        foreach ($listSkills as $skill) {
            // On crée une nouvelle « relation entre 1 annonce et 1 compétence »
            $advertSkill = new AdvertSkill();

            // On la lie à l'annonce, qui est ici toujours la même
            $advertSkill->setAdvert($advert);
            // On la lie à la compétence, qui change ici dans la boucle foreach
            $advertSkill->setSkill($skill);

            // Arbitrairement, on dit que chaque compétence est requise au niveau 'Expert'
            $advertSkill->setLevel('Expert');

            // Et bien sûr, on persiste cette entité de relation, propriétaire des deux autres relations
            $em->persist($advertSkill);
        }

        // Étape 1 : On « persiste » l'entité
        $em->persist($advert);

        // Étape 1 bis : pour cette relation pas de cascade lorsqu'on persiste Advert, car la relation est
        // définie dans l'entité Application et non Advert. On doit donc tout persister à la main ici.
        $em->persist($application1);
        $em->persist($application2);

        // Étape 2 : On « flush » tout ce qui a été persisté avant
        $em->flush();

        if ($request->isMethod('POST')) {
            $request->getSession()->getFlashBag()->add('notice', 'Annonce bien enregistrée.');
            return $this->redirect($this->generateUrl('oc_platform_view', array('id' => $advert->getId())));
        }

        return $this->render('OCPlatformBundle:Advert:add.html.twig');
    }

    public function editAction($id, Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        // On récupère l'annonce $id
        $advert = $em->getRepository('OCPlatformBundle:Advert')->find($id);

        if (null === $advert) {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        // La méthode findAll retourne toutes les catégories de la base de données
        $listCategories = $em->getRepository('OCPlatformBundle:Category')->findAll();

        // On boucle sur les catégories pour les lier à l'annonce
        foreach ($listCategories as $category) {
            $advert->addCategory($category);
        }

        // Pour persister le changement dans la relation, il faut persister l'entité propriétaire
        // Ici, Advert est le propriétaire, donc inutile de la persister car on l'a récupérée depuis Doctrine

        // Étape 2 : On déclenche l'enregistrement
        $em->flush();

        // Même mécanisme que pour l'ajout
        if ($request->isMethod('POST')) {
            $request->getSession()->getFlashBag()->add('notice', 'Annonce bien modifiée.');

            return $this->redirect($this->generateUrl('oc_platform_view', array('id' => 5)));
        }

        $advert = array(
            'title'   => 'Recherche développpeur Symfony2',
            'id'      => $id,
            'author'  => 'Alexandre',
            'content' => 'Nous recherchons un développeur Symfony2 débutant sur Lyon. Blabla…',
            'date'    => new \Datetime()
        );

        return $this->render('OCPlatformBundle:Advert:edit.html.twig', array(
            'advert' => $advert
        ));
    }

    public function deleteAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        // On récupère l'annonce $id
        $advert = $em->getRepository('OCPlatformBundle:Advert')->find($id);

        if (null === $advert) {
            throw new NotFoundHttpException("L'annonce d'id ".$id." n'existe pas.");
        }

        // On boucle sur les catégories de l'annonce pour les supprimer
        foreach ($advert->getCategories() as $category) {
            $advert->removeCategory($category);
        }

        // Pour persister le changement dans la relation, il faut persister l'entité propriétaire
        // Ici, Advert est le propriétaire, donc inutile de la persister car on l'a récupérée depuis Doctrine

        // On déclenche la modification
        $em->flush();

        return $this->render('OCPlatformBundle:Advert:delete.html.twig');
    }

    public function menuAction($limit)
    {
        // On fixe en dur une liste ici, bien entendu par la suite
        // on la récupérera depuis la BDD !
        $listAdverts = array(
            array('id' => 2, 'title' => 'Recherche développeur Symfony2'),
            array('id' => 5, 'title' => 'Mission de webmaster'),
            array('id' => 9, 'title' => 'Offre de stage webdesigner')
        );

        return $this->render('OCPlatformBundle:Advert:menu.html.twig', array(
            // Tout l'intérêt est ici : le contrôleur passe
            // les variables nécessaires au template !
            'listAdverts' => $listAdverts
        ));
    }
}