text:
an async clojure NATS client, wrapping jnats

creates Manifold streams on a NATS subject for :

- publish only (a sink-only stream)
- subscribe only (a source-only stream)
- pubsub (a source+sink stream)

## Usage

    (require '[clj-nats-async.core :as nats])

    (def n (nats/create-nats "nats://localhost:4222"))

    (def s (nats/pubsub n "foo"))

    (manifold.stream/put! s "boo")

    (def msg (manifold.stream/take! s))
    (nats/msg-body @msg) ;; => "boo"

    (.close s)

## License

Copyright 2016 Employee Republic Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this software 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.

redpajama_set_name: RedPajamaGithub


text:
<?php

declare(strict_types=1);

namespace Starychfojtu\ViewComponentBundle\Tests\Finder;

use PHPUnit_Framework_TestCase;

class ViewComponentFinderTest extends PHPUnit_Framework_TestCase
{

}


text:
package kvstore

import (
	"sync"
)

// EventType defines the type of watch event that occurred
type EventType int

const (
	// EventTypeCreate represents a newly created key
	EventTypeCreate EventType = iota
	// EventTypeModify represents a modified key
	EventTypeModify
	// EventTypeDelete represents a deleted key
	EventTypeDelete
	//EventTypeListDone signals that the initial list operation has completed
	EventTypeListDone
)

// String() returns the human readable format of an event type
func (t EventType) String() string {
	switch t {
	case EventTypeCreate:
		return "create"
	case EventTypeModify:
		return "modify"
	case EventTypeDelete:
		return "delete"
	case EventTypeListDone:
		return "listDone"
	default:
		return "unknown"
	}
}

// KeyValueEvent is a change event for a Key/Value pair
type KeyValueEvent struct {
	// Typ is the type of event { EventTypeCreate | EventTypeModify | EventTypeDelete | EventTypeListDone }
	Typ EventType

	// Key is the kvstore key that changed
	Key string

	// Value is the kvstore value associated with the key
	Value []byte
}

// EventChan is a channel to receive events on
type EventChan chan KeyValueEvent

// stopChan is the channel used to indicate stopping of the watcher
type stopChan chan struct{}

// signalChan is used to signal readiness, the purpose is specific to the
// individual functions
type signalChan chan struct{}

// Watcher represents a KVstore watcher
type Watcher struct {
	// Events is the channel to which change notifications will be sent to
	Events EventChan

	name      string
	prefix    string
	stopWatch stopChan

	// stopOnce guarantees that Stop() is only called once
	stopOnce sync.Once

	// stopWait is the wait group to wait for watchers to exit gracefully
	stopWait sync.WaitGroup
}

func newWatcher(name, prefix string, chanSize int) *Watcher {
	w := &Watcher{
		name:      name,
		prefix:    prefix,
		Events:    make(EventChan, chanSize),
		stopWatch: make(stopChan, 0),
	}

	w.stopWait.Add(1)

	return w
}

// String returns the name of the wather
func (w *Watcher) String() string {
	return w.name
}

// ListAndWatch creates a new watcher which will watch the specified prefix for
// changes. Before doing this, it will list the current keys matching the
// prefix and report them as new keys. Name can be set to anything and is used
// for logging messages. The Events channel is created with the specified
// sizes. Upon every change observed, a KeyValueEvent will be sent to the
// Events channel
//
// Returns a watcher structure plus a channel that is closed when the initial
// list operation has been completed
func ListAndWatch(name, prefix string, chanSize int) *Watcher {
	return Client().ListAndWatch(name, prefix, chanSize)
}

// Stop stops a watcher previously created and started with Watch()
func (w *Watcher) Stop() {
	w.stopOnce.Do(func() {
		close(w.stopWatch)
		log.WithField(fieldWatcher, w).Debug("Stopped watcher")
		w.stopWait.Wait()
	})
}


text: Responsive sticky footer, supports IE8+, requires jQuery


text:
package org.apache.usergrid.persistence.map;

/**
 * Factory for creating map managers
 */
public interface MapManagerFactory {

    /**
     * Get the map manager
     */
    public MapManager createMapManager( final MapScope scope );

    void invalidate();
}


text:
//******************************************************************************************************
//  ArchiveListLogSettings.cs - Gbtc
//
//  Copyright © 2014, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), the "License"; you may
//  not use this file except in compliance with the License. You may obtain a copy of the License at:
//
//      http://opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  10/04/2014 - Steven E. Chisholm
//       Generated original version of source code.
//
//******************************************************************************************************

using System;
using System.Data;
using System.IO;
using GSF.IO;

namespace GSF.Snap.Services.Writer
{
    /// <summary>
    /// The settings for a <see cref="RolloverLogFile"/>.
    /// </summary>
    public class RolloverLogSettings
        : SettingsBase<RolloverLogSettings>
    {
        private string m_logPath = string.Empty;
        private string m_logFilePrefix = "Rollover";
        private string m_logFileExtension = ".RolloverLog";

        /// <summary>
        /// Gets if this archive log will be file backed.
        /// This is true as long as <see cref="LogPath"/> is assigned
        /// a value.
        /// </summary>
        public bool IsFileBacked => m_logPath != string.Empty;

        /// <summary>
        /// The path to store all log files. Can be an empty string to
        /// not enable file based logging.
        /// </summary>
        public string LogPath
        {
            get => m_logPath;
            set
            {
                TestForEditable();
                if (string.IsNullOrWhiteSpace(value))
                {
                    m_logPath = string.Empty;
                    return;
                }
                PathHelpers.ValidatePathName(value);
                m_logPath = value;
            }
        }

        /// <summary>
        /// The prefix to assign to all log files. Can be string.empty
        /// </summary>
        public string LogFilePrefix
        {
            get => m_logFilePrefix;
            set
            {
                TestForEditable();
                if (string.IsNullOrWhiteSpace(value))
                {
                    m_logFilePrefix = string.Empty;
                    return;
                }
                PathHelpers.ValidatePathName(value);
                m_logFilePrefix = value;
            }
        }

        /// <summary>
        /// The file extension to write the log files.
        /// </summary>
        public string LogFileExtension
        {
            get => m_logFileExtension;
            set
            {
                TestForEditable();
                m_logFileExtension = PathHelpers.FormatExtension(value);
            }
        }

        /// <summary>
        /// Gets the wildcard search string for a log file.
        /// </summary>
        internal string SearchPattern
        {
            get
            {
                if (LogFilePrefix == string.Empty)
                {
                    return "*" + LogFileExtension;
                }
                return LogFilePrefix + " *" + LogFileExtension;
            }
        }

        /// <summary>
        /// Generates a new file name.
        /// </summary>
        /// <returns></returns>
        internal string GenerateNewFileName()
        {
            if (!IsFileBacked)
                throw new Exception("Cannot generate a file name when the log is not a file backed log");
            if (LogFilePrefix == string.Empty)
            {
                return Path.Combine(LogPath, Guid.NewGuid().ToString() + LogFileExtension);
            }
            return Path.Combine(LogPath, LogFilePrefix + " " + Guid.NewGuid().ToString() + LogFileExtension);
        }

        public override void Save(Stream stream)
        {
            stream.Write((byte)1);
            stream.Write(m_logPath);
            stream.Write(m_logFilePrefix);
            stream.Write(m_logFileExtension);
        }

        public override void Load(Stream stream)
        {
            TestForEditable();
            byte version = stream.ReadNextByte();
            switch (version)
            {
                case 1:
                    m_logPath = stream.ReadString();
                    m_logFilePrefix = stream.ReadString();
                    m_logFileExtension = stream.ReadString();
                    break;
                default:
                    throw new VersionNotFoundException("Unknown Version Code: " + version);
            }
        }

        public override void Validate()
        {
            if (m_logPath != string.Empty && !Directory.Exists(m_logPath))
                Directory.CreateDirectory(m_logPath);
            //Nothing to validate.
        }

    }
}


text:
using System.Reflection;

[assembly: AssemblyTitle("Leak.Peer.Coordinator.Tests")]
[assembly: AssemblyProduct("Leak.Peer.Coordinator.Tests")]
[assembly: AssemblyCopyright("Copyright © Adrian Macal 2016")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
//
//  c3dNode.h
//  HelloCpp
//
//  Created by apple on 14-1-4.
//
//

#ifndef __HelloCpp__c3dNode__
#define __HelloCpp__c3dNode__

#include <iostream>
using namespace std;
#include "cocos2d.h"
using namespace cocos2d;
#include "c3dMatrix.h"
#include "c3dMath.h"
#include "c3dVector.h"
#include "c3dCommonFunc.h"
#include "c3dGLMath.h"
#include "c3dCamera.h"
class Cc3dNode:public CCNode
{
public:
    Cc3dNode(){
        m_mat=unitMat();
        m_camera=NULL;
    }
    virtual~Cc3dNode(){
        if(m_camera)m_camera->release();
    }
    static Cc3dNode*create();
    virtual bool init();
    virtual void visit();
    virtual bool isSceneNode3D(){return false;}
    //transform
    virtual void setTransform3D(const Cc3dMatrix4&mat);
    virtual Cc3dMatrix4 getTransform3D();
    virtual Cc3dMatrix4 nodeToWorldTransform3D();
    virtual Cc3dMatrix4 worldToNodeTransform3D();
    virtual Cc3dMatrix4 nodeToParentTransform3D();
    virtual Cc3dVector4 convertToWorldSpace3D(const Cc3dVector4&v);
    virtual Cc3dVector4 convertToNodeSpace3D(const Cc3dVector4&v);
    //translate
    virtual void setPosition3D(const Cc3dVector4&position);
    virtual Cc3dVector4 getPosition3D()const;
    virtual Cc3dVector4 getWorldPosition3D();
    virtual void translate3D(const Cc3dVector4&translate);
    virtual void translateRelativeToParent3D(const Cc3dVector4&translate);
    //rotate
    virtual void setRotation3D(const Cc3dVector4&axis,float cosA,float sinA);
    virtual void setRotation3D(const Cc3dVector4&axis,float A);
    virtual Cc3dMatrix4 getRotation3D();
    virtual void rotate3D(const Cc3dVector4&axis,float cosA,float sinA);
    virtual void rotate3D(const Cc3dVector4&axis,float A);
    virtual void rotateRelativeToParent3D(const Cc3dVector4&axis,float cosA,float sinA);
    virtual void rotateRelativeToParent3D(const Cc3dVector4&axis,float A);
    //scale
    virtual void scale3D(float kx,float ky,float kz);
    virtual void scaleRelativeToParent3D(float kx,float ky,float kz);
    Cc3dCamera* getCamera3D(){return m_camera;}
    void setCamera3D(Cc3dCamera*camera);

protected:
    virtual void transform3D();
protected:
    Cc3dMatrix4 m_mat;//node to parent transform matrix
    Cc3dCamera*m_camera;

};
#endif /* defined(__HelloCpp__c3dNode__) */


text:
include Windows::Helper

def load_current_resource
  require 'win32ole'
  fonts_dir = WIN32OLE.new('WScript.Shell').SpecialFolders('Fonts')
  @current_resource = Chef::Resource::WindowsFont.new(@new_resource.name)
  @current_resource.file(win_friendly_path(::File.join(fonts_dir, @new_resource.file)))
  @current_resource
end

# Check to see if the font is installed
#
# === Returns
# <true>:: If the font is installed
# <false>:: If the font is not instaled
def font_exists?
  ::File.exist?(@current_resource.file)
end

def get_cookbook_font
  font_file = @new_resource.file
  cookbook_file font_file do
    action    :nothing
    cookbook  cookbook_name.to_s unless cookbook_name.nil?
    path      win_friendly_path(::File.join(ENV['TEMP'], font_file))
  end.run_action(:create)
end

def del_cookbook_font
  file ::File.join(ENV['TEMP'], @new_resource.file) do
    action :delete
  end
end

def install_font
  require 'win32ole'
  fonts_dir = WIN32OLE.new('WScript.Shell').SpecialFolders('Fonts')
  folder = WIN32OLE.new('Shell.Application').Namespace(fonts_dir)
  folder.CopyHere(win_friendly_path(::File.join(ENV['TEMP'], @new_resource.file)))
  Chef::Log.debug("Installing font: #{@new_resource.file}")
end

def action_install
  unless font_exists?
    get_cookbook_font
    install_font
    del_cookbook_font
    new_resource.updated_by_last_action(true)
  else
    Chef::Log.debug("Not installing font: #{@new_resource.file}, font already installed.")
    new_resource.updated_by_last_action(false)
  end
end


text:
#include "LFileListComponent.h"
#include "LFileTreeComponent.h"
#include "LMidiKeyboardComponent.h"
#include "LAudioThumbnail.h"
#include "LAudioPlayHead.h"
#include "LButton.h"
#include "LTextButton.h"
#include "LToggleButton.h"
#include "LAffineTransform.h"
#include "LAudioFile.h"
#include "LAudioFormat.h"
#include "LAudioSampleBuffer.h"
#include "LBigInteger.h"
#include "LColourGradient.h"
#include "LColour.h"
#include "LComponent.h"
#include "LFile.h"
#include "LGraphics.h"
#include "LImage.h"
#include "LJustification.h"
#include "LLine.h"
#include "LMemoryBlock.h"
#include "LMidiMessage.h"
#include "LMidiBuffer.h"
#include "LModifierKeys.h"
#include "LMouseCursor.h"
#include "LMouseEvent.h"
#include "LPath.h"
#include "LPoint.h"
#include "LPopupMenu.h"
#include "LRandom.h"
#include "LRectangle.h"
#include "LResult.h"
#include "LString.h"
#include "LTime.h"
#include "LURL.h"
#include "LValue.h"
#include "LValueTree.h"
#include "LLookAndFeel.h"
#include "LLabel.h"
#include "LSlider.h"
#include "LTimer.h"
#include "LFont.h"
#include "LBubbleMessageComponent.h"
#include "LAttributedString.h"
#include "LRange.h"
#include "LComponentPeer.h"
#include "LGlyphArrangement.h"
#include "LZipFile.h"
#include "LMemoryInputStream.h"
#include "LInputStream.h"
#include "LDrawable.h"
#include "LRelativeCoordinate.h"
#include "LExpression.h"
#include "LSparseSet.h"
#include "LAlertWindow.h"
#include "LComboBox.h"
#include "LTextEditor.h"
#include "LKeyPress.h"
#include "LThread.h"
#include "LThreadWithProgressWindow.h"
#include "LXmlElement.h"
#include "LTypeface.h"
#include "LBorderSize.h"
#include "LGlobalFunctions.h"
#include "LAsyncUpdater.h"

#endif


text:
package online.luhmirin.visionapiexperiment.preview.detector;

import java.util.List;

public interface DetectorListener<T> {

    void onResultFound(List<T> results);

}


text:
REPORTE DE EGRESADOS

                    <button class="btn btn-danger btn-md" id="cerrar">Salir</button>


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
    The MIT License (MIT)

    Copyright (c) 2010-2015 Carnegie Mellon University

    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.
-->

<resources>

    <string name="ask_QuitConfirmation">Выйти? Вы уверены?</string>

    <string name="btn_Match">Далее</string>
    <string name="btn_NoMatch">Нет совпадений</string>

    <string name="choice_NumUsers">%d пользователей</string>

    <string name="error_AllMembersMustUpgrade">Некоторые члены используете старую версию; все члены должны обновить до последней версии.</string>
    <string name="error_AllMembersMustUpgradeBadPushToken">Все члены должны обновить, некоторые используют устаревшие форматы ID уведомлений.</string>
    <string name="error_CorrectYourInternetConnection">Интернет не доступен, проверьте настройки.</string>
    <string name="error_ExchangeProtocolTimeoutExceeded">Время ожидания про обмене превышено, начать обмен заново.</string>
    <string name="error_HttpCode">HTTP oшибка сервера: %d</string>
    <string name="error_InvalidCommitVerify">Неправильные данные найдены в обмен. Начните обмен снова.</string>
    <string name="error_InvalidCommonUserId">Пожалуйста, введите целое положительное число.</string>
    <string name="error_LocalGroupCommitDiffer">Вы сообщили разницу в фраз. Начните обмен снова.</string>
    <string name="error_MinUsersRequired">Для обмена данными необходимо как минимум %d членов.</string>
    <string name="error_MoreDataThanUsers">Неожиданные данные найдены в обмен. Начните обмен снова.</string>
    <string name="error_NoDataToExchange">Обмен отсутствует необходимые данные.</string>
    <string name="error_NoWordListSelected">Вы должны выбрать одну из фраз, прежде чем продолжить.</string>
    <string name="error_OtherGroupCommitDiffer">Кто-то сообщил разницу в фразы. Начните обмен снова.</string>
    <string name="error_OutOfMemoryError">Слишком мало памяти для выполнения этой команды.</string>
    <string name="error_ServerAppMessage">Сообщение сервера: %s</string>
    <string name="error_ServerNotResponding">Сервер не отвечает.</string>
    <string name="error_TimeoutWaitingForAllMembers">Истек срок ожидания того, что некоторые члены группы добавят данные.</string>
    <string name="error_WebCancelledByUser">Пользователь отменил запрос к серверу.</string>

    <string name="help_size">Выберите количество людей, которые пытаются обмениваться данными вместе и нажмите кнопку ОК.</string>
    <string name="help_userid">Это число на экране используется для создания уникальной группы пользователей. Просмотрите номера на экранах всех пользователей, то все пользователи должны ввести тот же самый низкий номер и нажмите OK.</string>
    <string name="help_verify">Теперь вы должны соотнести одну из фраз из 3х слов со всеми пользователями. Каждый пользователь должен выбрать ту же общую фразу и нажать 'Далее'.</string>

    <string name="label_CompareScreensNDevices">Сравните экранов на %s устройств.</string>
    <string name="label_NumericModeHint">Не на английском языке</string>
    <string name="label_PromptInstruct">Этот номер используется для создания уникальной группы пользователей. Сравните, затем введите наименьший номер среди всех пользователей.</string>
    <string name="label_ReceivedNItems">получил %d пунктов</string>
    <string name="label_UserIdHint">Самый низкий</string>
    <string name="label_VerifyInstruct">У всех телефонов должна совпасть одна из фраз из трех слов. Сравните и выберите совпавшую фразу.</string>

    <string name="lib_name">SafeSlinger Обмен</string>

    <string name="prog_CollectingOthersCommitVerify">ожидается подтверждение от всех членов…</string>
    <string name="prog_CollectingOthersItems">ожидаем, чтобы присоединились все пользователи…</string>
    <string name="prog_ConstructingGroupKey">создание общего ключа…</string>
    <string name="prog_RequestingUserId">запрашивается членство…</string>

    <string name="title_size">Сколько пользователей в обмене?</string>
    <string name="title_userid">Группировка</string>
    <string name="title_verify">Проверить</string>

</resources>


text:
def is_logged_by_facebook(request):
    esta_logueado_por_facebook = request.session.get("is_logged_by_facebook")

    return {
        "logged_by_facebook" : True#esta_logueado_por_facebook
    }


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>error::basic_errors</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../boost_asio.html" title="Boost.Asio">
<link rel="up" href="../reference.html" title="Reference">
<link rel="prev" href="error__addrinfo_errors.html" title="error::addrinfo_errors">
<link rel="next" href="error__get_addrinfo_category.html" title="error::get_addrinfo_category">

Home
Libraries
People
FAQ
More

error::basic_errors

enum basic_errors

        Values

access_denied

              Permission denied.

address_family_not_supported

              Address family not supported by protocol.

address_in_use

              Address already in use.

already_connected

              Transport endpoint is already connected.

already_started

              Operation already in progress.

broken_pipe

              Broken pipe.

connection_aborted

              A connection has been aborted.

connection_refused

              Connection refused.

connection_reset

              Connection reset by peer.

bad_descriptor

              Bad file descriptor.

fault

              Bad address.

host_unreachable

              No route to host.

in_progress

              Operation now in progress.

interrupted

              Interrupted system call.

invalid_argument

              Invalid argument.

message_size

              Message too long.

name_too_long

              The name was too long.

network_down

              Network is down.

network_reset

              Network dropped connection on reset.

network_unreachable

              Network is unreachable.

no_descriptors

              Too many open files.

no_buffer_space

              No buffer space available.

no_memory

              Cannot allocate memory.

no_permission

              Operation not permitted.

no_protocol_option

              Protocol not available.

no_such_device

              No such device.

not_connected

              Transport endpoint is not connected.

not_socket

              Socket operation on non-socket.

operation_aborted

              Operation cancelled.

operation_not_supported

              Operation not supported.

shut_down

              Cannot send after transport endpoint shutdown.

timed_out

              Connection timed out.

try_again

              Resource temporarily unavailable.

would_block

              The socket is marked non-blocking and the requested operation would
              block.

        Requirements

        Header: boost/asio/error.hpp

        Convenience header: boost/asio.hpp

Copyright © 2003-2015 Christopher M.
      Kohlhoff

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package com.siva.websocket;

import org.glassfish.tyrus.client.ClientManager;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class DocClient {
    private static CountDownLatch messageLatch;
    private static AtomicInteger count = new AtomicInteger();
    private static final String SENT_MESSAGE = "Hello World";

    public static void main(String[] args) {
        try {
            messageLatch = new CountDownLatch(1);

            final ClientEndpointConfig cec = ClientEndpointConfig.Builder
                    .create().configurator(new ClientEndpointConfig.Configurator() {
                        public void beforeRequest(Map<String, List<String>> headers) {
                            System.out.println("Setting user cookie in beforeRequest ...");
                            ArrayList<String> value = new ArrayList<>();
                            value.add("user=TyrusUser");
                            headers.put("cookie", value);
                        }
                    }).build();
            ClientManager client = ClientManager.createClient();
            client.connectToServer(new Endpoint() {

                @Override
                public void onOpen(final Session session, EndpointConfig config) {
                    try {
                        session.addMessageHandler(new MessageHandler.Whole<String>() {

                            public void onMessage(String message) {
                                System.out.println("Received message: "
                                        + message);
                                try {
                                    if (count.get() > 10) {
                                        messageLatch.countDown();
                                        session.getBasicRemote().sendText("bye");
                                    }
                                    session.getBasicRemote().sendText(SENT_MESSAGE + " - " + count.incrementAndGet());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                            }
                        });
                        session.getBasicRemote().sendText(SENT_MESSAGE);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, cec, new URI("ws://localhost:8080/echo"));
            messageLatch.await(900, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
from django.core import management
import pytest
from model_mommy import mommy

from example.app.models import Channel, Video

@pytest.mark.django_db
def test_searchable_has_search():
    management.call_command("sync_es")
    channel = mommy.make(Channel)
    assert hasattr(channel, "search")

@pytest.mark.django_db
def test_searchable_simple_search():
    management.call_command("sync_es")
    onion = mommy.make(Channel, name="The Onion")
    _ = mommy.make(Channel, _quantity=20)
    results = Channel.search(query="onion")
    assert len(results) == 1
    assert results[0].name == onion.name

@pytest.mark.django_db
def test_searchable_filtered_search():
    management.call_command("sync_es")
    onion = mommy.make(Channel, name="The Onion")
    avc = mommy.make(Channel, name="The A.V. Club")
    _ = mommy.make(Video, channel=onion, _quantity=20)
    _ = mommy.make(Video, channel=avc, _quantity=10)
    results = Video.search(filters={"channel__name__raw": onion.name})
    assert len(results) == 20

@pytest.mark.django_db
def test_searchable_ordered_search():
    management.call_command("sync_es")
    _ = mommy.make(Channel, _quantity=10)
    results = Channel.search(ordering=["-name", ])
    current_result = results[0]
    for result in results[1:]:
        assert current_result.name.lower() >= result.name.lower()
        current_result = result

@pytest.mark.django_db
def test_searchable_complete_search():
    management.call_command("sync_es")
    onion = mommy.make(Channel, name="The Onion")
    avc = mommy.make(Channel, name="The A.V. Club")
    video = mommy.make(Video, channel=onion, name="Some Test Video")
    _ = mommy.make(Video, channel=onion, _quantity=20)
    _ = mommy.make(Video, channel=avc, _quantity=10)
    results = Video.search(
        query="test video",
        filters={"channel__name__raw": onion.name},
        ordering=["-name"]
    )
    assert len(results) > 0
    current_result = results[0]
    assert current_result.name == video.name
    for result in results[1:]:
        assert current_result.name.lower() >= result.name.lower()
        current_result = result

@pytest.mark.django_db
def test_aggregateable_has_search():
    management.call_command("sync_es")
    video = mommy.make(Video)
    assert hasattr(video, "search")

@pytest.mark.django_db
def test_aggregateable_has_get_aggregates():
    management.call_command("sync_es")
    video = mommy.make(Video)
    assert hasattr(video, "get_aggregates")

@pytest.mark.django_db
def test_aggregateable_get_aggregates_simple():
    management.call_command("sync_es")
    _ = mommy.make(Channel, _quantity=3)
    results = Video.get_aggregates()
    assert len(results) == 1
    assert "channel__name__raw" in results
    assert len(results["channel__name__raw"]) == 3

@pytest.mark.django_db
def test_aggregateable_get_aggregates_with_query():
    management.call_command("sync_es")
    onion = mommy.make(Channel, name="The Onion")
    avc = mommy.make(Channel, name="The A.V. Club")
    _ = mommy.make(Video, channel=onion, name="Another Test Video")
    _ = mommy.make(Video, channel=onion, _quantity=5)
    _ = mommy.make(Video, channel=avc, _quantity=5)
    results = Video.get_aggregates(query="test video")
    assert results == {
        "channel__name__raw": {
            "The Onion": 1
        }
    }

@pytest.mark.django_db
def test_aggregateable_get_aggregates_with_filters():
    management.call_command("sync_es")
    onion = mommy.make(Channel, name="The Onion")
    avc = mommy.make(Channel, name="The A.V. Club")
    _ = mommy.make(Video, channel=onion, name="Another Test Video")
    _ = mommy.make(Video, channel=onion, _quantity=5)
    _ = mommy.make(Video, channel=avc, _quantity=5)
    results = Video.get_aggregates(filters={"channel__name__raw": "barf"})
    assert results == {}

@pytest.mark.django_db
def test_aggregateable_get_aggregates_complete():
    management.call_command("sync_es")
    onion = mommy.make(Channel, name="The Onion")
    avc = mommy.make(Channel, name="The A.V. Club")
    for index in range(10):
        _ = mommy.make(Video, channel=onion, name="Looped Video {}".format(index))
    _ = mommy.make(Video, channel=onion, _quantity=5)
    for index in range(10):
        _ = mommy.make(Video, channel=avc, name="Looped Video {}".format(index+100))
    results = Video.get_aggregates(
        query="looped",
        filters={"channel__name__raw": onion.name}
    )
    assert len(results) == 0


text:
package org.my4x.utilities.svg;

import org.fest.assertions.Assertions;
import org.junit.Test;
import org.my4x.utilities.svg.builder.SVGCircleBuilder;

public class SVGCircleBuilderTest {

	@Test
	public void test() {
		String circleStr = new SVGCircleBuilder("circleid").withFill("red").withCoords(10,10,20).build();
		Assertions.assertThat(circleStr).isNotEmpty().isEqualTo("<circle id=\"circleid\" cx=\"10\" cy=\"10\" r=\"20\" style=\"fill:red;stroke:black\" />");
	}

}


text:
L'operatore `typeof` (assieme a [`instanceof`](#types.instanceof)) è
probabilmente il più grande difetto di progettazione di JavaScript,
dato che è quasi **completamente inusabile**.

Sebbene `instanceof` abbia ancora limitati casi d'uso, `typeof` ha realmente
un solo caso d'uso, che **non** è quello di verificare il tipo di un oggetto.

> **Nota:** mentre `typeof` può anche essere richiamato usando una sintassi
> simile a quella di una funzione (ad esempio, `typeof(obj)`), questa non è
> una funzione. Le parentesi funzionano normalmente e il valore di ritorno
> viene usato come operando per l'operatore `typeof`. **Non** esiste una
> funzione `typeof`.

### Tabella dei tipi di JavaScript

    Valore              Classe     Tipo
    -------------------------------------
    "foo"               String     string
    new String("foo")   String     object
    1.2                 Number     number
    new Number(1.2)     Number     object
    true                Boolean    boolean
    new Boolean(true)   Boolean    object
    new Date()          Date       object
    new Error()         Error      object
    [1,2,3]             Array      object
    new Array(1, 2, 3)  Array      object
    new Function("")    Function   function
    /abc/g              RegExp     object (function in Nitro/V8)
    new RegExp("meow")  RegExp     object (function in Nitro/V8)
    {}                  Object     object
    new Object()        Object     object

In questa tabella, *Tipo* fa riferimento al valore ritornato dall'operatore `typeof`.
Come si può chiaramente vedere, questo valore è tutto fuorchè affidabile.

*Classe* si riferisce al valore della proprietà interna `[[Class]]` di un oggetto.

> **Da specifiche:** il valore di `[[Class]]` può essere una delle seguenti
> stringhe: `Arguments`, `Array`, `Boolean`, `Date`, `Error`, `Function`,
> `JSON`, `Math`, `Number`, `Object`, `RegExp`, `String`.

Per ottenere il valore di `[[Class]]`, bisogna usare il metodo `toString` di
`Object.prototype`.

### La classe di un oggetto

Le specifiche forniscono esattamente un modo per accedere al valore di
`[[Class]]`, con l'uso di `Object.prototype.toString`.

    function is(type, obj) {
        var clas = Object.prototype.toString.call(obj).slice(8, -1);
        return obj !== undefined && obj !== null && clas === type;
    }

    is('String', 'test'); // true
    is('String', new String('test')); // true

Nel esempio qui sopra, `Object.prototype.toString` viene chiamato con il valore
di [this](#function.this) impostato all'oggetto di cui si vuole ottenere il
valore di `[[Class]]`.

> **ES5 Nota:** per comodità, il valore di ritorno di `Object.prototype.toString`
> per `null` e `undefined` è stato **cambiato** da `Object` a `Null` e
> `Undefined` in ECMAScript 5.

### Testare variabili non definite

    typeof foo !== 'undefined'

Questo esempio verificherà se `foo` è stata attualmente dichiarata oppure no.
Un semplice referenziamento ad essa risulterebbe in un `ReferenceError`.
Questo è l'unico caso in cui `typeof` è utile a qualcosa.

### In conclusione

Per verificare il tipo di un oggetto, è altamente raccomandato l'utilizzo di
`Object.prototype.toString`, dato che questo è il solo modo affidabile per
fare ciò. Come mostrato nella tabella precedente, alcuni valori di ritorno
di `typeof` non sono definiti nelle specifiche, e ciò dimostra come essi
potrebbero differire tra implementazioni differenti.

A meno che non si debba verificare se una variabile è definta, `typeof`
dovrebbe essere evitato.


text:
import json, hmac, hashlib, time, requests, base64
from requests.auth import AuthBase

class CoinbaseAuth(AuthBase):
    SIGNATURE_HTTP_HEADER = 'CB-ACCESS-SIGN'
    TIMESTAMP_HTTP_HEADER = 'CB-ACCESS-TIMESTAMP'
    KEY_HTTP_HEADER = 'CB-ACCESS-KEY'
    PASSPHRASE_HTTP_HEADER = 'CB-ACCESS-PASSPHRASE'

    def __init__(self, api_key, secret_key, passphrase):
        self.api_key = api_key
        self.secret_key = secret_key
        self.passphrase = passphrase

    def __call__(self, request):
        #Add headers
        request.headers[CoinbaseAuth.KEY_HTTP_HEADER] = self.api_key
        request.headers[CoinbaseAuth.PASSPHRASE_HTTP_HEADER] = self.passphrase
        timestamp = str(time.time())
        request.headers[CoinbaseAuth.TIMESTAMP_HTTP_HEADER] = timestamp

        #add signature
        method = request.method
        path = request.path_url
        content = request.body
        message = timestamp + method + path
        if content:
            message += content
        print message
        hmac_key = base64.b64decode(self.secret_key)
        sig = hmac.new(hmac_key, message, hashlib.sha256)
        sig_b64 = sig.digest().encode("base64").rstrip("\n")

        #Add signature header
        request.headers[CoinbaseAuth.SIGNATURE_HTTP_HEADER] = sig_b64
        return request


text:
class Pry
  class Command::Whereami < Pry::ClassCommand

    class << self
      attr_accessor :method_size_cutoff
    end

    @method_size_cutoff = 30

    match 'whereami'
    description 'Show code surrounding the current context.'
    group 'Context'

    banner <<-'BANNER'
      Usage: whereami [-qn] [LINES]

      Describe the current location. If you use `binding.pry` inside a method then
      whereami will print out the source for that method.

      If a number is passed, then LINES lines before and after the current line will be
      shown instead of the method itself.

      The `-q` flag can be used to suppress error messages in the case that there's
      no code to show. This is used by pry in the default before_session hook to show
      you when you arrive at a `binding.pry`.

      The `-n` flag can be used to hide line numbers so that code can be copy/pasted
      effectively.

      When pry was started on an Object and there is no associated method, whereami
      will instead output a brief description of the current object.
    BANNER

    def setup
      @file = expand_path(target.eval('__FILE__'))
      @line = target.eval('__LINE__')
      @method = Pry::Method.from_binding(target)
    end

    def options(opt)
      opt.on :q, :quiet,             "Don't display anything in case of an error"
      opt.on :n, :"no-line-numbers", "Do not display line numbers"
      opt.on :m, :"method", "Show the complete source for the current method."
      opt.on :c, :"class", "Show the complete source for the current class or module."
      opt.on :f, :"file", "Show the complete source for the current file."
    end

    def code
      @code ||= if opts.present?(:m)
                  method_code or raise CommandError, "Cannot find method code."
                elsif opts.present?(:c)
                  class_code or raise CommandError, "Cannot find class code."
                elsif opts.present?(:f)
                  Pry::Code.from_file(@file)
                elsif args.any?
                  code_window
                else
                  default_code
                end
    end

    def code?
      !!code
    rescue MethodSource::SourceNotFoundError
      false
    end

    def bad_option_combination?
      [opts.present?(:m), opts.present?(:f),
       opts.present?(:c), args.any?].count(true) > 1
    end

    def location
      "#{@file} @ line #{@line} #{@method && @method.name_with_owner}"
    end

    def process
      if bad_option_combination?
        raise CommandError, "Only one of -m, -c, -f, and  LINES may be specified."
      end

      if nothing_to_do?
        return
      elsif internal_binding?(target)
        handle_internal_binding
        return
      end

      set_file_and_dir_locals(@file)

      out = "\n#{text.bold('From:')} #{location}:\n\n" <<
        code.with_line_numbers(use_line_numbers?).with_marker(marker).to_s << "\n"

      stagger_output(out)
    end

    private

    def nothing_to_do?
      opts.quiet? && (internal_binding?(target) || !code?)
    end

    def use_line_numbers?
      !opts.present?(:n)
    end

    def marker
      !opts.present?(:n) && @line
    end

    def top_level?
      target_self == TOPLEVEL_BINDING.eval("self")
    end

    def handle_internal_binding
      if top_level?
        output.puts "At the top level."
      else
        output.puts "Inside #{Pry.view_clip(target_self)}."
      end
    end

    def small_method?
      @method.source_range.count < self.class.method_size_cutoff
    end

    def default_code
      if method_code && small_method?
        method_code
      else
        code_window
      end
    end

    def code_window
      Pry::Code.from_file(@file).around(@line, window_size)
    end

    def method_code
      return @method_code if @method_code

      if valid_method?
        @method_code = Pry::Code.from_method(@method)
      end
    end

    # This either returns the `target_self`
    # or it returns the class of `target_self` if `target_self` is not a class.
    # @return [Pry::WrappedModule]
    def target_class
      target_self.is_a?(Module) ? Pry::WrappedModule(target_self) :
        Pry::WrappedModule(target_self.class)
    end

    def class_code
      return @class_code if @class_code

      mod = @method ? Pry::WrappedModule(@method.owner) : target_class

      idx = mod.candidates.find_index { |v| expand_path(v.source_file) == @file }
      @class_code = idx && Pry::Code.from_module(mod, idx)
    end

    def valid_method?
      @method && @method.source? && expand_path(@method.source_file) == @file &&
        @method.source_range.include?(@line)
    end

    def expand_path(f)
      return if !f

      if Pry.eval_path == f
        f
      else
        File.expand_path(f)
      end
    end

    def window_size
      if args.empty?
        Pry.config.default_window_size
      else
        args.first.to_i
      end
    end
  end

  Pry::Commands.add_command(Pry::Command::Whereami)
  Pry::Commands.alias_command '@', 'whereami'
end


text:
namespace pb {

	namespace math {
		template <typename T> class Scalar;
	}

	// Base template
	template <typename T>
	class ExprTraits {
	public:
		typedef T const & ExprReference;     // Refer as constant reference
	};

	// Specialization for scalars
	template <typename T>
	class ExprTraits<pb::math::Scalar<T> > {
	public:
		typedef pb::math::Scalar<T> ExprReference;  // Refer as value
	};

} // pb namespace


text:
'''

    whooshalchemy flask extension
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    Adds whoosh indexing capabilities to SQLAlchemy models for Flask
    applications.

    :copyright: (c) 2012 by Karl Gyllstrom
    :license: BSD (see LICENSE.txt)

'''

from __future__ import absolute_import

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_testing import TestCase
import flask_whooshalchemy as wa
from whoosh.analysis import StemmingAnalyzer, DoubleMetaphoneFilter

import datetime
import os
import tempfile
import shutil

db = SQLAlchemy()

class BlogishBlob(object):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.Text)
    content = db.Column(db.String)
    blurb = db.Column(db.Unicode)
    ignored = db.Column(db.Unicode)
    created = db.Column(db.DateTime(), default=datetime.datetime.utcnow())

    def __repr__(self):
        return '{0}(title={1})'.format(self.__class__.__name__, self.title)

def _after_flush(app, changes):
    from sqlalchemy.orm import EXT_CONTINUE
    return EXT_CONTINUE

class ObjectA(db.Model, BlogishBlob):
    __tablename__ = 'objectA'
    __searchable__ = ['title', 'content', 'blurb']

class ObjectB(db.Model, BlogishBlob):
    __tablename__ = 'objectB'
    __searchable__ = ['title', 'content', 'content']  # dup intentional

class ObjectC(db.Model, BlogishBlob):
    __tablename__ = 'objectC'
    __searchable__ = ['title', 'field_that_doesnt_exist']

class ObjectD(db.Model, BlogishBlob):
    __tablename__ = 'objectD'
    __searchable__ = ['title']
    __analyzer__ = StemmingAnalyzer() | DoubleMetaphoneFilter()

class Tests(TestCase):
    DATABASE_URL = 'sqlite://'
    TESTING = True

    def create_app(self):
        tmp_dir = tempfile.mkdtemp()

        app = Flask(__name__)

        app.config['WHOOSH_BASE'] = os.path.join(tmp_dir, 'whoosh')

        return app

    def setUp(self):
        db.init_app(self.app)
        db.create_all()

    def tearDown(self):
        try:
            shutil.rmtree(self.app.config['WHOOSH_BASE'])
        except OSError as e:
            if e.errno != 2:  # code 2 - no such file or directory
                raise

        db.drop_all()

    def test_all(self):
        title1 = u'a slightly long title'
        title2 = u'another title'
        title3 = u'wow another title'

        obj = ObjectA(title=u'title', blurb='this is a blurb')
        db.session.add(obj)
        db.session.commit()

        self.assertEqual(len(list(ObjectA.query.whoosh_search('blurb'))), 1)
        db.session.delete(obj)
        db.session.commit()

        db.session.add(ObjectA(title=title1, content=u'hello world', ignored=u'no match'))
        db.session.commit()

        self.assertEqual(len(list(ObjectA.query.whoosh_search('what'))), 0)
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'no match'))), 0)
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'title'))), 1)
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'hello'))), 1)

        db.session.add(ObjectB(title=u'my title', content=u'hello world'))
        db.session.commit()

        # make sure does not interfere with ObjectA's results
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'what'))), 0)
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'title'))), 1)
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'hello'))), 1)

        self.assertEqual(len(list(ObjectB.query.whoosh_search(u'what'))), 0)
        self.assertEqual(len(list(ObjectB.query.whoosh_search(u'title'))), 1)
        self.assertEqual(len(list(ObjectB.query.whoosh_search(u'hello'))), 1)

        obj2 = ObjectA(title=title2, content=u'a different message')
        db.session.add(obj2)
        db.session.commit()

        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'what'))), 0)
        l = list(ObjectA.query.whoosh_search(u'title'))
        self.assertEqual(len(l), 2)

        # ranking should always be as follows, since title2 should have a higher relevance score

        self.assertEqual(l[0].title, title2)
        self.assertEqual(l[1].title, title1)

        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'hello'))), 1)
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'message'))), 1)

        self.assertEqual(len(list(ObjectB.query.whoosh_search(u'what'))), 0)
        self.assertEqual(len(list(ObjectB.query.whoosh_search(u'title'))), 1)
        self.assertEqual(len(list(ObjectB.query.whoosh_search(u'hello'))), 1)
        self.assertEqual(len(list(ObjectB.query.whoosh_search(u'message'))), 0)

        db.session.add(ObjectA(title=title3, content=u'a different message'))
        db.session.commit()

        l = list(ObjectA.query.whoosh_search(u'title'))
        self.assertEqual(len(l), 3)
        self.assertEqual(l[0].title, title2)
        self.assertEqual(l[1].title, title3)
        self.assertEqual(l[2].title, title1)

        db.session.delete(obj2)
        db.session.commit()

        l = list(ObjectA.query.whoosh_search(u'title'))
        self.assertEqual(len(l), 2)
        self.assertEqual(l[0].title, title3)
        self.assertEqual(l[1].title, title1)

        two_days_ago = datetime.date.today() - datetime.timedelta(2)

        title4 = u'a title that is significantly longer than the others'

        db.session.add(ObjectA(title=title4, created=two_days_ago))
        db.session.commit()

        one_day_ago = datetime.date.today() - datetime.timedelta(1)

        recent = list(ObjectA.query.whoosh_search(u'title')
                .filter(ObjectA.created >= one_day_ago))

        self.assertEqual(len(recent), 2)
        self.assertEqual(l[0].title, title3)
        self.assertEqual(l[1].title, title1)

        three_days_ago = datetime.date.today() - datetime.timedelta(3)

        l = list(ObjectA.query.whoosh_search(u'title')
                .filter(ObjectA.created >= three_days_ago))

        self.assertEqual(len(l), 3)
        self.assertEqual(l[0].title, title3)
        self.assertEqual(l[1].title, title1)
        self.assertEqual(l[2].title, title4)

        title5 = u'title with title as frequent title word'

        db.session.add(ObjectA(title=title5))
        db.session.commit()

        l = list(ObjectA.query.whoosh_search(u'title'))
        self.assertEqual(len(l), 4)
        self.assertEqual(l[0].title, title5)
        self.assertEqual(l[1].title, title3)
        self.assertEqual(l[2].title, title1)
        self.assertEqual(l[3].title, title4)

        # test limit
        l = list(ObjectA.query.whoosh_search(u'title', limit=2))
        self.assertEqual(len(l), 2)
        self.assertEqual(l[0].title, title5)
        self.assertEqual(l[1].title, title3)

        # XXX should replace this with a new function, but I can't figure out
        # how to do this cleanly with flask sqlalchemy and testing

        db.drop_all()
        db.create_all()

        title1 = u'my title'
        db.session.add(ObjectA(title=title1, content=u'hello world'))
        db.session.commit()

        l = list(ObjectA.query.whoosh_search(u'title'))
        self.assertEqual(len(l), 1)

        l = list(ObjectA.query.whoosh_search(u'hello'))
        self.assertEqual(len(l), 1)

        l = list(ObjectA.query.whoosh_search(u'title', fields=('title',)))
        self.assertEqual(len(l), 1)
        l = list(ObjectA.query.whoosh_search(u'hello', fields=('title',)))
        self.assertEqual(len(l), 0)

        l = list(ObjectA.query.whoosh_search(u'title', fields=('content',)))
        self.assertEqual(len(l), 0)
        l = list(ObjectA.query.whoosh_search(u'hello', fields=('content',)))
        self.assertEqual(len(l), 1)

        l = list(ObjectA.query.whoosh_search(u'hello dude', fields=('content',), or_=True))
        self.assertEqual(len(l), 1)

        l = list(ObjectA.query.whoosh_search(u'hello dude', fields=('content',), or_=False))
        self.assertEqual(len(l), 0)

        # new function: test chaining
        db.drop_all()
        db.create_all()

        db.session.add(ObjectA(title=u'title one', content=u'a poem'))
        db.session.add(ObjectA(title=u'title two', content=u'about testing'))
        db.session.add(ObjectA(title=u'title three', content=u'is delightfully tested'))
        db.session.add(ObjectA(title=u'four', content=u'tests'))
        db.session.commit()

        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'title'))), 3)
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'test'))), 3)

        # chained query, operates as AND
        self.assertEqual(len(list(ObjectA.query.whoosh_search(u'title').whoosh_search(u'test'))),
                2)

    def test_invalid_attribute(self):
        db.session.add(ObjectC(title=u'my title', content=u'hello world'))
        self.assertRaises(AttributeError, db.session.commit)

    def test_default_analyzer(self):
        db.session.add(ObjectA(title=u'jumping', content=u''))
        db.session.commit()
        assert ['jumping'] == [obj.title for obj in ObjectA.query.whoosh_search(u'jump')]

    def test_custom_analyzer(self):
        from whoosh.analysis import SimpleAnalyzer
        self.app.config['WHOOSH_ANALYZER'] = SimpleAnalyzer()
        db.init_app(self.app)
        db.create_all()
        db.session.add(ObjectA(title=u'jumping', content=u''))
        db.session.commit()
        assert not list(ObjectA.query.whoosh_search(u'jump'))
        assert ['jumping'] == [obj.title for obj in ObjectA.query.whoosh_search(u'jumping')]

        db.session.add(ObjectD(title=u'Travelling', content=u'Stemming'))
        db.session.add(ObjectD(title=u'travel', content=u'Unstemmed and normal'))
        db.session.add(ObjectD(title=u'trevel', content=u'Mispelt'))

        db.session.commit()
        # When mispelt on either the indexed side or the query side, they should all return 3 due to the DoubleMetaphoneFilter
        self.assertEqual(len(list(ObjectD.query.whoosh_search('travelling'))), 3)
        self.assertEquals(len(list(ObjectD.query.whoosh_search('trovel'))), 3)

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


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <RelativeLayout
        android:id="@+id_page_adapter_view/top"
        android:layout_width="fill_parent"
        android:layout_height="48dp"
        android:background="@drawable/title_bar"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id_page_adapter_view/plus_image"
            android:layout_width="48dp"
            android:layout_height="48dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="8dp"
            android:contentDescription="@string/noimage"
            android:src="@drawable/down" />

        <TextView
            android:id="@+id_page_adapter_view/text"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginLeft="5dp"
            android:layout_toLeftOf="@id_page_adapter_view/plus_image"
            android:gravity="left|center_vertical"
            android:textColor="@color/title_color"
            android:textSize="20dp" />
    </RelativeLayout>

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id_page_adapter_view/top"
        android:background="@color/default_back_color"
        android:fadingEdge="none" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@color/default_back_color" >

            <ImageView
                android:id="@+id_catalog_page_adapter/image"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginTop="5dp"
                android:adjustViewBounds="true"
                android:contentDescription="@string/noimage"
                android:scaleType="fitCenter" />

            <WebView
                android:id="@+id_catalog_page_adapter/web"
                android:layout_width="wrap_content"
                android:layout_height="fill_parent"
                android:layout_below="@+id_catalog_page_adapter/image"
                android:scrollbarStyle="insideOverlay" />
        </RelativeLayout>
    </ScrollView>

