text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.sql.parser;

import io.trino.sql.tree.DataType;
import io.trino.sql.tree.Expression;
import io.trino.sql.tree.Node;
import io.trino.sql.tree.PathSpecification;
import io.trino.sql.tree.RowPattern;
import io.trino.sql.tree.Statement;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DefaultErrorStrategy;
import org.antlr.v4.runtime.InputMismatchException;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;
import org.antlr.v4.runtime.Token;
import org.antlr.v4.runtime.atn.PredictionMode;
import org.antlr.v4.runtime.misc.Pair;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.TerminalNode;

import java.util.Arrays;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;

import static java.util.Objects.requireNonNull;

public class SqlParser
{
    private static final BaseErrorListener LEXER_ERROR_LISTENER = new BaseErrorListener()
    {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String message, RecognitionException e)
        {
            throw new ParsingException(message, e, line, charPositionInLine + 1);
        }
    };
    private static final BiConsumer<SqlBaseLexer, SqlBaseParser> DEFAULT_PARSER_INITIALIZER = (SqlBaseLexer lexer, SqlBaseParser parser) -> {};

    private static final ErrorHandler PARSER_ERROR_HANDLER = ErrorHandler.builder()
            .specialRule(SqlBaseParser.RULE_expression, "<expression>")
            .specialRule(SqlBaseParser.RULE_booleanExpression, "<expression>")
            .specialRule(SqlBaseParser.RULE_valueExpression, "<expression>")
            .specialRule(SqlBaseParser.RULE_primaryExpression, "<expression>")
            .specialRule(SqlBaseParser.RULE_predicate, "<predicate>")
            .specialRule(SqlBaseParser.RULE_identifier, "<identifier>")
            .specialRule(SqlBaseParser.RULE_string, "<string>")
            .specialRule(SqlBaseParser.RULE_query, "<query>")
            .specialRule(SqlBaseParser.RULE_type, "<type>")
            .specialToken(SqlBaseLexer.INTEGER_VALUE, "<integer>")
            .ignoredRule(SqlBaseParser.RULE_nonReserved)
            .build();

    private final BiConsumer<SqlBaseLexer, SqlBaseParser> initializer;

    public SqlParser()
    {
        this(DEFAULT_PARSER_INITIALIZER);
    }

    public SqlParser(BiConsumer<SqlBaseLexer, SqlBaseParser> initializer)
    {
        this.initializer = requireNonNull(initializer, "initializer is null");
    }

    public Statement createStatement(String sql, ParsingOptions parsingOptions)
    {
        return (Statement) invokeParser("statement", sql, SqlBaseParser::singleStatement, parsingOptions);
    }

    public Expression createExpression(String expression, ParsingOptions parsingOptions)
    {
        return (Expression) invokeParser("expression", expression, SqlBaseParser::standaloneExpression, parsingOptions);
    }

    public DataType createType(String expression)
    {
        return (DataType) invokeParser("type", expression, SqlBaseParser::standaloneType, new ParsingOptions());
    }

    public PathSpecification createPathSpecification(String expression)
    {
        return (PathSpecification) invokeParser("path specification", expression, SqlBaseParser::standalonePathSpecification, new ParsingOptions());
    }

    public RowPattern createRowPattern(String pattern)
    {
        return (RowPattern) invokeParser("row pattern", pattern, SqlBaseParser::standaloneRowPattern, new ParsingOptions());
    }

    private Node invokeParser(String name, String sql, Function<SqlBaseParser, ParserRuleContext> parseFunction, ParsingOptions parsingOptions)
    {
        try {
            SqlBaseLexer lexer = new SqlBaseLexer(new CaseInsensitiveStream(CharStreams.fromString(sql)));
            CommonTokenStream tokenStream = new CommonTokenStream(lexer);
            SqlBaseParser parser = new SqlBaseParser(tokenStream);
            initializer.accept(lexer, parser);

            // Override the default error strategy to not attempt inserting or deleting a token.
            // Otherwise, it messes up error reporting
            parser.setErrorHandler(new DefaultErrorStrategy()
            {
                @Override
                public Token recoverInline(Parser recognizer)
                        throws RecognitionException
                {
                    if (nextTokensContext == null) {
                        throw new InputMismatchException(recognizer);
                    }
                    throw new InputMismatchException(recognizer, nextTokensState, nextTokensContext);
                }
            });

            parser.addParseListener(new PostProcessor(Arrays.asList(parser.getRuleNames()), parser));

            lexer.removeErrorListeners();
            lexer.addErrorListener(LEXER_ERROR_LISTENER);

            parser.removeErrorListeners();
            parser.addErrorListener(PARSER_ERROR_HANDLER);

            ParserRuleContext tree;
            try {
                // first, try parsing with potentially faster SLL mode
                parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
                tree = parseFunction.apply(parser);
            }
            catch (ParseCancellationException ex) {
                // if we fail, parse with LL mode
                tokenStream.seek(0); // rewind input stream
                parser.reset();

                parser.getInterpreter().setPredictionMode(PredictionMode.LL);
                tree = parseFunction.apply(parser);
            }

            return new AstBuilder(parsingOptions).visit(tree);
        }
        catch (StackOverflowError e) {
            throw new ParsingException(name + " is too large (stack overflow while parsing)");
        }
    }

    private static class PostProcessor
            extends SqlBaseBaseListener
    {
        private final List<String> ruleNames;
        private final SqlBaseParser parser;

        public PostProcessor(List<String> ruleNames, SqlBaseParser parser)
        {
            this.ruleNames = ruleNames;
            this.parser = parser;
        }

        @Override
        public void exitQuotedIdentifier(SqlBaseParser.QuotedIdentifierContext context)
        {
            Token token = context.QUOTED_IDENTIFIER().getSymbol();
            if (token.getText().length() == 2) { // empty identifier
                throw new ParsingException("Zero-length delimited identifier not allowed", null, token.getLine(), token.getCharPositionInLine() + 1);
            }
        }

        @Override
        public void exitBackQuotedIdentifier(SqlBaseParser.BackQuotedIdentifierContext context)
        {
            Token token = context.BACKQUOTED_IDENTIFIER().getSymbol();
            throw new ParsingException(
                    "backquoted identifiers are not supported; use double quotes to quote identifiers",
                    null,
                    token.getLine(),
                    token.getCharPositionInLine() + 1);
        }

        @Override
        public void exitDigitIdentifier(SqlBaseParser.DigitIdentifierContext context)
        {
            Token token = context.DIGIT_IDENTIFIER().getSymbol();
            throw new ParsingException(
                    "identifiers must not start with a digit; surround the identifier with double quotes",
                    null,
                    token.getLine(),
                    token.getCharPositionInLine() + 1);
        }

        @Override
        public void exitNonReserved(SqlBaseParser.NonReservedContext context)
        {
            // we can't modify the tree during rule enter/exit event handling unless we're dealing with a terminal.
            // Otherwise, ANTLR gets confused and fires spurious notifications.
            if (!(context.getChild(0) instanceof TerminalNode)) {
                int rule = ((ParserRuleContext) context.getChild(0)).getRuleIndex();
                throw new AssertionError("nonReserved can only contain tokens. Found nested rule: " + ruleNames.get(rule));
            }

            // replace nonReserved words with IDENT tokens
            context.getParent().removeLastChild();

            Token token = (Token) context.getChild(0).getPayload();
            Token newToken = new CommonToken(
                    new Pair<>(token.getTokenSource(), token.getInputStream()),
                    SqlBaseLexer.IDENTIFIER,
                    token.getChannel(),
                    token.getStartIndex(),
                    token.getStopIndex());

            context.getParent().addChild(parser.createTerminalNode(context.getParent(), newToken));
        }
    }
}


text:
namespace GraphDB {

WriteBatch::~WriteBatch() { }

void WriteBatch::commit(StorageFacade& storage,
                         EdgeStreamDistributor& stream) {
	storage.commitBatch(this->batch_);
	stream.publish(this->event_queue_);
}

template <class Key>
void WriteBatch::set(const Key& id, const PropertyValue& value) {
	BufferGuard<NullBuffer> valueBuffer;
	valueBuffer.resize(value.record.ByteSize());

	BufferGuard<Key> keyBuffer;
	Key::toBuffer(id, keyBuffer);

	value.record.SerializeToArray(valueBuffer.data, valueBuffer.size);

	this->batch_.Put(
		leveldb::Slice(reinterpret_cast<char*>(keyBuffer.data),
		               keyBuffer.size),
		leveldb::Slice(reinterpret_cast<char*>(valueBuffer.data),
		               valueBuffer.size)
	);
}

template <class Key>
void WriteBatch::set(const Key& id) {
	BufferGuard<Key> keyBuffer;
	Key::toBuffer(id, keyBuffer);

	this->batch_.Put(
		leveldb::Slice(reinterpret_cast<char*>(keyBuffer.data),
		               keyBuffer.size),
		leveldb::Slice()
	);
}

template <class Key>
void WriteBatch::remove(const Key& id) {
	BufferGuard<Key> keyBuffer;
	Key::toBuffer(id, keyBuffer);

	this->batch_.Delete(
		leveldb::Slice(reinterpret_cast<char*>(keyBuffer.data),
		               keyBuffer.size)
	);
}

}

#include "storage/write/write_batch.tmpl"

redpajama_set_name: RedPajamaGithub


text:
namespace Google.Cloud.OsLogin.V1Beta.Snippets
{
    // [START oslogin_v1beta_generated_OsLoginService_ImportSshPublicKey_sync]
    using Google.Cloud.OsLogin.Common;
    using Google.Cloud.OsLogin.V1Beta;

    public sealed partial class GeneratedOsLoginServiceClientSnippets
    {
        /// <summary>Snippet for ImportSshPublicKey</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void ImportSshPublicKeyRequestObject()
        {
            // Create client
            OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create();
            // Initialize request argument(s)
            ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest
            {
                ParentAsUserName = UserName.FromUser("[USER]"),
                SshPublicKey = new SshPublicKey(),
                ProjectId = "",
                View = LoginProfileView.Unspecified,
            };
            // Make the request
            ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(request);
        }
    }
    // [END oslogin_v1beta_generated_OsLoginService_ImportSshPublicKey_sync]
}


text:
@interface CSTransaction_Utility()
@property (nonatomic, strong) id target;
@property (nonatomic, assign) SEL selector;
@end

static NSMutableSet *transactionSet = nil;

static void CSRunLoopObserverCallBack(CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info) {
    if (transactionSet.count == 0) return;
    NSSet *currentSet = transactionSet;
    transactionSet = [NSMutableSet new];
    [currentSet enumerateObjectsUsingBlock:^(CSTransaction_Utility *transaction, BOOL *stop) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [transaction.target performSelector:transaction.selector];
#pragma clang diagnostic pop
    }];
}

