text:
//
//  CiOSAudio.h
//
//

#ifndef CiOSAudio_h
#define CiOSAudio_h

#import <UIKit/UIKit.h>
#import <GLKit/GLKit.h>
#import <mach/time_value.h>
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AudioToolbox/ExtendedAudioFile.h>
#import <AudioToolbox/AudioFile.h>
#include "CSoundAnalysis.h"
#include "encryptFile.h"

class CiOSPlatform;
class CiOSAudio;
class CiOSAudioSession;

class cAudioFadeParam
{
    friend class CiOSAudio;
    friend class CiOSAudioSession;
public:
    cAudioFadeParam();
    virtual ~cAudioFadeParam();

    void attach();
    void detach();
    void exec();
    bool setFadeParam(s16 _fadeType, float _tgtVol, u32 _msec, s16 _interType=INTER_TYPE_LINEAR, float _startVolume=1.0f);

    static void AudioFadeParamInit();
    static void AudioFadeParamExit();
    static void SetFadeParam(CiOSAudio * _audio, CiOSAudioSession * _settion, s16 _fadeType, float _tgtVol, u32 _msec, s16 _interType=INTER_TYPE_LINEAR, float _startVolume=0.0f);
    static void Remove(void * _audio);
	static s32 ThreadAudioFadeParam(void * hThread, void * data);
public:
    // フェード関係のパラメータ
    enum FADE_TYPE
    {
        FADE_TYPE_NONE = 0,
        FADE_TYPE_PLAY,         //!< fade in
        FADE_TYPE_STOP,         //!< fade out
        FADE_TYPE_PAUSE,        //!< fade out
        FADE_TYPE_RESUME,       //!< fade in
        FADE_TYPE_PLAYING,      //!< fade

        FADE_TYPE_NUM,
    };

    enum INTER_TYPE
    {
        INTER_TYPE_NONE = 0,
        INTER_TYPE_LINEAR,         //!< Linear

        INTER_TYPE_NUM,
    };

private:
    s32                 m_fadeCnt;          //!< フェードカウント(ミリ秒)
    float               m_startVol;         //!< フェード開始のボリューム値(0.0f~1.0f)
    float               m_endVol;           //!< フェード終了のボリューム値(0.0f~1.0f)
    float               m_fadeRatio;        //!< フェード割合(0.0f〜1.0f)
    s32                 m_fadeMiliSec;      //!< フェードに要する時間(ミリ秒)
    s16                 m_nowFadeInterType; //!< 現在のフェード補間タイプ
    s16                 m_nowFadeType;      //!< 現在のフェードタイプ
    bool                m_bfade;            //!< フェード中?
    s64                 m_prevmseq;         //!< 前回の再生時間

    CiOSAudio*          m_pAudio;           //!< 対象者
    CiOSAudioSession*   m_pSession;         //!< 対象者

    cAudioFadeParam*    m_prev; //!< 前のフェードパラメータ
    cAudioFadeParam*    m_next; //!< 次のフェードパラメータ

    static cAudioFadeParam* s_fadeParamList;
    static void*            s_fadeParamThread;
};

class CiOSAudioSession
{
    friend class CiOSAudio;
private:
    CiOSAudioSession(CiOSAudio * pAudio);
    virtual ~CiOSAudioSession();

    void init();
public:
    void play();
    void stop();
    void pause();
    void resume();
    s64 tell();
    void checkSessionStoped();
    inline bool isPlaying() { return m_isPlaying; }
    inline bool isPause() { return m_isPause; }

    inline float getFadeRatio(void) { return m_fadeRatio; }
    void setFadeRatio(float _fadeRatio);
private:
    CiOSAudioSession    *   m_prev;
    CiOSAudioSession    *   m_next;

    CiOSAudio   *       m_audio;
    AudioUnit           m_audioUnit;

    SInt64              m_currentFrame; //!< 現在の再生フレーム
    bool                m_isDone;       //!< 再生終了?
    bool                m_isPlaying;    //!< 再生中?
    bool                m_isPause;      //!< pause中?

    float               m_volume;       //!< ボリューム(0.0f~1.0f)
    float               m_panL;         //!< 左ボリューム
    float               m_panR;         //!< 右ボリューム

    float               m_fadeRatio;

    OSStatus callbackSE(AudioUnitRenderActionFlags * ioActionFlags,
                        const AudioTimeStamp * inTimeStamp,
                        UInt32 inBusNumber,
                        UInt32 inNumberFrames,
                        AudioBufferList * ioData);

    static OSStatus renderCallback(void * inRefCon, AudioUnitRenderActionFlags * ioActionFlags,
                                   const AudioTimeStamp * inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList * ioData);
};

class AudioFileMemory
{
public:
	AudioFileMemory();
    ~AudioFileMemory() {}

public:
	u8*				m_decryptBuffer;
	u32				m_dataLength;

public:
	bool			loadFile		(const char* url);
	void			release			();

private:
    CDecryptBaseClass m_decrypter;
    inline void decrypt(void* ptr, u32 length) {
        m_decrypter.decryptBlck(ptr, length);
    }
	inline u32 decryptSetup(const u8* ptr, const u8* hdr) {
        return m_decrypter.decryptSetup(ptr, hdr);
    }
};

class CiOSAudio
{
    friend class CiOSAudioSession;
private:
    typedef struct {
        const char * top;
        const char * phisical;
    } LOCLIST;
    static const LOCLIST m_toplevel[];

public:
    CiOSAudio();
    virtual ~CiOSAudio();

    bool openAudio(const char * path, CiOSPlatform * platform);
    bool loadMem(); // オンメモリ化

    inline void setLuaPause(bool _bLuaPause) { m_luaPause = _bLuaPause; }
    inline bool getLuaPause(void) { return m_luaPause; }

    void play(s32 _msec=0, float _tgtVol=1.0f, float _startVol=1.0f);
    void stop(s32 _msec=0, float _tgtVol=0.0f);
    void pause(s32 _msec=0, float _tgtVol=0.0f);
    void resume(s32 _msec=0, float _tgtVol=1.0f);
    void seek(s32 millisec);
    s32 tell();
    s32 totalPlayTime();

    void setFadeParam(float _tgtVol, u32 _msec);
    inline float getFadeRatio(void) { return m_fadeRatio; }
    void setFadeRatio(float _fadeRatio);
    s32 getState();

    void closeAudio();

    void setVolume(float volume);
    inline float getVolume() { return m_volume; }
    void setPan(float pan);
    inline float getPan() { return m_pan; }

    inline bool isActive() { return m_bActive; }
    inline int getInterruptionType() { return m_interruptionType; }
    inline void setInterruptionType( int _interruptionType ) { m_interruptionType = _interruptionType; }

    inline bool setBufSize(int level) {
        if(level < 0 || level > 2) return false;
        m_buf_level = level;
        return true;
    }
    void updateVolume();
    void checkSessionStoped();
    void audioSessionCleanup();

private:

    enum {
        BUF_COUNT = 3
    };
    enum {
        STEP_WAIT,
        STEP_PLAY,
        STEP_PAUSE
    };
    const char                      *   m_soundPath;
    // char                         *   m_soundFullpath;
    bool                                m_bActive;
    bool                                m_preLoad;
    bool                                m_bInit;
    bool                                m_bSeeked;
    int                                 m_interruptionType;    //!< サウンドの割り込みタイプ
    bool                                m_luaPause;

    int                                 m_buf_level;
    int                                 m_step;

    NSURL                           *   m_soundURL;
    AudioFileID                         m_audioID;
    AudioStreamBasicDescription         m_ASBD;
    AudioStreamPacketDescription    *   m_ASPD;
    AudioQueueRef                       m_queue;
    AudioQueueBufferRef                 m_qBuf[ BUF_COUNT ];
    AudioQueueTimelineRef               m_TlineRef;

    int                                 m_bufIndex;

    UInt64                              m_numPacketPerTime;
    UInt32                              m_maxPacketSize;
    SInt64                              m_startPackNum;
    SInt64                              m_pauseTime;
    s32                                 m_nowPlayTime;  // BGMの現在再生時刻
    uint64_t                            m_tval;
    uint64_t                            m_last_delta;

    float                               m_volume;
    float                               m_pan;
    float                               m_panR;
    float                               m_panL;

    float                               m_fadeRatio;
    sSoundAnalysisData                  m_soundAnalysisData;

    ExtAudioFileRef                     m_extAudioID;
    AudioStreamBasicDescription         m_clientFormat;
    SInt64                              m_totalFrames;

    AudioUnitSampleType             **  m_playBuffer;

    CiOSAudioSession                *   m_begin;
    CiOSAudioSession                *   m_end;

    CiOSPlatform                    *   m_platform;
	AudioFileMemory						m_encFile;
private:

    void initBGM();
    void playBGM();
    void initSE();
    void playSE(s32 _msec=0, float _tgtVol=1.0f, float _startVol=1.0f);

    void cleanup();

    void sendQueue(AudioQueueRef inAQ, AudioQueueBufferRef inBuffer);

    static void queueCallback(void * inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer);
};

#endif // CiOSAudio_h


text:
'use strict';

angular.module('repeatAnimateBenchmark', ['ngAnimate'])
  .run(function($rootScope) {
    $rootScope.fileType = 'default';
  });

redpajama_set_name: RedPajamaGithub


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

//http://stackoverflow.com/questions/22677931/react-js-onchange-event-for-contenteditable

var propTypes = {
  // editorType: PropTypes.string,
};
var defaultProps = {
  toolbarProps: {
    style: {
      padding: '0.25rem'
    }
  },
  wrapperProps: {
    style: {
      overflow: 'hidden',
      backgroundColor: 'white',
      border: '1px solid #d3d6db',
      borderRadius: 3,
      minHeight: '2rem',
      display: 'flex',
      boxShadow: 'inset 0 1px 2px rgba(17,17,17,.1)'
    }
  }
};