</RelativeLayout>


text:
    <title>worker</title>

worker

    https://github.com/node-linda/linda


text:
Ti.include('../common.js');

var data = [
	{title:'Local', test:'../examples/sound_local.js'},
	{title:'Local with File', test:'../examples/sound_file.js'},
	{title:'Local with File URL', test:'../examples/sound_file_url.js'},
	{title:'Remote URL', test:'../examples/sound_remote_url.js'},
	{title:'Remote Streaming', test:'../examples/sound_remote.js'}

];

Titanium.UI.currentWindow.add(NookKS.createNavigationTableView(data));


text:
def provides_facts():
    """
    Returns a dictionary keyed on the facts provided by this module. The value
    of each key is the doc string describing the fact.
    """
    return {'ifd_style': "The type of physical interface (ifd) supported by "
                         "the device. Choices are 'CLASSIC' or 'SWITCH'.", }

def get_facts(device):
    """
    Determines ifd_style fact based on the personality.
    """
    ifd_style = 'CLASSIC'

    if device.facts['personality'] == 'SWITCH':
        ifd_style = 'SWITCH'

    return {'ifd_style': ifd_style, }


text:
BUILD_DIR := build

CLAR_DIR := vendor/clar

TERMBOX_DIR := vendor/termbox
TERMBOX_INSTALL_DIR := $(BUILD_DIR)/termbox
TERMBOX_BUILD_DIR := $(TERMBOX_INSTALL_DIR)/build
TERMBOX_HEADER := $(TERMBOX_INSTALL_DIR)/include/termbox.h
TERMBOX_LIBRARY := $(TERMBOX_INSTALL_DIR)/lib/libtermbox.a
TERMBOX := $(TERMBOX_HEADER) $(TERMBOX_LIBRARY)

