text:
'use strict';
var FIREBASE_URL = 'https://eamdb.firebaseio.com/';
var fb = new Firebase(FIREBASE_URL);
var initLoad = true;

$('.onLoggedIn form').submit(function () {
  var url = $('.onLoggedIn input[type="url"]').val();
  var uid = fb.getAuth().uid;
  console.log(uid);
  var token = fb.getAuth().token;
  var postUrl = FIREBASE_URL + '/users/' + uid + '/movies.json?auth=$token';
  $.post(postUrl, JSON.stringify(url), function (res) {
    console.log(url);
    console.log(token);
    console.log(postUrl);
    console.log(uid);
    addMoviesToDom({
      url: url
    });
    clearForms();
    // res = { name: '-Jk4dfDd123' }
  });
  event.preventDefault();
})

$('.onTempPassword form').submit(function () {
  var email = fb.getAuth().password.email;
  var oldPw = $('.onTempPassword input:nth-child(1)').val();
  var newPw = $('.onTempPassword input:nth-child(2)').val();
  fb.changePassword({
    email: email,
    oldPassword: oldPw,
    newPassword: newPw
  }, function (err) {
    if (err) {
      alert(err.toString());
    } else {
      fb.unauth();
    }
  });
  event.preventDefault();
})
$('.doResetPassword').click(function () {
  var email = $('.onLoggedOut input[type="email"]').val();
  fb.resetPassword({
    email: email
  }, function (err) {
    if (err) {
      alert(err.toString());
    } else {
      alert('Check your email!');
    }
  });
});
$('.doLogout').click(function () {
  fb.unauth(function () {
    window.location.reload();
  });
})
$(".goToMovies").click(function () {
  window.location = "movies.html";
});
$('.doRegister').click(function () {
  var email = $('.onLoggedOut input[type="email"]').val();
  var password = $('.onLoggedOut input[type="password"]').val();
  fb.createUser({
    email: email,
    password: password
  }, function (err, userData) {
    if (err) {
      alert(err.toString());
    } else {
      clearForms();
      doLogin(email, password, function () {
        window.location.reload();
      });
    }
  });
  event.preventDefault();
});
$('.onLoggedOut form').submit(function () {
  var email = $('.onLoggedOut input[type="email"]').val();
  var password = $('.onLoggedOut input[type="password"]').val();
  doLogin(email, password, function () {
    window.location.reload();
  });
  event.preventDefault();
});
function clearForms() {
  $('input[type="text"], input[type="email"], input[type="password"], input[type="url"]').val('');
}
function saveAuthData(authData) {
  $.ajax({
    method: 'PUT',
    url: `${FIREBASE_URL}users/${authData.uid}/profile.json?auth=${authData.token}`,
    data: JSON.stringify(authData)
  });
}
function doLogin(email, password, cb) {
  fb.authWithPassword({
    email: email,
    password: password
  }, function (err, authData) {
    if (err) {
      alert(err.toString());
    } else {
      saveAuthData(authData);
      typeof cb === 'function' && cb(authData);
    }
  });
}
function getUserData(cb) {
  var uid = fb.getAuth().uid;
  var token = fb.getAuth().token;
  var getUrl = `${FIREBASE_URL}/users/${uid}/movies.json?auth=${token}`;
  $.get(getUrl, cb);
}
function addMoviesToDom(movies) {
  if (movies) {
    Object.keys(movies).forEach(function (uuid) {
      $(`<img src="${movies[uuid]}" data-uid="${uuid}">`).appendTo($('.favMovies'));
    })
  }
}

/*
$('.onLoggedIn form').submit(function () {
  debugger;
  var url = $('.onLoggedIn input[type="url"]').val();
  var uid = fb.getAuth().uid;
  var token = fb.getAuth().token;
  //var postUrl = `${FIREBASE_URL}users/${uid}/movies.json?auth=${token}`;//doesn't like babel yet
    var postUrl = FIREBASE_URL + '/users/' + uid + '/movies.json?auth=$token';$.post(postUrl, JSON.stringify(url), function (res) {
    console.log(url);
    console.log(token);
    console.log(postUrl);
    console.log(uid);
    addMoviesToDom({
      url: url
    });
    clearForms();
*/

fb.onAuth(function (authData) {
  if (initLoad) {
    var onLoggedOut = $('.onLoggedOut');
    var onLoggedIn = $('.onLoggedIn');
    var onTempPassword = $('.onTempPassword');
    if (authData && authData.password.isTemporaryPassword) {
      // temporary log in
      onTempPassword.removeClass('hidden');
      onLoggedIn.addClass('hidden');
      onLoggedOut.addClass('hidden');
    } else if (authData) {
      // logged in
      onLoggedIn.removeClass('hidden');
      onLoggedOut.addClass('hidden');
      onTempPassword.addClass('hidden');
      $('.onLoggedIn h1').text(`Hello ${authData.password.email}`);
      //getUserData(function (urls) {
      //  addMoviesToDom(urls);

  var url = $('.onLoggedIn input[type="url"]').val();
  var uid = fb.getAuth().uid;
  var token = fb.getAuth().token;
  //var postUrl = `${FIREBASE_URL}users/${uid}/movies.json?auth=${token}`;//doesn't like babel yet
    var postUrl = FIREBASE_URL + 'users/' + uid + '/movies.json?auth=$token';$.post(postUrl, JSON.stringify(url), function (res) {
    console.log(url);
    console.log(token);
    console.log(postUrl);
    console.log(uid);
    });
    } else {
      // on logged out
      onLoggedOut.removeClass('hidden');
      onLoggedIn.addClass('hidden');
      onTempPassword.addClass('hidden');
    }
    clearForms();
  }
  initLoad = false;
});


text:
package com.dak.duty.model.enums;

public enum IntervalWeekly {

	MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

	public static boolean isEnumValue(final String input) {

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

		try {
			Enum.valueOf(IntervalWeekly.class, input);
			return true;
		} catch (final IllegalArgumentException iae) {
			return false;
		}

	}

}

redpajama_set_name: RedPajamaGithub


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Heiko Strathmann
 */
#include <gtest/gtest.h>
#include <shogun/labels/MulticlassLabels.h>
#include <shogun/features/DenseFeatures.h>
#include <shogun/features/DataGenerator.h>
#include <shogun/multiclass/MCLDA.h>

#define NUM  50
#define DIMS 2
#define CLASSES 2

using namespace shogun;

#ifdef HAVE_LAPACK
TEST(MCLDA, train_and_apply)
{
	SGVector< float64_t > lab(CLASSES*NUM);
	SGMatrix< float64_t > feat(DIMS, CLASSES*NUM);

	feat = CDataGenerator::generate_gaussians(NUM,CLASSES,DIMS);
	for( int i = 0 ; i < CLASSES ; ++i )
		for( int j = 0 ; j < NUM ; ++j )
			lab[i*NUM+j] = double(i);

	CMulticlassLabels* labels = new CMulticlassLabels(lab);
	CDenseFeatures< float64_t >* features = new CDenseFeatures< float64_t >(feat);

	CMCLDA* lda = new CMCLDA(features, labels);
	SG_REF(lda);
	lda->train();

	CMulticlassLabels* output = lda->apply()->as<CMulticlassLabels>();
	SG_REF(output);

	// Test
	for ( index_t i = 0; i < CLASSES*NUM; ++i )
		EXPECT_EQ(output->get_label(i), labels->get_label(i));

	SG_UNREF(output);
	SG_UNREF(lda);
}
#endif // HAVE_LAPACK


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ClipParameter</title>
<meta name="date" content="2015-01-13" />
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style" />

 <meta name="generator" content="Adobe RoboHelp 10" />

概述
软件包
 类
树
已过时
索引
帮助

 上一个类   下一个类
    无框架     所有类

摘要: 嵌套 | 字段 | 构造方法 | 方法
详细信息: 字段 | 构造方法 | 方法

com.supermap.android.spatialAnalyst

类 ClipParameter

java.lang.Object
  com.supermap.android.spatialAnalyst.ClipParameter

所有已实现的接口:

java.io.Serializable

public class ClipParameter

extends java.lang.Object

implements java.io.Serializable

用于裁剪的参数。优先使用用户指定的裁剪区域多边形进行裁剪,也可以通过指定数据源和数据集名,从而使用指定数据集的边界多边形进行裁剪。

另请参见:

序列化表格

字段摘要

 java.lang.String
clipDatasetName

           用于裁剪的数据集名,当clipRegion不设置时起作用。

 java.lang.String
clipDatasourceName

           用于裁剪的数据集所在数据源的名字。

 Geometry
clipRegion

           用户指定的裁剪区域,优先使用。

 boolean
isClipInRegion

           是否对裁剪区内的数据集进行裁剪。

 boolean
isExactClip

           是否使用精确裁剪。

构造方法摘要

ClipParameter()

           构造函数。

方法摘要

从类 java.lang.Object 继承的方法

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

字段详细信息

clipDatasetName

public java.lang.String clipDatasetName

用于裁剪的数据集名,当clipRegion不设置时起作用。

clipDatasourceName

public java.lang.String clipDatasourceName

用于裁剪的数据集所在数据源的名字。

clipRegion

public Geometry clipRegion

用户指定的裁剪区域,优先使用。

isClipInRegion

public boolean isClipInRegion

是否对裁剪区内的数据集进行裁剪。

isExactClip

public boolean isExactClip

是否使用精确裁剪。

构造方法详细信息

ClipParameter

public ClipParameter()

构造函数。

概述
软件包
 类
树
已过时
索引
帮助

 上一个类   下一个类
    无框架     所有类

摘要: 嵌套 | 字段 | 构造方法 | 方法
详细信息: 字段 | 构造方法 | 方法


text:
<!DOCTYPE html>

	<title></title>

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">

    Email
    <input type="email" class="form-control" id="email-nuevo" placeholder="Ingresa un email...">
    <button id="btn-agregar" type="submit" class="btn btn-default">Enviar</button>

Listado de miembros

			Nombre
			Apellido
			Email
			Eliminar

	<?php
	//var_dump($members);die;
		foreach ($members as $m)
		{
	?>

				<?php echo $m['merges']['FNAME']; ?>
				<?php echo $m['merges']['LNAME']; ?>
				<?php echo $m['merges']['EMAIL']; ?>
				<a href="javascript: eliminar('<?php echo $m['euid']; ?>')">

	<?php
		}
	?>


text:
<?php

namespace AuthBucket\OAuth2\ResponseType;

/**
 * OAuth2 response type handler factory interface.
 *
 * @author Wong Hoi Sing Edison <hswong3i@pantarei-design.com>
 */
interface ResponseTypeHandlerFactoryInterface
{
    /**
     * Gets a stored response type handler.
     *
     * @param string $type Type of response type handler, as refer to RFC6749
     *
     * @return ResponseTypeHandlerInterface The stored response type handler
     *
     * @throw UnsupportedResponseTypeException If supplied response type not found.
     */
    public function getResponseTypeHandler($type = null);

    /**
     * Get a list of all supported handler.
     *
     * @return array Supported handler in key-value pair
     */
    public function getResponseTypeHandlers();
}