static void CSTransactionSetup() {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        transactionSet = [NSMutableSet new];
        CFRunLoopRef runloop = CFRunLoopGetMain();
        CFRunLoopObserverRef observer;

        observer = CFRunLoopObserverCreate(CFAllocatorGetDefault(),
                                           kCFRunLoopBeforeWaiting | kCFRunLoopExit,
                                           true,      // repeat
                                           0xFFFFFF,  // after CATransaction(2000000)
                                           CSRunLoopObserverCallBack, NULL);
        CFRunLoopAddObserver(runloop, observer, kCFRunLoopCommonModes);
        CFRelease(observer);
    });
}

@implementation CSTransaction_Utility

+ (CSTransaction_Utility *)transactionWithTarget:(id)target selector:(SEL)selector{
    if (!target || !selector) return nil;
    CSTransaction_Utility *t = [CSTransaction_Utility new];
    t.target = target;
    t.selector = selector;
    return t;
}

- (void)commit {
    if (!_target || !_selector) return;
    CSTransactionSetup();
    [transactionSet addObject:self];
}

- (NSUInteger)hash {
    long v1 = (long)((void *)_selector);
    long v2 = (long)_target;
    return v1 ^ v2;
}

- (BOOL)isEqual:(id)object {
    if (self == object) return YES;
    if (![object isMemberOfClass:self.class]) return NO;
    CSTransaction_Utility *other = object;
    return other.selector == _selector && other.target == _target;
}

@end


text:
/*
© 2017 Altavant Technologies Inc.
Web: http://www.altavant.com
*/

using UIKit;

namespace Altavant.AssetGen
{
	public class AssetGen
	{
		public static void Main(string[] args)
		{
			UIApplication.Main(args, null, "AppDelegate");
		}
	}
}


text:
import os
from pycodeexport.codeexport import make_PCEExtension_for_prebuilding_Code

def get_gsl_pce_ext(basename):
    from .interface import GSL_Code
    return make_PCEExtension_for_prebuilding_Code(
        basename+'.gsl._drivers', GSL_Code,
        ['drivers.c', '_drivers.pyx'],
        srcdir=os.path.join(basename, 'gsl'),
        logger=True
    )


text:
var fooRequires = 0;
module.exports = {
    fooRequires: function () { return fooRequires; }
  , incFooRequires: function () { fooRequires++; }
};


text:
namespace chromeos {

BluetoothManagerClient::Properties::Properties(dbus::ObjectProxy* object_proxy,
                                               PropertyChangedCallback callback)
    : BluetoothPropertySet(object_proxy,
                           bluetooth_manager::kBluetoothManagerInterface,
                           callback) {
  RegisterProperty(bluetooth_manager::kAdaptersProperty, &adapters);
}

BluetoothManagerClient::Properties::~Properties() {
}

// The BluetoothManagerClient implementation used in production.
class BluetoothManagerClientImpl : public BluetoothManagerClient {
 public:
  explicit BluetoothManagerClientImpl(dbus::Bus* bus)
      : weak_ptr_factory_(this),
        object_proxy_(NULL) {
    DVLOG(1) << "Creating BluetoothManagerClientImpl";

    // Create the object proxy.
    DCHECK(bus);
    object_proxy_ = bus->GetObjectProxy(
        bluetooth_manager::kBluetoothManagerServiceName,
        dbus::ObjectPath(bluetooth_manager::kBluetoothManagerServicePath));

    object_proxy_->ConnectToSignal(
        bluetooth_manager::kBluetoothManagerInterface,
        bluetooth_manager::kAdapterAddedSignal,
        base::Bind(&BluetoothManagerClientImpl::AdapterAddedReceived,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&BluetoothManagerClientImpl::AdapterAddedConnected,
                   weak_ptr_factory_.GetWeakPtr()));

    object_proxy_->ConnectToSignal(
        bluetooth_manager::kBluetoothManagerInterface,
        bluetooth_manager::kAdapterRemovedSignal,
        base::Bind(&BluetoothManagerClientImpl::AdapterRemovedReceived,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&BluetoothManagerClientImpl::AdapterRemovedConnected,
                   weak_ptr_factory_.GetWeakPtr()));

    object_proxy_->ConnectToSignal(
        bluetooth_manager::kBluetoothManagerInterface,
        bluetooth_manager::kDefaultAdapterChangedSignal,
        base::Bind(&BluetoothManagerClientImpl::DefaultAdapterChangedReceived,
                   weak_ptr_factory_.GetWeakPtr()),
        base::Bind(&BluetoothManagerClientImpl::DefaultAdapterChangedConnected,
                   weak_ptr_factory_.GetWeakPtr()));

    // Create the properties structure.
    properties_ = new Properties(
        object_proxy_,
        base::Bind(&BluetoothManagerClientImpl::OnPropertyChanged,
                   weak_ptr_factory_.GetWeakPtr()));

    properties_->ConnectSignals();
    properties_->GetAll();
  }

  virtual ~BluetoothManagerClientImpl() {
    // Clean up the Properties structure.
    delete properties_;
  }

  // BluetoothManagerClient override.
  virtual void AddObserver(Observer* observer) OVERRIDE {
    DCHECK(observer);
    observers_.AddObserver(observer);
  }

  // BluetoothManagerClient override.
  virtual void RemoveObserver(Observer* observer) OVERRIDE {
    DCHECK(observer);
    observers_.RemoveObserver(observer);
  }

  // BluetoothManagerClient override.
  virtual Properties* GetProperties() OVERRIDE {
    return properties_;
  }

  // BluetoothManagerClient override.
  virtual void DefaultAdapter(const AdapterCallback& callback) OVERRIDE {
    dbus::MethodCall method_call(
      bluetooth_manager::kBluetoothManagerInterface,
      bluetooth_manager::kDefaultAdapter);

    DCHECK(object_proxy_);
    object_proxy_->CallMethod(
      &method_call,
      dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(&BluetoothManagerClientImpl::OnDefaultAdapter,
                 weak_ptr_factory_.GetWeakPtr(), callback));
  }

  // BluetoothManagerClient override.
  virtual void FindAdapter(const std::string& address,
                           const AdapterCallback& callback) {
    dbus::MethodCall method_call(
      bluetooth_manager::kBluetoothManagerInterface,
      bluetooth_manager::kFindAdapter);

    dbus::MessageWriter writer(&method_call);
    writer.AppendString(address);

    DCHECK(object_proxy_);
    object_proxy_->CallMethod(
      &method_call,
      dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
      base::Bind(&BluetoothManagerClientImpl::OnFindAdapter,
                 weak_ptr_factory_.GetWeakPtr(), callback));
  }

 private:
  // Called by BluetoothPropertySet when a property value is changed,
  // either by result of a signal or response to a GetAll() or Get()
  // call. Informs observers.
  void OnPropertyChanged(const std::string& property_name) {
    FOR_EACH_OBSERVER(BluetoothManagerClient::Observer, observers_,
                      ManagerPropertyChanged(property_name));
  }

  // Called by dbus:: when an AdapterAdded signal is received.
  void AdapterAddedReceived(dbus::Signal* signal) {
    DCHECK(signal);
    dbus::MessageReader reader(signal);
    dbus::ObjectPath object_path;
    if (!reader.PopObjectPath(&object_path)) {
      LOG(WARNING) << "AdapterAdded signal has incorrect parameters: "
                   << signal->ToString();
      return;
    }

    DVLOG(1) << "Adapter added: " << object_path.value();
    FOR_EACH_OBSERVER(Observer, observers_, AdapterAdded(object_path));
  }

  // Called by dbus:: when the AdapterAdded signal is initially connected.
  void AdapterAddedConnected(const std::string& interface_name,
                             const std::string& signal_name,
                             bool success) {
    LOG_IF(WARNING, !success) << "Failed to connect to AdapterAdded signal.";
  }

  // Called by dbus:: when an AdapterRemoved signal is received.
  void AdapterRemovedReceived(dbus::Signal* signal) {
    DCHECK(signal);
    dbus::MessageReader reader(signal);
    dbus::ObjectPath object_path;
    if (!reader.PopObjectPath(&object_path)) {
      LOG(WARNING) << "AdapterRemoved signal has incorrect parameters: "
                   << signal->ToString();
      return;
    }

    DVLOG(1) << "Adapter removed: " << object_path.value();
    FOR_EACH_OBSERVER(Observer, observers_, AdapterRemoved(object_path));
  }

  // Called by dbus:: when the AdapterRemoved signal is initially connected.
  void AdapterRemovedConnected(const std::string& interface_name,
                               const std::string& signal_name,
                               bool success) {
    LOG_IF(WARNING, !success) << "Failed to connect to AdapterRemoved signal.";
  }

  // Called by dbus:: when a DefaultAdapterChanged signal is received.
  void DefaultAdapterChangedReceived(dbus::Signal* signal) {
    DCHECK(signal);
    dbus::MessageReader reader(signal);
    dbus::ObjectPath object_path;
    if (!reader.PopObjectPath(&object_path)) {
      LOG(WARNING) << "DefaultAdapterChanged signal has incorrect parameters: "
                   << signal->ToString();
      return;
    }

    DVLOG(1) << "Default adapter changed: " << object_path.value();
    FOR_EACH_OBSERVER(Observer, observers_, DefaultAdapterChanged(object_path));
  }

  // Called by dbus:: when the DefaultAdapterChanged signal is initially
  // connected.
  void DefaultAdapterChangedConnected(const std::string& interface_name,
                                      const std::string& signal_name,
                                      bool success) {
    LOG_IF(WARNING, !success)
        << "Failed to connect to DefaultAdapterChanged signal.";
  }

  // Called when a response for DefaultAdapter() is received.
  void OnDefaultAdapter(const AdapterCallback& callback,
                        dbus::Response* response) {
    // Parse response.
    bool success = false;
    dbus::ObjectPath object_path;
    if (response != NULL) {
      dbus::MessageReader reader(response);
      if (!reader.PopObjectPath(&object_path)) {
        LOG(WARNING) << "DefaultAdapter response has incorrect parameters: "
                     << response->ToString();
      } else {
        success = true;
      }
    } else {
      LOG(WARNING) << "Failed to get default adapter.";
    }

    // Notify client.
    callback.Run(object_path, success);
  }