LIBCLIPBOARD_DIR := vendor/libclipboard
LIBCLIPBOARD_INSTALL_DIR := $(BUILD_DIR)/libclipboard
LIBCLIPBOARD_BUILD_DIR := $(LIBCLIPBOARD_INSTALL_DIR)/build
LIBCLIPBOARD_HEADER := $(LIBCLIPBOARD_INSTALL_DIR)/include/libclipboard.h
LIBCLIPBOARD_LIBRARY := $(LIBCLIPBOARD_INSTALL_DIR)/lib/libclipboard.a
LIBCLIPBOARD := $(LIBCLIPBOARD_HEADER) $(LIBCLIPBOARD_LIBRARY)

PCRE2_DIR := vendor/pcre2
PCRE2_INSTALL_DIR := $(BUILD_DIR)/pcre2
PCRE2_BUILD_DIR := $(PCRE2_INSTALL_DIR)/build
PCRE2_HEADER := $(PCRE2_INSTALL_DIR)/include/pcre2.h
PCRE2_LIBRARY := $(PCRE2_INSTALL_DIR)/lib/libpcre2-8.a
PCRE2 := $(PCRE2_HEADER) $(PCRE2_LIBRARY)

OS := $(shell uname)
ifeq ($(OS),Darwin)
LIBCLIPBOARD_LDFLAGS := -framework Cocoa
else ifeq ($(OS),Linux)
LIBCLIPBOARD_LDFLAGS := -lxcb -lpthread
endif
LDFLAGS := $(LIBCLIPBOARD_LDFLAGS)