text:
using Jal.Router.Interface;
using Jal.Router.Model;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Jal.Router.Impl
{
    public class FileSystemSubscriptionToPublishSubscribeChannel : AbstractChannel, ISubscriptionToPublishSubscribeChannel
    {
        private readonly FileSystemParameter _parameter;

        private readonly IFileSystemTransport _transport;

        private FileSystemWatcher _watcher;

        public FileSystemSubscriptionToPublishSubscribeChannel(IComponentFactoryFacade factory, ILogger logger, IParameterProvider provider, IFileSystemTransport transport)
        : base(factory, logger)
        {
            _parameter = provider.Get<FileSystemParameter>();

            _transport = transport;
        }

        public Task<Statistic> GetStatistic(Channel channel)
        {
            return Task.FromResult(default(Statistic));
        }

        public Task<bool> DeleteIfExist(Channel channel)
        {
            var path = string.Empty;

            path = _transport.CreateSubscriptionToPublishSubscribeChannelPath(_parameter, channel.ConnectionString, channel.Path, channel.Subscription);

            return Task.FromResult(_transport.DeleteDirectory(path));
        }

        public Task Close(ListenerContext listenercontext)
        {
            _watcher.Dispose();

            return Task.CompletedTask;
        }

        public Task<bool> CreateIfNotExist(Channel channel)
        {
            var path = string.Empty;

            path = _transport.CreateSubscriptionToPublishSubscribeChannelPath(_parameter, channel.ConnectionString, channel.Path, channel.Subscription);

            return Task.FromResult(_transport.CreateDirectory(path));
        }

        public bool IsActive(ListenerContext listenercontext)
        {
            return _watcher.EnableRaisingEvents;
        }

        public void Listen(ListenerContext listenercontext)
        {
            _watcher.Created += async (object sender, FileSystemEventArgs e) =>
            {
                if (e.FullPath.Contains(".jal"))
                {
                    Thread.Sleep(500);

                    var message = _transport.ReadFile(e.FullPath, listenercontext.MessageSerializer);

                    var context = await listenercontext.Read(message).ConfigureAwait(false);

                    Logger.Log($"Message {context.Id} arrived to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath}");

                    try
                    {
                        await listenercontext.Dispatch(context).ConfigureAwait(false);

                        _transport.DeleteFile(e.FullPath);
                    }
                    catch (Exception ex)
                    {
                        Logger.Log($"Message {context.Id} failed to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath} {ex}");
                    }
                    finally
                    {
                        Logger.Log($"Message {context.Id} completed to {listenercontext.Channel.ToString()} channel {listenercontext.Channel.FullPath}");
                    }
                }
            };

            _watcher.EnableRaisingEvents = true;
        }

        public void Open(ListenerContext listenercontext)
        {
            var path = _transport.CreateSubscriptionToPublishSubscribeChannelPath(_parameter, listenercontext.Channel.ConnectionString, listenercontext.Channel.Path, listenercontext.Channel.Subscription);

            _watcher = new FileSystemWatcher(path);
        }
    }
}


text:
#region License

#endregion
using System;
using System.Runtime.InteropServices;
namespace Contoso.Hosting
{
    internal sealed class ProcessImpersonationContext : ImpersonationContext
    {
        internal ProcessImpersonationContext()
        {
            ImpersonateToken(new HandleRef(this, IntPtr.Zero));
        }
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lactarius beardslei Burl.

### Remarks
null


text:
					 Six Manantiales - Mobile Promos

 Agregar Nuevo Promo

 Notificaciones

                        Más

Pushwoosh (Notificaciones)

Cloudinary (Administrar Imagenes)

Acerca

Cerrar Sesión


text:
package edu.mit.streamjit.util.bytecode.insts;

import com.google.common.base.Function;
import static com.google.common.base.Preconditions.*;
import edu.mit.streamjit.util.bytecode.Field;
import edu.mit.streamjit.util.bytecode.LocalVariable;
import edu.mit.streamjit.util.bytecode.Value;
import edu.mit.streamjit.util.bytecode.types.FieldType;
import edu.mit.streamjit.util.bytecode.types.InstanceFieldType;

/**
 * Loads a static or instance field.  (Does not load array elements.)
 * @author Jeffrey Bosboom <jbosboom@csail.mit.edu>
 * @since 4/14/2013
 */
public final class LoadInst extends Instruction {
	public LoadInst(Field f) {
		super(checkNotNull(f).getType().getFieldType(), f.isStatic() ? 1 : 2);
		setOperand(0, f);
	}
	public LoadInst(Field f, Value v) {
		this(f);
		checkArgument(!f.isStatic(), "loading from static field %s with instance %s", f, v);
		setOperand(1, v);
	}
	public LoadInst(LocalVariable v) {
		super(checkNotNull(v).getType().getFieldType(), 1);
		setOperand(0, v);
	}

	public Value getLocation() {
		return getOperand(0);
	}
	public void setLocation(Value f) {
		setOperand(0, f);
	}
	public Value getInstance() {
		return getOperand(1);
	}
	public void setInstance(Value v) {
		setOperand(1, v);
	}

	@Override
	public Instruction clone(Function<Value, Value> operandMap) {
		Value newLocation = operandMap.apply(getLocation());
		if (getNumOperands() == 1)
			if (newLocation instanceof Field)
				return new LoadInst((Field)newLocation);
			else
				return new LoadInst((LocalVariable)newLocation);
		else
			return new LoadInst((Field)newLocation, operandMap.apply(getInstance()));
	}

	@Override
	protected void checkOperand(int i, Value v) {
		checkElementIndex(i, 2);
		if (i == 0) {
			checkArgument(v.getType() instanceof FieldType);
			FieldType ft = (FieldType)v.getType();
			checkArgument(ft.getFieldType().isSubtypeOf(getType()));
		} else if (i == 1) {
			Field f = (Field)getLocation();
			if (f != null) {
				checkState(f.getType() instanceof InstanceFieldType);
				checkArgument(v.getType().isSubtypeOf(((InstanceFieldType)f.getType()).getInstanceType()));
			}
		}
		super.checkOperand(i, v);
	}

	@Override
	public String toString() {
		if (getLocation() instanceof LocalVariable) {
			return String.format("%s (%s) = load %s",
						getName(), getType(),
						getLocation().getName());
		} else {
			Field f = (Field)getLocation();
			if (f.isStatic())
				return String.format("%s (%s) = getstatic %s#%s",
						getName(), getType(),
						f.getParent().getName(), f.getName());
			else
				return String.format("%s (%s) = getfield %s#%s from %s",
						getName(), getType(),
						f.getParent().getName(), f.getName(),
						getOperand(1).getName());
		}
	}
}


text:
'''
    salt.utils.gzip
    ~~~~~~~~~~~~~~~
    Helper module for handling gzip consistently between 2.7+ and 2.6-
'''

from __future__ import absolute_import

# Import python libs
import gzip

# Import 3rd-party libs
from salt.ext.six.moves import StringIO  # pylint: disable=import-error

class GzipFile(gzip.GzipFile):
    def __init__(self, filename=None, mode=None,
                 compresslevel=9, fileobj=None):
        gzip.GzipFile.__init__(self, filename, mode, compresslevel, fileobj)

    ### Context manager (stolen from Python 2.7)###
    def __enter__(self):
        """Context management protocol.  Returns self."""
        return self

    def __exit__(self, *args):
        """Context management protocol.  Calls close()"""
        self.close()

def open(filename, mode="rb", compresslevel=9):
    if hasattr(gzip.GzipFile, '__enter__'):
        return gzip.open(filename, mode, compresslevel)
    else:
        return GzipFile(filename, mode, compresslevel)

def open_fileobj(fileobj, mode='rb', compresslevel=9):
    if hasattr(gzip.GzipFile, '__enter__'):
        return gzip.GzipFile(
            filename='', mode=mode, fileobj=fileobj,
            compresslevel=compresslevel
        )
    return GzipFile(
        filename='', mode=mode, fileobj=fileobj, compresslevel=compresslevel
    )

def compress(data, compresslevel=9):
    '''
    Returns the data compressed at gzip level compression.
    '''
    buf = StringIO()
    with open_fileobj(buf, 'wb', compresslevel) as ogz:
        ogz.write(data)
    compressed = buf.getvalue()
    return compressed

def uncompress(data):
    buf = StringIO(data)
    with open_fileobj(buf, 'rb') as igz:
        unc = igz.read()
        return unc


text:
package com.haxademic.core.data.store;

import processing.core.PGraphics;
import processing.core.PImage;

public interface IAppStoreListener {
	public void updatedNumber(String key, Number val);
	public void updatedString(String key, String val);
	public void updatedBoolean(String key, Boolean val);
	public void updatedImage(String key, PImage val);
	public void updatedBuffer(String key, PGraphics val);
}


text:
package com.profitbricks.sdk;

import com.profitbricks.rest.client.RestClientException;
import com.profitbricks.rest.domain.LoadBalancer;
import com.profitbricks.rest.domain.LoadBalancers;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

/**
 *
 * @author jasmin@stackpointcloud.com
 */
public class Loadbalancer extends ProfitbricksAPIBase {

    public Loadbalancer() throws Exception {
        super("loadbalancers", "datacenters");
    }

    /**
     * Retrieve a list of load balancers within the data center.
     *
     * @param dataCenterId The unique ID of the data center
     * @return LoadBalancers object with a list of LoadBalancer in datacenter.
     */
    public LoadBalancers getAllLoadBalancers(String dataCenterId) throws RestClientException, IOException {
        return client.get(getUrlBase().concat(parentResource).concat("/").concat(dataCenterId)
                .concat("/").concat(resource)
                .concat(depth), null, LoadBalancers.class);
    }

    /**
     * Retrieves the attributes of a given load balancer.
     *
     * @param dataCenterId The unique ID of the data center
     * @param loadBalancerId The unique ID of the nic
     * @return LoadBalancer object with properties and metadata
     */
    public LoadBalancer getLoadBalancer(String dataCenterId, String loadBalancerId) throws RestClientException, IOException {
        return client.get(getUrlBase().concat(parentResource).concat("/").concat(dataCenterId)
                .concat("/").concat(resource).concat("/").concat(loadBalancerId)
                .concat(depth), null, LoadBalancer.class);
    }

    /**
     * Creates a load balancer within the data center. Load balancers can be
     * used for public or private IP traffic.
     *
     * @param dataCenterId The unique ID of the data center
     * @param loadBalancer object has the following properties:
     *

     *

     * name = The name of your loadBalancer.
     *

     *

     * ip = IPv4 address of the load balancer. All attached NICs will inherit
     * this IP.
     *

     *

     * dhcp = Indicates if the load balancer will reserve an IP using DHCP.
     *

     *

     * balancednics = List of NICs taking part in load-balancing. All balanced
     * nics inherit the IP of the load balancer.
     *

     *

     * @return LoadBalancer object with properties and metadata.
     */
    public LoadBalancer createLoadBalancer(String dataCenterId, LoadBalancer loadBalancer) throws RestClientException, IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        return client.create(getUrlBase().concat(parentResource).concat("/").concat(dataCenterId)
                .concat("/").concat(resource), loadBalancer, LoadBalancer.class, 202);
    }

    /**
     * Perform updates to attributes of a load balancer.
     *
     * @param dataCenterId The unique ID of the data center
     * @param loadBalancerId The unique ID of the LoadBalancer
     * @param loadBalancer
     *

     *

     * name = The name of the load balancer.
     *

     *

     * ip = The IP of the load balancer.
     *

     *

     * dhcp = Indicates if the load balancer will reserve an IP using DHCP.
     *

     *

     * @return LoadBalancer object with properties and metadata.
     */
    public LoadBalancer updateLoadBalancer(String dataCenterId, String loadBalancerId, LoadBalancer.Properties loadBalancer) throws RestClientException, IOException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        return client.update(getUrlBase().concat(parentResource).concat("/").concat(dataCenterId)
                .concat("/").concat(resource).concat("/").concat(loadBalancerId), loadBalancer, LoadBalancer.class, 202);
    }