  // Called when a response for FindAdapter() is received.
  void OnFindAdapter(const AdapterCallback& callback,
                     dbus::Response* response) {
    // Parse response.
    bool success = false;
    dbus::ObjectPath object_path;
    if (response != NULL) {
      dbus::MessageReader reader(response);
      if (!reader.PopObjectPath(&object_path)) {
        LOG(WARNING) << "FindAdapter response has incorrect parameters: "
                     << response->ToString();
      } else {
        success = true;
      }
    } else {
      LOG(WARNING) << "Failed to find adapter.";
    }

    // Notify client.
    callback.Run(object_path, success);
  }

  // Weak pointer factory for generating 'this' pointers that might live longer
  // than we do.
  base::WeakPtrFactory<BluetoothManagerClientImpl> weak_ptr_factory_;

  // D-Bus proxy for BlueZ Manager interface.
  dbus::ObjectProxy* object_proxy_;

  // Properties for BlueZ Manager interface.
  Properties* properties_;

  // List of observers interested in event notifications from us.
  ObserverList<Observer> observers_;

  DISALLOW_COPY_AND_ASSIGN(BluetoothManagerClientImpl);
};

// The BluetoothManagerClient implementation used on Linux desktop, which does
// nothing.
class BluetoothManagerClientStubImpl : public BluetoothManagerClient {
 public:
  // BluetoothManagerClient override.
  virtual void AddObserver(Observer* observer) OVERRIDE {
  }

  // BluetoothManagerClient override.
  virtual void RemoveObserver(Observer* observer) OVERRIDE {
  }

  // BluetoothManagerClient override.
  virtual Properties* GetProperties() OVERRIDE {
    VLOG(1) << "GetProperties";
    return NULL;
  }

  // BluetoothManagerClient override.
  virtual void DefaultAdapter(const AdapterCallback& callback) OVERRIDE {
    VLOG(1) << "DefaultAdapter.";
    callback.Run(dbus::ObjectPath(), false);
  }

  // BluetoothManagerClient override.
  virtual void FindAdapter(const std::string& address,
                           const AdapterCallback& callback) {
    VLOG(1) << "FindAdapter: " << address;
    callback.Run(dbus::ObjectPath(), false);
  }
};

BluetoothManagerClient::BluetoothManagerClient() {
}

BluetoothManagerClient::~BluetoothManagerClient() {
}

BluetoothManagerClient* BluetoothManagerClient::Create(dbus::Bus* bus) {
  if (base::chromeos::IsRunningOnChromeOS()) {
    return new BluetoothManagerClientImpl(bus);
  } else {
    return new BluetoothManagerClientStubImpl();
  }
}

}  // namespace chromeos


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>FreeType-2.5.0 API Reference</title>

[Index]

FreeType-2.5.0 API Reference

Table of Contents

General Remarks

User allocation

How client applications should allocate FreeType data structures.

Core API

FreeType Version

Functions and macros related to FreeType versions.

Basic Data Types

The basic data types defined by the library.

Base Interface

The FreeType 2 base font interface.

Glyph Variants

The FreeType 2 interface to Unicode Ideographic Variation Sequences (IVS), using the SFNT cmap format 14.

Glyph Management

Generic interface to manage individual glyph data.

Mac Specific Interface

Only available on the Macintosh.

Size Management

Managing multiple sizes per face.

Header File Macros

Macro definitions used to #include specific header files.

Format-Specific API

Multiple Masters

How to manage Multiple Masters fonts.

TrueType Tables

TrueType specific table types and functions.

Type 1 Tables

Type 1 (PostScript) specific font tables.

SFNT Names

Access the names embedded in TrueType and OpenType files.

BDF and PCF Files

BDF and PCF specific API.

CID Fonts

CID-keyed font specific API.

PFR Fonts

PFR/TrueDoc specific API.

Window FNT Files

Windows FNT specific API.

Font Formats

Getting the font format.

Gasp Table

Retrieving TrueType ‘gasp’ table entries.

Controlling FreeType Modules

The auto-hinter

Controlling the auto-hinting module.

The CFF driver

Controlling the CFF driver module.

The TrueType driver

Controlling the TrueType driver module.

Cache Sub-System

Cache Sub-System

How to cache face, size, and glyph data with FreeType 2.

Support API

Computations

Crunching fixed numbers and vectors.

List Processing

Simple management of lists.

Outline Processing

Functions to create, transform, and render vectorial glyph images.

Quick retrieval of advance values

Retrieve horizontal and vertical advance values without processing glyph outlines, if possible.

Bitmap Handling

Handling FT_Bitmap objects.

Scanline Converter

How vectorial outlines are converted into bitmaps and pixmaps.

Glyph Stroker

Generating bordered and stroked glyphs.

System Interface

How FreeType manages memory and i/o.

Module Management

How to add, upgrade, remove, and control modules from FreeType.

GZIP Streams

Using gzip-compressed font files.

LZW Streams

Using LZW-compressed font files.

BZIP2 Streams

Using bzip2-compressed font files.

LCD Filtering

Reduce color fringes of LCD-optimized bitmaps.

Miscellaneous

OpenType Validation

An API to validate OpenType tables.

Incremental Loading

Custom Glyph Loading.

The TrueType Engine

TrueType bytecode support.

TrueTypeGX/AAT Validation

An API to validate TrueTypeGX/AAT tables.

Global Index

[Index]

generated on Wed Jun 19 23:29:20 2013


text:
package org.keycloak.operator.v2alpha1.crds;

import java.util.List;
import java.util.Objects;

/**
 * @author Vaclav Muzikar <vmuzikar@redhat.com>
 */
public class KeycloakStatus {
    private List<KeycloakStatusCondition> conditions;

    public List<KeycloakStatusCondition> getConditions() {
        return conditions;
    }

    public void setConditions(List<KeycloakStatusCondition> conditions) {
        this.conditions = conditions;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        KeycloakStatus status = (KeycloakStatus) o;
        return Objects.equals(getConditions(), status.getConditions());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getConditions());
    }
}


text:
package org.apache.druid.server.security;

import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import org.apache.druid.java.util.http.client.HttpClient;

/**
 * This interface provides methods needed for escalating internal system requests with priveleged authentication
 * credentials. Each Escalator is associated with a specific authentication scheme, like Authenticators.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = NoopEscalator.class)
@JsonSubTypes(value = {
    @JsonSubTypes.Type(name = "noop", value = NoopEscalator.class),
})
public interface Escalator
{
  /**
   * Return a client that sends requests with the format/information necessary to authenticate successfully
   * against this Escalator's authentication scheme using the identity of the internal system user.
   * <p>
   * This HTTP client is used for internal communications between Druid nodes, such as when a broker communicates
   * with a historical node during query processing.
   *
   * @param baseClient Base HTTP client for internal Druid communications
   *
   * @return metamx HttpClient that sends requests with the credentials of the internal system user
   */
  HttpClient createEscalatedClient(HttpClient baseClient);

  /**
   * @return an AuthenticationResult representing the identity of the internal system user.
   */
  AuthenticationResult createEscalatedAuthenticationResult();

}


text:
import numpy as np

# =============================================================================
# Define variables
# =============================================================================

# =============================================================================
# Define functions
# =============================================================================
def timestamp(types=None):
    """
    Creates a timestamp string

    :param types: integer, 0 1 or 2 see below:

        mode 0: YYYY-MM-DD_HH-MM-SS    (Default)
        mode 1: HH:MM:SS
        mode 2: YYYY/MM/DD

    :return today: string, timestamp in format above
    """
    now = datetime.datetime.now()
    if(types==1):
        today = str(now.hour)+":"+str(now.minute)+":"+str(now.second)
    elif(types==2):
        today = str(now.year)+"/"+str(now.month)+"/"+str(now.day)
    else:
        today = str(now.year)+"-"+str(now.month)+"-"+str(now.day)+\
                "_"+str(now.hour)+"-"+str(now.minute)+"-"+str(now.second)
    return today

def percentage(it1, total, message, ptype=None):
    """
    ===========================================================================
    Displays percentage bar
    ===========================================================================
    Displays a simple message followed by a updating percentage
    bar, for use inside a loop, variables are as follows:

     - Format:
        percentage(it1, total, message, ptype)

            it1 (INT) is the iteration number of the loops

            total (INT) is the total number of iterations of the loop

            message (STRING) is displayed as follows:
                "[message] ...0%"
                "[message] ...50%"
                "[message] ...100%"

            ptype (STRING) is the format in which to return the percentage.
                Current accepted formats are:

                'i'         - returns percentage in integer form

                    message ...12%

                'f0'         - returns percentage in integer form

                    message ...12%

                'f2'         - returns percentage to two decimal places

                    message ...12.34%

                'f4'         - returns percentage to four decimal places

                    message ...12.3456%

                'bar'      - returns a loading percentage bar:

                    Loading =================================================

                None/Other  - returns percentage to six decimal places
    """
    import sys as sys

    percent = (float(it1) / float(total)) * 100.0
    if ptype == 'i':
        sys.stdout.write("\r" + message + "...%d%%" % percent)
        sys.stdout.flush()
    elif ptype == 'f0':
        sys.stdout.write("\r" + message + "...%.0f%%" % percent)
        sys.stdout.flush()
    elif ptype == 'f2':
        sys.stdout.write("\r" + message + "...%.2f%%" % percent)
        sys.stdout.flush()
    elif ptype == 'f4':
        sys.stdout.write("\r" + message + "...%.4f%%" % percent)
        sys.stdout.flush()
    elif ptype == 'bar':
        for j1 in range(1, 50):
            if round(percent) == float(j1 * 2.0):
                sys.stdout.write("\r" + "Loading (%.2f%%)" % percent + "=" * j1)
                sys.stdout.flush()
    else:
        sys.stdout.write("\r" + message + "...%.6f%%" % percent)
        sys.stdout.flush()

def percentage2(i1, i2, t1, t2, message, ptype=None):
    """
    ===========================================================================
    Displays percentage bar
    ===========================================================================
    Same as percentage except for a double for loop

    i.e.     it1 = i2 + i1*t2 + 1

             total = t1 * t2
    """
    it1 = i2 + i1 * t2 + 1
    total = t1 * t2

    percentage(it1, total, message, ptype=ptype)