THIRD_PARTY_HEADERS := $(TERMBOX_HEADER) $(LIBCLIPBOARD_HEADER) $(PCRE2_HEADER)
THIRD_PARTY_LIBRARIES := $(TERMBOX_LIBRARY) $(LIBCLIPBOARD_LIBRARY) $(PCRE2_LIBRARY)

WARNING_CFLAGS := -Wall -Wextra -Werror

COVERAGE_CFLAGS := $(if $(COVERAGE),-coverage)
ASAN_CFLAGS := $(if $(ASAN),-fsanitize=address -fsanitize-recover=address)
LDFLAGS += $(COVERAGE_CFLAGS) $(ASAN_CFLAGS)

# Use C11 for anonymous structs.
COMMON_CFLAGS := -g -std=c11 -D_GNU_SOURCE -DPCRE2_CODE_UNIT_WIDTH=8 \
	$(addprefix -isystem ,$(dir $(THIRD_PARTY_HEADERS))) \
	$(WARNING_CFLAGS)

CFLAGS := $(COMMON_CFLAGS) $(COVERAGE_CFLAGS) $(ASAN_CFLAGS)

TEST_CFLAGS := $(COMMON_CFLAGS) -Wno-missing-prototypes \
	-I. -isystem $(CLAR_DIR) -I$(BUILD_DIR)/tests \
	-DCLAR_FIXTURE_PATH=\"$(abspath tests/testdata)\"