var PreviewEditor = function (_Component) {
  (0, _inherits3.default)(PreviewEditor, _Component);

  function PreviewEditor(props) {
    (0, _classCallCheck3.default)(this, PreviewEditor);

    var _this = (0, _possibleConstructorReturn3.default)(this, (PreviewEditor.__proto__ || (0, _getPrototypeOf2.default)(PreviewEditor)).call(this, props));

    _this.state = (0, _assign2.default)({}, props);
    return _this;
  }

  (0, _createClass3.default)(PreviewEditor, [{
    key: 'componentWillReceiveProps',
    value: function componentWillReceiveProps(nextProps) {
      // console.debug({ nextProps });
      this.setState((0, _assign2.default)({}, nextProps));
    }
  }, {
    key: 'render',
    value: function render() {
      return _react2.default.createElement(
        'div',
        this.props.wrapperProps,
        _react2.default.createElement('div', this.props.toolbarProps),
        _react2.default.createElement('div', (0, _extends3.default)({}, this.props.passProps, {
          className: 'contenteditable',
          onInput: this.emitChange.bind(this),
          onBlur: this.emitChange.bind(this),
          contentEditable: true,
          dangerouslySetInnerHTML: {
            __html: this.state.value
          } }))
      );
    }
  }, {
    key: 'getInnerHTML',
    value: function getInnerHTML() {
      return _reactDom2.default.findDOMNode(this).children[0].innerHTML;
    }
  }, {
    key: 'shouldComponentUpdate',
    value: function shouldComponentUpdate(nextProps) {
      return nextProps.value !== this.getInnerHTML();
    }
  }, {
    key: 'componentDidUpdate',
    value: function componentDidUpdate() {
      if (this.props.value !== this.getInnerHTML()) {
        _reactDom2.default.findDOMNode(this).children[0].innerHTML = this.props.value;
      }
    }
  }, {
    key: 'emitChange',
    value: function emitChange() {
      var html = this.getInnerHTML();
      // console.debug({ html });
      if (this.props.onChange && typeof this.props.onChange === 'function' && html !== this.lastHtml) {
        this.props.onChange({
          target: {
            value: _reactDom2.default.findDOMNode(this).children[0].innerHTML
          }
        });
      }
      if (this.props.setDynamicData && typeof this.props.setDynamicData === 'string' && html !== this.lastHtml) {
        this.props.setDynamicData(this.props.dynamicField, html);
      }
      this.lastHtml = html;
    }
  }]);
  return PreviewEditor;
}(_react.Component);

PreviewEditor.propTypes = propTypes;
PreviewEditor.defaultProps = defaultProps;

exports.default = PreviewEditor;


text:
This package provides a Basic Authentication middleware.

It'll try to compare credentials from Authentication request header to a username/password pair in middleware constructor.

More details about this type of authentication can be found in [Mozilla article](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication).

## Usage

```go
import httptransport "github.com/go-kit/kit/transport/http"

httptransport.NewServer(
		AuthMiddleware(cfg.auth.user, cfg.auth.password, "Example Realm")(makeUppercaseEndpoint()),
		decodeMappingsRequest,
		httptransport.EncodeJSONResponse,
		httptransport.ServerBefore(httptransport.PopulateRequestContext),
	)
```

For AuthMiddleware to be able to pick up the Authentication header from an HTTP request we need to pass it through the context with something like ```httptransport.ServerBefore(httptransport.PopulateRequestContext)```.


text:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Tearable cloth webgl</title>
    <style>
        .mp-0 {
            margin: 0;
            padding: 0;
        }
        .block {
            display: block;
            touch-action: none;
        }
    </style>
    <script src="stats.min.js"></script>
</head>
<body class="mp-0">
    <canvas class="block"></canvas>
    <script src="load.js"></script>
    <script src="webgl.js"></script>
    <script src="trigger.js"></script>
    <script src="pointer.js"></script>
    <script src="canvas.js"></script>
    <script src="constraint.js"></script>
    <script src="point.js"></script>
    <script src="cloth.js"></script>
    <script src="app.webgl.js"></script>
</body>
</html>


text:
// <copyright file="JungleQueue.cs">
//     The MIT License (MIT)
//
// Copyright(c) 2017 Ryan Fleming
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common.Logging;
using JungleQueue.Aws.Sqs;
using JungleQueue.Configuration;
using JungleQueue.Interfaces;
using JungleQueue.Interfaces.IoC;
using JungleQueue.Interfaces.Serialization;
using JungleQueue.Messaging;

namespace JungleQueue
{
    /// <summary>
    /// Main application queue for sending and receiving messages from AWS
    /// </summary>
    public class JungleQueue : IRunJungleQueue
    {
        /// <summary>
        /// Logger instance
        /// </summary>
        private static readonly ILog Log = LogManager.GetLogger(typeof(JungleQueue));

        /// <summary>
        /// SQS queue
        /// </summary>
        private readonly ISqsQueue _queue;

        /// <summary>
        /// Receive event message pump
        /// </summary>
        private readonly MessagePump _messagePump;

        /// <summary>
        /// Receive event message pump
        /// </summary>
        private Task _messagePumpTask;

        /// <summary>
        /// Message Logger
        /// </summary>
        private readonly IMessageLogger _messageLogger;

        /// <summary>
        /// Message serializer
        /// </summary>
        private readonly IMessageSerializer _messageSerializer;

        /// <summary>
        /// Initializes a new instance of the <see cref="JungleQueue" /> class.
        /// </summary>
        /// <param name="configuration">Configuration object</param>
        public JungleQueue(QueueConfiguration configuration)
        {
            _messageLogger = configuration.MessageLogger;
            _messageSerializer = configuration.MessageSerializer;
            Action<IObjectBuilder> queuePreHandler = x =>
            {
                x.RegisterInstance(CreateSendQueue());
                configuration.Prehandler?.Invoke(x);
            };
            _queue = new SqsQueue(configuration.Region, configuration.QueueName, configuration.RetryCount);
            _queue.WaitTimeSeconds = configuration.SqsPollWaitTime;
            if (configuration.MaxSimultaneousMessages > 0)
            {
                MessageParser parser = new MessageParser(configuration.MessageSerializer);
                MessageProcessor messageProcessor = new MessageProcessor(configuration.Handlers, configuration.FaultHandlers, configuration.ObjectBuilder, queuePreHandler);
                _messagePump = new MessagePump(_queue, configuration.RetryCount, messageProcessor, _messageLogger, parser);
                _messagePump.MaxSimultaneousMessages = configuration.MaxSimultaneousMessages;
            }
        }

        /// <summary>
        /// Gets an instance of the queue that can send messages
        /// </summary>
        /// <returns>Instance of the queue</returns>
        public IQueue CreateSendQueue()
        {
            _queue.Init().Wait();
            return new TransactionalQueue(_queue, _messageLogger, _messageSerializer);
        }

        /// <summary>
        /// Starts the queue receiving and processing messages
        /// </summary>
        public void StartReceiving()
        {
            if (_messagePump == null)
            {
                throw new InvalidOperationException("Queue is not configured for receive operations");
            }

            _queue.Init().Wait();
            Log.Info("Starting message pumps");
            _messagePumpTask = _messagePump.Run();
        }

        /// <summary>
        /// Triggers the queue to stop processing new messages
        /// </summary>
        public void StopReceiving()
        {
            Log.Info("Stopping the queue");
            _messagePump.Stop();
            Task.WaitAll(_messagePumpTask);
            _messagePump.Dispose();
            _messagePumpTask = null;
        }
    }
}


text:
import AGClientSocket = require('./clientsocket');

export function create(options?: AGClientSocket.ClientOptions): AGClientSocket;


text:
#include "DriveEnumerateDecorator.h"

namespace vtStor
{
    cDriveEnumerateDecorator::cDriveEnumerateDecorator(std::shared_ptr<IDriveEnumerator> DecoratedDriveEnumerator) : m_DecoratedDriveEnumerator(DecoratedDriveEnumerator)
    {
    }

    std::shared_ptr<IDrive> cDriveEnumerateDecorator::EnumerateDrive(const std::shared_ptr<IDevice>& Device)
    {
        std::shared_ptr<IDrive> drive = DoEnumerate(Device);
        if (nullptr != drive)
        {
            return drive;
        }
        return m_DecoratedDriveEnumerator->EnumerateDrive(Device);
    }
}


text:
package twitter.scrape;

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import twitter.exception.InvalidInputException;

import java.util.List;

@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@Ignore
public class TwitterScrapeTest {

    @Autowired
    private TwitterScrape twitterScrape;

    @Test
    public void testNotNullScrapeList() throws InvalidInputException{
        List<Tweet> tweetList = twitterScrape.scrape("#obama");
        Assert.assertNotNull(tweetList);
    }

    @Test
    public void assertNotEmptyScrapeList() throws InvalidInputException{
        List<Tweet> tweets = twitterScrape.scrape("#obama");
        Assert.assertTrue(tweets.size() > 0);
    }
}


text:
.class public Landroid/bluetooth/BluetoothGattService;
.super Ljava/lang/Object;
.source "BluetoothGattService.java"

# static fields
.field public static final SERVICE_TYPE_PRIMARY:I = 0x0

.field public static final SERVICE_TYPE_SECONDARY:I = 0x1

# instance fields
.field protected mCharacteristics:Ljava/util/List;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/List",
            "<",
            "Landroid/bluetooth/BluetoothGattCharacteristic;",
            ">;"
        }
    .end annotation
.end field

.field protected mDevice:Landroid/bluetooth/BluetoothDevice;

.field protected mHandles:I

.field protected mIncludedServices:Ljava/util/List;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/List",
            "<",
            "Landroid/bluetooth/BluetoothGattService;",
            ">;"
        }
    .end annotation
.end field

.field protected mInstanceId:I

.field protected mServiceType:I

.field protected mUuid:Ljava/util/UUID;

# direct methods
.method constructor <init>(Landroid/bluetooth/BluetoothDevice;Ljava/util/UUID;II)V
    .locals 1
    .param p1, "device"    # Landroid/bluetooth/BluetoothDevice;
    .param p2, "uuid"    # Ljava/util/UUID;
    .param p3, "instanceId"    # I
    .param p4, "serviceType"    # I

    .prologue
    .line 107
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 66
    const/4 v0, 0x0

    iput v0, p0, Landroid/bluetooth/BluetoothGattService;->mHandles:I

    .line 108
    iput-object p1, p0, Landroid/bluetooth/BluetoothGattService;->mDevice:Landroid/bluetooth/BluetoothDevice;

    .line 109
    iput-object p2, p0, Landroid/bluetooth/BluetoothGattService;->mUuid:Ljava/util/UUID;

    .line 110
    iput p3, p0, Landroid/bluetooth/BluetoothGattService;->mInstanceId:I

    .line 111
    iput p4, p0, Landroid/bluetooth/BluetoothGattService;->mServiceType:I

    .line 112
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mCharacteristics:Ljava/util/List;

    .line 113
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mIncludedServices:Ljava/util/List;

    .line 114
    return-void
.end method