def makedirs(folder):
    """
    Checks whether plot folder, subfolder and subsubfolder exist and
    if not creates the folders and folder path needed
    (warning try to create full path, so folder needs to be correct)

    :param folder: string, location of folder to create

    """
    temp = folder.split('/')
    xlink, xlink1 = '', ''
    made = False
    if len(temp[0]) == 0:
        temp[0] = '/'
    for j in ['..', '.', '/']:
        if temp[0] == j:
            for i in range(1, len(temp)):
                xlink = xlink + '/' + temp[i]
                if temp[i] not in os.listdir(j + xlink1) and temp[i] != '':
                    os.makedirs(j + xlink)
                    made = True
                    if prt:
                        print "makedirs"
                    tempdir = os.getcwd()
                    templink = folder.split('../')
                    if len(templink) == 1:
                        templink = folder.split('./')
                    print(str(timestamp(1)) + ": Made Folder: " + tempdir
                          + '/' + templink[-1])
                xlink1 = xlink
        if temp[0] not in ['..', '.', '/']:
            print ('\n' + str(timestamp(1)) +
                   ': Error: folder format not understood: ' + folder)
            made = True
    if not made:
        print('\n' + str(timestamp(1)) + ': All folders found for: ' +
              folder)
    return

def printcoeffs(p, f=2, xname='x', yname='f', formatx=None,
                errorlower=None, errorupper=None):
    """
    prints a nice version of coefficients
    :param p: list of floats, coefficents as in numpy.polyval
    :param f: integer, number of decimal places for coefficents
    :param xname: string, variable name assigned to x
    :param yname: string, variable name assigned to y
    :param formatx: None or string, format (currently None or "latex") if latex
                    use dollar notation to write string
    :param errorlower: None or list of floats, if None no uncertainties, if
                       error upper is None and error lower is not None assumes
                       uncertainties are equal i.e. +/-
                       error lower list must be same length as p
    :param errorupper: None or list of floats, error upper is None and
                       error lower is not None assumes uncertainties are equal
                       i.e. +/-
                       error upper list must be same length as p
    """
    # deal with formatting
    if formatx == 'latex':
        hat0, hat1 = '^{', '}'
        base0, base1 = '_{', '}'
        a0, a1 = '{hat0}', '{hat1}'
        b0, b1 = '{base0}', '{base1}'
        pm = r'\pm'
        ext = '$'
    else:
        hat0, hat1, hat2 = '^', '', ''
        base0, base1 = '', ''
        pm = '+-'
        a0, a1 = '+', ''
        b0, b1 = '-', ''
        ext = ''
    # deal with number of decimal places in coefficents
    d = '.{0}f'.format(f)
    # define length of coefficents (and assumed epu and epl)
    N = len(p)
    # deal formatting in the case of:
    #   1. no errors
    #   2. only error lower
    #   3. both error lower and uppwer
    if errorlower is None and errorupper is None:
        part0 = '{p:+' + d + '}'
        part1 = part0 + '{x}'
        partn = part1 + '{hat0}{n:.0f}{hat1}'

    elif errorupper is None:
        part0 = '[{p:+' + d + '}' + pm + '{epl:' + d + '}]'
        part1 = part0 + '{x}'
        partn = part1 + '{hat0}{n:.0f}{hat1}'
        epl = errorlower
        epu = np.zeros(N)
    else:
        part0 = ('[{p:+' + d + '}' + a0 + '+{epu:' + d + '}' + a1 +
                 b0 + '-{epl:' + d + '}' + b1 + ']')
        part1 = part0 + '{x}'
        partn = part1 + '{hat0}{n:.0f}{hat1}'
        epl = errorlower
        epu = errorupper
    # loop round p and construct coefficent string
    stringx = '{0}{1}({2})='.format(ext, yname, xname)
    for n in range(len(p)):
        # set up format dictionary
        fmt = dict(x=xname, p=p[n], epl=epl[n], epu=epu[n], n=N-n-1,
                   hat0=hat0, hat1=hat1, base0=base0, base1=base1)
        # if p[n] is zero skip
        if p[n] == 0:
            continue
        # if power=0 do not print +Ax^0, print +A
        if N - n -1 == 0:
            stringx += part0.format(**fmt)
        # if power=1 do not print +Ax^1, print Ax
        elif N - n -1 == 1:
            stringx += part1.format(**fmt)
        # else print +Ax^power
        else:
            stringx += partn.format(**fmt)
    stringx += ext
    # # get rid of any ++ and -+ and +-
    # stringx = stringx.replace('++', '+')
    # stringx = stringx.replace('-+', '-')
    # stringx = stringx.replace('+-', '-')
    # return string x
    return stringx


text:
<?php

namespace tallerreparacions\FrontEndBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction() {
        return $this->render('tallerreparacionsFrontEndBundle:Default:index.html.twig');
    }

    public function serveisAction() {
        return $this->render('tallerreparacionsFrontEndBundle:Default:serveis.html.twig');
    }

    public function llistatAction() {
        return $this->render('tallerreparacionsFrontEndBundle:Default:llistat.html.twig');
    }

    public function contactAction() {
        return $this->render('tallerreparacionsFrontEndBundle:Default:contact.html.twig');
    }
}


text:
DISS = diss.tex refs.bib propbody.tex figs/diagram.eps makefile.txt

PROP = proposal.tex propbody.tex

help:
	@echo
	@echo "USAGE:"
	@echo
	@echo "make          display help information"
	@echo "make prop     make the proposal and view it using xdvi"
	@echo "make diss.ps  make a postscript version of the dissertation"
	@echo "make diss.pdf make a .pdf version of the dissertation"
	@echo "make gv       view the dissertation with ghostview"
	@echo "make gs       view the dissertation with ghostscript"
	@echo "make all      construct proposal.dvi and diss.ps"
	@echo "make count    display an estimated word count"
	@echo "make pub      put demodiss.tar on my homepage"
	@echo "make clean    remove all remakeable files"
	@echo "make pr       print the dissertation"
	@echo

prop:	proposal.dvi
	xdvi proposal.dvi

diss.ps:	$(DISS)
	latex diss
	bibtex diss
	latex diss
	bibtex diss
	latex diss
	bibtex diss
	dvips -Ppdf -G0 -t a4 -pp 0-200 -o diss.ps diss.dvi

diss.pdf:	diss.ps
	ps2pdf diss.ps

makefile.txt:	Makefile
	expand Makefile >makefile.txt
count:
	detex diss.tex | tr -cd '0-9A-Za-z \n' | wc -w

proposal.dvi: $(PROP)
	latex proposal

all:	proposal.dvi diss.ps

pub:	diss.pdf
	cp diss.pdf /homes/mr/public_html/demodiss.pdf
	make clean
	(cd ..; tar cfv /homes/mr/public_html/demodiss.tar demodiss)

clean:
	rm -f diss.ps *.dvi *.aux *.log *.err
	rm -f core *~ *.lof *.toc *.blg *.bbl
	rm -f makefile.txt

gv:	diss.ps
	ghostview diss.ps

gs:	diss.ps
	gs diss.ps

pr:	diss.ps
	lpr diss.ps


text:
package com.txomon.rx;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.TextView;

import rx.Observable;
import rx.subjects.BehaviorSubject;
import rx.subjects.PublishSubject;

public class Events {

    // no instances for helper class
    private Events() {
    }

    /*
     * Creates a subject that emits events for the current text and each text change event
     */
    public static Observable<String> text(TextView view) {
        String currentText = String.valueOf(view.getText());
        final BehaviorSubject<String> subject = BehaviorSubject.create(currentText);
        view.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                subject.onNext(editable.toString());
            }
        });
        return subject;
    }

    /*
     * Creates a subject that emits events for each click on view
     */
    public static Observable<Object> click(View view) {
        final PublishSubject<Object> subject = PublishSubject.create();
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                subject.onNext(new Object());
            }
        });
        return subject;
    }

    /*
     * Creates a subject that emits events for item clicks of list views
     */
    public static Observable<Integer> itemClick(AbsListView view) {
        final PublishSubject<Integer> subject = PublishSubject.create();
        view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                subject.onNext(position);
            }
        });
        return subject;
    }

}


text:
#include <core/config.h>
#include <core/audio/Stream.h>
#include <core/audio/IOutput.h>
#include <core/audio/IPlayer.h>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/condition.hpp>
#include <sigslot/sigslot.h>

//////////////////////////////////////////////////////////////////////////////
namespace musik { namespace core { namespace audio {
//////////////////////////////////////////////////////////////////////////////

// Forward declare
class  Player;
class  Transport;
typedef boost::shared_ptr<Player> PlayerPtr;

//////////////////////////////////////////////////////////////////////////////
class  Player : public IPlayer {
    public:
        typedef boost::shared_ptr<IOutput> OutputPtr;

        static PlayerPtr Create(utfstring &url,OutputPtr *output=&OutputPtr());
    private:
        Player(utfstring &url,OutputPtr *output);
    public:
        ~Player(void);

        virtual void ReleaseBuffer(IBuffer *buffer);
        virtual void Notify();

        void Play();
        void Stop();
        void Pause();
        void Resume();

        double Position();
        void SetPosition(double seconds);

        double Volume();
        void SetVolume(double volume);

        bool Exited();

    public:
        typedef sigslot::signal1<Player*> PlayerEvent;
        PlayerEvent PlaybackStarted;
        PlayerEvent PlaybackAlmostEnded;
        PlayerEvent PlaybackEnded;
        PlayerEvent PlaybackError;

        OutputPtr output;

    private:
        void ThreadLoop();
        bool PreBuffer();
        int State();
        bool BufferQueueEmpty();

    protected:
        friend class Transport;
        utfstring url;
    private:
        StreamPtr stream;
        double volume;
        double currentPosition;

        double setPosition;

        long totalBufferSize;
        long maxBufferSize;

        typedef boost::scoped_ptr<boost::thread> ThreadPtr;
        ThreadPtr thread;

        typedef std::list<BufferPtr> BufferList;
        typedef std::set<BufferPtr> BufferSet;
        BufferList bufferQueue;
        BufferList lockedBuffers;

        typedef enum {
            Precache    = 0,
            Playing     = 1,
            Quit        = 2
        } States;

        int state;
        boost::mutex mutex;
        boost::condition waitCondition;

};

//////////////////////////////////////////////////////////////////////////////
} } }
//////////////////////////////////////////////////////////////////////////////


text:
package edu.emory.cci.aiw.i2b2etl.dest.metadata;

import org.protempa.ProtempaUtil;

/**
 *
 * @author arpAndrew Post
 */
abstract class ParentBuilder implements OntologyBuilder {
    private final String conceptCode;
    private final String displayName;
    private final OntologyBuilder[] children;
    private final Metadata metadata;
    private final boolean alreadyLoaded;

    ParentBuilder(Metadata metadata, String displayName, String conceptCode, boolean alreadyLoaded, OntologyBuilder... children) {
        assert metadata != null : "metadata cannot be null";
        assert displayName != null : "displayName cannot be null";
        assert conceptCode != null : "conceptCode cannot be null";
        ProtempaUtil.checkArrayForNullElement(children, "children");
        this.displayName = displayName;
        this.conceptCode = conceptCode;
        this.children = children;
        this.metadata = metadata;
        this.alreadyLoaded = alreadyLoaded;
    }