PROG := badavi
SRCS := $(wildcard *.c)
HDRS := $(wildcard *.h)
OBJS := $(SRCS:.c=.o)
OBJS := $(addprefix $(BUILD_DIR)/,$(OBJS))
DEPS := $(OBJS:.o=.d)

TEST_PROG := $(PROG)_test
TEST_SRCS := $(wildcard tests/*.c)
TEST_OBJS := $(TEST_SRCS:.c=.o)
TEST_OBJS := $(addprefix $(BUILD_DIR)/,$(TEST_OBJS))
TEST_DEPS := $(TEST_OBJS:.o=.d)
TEST_OBJS += $(filter-out $(BUILD_DIR)/main.o,$(OBJS))
TEST_OBJS += $(BUILD_DIR)/tests/clar.o

.PHONY: $(PROG)
$(PROG): $(BUILD_DIR)/$(PROG)

.PHONY: $(TEST_PROG)
$(TEST_PROG): $(BUILD_DIR)/$(TEST_PROG)

.PHONY: test
test: $(BUILD_DIR)/$(TEST_PROG)
	./$^

.PHONY: coverage
coverage:
	$(MAKE) BUILD_DIR=coverage-build COVERAGE=1 $(TEST_PROG)
	lcov -q -c -i -d coverage-build -o coverage-build/coverage.base
	./coverage-build/$(TEST_PROG)
	lcov -q -c -d coverage-build -o coverage-build/coverage.run
	lcov -q -d . -a coverage-build/coverage.base -a coverage-build/coverage.run -o coverage-build/coverage.total
	genhtml -q --no-branch-coverage -o $@ coverage-build/coverage.total

.PHONY: asan
asan:
	$(MAKE) BUILD_DIR=asan-build ASAN=1 $(PROG)

.PHONY: test-asan
test-asan:
	$(MAKE) BUILD_DIR=asan-build ASAN=1 $(TEST_PROG)
	./asan-build/$(TEST_PROG)

# Enable second expansion to access automatic variables in prerequisite lists.
# In particular, we write $$(@D)/. to refer to the directory of the target.
# Note the trailing dot -- make 3.81 seems to ignore trailing slashes.
.SECONDEXPANSION:

$(BUILD_DIR)/.:
	mkdir -p $@

$(BUILD_DIR)%/.:
	mkdir -p $@

define cmake_dep
$$($(1)_INSTALL_DIR): | $$$$(@D)/. $$($(1)_BUILD_DIR)/.
	(cd $$($(1)_BUILD_DIR) && \
	  cmake -DCMAKE_INSTALL_PREFIX=$$(abspath $$@) $(2) $$(abspath $$($(1)_DIR)) && \
	  $(MAKE) && \
	  $(MAKE) install)

$$($(1)): $$($(1)_INSTALL_DIR)
endef

$(eval $(call cmake_dep,TERMBOX,-DBUILD_SHARED_LIBS=OFF -DBUILD_DEMOS=OFF))
$(eval $(call cmake_dep,LIBCLIPBOARD))
$(eval $(call cmake_dep,PCRE2,-DPCRE2_BUILD_PCRE2GREP=OFF -DPCRE2_BUILD_TESTS=OFF))

# We define the rule for test objects first because in GNU make 3.81, when
# multiple pattern rules match a target, the first one is chosen. This is
# different than 3.82 and later, where the most specific one (i.e. the one with
# the shortest stem) is chosen.
$(BUILD_DIR)/tests/%.o: tests/%.c $(THIRD_PARTY_HEADERS) | $$(@D)/.
	$(CC) -MMD -MP $(TEST_CFLAGS) -c -o $@ $<

$(BUILD_DIR)/tests/clar.o: \
	$(CLAR_DIR)/clar.c $(BUILD_DIR)/tests/clar.suite | $$(@D)/.
	$(CC) $(TEST_CFLAGS) -w -c -o $@ $<

$(BUILD_DIR)/tests/clar.suite: $(TEST_SRCS) | $$(@D)/.
	$(CLAR_DIR)/generate.py --output=$(@D) tests

$(BUILD_DIR)/%.o: %.c $(THIRD_PARTY_HEADERS) | $$(@D)/.
	$(CC) -MMD -MP -o $@ -c $< $(CFLAGS)

$(BUILD_DIR)/%.pp: %.c $(THIRD_PARTY_HEADERS) | $$(@D)/.
	$(CC) -E -o $@ -c $< $(CFLAGS)

-include $(DEPS)
-include $(TEST_DEPS)

$(BUILD_DIR)/$(PROG): $(OBJS) $(THIRD_PARTY_LIBRARIES) | $$(@D)/.
	$(CC) -o $@ $^ $(LDFLAGS)

$(BUILD_DIR)/$(TEST_PROG): $(TEST_OBJS) $(filter-out $(TERMBOX_LIBRARY),$(THIRD_PARTY_LIBRARIES)) | $$(@D)/.
	$(CC) -o $@ $^ $(LDFLAGS)

tags: $(SRCS) $(HDRS)
	ctags $^


text:
package.loaded.string = nil; require 'string'

TestString = {}

function TestString:test_tonumber()
  lu.assertEquals(('asdf'):tonumber(), nil)
  lu.assertEquals(('10'):tonumber(), 10)
  lu.assertEquals(('10'):tonumber(16), 16)
end

function TestString:test_format_operator()
  lu.assertEquals('%d %d %d' % 1 % 2, '1 2 %d')
  lu.assertEquals('%d %d %d' % 1 % 2 % 3, '1 2 3')
  lu.assertEquals('%d %d %d' % { 1, 2, 3 }, '1 2 3')
end

function TestString:test_count()
  lu.assertEquals(('aaaaaa'):count('aa'), 3)
  lu.assertEquals(('a=1, b=23, c=45'):count('%d'), 5)
  lu.assertEquals(('a=1, b=23, c=45'):count('%d+'), 3)
end

function TestString:test_interpolate()
  local data = { d = 1; f = 2.2; s = "foo"; r = "${d}${d}"; R = "f" }
  lu.assertEquals(('${d} ${f} ${s}'):interpolate(data), "1 2.2 foo")
  lu.assertEquals(('${r}'):interpolate(data), '11')
  lu.assertEquals(('${${R}}'):interpolate(data), '2.2')
end

function TestString:test_join()
  lu.assertEquals((':'):join(1,2,3), '1:2:3')
  lu.assertEquals((':'):join(1), '1')
end

local function assertFind(start, finish, group, _start, _finish, _group)
  lu.assertEquals(_start, start)
  lu.assertEquals(_finish, finish)
  lu.assertEquals(_group, group)
end

function TestString:test_rfind()
  local str = "a b c a b c a b c"
  assertFind(11, 12, nil, str:rfind("c "))
  assertFind(17, 17, nil, str:rfind("c"))
  assertFind(2, 4, " b", str:rfind('( b) ', 7))
  assertFind(2, 4, " b", str:rfind('( b) ', -9))
end

function TestString:test_split()
  local str = "a-b c-d e-f"
  lu.assertEquals({str:split()}, {"a-b", "c-d", "e-f"})
  lu.assertEquals({str:split('%-')}, {"a", "b c", "d e", "f"})
  lu.assertEquals({str:split('%-', 2)}, {"a", "b c", "d e-f"})
  lu.assertEquals({str:split('[a-z ]+')}, {'', '-', '-', '-', ''})
end

function TestString:test_trim()
  lu.assertEquals(('  foo\t\r\n'):trim(), 'foo')
end

function TestString:test_wrap()
  local str = "With multi-hyphen-words -- and an emdash."
  lu.assertEquals(str:wrap(1), {'With', 'multi-', 'hyphen-', 'words', '--', 'and', 'an', 'emdash.'})
  lu.assertEquals(str:wrap(23), {'With multi-hyphen-words', '-- and an emdash.'})
end

--[[

    string.interpolate(s, data, seeall)

Searches `s` for sequences of the form `${expr}` or `${expr|format}` and recursively
expands them. This is effectively the same as replacing `${expr}` with the result
of `tostring(dostring(expr))`, and `${expr|format}` with the result of
`string.format(format, dostring(expr))`, except that any `${...}` sequences
in `expr` itself will be expanded before `expr` is evaluated, and any `${...}`
sequences in the result of the expansion will themselves be expanded.

When evaluating `expr`, `data` is used as the environment; if `seeall` is true,
failed lookups in `data` will fall back to the caller's environment.

    > str = "The Lua version is ${_VERSION}, and I am currently using ${collectgarbage 'count'|%d}KB of memory."
    > print(str:interpolate(_G))
    The Lua version is Lua 5.1, and I am currently using 22KB of memory.

-------

]]


text:
package org.apache.cassandra.utils;

public class DefaultInteger
{
    private final int originalValue;
    private int currentValue;

    public DefaultInteger(int value)
    {
        originalValue = value;
        currentValue = value;
    }

    public int value()
    {
        return currentValue;
    }

    public void set(int i)
    {
        currentValue = i;
    }

    public boolean isModified()
    {
        return originalValue != currentValue;
    }
}


text:
export type ZoneID = 'main' | 'zone2' | 'zone3' | 'zone4';
export type InputID =
  'cd'
  | 'tuner'
  | 'multi_ch'
  | 'phono'
  | 'hdmi1'
  | 'hdmi2'
  | 'hdmi3'
  | 'hdmi4'
  | 'hdmi5'
  | 'hdmi6'
  | 'hdmi7'
  | 'hdmi8'
  | 'hdmi'
  | 'av1'
  | 'av2'
  | 'av3'
  | 'av4'
  | 'av5'
  | 'av6'
  | 'av7'
  | 'v_aux'
  | 'aux1'
  | 'aux2'
  | 'aux'
  | 'audio1'
  | 'audio2'
  | 'audio3'
  | 'audio4'
  | 'audio_cd'
  | 'audio'
  | 'optical1'
  | 'optical2'
  | 'optical'
  | 'coaxial1'
  | 'coaxial2'
  | 'coaxial'
  | 'digital1'
  | 'digital2'
  | 'digital'
  | 'line1'
  | 'line2'
  | 'line3'
  | 'line_cd'
  | 'analog'
  | 'tv'
  | 'bd_dvd'
  | 'usb_dac'
  | 'usb'
  | 'bluetooth'
  | 'server'
  | 'net_radio'
  | 'rhapsody'
  | 'napster'
  | 'pandora'
  | 'siriusxm'
  | 'spotify'
  | 'juke'
  | 'airplay'
  | 'radiko'
  | 'qobuz'
  | 'mc_link'
  | 'main_sync'
  | 'none';
export type SoundProgramID =
  'munich_a'
  | 'munich_b'
  | 'munich'
  | 'frankfurt'
  | 'stuttgart'
  | 'vienna'
  | 'amsterdam'
  | 'usa_a'
  | 'usa_b'
  | 'tokyo'
  | 'freiburg'
  | 'royaumont'
  | 'chamber'
  | 'concert'
  | 'village_gate'
  | 'village_vanguard'
  | 'warehouse_loft'
  | 'cellar_club'
  | 'jazz_club'
  | 'roxy_theatre'
  | 'bottom_line'
  | 'arena'
  | 'sports'
  | 'action_game'
  | 'roleplaying_game'
  | 'game'
  | 'music_video'
  | 'music'
  | 'recital_opera'
  | 'pavilion'
  | 'disco'
  | 'standard'
  | 'spectacle'
  | 'sci-fi'
  | 'adventure'
  | 'drama'
  | 'talk_show'
  | 'tv_program'
  | 'mono_movie'
  | 'movie'
  | 'enhanced'
  | '2ch_stereo'
  | '5ch_stereo'
  | '7ch_stereo'
  | '9ch_stereo'
  | '11ch_stereo'
  | 'stereo'
  | 'surr_decoder'
  | 'my_surround'
  | 'target'
  | 'straight'
  | 'off';

export type PowerStatus = 'on' | 'standby';

export type RangeStepInfo = {
  id: string,
  min: number,
  max: number,
  step: number
};

export type SimpleResponse = {
  response_code: number
};

export type DeviceInfo = {
  response_code: number,
  model_name: string,
  destination: string,
  device_id: string,
  system_version: number,
  api_version: number,
  netmodule_version: string,
  netmodule_checksum: string,
  operation_mode: string,
  update_error_code?: string,
  update_progress?: Object
};
export type InputInfo = {
  id: InputID,
  distribution_enable: boolean,
  rename_enable: boolean,
  account_enable: boolean,
  play_info_type: 'none' | 'tuner' | 'netusb' | 'cd'

};
export type SystemInfo = {
  func_list: string[],
  zone_num: number,
  input_list: InputInfo[],
  ymap_list: string[]
};
export type TunerInfo = {
  func_list: string[],
  range_step: RangeStepInfo[],
  preset: { type: 'common' | 'separate', num: number }
};
export type NetUsbInfo = {
  func_list: string[],
  preset: { num: number },
  recent_info: { num: number },
  play_queue: { size: number },
  mc_playlist: { size: number, num: number },
  vtuner_fver: string
};
export type ZoneInfo = {
  id: ZoneID,
  zone_b: boolean,
  func_list: string[],
  input_list: InputID[],
  sound_program_list: SoundProgramID[],
  tone_control_mode_list: string[],
  equalizer_mode_list: string[],
  link_control_list: string[],
  link_audio_delay_list: string[],
  range_step: RangeStepInfo[]
};

export type FeatureInfo = {
  response_code: number,
  system: SystemInfo,
  zone: ZoneInfo[],
  tuner: TunerInfo,
  netusb: NetUsbInfo,
  distribution: Object,
  clock: Object,
};
export type ToneControlStatus = {
  mode: string,
  bass: number,
  treble: number
};

export type ZoneStatus = {
  response_code: number,
  power: PowerStatus,
  sleep: 0 | 30 | 60 | 90 | 120,
  volume: number,
  mute: boolean,
  input: InputID,
  sound_program: string,
  surround_3d: boolean,
  direct: boolean,
  pure_direct: boolean,
  enhancer: boolean,
  tone_control: ToneControlStatus
};

export type PlaybackStatus = 'play' | 'stop' | 'pause' | 'fast_reverse' | 'fast_forward';
export type ExtendedPlaybackStatus = 'play' | 'stop' | 'pause' | 'play_pause' | 'previous' | 'next'
  | 'fast_reverse_start' | 'fast_reverse_end' | 'fast_forward_start' | 'fast_forward_end';

export type PlaybackInfo = {
  response_code: number,
  input: InputID,
  play_queue_type: string,
  playback: PlaybackStatus,
  repeat: 'off' | 'one' | 'all',
  shuffle: 'off' | 'on' | 'songs' | 'albums',
  play_time: number,
  total_time: number,
  artist: string,
  album: string,
  track: string,
  albumart_url: string,
  albumart_id: number,
  usb_devicetype: 'msc' | 'ipod' | 'unknown',
  auto_stopped: boolean,
  attribute: number
};

export type SimplePlaybackInfo = {
  artist: string,
  album: string,
  track: string,
  albumArt: string,
};

export type ZoneChangeInfo = {
  power?: PowerStatus,
  input?: InputID,
  volume?: number,
  mute?: boolean,
  status_updated?: boolean,
  signal_info_updated?: boolean
};
export type SystemChangeInfo = {
  bluetooth_info_updated?: boolean,
  func_status_updated?: boolean,
  speaker_settings_updated?: boolean,
  name_text_updated?: boolean,
  tag_updated?: boolean,
  location_info_updated?: boolean,
  stereo_pair_info_updated?: boolean
};
export type NetUsbChangeInfo = {
  play_error?: number,
  multiple_play_errors?: number,
  play_message?: string,
  account_updated?: boolean,
  play_time?: number,
  preset_info_updated?: boolean,
  recent_info_updated?: boolean,
  preset_control?: {
    type: string,
    num: number,
    result: string
  },
  trial_status?: {
    input: InputID,
    enable: boolean
  },
  trial_time_left?: {
    input: InputID,
    time: number
  },
  play_info_updated?: boolean,
  list_info_updated?: boolean
};
export type StatusChangeEvent = {
  device_id: ?string,
  system?: SystemChangeInfo,
  main?: ZoneChangeInfo,
  zone2?: ZoneChangeInfo,
  zone3?: ZoneChangeInfo,
  zone4?: ZoneChangeInfo,
  netusb?: NetUsbChangeInfo
};

export type SignalInfo = {
  response_code: number,
  audio: {
    error: number,
    format: string,
    fs: string
  }
}

export type ListItemInfo = {
  text: string,
  thumbnail: string,
  attribute: number
};

export type ListInfo = {
  response_code: number,
  input: InputID,
  menu_layer: number,
  max_line: number,
  index: number,
  playing_index: number,
  menu_name: string,
  list_info: ListItemInfo[]
};

export type ListControlAction = 'select' | 'play' | 'return';

export type PresetItemInfo = {
  input: InputID | 'unknown',
  text: string,
  attribute: number
}

export type PresetInfo = {
  response_code: number,
  preset_info: PresetItemInfo[],
  func_list: string[]
}


text:
brew tap Homebrew/bundle

# Make sure we're using the latest Homebrew.
brew update

# Upgrade any already-installed formulae.
brew upgrade

# Install formulae in Brewfile
brew bundle

# Remove outdated versions from the cellar.
brew cleanup


text:
<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'species-form',
	'enableAjaxValidation'=>false,
	'htmlOptions'=>array('class'=>'form-horizontal')
)); ?>

Fields with * are required.

	<?php echo $form->errorSummary($model); ?>

		<?php echo $form->labelEx($model,'tax_id',array('class'=>'control-label')); ?>

		<?php echo $form->textField($model,'tax_id'); ?>
		<?php echo $form->error($model,'tax_id'); ?>

		<?php echo $form->labelEx($model,'common_name',array('class'=>'control-label')); ?>

		<?php echo $form->textField($model,'common_name',array('size'=>60,'maxlength'=>64)); ?>
		<?php echo $form->error($model,'common_name'); ?>

		<?php echo $form->labelEx($model,'genbank_name',array('class'=>'control-label')); ?>

		<?php echo $form->textField($model,'genbank_name',array('size'=>60,'maxlength'=>128)); ?>
		<?php echo $form->error($model,'genbank_name'); ?>

		<?php echo $form->labelEx($model,'scientific_name',array('class'=>'control-label')); ?>

		<?php echo $form->textField($model,'scientific_name',array('size'=>60,'maxlength'=>128)); ?>
		<?php echo $form->error($model,'scientific_name'); ?>

        Cancel
		<?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save',array('class'=>'btn')); ?>

<?php $this->endWidget(); ?>


text:
package eu.thog92.generator.api.tasks;

import java.util.concurrent.ScheduledExecutorService;

public interface ITaskManager
{
    void scheduleTask(ScheduledTask task);

    void onFinishTask(ScheduledTask task);

    ScheduledExecutorService getScheduler();
}


text:
class CreateEngineOnRailsPosts < ActiveRecord::Migration
  def change
    create_table :engine_on_rails_posts do |t|
      t.string :title
      t.text :content

      t.timestamps
    end
  end
end


text:
define(['dojo/dom', 'dojo/_base/declare'], function (dom, declare) {
    return declare(null, {
        _oldText: {},
        constructor: function () {

        },
        setText: function(id, text){
            var node = dom.byId(id);
            this._oldText[id] = node.innerHTML;
            node.innerHTML = text;
        },

        restoreText: function(id){
            var node = dom.byId(id);
            node.innerHTML = this._oldText[id];
            delete this._oldText[id];
        }
    });
});


text:
package org.tools4j.spockito.jupiter;

import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.params.aggregator.ArgumentsAccessor;
import org.junit.jupiter.params.aggregator.ArgumentsAggregationException;
import org.junit.jupiter.params.aggregator.ArgumentsAggregator;
import org.tools4j.spockito.table.Table;
import org.tools4j.spockito.table.TableRow;
import org.tools4j.spockito.table.ValueConverter;

import java.lang.reflect.Parameter;

import static org.tools4j.spockito.jupiter.TableValueConverter.valueConverter;

/**
 * Aggregator used by {@linkplain AggregateTableRow @AggregateTableRow} or if used with the
 * {@linkplain org.junit.jupiter.params.aggregator.AggregateWith @AggregateWith} annotation.
 *
 * <p>The annotated method parameter references a whole {@link TableRow} of a {@link Table}.
 */
public class TableRowAggregator implements ArgumentsAggregator {

    @Override
    public Object aggregateArguments(final ArgumentsAccessor accessor, final ParameterContext context) throws ArgumentsAggregationException {
        final Parameter parameter = context.getParameter();
        final ValueConverter valueConverter = valueConverter(context);
        final TableRow tableRow = accessor.get(context.getIndex(), TableRow.class);
        return tableRow.to(parameter.getType(), parameter.getParameterizedType(), valueConverter);
    }

}


text:
export interface ISubWork {
    title: string;
    technique: string;
    year: string;
    itemImage: string;
}

export interface IWorksEntry {
    jsonUrl: string;
    title: string;
    url: string;
    authorName: string;
    subWorks: ISubWork[];
}


text:
import { Router } from 'express';
import { User, Rejection } from '../data';
import { Logger } from '../util';
import { AuthService, UserService } from '../service';
import { Api, Route } from '../deco';

@Api('users')
export class UserApi {

  constructor(router: Router) { }

  @Route('register')
  postRegister(req, res) {

    const user = User.fromDTOWithPass(req.body);
    user.salt = AuthService.getSalt();
    const a = user.password;
    user.password = AuthService.hashPassword(a, user.salt);

    UserService.create(user).then(
    value => res.json(value.toDTO()),
    err => {
      res.status(err.status).send(err.message);
      Logger.error('POST: /users/register', err);
    });
  }

  @Route('login')
  postLogin(req, res) {
    AuthService.login(req).then(
      token => res.status(200).send(token),
      (err: Rejection) => {
        res.status(err.status).send(err.message);
        Logger.error('POST: /users/login', err);
    });
  }

  @Route('self')
  getSelf(req, res) { // check auth
    AuthService.auth(req).then(userId => {
      UserService.get(userId)
          .then(value => res.json(value.toDTO()));
    }, err => {
      res.status(err.status).send(err.message);
      Logger.error('PUT: /users/self', err);
    });
  }

  @Route('self')
  putSelf(req, res) { // check auth
    AuthService.auth(req).then(userId => {
      const user = User.fromDTO(req.body);
      user.id = userId;
      UserService.update(user)
          .then(value => res.sendStatus(204));
    }).catch(err => {
      res.status(err.status).send(err.message);
      Logger.error('PUT: /users/self', err);
    });
  }

  @Route('self')
  deleteSelf(req, res) { // check auth
    AuthService.auth(req).then(userId => {
      UserService.delete(userId)
          .then(() => res.sendStatus(204));
    }).catch(err => {
      res.status(err.status).send(err.message);
      Logger.error('DELETE: /users/self', err);
    });
  }

  @Route(':id')
  get(req, res) {
    AuthService.auth(req).then(userId => {
      UserService.get(req.params.id)
          .then(value => res.json(value.toDTO()));
    }).catch(err => {
      res.status(err.status).send(err.message);
      Logger.error('GET: /users/' + req.params.id, err);
    });
  }
}


text:
'''
lib/process
sublime-ycmd process management module.
'''

from .process import Process            # noqa
from .filehandles import FileHandles    # noqa

__all__ = ['process', 'filehandles']


text:
package org.apache.sysds.runtime.compress.colgroup.insertionsort;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.sysds.runtime.compress.colgroup.mapping.AMapToData;
import org.apache.sysds.runtime.compress.colgroup.mapping.MapToFactory;
import org.apache.sysds.runtime.compress.utils.IntArrayList;

/**
 * This abstract class is for sorting the IntArrayList entries efficiently for SDC Column Groups construction.
 *
 * The idea is to construct an object, where the array is inserted along with a label, and the values are sorted at
 * insertion time.
 *
 */
public abstract class AInsertionSorter {
	protected static final Log LOG = LogFactory.getLog(AInsertionSorter.class.getName());

	protected final IntArrayList[] _offsets;
	protected final int _negativeIndex;

	protected final int[] _indexes;
	protected final AMapToData _labels;

	protected final int _numLabels;
	protected final int _numRows;

	public AInsertionSorter(int endLength, int numRows, IntArrayList[] offsets) {
		_indexes = new int[endLength];
		_numLabels = offsets.length;
		_labels = MapToFactory.create(endLength, _numLabels );
		_numRows = numRows;
		_offsets = offsets;
		_negativeIndex = -1;
	}

	public AInsertionSorter(int endLength, int numRows, IntArrayList[] offsets, int negativeIndex) {
		_indexes = new int[endLength];
		_numLabels = offsets.length;
		_labels = MapToFactory.create(endLength, _numLabels );
		_numRows = numRows;
		_offsets = offsets;
		_negativeIndex = negativeIndex;
	}

	public int[] getIndexes() {
		return _indexes;
	}

	public AMapToData getData() {
		return _labels;
	}

	protected void set(int index, int value, int label) {
		_indexes[index] = value;
		_labels.set(index, label);
	}
}


text:
from django.conf.urls import patterns, url

from claims import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^about/?$', views.about, name='about'),

    #project area
    url(r'^project/discover/?$', views.project_discover, name='project_discover'),
    url(r'^project/create/?$', views.project_create, name='project_create'),
    url(r'^project/(?P<project_id>[0-9]+)/?$', views.project_start, name='project_start'),
    url(r'^project/(?P<project_id>[0-9]+)/fields/?$', views.project_edit_fields, name='project_edit_fields'),
)