.method public constructor <init>(Ljava/util/UUID;I)V
    .locals 2
    .param p1, "uuid"    # Ljava/util/UUID;
    .param p2, "serviceType"    # I

    .prologue
    const/4 v1, 0x0

    .line 93
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 66
    iput v1, p0, Landroid/bluetooth/BluetoothGattService;->mHandles:I

    .line 94
    const/4 v0, 0x0

    iput-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mDevice:Landroid/bluetooth/BluetoothDevice;

    .line 95
    iput-object p1, p0, Landroid/bluetooth/BluetoothGattService;->mUuid:Ljava/util/UUID;

    .line 96
    iput v1, p0, Landroid/bluetooth/BluetoothGattService;->mInstanceId:I

    .line 97
    iput p2, p0, Landroid/bluetooth/BluetoothGattService;->mServiceType:I

    .line 98
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mCharacteristics:Ljava/util/List;

    .line 99
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mIncludedServices:Ljava/util/List;

    .line 100
    return-void
.end method

# virtual methods
.method public addCharacteristic(Landroid/bluetooth/BluetoothGattCharacteristic;)Z
    .locals 1
    .param p1, "characteristic"    # Landroid/bluetooth/BluetoothGattCharacteristic;

    .prologue
    .line 144
    iget-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mCharacteristics:Ljava/util/List;

    invoke-interface {v0, p1}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    .line 145
    invoke-virtual {p1, p0}, Landroid/bluetooth/BluetoothGattCharacteristic;->setService(Landroid/bluetooth/BluetoothGattService;)V

    .line 146
    const/4 v0, 0x1

    return v0
.end method

.method addIncludedService(Landroid/bluetooth/BluetoothGattService;)V
    .locals 1
    .param p1, "includedService"    # Landroid/bluetooth/BluetoothGattService;

    .prologue
    .line 193
    iget-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mIncludedServices:Ljava/util/List;

    invoke-interface {v0, p1}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    .line 194
    return-void
.end method

.method public addService(Landroid/bluetooth/BluetoothGattService;)Z
    .locals 1
    .param p1, "service"    # Landroid/bluetooth/BluetoothGattService;

    .prologue
    .line 132
    iget-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mIncludedServices:Ljava/util/List;

    invoke-interface {v0, p1}, Ljava/util/List;->add(Ljava/lang/Object;)Z

    .line 133
    const/4 v0, 0x1

    return v0
.end method

.method public getCharacteristic(Ljava/util/UUID;)Landroid/bluetooth/BluetoothGattCharacteristic;
    .locals 3
    .param p1, "uuid"    # Ljava/util/UUID;

    .prologue
    .line 260
    iget-object v2, p0, Landroid/bluetooth/BluetoothGattService;->mCharacteristics:Ljava/util/List;

    invoke-interface {v2}, Ljava/util/List;->iterator()Ljava/util/Iterator;

    move-result-object v1

    .local v1, "i$":Ljava/util/Iterator;
    :cond_0
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v2

    if-eqz v2, :cond_1

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/bluetooth/BluetoothGattCharacteristic;

    .line 261
    .local v0, "characteristic":Landroid/bluetooth/BluetoothGattCharacteristic;
    invoke-virtual {v0}, Landroid/bluetooth/BluetoothGattCharacteristic;->getUuid()Ljava/util/UUID;

    move-result-object v2

    invoke-virtual {p1, v2}, Ljava/util/UUID;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_0

    .line 264
    .end local v0    # "characteristic":Landroid/bluetooth/BluetoothGattCharacteristic;
    :goto_0
    return-object v0

    :cond_1
    const/4 v0, 0x0

    goto :goto_0
.end method

.method getCharacteristic(Ljava/util/UUID;I)Landroid/bluetooth/BluetoothGattCharacteristic;
    .locals 3
    .param p1, "uuid"    # Ljava/util/UUID;
    .param p2, "instanceId"    # I

    .prologue
    .line 154
    iget-object v2, p0, Landroid/bluetooth/BluetoothGattService;->mCharacteristics:Ljava/util/List;

    invoke-interface {v2}, Ljava/util/List;->iterator()Ljava/util/Iterator;

    move-result-object v1

    .local v1, "i$":Ljava/util/Iterator;
    :cond_0
    invoke-interface {v1}, Ljava/util/Iterator;->hasNext()Z

    move-result v2

    if-eqz v2, :cond_1

    invoke-interface {v1}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/bluetooth/BluetoothGattCharacteristic;

    .line 155
    .local v0, "characteristic":Landroid/bluetooth/BluetoothGattCharacteristic;
    invoke-virtual {v0}, Landroid/bluetooth/BluetoothGattCharacteristic;->getUuid()Ljava/util/UUID;

    move-result-object v2

    invoke-virtual {p1, v2}, Ljava/util/UUID;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_0

    invoke-virtual {v0}, Landroid/bluetooth/BluetoothGattCharacteristic;->getInstanceId()I

    move-result v2

    if-ne v2, p2, :cond_0

    .line 159
    .end local v0    # "characteristic":Landroid/bluetooth/BluetoothGattCharacteristic;
    :goto_0
    return-object v0

    :cond_1
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public getCharacteristics()Ljava/util/List;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/List",
            "<",
            "Landroid/bluetooth/BluetoothGattCharacteristic;",
            ">;"
        }
    .end annotation

    .prologue
    .line 241
    iget-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mCharacteristics:Ljava/util/List;

    return-object v0
.end method

.method getDevice()Landroid/bluetooth/BluetoothDevice;
    .locals 1

    .prologue
    .line 121
    iget-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mDevice:Landroid/bluetooth/BluetoothDevice;

    return-object v0
.end method

.method getHandles()I
    .locals 1

    .prologue
    .line 176
    iget v0, p0, Landroid/bluetooth/BluetoothGattService;->mHandles:I

    return v0
.end method

.method public getIncludedServices()Ljava/util/List;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/List",
            "<",
            "Landroid/bluetooth/BluetoothGattService;",
            ">;"
        }
    .end annotation

    .prologue
    .line 232
    iget-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mIncludedServices:Ljava/util/List;

    return-object v0
.end method

.method public getInstanceId()I
    .locals 1

    .prologue
    .line 215
    iget v0, p0, Landroid/bluetooth/BluetoothGattService;->mInstanceId:I

    return v0
.end method

.method public getType()I
    .locals 1

    .prologue
    .line 222
    iget v0, p0, Landroid/bluetooth/BluetoothGattService;->mServiceType:I

    return v0
.end method

.method public getUuid()Ljava/util/UUID;
    .locals 1

    .prologue
    .line 202
    iget-object v0, p0, Landroid/bluetooth/BluetoothGattService;->mUuid:Ljava/util/UUID;

    return-object v0
.end method

.method public setHandles(I)V
    .locals 0
    .param p1, "handles"    # I

    .prologue
    .line 185
    iput p1, p0, Landroid/bluetooth/BluetoothGattService;->mHandles:I

    .line 186
    return-void
.end method

.method public setInstanceId(I)V
    .locals 0
    .param p1, "instanceId"    # I

    .prologue
    .line 168
    iput p1, p0, Landroid/bluetooth/BluetoothGattService;->mInstanceId:I

    .line 169
    return-void
.end method


text:
class AddMissingAttributesToUser < ActiveRecord::Migration[5.0]
  def up
    remove_column :users, :role
    add_column :users, :is_admin, :boolean
    User.update_all(is_admin: false)
    change_column :users, :is_admin, :boolean, null: false, default: false
  end

  def down
    remove_column :users, :is_admin
    add_column :users, :role, :string
    User.update_all(role: '')
    change_column :users, :role, :string, null:false
  end
end


text:
require "feedbag"
require "feedzirra"

class FeedDiscovery
  def discover(url, finder = Feedbag, parser = Feedzirra::Feed)
    begin
      feed = parser.fetch_and_parse(url)
      feed.feed_url ||= url
      return feed
    rescue Exception => e
      urls = finder.find(url)
      return false if urls.empty?
    end

    begin
      feed = parser.fetch_and_parse(urls.first)
      feed.feed_url ||= urls.first
      return feed
    rescue Exception => e
      return false
    end
  end
end


text:
class Hash
  # Public: Merges self with another Hash, recursively
  #
  # Taken from Jekyll, which was lovingly stolen from some random gem:
  # http://gemjack.com/gems/tartan-0.1.1/classes/Hash.html
  #
  def deep_merge(hash)
    target = dup
    hash.keys.each do |key|
      if hash[key].is_a? Hash and self[key].is_a? Hash
        target[key] = target[key].deep_merge(hash[key])
        next
      end

      target[key] = hash[key]
    end
    target
  end

  # Public: Destructively convert all keys to symbols, as long as they respond to to_sym
  # From Ruby on Rails source (v3.1.0)
  #
  def symbolize_keys!
    keys.each do |key|
      self[(key.to_sym rescue key) || key] = delete(key)
    end
    self
  end

  # Public: Return a new hash with all keys converted to symbols, as long as they respond to to_sym
  # From the Ruby on Rails source (v3.1.0)
  #
  def symbolize_keys
    dup.symbolize_keys!
  end

  # Public: Read array from the supplied hash favouring the singular key
  # and then the plural key, and handling any nil entries. From Jekyll!
  #   +hash+ the hash to read from
  #   +singular_key+ the singular key
  #   +plural_key+ the singular key
  #
  # Returns an array
  def pluralized_array(singular_key, plural_key)
    hash = self
    if hash.has_key?(singular_key)
      array = [hash[singular_key]] if hash[singular_key]
    elsif hash.has_key?(plural_key)
      case hash[plural_key]
      when String
        array = hash[plural_key].split
      when Array
        array = hash[plural_key].compact
      end
    end
    array || []
  end

end


text:
package sdk.weixin.msg.parser.impl;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import sdk.weixin.msg.*;
import sdk.weixin.msg.parser.Constants;
import sdk.weixin.msg.parser.ResolveParam;
import sdk.weixin.msg.parser.xml.Element;

/**
 * 时间消息解析器
 *
 * @author work
 * @version %I%, %G%
 * @since 1.0
 */
public class EventMessageResolver extends BaseContentMessageResolver {
    private static final String EVENT_KEY_PREFIX = "qrscene_";