    /**
     * Deletes the specified load balancer.
     *
     * @param dataCenterId The unique ID of the data center
     * @param loadBalancerId The unique ID of the LoadBalancer
     */
    public void deleteLoadBalaner(String dataCenterId, String loadBalancerId) throws RestClientException, IOException {
        client.delete(getUrlBase().concat(parentResource).concat("/").concat(dataCenterId)
                .concat("/").concat(resource).concat("/").concat(loadBalancerId), 202);
    }
}


text:
import sys
import ssl
from os.path import abspath, dirname

basepath = abspath(dirname(abspath(__file__)) + '/..')
sys.path.insert(0, basepath)

from websocket import websocket
from connection import Connection
from message import TextMessage

ADDR = ('localhost', 8000)

class EchoClient(Connection):
    def onopen(self):
        print 'Connection established, sending "foo"'
        self.send(TextMessage('foo'))

    def onmessage(self, msg):
        print 'Received', msg
        self.close(None, 'response received')

    def onerror(self, e):
        print 'Error:', e

    def onclose(self, code, reason):
        print 'Connection closed'

if __name__ == '__main__':
    secure = '-s' in sys.argv[1:]
    scheme = 'wss' if secure else 'ws'
    print 'Connecting to %s://%s' % (scheme, '%s:%d' % ADDR)
    sock = websocket()

    if secure:
        sock.enable_ssl(ca_certs='cert.pem', cert_reqs=ssl.CERT_REQUIRED)

    sock.connect(ADDR)
    EchoClient(sock).receive_forever()


text:
class AddStoreColumnToUploads < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  def change
    add_column(:uploads, :store, :integer)
  end
end


text:
chef_gem('chef-sugar') do
  version '2.3.0'
  action  :nothing
end.run_action(:install)

require 'chef/sugar'


text:
package com.gemstone.gemfire.security;

import com.gemstone.gemfire.GemFireException;

/**
 * The base class for all {@link com.gemstone.gemfire.security} related
 * exceptions.
 *
 * @author Sumedh Wale
 * @since 5.5
 */
public class GemFireSecurityException extends GemFireException {
private static final long serialVersionUID = 3814254578203076926L;

  /**
   * Constructs instance of SecurityException with error message.
   *
   * @param message
   *                the error message
   */
  public GemFireSecurityException(String message) {
    super(message);
  }

  /**
   * Constructs instance of SecurityException with error message
   * and cause.
   *
   * @param message
   *                the error message
   * @param cause
   *                a Throwable that is a cause of this exception
   */
  public GemFireSecurityException(String message, Throwable cause) {
    super(message, cause);
  }

}


text:
package self.philbrown.AbLE.annotations;

import self.philbrown.AbLE.AbLEActivity;
import self.philbrown.AbLE.AbLEUtil;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.view.View;
import android.view.ViewGroup;

/**
 * Creates a View from an Android Layout XML file.
 * @author Phil Brown
 *
 */
public class XMLLayoutInflater extends ClassAnnotationInflater {

	/**
	 * Constructor
	 * @param context used to create views and access resources. This is automatically saved
	 * to the {@link ClassAnnotationInflater#context context} variable in the super class.
	 * @param parent the parent {@code ClassAnnotationInflater} in this view hierarchy
	 */
	public XMLLayoutInflater(AbLEActivity context, ClassAnnotationInflater parent) {
		super(context, parent);
	}

	/**
	 * Creates the view from XML, then handles any fields or child views.
	 */
	@Override
	public View inflate(Class<?> layout) {
		XMLLayout xml = layout.getAnnotation(XMLLayout.class);
		String file = xml.resourceID();
		if (file.contains("R.layout"))
		{
			String[] array = file.split(".");
			file = array[array.length-1];
		}
		android.view.LayoutInflater inflater = (android.view.LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		view = inflater.inflate(context.getResources().getIdentifier(file, "layout", context.getPackageName()), null);

		createView(xml);
		if (view == null)
		{
			AbLEUtil.err("Could not create layout for resource R.layout.%s", file);
			return null;
		}

		handleFields(layout);
		handleGetters(view);
		handleBindings();
		performSetters(view);
		handleChildViews(layout);
		onLayoutComplete(layout, view);

		return view;
	}

	/**
	 * Creates the view based on the attributes in the given annotation
	 * @param xml an {@link XMLLayout} annotation
	 */
	private void createView(XMLLayout xml)
	{

		if (parent == null)
		{
			//if this is the top-level layout, then force the layout orientation
			ORIENTATION[] allowedOrientations = xml.orientation();
			boolean portrait = false,
					portraitUpsideDown = false,
					landscapeRight = false,
					landscapeLeft = false;
			for (ORIENTATION o : allowedOrientations)
			{
				if (o == ORIENTATION.portrait)
					portrait = true;
				else if (o == ORIENTATION.portraitUpsideDown)
					portraitUpsideDown = true;
				else if (o == ORIENTATION.landscapeRight)
					landscapeRight = true;
				else if (o == ORIENTATION.landscapeLeft)
					landscapeLeft = true;
			}
			if(portrait && portraitUpsideDown && landscapeRight && landscapeLeft)
				context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
			else if(landscapeRight && landscapeLeft)
				context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
			else if(portrait && portraitUpsideDown)
				context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
			else if(portrait)
				context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			else if(portraitUpsideDown)
				context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
			else if(landscapeRight)
				context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			else if(landscapeLeft)
				context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
			else
			{
				throw new UnsupportedOperationException("Invalid Layout Orientation parameters!");
			}
		}

		float[] origin = xml.origin();
		view.setX(origin[0]);
		view.setY(origin[1]);

		//Layout Params
		String[] params = xml.params();
		int width, height;
		if (params[0].equals("match_parent"))
		{
			width = ViewGroup.LayoutParams.MATCH_PARENT;
		}
		else if (params[0].equals("fill_parent"))
		{
			width = ViewGroup.LayoutParams.FILL_PARENT;
		}
		else if (params[0].equals("wrap_content"))
		{
			width = ViewGroup.LayoutParams.WRAP_CONTENT;
		}
		else
		{
			width = (int) Float.parseFloat(params[0]);
		}

		if (params[1].equals("match_parent"))
		{
			height = ViewGroup.LayoutParams.MATCH_PARENT;
		}
		else if (params[1].equals("fill_parent"))
		{
			height = ViewGroup.LayoutParams.FILL_PARENT;
		}
		else if (params[1].equals("wrap_content"))
		{
			height = ViewGroup.LayoutParams.WRAP_CONTENT;
		}
		else
		{
			height = (int) Float.parseFloat(params[1]);
		}

		view.setLayoutParams(new ViewGroup.LayoutParams(width, height));

	}

}


text:
using System;
using Marten.Schema.Testing.Documents;
using Marten.Testing.Harness;
using Shouldly;
using Xunit;

namespace Marten.Schema.Testing
{
    public class DocumentMapping_schema_patch_writing: IntegrationContext
    {
        [Fact]
        public void creates_the_table_in_update_ddl_if_all_new()
        {
            StoreOptions(_ =>
            {
                _.Schema.For<User>();
            });

            var patch = theStore.Schema.ToPatch();

            patch.UpdateDDL.ShouldContain($"CREATE TABLE public.mt_doc_user");
            patch.UpdateDDL.ShouldContain($"CREATE OR REPLACE FUNCTION public.mt_upsert_user(doc JSONB, docDotNetType varchar, docId uuid, docVersion uuid) RETURNS UUID LANGUAGE plpgsql SECURITY INVOKER AS $function$");
        }

        [Fact]
        public void drops_the_table_in_rollback_if_all_new()
        {
            var schemaName = StoreOptions(_ =>
            {
                _.Schema.For<User>();
            });

            var patch = theStore.Schema.ToPatch();

            patch.RollbackDDL.ShouldContain($"drop table if exists public.mt_doc_user cascade;");
        }

        [Fact]
        public void drops_the_table_in_rollback_if_all_new_different_schema()
        {
            StoreOptions(_ =>
            {
                _.Schema.For<User>();
                _.DatabaseSchemaName = "other";
            });

            var patch = theStore.Schema.ToPatch();

            patch.RollbackDDL.ShouldContain("drop table if exists other.mt_doc_user cascade;");
        }

        [Fact]
        public void does_not_drop_the_table_if_it_all_exists()
        {
            theStore.Tenancy.Default.EnsureStorageExists(typeof(User));

            var patch = theStore.Schema.ToPatch();

            patch.RollbackDDL.ShouldNotContain("drop table if exists public.mt_doc_user cascade;");
        }

        [Fact]
        public void can_drop_added_columns_in_document_storage()
        {
            theStore.Tenancy.Default.EnsureStorageExists(typeof(User));

            using (var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<User>().Duplicate(x => x.UserName);
            }))
            {
                var patch = store.Schema.ToPatch();

                patch.RollbackDDL.ShouldContain("alter table if exists public.mt_doc_user drop column if exists user_name;");
            }
        }

        [Fact]
        public void can_drop_indexes_that_were_added()
        {
            theStore.Tenancy.Default.EnsureStorageExists(typeof(User));

            using (var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<User>().Index(x => x.UserName);
            }))
            {
                var patch = store.Schema.ToPatch();

                patch.RollbackDDL.ShouldContain("drop index concurrently if exists public.mt_doc_user_idx_user_name;");
            }
        }

        [Fact]
        public void can_revert_indexes_that_changed()
        {
            StoreOptions(_ =>
            {
                _.Schema.For<User>()
                    .Duplicate(x => x.UserName, configure: i => i.Method = IndexMethod.btree);
            });
            theStore.Tenancy.Default.EnsureStorageExists(typeof(User));

            using (var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<User>()
                    .Duplicate(x => x.UserName, configure: i => i.Method = IndexMethod.hash);
            }))
            {
                var patch = store.Schema.ToPatch();

                patch.RollbackDDL.ShouldContain("drop index");

                patch.RollbackDDL.ShouldContain("CREATE INDEX mt_doc_user_idx_user_name");
            }
        }

        [Fact]
        public void can_revert_indexes_that_changed_in_non_public_schema()
        {
            StoreOptions(_ =>
            {
                _.DatabaseSchemaName = "other";
                _.Schema.For<User>()
                    .Duplicate(x => x.UserName, configure: i => i.Method = IndexMethod.btree);
            });
            theStore.Tenancy.Default.EnsureStorageExists(typeof(User));

            using (var store = DocumentStore.For(_ =>
            {
                _.DatabaseSchemaName = "other";
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<User>()
                    .Duplicate(x => x.UserName, configure: i => i.Method = IndexMethod.hash);
            }))
            {
                var patch = store.Schema.ToPatch();

                patch.RollbackDDL.ShouldContain("drop index other.mt_doc_user_idx_user_name;");

                patch.RollbackDDL.ShouldContain("CREATE INDEX mt_doc_user_idx_user_name ON other.mt_doc_user USING btree (user_name);");
            }
        }

        [Fact]
        public void can_create_and_drop_foreignkeys_todocuments_that_were_added()
        {
            theStore.Tenancy.Default.EnsureStorageExists(typeof(User));

            using (var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<Issue>().ForeignKey<User>(x => x.AssigneeId, fkd => fkd.CascadeDeletes = true);
            }))
            {
                var patch = store.Schema.ToPatch();

                patch.UpdateDDL.ShouldContain(@"ADD CONSTRAINT mt_doc_issue_assignee_id_fkey FOREIGN KEY (assignee_id)
                    REFERENCES public.mt_doc_user (id)
                    ON DELETE CASCADE;", StringComparisonOption.NormalizeWhitespaces);

                store.Schema.ApplyAllConfiguredChangesToDatabase();
            }
        }

        [Fact]
        public void for_document_with_int_id_when_schema_patch_applied_then_does_not_show_more_changes()
        {
            theStore.Tenancy.Default.EnsureStorageExists(typeof(IntDoc));

            using (var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<IntDoc>();
            }))
            {
                Should.NotThrow(() =>
                {
                    store.Schema.ApplyAllConfiguredChangesToDatabase();

                    store.Schema.AssertDatabaseMatchesConfiguration();
                });
            }
        }

        [Fact]
        public void can_create_duplicate_field_with_null_constraint()
        {
            theStore.Tenancy.Default.EnsureStorageExists(typeof(Target));
            using (var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<Target>().Duplicate(x => x.NullableDateTime);
            }))
            {
                var patch = store.Schema.ToPatch();
                SpecificationExtensions.ShouldContain(patch.UpdateDDL, "alter table public.mt_doc_target add column nullable_date_time timestamp without time zone NULL");
            }
        }

        [Fact]
        public void can_create_duplicate_field_with_not_null_constraint()
        {
            theStore.Tenancy.Default.EnsureStorageExists(typeof(Target));

            using (var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<Target>().Duplicate(x => x.Date, notNull: true);
            }))
            {
                var patch = store.Schema.ToPatch();
                SpecificationExtensions.ShouldContain(patch.UpdateDDL, "alter table public.mt_doc_target add column date timestamp without time zone NOT NULL");
            }
        }

        [Fact]
        public void can_create_duplicate_field_with_not_null_constraint_using_duplicate_field_attribute()
        {
            using (var store = DocumentStore.For(_ =>
            {
                _.Connection(ConnectionSource.ConnectionString);
                _.Schema.For<NonNullableDuplicateFieldTest>();
            }))
            {
                var patch = store.Schema.ToPatch();
                SpecificationExtensions.ShouldContain(patch.UpdateDDL, "non_nullable_duplicate_field    timestamp without time zone NOT NULL");
            }
        }

    }

    public class NonNullableDuplicateFieldTest
    {
        public Guid Id { get; set; }
        [DuplicateField(NotNull = true)]
        public DateTime NonNullableDuplicateField { get; set; }
    }
}