text:
<?php
namespace Chamilo\Core\Repository\Workspace\Form;

use Chamilo\Core\Repository\Workspace\Storage\DataClass\Workspace;
use Chamilo\Libraries\Format\Form\FormValidator;
use Chamilo\Libraries\Translation\Translation;
use Chamilo\Libraries\Utilities\Utilities;

/**
 *
 * @package Chamilo\Core\Repository\Workspace\Form
 * @author Hans De Bisschop <hans.de.bisschop@ehb.be>
 * @author Magali Gillard <magali.gillard@ehb.be>
 * @author Eduard Vossen <eduard.vossen@ehb.be>
 */
class WorkspaceForm extends FormValidator
{

    /**
     *
     * @var \Chamilo\Core\Repository\Workspace\Storage\DataClass\Workspace
     */
    private $workspace;

    /**
     * Constructor
     *
     * @param string $form_url
     * @param \Chamilo\Core\Repository\Workspace\Storage\DataClass\Workspace $workspace
     */
    public function __construct($formUrl, Workspace $workspace = null)
    {
        parent::__construct('workspace', 'post', $formUrl);

        $this->workspace = $workspace;

        $this->buildForm();
        $this->setFormDefaults();
    }

    /**
     * Builds this form
     */
    protected function buildForm()
    {
        $this->addElement('text', Workspace::PROPERTY_NAME, Translation::get('Name'), array("size" => "50"));

        $this->addRule(
            Workspace::PROPERTY_NAME,
            Translation::get('ThisFieldIsRequired', null, Utilities::COMMON_LIBRARIES),
            'required');

        $this->add_html_editor(Workspace::PROPERTY_DESCRIPTION, Translation::get('Description'));

        $this->addSaveResetButtons();
    }