    @Override
    public void build(Concept parent) throws OntologyBuildException {
        Concept root = metadata.newContainerConcept(this.displayName, this.conceptCode);
        root.setAlreadyLoaded(this.alreadyLoaded);
        if (parent != null) {
            parent.add(root);
        }
        for (OntologyBuilder child : this.children) {
            child.build(root);
        }
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.castle</groupId>
    <artifactId>castle-platform</artifactId>
    <version>2.0</version>
  </parent>
  <artifactId>castle-themes</artifactId>
  <packaging>pom</packaging>
  <name>Castle Themes</name>
  <description>The themes of Castle Platform.</description>
  <modules>
  	<module>castle-theme-adminlte</module>
  	<module>castle-theme-uikit</module>
  	<module>castle-theme-uikit-custom</module>
  </modules>
</project>


text:
package com.xiaogua.better.reflect;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.junit.Test;

import com.xiaogua.better.bean.Interface_SayHello;
import com.xiaogua.better.bean.Simple_HelloImpl;

public class TestJavaDynamicProxy {

	@Test
	public void testJavaDynamicProxyHello() throws Exception {
		// 被动态代理的IHello实例对象A
		Interface_SayHello helloA = new Simple_HelloImpl("testName");
		// 生成对象A的动态代理
		Interface_SayHello helloAProxy = (Interface_SayHello) JavaDynamicProxy.generateProxy(helloA);
		helloAProxy.hello();

		@SuppressWarnings("restriction")
		//生成代理类,保存代理类的字节码
		byte[] fileClass = sun.misc.ProxyGenerator.generateProxyClass("$Proxy0",
				Simple_HelloImpl.class.getInterfaces());
		OutputStream out = new FileOutputStream(new File("e:/test_tmp/sys_" + System.currentTimeMillis() + ".class"));
		IOUtils.write(fileClass, out);
		IOUtils.closeQuietly(out);
	}
}


text:
var Cli = require('structured-cli');

var category = module.exports = Cli.createCategory('profile', {
    description: 'Manage webtask profiles',
});

category.addChild(require('./profile/init'));
category.addChild(require('./profile/ls'));
category.addChild(require('./profile/get'));
category.addChild(require('./profile/rm'));
category.addChild(require('./profile/nuke'));


text:
package org.kuali.rice.kew.docsearch;

import org.kuali.rice.core.api.uif.RemotableAttributeError;
import org.kuali.rice.kew.api.document.search.DocumentSearchCriteria;
import org.kuali.rice.kew.api.document.search.DocumentSearchResults;
import org.kuali.rice.kew.framework.document.search.DocumentSearchCriteriaConfiguration;
import org.kuali.rice.kew.framework.document.search.DocumentSearchResultSetConfiguration;
import org.kuali.rice.kew.framework.document.search.DocumentSearchResultValues;
import org.kuali.rice.kew.doctype.bo.DocumentType;

import java.util.List;

/**
 * Handles communication between {@link org.kuali.rice.kew.framework.document.search.DocumentSearchCustomizationHandlerService}
 * endpoints in order to invoke document search customizations which might be hosted from various applications.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public interface DocumentSearchCustomizationMediator {

    /**
     * Retrieves the document search criteria configuration for the given document type.  This should include attribute
     * fields that should be included in the document search user interface when displaying criteria by which a user
     * can search for documents.  If this method returns null then no additional criteria should be presented on the
     * search screen.
     *
     * @param documentType the document type for which to find document search criteria configuration, must not be null
     *
     * @return configuration information containing additional criteria (beyond the default set) which should be
     * displayed to the user when performing a search against documents of the given type, if null is returned this
     * indicates that the default document search criteria configuration should be used
     */
    DocumentSearchCriteriaConfiguration getDocumentSearchCriteriaConfiguration(DocumentType documentType);

    /**
     * Performs optional validation of document search criteria prior to execution of the search.
     *
     * @param documentType the document type against which the lookup is being performed
     * @param documentSearchCriteria the criteria representing the submission of the document search
     *
     * @return a list of error messages generated by the validation, may an empty list in which case the calling code
     * may safely ignore the response and assume that the given criteria validated successfully
     */
    List<RemotableAttributeError> validateLookupFieldParameters(DocumentType documentType,
            DocumentSearchCriteria documentSearchCriteria);

    /**
     * Optionally performs customization of the given document search criteria in the cases where the document type
     * implements criteria customization.  If this method returns a non-null value, then the calling code should use
     * the returned criteria in order to execute the search.  If this method returns a null value, it means the criteria
     * that was given did not require any customization.  In this case, the calling code should proceed with search
     * execution using the originally provided criteria.
     *
     * @param documentType the document type against which to perform the criteria customization, should never be null
     * @param documentSearchCriteria the criteria to use as the starting point for customization
     *
     * @return a customized version of the given criteria, or null if the criteria was not customized
     */
    DocumentSearchCriteria customizeCriteria(DocumentType documentType, DocumentSearchCriteria documentSearchCriteria);

    /**
     * Optionally performs a custom clearing of the given document search criteria if the given document type
     * implements a customized clear algorithm.  If this method returns a non-null value, then the value returned
     * should be instated by the calling code as the "cleared" version of the criteria.  If null is returned, then the
     * default implementation of criteria clearing should be used.
     *
     * @param documentType the document type against which to check for a custom implementation of criteria clearing
     * @param documentSearchCriteria the current criteria of the document search prior to being cleared
     *
     * @return the result of clearing the criteria, if this returns null it means the given document type does not
     * implement custom clearing and the default behavior should be used
     */
    DocumentSearchCriteria customizeClearCriteria(DocumentType documentType,
            DocumentSearchCriteria documentSearchCriteria);

    /**
     * Optionally performs customization on the given set of document search results.  This could include changing
     * existing document values or synthesizing new ones.  The results of this method include a list of
     * {@link org.kuali.rice.kew.framework.document.search.DocumentSearchResultValue} objects, each of which are mapped to a
     * specific document id from the results and include additional key-value pairs for customized or synthesized
     * values for that document.  This method can return a null value if no customization was performed.
     *
     * @param documentType the document type to use when determining what customization logic (if any) should be invoked
     * @param documentSearchCriteria the criteria of the document search which produced the supplied results
     * @param results the results of the document search which are being considered for customization
     *
     * @return the customized result values, or null if not result customization was performed
     */
    DocumentSearchResultValues customizeResults(DocumentType documentType,
            DocumentSearchCriteria documentSearchCriteria,
            DocumentSearchResults results);

    /**
     * Optionally provides configuration information that allows for document search result set customization to occur.
     * The resulting {@code DocumentSearchResultSetConfiguration} can be used by the calling code to determine how best
     * to render the lookup results.
     *
     * @param documentType the document type for which to customize result set configuration
     * @param documentSearchCriteria the criteria that was used to perform the lookup
     *
     * @return the customized document search result set configuration, or null if no result set customization was
     * performed
     */
    DocumentSearchResultSetConfiguration customizeResultSetConfiguration(DocumentType documentType,
            DocumentSearchCriteria documentSearchCriteria);

}


text:
package vn.tuan.app.controller;

import vn.tuan.app.model.SearchMachine;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

/**
 * Created by tuan on 19/04/2015.
 */
public class PlayButtonHandler implements ActionListener {
    private SearchMachine en = SearchMachine.getInstance();
    private Component c;