    @Override protected boolean initMessage(ResolveParam param) {
        Element eventElement =
            CollectionUtils.find(param.getElementList(), new Predicate<Element>() {
                @Override public boolean evaluate(Element object) {
                    return Constants.ELE_EVT.equals(object.getName());
                }
            });

        if (null == eventElement) {
            return false;
        }

        // check subscribe | qc
        boolean hasParsed = false;
        switch (eventElement.getValue().toLowerCase()) {
            case "subscribe":
                Element eventKey =
                    CollectionUtils.find(param.getElementList(), new Predicate<Element>() {
                        @Override public boolean evaluate(Element object) {
                            return Constants.ELE_QR_KEY.equals(object.getName());
                        }
                    });

                if (null == eventKey) {
                    // subscribe
                    SubscribeMessage msg = new SubscribeMessage();
                    msg.setIsSubscribe(true);
                    setMessage(msg);

                } else {
                    // qr
                    setMessage(new ScanQRCodeMessage());

                }
                hasParsed = true;
                break;

            case "unsubscribe":
                SubscribeMessage msg = new SubscribeMessage();
                msg.setIsSubscribe(false);
                setMessage(msg);
                hasParsed = true;
                break;

            case "scan":
                setMessage(new ScanQRSubscribeMessage());
                hasParsed = true;
                break;

            case "location":
                setMessage(new LocationUploadMessage());
                hasParsed = true;
                break;

            case "click":
                setMessage(new MenuMessage());
                hasParsed = true;
                break;

            default:
                break;
        }

        if (hasParsed) {
            castMessage(EventMessage.class).setEvent(eventElement.getValue());
        }

        return hasParsed;
    }

    @Override public boolean parseExtElement(Element element) {
        if (super.parseExtElement(element)) {
            return true;
        }

        if (message instanceof ScanQRSubscribeMessage) {
            return parseScanQRSubElement(element);

        } else if (message instanceof ScanQRCodeMessage) {
            return parseScanQRElement(element);

        } else if (message instanceof LocationUploadMessage) {
            return parseLocationUploadElement(element);

        } else if (message instanceof MenuMessage) {
            return parseMenuElement(element);
        }

        return false;
    }

    private boolean parseMenuElement(Element e) {
        MenuMessage msg = castMessage(MenuMessage.class);
        switch (e.getName()) {
            case Constants.ELE_QR_KEY:
                msg.setMenuKey(e.getValue());
                return true;
            default:
                break;
        }

        return false;
    }

    private boolean parseLocationUploadElement(Element e) {
        LocationUploadMessage msg = castMessage(LocationUploadMessage.class);
        switch (e.getName()) {
            case Constants.ELE_LOCU_LAT:
                msg.setLatitude(e.getValue());
                return true;

            case Constants.ELE_LOCU_LONG:
                msg.setLongitude(e.getValue());
                return true;

            case Constants.ELE_LOCU_PRECISION:
                msg.setPrecision(e.getValue());
                return true;

            default:
                break;
        }
        return false;
    }

    private boolean parseScanQRElement(Element e) {
        ScanQRCodeMessage msg = castMessage(ScanQRCodeMessage.class);
        switch (e.getName()) {
            case Constants.ELE_QR_KEY:
                // remove prefix qrscene_
                String val = e.getValue();
                int prefixPos = val.indexOf(EVENT_KEY_PREFIX);
                if (-1 < prefixPos) {
                    msg.setEventKey(val.substring(prefixPos + EVENT_KEY_PREFIX.length()));

                } else {
                    msg.setEventKey(val);

                }
                return true;

            case Constants.ELE_QR_TICKET:
                msg.setTicket(e.getValue());
                return true;

            default:
                break;
        }
        return false;
    }

    private boolean parseScanQRSubElement(Element e) {
        ScanQRSubscribeMessage msg = castMessage(ScanQRSubscribeMessage.class);
        switch (e.getName()) {
            case Constants.ELE_QR_KEY:
                msg.setEventKey(e.getValue());
                return true;

            case Constants.ELE_QR_TICKET:
                msg.setTicket(e.getValue());
                return true;

            default:
                break;

        }

        return false;
    }
}


text:
layout: post
title: "Elixir Pattern Matching"
date: 2015-12-06 15-12-34
description: "A brief look at Elixirs Pattern matching and the power the equal sign operator."
tags: [development, elixir, programming]
comments: true
---
## Special Characters have meaning as well

Learning any new programming language is a always a great challenge. There's always new techniques, methods, and syntax to learn. But it is also a great experience to expand you knowledge and learn new tricks and with Elixir this is also the case. As with many programming languages there are numerous keywords and special characters that have meaning. They can assign a value, perform some sort of logic test, run a method, etc. And in this article we will taking a brief look at Elixir based Pattern Matching.

### Pattern matching

In numerous programming languages the equal symbol `=` is generally an assignment operator. Which means you set XYZ variable to the value of JKL `xyz = 'FooBar'`. You can usually assign an object, a value, a function, or many other datatypes to a variable. With Elixir this is still the case, but with exceptions. In Elixir, the equals operator means to match the left side of the `=` sign to the the right side.

```elixir
iex> x = 7
# => 7
iex> y = 5
# => 5
iex> 7 = y
# => ** (MatchError) no match of right hand side value: 5
```

You may be wondering what this error is about. Well the variable `y` was assigned the value of 5, meaning that in the last line you are stating that 7 = 5. This value should always be false. Now if the variable was on the left side of the equal sign the value of 7 would have been assigned the variable.

### Taking it a step farther
Once you begin using pattern matching, it can become a very powerful feature in you application. Not only can you do pattern matching with basic variables and datatypes, you can also match values with tuples and lists. This can be a double edged sword, it can either complicate the heck out of your program or make things work extremely effectively. Pattern matching assignment is a great tool when working with tuples/lists, because it allows us to pick which values we wish to assign and use.

```elixir
costanza = %{name: "George", age: 27, likes: "Sports"}
# => %{age: 27, likes: "Sports", name: "George"}

# lets verify name is an unassigned variable
name
# => ** (CompileError) iex:2: undefined function name/0

%{name: name} = costanza
# => %{age: 27, likes: "Sports", name: "George"}

name
# => "George"
```

Lets put this in prospective of an HTTP request/response, to assign

```elixir
{result, value} = {:error, 404}
# => {:error, 404}

result
# => :error
```

Now rather than assigning values, lets look at an example of pattern matching based on conditional comparisons.

```elixir
{:ok, reponse} = {:error, 404}
# => ** (MatchError) no match of right hand side value: {:error, 404}

{:status, reponse} = {:status, 200}
# => {:status, 200}

{200, response} = {200, "html/text;"}
# => {200, "html/text;"}
```
In the first example you can see the left hand and right hand of the `=` operator are not equal and do not having matching :atoms so they can not be assigned values to their corresponding variables. But the second example does have matching atoms/object so their values can be associated with one another. By using this pattern matching techniques, you are not solely limited to using :atoms to match the values, you can use various data types. If you look at the third example you can see that they correspond with each other with an integer that has the value of `200`. This may look like a mess, why would you want to do this? Well the sample below might shine some like on this. With pattern matching you could assign the values based on a functions response values, using a simple HTTP request I will try to show you that it isn't so hard to understand how and why these values may be passed.

```elixir
defmodule Http do
  def request do
    # ...
    {:status, 404}
  end
end

{:status, response} = Http.request()
# => {:status, 404}

response
# => 404
```

### Functional Pattern Matching

When declaring and calling functions you can continue to do pattern matching based on the declared values without using the equals `=` assignment operator. Generally function pattern matching is used for with making recursion effective and manageable.

```elixir
defmodule Seinfield do
  def cast([], _), do: [] # STOP: when end of list has been reached

  def cast(list), do: cast(list, 1) # start index from 1 when beginning to map through the list
  def cast([head | tail], count) do
    IO.puts "#{count}: #{head}"
    cast(tail, (count+1))
  end
end

characters = ["George","Jerry","Kramer","Elaine","Newman"]
# => ["George", "Jerry", "Kramer", "Elaine", "Newman"]

Seinfield.cast(characters)

# => George
# Jerry
# Kramer
# Elaine
# Newman
```

I know this is an extreme example jumping from basic variable declarations to module/function matching. But if you look at the cast function, you'll notice that when passing parameters using a list Elixir will match to the lists `[head |tail]` to make break down in forms of context here is what it would look like with the characters list passed through it.

```elixir
[head | tail]
["George" | "Jerry","Kramer","Elaine","Newman"]
```

### Clearing it up
I hope you have better understanding of Elixirs pattern matching capabilities and that the equal sign is not just an assignment operator in Elixir. Elixir has a massive amount of capabilities and some of these may be confusing as hell, but pattern matching helps bring it one step closer to help make everything easier to understand and use.