    /**
     * Sets the default values
     *
     * @param \Chamilo\Core\Repository\Workspace\Storage\DataClass\Workspace $workspace
     */
    protected function setFormDefaults()
    {
        $defaults = array();

        if ($this->workspace instanceof Workspace)
        {
            $defaults[Workspace::PROPERTY_NAME] = $this->workspace->getName();
            $defaults[Workspace::PROPERTY_DESCRIPTION] = $this->workspace->getDescription();
        }

        $this->setDefaults($defaults);
    }
}


text:
static const struct file_operations nouveau_driver_fops = {
	.llseek = noop_llseek,
};

static struct file_operations* dummy(void)
{
	return &nouveau_driver_fops;
}


text:
<?php

namespace Mpwar\CoreServices\Candidate\Service;

use Mpwar\CoreDomain\Candidate\Candidate;
use Mpwar\CoreDomain\Candidate\CandidateRepository;

final class CandidateDelete
{
    private $repository;

    public function __construct(CandidateRepository $repository)
    {
        $this->repository = $repository;
    }

    public function deleteCandidate(Candidate $candidate)
    {
        $this->repository->delete($candidate);
    }
}


text:
oclazyloading-play-a
====================

Play with ocLazyLoad


text:
include_recipe 'logadm::default'

logadm 'chef-client' do
  path '/var/log/chef/client.log'
  copy true
  size '1b'
  period '7d'
  action :create
end


text:
import socket

# 3rd party
import simplejson as json

# project
from checks import AgentCheck

GLOBAL_STATS = set([
    'curr_connections',
])

GLOBAL_STATS_RATES = set([
    'total_connections'
])

POOL_STATS = set([
    'client_connections',
    'server_ejects',
])

POOL_STATS_RATES = set([
    'client_eof',
    'client_err',
    'forward_error',
    'fragments'
])

SERVER_STATS = set([
    'server_connections',
    'server_timedout',
])

SERVER_STATS_RATES = set([
    'in_queue',
    'out_queue',
    'in_queue_bytes',
    'out_queue_bytes',
    'requests',
    'request_bytes',
    'responses',
    'response_bytes',
    'server_err',
    'server_eof'
])