text:
cask "switchhosts" do
  version "4.0.2.6057"

  if Hardware::CPU.intel?
    sha256 "c522611862ef91a1cf204c39b385ac44397cfae84e05aa4ea12d21db25badb02"
    url "https://github.com/oldj/SwitchHosts/releases/download/v#{version.major_minor_patch}/SwitchHosts_#{version}.dmg",
        verified: "github.com/oldj/SwitchHosts/"
  else
    sha256 "445b3986eb270443eb74e34dd96359de56bedbfc03690c0905aec1f1dbe2447a"
    url "https://github.com/oldj/SwitchHosts/releases/download/v#{version.major_minor_patch}/SwitchHosts_arm64_#{version}.dmg",
        verified: "github.com/oldj/SwitchHosts/"
  end

  name "SwitchHosts"
  desc "App to switch hosts"
  homepage "https://oldj.github.io/SwitchHosts/"

  livecheck do
    url :url
    strategy :github_latest
    regex(%r{/SwitchHosts_(\d+(?:\.\d+)*)\.dmg}i)
  end

  app "SwitchHosts.app"
end


text:
from rest_framework import serializers

from junction.proposals.serializers import ProposalSerializer

from .models import ScheduleItem

class ScheduleSerializer(serializers.HyperlinkedModelSerializer):
    session = ProposalSerializer()

    class Meta:
        model = ScheduleItem
        fields = ('room', 'event_date', 'start_time', 'end_time',
                  'name', 'session', 'type', 'conference')


text:
import java.util.stream.Stream;

public class AccessToPrivateMethodsInStaticContext {
  public static void main(String[] args) {
    // Breakpoint!
    Stream.generate(() -> 1).limit(10).peek(x -> method(x)).filter(x -> x % 2 == 0).count();
  }

  private static boolean method(int x) {
    return true;
  }
}


text:
namespace il2cpp
{
namespace os
{
    class ThreadLocalValueImpl : public il2cpp::utils::NonCopyable
    {
    public:
        ThreadLocalValueImpl();
        ~ThreadLocalValueImpl();
        ErrorCode SetValue(void* value);
        ErrorCode GetValue(void** value);
    private:
        pthread_key_t m_Key;
    };
}
}

#endif


text:
using System.Diagnostics.CodeAnalysis;
using NUnit.Framework;

// ReSharper disable CheckNamespace
namespace HotPlate.Core.Tests
{
    [TestFixture]
    [SuppressMessage("ReSharper", "InconsistentNaming")]
    class Cells_in_a_hot_plate_that_are_neither_hot_nor_cold_should_be_50_degrees
    {
        private HotPlate hotPlate;
        private readonly int size = 3;
        private readonly int expected = 50;

        [SetUp]
        public void Setup()
        {
            hotPlate = new HotPlate(size);
        }

        [Test]
        public void Verify_top()
        {
            Assert.AreEqual(expected, hotPlate[0, 1]);
        }

        [Test]
        public void Verify_left()
        {
            Assert.AreEqual(expected, hotPlate[1, 0]);
        }

        [Test]
        public void Verify_right()
        {
            Assert.AreEqual(expected, hotPlate[1, 2]);
        }

        [Test]
        public void Verify_bottom()
        {
            Assert.AreEqual(expected, hotPlate[2, 1]);
        }
    }
}


text:
package org.ehcache.impl.internal.store.heap;

import org.ehcache.Cache;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.core.spi.store.StoreAccessException;
import org.ehcache.expiry.Expirations;
import org.ehcache.core.spi.function.BiFunction;
import org.ehcache.core.spi.function.Function;
import org.ehcache.core.spi.function.NullaryFunction;
import org.ehcache.impl.copy.IdentityCopier;
import org.ehcache.impl.internal.events.NullStoreEventDispatcher;
import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine;
import org.ehcache.core.spi.time.SystemTimeSource;
import org.ehcache.core.spi.store.Store;
import org.ehcache.spi.copy.Copier;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import static java.util.Collections.singleton;
import static java.util.Collections.singletonMap;
import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * OnHeapStoreKeyCopierTest
 */
@RunWith(Parameterized.class)
public class OnHeapStoreKeyCopierTest {

  private static final Key KEY = new Key("WHat?");
  public static final String VALUE = "TheAnswer";
  public static final NullaryFunction<Boolean> NOT_REPLACE_EQUAL = new NullaryFunction<Boolean>() {
    @Override
    public Boolean apply() {
      return false;
    }
  };
  public static final NullaryFunction<Boolean> REPLACE_EQUAL = new NullaryFunction<Boolean>() {
    @Override
    public Boolean apply() {
      return true;
    }
  };

  @Parameterized.Parameters(name = "copyForRead: {0} - copyForWrite: {1}")
  public static Collection<Object[]> config() {
    return Arrays.asList(new Object[][] {
        {false, false}, {false, true}, {true, false}, {true, true}
    });
  }

  @Parameterized.Parameter(value = 0)
  public boolean copyForRead;

  @Parameterized.Parameter(value = 1)
  public boolean copyForWrite;

  private OnHeapStore<Key, String> store;

  @Before
  public void setUp() {
    Store.Configuration configuration = mock(Store.Configuration.class);
    when(configuration.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build());
    when(configuration.getKeyType()).thenReturn(Key.class);
    when(configuration.getValueType()).thenReturn(String.class);
    when(configuration.getExpiry()).thenReturn(Expirations.noExpiration());
    @SuppressWarnings("unchecked")
    Store.Configuration<Key, String> config = configuration;

    Copier<Key> keyCopier = new Copier<Key>() {
      @Override
      public Key copyForRead(Key obj) {
        if (copyForRead) {
          return new Key(obj);
        }
        return obj;
      }

      @Override
      public Key copyForWrite(Key obj) {
        if (copyForWrite) {
          return new Key(obj);
        }
        return obj;
      }
    };

    store = new OnHeapStore<Key, String>(config, SystemTimeSource.INSTANCE, keyCopier, new IdentityCopier<String>(), new NoopSizeOfEngine(), NullStoreEventDispatcher.<Key, String>nullStoreEventDispatcher());
  }

  @Test
  public void testPutAndGet() throws StoreAccessException {
    Key copyKey = new Key(KEY);
    store.put(copyKey, VALUE);

    copyKey.state = "Different!";

    Store.ValueHolder<String> firstStoreValue = store.get(KEY);
    Store.ValueHolder<String> secondStoreValue = store.get(copyKey);
    if (copyForWrite) {
      assertThat(firstStoreValue.value(), is(VALUE));
      assertThat(secondStoreValue, nullValue());
    } else {
      assertThat(firstStoreValue, nullValue());
      assertThat(secondStoreValue.value(), is(VALUE));
    }
  }

  @Test
  public void testCompute() throws StoreAccessException {
    final Key copyKey = new Key(KEY);
    store.compute(copyKey, new BiFunction<Key, String, String>() {
      @Override
      public String apply(Key key, String value) {
        assertThat(key, is(copyKey));
        return VALUE;
      }
    });
    copyKey.state = "Different!";
    store.compute(copyKey, new BiFunction<Key, String, String>() {
      @Override
      public String apply(Key key, String value) {
        if (copyForWrite) {
          assertThat(value, nullValue());
        } else {
          assertThat(value, is(VALUE));
          assertThat(key, is(copyKey));
          if (copyForRead) {
            key.state = "Changed!";
          }
        }
        return value;
      }
    });

    if (copyForRead) {
      assertThat(copyKey.state, is("Different!"));
    }
  }

  @Test
  public void testComputeWithoutReplaceEqual() throws StoreAccessException {
    final Key copyKey = new Key(KEY);
    store.compute(copyKey, new BiFunction<Key, String, String>() {
      @Override
      public String apply(Key key, String value) {
        assertThat(key, is(copyKey));
        return VALUE;
      }
    }, NOT_REPLACE_EQUAL);
    copyKey.state = "Different!";
    store.compute(copyKey, new BiFunction<Key, String, String>() {
      @Override
      public String apply(Key key, String value) {
        if (copyForWrite) {
          assertThat(value, nullValue());
        } else {
          assertThat(value, is(VALUE));
          assertThat(key, is(copyKey));
          if (copyForRead) {
            key.state = "Changed!";
          }
        }
        return value;
      }
    }, NOT_REPLACE_EQUAL);

    if (copyForRead) {
      assertThat(copyKey.state, is("Different!"));
    }
  }

  @Test
  public void testComputeWithReplaceEqual() throws StoreAccessException {
    final Key copyKey = new Key(KEY);
    store.compute(copyKey, new BiFunction<Key, String, String>() {
      @Override
      public String apply(Key key, String value) {
        assertThat(key, is(copyKey));
        return VALUE;
      }
    }, REPLACE_EQUAL);
    copyKey.state = "Different!";
    store.compute(copyKey, new BiFunction<Key, String, String>() {
      @Override
      public String apply(Key key, String value) {
        if (copyForWrite) {
          assertThat(value, nullValue());
        } else {
          assertThat(value, is(VALUE));
          assertThat(key, is(copyKey));
          if (copyForRead) {
            key.state = "Changed!";
          }
        }
        return value;
      }
    }, REPLACE_EQUAL);

    if (copyForRead) {
      assertThat(copyKey.state, is("Different!"));
    }
  }