text:
cd ~/storage
rsync -a --exclude .git CBIG/* Standalone_CBIG2022_DiffProc

# remove useless stable projects
rm -r Standalone_CBIG2022_DiffProc/stable_projects/brain_parcellation
rm -r Standalone_CBIG2022_DiffProc/stable_projects/disorder_subtypes
rm -r Standalone_CBIG2022_DiffProc/stable_projects/fMRI_dynamics
rm -r Standalone_CBIG2022_DiffProc/stable_projects/registration
rm -r Standalone_CBIG2022_DiffProc/stable_projects/predict_phenotypes
rm -r Standalone_CBIG2022_DiffProc/stable_projects/meta-analysis
rm -r Standalone_CBIG2022_DiffProc/stable_projects/preprocessing/Orban2020_tod
rm -r Standalone_CBIG2022_DiffProc/stable_projects/preprocessing/Li2019_GSR
rm -r Standalone_CBIG2022_DiffProc/stable_projects/preprocessing/CBIG_fMRI_Preproc2016


text:
<!doctype html>

    <title>Code coverage report for src/components/article/articleActions.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      all files / src/components/article/ articleActions.js

        55.56%
        Statements
        10/18

        100%
        Branches
        0/0

        37.5%
        Functions
        3/8

        56.25%
        Lines
        9/16

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25	1×
1×
1×
1×
1×
1×

1×

1×

import { resource } from '../../actions'
import { initFollowing } from '../main/followingActions'
export const initArticles = () => {
    return (dispatch) => {
        dispatch({type: 'CLEAN'})
        resource('GET', 'articles')
        .then((response) => {
            dispatch({type: 'UPDATE_ARTICLES', articles: response.articles})
    })
        .catch((error) => console.log(error))
    }
}

export const addNewArticle = ({text}) => {
    return (dispatch) => {
        console.log(text)
        resource('POST', 'article', {text})
        .then((response) => {
            dispatch(initArticles())
            dispatch(initFollowing())
        })
        .catch((error) => console.log(error))
    }
}

  Code coverage
  generated by istanbul at Fri Mar 24 2017 21:48:13 GMT-0500 (CDT)


text:
struct TRI_doc_mptr_t;
struct TRI_shaped_sub_s;

// -----------------------------------------------------------------------------
// --SECTION--                                                        HASH INDEX
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                                      public types
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief hash index element
///
/// This structure is used for the elements of a unique hash index.
////////////////////////////////////////////////////////////////////////////////

typedef struct TRI_hash_index_element_s {
  struct TRI_doc_mptr_t*                  _document;
  struct TRI_shaped_sub_s*                _subObjects;
}
TRI_hash_index_element_t;

////////////////////////////////////////////////////////////////////////////////
/// @brief hash index element
///
/// This structure is used for the elements of a non-unique hash index.
////////////////////////////////////////////////////////////////////////////////

typedef struct TRI_hash_index_element_multi_s {
  struct TRI_doc_mptr_t*                  _document;
  struct TRI_shaped_sub_s*                _subObjects;
  struct TRI_hash_index_element_multi_s*  _next;
}
TRI_hash_index_element_multi_t;

////////////////////////////////////////////////////////////////////////////////
/// @brief hash index
////////////////////////////////////////////////////////////////////////////////

typedef struct TRI_hash_index_s {
  TRI_index_t base;

  union {
    TRI_hash_array_t       _hashArray;   // the hash array itself, unique values
    TRI_hash_array_multi_t _hashArrayMulti;   // the hash array itself, non-unique values
  };
  TRI_vector_t             _paths;       // a list of shape pid which identifies the fields of the index
}
TRI_hash_index_t;

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief creates a hash index
////////////////////////////////////////////////////////////////////////////////

TRI_index_t* TRI_CreateHashIndex (struct TRI_document_collection_t*,
                                  TRI_idx_iid_t,
                                  TRI_vector_pointer_t*,
                                  TRI_vector_t*,
                                  bool);

////////////////////////////////////////////////////////////////////////////////
/// @brief frees the memory allocated, but does not free the pointer
////////////////////////////////////////////////////////////////////////////////

void TRI_DestroyHashIndex (TRI_index_t*);

////////////////////////////////////////////////////////////////////////////////
/// @brief frees the memory allocated and frees the pointer
////////////////////////////////////////////////////////////////////////////////

void TRI_FreeHashIndex (TRI_index_t*);

// -----------------------------------------------------------------------------
// --SECTION--                                                  public functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief locates entries in the hash index given shaped json objects
/// it is the callers responsibility to destroy the result
////////////////////////////////////////////////////////////////////////////////

TRI_vector_pointer_t TRI_LookupHashIndex (TRI_index_t*,
                                          struct TRI_index_search_value_s*);

////////////////////////////////////////////////////////////////////////////////
/// @brief locates entries in the hash index given shaped json objects
/// this function uses the state passed to it to return a fragment of the
/// total result - the next call to the function can resume at the state where
/// it was left off last
/// note: state is ignored for unique indexes as there will be at most one
/// item in the result
/// it is the callers responsibility to destroy the result
////////////////////////////////////////////////////////////////////////////////

TRI_vector_pointer_t TRI_LookupHashIndex (TRI_index_t*,
                                          struct TRI_index_search_value_s*,
                                          struct TRI_hash_index_element_multi_s*&,
                                          size_t);

#endif

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:


text:
#ifndef ROCKETINVADERSEVENTHANDLERHIGHSCORE_H
#define ROCKETINVADERSEVENTHANDLERHIGHSCORE_H

#include "EventHandler.h"

/**
 */

class EventHandlerHighScore : public EventHandler
{
public:
	EventHandlerHighScore();
	virtual ~EventHandlerHighScore();

	virtual void ProcessEvent(Rocket::Core::Event& event, const Rocket::Core::String& value);
};

#endif


text:
Demangle::NodePointer
swift::_swift_buildDemanglingForMetadata(const Metadata *type);

// Build a demangled type tree for a nominal type.
static Demangle::NodePointer
_buildDemanglingForNominalType(const Metadata *type) {
  using namespace Demangle;

  const Metadata *parent;
  Node::Kind boundGenericKind;
  const NominalTypeDescriptor *description;

  // Demangle the parent type, if any.
  switch (type->getKind()) {
  case MetadataKind::Class: {
    auto classType = static_cast<const ClassMetadata *>(type);
#if SWIFT_OBJC_INTEROP
    // Peek through artificial subclasses.
    while (classType->isTypeMetadata() && classType->isArtificialSubclass())
      classType = classType->SuperClass;
#endif
    parent = classType->getParentType(classType->getDescription());
    boundGenericKind = Node::Kind::BoundGenericClass;
    description = classType->getDescription();
    break;
  }
  case MetadataKind::Enum:
  case MetadataKind::Optional: {
    auto enumType = static_cast<const EnumMetadata *>(type);
    parent = enumType->Parent;
    boundGenericKind = Node::Kind::BoundGenericEnum;
    description = enumType->Description;
    break;
  }
  case MetadataKind::Struct: {
    auto structType = static_cast<const StructMetadata *>(type);
    parent = structType->Parent;
    boundGenericKind = Node::Kind::BoundGenericStructure;
    description = structType->Description;
    break;
  }
  default:
    return nullptr;
  }

  // Demangle the base name.
  auto node = demangleTypeAsNode(description->Name,
                                 strlen(description->Name));
  assert(node->getKind() == Node::Kind::Type);

  // Demangle the parent.
  if (parent) {
    auto parentNode = _swift_buildDemanglingForMetadata(parent);
    if (parentNode->getKind() == Node::Kind::Type)
      parentNode = parentNode->getChild(0);

    auto typeNode = node->getChild(0);
    auto newTypeNode = NodeFactory::create(typeNode->getKind());
    newTypeNode->addChild(parentNode);
    newTypeNode->addChild(typeNode->getChild(1));

    auto newNode = NodeFactory::create(Node::Kind::Type);
    newNode->addChild(newTypeNode);
    node = newNode;
  }

  // If generic, demangle the type parameters.
  if (description->GenericParams.NumPrimaryParams > 0) {
    auto typeParams = NodeFactory::create(Node::Kind::TypeList);
    auto typeBytes = reinterpret_cast<const char *>(type);
    auto genericParam = reinterpret_cast<const Metadata * const *>(
                 typeBytes + sizeof(void*) * description->GenericParams.Offset);
    for (unsigned i = 0, e = description->GenericParams.NumPrimaryParams;
         i < e; ++i, ++genericParam) {
      auto demangling = _swift_buildDemanglingForMetadata(*genericParam);
      if (demangling == nullptr)
        return nullptr;
      typeParams->addChild(demangling);
    }

    auto genericNode = NodeFactory::create(boundGenericKind);
    genericNode->addChild(node);
    genericNode->addChild(typeParams);
    return genericNode;
  }
  return node;
}

// Build a demangled type tree for a type.
Demangle::NodePointer swift::_swift_buildDemanglingForMetadata(const Metadata *type) {
  using namespace Demangle;

  switch (type->getKind()) {
  case MetadataKind::Class:
  case MetadataKind::Enum:
  case MetadataKind::Optional:
  case MetadataKind::Struct:
    return _buildDemanglingForNominalType(type);
  case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
    auto objcWrapper = static_cast<const ObjCClassWrapperMetadata *>(type);
    const char *className = class_getName((Class)objcWrapper->Class);

    // ObjC classes mangle as being in the magic "__ObjC" module.
    auto module = NodeFactory::create(Node::Kind::Module, "__ObjC");

    auto node = NodeFactory::create(Node::Kind::Class);
    node->addChild(module);
    node->addChild(NodeFactory::create(Node::Kind::Identifier,
                                       llvm::StringRef(className)));

    return node;
#else
    assert(false && "no ObjC interop");
    return nullptr;
#endif
  }
  case MetadataKind::ForeignClass: {
    auto foreign = static_cast<const ForeignClassMetadata *>(type);
    return Demangle::demangleTypeAsNode(foreign->getName(),
                                        strlen(foreign->getName()));
  }
  case MetadataKind::Existential: {
    auto exis = static_cast<const ExistentialTypeMetadata *>(type);
    NodePointer proto_list = NodeFactory::create(Node::Kind::ProtocolList);
    NodePointer type_list = NodeFactory::create(Node::Kind::TypeList);

    proto_list->addChild(type_list);

    std::vector<const ProtocolDescriptor *> protocols;
    protocols.reserve(exis->Protocols.NumProtocols);
    for (unsigned i = 0, e = exis->Protocols.NumProtocols; i < e; ++i)
      protocols.push_back(exis->Protocols[i]);

    // Sort the protocols by their mangled names.
    // The ordering in the existential type metadata is by metadata pointer,
    // which isn't necessarily stable across invocations.
    std::sort(protocols.begin(), protocols.end(),
          [](const ProtocolDescriptor *a, const ProtocolDescriptor *b) -> bool {
            return strcmp(a->Name, b->Name) < 0;
          });

    for (auto *protocol : protocols) {
      // The protocol name is mangled as a type symbol, with the _Tt prefix.
      auto protocolNode = demangleSymbolAsNode(protocol->Name,
                                               strlen(protocol->Name));

      // ObjC protocol names aren't mangled.
      if (!protocolNode) {
        auto module = NodeFactory::create(Node::Kind::Module,
                                          MANGLING_MODULE_OBJC);
        auto node = NodeFactory::create(Node::Kind::Protocol);
        node->addChild(module);
        node->addChild(NodeFactory::create(Node::Kind::Identifier,
                                           llvm::StringRef(protocol->Name)));
        auto typeNode = NodeFactory::create(Node::Kind::Type);
        typeNode->addChild(node);
        type_list->addChild(typeNode);
        continue;
      }

      // FIXME: We have to dig through a ridiculous number of nodes to get
      // to the Protocol node here.
      protocolNode = protocolNode->getChild(0); // Global -> TypeMangling
      protocolNode = protocolNode->getChild(0); // TypeMangling -> Type
      protocolNode = protocolNode->getChild(0); // Type -> ProtocolList
      protocolNode = protocolNode->getChild(0); // ProtocolList -> TypeList
      protocolNode = protocolNode->getChild(0); // TypeList -> Type

      assert(protocolNode->getKind() == Node::Kind::Type);
      assert(protocolNode->getChild(0)->getKind() == Node::Kind::Protocol);
      type_list->addChild(protocolNode);
    }

    return proto_list;
  }
  case MetadataKind::ExistentialMetatype: {
    auto metatype = static_cast<const ExistentialMetatypeMetadata *>(type);
    auto instance = _swift_buildDemanglingForMetadata(metatype->InstanceType);
    auto node = NodeFactory::create(Node::Kind::ExistentialMetatype);
    node->addChild(instance);
    return node;
  }
  case MetadataKind::Function: {
    auto func = static_cast<const FunctionTypeMetadata *>(type);

    Node::Kind kind;
    switch (func->getConvention()) {
    case FunctionMetadataConvention::Swift:
      kind = Node::Kind::FunctionType;
      break;
    case FunctionMetadataConvention::Block:
      kind = Node::Kind::ObjCBlock;
      break;
    case FunctionMetadataConvention::CFunctionPointer:
      kind = Node::Kind::CFunctionPointer;
      break;
    case FunctionMetadataConvention::Thin:
      kind = Node::Kind::ThinFunctionType;
      break;
    }

    std::vector<NodePointer> inputs;
    for (unsigned i = 0, e = func->getNumArguments(); i < e; ++i) {
      auto arg = func->getArguments()[i];
      auto input = _swift_buildDemanglingForMetadata(arg.getPointer());
      if (arg.getFlag()) {
        NodePointer inout = NodeFactory::create(Node::Kind::InOut);
        inout->addChild(input);
        input = inout;
      }
      inputs.push_back(input);
    }

    NodePointer totalInput;
    if (inputs.size() > 1) {
      auto tuple = NodeFactory::create(Node::Kind::NonVariadicTuple);
      for (auto &input : inputs)
        tuple->addChild(input);
      totalInput = tuple;
    } else {
      totalInput = inputs.front();
    }

    NodePointer args = NodeFactory::create(Node::Kind::ArgumentTuple);
    args->addChild(totalInput);

    NodePointer resultTy = _swift_buildDemanglingForMetadata(func->ResultType);
    NodePointer result = NodeFactory::create(Node::Kind::ReturnType);
    result->addChild(resultTy);

    auto funcNode = NodeFactory::create(kind);
    if (func->throws())
      funcNode->addChild(NodeFactory::create(Node::Kind::ThrowsAnnotation));
    funcNode->addChild(args);
    funcNode->addChild(result);
    return funcNode;
  }
  case MetadataKind::Metatype: {
    auto metatype = static_cast<const MetatypeMetadata *>(type);
    auto instance = _swift_buildDemanglingForMetadata(metatype->InstanceType);
    auto typeNode = NodeFactory::create(Node::Kind::Type);
    typeNode->addChild(instance);
    auto node = NodeFactory::create(Node::Kind::Metatype);
    node->addChild(typeNode);
    return node;
  }
  case MetadataKind::Tuple: {
    auto tuple = static_cast<const TupleTypeMetadata *>(type);
    const char *labels = tuple->Labels;
    auto tupleNode = NodeFactory::create(Node::Kind::NonVariadicTuple);
    for (unsigned i = 0, e = tuple->NumElements; i < e; ++i) {
      auto elt = NodeFactory::create(Node::Kind::TupleElement);

      // Add a label child if applicable:
      if (labels) {
        // Look for the next space in the labels string.
        if (const char *space = strchr(labels, ' ')) {
          // If there is one, and the label isn't empty, add a label child.
          if (labels != space) {
            auto eltName =
              NodeFactory::create(Node::Kind::TupleElementName,
                                  std::string(labels, space));
            elt->addChild(std::move(eltName));
          }

          // Skip past the space.
          labels = space + 1;
        }
      }

      // Add the element type child.
      auto eltType =
        _swift_buildDemanglingForMetadata(tuple->getElement(i).Type);
      elt->addChild(std::move(eltType));

      // Add the completed element to the tuple.
      tupleNode->addChild(std::move(elt));
    }
    return tupleNode;
  }
  case MetadataKind::Opaque:
    // FIXME: Some opaque types do have manglings, but we don't have enough info
    // to figure them out.
  case MetadataKind::HeapLocalVariable:
  case MetadataKind::HeapGenericLocalVariable:
  case MetadataKind::ErrorObject:
    break;
  }
  // Not a type.
  return nullptr;
}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Uses of Interface com.hazelcast.nio.ConnectionManager (Hazelcast Root 3.3.3 API)</title>
<meta name="date" content="2014-11-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.hazelcast.nio.ConnectionManager