    public PlayButtonHandler(Component c){
        this.c=c;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        if(c instanceof JButton){
            ((JButton) c).setFocusPainted(true);
        }
        try {
            en.playForMe(en.getCurrentPick());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


text:
static const int GROUP_CREATION = 1;
static NSString *const DEFAULT_GROUP_ICON_NAME = @"applozic_group_icon";

@interface ALGroupCreationViewController ()

@property (nonatomic,strong) UIImagePickerController *mImagePicker;
@property (nonatomic,strong) NSString *mainFilePath;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityIndicator;

@end

@implementation ALGroupCreationViewController {
    UIBarButtonItem *nextContacts;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    nextContacts = [[UIBarButtonItem alloc] init];
    [nextContacts setStyle:UIBarButtonItemStylePlain];
    [nextContacts setTarget:self];

    self.navigationItem.rightBarButtonItem = nextContacts;

    if ([UIApplication sharedApplication].userInterfaceLayoutDirection == UIUserInterfaceLayoutDirectionRightToLeft) {
        self.groupNameInput.textAlignment = NSTextAlignmentRight;
    }

    NSDictionary *attrs = @{ NSForegroundColorAttributeName : UIColor.grayColor};
    self.groupNameInput.attributedPlaceholder = [[NSAttributedString alloc] initWithString:NSLocalizedStringWithDefaultValue(@"groupNameTextField", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Type your group name", @"") attributes:attrs];

    [self.descriptionTextView setText: NSLocalizedStringWithDefaultValue(@"descriptionTextForGroup", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Please provide group name", @"")];

    if (self.isViewForUpdatingGroup) {
        [self setTitle:NSLocalizedStringWithDefaultValue(@"groupUpdateViewText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Group Update", @"")];
        [nextContacts setTitle:NSLocalizedStringWithDefaultValue(@"updateUiButtonText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Update", @"")];
        [nextContacts setAction:@selector(updateGroupInfo:)];
        self.groupNameInput.text = self.channelName;
        [self setProfileImage];
    } else {
        [self setTitle:NSLocalizedStringWithDefaultValue(@"groupTitle", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Create Group", @"")];
        [nextContacts setTitle:NSLocalizedStringWithDefaultValue(@"nextUiButtonText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Next", @"")];
        [nextContacts setAction:@selector(launchContactSelection:)];
    }

    self.automaticallyAdjustsScrollViewInsets = NO; //setting to NO helps show UITextView's text at view load
    [self setupGroupIcon];

    self.mImagePicker = [[UIImagePickerController alloc] init];
    self.mImagePicker.delegate = self;
    self.mImagePicker.allowsEditing = YES;

    [self.activityIndicator setHidesWhenStopped:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    [self.groupNameInput becomeFirstResponder];
    self.descriptionTextView.hidden = NO;
    self.descriptionTextView.userInteractionEnabled = NO;
    [self.tabBarController.tabBar setHidden:YES];
}

- (void)setProfileImage {
    NSURL *imageURL = [NSURL URLWithString:self.groupImageURL];
    if (imageURL.path.length) {
        [self.groupIconView sd_setImageWithURL:imageURL placeholderImage:nil options:SDWebImageRefreshCached];
    } else {
        [self.groupIconView setImage:[ALUIUtilityClass getImageFromFramworkBundle:DEFAULT_GROUP_ICON_NAME]];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

//=========================================================================================================================================
#pragma mark - NAVIGATION RIGHT BUTTON SELECTORS : CREATION/UPDATE
//=========================================================================================================================================

- (void)launchContactSelection:(id)sender {
    //Check if group name text is empty
    if ([self.groupNameInput.text isEqualToString:@""]) {

        UIAlertController *alertController = [UIAlertController
                                              alertControllerWithTitle: NSLocalizedStringWithDefaultValue(@"groupNameInfo", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Group Name", @"")
                                              message: NSLocalizedStringWithDefaultValue(@"groupNameEmptyAlertMessage", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Please give the group name.", @"")
                                              preferredStyle:UIAlertControllerStyleAlert];

        [ALUIUtilityClass setAlertControllerFrame:alertController andViewController:self];

        UIAlertAction *okAction = [UIAlertAction
                                   actionWithTitle:NSLocalizedStringWithDefaultValue(@"okText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"OK", @"")                                   style:UIAlertActionStyleDefault
                                   handler:^(UIAlertAction *action)
                                   {
            ALSLog(ALLoggerSeverityInfo, @"OK action");
        }];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:YES completion:nil];
        return;
    }

    //Moving forward to member selection
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Applozic"
                                                         bundle:[NSBundle bundleForClass:ALGroupCreationViewController.class]];
    ALNewContactsViewController *contactsVC = [storyboard instantiateViewControllerWithIdentifier:@"ALNewContactsViewController"];

    //Setting groupName and forGroup flag
    contactsVC.forGroup = [NSNumber numberWithInt:GROUP_CREATION];
    contactsVC.groupName = self.groupNameInput.text;
    contactsVC.groupImageURL = self.groupImageURL;

    if ([ALApplozicSettings getSubGroupLaunchFlag]) {
        ALChannelService *channelService = [ALChannelService new];
        ALChannel *parentChannel = [channelService getChannelByKey:self.parentChannelKey];
        contactsVC.parentChannel = parentChannel;
        contactsVC.childChannels = [[NSMutableArray alloc] initWithArray:[channelService fetchChildChannelsWithParentKey:parentChannel.key]];
    }

    //Moving to contacts view for group member selection
    [self.navigationController pushViewController:contactsVC animated:YES];
}

- (void)updateGroupInfo:(id)sender {
    if (!self.groupNameInput.text.length) {
        [ALUIUtilityClass showAlertMessage:
         NSLocalizedStringWithDefaultValue(@"youHaveNotUpdatedAnything", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"You haven't update anything", @"")  andTitle:NSLocalizedStringWithDefaultValue(@"wait", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Wait!!!", @"")];
        return;

    }
    [self.loadingIndicator startAnimating];

    ALChannelService *channelService = [ALChannelService new];

    NSString *changedName;

    if (self.channelName != nil && [self.groupNameInput.text isEqualToString:self.channelName]) {
        changedName = nil;
    } else {
        changedName = self.groupNameInput.text;
    }
    ALChannel *oldChannel =  [channelService getChannelByKey:self.channelKey ];
    BOOL isIngoreUpdating = NO;
    if (oldChannel != nil && oldChannel.channelImageURL != NULL && [oldChannel.channelImageURL isEqualToString:self.groupImageURL]) {
        self.groupImageURL = nil;
        isIngoreUpdating = YES;
    }

    [channelService updateChannel:self.channelKey andNewName:changedName
                      andImageURL:self.groupImageURL orClientChannelKey:nil isUpdatingMetaData:isIngoreUpdating
                         metadata:nil orChildKeys:nil orChannelUsers:nil  withCompletion:^(NSError *error) {

        if (!error) {

            ALSLog(ALLoggerSeverityInfo, @"ALGroupCreationViewController updated the group info");
            [self.navigationController popViewControllerAnimated:YES];
            [self.grpInfoDelegate updateGroupInformation];
        }
        [self.loadingIndicator stopAnimating];
    }];
}

//=========================================================================================================================================
#pragma mark - GROUP ICON VIEW SETUP
//=========================================================================================================================================

- (void)setupGroupIcon {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.groupIconView.layer.cornerRadius = self.groupIconView.frame.size.width/2;
        self.groupIconView.layer.masksToBounds = YES;
        self.groupIconView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    });

    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(uploadImage)];
    singleTap.numberOfTapsRequired = 1;
    [self.groupIconView addGestureRecognizer:singleTap];
}

- (void)uploadImage {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

    [ALUIUtilityClass setAlertControllerFrame:alertController andViewController:self];

    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedStringWithDefaultValue(@"cancelOptionText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Cancel", @"") style:UIAlertActionStyleCancel handler:nil]];

    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedStringWithDefaultValue(@"photoLibraryText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Photo Library", @"")style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self uploadByPhotos];
    }]];

    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedStringWithDefaultValue(@"takePhotoText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Take Photo", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

        [self uploadByCamera];
    }]];

    if (self.isViewForUpdatingGroup && self.groupImageURL.length) {
        UIAlertAction *removeAction = [UIAlertAction actionWithTitle:NSLocalizedStringWithDefaultValue(@"removePhoto", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Remove Photo", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

            self.groupImageURL = @"";
            [self setProfileImage];
        }];

        [removeAction setValue:[UIColor redColor] forKey:@"titleTextColor"];
        [alertController addAction:removeAction];
    }

    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)uploadByPhotos {
    self.mImagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.mImagePicker.mediaTypes = [NSArray arrayWithObject:(NSString *)kUTTypeImage];
    [self presentViewController:self.mImagePicker animated:YES completion:nil];
}

- (void)uploadByCamera {
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {

            dispatch_async(dispatch_get_main_queue(), ^{

                if (granted) {
                    self.mImagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                    self.mImagePicker.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeImage, nil];
                    [self presentViewController:self.mImagePicker animated:YES completion:nil];
                } else {
                    [ALUIUtilityClass permissionPopUpWithMessage:NSLocalizedStringWithDefaultValue(@"permissionPopMessageForCamera", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Enable Camera Permission", @"") andViewController:self];
                }
            });
        }];
    } else {
        [ALUIUtilityClass showAlertMessage:NSLocalizedStringWithDefaultValue(@"permissionNotAvailableMessageForCamera", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Camera is not Available !!!", @"") andTitle:NSLocalizedStringWithDefaultValue(@"oppsText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"OPPS !!", @"")];

    }
}

//=========================================================================================================================================
#pragma mark - IMAGE PICKER DELEGATES
//=========================================================================================================================================

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    UIImage *rawImage = [info valueForKey:UIImagePickerControllerEditedImage];
    UIImage *normalizedImage = [ALUIUtilityClass getNormalizedImage:rawImage];
    [self.groupIconView setImage:normalizedImage];

    [picker dismissViewControllerAnimated:YES completion:nil];
    self.mainFilePath = [self getImageFilePath:normalizedImage];
    [self confirmUserForGroupImage:normalizedImage];
}

- (NSString *)getImageFilePath:(UIImage *)image {
    NSString *filePath = [ALImagePickerHandler saveImageToDocDirectory:image];
    return filePath;
}

- (void)confirmUserForGroupImage:(UIImage *)image {
    image = [image getCompressedImageLessThanSize:1];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedStringWithDefaultValue(@"confirmationText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Confirmation!", @"")
                                                                   message:NSLocalizedStringWithDefaultValue(@"areYouSureForUploadText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Are you sure to upload?", @"")
                                                            preferredStyle:UIAlertControllerStyleAlert];

    [ALUIUtilityClass setAlertControllerFrame:alert andViewController:self];

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedStringWithDefaultValue(@"cancelOptionText", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Cancel", @"") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self.groupIconView setImage:[ALUIUtilityClass getImageFromFramworkBundle:DEFAULT_GROUP_ICON_NAME]];
        [alert dismissViewControllerAnimated:YES completion:nil];
    }];

    UIAlertAction *upload = [UIAlertAction actionWithTitle: NSLocalizedStringWithDefaultValue(@"upload", [ALApplozicSettings getLocalizableName], [NSBundle mainBundle], @"Upload", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

        [self.activityIndicator startAnimating];

        if (![ALDataNetworkConnection checkDataNetworkAvailable]) {
            ALNotificationView *notification = [ALNotificationView new];
            [notification noDataConnectionNotificationView];
            [self.activityIndicator stopAnimating];
            return;
        }

        NSString *uploadUrl = [KBASE_URL stringByAppendingString:AL_IMAGE_UPLOAD_URL];

        self.groupImageUploadURL = uploadUrl;

        ALHTTPManager *manager = [[ALHTTPManager alloc]init];
        [manager uploadProfileImage:image withFilePath:self.mainFilePath uploadURL:uploadUrl withCompletion:^(NSData *_Nullable data, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (error == nil) {

                    NSString *imageLinkFromServer = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    ALSLog(ALLoggerSeverityInfo, @"GROUP_IMAGE_LINK :: %@",imageLinkFromServer);
                    self.groupImageURL = imageLinkFromServer;
                }
                [self.activityIndicator stopAnimating];
            });
        }];
    }];

    [alert addAction:cancel];
    [alert addAction:upload];
    [self presentViewController:alert animated:YES completion:nil];

}

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="404 Error Page for NicoJensen.de">
    <meta name="author" content="Nico Jensen">
    <link rel="shortcut icon" href="images/ico/favicon.ico">

    <title>Nico Jensen</title>

    <link href="style.css" rel="stylesheet">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,600' rel='stylesheet' type='text/css'>

Nico Jensen

Was kostet die Welt?! Achso... hm, dann nehm ich ne kleine Cola!

Tut mir leid die von Ihnen gesuchte Seite existiert nicht mehr oder hatte nie existiert. Wenn Sie jedoch der Meinung sind, dass die Seite existieren sollte, können Sie mir dies jederzeit Mitteilen. Meine Kontaktdaten dazu finden Sie auf der Hauptseite.

Handmade with ♥ in Hamburg by Nico Jensen


text:
{% load i18n %}
{% load currency_filters %}

{% trans "Basket" %}

        {% with discounts=order.basket_discounts %}
            {% block discount_totals %}
                {% if discounts %}

                        {% trans "Basket total (before discounts)" %}
                        {{ order.basket_total_before_discounts_incl_tax|currency:order.currency }}

                    {% for discount in discounts %}

                            {% trans "Discount" %} {{ discount.offer }}
                            - {{ discount.amount|currency:order.currency }}

                    {% endfor %}
                {% endif %}
            {% endblock discount_totals %}

            {% block basket_total %}
                {% if discounts %}

                        {% trans "Basket total (after discounts)" %}
                        {{ order.basket_total_incl_tax|currency:order.currency }}

                {% else %}

                        {% trans "Basket total" %}

                            {% if show_tax_separately %}
                                {{ order.basket_total_excl_tax|currency:order.currency }}
                            {% else %}
                                {{ order.basket_total_incl_tax|currency:order.currency }}
                            {% endif %}

                {% endif %}
            {% endblock basket_total %}
        {% endwith %}

        {% block shipping_total %}