  @Test
  public void testIteration() throws StoreAccessException {
    store.put(KEY, VALUE);
    Store.Iterator<Cache.Entry<Key, Store.ValueHolder<String>>> iterator = store.iterator();
    assertThat(iterator.hasNext(), is(true));
    while (iterator.hasNext()) {
      Cache.Entry<Key, Store.ValueHolder<String>> entry = iterator.next();
      if (copyForRead || copyForWrite) {
        assertThat(entry.getKey(), not(sameInstance(KEY)));
      } else {
        assertThat(entry.getKey(), sameInstance(KEY));
      }
    }
  }

  @Test
  public void testComputeIfAbsent() throws StoreAccessException {
    store.computeIfAbsent(KEY, new Function<Key, String>() {
      @Override
      public String apply(Key key) {
        if (copyForRead || copyForWrite) {
          assertThat(key, not(sameInstance(KEY)));
        } else {
          assertThat(key, sameInstance(KEY));
        }
        return VALUE;
      }
    });
  }

  @Test
  public void testBulkCompute() throws StoreAccessException {
    final AtomicReference<Key> keyRef = new AtomicReference<Key>();
    store.bulkCompute(singleton(KEY), new Function<Iterable<? extends Map.Entry<? extends Key, ? extends String>>, Iterable<? extends Map.Entry<? extends Key, ? extends String>>>() {
      @Override
      public Iterable<? extends Map.Entry<? extends Key, ? extends String>> apply(Iterable<? extends Map.Entry<? extends Key, ? extends String>> entries) {
        Key key = entries.iterator().next().getKey();
        if (copyForRead || copyForWrite) {
          assertThat(key, not(sameInstance(KEY)));
        } else {
          assertThat(key, sameInstance(KEY));
        }
        keyRef.set(key);
        return singletonMap(KEY, VALUE).entrySet();
      }
    });

    store.bulkCompute(singleton(KEY), new Function<Iterable<? extends Map.Entry<? extends Key, ? extends String>>, Iterable<? extends Map.Entry<? extends Key, ? extends String>>>() {
      @Override
      public Iterable<? extends Map.Entry<? extends Key, ? extends String>> apply(Iterable<? extends Map.Entry<? extends Key, ? extends String>> entries) {
        if (copyForRead) {
          assertThat(entries.iterator().next().getKey(), not(sameInstance(keyRef.get())));
        }
        return singletonMap(KEY, VALUE).entrySet();
      }
    });
  }

  @Test
  public void testBulkComputeWithoutReplaceEqual() throws StoreAccessException {
    store.bulkCompute(singleton(KEY), new Function<Iterable<? extends Map.Entry<? extends Key, ? extends String>>, Iterable<? extends Map.Entry<? extends Key, ? extends String>>>() {
      @Override
      public Iterable<? extends Map.Entry<? extends Key, ? extends String>> apply(Iterable<? extends Map.Entry<? extends Key, ? extends String>> entries) {
        if (copyForRead || copyForWrite) {
          assertThat(entries.iterator().next().getKey(), not(sameInstance(KEY)));
        } else {
          assertThat(entries.iterator().next().getKey(), sameInstance(KEY));
        }
        return singletonMap(KEY, VALUE).entrySet();
      }
    }, NOT_REPLACE_EQUAL);
  }

  @Test
  public void testBulkComputeWithReplaceEqual() throws StoreAccessException {
    store.bulkCompute(singleton(KEY), new Function<Iterable<? extends Map.Entry<? extends Key, ? extends String>>, Iterable<? extends Map.Entry<? extends Key, ? extends String>>>() {
      @Override
      public Iterable<? extends Map.Entry<? extends Key, ? extends String>> apply(Iterable<? extends Map.Entry<? extends Key, ? extends String>> entries) {
        if (copyForRead || copyForWrite) {
          assertThat(entries.iterator().next().getKey(), not(sameInstance(KEY)));
        } else {
          assertThat(entries.iterator().next().getKey(), sameInstance(KEY));
        }
        return singletonMap(KEY, VALUE).entrySet();
      }
    }, REPLACE_EQUAL);
  }

  @Test
  public void testBulkComputeIfAbsent() throws StoreAccessException {
    store.bulkComputeIfAbsent(singleton(KEY), new Function<Iterable<? extends Key>, Iterable<? extends Map.Entry<? extends Key, ? extends String>>>() {
      @Override
      public Iterable<? extends Map.Entry<? extends Key, ? extends String>> apply(Iterable<? extends Key> keys) {
        if (copyForWrite || copyForRead) {
          assertThat(keys.iterator().next(), not(sameInstance(KEY)));
        } else {
          assertThat(keys.iterator().next(), sameInstance(KEY));
        }
        return singletonMap(KEY, VALUE).entrySet();
      }
    });
  }

  public static final class Key {
    String state;
    final int hashCode;

    public Key(String state) {
      this.state = state;
      this.hashCode = state.hashCode();
    }

    public Key(Key key) {
      this.state = key.state;
      this.hashCode = key.hashCode();
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      Key value = (Key) o;
      return state.equals(value.state);
    }

    @Override
    public int hashCode() {
      return hashCode;
    }
  }
}


text:
require "mousecop/version"
require "mousecop/player"
require "mousecop/player_source"

module Mousecop
  # Your code goes here...
end


text:
#ifndef TABLE_REC_ITER_H
#define TABLE_REC_ITER_H

#include "MyDB_RecordIterator.h"
#include "MyDB_Record.h"
#include "MyDB_TableReaderWriter.h"
#include "MyDB_Table.h"

class MyDB_TableRecIterator : public MyDB_RecordIterator {

public:

	// put the contents of the next record in the file/page into the iterator record
	// this should be called BEFORE the iterator record is first examined
	void getNext () override;

	// return true iff there is another record in the file/page
	bool hasNext () override;

	// destructor and contructor
	MyDB_TableRecIterator (MyDB_TableReaderWriter &myParent, MyDB_TablePtr myTableIn,
        	MyDB_RecordPtr myRecIn);
	~MyDB_TableRecIterator ();

private:

	MyDB_RecordIteratorPtr myIter;
	int curPage;

	MyDB_TableReaderWriter &myParent;
	MyDB_TablePtr myTable;
        MyDB_RecordPtr myRec;

};

#endif


text:
vaadin addon to support fluent creation of UI components.

See this addon in the vaadin directory: https://vaadin.com/directory#addon/fluent-ui:vaadin

add this addon to your projects pom.xml

```xml
<dependency>
   <groupId>org.vaadin.addons</groupId>
   <artifactId>fluent-ui</artifactId>
   <version>0.1.0</version>
</dependency>

<repository>
   <id>vaadin-addons</id>
   <url>http://maven.vaadin.com/vaadin-addons</url>
</repository>
```

## Rules for fluent API

First: these are not Builders. The Builder pattern assumes that calling "build()" creates a new instance every time.
The Fluent-helpers do not create new instances, they just wrap a concrete final component and allow fluent access to
its setters.

### How it is done

- a fluent wrapper is created for every Vaadin Component
- every constructor of Component "Bar" can be accessed via static method FluentBar.bar(....)
- every "setFoo()" method can be accessed via "foo()" (no "with...")
- every "addFoo(Foo foo)" method can be accessed via vararg "addFoo(Foo... foos)", so many items can be added at once
- methods concerning lifecycle and composition (setParent, setCompositionRoot) must not be exposed.
- boolean setters (setEnabled()) become enabled(boolean) but might be flanked by enable() and disable() when applicable.

## Vaadin Addon rules

This project follows the rules and guidelines described here: https://vaadin.com/directory/help/creating-vaadin-add-ons


text:
using System;
using Newtonsoft.Json.Linq;
using System.Net;
using Newtonsoft.Json;
using System.Text;
using System.IO;

namespace Earlz.Btcd
{
    public class Btcd : IBtcd
    {
        public Btcd (string url, ICredentials credentials)
        {
            Url = url;
            Credentials = credentials;
        }
        ICredentials Credentials;
        string Url;
        public JObject Invoke (string method, params object[] _params)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
            webRequest.Credentials = Credentials;

            webRequest.ContentType = "application/json-rpc";
            webRequest.Method = "POST";

            JObject jo = new JObject ();
            jo ["jsonrpc"] = "1.0";
            jo ["id"] = "btcd";
            jo ["method"] = method;

            if (_params != null) {
                if (_params.Length > 0) {
                    JArray props = new JArray ();
                    foreach (var p in _params) {
                        props.Add (p);
                    }
                    jo.Add (new JProperty ("params", props));
                }
            }

            string s = JsonConvert.SerializeObject (jo);
            // serialize json for the request
            byte[] byteArray = Encoding.UTF8.GetBytes (s);
            webRequest.ContentLength = byteArray.Length;

            using (Stream dataStream = webRequest.GetRequestStream()) {
                dataStream.Write (byteArray, 0, byteArray.Length);
            }

            using (WebResponse webResponse = webRequest.GetResponse()) {
                using (Stream str = webResponse.GetResponseStream()) {
                    using (StreamReader sr = new StreamReader(str)) {
                        return JsonConvert.DeserializeObject<JObject> (sr.ReadToEnd ());
                    }
                }
            }
        }

    }
}


text:
#include <Core/Platform.h>
#include <bass24/c/bass.h>
#include "Audio.h"
#include "SetLastError.h"
#include "Content/Demo.h" // FIXME: for TPB-06 sample loads only

static HSTREAM s_hMP3[3] = { 0 };
static HFX s_hFX = 0;

bool Audio_Create(unsigned int iDevice, HWND hWnd, const std::string &mp3Path, bool mute)
{
	ASSERT(iDevice == -1); // || iDevice < Audio_GetDeviceCount());
	ASSERT(hWnd != NULL);

	// Bass device IDs:
	//  0 = No sound (causes functionality to be limited, so -1 is the better pick).
	// -1 = Default.
	// >0 = As enumerated.

//	DWORD devCount = 0;
//	BASS_DEVICEINFO devInfo;
//	for (DWORD iDev = 0; BASS_GetDeviceInfo(iDev, &devInfo); ++iDev)
//		if (devInfo.flags & BASS_DEVICE_ENABLED)
//			++devCount;
//

	if (!BASS_Init(iDevice, 44100, BASS_DEVICE_LATENCY, hWnd, NULL))
	{
		switch (BASS_ErrorGetCode())
		{
		case BASS_ERROR_DEVICE:
		case BASS_ERROR_ALREADY:
		case BASS_ERROR_NO3D:
		case BASS_ERROR_UNKNOWN:
		case BASS_ERROR_MEM:
			ASSERT(0);

		case BASS_ERROR_DRIVER:
		case BASS_ERROR_FORMAT:
			SetLastError("Can not initialize BASS audio library @ 44.1 kHz.");
			return false;
		}
	}

	// hack: load MP3 as well as gun shot & shell drop
	std::vector<const std::string> MP3s;
	MP3s.push_back(mp3Path);
	MP3s.push_back(Demo::GetAssetsPath() + "shot.mp3");
	MP3s.push_back(Demo::GetAssetsPath() + "shelldrop.mp3");

	int iMP3 = 0;
	for (auto &path : MP3s)
	{
		DWORD streamFlags = BASS_SAMPLE_FX | BASS_MP3_SETPOS | BASS_STREAM_PRESCAN;
		if (0 != iMP3) streamFlags |= (0 == iDevice) ? BASS_STREAM_DECODE : 0; // Decode disables FX.
//		const DWORD streamFlags = BASS_SAMPLE_FX | BASS_MP3_SETPOS | BASS_STREAM_PRESCAN | ( (0 == iDevice) ? BASS_STREAM_DECODE : 0 );
		HSTREAM hMP3 = BASS_StreamCreateFile(FALSE, path.c_str(), 0, 0, streamFlags /* BASS_UNICODE */);
		if (hMP3 == NULL)
		{
			switch (BASS_ErrorGetCode())
			{
			case BASS_ERROR_INIT:
			case BASS_ERROR_NOTAVAIL:
			case BASS_ERROR_ILLPARAM:
			case BASS_ERROR_NO3D:
			case BASS_ERROR_FILEFORM:
			case BASS_ERROR_CODEC:
			case BASS_ERROR_FORMAT:
			case BASS_ERROR_SPEAKER:
			case BASS_ERROR_MEM:
				ASSERT(0);

			case BASS_ERROR_FILEOPEN:
			case BASS_ERROR_UNKNOWN:
				SetLastError("Can not load MP3: " + path);
				return false;
			}
		}

		s_hMP3[iMP3++] = hMP3;
	}

	s_hFX = BASS_ChannelSetFX(s_hMP3[0], BASS_FX_DX8_FLANGER, 1);
	if (0 == s_hFX)
	{
		SetLastError("Can't enable DirectX 8 sound effect on our MP3 through BASS.");
		return false;
	}

	Audio_FlangerMP3(0.25f, 6.f);

#if defined(_DEBUG) || defined(_DESIGN)
	// Looping soundtrack is convenient when editing.
	BASS_ChannelFlags(s_hMP3[0], BASS_SAMPLE_LOOP, BASS_SAMPLE_LOOP);
#endif

	if (true == mute)
	{
		for (int iMP3 = 0; iMP3 < 3; ++iMP3)
			BASS_ChannelSetAttribute(s_hMP3[iMP3], BASS_ATTRIB_VOL, 0.f);
	}

	return true;
}