class Twemproxy(AgentCheck):
    """Tracks twemproxy metrics via the stats monitoring port

    Connects to twemproxy via the configured stats port.
    See https://github.com/twitter/twemproxy#observability

    $ curl localhost:22222
    {
        "service":"nutcracker",
        "source":"i-deadbeef",
        "version":"0.4.1",
        "uptime":4018,
        "timestamp":1446677875,
        "total_connections":244,
        "curr_connections":23,
        "poolA": {
            # pool stats
            "client_eof":221,
            "client_err":0,
            "client_connections":15,
            "server_ejects":0,
            "forward_error":0,
            "fragments":0,
            "serverA": {
                # server stats
                "server_eof":0,
                "server_err":0,
                "server_timedout":0,
                "server_connections":1,
                "server_ejected_at":0,
                "requests":46873,
                "request_bytes":127685831,
                "responses":46872,
                "response_bytes":194030,
                "in_queue":1,
                "in_queue_bytes":190,
                "out_queue":0,
                "out_queue_bytes":0
            }
        }
    }

    """

    SERVICE_CHECK_NAME = 'twemproxy.can_connect'

    def check(self, instance):
        if 'host' not in instance:
            raise Exception('Twemproxy instance missing "host" value.')
        tags = instance.get('tags', [])

        response = self._get_data(instance)
        self.log.debug(u"Twemproxy `response`: {0}".format(response))

        if not response:
            self.log.warning(u"No response received from twemproxy.")
            return

        metrics = Twemproxy.parse_json(response, tags)
        for row in metrics:
            try:
                name, value, tags = row
                if name.split('.')[1] in (GLOBAL_STATS | POOL_STATS | SERVER_STATS):
                    self.gauge(name, value, tags)
                else:
                    self.rate(name, value, tags)
            except Exception, e:
                self.log.error(
                    u'Could not submit metric: %s: %s',
                    repr(row), str(e)
                )

    def _get_data(self, instance):
        host = instance.get('host')
        port = int(instance.get('port', 2222)) # 2222 is default

        service_check_tags = ['host:{}'.format(host), 'port:{}'.format(port)]

        try:
            addrs = socket.getaddrinfo(host, port, 0, 0, socket.IPPROTO_TCP)
        except socket.gaierror as e:
            self.log.warning("unable to retrieve address info for %s:%s - %s", host, port, e)
            self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
                               tags=service_check_tags)
            return None

        response = ""
        for addr in addrs:
            try:
                if addr[1] == socket.SOCK_STREAM:
                    client = socket.socket(*addr[0:3])
                    client.connect(addr[-1])

                    self.log.debug(u"Querying: {0}:{1}".format(host, port))
                    while 1:
                        data = client.recv(1024)
                        if not data:
                            break
                        response = ''.join([response, data])

                client.close()
                break
            except socket.error as e:
                self.log.warning("unable to connect to %s - %s", addr[-1], e)

        status = AgentCheck.OK if response else AgentCheck.CRITICAL
        self.service_check(self.SERVICE_CHECK_NAME, status, tags=service_check_tags)

        return response

    @classmethod
    def parse_json(cls, raw, tags=None):
        if tags is None:
            tags = []
        parsed = json.loads(raw)
        metric_base = 'twemproxy'
        output = []

        for key, val in parsed.iteritems():
            if isinstance(val, dict):
                # server pool
                pool_tags = tags + ['pool:%s' % key]
                for server_key, server_val in val.iteritems():
                    if isinstance(server_val, dict):
                        # server
                        server_tags = pool_tags + ['server:%s' % server_key]
                        for stat in (SERVER_STATS | SERVER_STATS_RATES):
                            metric_name = '%s.%s' % (metric_base, stat)
                            output.append(
                                (metric_name, server_val.get(stat), server_tags)
                            )

                    elif server_key in (POOL_STATS | POOL_STATS_RATES):
                        metric_name = '%s.%s' % (metric_base, server_key)
                        output.append((metric_name, server_val, pool_tags))

            elif key in (GLOBAL_STATS | GLOBAL_STATS_RATES):
                metric_name = '%s.%s' % (metric_base, key)
                output.append((metric_name, val, tags))

        return output


text:
using System;
using Xunit;

namespace Microsoft.AspNetCore.Cryptography.Cng;

public unsafe class BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO_Tests
{
    [Fact]
    public void Init_SetsProperties()
    {
        // Act
        BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO.Init(out var cipherModeInfo);

        // Assert
        Assert.Equal((uint)sizeof(BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO), cipherModeInfo.cbSize);
        Assert.Equal(1U, cipherModeInfo.dwInfoVersion);
        Assert.Equal(IntPtr.Zero, (IntPtr)cipherModeInfo.pbNonce);
        Assert.Equal(0U, cipherModeInfo.cbNonce);
        Assert.Equal(IntPtr.Zero, (IntPtr)cipherModeInfo.pbAuthData);
        Assert.Equal(0U, cipherModeInfo.cbAuthData);
        Assert.Equal(IntPtr.Zero, (IntPtr)cipherModeInfo.pbTag);
        Assert.Equal(0U, cipherModeInfo.cbTag);
        Assert.Equal(IntPtr.Zero, (IntPtr)cipherModeInfo.pbMacContext);
        Assert.Equal(0U, cipherModeInfo.cbMacContext);
        Assert.Equal(0U, cipherModeInfo.cbAAD);
        Assert.Equal(0UL, cipherModeInfo.cbData);
        Assert.Equal(0U, cipherModeInfo.dwFlags);
    }
}


text:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from yats.models import UserProfile, organisation, ticket_type, ticket_priority, ticket_resolution, ticket_flow

@admin.register(organisation, ticket_type, ticket_priority, ticket_resolution, ticket_flow)
class yatsAdmin(admin.ModelAdmin):
    exclude = ('c_date','c_user','u_user','u_date','d_user','d_date','active_record')
    list_filter = ('active_record',)

    def save_model(self, request, obj, form, change):
        obj.save(user=request.user)

    def delete_model(self, request, obj):
        obj.delete(user=request.user)

    """
    def changelist_view(self, request, extra_context=None):

        if not request.GET.has_key('active_record__exact'):
            q = request.GET.copy()
            q['active_record__exact'] = 'N'
            request.GET = q
            request.META['QUERY_STRING'] = request.GET.urlencode()
        return super(yatsAdmin, self).changelist_view(request, extra_context=extra_context)
    """

# Define an inline admin descriptor for UserProfile model
# which acts a bit like a singleton
class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'profile'

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "party":
            kwargs["queryset"] = organisation.objects.order_by('name')
        return super(UserProfileInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

# Define a new User admin
class UserAdmin(UserAdmin):
    inlines = (UserProfileInline, )

admin.site.unregister(User)
admin.site.register(User, UserAdmin)


text: Web application for the Mapping Expatriate Paris project


text:
package com.orientechnologies.orient.test.database.speed;

import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.util.io.graphml.GraphMLReader;

import java.io.FileInputStream;

/**
 * @author Marko A. Rodriguez (http://markorodriguez.com)
 */
public class OrientBenchmarkTestSuite {

  private static final int TOTAL_RUNS = 1;

  public void main(String args[]) throws Exception {
    new OrientBenchmarkTestSuite().testOrientGraph();
  }

  public OrientBenchmarkTestSuite() {
  }

  public void testOrientGraph() throws Exception {
    long totalTime = 0;

    OrientBaseGraph graph = new OrientGraphNoTx("GraphExample2");

    GraphMLReader.inputGraph(graph, new FileInputStream("/Users/luca/Downloads/graph-example-2.xml"));
    System.out.println("V: " + graph.getRawGraph().countClass("V") + " E: " + graph.getRawGraph().countClass("E"));
    graph.shutdown();

    long lastTime = System.currentTimeMillis();
    for (int i = 0; i < TOTAL_RUNS; i++) {
      graph = new OrientGraphNoTx("GraphExample2");
      int counter = execute(graph);

      long currentTime = System.currentTimeMillis() - lastTime;
      lastTime = System.currentTimeMillis();

      totalTime += currentTime;
      System.out.println("OrientGraph elements touched " + counter + " in " + currentTime);
      graph.shutdown();
    }
    System.out.println("OrientGraph experiment average = " + (totalTime / (double) TOTAL_RUNS));
  }

  private int execute(Graph graph) {
    int counter = 0;

    for (final Vertex vertex : graph.getVertices()) {
      counter++;
      for (final Edge edge : vertex.getEdges(Direction.OUT)) {
        counter++;
        final Vertex vertex2 = edge.getVertex(Direction.IN);
        counter++;
        for (final Edge edge2 : vertex2.getEdges(Direction.OUT)) {
          counter++;
          final Vertex vertex3 = edge2.getVertex(Direction.IN);
          counter++;
          for (final Edge edge3 : vertex3.getEdges(Direction.OUT)) {
            counter++;
            edge3.getVertex(Direction.OUT);
            counter++;
          }
        }
      }
    }
    return counter;
  }
}


text:
package smartag

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

import (
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses"
)

// ModifySmartAccessGatewayClientUser invokes the smartag.ModifySmartAccessGatewayClientUser API synchronously
func (client *Client) ModifySmartAccessGatewayClientUser(request *ModifySmartAccessGatewayClientUserRequest) (response *ModifySmartAccessGatewayClientUserResponse, err error) {
	response = CreateModifySmartAccessGatewayClientUserResponse()
	err = client.DoAction(request, response)
	return
}

// ModifySmartAccessGatewayClientUserWithChan invokes the smartag.ModifySmartAccessGatewayClientUser API asynchronously
func (client *Client) ModifySmartAccessGatewayClientUserWithChan(request *ModifySmartAccessGatewayClientUserRequest) (<-chan *ModifySmartAccessGatewayClientUserResponse, <-chan error) {
	responseChan := make(chan *ModifySmartAccessGatewayClientUserResponse, 1)
	errChan := make(chan error, 1)
	err := client.AddAsyncTask(func() {
		defer close(responseChan)
		defer close(errChan)
		response, err := client.ModifySmartAccessGatewayClientUser(request)
		if err != nil {
			errChan <- err
		} else {
			responseChan <- response
		}
	})
	if err != nil {
		errChan <- err
		close(responseChan)
		close(errChan)
	}
	return responseChan, errChan
}

// ModifySmartAccessGatewayClientUserWithCallback invokes the smartag.ModifySmartAccessGatewayClientUser API asynchronously
func (client *Client) ModifySmartAccessGatewayClientUserWithCallback(request *ModifySmartAccessGatewayClientUserRequest, callback func(response *ModifySmartAccessGatewayClientUserResponse, err error)) <-chan int {
	result := make(chan int, 1)
	err := client.AddAsyncTask(func() {
		var response *ModifySmartAccessGatewayClientUserResponse
		var err error
		defer close(result)
		response, err = client.ModifySmartAccessGatewayClientUser(request)
		callback(response, err)
		result <- 1
	})
	if err != nil {
		defer close(result)
		callback(nil, err)
		result <- 0
	}
	return result
}

// ModifySmartAccessGatewayClientUserRequest is the request struct for api ModifySmartAccessGatewayClientUser
type ModifySmartAccessGatewayClientUserRequest struct {
	*requests.RpcRequest
	ResourceOwnerId      requests.Integer `position:"Query" name:"ResourceOwnerId"`
	ClientIp             string           `position:"Query" name:"ClientIp"`
	Email                string           `position:"Query" name:"Email"`
	EnableStaticIp       requests.Boolean `position:"Query" name:"EnableStaticIp"`
	ResourceOwnerAccount string           `position:"Query" name:"ResourceOwnerAccount"`
	Bandwidth            requests.Integer `position:"Query" name:"Bandwidth"`
	OwnerAccount         string           `position:"Query" name:"OwnerAccount"`
	OwnerId              requests.Integer `position:"Query" name:"OwnerId"`
	SmartAGId            string           `position:"Query" name:"SmartAGId"`
	UserName             string           `position:"Query" name:"UserName"`
}

// ModifySmartAccessGatewayClientUserResponse is the response struct for api ModifySmartAccessGatewayClientUser
type ModifySmartAccessGatewayClientUserResponse struct {
	*responses.BaseResponse
	UserName  string `json:"UserName" xml:"UserName"`
	RequestId string `json:"RequestId" xml:"RequestId"`
	UserMail  string `json:"UserMail" xml:"UserMail"`
	Bandwidth int    `json:"Bandwidth" xml:"Bandwidth"`
	ClientIp  string `json:"ClientIp" xml:"ClientIp"`
}

// CreateModifySmartAccessGatewayClientUserRequest creates a request to invoke ModifySmartAccessGatewayClientUser API
func CreateModifySmartAccessGatewayClientUserRequest() (request *ModifySmartAccessGatewayClientUserRequest) {
	request = &ModifySmartAccessGatewayClientUserRequest{
		RpcRequest: &requests.RpcRequest{},
	}
	request.InitWithApiInfo("Smartag", "2018-03-13", "ModifySmartAccessGatewayClientUser", "smartag", "openAPI")
	request.Method = requests.POST
	return
}

// CreateModifySmartAccessGatewayClientUserResponse creates a response to parse from ModifySmartAccessGatewayClientUser response
func CreateModifySmartAccessGatewayClientUserResponse() (response *ModifySmartAccessGatewayClientUserResponse) {
	response = &ModifySmartAccessGatewayClientUserResponse{
		BaseResponse: &responses.BaseResponse{},
	}
	return
}