{% trans "Shipping" %}

                {% trans "Shipping method" %}
                {{ order.shipping_method }}

            {% if order.has_shipping_discounts %}

                    {% trans "Shipping charge (before discounts)" %}
                    {{ order.shipping_before_discounts_incl_tax|currency:order.currency }}

                {% for discount in order.shipping_discounts %}

                        {% trans "Discount" %} {{ discount.offer }}
                        - {{ discount.amount|currency:order.currency }}

                {% endfor %}

                    {% trans "Shipping charge (after discounts)" %}
                    {{ order.shipping_incl_tax|currency:order.currency }}

            {% else %}

                    {% trans "Shipping charge" %}

                        {% if show_tax_separately %}
                            {{ order.shipping_excl_tax|currency:order.currency }}
                        {% else %}
                            {{ order.shipping_incl_tax|currency:order.currency }}
                        {% endif %}

            {% endif %}
        {% endblock shipping_total %}

        {% block surcharges %}
            {% with surcharges=order.surcharges.all %}
            {% if surcharges %}

{% trans "Surcharges" %}

                {% for charge in surcharges %}

                        {{ charge.name }}

                            {% if show_tax_separately %}
                                {{ charge.excl_tax|currency:order.currency }}
                            {% else %}
                                {{ charge.incl_tax|currency:order.currency }}
                            {% endif %}

                {% endfor %}
            {% endif %}
            {% endwith %}
        {% endblock %}

        {% if show_tax_separately %}

                {% trans "Order tax" %}

                    {{ order.total_tax|currency:order.currency }}

        {% endif %}

        {% block post_order_action_totals %}
            {% with actions=order.post_order_actions %}
                {% if actions %}

{% trans "Post order actions" %}

                    {% for action in order.post_order_actions %}

{{ action.message }}

                    {% endfor %}
                {% endif %}
            {% endwith %}
        {% endblock post_order_action_totals %}

        {% block order_total %}

{% trans "Order total" %}

{{ order.total_incl_tax|currency:order.currency }}

        {% endblock order_total %}


text:
const Promise = require('bluebird');
const moment = require('moment');
const find = require('lodash/find');

exports.duration = 50 * 30 * 3 * 1000;

exports.simpleDispatcher = function simpleDispatcher(service) {
  return function dispatch(route, params) {
    return service.amqp.publishAndWait(route, params, { timeout: exports.duration * 2 });
  };
};

exports.clearRedis = function clearRedis(redis) {
  if (redis.nodes) {
    const nodes = redis.nodes('master');

    return Promise
      .map(nodes, (node) => node.flushdb())
      .reflect();
  }

  return redis.flushdb();
};

async function updateUserMetadata(service, owner, subscription, agreement, planId) {
  const { prefix, postfix, audience } = service.config.users;
  const path = `${prefix}.${postfix.updateMetadata}`;
  const updateRequest = {
    username: owner,
    audience,
    metadata: {
      $set: {
        nextCycle: moment(agreement.start_date).valueOf(),
        agreement: agreement.id,
        plan: planId,
        modelPrice: subscription.price,
        subscriptionType: 'paypal',
        subscriptionPrice: agreement.plan.payment_definitions[0].amount.value,
        subscriptionInterval: agreement.plan.payment_definitions[0].frequency.toLowerCase(),
      },
      $incr: {
        models: subscription.models,
      },
    },
  };

  await service.amqp
    .publishAndWait(path, updateRequest, { timeout: 5000 });
}

/**
 * Temporary workaround. To remove writes to ms-users, but still support read operations,
 * I request metadata update outside of the agreement execute logic.
 * In future, we must pass user everywhere instead of fetching it from ms-users by agreement id.
 */
async function afterAgreementExecution(service, dispatch, agreement, planId) {
  const subscriptionName = agreement.plan.payment_definitions[0].frequency.toLowerCase();
  const plan = await dispatch('payments.plan.get', planId);
  const subscription = find(plan.subs, { name: subscriptionName });
  await updateUserMetadata(service, 'test@test.ru', subscription, agreement, planId);
}

exports.afterAgreementExecution = afterAgreementExecution;


text:
import json
import time
import threading

from functools import wraps
from inspect import getcallargs

class CacheNameClashException(Exception):
    pass

# Though it might make sense to look for name clashes on
# per-cache level, it is conceivable that we might call
# create_cache on the same connection twice, so this
# is a better safeguard against bad habits, even though it's global
decorated = {}

def mangle(fname, f, args, kwargs):
    # We uniquely identify functions by their list of arguments
    # as resolved by the function definition.
    print(fname, f, args, kwargs)
    print(getcallargs)
    print(json.dumps(sorted(getcallargs(f, *args, **kwargs).items(), key=lambda x: x[0])))

    return "@" + fname + "_" + json.dumps(getcallargs(f, *args, **kwargs))

def create_cache(cache_store, prefix=""):
    """
    Creates a caching decorator that connects to the given Redis client
    (or any object similarly supporting get(), set() and lock())

    `cache_store` -- An object supporting get(), set(), and lock()

    `prefix` -- a prefix to append to the keys of the cache entries for the functions decorated
        by the returned decorator. This prevents name clashes between identically-named functions
        in the same module

    Returns -- cache decorator function
    """

    def cache(expires=5, prefix=prefix, bg_caching=False, stale=None):
        """
        Decorator for any function which takes json-serializable arguments and returns json-serializable output
        which caches the results for the given arguments in the given redis database.

        `expires` -- How long to return cached results before calling the underlying function again.
            Defaults to 5 seconds, since permanent caching is rarely what is actually desired.
        `prefix` -- A prefix appended to the cache keys of the decorated function
        `bg_caching` -- Whether to return cached results while results are updated from the underlying function
            in a background thread
        `stale` -- How long old results can be returned when bg_caching is True, so that two calls don't
            try to update the cache in the background. Defaults to 2 * expires
        """
        if not stale:
            stale = 2 * expires

        def decorate(f):
            fname = prefix + "_" + f.__module__ + "_" + f.__name__
            # Prevent two functions in the same program with the same name from
            # accidentally stepping on each others' cache.
            if decorated.get(fname):
                raise CacheNameClashException("A function with the name " + f.__name__ + " has already been cached elsewhere in this module. Please add a prefix to these functions to uniquely identify them")
            decorated[fname] = True

            def update_cache(f, lock, *args, **kwargs):
                try:
                    result = f(*args, **kwargs)
                    cache_store.set(mangle(fname, f, args, kwargs), json.dumps({'timestamp': time.time(), 'result': result}))
                    return result
                finally:
                    lock.release()

            @wraps(f)
            def wrapped(*args, **kwargs):
                cached_result = cache_store.get(mangle(fname, f, args, kwargs))
                try:
                    cached_result = json.loads(cached_result)
                except:
                    cached_result = {}

                now = time.time()
                age = now - cached_result.get('timestamp', 0) if cached_result else now
                if not cached_result or age > expires:
                    # Have to use try-finally instead of with, since the implementation of __enter__
                    # in redis.lock.Lock automatically blocks https://github.com/andymccurdy/redis-py/blob/master/redis/lock.py
                    # We don't want thread-local storage because we want to release our lock from the
                    # background thread
                    lock = cache_store.lock('__lock_' + fname, timeout=expires, blocking_timeout=0.1, thread_local=False)
                    if lock.acquire():
                        if bg_caching and cached_result and now - cached_result['timestamp'] < stale:
                            # Update redis in the bg, and return the already-cached result, if we already have something
                            # in the cache and it's still valid.
                            try:
                                # update_cache releases the lock when it's done
                                threading.Thread(target=update_cache, args=(f, lock) + args, kwargs=kwargs).start()
                            except Exception as e:
                                lock.release()
                                raise e
                        else:
                            # Otherwise update the cache and return the result of the function in this thread
                            return update_cache(f, lock, *args, **kwargs)
                    else:
                        # Can't get the lock, just return the underlying function
                        if not bg_caching or not cached_result:
                            return f(*args, **kwargs)

                return cached_result['result']

            return wrapped
        return decorate
    return cache


text:
package by.bsu.dao;

import by.bsu.exception.dao.DAOCarException;
import by.bsu.model.Car;

import java.util.List;

public interface DAOCar {
    public Car getCarById(int carId) throws DAOCarException;
    public List<Car> getAllCars() throws DAOCarException;
    public List<Car> getCarsInCity(String city) throws DAOCarException;

    public void addCar(Car car) throws DAOCarException;

    public void deleteCarById(int id) throws DAOCarException;

    public void updateCity(int id, String city) throws DAOCarException;

}


text:
<!DOCTYPE html>

<title>Modest Maps JS - Throwable Test</title>

Click/drag to throw the map, or press and hold the arrow keys to fly around.

drag : <input id="drag" type="range" value="1000" min="0" max="2000"></input>

zoom : <input id="zoom" type="range" value="10000" min="0" max="18000"></input>

Built with Modest Maps JS. Tiles Courtesy of MapQuest


text:
package osl

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"runtime"
	"sync"
	"syscall"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/docker/docker/pkg/reexec"
	"github.com/docker/libnetwork/ns"
	"github.com/docker/libnetwork/types"
	"github.com/vishvananda/netlink"
	"github.com/vishvananda/netns"
)

const prefix = "/var/run/docker/netns"

var (
	once             sync.Once
	garbagePathMap   = make(map[string]bool)
	gpmLock          sync.Mutex
	gpmWg            sync.WaitGroup
	gpmCleanupPeriod = 60 * time.Second
	gpmChan          = make(chan chan struct{})
	nsOnce           sync.Once
)

// The networkNamespace type is the linux implementation of the Sandbox
// interface. It represents a linux network namespace, and moves an interface
// into it when called on method AddInterface or sets the gateway etc.
type networkNamespace struct {
	path         string
	iFaces       []*nwIface
	gw           net.IP
	gwv6         net.IP
	staticRoutes []*types.StaticRoute
	neighbors    []*neigh
	nextIfIndex  int
	sync.Mutex
}

func init() {
	reexec.Register("netns-create", reexecCreateNamespace)
}