void Audio_Destroy()
{
	BASS_Free();
}

void Audio_Update()
{
	ASSERT(s_hMP3[0] != NULL);
	BASS_Update(0);
}

void Audio_Start()
{
	ASSERT(s_hMP3[0] != NULL);
	BASS_ChannelPlay(s_hMP3[0], TRUE);
}

void Audio_Gunshot() { BASS_ChannelPlay(s_hMP3[1], TRUE); }
void Audio_Shelldrop() { BASS_ChannelPlay(s_hMP3[2], TRUE); }

void Audio_Pause()
{
	ASSERT(s_hMP3[0] != NULL);
	BASS_ChannelPause(s_hMP3[0]);
}

void Audio_Unpause()
{
	ASSERT(s_hMP3[0] != NULL);
 	BASS_ChannelPlay(s_hMP3[0], FALSE);
}

bool Audio_IsPlaying()
{
	ASSERT(s_hMP3[0] != NULL);
	return BASS_ChannelIsActive(s_hMP3[0]) == BASS_ACTIVE_PLAYING;
}

void Audio_SetPosition(float secPos)
{
	ASSERT(s_hMP3[0] != NULL);
	const QWORD newChanPos = BASS_ChannelSeconds2Bytes(s_hMP3[0], secPos);
	BASS_ChannelSetPosition(s_hMP3[0], newChanPos, BASS_POS_BYTE);
}

float Audio_GetPosition()
{
	ASSERT(s_hMP3[0] != NULL);
	const QWORD chanPos = BASS_ChannelGetPosition(s_hMP3[0], BASS_POS_BYTE);
	const double secPos = BASS_ChannelBytes2Seconds(s_hMP3[0], chanPos);
	return (float) secPos;
}