Packages that use ConnectionManager

Package
Description

com.hazelcast.instance

This package contains Hazelcast Instance functionality.

com.hazelcast.jmx

Contains Hazelcast management bean classes.

com.hazelcast.management

Contains classes to provide data/operation interface for Management Center.

com.hazelcast.nio.tcp

Contains functionality for the TCP/IP Networking between cluster members

Uses of ConnectionManager in com.hazelcast.instance

Fields in com.hazelcast.instance declared as ConnectionManager

Modifier and Type
Field and Description

ConnectionManager
Node.connectionManager

Methods in com.hazelcast.instance that return ConnectionManager

Modifier and Type
Method and Description

ConnectionManager
NodeContext.createConnectionManager(Node node,
                       ServerSocketChannel serverSocketChannel)

ConnectionManager
DefaultNodeContext.createConnectionManager(Node node,
                       ServerSocketChannel serverSocketChannel)

ConnectionManager
Node.getConnectionManager()

Uses of ConnectionManager in com.hazelcast.jmx

Methods in com.hazelcast.jmx that return ConnectionManager

Modifier and Type
Method and Description

ConnectionManager
ConnectionManagerMBean.getConnectionManager()

Constructors in com.hazelcast.jmx with parameters of type ConnectionManager

Constructor and Description

ConnectionManagerMBean(HazelcastInstance hazelcastInstance,
                      ConnectionManager connectionManager,
                      ManagementService service)

Uses of ConnectionManager in com.hazelcast.management

Constructors in com.hazelcast.management with parameters of type ConnectionManager

Constructor and Description

SerializableConnectionManagerBean(ConnectionManager cm)

Uses of ConnectionManager in com.hazelcast.nio.tcp

Classes in com.hazelcast.nio.tcp that implement ConnectionManager

Modifier and Type
Class and Description

class
TcpIpConnectionManager

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Hazelcast, Inc.. All Rights Reserved.


text:
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// This file is a part of the 'esoco-lib' project.
// Copyright 2017 Elmar Sonnenschein, esoco GmbH, Flensburg, Germany
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//	  http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package de.esoco.lib.comm.http;

import de.esoco.lib.collection.CollectionUtil;
import de.esoco.lib.comm.http.HttpHeaderTypes.HttpHeaderField;
import de.esoco.lib.datatype.Pair;

import java.util.Collections;
import java.util.Map;

/********************************************************************
 * An unchecked exception to report exceptional HTTP responses.
 *
 * @author eso
 */
public class HttpStatusException extends RuntimeException
{
	//~ Static fields/initializers ---------------------------------------------

	private static final long serialVersionUID = 1L;

	//~ Instance fields --------------------------------------------------------

	private final HttpStatusCode eStatusCode;

	private Map<HttpHeaderField, String> rResponseHeaders =
		Collections.emptyMap();

	//~ Constructors -----------------------------------------------------------

	/***************************************
	 * Creates a new instance with a status code and causing exception.
	 *
	 * @param eStatusCode The status code
	 * @param eCause      The causing exception
	 */
	public HttpStatusException(HttpStatusCode eStatusCode, Exception eCause)
	{
		super(eCause);

		this.eStatusCode = eStatusCode;
	}

	/***************************************
	 * Creates a new instance with a status code and message.
	 *
	 * @param eStatusCode      The status code
	 * @param sMessage         The error message
	 * @param rResponseHeaders An optional array of headers to be set on the
	 *                         response
	 */
	@SafeVarargs
	public HttpStatusException(
		HttpStatusCode					 eStatusCode,
		String							 sMessage,
		Pair<HttpHeaderField, String>... rResponseHeaders)
	{
		super(sMessage);

		this.eStatusCode	  = eStatusCode;
		this.rResponseHeaders =
			CollectionUtil.fixedOrderedMapOf(rResponseHeaders);
	}

	/***************************************
	 * Creates a new instance with a status code, message, and causing
	 * exception.
	 *
	 * @param eStatusCode The status code
	 * @param sMessage    The error message
	 * @param eCause      The causing exception
	 */
	public HttpStatusException(HttpStatusCode eStatusCode,
							   String		  sMessage,
							   Exception	  eCause)
	{
		super(sMessage, eCause);

		this.eStatusCode = eStatusCode;
	}

	//~ Methods ----------------------------------------------------------------

	/***************************************
	 * Returns a map of the optional response headers for this status code
	 * exception.
	 *
	 * @return The response headers map (may be empty but will never be NULL)
	 */
	public final Map<HttpHeaderField, String> getResponseHeaders()
	{
		return rResponseHeaders;
	}

	/***************************************
	 * Returns the HTTP status code.
	 *
	 * @return The status code
	 */
	public final HttpStatusCode getStatusCode()
	{
		return eStatusCode;
	}

	//~ Inner Classes ----------------------------------------------------------

	/********************************************************************
	 * A subclass that indicates a bad request that has no content.
	 *
	 * @author eso
	 */
	public static class EmptyRequestException extends HttpStatusException
	{
		//~ Static fields/initializers -----------------------------------------

		private static final long serialVersionUID = 1L;

		//~ Constructors -------------------------------------------------------

		/***************************************
		 * Creates a new instance.
		 */
		public EmptyRequestException()
		{
			super(HttpStatusCode.BAD_REQUEST, "Request empty");
		}
	}
}


text:
export {ExportAssignment} from './export_assignment';
export {ExportDeclaration} from './export_declaration';
export {ImportDeclaration} from './import_declaration';
export {ModuleDeclaration} from './module_declaration';


text:
package Rakudobrew::Variables;
require Exporter;
our @ISA = qw( Exporter );
our @EXPORT = qw( $brew_name $env_var $local_filename $prefix $versions_dir $shim_dir $git_reference $GIT $GIT_PROTO $PERL5 %git_repos %impls );

use strict;
use warnings;
use 5.010;

use FindBin qw($RealBin);
use File::Spec::Functions qw(catfile catdir updir);
use Cwd 'abs_path';

our $brew_name = 'rakudobrew';
our $env_var = 'PL6ENV_VERSION';
our $local_filename = '.perl6-version';

our $prefix = abs_path(catdir($RealBin, updir()));
our $versions_dir = catdir($prefix, 'versions');
our $shim_dir = catdir($prefix, 'shims');
our $git_reference = catdir($prefix, 'git_reference');

our $GIT       = $ENV{GIT_BINARY} // 'git';
our $GIT_PROTO = $ENV{GIT_PROTOCOL} // 'git';
our $PERL5     = $^X;

sub get_git_url {
    my ($protocol, $host, $user, $project) = @_;
    if ($protocol eq "ssh") {
        return "git\@${host}:${user}/${project}.git";
    } else {
        return "${protocol}://${host}/${user}/${project}.git";
    }
}