func createBasePath() {
	err := os.MkdirAll(prefix, 0755)
	if err != nil {
		panic("Could not create net namespace path directory")
	}

	// Start the garbage collection go routine
	go removeUnusedPaths()
}

func removeUnusedPaths() {
	gpmLock.Lock()
	period := gpmCleanupPeriod
	gpmLock.Unlock()

	ticker := time.NewTicker(period)
	for {
		var (
			gc   chan struct{}
			gcOk bool
		)

		select {
		case <-ticker.C:
		case gc, gcOk = <-gpmChan:
		}

		gpmLock.Lock()
		pathList := make([]string, 0, len(garbagePathMap))
		for path := range garbagePathMap {
			pathList = append(pathList, path)
		}
		garbagePathMap = make(map[string]bool)
		gpmWg.Add(1)
		gpmLock.Unlock()

		for _, path := range pathList {
			os.Remove(path)
		}

		gpmWg.Done()
		if gcOk {
			close(gc)
		}
	}
}

func addToGarbagePaths(path string) {
	gpmLock.Lock()
	garbagePathMap[path] = true
	gpmLock.Unlock()
}

func removeFromGarbagePaths(path string) {
	gpmLock.Lock()
	delete(garbagePathMap, path)
	gpmLock.Unlock()
}

// GC triggers garbage collection of namespace path right away
// and waits for it.
func GC() {
	gpmLock.Lock()
	if len(garbagePathMap) == 0 {
		// No need for GC if map is empty
		gpmLock.Unlock()
		return
	}
	gpmLock.Unlock()

	// if content exists in the garbage paths
	// we can trigger GC to run, providing a
	// channel to be notified on completion
	waitGC := make(chan struct{})
	gpmChan <- waitGC
	// wait for GC completion
	<-waitGC
}

// GenerateKey generates a sandbox key based on the passed
// container id.
func GenerateKey(containerID string) string {
	maxLen := 12
	if len(containerID) < maxLen {
		maxLen = len(containerID)
	}

	return prefix + "/" + containerID[:maxLen]
}

// NewSandbox provides a new sandbox instance created in an os specific way
// provided a key which uniquely identifies the sandbox
func NewSandbox(key string, osCreate bool) (Sandbox, error) {
	err := createNetworkNamespace(key, osCreate)
	if err != nil {
		return nil, err
	}

	return &networkNamespace{path: key}, nil
}

func (n *networkNamespace) InterfaceOptions() IfaceOptionSetter {
	return n
}

func (n *networkNamespace) NeighborOptions() NeighborOptionSetter {
	return n
}

func mountNetworkNamespace(basePath string, lnPath string) error {
	if err := syscall.Mount(basePath, lnPath, "bind", syscall.MS_BIND, ""); err != nil {
		return err
	}

	if err := loopbackUp(); err != nil {
		return err
	}
	return nil
}

// GetSandboxForExternalKey returns sandbox object for the supplied path
func GetSandboxForExternalKey(basePath string, key string) (Sandbox, error) {
	var err error
	if err = createNamespaceFile(key); err != nil {
		return nil, err
	}
	n := &networkNamespace{path: basePath}
	n.InvokeFunc(func() {
		err = mountNetworkNamespace(basePath, key)
	})
	if err != nil {
		return nil, err
	}
	return &networkNamespace{path: key}, nil
}

func reexecCreateNamespace() {
	if len(os.Args) < 2 {
		log.Fatal("no namespace path provided")
	}
	if err := mountNetworkNamespace("/proc/self/ns/net", os.Args[1]); err != nil {
		log.Fatal(err)
	}
}

func createNetworkNamespace(path string, osCreate bool) error {
	if err := createNamespaceFile(path); err != nil {
		return err
	}

	cmd := &exec.Cmd{
		Path:   reexec.Self(),
		Args:   append([]string{"netns-create"}, path),
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}
	if osCreate {
		cmd.SysProcAttr = &syscall.SysProcAttr{}
		cmd.SysProcAttr.Cloneflags = syscall.CLONE_NEWNET
	}
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("namespace creation reexec command failed: %v", err)
	}

	return nil
}

func unmountNamespaceFile(path string) {
	if _, err := os.Stat(path); err == nil {
		syscall.Unmount(path, syscall.MNT_DETACH)
	}
}

func createNamespaceFile(path string) (err error) {
	var f *os.File

	once.Do(createBasePath)
	// Remove it from garbage collection list if present
	removeFromGarbagePaths(path)

	// If the path is there unmount it first
	unmountNamespaceFile(path)

	// wait for garbage collection to complete if it is in progress
	// before trying to create the file.
	gpmWg.Wait()

	if f, err = os.Create(path); err == nil {
		f.Close()
	}

	return err
}

func loopbackUp() error {
	iface, err := netlink.LinkByName("lo")
	if err != nil {
		return err
	}
	return netlink.LinkSetUp(iface)
}

func (n *networkNamespace) InvokeFunc(f func()) error {
	return nsInvoke(n.nsPath(), func(nsFD int) error { return nil }, func(callerFD int) error {
		f()
		return nil
	})
}

// InitOSContext initializes OS context while configuring network resources
func InitOSContext() func() {
	runtime.LockOSThread()
	nsOnce.Do(ns.Init)
	if err := ns.SetNamespace(); err != nil {
		log.Error(err)
	}

	return runtime.UnlockOSThread
}

func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
	defer InitOSContext()()

	f, err := os.OpenFile(path, os.O_RDONLY, 0)
	if err != nil {
		return fmt.Errorf("failed get network namespace %q: %v", path, err)
	}
	defer f.Close()

	nsFD := f.Fd()

	// Invoked before the namespace switch happens but after the namespace file
	// handle is obtained.
	if err := prefunc(int(nsFD)); err != nil {
		return fmt.Errorf("failed in prefunc: %v", err)
	}

	if err = netns.Set(netns.NsHandle(nsFD)); err != nil {
		return err
	}
	defer ns.SetNamespace()

	// Invoked after the namespace switch.
	return postfunc(ns.ParseHandlerInt())
}

func (n *networkNamespace) nsPath() string {
	n.Lock()
	defer n.Unlock()

	return n.path
}

func (n *networkNamespace) Info() Info {
	return n
}

func (n *networkNamespace) Key() string {
	return n.path
}

func (n *networkNamespace) Destroy() error {
	// Assuming no running process is executing in this network namespace,
	// unmounting is sufficient to destroy it.
	if err := syscall.Unmount(n.path, syscall.MNT_DETACH); err != nil {
		return err
	}

	// Stash it into the garbage collection list
	addToGarbagePaths(n.path)
	return nil
}


text:
import IndexedArray from 'ui/indexed_array';
export default function CastMappingTypeFn() {

  castMappingType.types = new IndexedArray({
    index: ['name'],
    group: ['type'],
    immutable: true,
    initialSet: [
      { name: 'string',       type: 'string',     group: 'base'   },
      { name: 'text',         type: 'string',     group: 'base'   },
      { name: 'keyword',      type: 'string',     group: 'base'   },
      { name: 'date',         type: 'date',       group: 'base'   },
      { name: 'boolean',      type: 'boolean',    group: 'base'   },
      { name: 'float',        type: 'number',     group: 'number' },
      { name: 'half_float',   type: 'number',     group: 'number' },
      { name: 'scaled_float', type: 'number',     group: 'number' },
      { name: 'double',       type: 'number',     group: 'number' },
      { name: 'integer',      type: 'number',     group: 'number' },
      { name: 'long',         type: 'number',     group: 'number' },
      { name: 'short',        type: 'number',     group: 'number' },
      { name: 'byte',         type: 'number',     group: 'number' },
      { name: 'token_count',  type: 'number',     group: 'number' },
      { name: 'geo_point',    type: 'geo_point',  group: 'geo'    },
      { name: 'geo_shape',    type: 'geo_shape',  group: 'geo'    },
      { name: 'ip',           type: 'ip',         group: 'other'  },
      { name: 'attachment',   type: 'attachment', group: 'other'  },
      { name: 'murmur3',      type: 'murmur3',    group: 'hash'   }
    ]
  });

  /**
   * Accepts a mapping type, and converts it into it's js equivilent
   * @param  {String} type - the type from the mapping's 'type' field
   * @return {String} - the most specific type that we care for
   */
  function castMappingType(name) {
    if (!name) return 'unknown';

    const match = castMappingType.types.byName[name];
    return match ? match.type : 'string';
  }

  return castMappingType;
}


text:
const debug = require('debug')('App:Plugin');
const API = {};

API.Config = {};
API.provider = {};

API.Init = async (Config) => {
  API.Config = Config;
  API.UseSystem(Config.defaultSystem);

  debug('Loading Plugin : Payment');
};

API.UseSystem = (system) => {
  API.provider = require('./' + system);

  return API.provider.Init(API.Config.systems[system], API.Config.shared, API.Config.products);
};

/**
 * Do upfront payment using order info
 * TO DO LATER: Add tax, discount as items in the order
 *  */
API.QuickPay = async (packageName, email, currency, token, couponId = null) => {
  // Add package as sku
  var items = [{
    type: 'sku',
    parent: API.provider.productConfig[packageName]
  }];
  var orderBody = new API.Order(items, email, currency, couponId);
  console.log(orderBody, token);
  const order = await API.provider.QuickPay(orderBody, token);
  console.log(order);
  return API.provider.Charges.GetCharge(order.charge);
};

/**
 * Payment after delivery
 * Step 1: Creates an unpaid order
 * Step 2: Payment for the order using order ID
 *  */
API.CreateOrder = async (packageName, email, currency, customerId, couponId = null) => {
  const items = [{
    type: 'sku',
    parent: API.provider.productConfig[packageName]
  }];
  var order = new API.Order(items, email, currency, customerId, couponId);
  return API.provider.Orders.CreateOrder(order);
};

API.PayAfterDelivery = async (orderId, token) => {
  const order = await API.provider.Orders.GetOrder(orderId);
  console.log(order);
  const orderPaid = API.provider.Orders.PayOrder(order, token);
  return API.provider.Charges.GetCharge(orderPaid.charge);
};

// to be done later
API.RefundOrder = async () => {
  //
};
API.CouponValidation = async () => {
  //
};

// MODELS
API.Order = class {
  constructor (items, email, currency, couponId, customerId) {
    this.items = items || [];
    this.email = email || null;
    this.currency = currency || 'usd';
    // this.customer = customerId || null;
    // this.coupon = couponId || null;
  }
};

module.exports = API;


text:
require File.dirname(__FILE__) + '/codebreak/game.rb'

module Codebreak
  class Chatter
    def start_game
      Game.new($stdout).start
    end
  end
end