void Audio_FlangerMP3(float wetDry, float freqMod)
{
	BASS_DX8_FLANGER fxParams;
	fxParams.fWetDryMix = wetDry; // 0 = silent, 100 = wet
	fxParams.fDepth = 100.f;
	fxParams.fFeedback = -50.f;
	fxParams.fFrequency = freqMod; // upwards of 6 is cool
	fxParams.lWaveform = 1; // Sine
	fxParams.fDelay = 2.f;
	fxParams.lPhase = BASS_DX8_PHASE_ZERO;

	if (FALSE == BASS_FXSetParameters(s_hFX, &fxParams))
	{
		int errCode = BASS_ErrorGetCode();
		ASSERT(0);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?><module codename="org.netbeans.modules.websvc.jaxws.lightapi">
    <module_version install_time="1360798444578" last="true" origin="installer" specification_version="1.15.1">
        <file crc="301239234" name="config/Modules/org-netbeans-modules-websvc-jaxws-lightapi.xml"/>
        <file crc="2940723183" name="modules/locale/org-netbeans-modules-websvc-jaxws-lightapi_ja.jar"/>
        <file crc="1266018910" name="modules/locale/org-netbeans-modules-websvc-jaxws-lightapi_pt_BR.jar"/>
        <file crc="38569709" name="modules/locale/org-netbeans-modules-websvc-jaxws-lightapi_ru.jar"/>
        <file crc="140195465" name="modules/locale/org-netbeans-modules-websvc-jaxws-lightapi_zh_CN.jar"/>
        <file crc="2515295197" name="modules/org-netbeans-modules-websvc-jaxws-lightapi.jar"/>
    </module_version>
</module>


text:
Receive Addresses

      <% if(data.addresses.length == 0) {%>

No receive addresses yet.

      <% } else { %>

          <% for(var i=0;i<data.addresses.length;i++) { %>

                <%- data.addresses[i].name || 'No Label' %>

                  <%- coinpunk.wallet.addressReceivedAmount(data.addresses[i].address) %> BTC

<%- data.addresses[i].address %>

<a href="#/addresses/request/<%- data.addresses[i].address %>" class="btn btn-primary"> Request Payment

          <% } %>

                Label
                Address

                  Total
                  Total Received

              <% for(var i=0; i<data.addresses.length; i++) { %>
                <% if(!data.addresses[i].isChange) { %>

                    <%- data.addresses[i].name %>
                    <%- data.addresses[i].address %>

                        <%- coinpunk.wallet.addressReceivedAmount(data.addresses[i].address) %> BTC

                      <a href="#/addresses/request/<%- data.addresses[i].address %>" class="btn btn-primary"> Request Payment

                <% } %>
              <% } %>

      <% } %>

New Address

    <form onsubmit="coinpunk.controllers.addresses.generateNewAddress($('#addressLabel').val()); return false;">

        Label (optional): <input id="addressLabel" type="text" style="width: 200px"> <button class="btn btn-primary"> Generate</button>

          <button type="btn" class="close" data-dismiss="alert" aria-hidden="true">×</button>

    </form>


text:
CREATE TABLE `typecho_links_upgrade` (
  `lid` INTEGER NOT NULL PRIMARY KEY,
  `name` varchar(200) default NULL,
  `url` varchar(200) default NULL,
  `sort` varchar(200) default NULL,
  `image` varchar(200) default NULL,
  `description` varchar(200) default NULL,
  `user` varchar(200) default NULL,
  `order` int(10) default '0'
);
INSERT INTO `typecho_links_upgrade` (`lid`, `name`, `url`, `sort`, `image`, `description`, `user`, `order`)
SELECT `lid`, `name`, `url`, NULL, NULL, `description`, NULL, `order` FROM `typecho_links`;
DROP TABLE `typecho_links`;
CREATE TABLE `typecho_links` (
  `lid` INTEGER NOT NULL PRIMARY KEY,
  `name` varchar(200) default NULL,
  `url` varchar(200) default NULL,
  `sort` varchar(200) default NULL,
  `image` varchar(200) default NULL,
  `description` varchar(200) default NULL,
  `user` varchar(200) default NULL,
  `order` int(10) default '0'
);
INSERT INTO `typecho_links` SELECT * FROM `typecho_links_upgrade`;
DROP TABLE `typecho_links_upgrade`;


text:
title: Android 扩展
type: references
order: 11.2
version: 2.1
---

# Android 扩展

Weex 提供了扩展机制,可以根据自己的业务进行定制自己的功能。
主要分为两类扩展:

- Module 扩展 非 UI 的特定功能。例如 sendHttp、openURL 等。
- Component 扩展 实现特别功能的 Native 控件。例如:RichTextview,RefreshListview 等。
- Adapter 扩展 Weex 对一些基础功能实现了统一的接口,可实现这些接口来定制自己的业务。例如:图片下载等。

## Module 扩展

1. Module 扩展必须继承 WXModule 类。
2. 扩展方法必须加上 @WXModuleAnno 注解。Weex 会根据注解来判断当前方法是否要运行在 UI 线程,和当前方法是否是扩展方法。
3. Weex是根据反射来进行调用 Module 扩展方法,所以Module中的扩展方法必须是 public 类型。
4. 同样因为是通过反射调用,Module 不能被混淆。请在混淆文件中添加代码:`-keep public class * extends com.taobao.weex.common.WXModule{*;}`
5. Module 扩展的方法可以使用 int, double, float, String, Map, List 类型的参数
6. 完成 Module 后一定要在初始化时注册 `WXSDKEngine.registerModule("myModule", MyModule.class);` 否则会报类似错误:`ReportException :undefined:9: TypeError: Object #<Object> has no method 'printLog'`

示例如下:

```java
public class MyModule extends WXModule {

  @WXModuleAnno(runOnUIThread = true)
  public void printLog(String msg) {
    Toast.makeText(mWXSDKInstance.getContext(),msg,Toast.LENGTH_SHORT).show();
  }
}
```

JS 调用如下:

```html
<template>
  <div>
    <text onclick="click">点击我测试</text>
  </div>
</template>

<script>
  module.exports = {
    methods: {
      click: function() {
        weex.requireModule('myModule').printLog("我是一个测试!");
      }
    }
  }
</script>
```

#### 支持 synchronous/asynchronous 回调

你可以添加 `@JSMethod(uiThread = false或true)` 注释来选择 moudle 的回调模式。请参见以下示例:

```java
  // as sync-callback mode
@JSMethod (uiThread = false)
public void testSyncCall(){
    WXLogUtils.d("WXComponentSyncTest : Thread.currentThread().getName());
}

// as async-callback mode
@JSMethod (uiThread = true)
public void testAsyncCall(){
    WXLogUtils.e("WXComponentASynTest : Thread.currentThread().getName() );
}
```

## Component 扩展

1. Component 扩展类必须集成 WXComponent.
2. Component 对应的设置属性的方法必须添加注解 @WXComponentProp(name=value(value is attr or style of dsl))
3. Weex sdk 通过反射调用对应的方法,所以 Component 对应的属性方法必须是 public,并且不能被混淆。请在混淆文件中添加代码  `-keep public class * extends com.taobao.weex.ui.component.WXComponent{*;}`
4. Component 扩展的方法可以使用 int, double, float, String, Map, List 类型的参数
5. 完成 Component 后一定要在初始化时注册 `WXSDKEngine.registerComponent("richtext",RichText.class);`

示例如下:

```java
public class RichText extends WXComponent {

  public RichText(WXSDKInstance instance, WXDomObject dom, WXVContainer parent, boolean isLazy) {
    super(instance, dom, parent, isLazy);
  }

  @Override
  protected void initView() {
    mHost=new TextView(mContext);
    ((TextView)mHost).setMovementMethod(LinkMovementMethod.getInstance());
  }

  @WXComponentProp(name = "tel")
  public void setTelLink(String tel){
    SpannableString spannable=new SpannableString(tel);
    spannable.setSpan(new URLSpan("tel:"+tel),0,tel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    ((TextView)mHost).setText(spannable);
  }
}
```

JS 调用如下:

```html
<template>
  <div>
    <richText tel="12305" style="width:200;height:100">12305</text>
  </div>
</template>
```
## Adapter扩展

图片下载:

需要时集成接口 IWXImgLoaderAdapter,实现 setImage 方法。

示例如下:

```java
public class ImageAdapter implements IWXImgLoaderAdapter {

  public ImageAdapter() {
  }

  @Override
  public void setImage(final String url, final ImageView view,
                       WXImageQuality quality, WXImageStrategy strategy) {

    WXSDKManager.getInstance().postOnUiThread(new Runnable() {

      @Override
      public void run() {
        if(view==null||view.getLayoutParams()==null){
          return;
        }
        if (TextUtils.isEmpty(url)) {
          view.setImageBitmap(null);
          return;
        }
        String temp = url;
        if (url.startsWith("//")) {
          temp = "http:" + url;
        }
        if (view.getLayoutParams().width <= 0 || view.getLayoutParams().height <= 0) {
          return;
        }
        Picasso.with(WXEnvironment.getApplication())
            .load(temp)
            .into(view);
      }
    },0);
  }
}
```
#### 组件方法支持
从WeexSDK 0.9.5开始,你可以定义组件方法

- 在组件中如下声明一个组件方法

 ```java
 @JSMethod
 public void focus(){
  //method implementation
 }
 ```

- 注册组之后,你可以在weex 文件中调用

  ```html
	<template>
    <mycomponent id='mycomponent'></mycomponent>
	</template>
	<script>
    module.exports = {
      created: function() {
        this.$el('mycomponent').focus();
      }
    }
	</script>
	```

注:工程要添加依赖 `compile 'com.squareup.picasso:picasso:2.5.2'`

#### SDK混淆规则
若要在APP中使用混淆,请在相应的配置文件中添加如下规则:

```java
-keep class com.taobao.weex.WXDebugTool{*;}
-keep class com.taobao.weex.devtools.common.LogUtil{*;}
-keepclassmembers class ** {
  @com.taobao.weex.ui.component.WXComponentProp public *;
}
-keep class com.taobao.weex.bridge.**{*;}
-keep class com.taobao.weex.dom.**{*;}
-keep class com.taobao.weex.adapter.**{*;}
-keep class com.taobao.weex.common.**{*;}
-keep class * implements com.taobao.weex.IWXObject{*;}
-keep class com.taobao.weex.ui.**{*;}
-keep class com.taobao.weex.ui.component.**{*;}
-keep class com.taobao.weex.utils.**{
    public <fields>;
    public <methods>;
    }
-keep class com.taobao.weex.view.**{*;}
-keep class com.taobao.weex.module.**{*;}
-keep public class * extends com.taobao.weex.common.WXModule{*;}
-keep public class * extends com.taobao.weex.ui.component.WXComponent{*;}
-keep public class com.taobao.taolive.ui.weex.**{*;}
-keep class * implements com.taobao.weex.ui.IExternalComponentGetter{*;}
-keep class com.alibaba.aliweex.hc.HCConfig{*;}
-keep class com.alibaba.dynamic.**{*;}
```


text:
layout: post
title:  "Example Fact Post 2"
date:   2017-02-02
author:
  name: "Authors name"
  email: "Authors email"
  website: "Authors website"
  twitter: "Authors twitter"
editor:
  name: "Editors Name"
  email: "Editors email address"
  website: "Editors website"
  twitter: "Editors twitter"
category: fact
tags: tag1 tag2 tag3
comments: true
---
This is a fact. Everyone knows this is the truth. We have the best truths.

>This is the fact post content.
>Someone awesome
>--[Twitter][]

Sources:
[Google][]
[Yahoo][]
[MSN][]
[Twitter][]

[twitter]: http://twitter.com/        "Twitter"
[google]: http://google.com/        "Google"
[yahoo]:  http://search.yahoo.com/  "Yahoo Search"
[msn]:    http://search.msn.com/    "MSN Search"


text:
using DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Yad2.Controllers
{
    public class RentController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<RentApartment> Get()
        {
            IDataRepository data = new DataRepository();

            var a= data.GetAppartments();

            return a;
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}


text:
from flask import Flask
app = Flask(__name__)

# define our models
class User(Model):
    user_id = UUID(primary_key=True)
    name = Text()
    email = Text(required=True)

class EmailToUser(Model):
    email = Text(primary_key=True)
    user_id = UUID(required=True)

class LoginHistory(Model):
    # TTL = 60 days
    user_id = UUID(primary_key=True)
    login_date = DateTime(primary_true=True)
    ip_address = Text()

# routes

@app.before_first_request
def connect_to_db():
    print "Connecting to cassandra"
    try:
        setup(["localhost"], "users_demo")
    except Exception as e:
        print e

# routes

print("Starting up the demo app")
app.run(port=7777)


text:
var express = require('express'),
    ObjectID = require('mongodb').ObjectID;

//  Structure Routes
module.exports = function (app, db, Users) {
	var router = express.Router(),
        structures = db.collection("structures");

    router.post('/', function(req, res) {
		structures.insert({name: req.body.name, type: req.body.type, data: req.body.data}, function(err){
            if (err) {
                return console.log("Error inserting structure ", err);
            }
        });
		res.json({success: true, message: "structure Created"});
	});

	router.get('/all', function(req, res) {
		structures.find({}).toArray(function(err, found) {
            if (err) {
                return console.log("Error getting all structures: ", err);
            }
            res.json(found);
        });
	});

	router.get('/:structure', function(req, res) {
		structures.find({name: req.params.structure}).toArray(function(err, found) {
            if (err) {
                return console.log("Error getting structure: ", err);
            }
            res.json(found);
        });
	});

	router.get('/search/:structure', function(req, res) {
		structures.find({name: req.params.structure}).toArray(function (err, found) {
            if (err) {
                return console.log("Error searching for structures: ", err);
            }
            res.json(found);
        });
	});

	router.put('/:structure', function(req, res) {
		structures.update({_id: ObjectID(req.params.structure)}, {$set: {name: req.body.name, data: req.body.data}}, function(err) {
            if (err) {
                return console.log("Error updating structure: ", err);
            }
            res.json({success: true, message: "structure Updated"});
        });
	});

	router.delete('/:structure', function(req, res) {
		structures.remove({_id: ObjectID(req.params.structure)}, function(err) {
            if(err) {
                return console.log('Error removing structure: ', err);
            }
            res.json({success: true, message: "structure Deleted"});
        });
	});

    return router;
};


text:
{% extends "base.html" %}
{% load staticfiles %}
{% load i18n %}
{% block nav %}{% endblock nav %}

{% block content %}

{% trans "You have successfully declined your invitation to edit this channel" %}

			{% trans "Go Home" %}

{% endblock %}


text:
package org.apache.camel.component.cxf;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.Endpoint;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.component.cxf.common.message.CxfConstants;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.frontend.AbstractWSDLBasedEndpointFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.apache.hello_world_soap_http.Greeter;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.support.AbstractXmlApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CxfTimeoutTest extends CamelSpringTestSupport {

    protected static final String GREET_ME_OPERATION = "greetMe";
    protected static final String TEST_MESSAGE = "Hello World!";
    protected static final String JAXWS_SERVER_ADDRESS
        = "http://localhost:" + CXFTestSupport.getPort1() + "/CxfTimeoutTest/SoapContext/SoapPort";

    @Override
    public boolean isCreateCamelContextPerClass() {
        return true;
    }

    @BeforeClass
    public static void startService() {
        Greeter implementor = new GreeterImplWithSleep();
        Endpoint.publish(JAXWS_SERVER_ADDRESS, implementor);
    }

    @Test
    public void testInvokingJaxWsServerWithBusUriParams() throws Exception {
        sendTimeOutMessage("cxf://" + JAXWS_SERVER_ADDRESS + "?serviceClass=org.apache.hello_world_soap_http.Greeter&bus=#cxf");
    }

    @Test
    public void testInvokingJaxWsServerWithoutBusUriParams() throws Exception {
        sendTimeOutMessage("cxf://" + JAXWS_SERVER_ADDRESS + "?serviceClass=org.apache.hello_world_soap_http.Greeter");
    }

    @Test
    public void testInvokingJaxWsServerWithCxfEndpoint() throws Exception {
        sendTimeOutMessage("cxf://bean:springEndpoint");
    }

    @Test
    public void testInvokingJaxWsServerWithCxfEndpointWithConfigurer() throws Exception {
        Exchange reply = sendJaxWsMessage("cxf://bean:springEndpoint?cxfEndpointConfigurer=#myConfigurer");
        // we don't expect the exception here
        assertFalse("We don't expect the exception here", reply.isFailed());
        assertEquals("Get a wrong response", "Greet Hello World!", reply.getOut().getBody(String.class));
    }

    @Test
    public void testInvokingFromCamelRoute() throws Exception {
        sendTimeOutMessage("direct:start");
    }

    @Test
    public void testDoCatchWithTimeOutException() throws Exception {
        MockEndpoint error = context.getEndpoint("mock:error", MockEndpoint.class);
        error.expectedMessageCount(1);
        sendTimeOutMessage("direct:doCatch");
        error.assertIsSatisfied();
    }

    protected void sendTimeOutMessage(String endpointUri) throws Exception {
        Exchange reply = sendJaxWsMessage(endpointUri);
        Exception e = reply.getException();
        assertNotNull("We should get the exception cause here", e);
        assertTrue("We should get the socket time out exception here", e instanceof SocketTimeoutException);
    }

    protected Exchange sendJaxWsMessage(String endpointUri) throws InterruptedException {
        Exchange exchange = template.send(endpointUri, new Processor() {
            public void process(final Exchange exchange) {
                final List<String> params = new ArrayList<>();
                params.add(TEST_MESSAGE);
                exchange.getIn().setBody(params);
                exchange.getIn().setHeader(CxfConstants.OPERATION_NAME, GREET_ME_OPERATION);
            }
        });
        return exchange;
    }

    @Override
    protected AbstractXmlApplicationContext createApplicationContext() {
        // we can put the http conduit configuration here
        return new ClassPathXmlApplicationContext("org/apache/camel/component/cxf/cxfConduitTimeOutContext.xml");
    }

    public static class MyCxfEndpointConfigurer implements CxfEndpointConfigurer {

        @Override
        public void configure(AbstractWSDLBasedEndpointFactory factoryBean) {
            // Do nothing here
        }

        @Override
        public void configureClient(Client client) {
            // reset the timeout option to override the spring configuration one
            HTTPConduit conduit = (HTTPConduit) client.getConduit();
            HTTPClientPolicy policy = new HTTPClientPolicy();
            policy.setReceiveTimeout(60000);
            conduit.setClient(policy);

        }

        @Override
        public void configureServer(Server server) {
            // Do nothing here

        }

    }

}


text:
<?php

/*
  |--------------------------------------------------------------------------
  | Web Routes
  |--------------------------------------------------------------------------
  |
  | Here is where you can register web routes for your application. These
  | routes are loaded by the RouteServiceProvider within a group which
  | contains the "web" middleware group. Now create something great!
  |
 */

/* Public Routes */
// home page
Route::get('/', 'Publics\\HomeController@index');
Route::get('{locale}', 'Publics\\HomeController@index')
        ->where('locale', implode('|', Config::get('app.locales')));

// open one product
Route::get('{any}-{id}', 'Publics\\ProductsController@productPreview')->where('id', '[\d+]+')->where('any', '(.*)');
Route::get('{locale}/{any}-{id}', 'Publics\\ProductsController@productPreview')
        ->where('locale', implode('|', Config::get('app.locales')))->where('id', '[\d+]+')->where('any', '(.*)');

// open all products
Route::get('products', 'Publics\\ProductsController@index');
Route::get('{locale}/products', 'Publics\\ProductsController@index')
        ->where('locale', implode('|', Config::get('app.locales')));

// open all products with categorie
Route::get('category/{category}', 'Publics\\ProductsController@index')->where('category', '(.*)');
Route::get('{locale}/category/{category}', 'Publics\\ProductsController@index')
        ->where('locale', implode('|', Config::get('app.locales')))->where('category', '(.*)');

// checkout please
Route::get('checkout', 'Publics\\CheckoutController@index');
Route::get('{locale}/checkout', 'Publics\\CheckoutController@index')
        ->where('locale', implode('|', Config::get('app.locales')));

// checkout post req
Route::post('checkout', 'Publics\\CheckoutController@setOrder');
Route::post('{locale}/checkout', 'Publics\\CheckoutController@setOrder')
        ->where('locale', implode('|', Config::get('app.locales')));

// open contacts
Route::get('contacts', 'Publics\\ContactsController@index');
Route::get('{locale}/contacts', 'Publics\\ContactsController@index')
        ->where('locale', implode('|', Config::get('app.locales')));

// send message from contacts
Route::post('contacts', 'Publics\\ContactsController@sendMessage');
Route::post('{locale}/contacts', 'Publics\\ContactsController@sendMessage')
        ->where('locale', implode('|', Config::get('app.locales')));

// save fast order
Route::post('fast-order', 'Publics\\CheckoutController@setFastOrder');
Route::post('{locale}/fast-order', 'Publics\\CheckoutController@setFastOrder')
        ->where('locale', implode('|', Config::get('app.locales')));

// add product to cart from add button (ajax)
Route::post('addProduct', 'Publics\\CartController@addProduct');
// get products and cart html
Route::post('getGartProducts', 'Publics\\CartController@renderCartProductsWithHtml');
// get products and cart html
Route::post('removeProductQuantity', 'Publics\\CartController@removeProductQuantity');
// get products and cart html for checkout page
Route::post('getProductsForCheckoutPage', 'Publics\\CartController@getProductsForCheckoutPage');
// remove product from cart
Route::post('removeProduct', 'Publics\\CartController@removeProduct');

/* Administration Routes */
Route::middleware(['auth'])->group(function () { // check for autherization
    Route::get('admin', 'Admin\\DashboardController@index');
    Route::get('{locale}/admin', 'Admin\\DashboardController@index')
            ->where('locale', implode('|', Config::get('app.locales')));
//////////////
    Route::get('admin/publish', 'Admin\\PublishController@index')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/publish', 'Admin\\PublishController@index');
//////////////
    Route::get('admin/edit/pruduct/{number}', 'Admin\\PublishController@index')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/edit/pruduct/{number}', 'Admin\\PublishController@index');
//////////////
    Route::post('admin/publish', 'Admin\\PublishController@setProduct')->where('locale', implode('|', Config::get('app.locales')));
    Route::post('{locale}/admin/publish', 'Admin\\PublishController@setProduct');
//////////////
    Route::post('admin/edit/pruduct/{number}', 'Admin\\PublishController@setProduct')->where('locale', implode('|', Config::get('app.locales')));
    Route::post('{locale}/admin/edit/pruduct/{number}', 'Admin\\PublishController@setProduct');
//////////////
    Route::get('admin/products', 'Admin\\ProductsController@index')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/products', 'Admin\\ProductsController@index');
//////////////
    Route::get('admin/categories', 'Admin\\ProductsCategoryController@index')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/categories', 'Admin\\ProductsCategoryController@index');
//////////////
    Route::post('admin/categories', 'Admin\\ProductsCategoryController@setCategory')->where('locale', implode('|', Config::get('app.locales')));
    Route::post('{locale}/admin/categories', 'Admin\\ProductsCategoryController@setCategory');
//////////////
    Route::post('admin/categories/{number}', 'Admin\\ProductsCategoryController@setCategory')->where('locale', implode('|', Config::get('app.locales')));
    Route::post('{locale}/admin/categories/{number}', 'Admin\\ProductsCategoryController@setCategory');
//////////////
    Route::get('admin/delete/product/{number}', 'Admin\\ProductsController@deleteProduct')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/delete/product/{number}', 'Admin\\ProductsController@deleteProduct');
//////////////
    Route::get('admin/delete/categories', 'Admin\\ProductsCategoryController@deleteCategories')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/delete/categories', 'Admin\\ProductsCategoryController@deleteCategories');
//////////////
    Route::get('admin/users', 'Admin\\UsersController@index')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/users', 'Admin\\UsersController@index');
//////////////
    Route::post('admin/users', 'Admin\\UsersController@setUser')->where('locale', implode('|', Config::get('app.locales')));
    Route::post('{locale}/admin/users', 'Admin\\UsersController@setUser');
//////////////
    Route::get('admin/carousel', 'Admin\\CarouselController@index')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/carousel', 'Admin\\CarouselController@index');
//////////////
    Route::post('admin/carousel', 'Admin\\CarouselController@setSlider')->where('locale', implode('|', Config::get('app.locales')));
    Route::post('{locale}/admin/carousel', 'Admin\\CarouselController@setSlider');
//////////////
    Route::get('admin/delete/user/{userId}', 'Admin\\UsersController@deleteUser')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/delete/user/{userId}', 'Admin\\UsersController@deleteUser');
//////////////
    Route::get('admin/delete/slider/{id}', 'Admin\\CarouselController@deleteSlider')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/delete/slider/{id}', 'Admin\\CarouselController@deleteSlider');
//////////////
    Route::get('admin/orders', 'Admin\\OrdersController@index')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/orders', 'Admin\\OrdersController@index');
//////////////
    Route::get('admin/fast/ord/is/viewed/{id}', 'Admin\\OrdersController@markFastOrder')->where('locale', implode('|', Config::get('app.locales')));
    Route::get('{locale}/admin/fast/ord/is/viewed/{id}', 'Admin\\OrdersController@markFastOrder');
//////////////
    Route::post('admin/removeGalleryImage', 'Admin\\PublishController@removeGalleryImage');
//////////////
    Route::post('admin/changeOrderStatus', 'Admin\\OrdersController@changeStatus');
});

// Authentication Routes...
Route::get('login', [
    'as' => 'login',
    'uses' => 'Auth\LoginController@showLoginForm'
]);
Route::post('login', [
    'as' => '',
    'uses' => 'Auth\LoginController@login'
]);
Route::get('logout', 'Admin\\UsersController@logout');

// Password Reset Routes...
Route::post('password/email', [
    'as' => 'password.email',
    'uses' => 'Auth\ForgotPasswordController@sendResetLinkEmail'
]);
Route::get('password/reset', [
    'as' => 'password.request',
    'uses' => 'Auth\ForgotPasswordController@showLinkRequestForm'
]);
Route::post('password/reset', [
    'as' => '',
    'uses' => 'Auth\ResetPasswordController@reset'
]);
Route::get('password/reset/{token}', [
    'as' => 'password.reset',
    'uses' => 'Auth\ResetPasswordController@showResetForm'
]);

/* Registration Routes. We dont need it
Route::get('register', [
    'as' => 'register',
    'uses' => 'Auth\RegisterController@showRegistrationForm'
]);
Route::post('register', [
    'as' => '',
    'uses' => 'Auth\RegisterController@register'
]);
*/


text:
package com.sgf.entities;

/**Classe Account com respectivos getters e setters
 * @author wgovindji
 *
 */
public class Account {
	private String _id;
	private String sgf_account_id;
	private String account_number;
	private String account_name;
	private Double account_balance;
	private String account_other_info;
	private String account_active;
	private String account_bank_name;
	public String getAccount_bank_name() {
		return account_bank_name;
	}
	public void setAccount_bank_name(String account_bank_name) {
		this.account_bank_name = account_bank_name;
	}
	public String get_id() {
		return _id;
	}
	public void set_id(String _id) {
		this._id = _id;
	}
	public String getSgf_account_id() {
		return sgf_account_id;
	}
	public void setSgf_account_id(String sgf_account_id) {
		this.sgf_account_id = sgf_account_id;
	}
	public String getAccount_number() {
		return account_number;
	}
	public void setAccount_number(String account_number) {
		this.account_number = account_number;
	}
	public String getAccount_name() {
		return account_name;
	}
	public void setAccount_name(String account_name) {
		this.account_name = account_name;
	}
	public Double getAccount_balance() {
		return account_balance;
	}
	public void setAccount_balance(Double account_balance) {
		this.account_balance = account_balance;
	}
	public String getAccount_other_info() {
		return account_other_info;
	}
	public void setAccount_other_info(String account_other_info) {
		this.account_other_info = account_other_info;
	}
	public String getAccount_active() {
		return account_active;
	}
	public void setAccount_active(String account_active) {
		this.account_active = account_active;
	}

}


text:
print("\tWelcome to the 'Three-Year-Old Simulator'\n")
print("This program simulates a conversation with a three-year-old child.")
print("Try to stop the madness.\n")

response = ""
while response != "Because.":
    response = input("Why?\n")

print("Oh.  Okay.")

input("\n\nPress the enter key to exit.")


text:
package com.codedisaster.steamworks;

public class SteamControllerHandle extends SteamNativeHandle {

	public SteamControllerHandle(long handle) {
		super(handle);
	}

}


text:
require "appsnap_sls/log_level"
require "appsnap_sls/simple_logger_configuration"
require "appsnap_sls/simple_logger"

module AppsnapSls

end


text:
@interface BDLBundleConnection : HTTPConnection

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Couper - List All Coupons</title>
    <link rel="stylesheet" href="css/bootstrap.css">
    <link rel="stylesheet" href="css/listall.css">

                    Coupon Code
                    Description

Copied


text:
#region Copyright
// Copyright 2014 Myrcon Pty. Ltd.
//
// 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.
#endregion
#region

using NUnit.Framework;

#endregion

namespace Potato.Core.Shared.Test.ExecutableCommands {
    [TestFixture]
    public class TestCommandAttribute {
        /// <summary>
        ///     Tests that a command type will pass on the value as a string to the Name attribute.
        /// </summary>
        [Test]
        public void TestCommandAttributeNameAliasFromCommandType() {
            var command = new CommandDispatch() {
                CommandType = CommandType.PotatoAddConnection
            };

            Assert.AreEqual("PotatoAddConnection", command.Name);
            Assert.AreEqual(CommandType.PotatoAddConnection, command.CommandType);
        }

        /// <summary>
        ///     Tests that if a command type is not valid during parsing the Name will at least be populated (good thing)
        /// </summary>
        [Test]
        public void TestCommandAttributeParseInvalidCommandType() {
            ICommandDispatch command = new CommandDispatch().ParseCommandType("CustomCommand");

            Assert.AreEqual("CustomCommand", command.Name);
            Assert.AreEqual(CommandType.None, command.CommandType);
        }

        /// <summary>
        ///     Tests the command type can be found from the string.
        /// </summary>
        [Test]
        public void TestCommandAttributeParseValidCommandType() {
            ICommandDispatch command = new CommandDispatch().ParseCommandType("PotatoAddConnection");

            Assert.AreEqual("PotatoAddConnection", command.Name);
            Assert.AreEqual(CommandType.PotatoAddConnection, command.CommandType);
        }
    }
}