our %git_repos = (
    rakudo => get_git_url($GIT_PROTO, 'github.com', 'rakudo', 'rakudo'),
    MoarVM => get_git_url($GIT_PROTO, 'github.com', 'MoarVM', 'MoarVM'),
    nqp    => get_git_url($GIT_PROTO, 'github.com', 'perl6',  'nqp'),
    zef    => get_git_url($GIT_PROTO, 'github.com', 'ugexe',  'zef'),
);

our %impls = (
    jvm => {
        name      => "jvm",
        weight    => 20,
        configure => "$PERL5 Configure.pl --backends=jvm --gen-nqp --git-reference=\"$git_reference\" --make-install",
        need_repo => ['rakudo', 'nqp'],
    },
    moar => {
        name      => "moar",
        weight    => 30,
        configure => "$PERL5 Configure.pl --backends=moar --gen-moar --git-reference=\"$git_reference\" --make-install",
        need_repo => ['rakudo', 'nqp', 'MoarVM'],
    },
    'moar-blead' => {
        name      => "moar-blead",
        weight    => 35,
        configure => "$PERL5 Configure.pl --backends=moar --gen-moar=master --gen-nqp=master --git-reference=\"$git_reference\" --make-install",
        need_repo => ['rakudo', 'nqp', 'MoarVM'],
    },
);

1;


text:
require 'spec_helper'

module Rubocop
  module Cop
    module Style
      describe SpaceAfterComma do
        let(:space) { SpaceAfterComma.new }

        it 'registers an offence for block argument commas without space' do
          inspect_source(space, ['each { |s,t| }'])
          expect(space.offences.map(&:message)).to eq(
            ['Space missing after comma.'])
        end

        it 'registers an offence for array index commas without space' do
          inspect_source(space, ['formats[0,1]'])
          expect(space.offences.map(&:message)).to eq(
            ['Space missing after comma.'])
        end

        it 'registers an offence for method call arg commas without space' do
          inspect_source(space, ['a(1,2)'])
          expect(space.offences.map(&:message)).to eq(
            ['Space missing after comma.'])
        end
      end
    end
  end
end


text:
<?php
namespace phpmongoweb\repository;

class MongoDB {
    function __construct($connectionString) {
    }
}


text:
<?php
$access = base64_decode(getenv('POPCLIP_OPTION_AUTHSECRET'));
$url = rawurlencode(getenv('POPCLIP_TEXT'));

// execute request
$ch = curl_init("https://api-ssl.bitly.com/v3/shorten?format=json&access_token=$access&longUrl=$url");
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$json = json_decode($response);
$status = $json->status_code;
$result = $json->data->url;

if ($code==200&&$status==200) {
	echo $result;
	exit(0); // success
}
else if ($code==200&&$status=500) {
	exit(2); // bad auth
}
else {
	exit(1); // other error
}

?>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="BaseMapper">
    <sql id="Base_Condition">
        <where>
            <if test="abstractSql and abstractSql.whereObject">
                <trim prefix="(" suffix=")" prefixOverrides="and" >
                    <foreach collection="abstractSql.whereObject" index="field" item="cons" >
                        <if test="cons">
                            <foreach collection="cons" item="value" index="op" >
                                AND ${field} ${value}
                            </foreach>
                        </if>
                    </foreach>
                </trim>
            </if>
        </where>
    </sql>
    <sql id="Base_Group">
        <if test="abstractSql and abstractSql.group">
            GROUP BY ${abstractSql.group}
        </if>
    </sql>
    <sql id="Base_Order">
        <if test="abstractSql and abstractSql.order">
            ORDER BY ${abstractSql.order}
        </if>
    </sql>
    <sql id="Base_Limit">
        <if test="abstractSql and abstractSql.limitObject">
            LIMIT ${abstractSql.limitObject}
        </if>
    </sql>

</mapper>


text:
import React, { Component, PropTypes } from 'react'

class JqueryComponent extends Component {
    componentDidMount() {
        console.log('---', 'do some jquery magic with', this.refs.container);
    }
    render() {
        return (
            <div ref = "container"/>
        )
    }
}

export default JqueryComponent


text:
package net.largem.poc.strongtype;

public enum MessageOperation {
  FORWARD,
  RETURN
}


text:
from PySide.QtCore import QObject
from PySide.QtGui import QApplication, QIcon, QBrush, QColor

from .templates import Template, TemplateError

class Formatter(QObject):

    def __init__(self, settings, error_callback):
        super().__init__()
        self._error = error_callback
        self.settings = settings
        self._tmplcache = {}
        self.retranslate()

    _directory_icon = QIcon.fromTheme('folder')
    _playlist_icon = QIcon.fromTheme('text-plain')
    _high_prio_background = QBrush(QColor(255, 255, 0, 127))

    playlist_column_count = 2

    def retranslate(self):
        self.display_names = {
            'current_song': self.tr('Current song'),
            'playlist_item': self.tr('Playlist item'),
            'progressbar': self.tr('Progress bar'),
            'window_title': self.tr('Window title'),
            'sort_order': self.tr('Sort order'),
        }
        self.templates = {
            'current_song_tooltip': self.tr(
                '$if3(%paused%,[Paused] ,'
                    '%stopped%,[Stopped] ,'
                    '%connected%,[Connected] ,'
                    '%disconnected%,[Disconnected])'
                '$if2(%file%,%directory%,%playlist%)'
            ),
            'playlist_column2': self.tr('$time(%length%)'),
            'playlist_tooltip': self.tr(
                '$if($ne(%prio%,0),[High priority] ,)'
                '$if2(%file%,%directory%,%playlist%)'
            ),
            'status': self.tr(
                '$if(%disconnected%,,'
                    '%totalcount% songs'
                    '$if($gt(%totallength%,0),'
                        '\\, $time(%totallength%) total,))'
            ),
            'browser_status': self.tr(
                '$if(%disconnected%,,'
                    '%totalcount% items'
                    '$if($gt(%totallength%,0),'
                        '\\, $time(%totallength%) total,))'
            ),
            'statistics': (
                (self.tr('MPD version:'), self.tr('%mpdversion%')),
                (self.tr('Songs:'), self.tr('%songs%')),
                (self.tr('Albums:'), self.tr('%albums%')),
                (self.tr('Artists:'), self.tr('%artists%')),
                (self.tr('Uptime:'), self.tr('$time(%uptime%)')),
                (self.tr('DB playtime:'), self.tr('$time(%db_playtime%)')),
                (self.tr('This instance:'), self.tr('$time(%playtime%)')),
            ),
            'details': (
                (self.tr('%file%'), None),
                (self.tr('Name:'), self.tr('%name%')),
                (self.tr('Title:'), self.tr('%title%')),
                (self.tr('Artist:'), self.tr('%artist%')),
                (self.tr('Album:'), self.tr('%album%')),
                (self.tr('Date:'), self.tr('%date%')),
                (self.tr('Track:'), self.tr('%track%$if(%totaltracks%, / %totaltracks%,)')),
                (self.tr('Disc:'), self.tr('%disc%$if(%totaldiscs%, / %totaldiscs%,)')),
                (self.tr('Comment:'), self.tr('%comment%')),
                (self.tr('Length:'), self.tr('$if(%length%,$time(%length%),)')),
                (self.tr('Last modified:'), self.tr('%lastmodified%')),
                (self.tr('Composer:'), self.tr('%composer%')),
                (self.tr('Performer:'), self.tr('%performer%')),
            ),
        }

    standard_tags = {'file', 'directory', 'playlist', 'filename', 'name', 'title',
        'artist', 'album', 'date', 'track', 'totaltracks', 'disc', 'totaldiscs',
        'comment', 'length', 'lastmodified', 'composer', 'performer',
    }

    def _escape(self, s):
        return s.replace('&', '&').replace('<', '<').replace('>', '>')

    def _prepare_song(self, song, html=True):
        song = song.copy()
        song.pop('id', None)
        song.pop('pos', None)
        if 'prio' not in song:
            song['prio'] = '0'
        for key in ['file', 'directory', 'playlist']:
            if key in song:
                filename = song[key].rstrip('/').rsplit('/', 1)[-1]
                if filename:
                    song['filename'] = filename
        if 'time' in song:
            song['length'] = int(song.pop('time'))
        if 'track' in song and '/' in song['track']:
            song['track'], song['totaltracks'] = song['track'].split('/', 1)
        if 'disc' in song and '/' in song['disc']:
            song['disc'], song['totaldiscs'] = song['disc'].split('/', 1)
        if 'last-modified' in song:
            song['lastmodified'] = song.pop('last-modified').replace('T', ' ').replace('Z', '')
        ret = {}
        for k, v in song.items():
            if isinstance(v, (list, tuple)):
                v = ', '.join(v)
            else:
                v = str(v)
            if html:
                v = self._escape(v)
            if v != '':
                ret[k] = v
        return ret

    def _prepare_state(self, state):
        return {{
            'play': 'playing',
            'pause': 'paused',
            'stop': 'stopped',
            'disconnect': 'disconnected',
            'connect': 'connected',
        }[state]: '1'}

    def _prepare_times(self, elapsed, total):
        return {
            'elapsed': str(elapsed),
            'total': str(total),
        }

    def _compile(self, template, boldable, tmplmodules, name):
        if isinstance(template, str):
            if boldable:
                pref = '$if(%bold%,,)'
                suff = '$if(%bold%,,)'
                template = pref + template + suff
            try:
                return Template(template, tmplmodules + self.settings.tmplplugins)
            except TemplateError as e:
                self._error(self.tr('{} template error: {}')
                        .format(self.display_names.get(name, name), e))
                return Template('')
        r = []
        for a, b in template:
            a = self._compile(a, boldable, tmplmodules, name)
            if b is not None:
                b = self._compile(b, boldable, tmplmodules, name)
            r.append((a, b))
        return tuple(r)

    def _render(self, template, context):
        if isinstance(template, Template):
            return template.render(context)
        r = []
        for a, b in template:
            a = self._render(a, context)
            if b is not None:
                b = self._render(b, context)
            r.append((a, b))
        return r

    def render(self, name, context, bold=None, tmplmodules=[]):
        tmpl = self._tmplcache.get(name)
        if tmpl is None:
            if name in self.settings['format']:
                t = self.settings['format'][name]
            else:
                t = self.templates[name]
            tmpl = self._tmplcache[name] = self._compile(t, bold is not None,
                    tmplmodules, name)
        if bold is not None:
            context['bold'] = '1' if bold else ''
        return self._render(tmpl, context)

    def clear_cache(self):
        self._tmplcache.clear()

    def window_title(self, state, song):
        context = self._prepare_state(state)
        context.update(self._prepare_song(song, html=False))
        return self.render('window_title', context)

    def progressbar(self, state, elapsed, total, song):
        context = self._prepare_state(state)
        context.update(self._prepare_times(elapsed, total))
        context.update(self._prepare_song(song, html=False))
        return self.render('progressbar', context)

    def current_song(self, state, song):
        context = self._prepare_state(state)
        context.update(self._prepare_song(song))
        return self.render('current_song', context)

    def current_song_tooltip(self, state, song):
        context = self._prepare_state(state)
        context.update(self._prepare_song(song, html=False))
        return self.render('current_song_tooltip', context)

    def playlist_item(self, song, column, is_current):
        if column == 0:
            return self.render('playlist_item', self._prepare_song(song), bold=is_current)
        elif column == 1 and 'time' in song:
            return self.render('playlist_column2', {'length': song['time']}, bold=is_current)
        return ''

    def playlist_icon(self, song, column, is_current):
        if column == 0:
            if 'playlist' in song:
                return self._playlist_icon
            if 'directory' in song:
                return self._directory_icon

    def playlist_tooltip(self, song, column, is_current):
        return self.render('playlist_tooltip', self._prepare_song(song, html=False))

    def playlist_background(self, song, column, is_current):
        if song.get('prio', '0') != '0':
            return self._high_prio_background

    _REVERSED = '\U000f6eec'

    class _Reversed:
        @staticmethod
        def f_reversed(s):
            return Formatter._REVERSED + s + Formatter._REVERSED

    def sort_order(self, song):
        return self.render('sort_order',
                self._prepare_song(song, html=False),
                tmplmodules=[self._Reversed]
            ).split(self._REVERSED)

    def status(self, state, totallength, totalcount):
        context = {'totallength': str(totallength), 'totalcount': str(totalcount)}
        context.update(self._prepare_state(state))
        return self.render('status', context)

    def browser_status(self, state, totallength, totalcount):
        context = {'totallength': str(totallength), 'totalcount': str(totalcount)}
        context.update(self._prepare_state(state))
        return self.render('browser_status', context)

    def info_dialog(self, name, info):
        unrecognized = []
        if name == 'details':
            info = self._prepare_song(info, html=False)
            info.pop('prio', None)
            for k, v in info.items():
                if k not in self.standard_tags and k and v:
                    unrecognized.append((k + ':', v))
        r = [i for i in self.render(name, info) if i[1] != '']
        return r + unrecognized


text:
-- MySQL dump 10.13  Distrib 5.5.29, for Linux (x86_64)
--
-- Host: 192.168.0.1    Database: edesirs_new_admin
-- ------------------------------------------------------
-- Server version	5.0.95-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Not dumping tablespaces as no INFORMATION_SCHEMA.FILES table on this server
--

--
-- Table structure for table `lm_languages`
--

/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE IF NOT EXISTS `lm_languages` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(255) character set latin1 NOT NULL default '',
  `description` varchar(255) NOT NULL default '',
  `default` int(1) unsigned NOT NULL default '0',
  PRIMARY KEY  (`id`),
  UNIQUE KEY `name` (`name`),
  KEY `def` (`default`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2013-02-06 17:12:10

INSERT INTO `lm_languages` (`name`, `description`, `default`) VALUES ('en', 'English', 1);


text:
rss: false
layout: article
title: "Inspect and Manage Your Local Storage APIs"
seotitle: "Inspect and Manage Local Storage APIs in the Chrome DevTools Resources Panel"
description: "Inspect and edit local storage APIs including local and session storage, IndexedDB and Web SQL databases, and the Application Cache in the Chrome DevTools Resources panel."
introduction: "Inspect and manage local storage APIs including local and session storage, IndexedDB and Web SQL databases, and the Application Cache in the Chrome DevTools Resources panel."
article:
  written_on: 2015-04-14
  updated_on: 2015-05-18
  order: 1
authors:
  - megginkearney
priority: 0
collection: manage-data
key-takeaways:
  tldr-tbd:
    - TBD tldr.
remember:
  note-tbd:
    - TBD note.
---
{% wrap content %}

{% include modules/toc.liquid %}

## Local and session storage

You can view and edit local and session storage key/value pairs you've created using the [Web Storage APIs](http://www.w3.org/TR/webstorage/). You can edit, delete, and create both local and session storage data.

**To delete a key/value pair**, do one of the following:

* Select the item in the data table and do one of the following:
    2. Click the Delete button.
    3. Press the Delete key on your keyboard.
* Right-click or Control-click on the data item and choose Delete from the context menu.

**To add a new key/value pair:**

1. Double-click inside an empty Key table cell and enter the key name.
2. Double-click inside the corresponding Value table cell and enter the key's value.

**To edit an existing key/value pair**, do one of the following:

* Double-click in the cell you want to edit.
* Right-click or Control-click the cell you want to edit and choose Edit from the context menu.

**To refresh the table with new storage data**, click the Refresh button at the bottom of the panel.

![Refresh](imgs/refresh.png)

## IndexedDB

You can inspect IndexedDB databases and object stores, page through an object store's records, and clear an object store of its records.

* **To view a list of available database**, expand the IndexedDB category.
* **To view a database's object stores**, select it from the list of available databases.

![IndexedDB](imgs/indexeddb.png)

**To page through records in the object store**, click the Previous and Next page buttons. You can also specify the record where paging starts by specifying the record's key.

![Next-previous page](imgs/next-previous-page.png)

**To clear the object store**, do one of the following:

* Click the **Clear object store** button  at the bottom of the panel.
* Right-click or Control-click the object store and select **Clear** from the context menu.

**To view properties of a database**, select it from the list of databases.

![Database properties](imgs/database-properties.png)

## Web SQL

You can inspect the content of Web SQL databases, and run SQL commands against
their contents.

* **To view the available Web SQL databases**, expand the Web SQL item in the tree control.
* **To view available tables in a database**, expand the database tree item.
* **To view a table's records**, select the table. It's properties appear in the right-hand pane.
* **To refresh the view of the database**, click the Refresh button ![Refresh button](refresh.png) at the bottom of the panel.

You can query a Web SQL database's tables with SQL commands and view
query results in a tabular format. As you type out a command or table name, code hints are provided for the names of supported SQL commands and clauses, and the names of tables that the database contains.

**To run a SQL command against a database**:

1. Select the database containing the table you want to query.
2. At the prompt that appears in the right-hand panel, enter the SQL statement you want to execute.

![SQL](imgs/sql.png)

## Application Cache

You can examine resources that Chrome has cached according to the Application Cache manifest file specified by the current document. You can view the current status of the Application Cache (idle or downloading, for
example), and the browser's connection status (online or offline).

![Application Cache](imgs/app-cache.png)

The table of cached resources includes the following properties for each resource:

* **Resource** — The URL of the resource.
* **Type** — The type of cached resource, which can have one of the following
  values:
    * **Master** — The resource was added to the cache because it's
      [manifest](http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#attr-html-manifest)
      attribute indicated that this was its cache.
    * **Explicit** — The resource was explicitly listed in the application's
      cache manifest file.
    * **Network** — The resources was listed in the application's cache manifest
      file as a network entry.
    * **Fallback** — The resource was specified as a fallback if a resource is inaccessible.
* **Size** — Size of the cached resource.

The Resources panel displays the current [status](http://www.whatwg.org/specs/web-apps/current-work/#dom-appcache-status)
of the application cache along with a colored status icon (green, yellow, or red). The following are the possible status values and their descriptions:

Status
Description

 IDLE
The application cache is idle.

CHECKING
The manifest is being fetched and checked for updates.

DOWNLOADING
Resources are being downloaded to be added to the cache, due to a changed resource manifest.

UPDATEREADY
There is a new version of the application cache available.

OBSOLETE
The application cache group is obsolete.

{% include modules/nextarticle.liquid %}

{% endwrap %}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.ResourceManager.Media.Models
{
    public partial class CommonEncryptionCenc : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(EnabledProtocols))
            {
                writer.WritePropertyName("enabledProtocols");
                writer.WriteObjectValue(EnabledProtocols);
            }
            if (Optional.IsCollectionDefined(ClearTracks))
            {
                writer.WritePropertyName("clearTracks");
                writer.WriteStartArray();
                foreach (var item in ClearTracks)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (Optional.IsDefined(ContentKeys))
            {
                writer.WritePropertyName("contentKeys");
                writer.WriteObjectValue(ContentKeys);
            }
            if (Optional.IsDefined(Drm))
            {
                writer.WritePropertyName("drm");
                writer.WriteObjectValue(Drm);
            }
            if (Optional.IsDefined(ClearKeyEncryptionConfiguration))
            {
                writer.WritePropertyName("clearKeyEncryptionConfiguration");
                writer.WriteObjectValue(ClearKeyEncryptionConfiguration);
            }
            writer.WriteEndObject();
        }

        internal static CommonEncryptionCenc DeserializeCommonEncryptionCenc(JsonElement element)
        {
            Optional<MediaEnabledProtocols> enabledProtocols = default;
            Optional<IList<MediaTrackSelection>> clearTracks = default;
            Optional<StreamingPolicyContentKeys> contentKeys = default;
            Optional<CencDrmConfiguration> drm = default;
            Optional<ClearKeyEncryptionConfiguration> clearKeyEncryptionConfiguration = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("enabledProtocols"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    enabledProtocols = MediaEnabledProtocols.DeserializeMediaEnabledProtocols(property.Value);
                    continue;
                }
                if (property.NameEquals("clearTracks"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    List<MediaTrackSelection> array = new List<MediaTrackSelection>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        array.Add(MediaTrackSelection.DeserializeMediaTrackSelection(item));
                    }
                    clearTracks = array;
                    continue;
                }
                if (property.NameEquals("contentKeys"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    contentKeys = StreamingPolicyContentKeys.DeserializeStreamingPolicyContentKeys(property.Value);
                    continue;
                }
                if (property.NameEquals("drm"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    drm = CencDrmConfiguration.DeserializeCencDrmConfiguration(property.Value);
                    continue;
                }
                if (property.NameEquals("clearKeyEncryptionConfiguration"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    clearKeyEncryptionConfiguration = ClearKeyEncryptionConfiguration.DeserializeClearKeyEncryptionConfiguration(property.Value);
                    continue;
                }
            }
            return new CommonEncryptionCenc(enabledProtocols.Value, Optional.ToList(clearTracks), contentKeys.Value, drm.Value, clearKeyEncryptionConfiguration.Value);
        }
    }
}