text:
[![GoDoc](https://godoc.org/github.com/denisenkom/go-mssqldb?status.svg)](http://godoc.org/github.com/denisenkom/go-mssqldb)
[![Build status](https://ci.appveyor.com/api/projects/status/jrln8cs62wj9i0a2?svg=true)](https://ci.appveyor.com/project/denisenkom/go-mssqldb)
[![codecov](https://codecov.io/gh/denisenkom/go-mssqldb/branch/master/graph/badge.svg)](https://codecov.io/gh/denisenkom/go-mssqldb)

## Install

Requires Go 1.8 or above.

Install with `go get github.com/denisenkom/go-mssqldb` .

## Connection Parameters and DSN

The recommended connection string uses a URL format:
`sqlserver://username:password@host/instance?param1=value&param2=value`
Other supported formats are listed below.

### Common parameters:

* `user id` - enter the SQL Server Authentication user id or the Windows Authentication user id in the DOMAIN\User format. On Windows, if user id is empty or missing Single-Sign-On is used. The user domain sensitive to the case which is defined in the connection string.
* `password`
* `database`
* `connection timeout` - in seconds (default is 0 for no timeout), set to 0 for no timeout. Recommended to set to 0 and use context to manage query and connection timeouts.
* `dial timeout` - in seconds (default is 15), set to 0 for no timeout
* `encrypt`
  * `disable` - Data send between client and server is not encrypted.
  * `false` - Data sent between client and server is not encrypted beyond the login packet. (Default)
  * `true` - Data sent between client and server is encrypted.
* `app name` - The application name (default is go-mssqldb)

### Connection parameters for ODBC and ADO style connection strings:

* `server` - host or host\instance (default localhost)
* `port` - used only when there is no instance in server (default 1433)

### Less common parameters:

* `keepAlive` - in seconds; 0 to disable (default is 30)
* `failoverpartner` - host or host\instance (default is no partner).
* `failoverport` - used only when there is no instance in failoverpartner (default 1433)
* `packet size` - in bytes; 512 to 32767 (default is 4096)
  * Encrypted connections have a maximum packet size of 16383 bytes
  * Further information on usage: https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/configure-the-network-packet-size-server-configuration-option
* `log` - logging flags (default 0/no logging, 63 for full logging)
  *  1 log errors
  *  2 log messages
  *  4 log rows affected
  *  8 trace sql statements
  * 16 log statement parameters
  * 32 log transaction begin/end
* `TrustServerCertificate`
  * false - Server certificate is checked. Default is false if encypt is specified.
  * true - Server certificate is not checked. Default is true if encrypt is not specified. If trust server certificate is true, driver accepts any certificate presented by the server and any host name in that certificate. In this mode, TLS is susceptible to man-in-the-middle attacks. This should be used only for testing.
* `certificate` - The file that contains the public key certificate of the CA that signed the SQL Server certificate. The specified certificate overrides the go platform specific CA certificates.
* `hostNameInCertificate` - Specifies the Common Name (CN) in the server certificate. Default value is the server host.
* `ServerSPN` - The kerberos SPN (Service Principal Name) for the server. Default is MSSQLSvc/host:port.
* `Workstation ID` - The workstation name (default is the host name)
* `ApplicationIntent` - Can be given the value `ReadOnly` to initiate a read-only connection to an Availability Group listener. The `database` must be specified when connecting with `Application Intent` set to `ReadOnly`.

### The connection string can be specified in one of three formats:

1. URL: with `sqlserver` scheme. username and password appears before the host. Any instance appears as
    the first segment in the path. All other options are query parameters. Examples:

  * `sqlserver://username:password@host/instance?param1=value&param2=value`
  * `sqlserver://username:password@host:port?param1=value&param2=value`
  * `sqlserver://sa@localhost/SQLExpress?database=master&connection+timeout=30` // `SQLExpress instance.
  * `sqlserver://sa:mypass@localhost?database=master&connection+timeout=30`     // username=sa, password=mypass.
  * `sqlserver://sa:mypass@localhost:1234?database=master&connection+timeout=30` // port 1234 on localhost.
  * `sqlserver://sa:my%7Bpass@somehost?connection+timeout=30` // password is "my{pass"

  A string of this format can be constructed using the `URL` type in the `net/url` package.

```go
  query := url.Values{}
  query.Add("app name", "MyAppName")

  u := &url.URL{
      Scheme:   "sqlserver",
      User:     url.UserPassword(username, password),
      Host:     fmt.Sprintf("%s:%d", hostname, port),
      // Path:  instance, // if connecting to an instance instead of a port
      RawQuery: query.Encode(),
  }
  db, err := sql.Open("sqlserver", u.String())
```

2. ADO: `key=value` pairs separated by `;`. Values may not contain `;`, leading and trailing whitespace is ignored.
     Examples:

  * `server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName`
  * `server=localhost;user id=sa;database=master;app name=MyAppName`

3. ODBC: Prefix with `odbc`, `key=value` pairs separated by `;`. Allow `;` by wrapping
    values in `{}`. Examples:

  * `odbc:server=localhost\\SQLExpress;user id=sa;database=master;app name=MyAppName`
  * `odbc:server=localhost;user id=sa;database=master;app name=MyAppName`
  * `odbc:server=localhost;user id=sa;password={foo;bar}` // Value marked with `{}`, password is "foo;bar"
  * `odbc:server=localhost;user id=sa;password={foo{bar}` // Value marked with `{}`, password is "foo{bar"
  * `odbc:server=localhost;user id=sa;password={foobar }` // Value marked with `{}`, password is "foobar "
  * `odbc:server=localhost;user id=sa;password=foo{bar`   // Literal `{`, password is "foo{bar"
  * `odbc:server=localhost;user id=sa;password=foo}bar`   // Literal `}`, password is "foo}bar"
  * `odbc:server=localhost;user id=sa;password={foo{bar}` // Literal `{`, password is "foo{bar"
  * `odbc:server=localhost;user id=sa;password={foo}}bar}` // Escaped `} with `}}`, password is "foo}bar"

### Azure Active Directory authentication - preview

The configuration of functionality might change in the future.

Azure Active Directory (AAD) access tokens are relatively short lived and need to be
valid when a new connection is made. Authentication is supported using a callback func that
provides a fresh and valid token using a connector:
``` golang
conn, err := mssql.NewAccessTokenConnector(
  "Server=test.database.windows.net;Database=testdb",
  tokenProvider)
if err != nil {
	// handle errors in DSN
}
db := sql.OpenDB(conn)
```
Where `tokenProvider` is a function that returns a fresh access token or an error. None of these statements
actually trigger the retrieval of a token, this happens when the first statment is issued and a connection
is created.

## Executing Stored Procedures

To run a stored procedure, set the query text to the procedure name:
```go
var account = "abc"
_, err := db.ExecContext(ctx, "sp_RunMe",
	sql.Named("ID", 123),
	sql.Named("Account", sql.Out{Dest: &account}),
)
```

## Reading Output Parameters from a Stored Procedure with Resultset

To read output parameters from a stored procedure with resultset, make sure you read all the rows before reading the output parameters:
```go
sqltextcreate := `
CREATE PROCEDURE spwithoutputandrows
	@bitparam BIT OUTPUT
AS BEGIN
	SET @bitparam = 1
	SELECT 'Row 1'
END
`
var bitout int64
rows, err := db.QueryContext(ctx, "spwithoutputandrows", sql.Named("bitparam", sql.Out{Dest: &bitout}))
var strrow string
for rows.Next() {
	err = rows.Scan(&strrow)
}
fmt.Printf("bitparam is %d", bitout)
```

## Caveat for local temporary tables

Due to protocol limitations, temporary tables will only be allocated on the connection
as a result of executing a query with zero parameters. The following query
will, due to the use of a parameter, execute in its own session,
and `#mytemp` will be de-allocated right away:

```go
conn, err := pool.Conn(ctx)
defer conn.Close()
_, err := conn.ExecContext(ctx, "select @p1 as x into #mytemp", 1)
// at this point #mytemp is already dropped again as the session of the ExecContext is over
```

To work around this, always explicitly create the local temporary
table in a query without any parameters. As a special case, the driver
will then be able to execute the query directly on the
connection-scoped session. The following example works:

```go
conn, err := pool.Conn(ctx)

// Set us up so that temp table is always cleaned up, since conn.Close()
// merely returns conn to pool, rather than actually closing the connection.
defer func() {
	_, _ = conn.ExecContext(ctx, "drop table #mytemp")  // always clean up
	conn.Close() // merely returns conn to pool
}()

// Since we not pass any parameters below, the query will execute on the scope of
// the connection and succeed in creating the table.
_, err := conn.ExecContext(ctx, "create table #mytemp ( x int )")

// #mytemp is now available even if you pass parameters
_, err := conn.ExecContext(ctx, "insert into #mytemp (x) values (@p1)", 1)

```

## Return Status

To get the procedure return status, pass into the parameters a
`*mssql.ReturnStatus`. For example:
```
var rs mssql.ReturnStatus
_, err := db.ExecContext(ctx, "theproc", &rs)
log.Printf("status=%d", rs)
```

or

```
var rs mssql.ReturnStatus
_, err := db.QueryContext(ctx, "theproc", &rs)
for rows.Next() {
	err = rows.Scan(&val)
}
log.Printf("status=%d", rs)
```

Limitation: ReturnStatus cannot be retrieved using `QueryRow`.

## Parameters

The `sqlserver` driver uses normal MS SQL Server syntax and expects parameters in
the sql query to be in the form of either `@Name` or `@p1` to `@pN` (ordinal position).

```go
db.QueryContext(ctx, `select * from t where ID = @ID and Name = @p2;`, sql.Named("ID", 6), "Bob")
```

### Parameter Types

To pass specific types to the query parameters, say `varchar` or `date` types,
you must convert the types to the type before passing in. The following types
are supported:

 * string -> nvarchar
 * mssql.VarChar -> varchar
 * time.Time -> datetimeoffset or datetime (TDS version dependent)
 * mssql.DateTime1 -> datetime
 * mssql.DateTimeOffset -> datetimeoffset
 * "github.com/golang-sql/civil".Date -> date
 * "github.com/golang-sql/civil".DateTime -> datetime2
 * "github.com/golang-sql/civil".Time -> time
 * mssql.TVP -> Table Value Parameter (TDS version dependent)

## Important Notes

 * [LastInsertId](https://golang.org/pkg/database/sql/#Result.LastInsertId) should
    not be used with this driver (or SQL Server) due to how the TDS protocol
	works. Please use the [OUTPUT Clause](https://docs.microsoft.com/en-us/sql/t-sql/queries/output-clause-transact-sql)
	or add a `select ID = convert(bigint, SCOPE_IDENTITY());` to the end of your
	query (ref [SCOPE_IDENTITY](https://docs.microsoft.com/en-us/sql/t-sql/functions/scope-identity-transact-sql)).
	This will ensure you are getting the correct ID and will prevent a network round trip.
 * [NewConnector](https://godoc.org/github.com/denisenkom/go-mssqldb#NewConnector)
    may be used with [OpenDB](https://golang.org/pkg/database/sql/#OpenDB).
 * [Connector.SessionInitSQL](https://godoc.org/github.com/denisenkom/go-mssqldb#Connector.SessionInitSQL)
	may be set to set any driver specific session settings after the session
	has been reset. If empty the session will still be reset but use the database
	defaults in Go1.10+.

## Features

* Can be used with SQL Server 2005 or newer
* Can be used with Microsoft Azure SQL Database
* Can be used on all go supported platforms (e.g. Linux, Mac OS X and Windows)
* Supports new date/time types: date, time, datetime2, datetimeoffset
* Supports string parameters longer than 8000 characters
* Supports encryption using SSL/TLS
* Supports SQL Server and Windows Authentication
* Supports Single-Sign-On on Windows
* Supports connections to AlwaysOn Availability Group listeners, including re-direction to read-only replicas.
* Supports query notifications

## Tests

`go test` is used for testing. A running instance of MSSQL server is required.
Environment variables are used to pass login information.

Example:

    env SQLSERVER_DSN=sqlserver://user:pass@hostname/instance?database=test1 go test

## Deprecated

These features still exist in the driver, but they are are deprecated.

### Query Parameter Token Replace (driver "mssql")

If you use the driver name "mssql" (rather then "sqlserver") the SQL text
will be loosly parsed and an attempt to extract identifiers using one of

* ?
* ?nnn
* :nnn
* $nnn

will be used. This is not recommended with SQL Server.
There is at least one existing `won't fix` issue with the query parsing.

Use the native "@Name" parameters instead with the "sqlserver" driver name.

## Known Issues

* SQL Server 2008 and 2008 R2 engine cannot handle login records when SSL encryption is not disabled.
To fix SQL Server 2008 R2 issue, install SQL Server 2008 R2 Service Pack 2.
To fix SQL Server 2008 issue, install Microsoft SQL Server 2008 Service Pack 3 and Cumulative update package 3 for SQL Server 2008 SP3.
More information: http://support.microsoft.com/kb/2653857


text:
'use strict';

var directiveName = function() {
    return {
        restrict: 'EA',
        link: function() {

        }
    };
};

directiveName.$inject = [''];
module.exports = directiveName;

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2015-2025 Finsa S.p.A. <finsa@finsa.it>
//
// 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.

using PommaLabs.CodeServices.Common.Portability;

namespace Finsa.CodeServices.Security.Hashing
{
    /// <summary>
    ///   Settings shared among all <see cref="IHasher"/> instances.
    /// </summary>
    public abstract class AbstractHasherSettings
    {
        /// <summary>
        ///   The name of the specific implementation to use.
        /// </summary>
        public string AlgorithmName { get; set; }

        /// <summary>
        ///   The encoding used when extracing bytes from a <see cref="string"/>. Defaults to <see cref="PortableEncoding.UTF8WithoutBOM"/>.
        /// </summary>
        public System.Text.Encoding Encoding { get; set; } = PortableEncoding.UTF8WithoutBOM;
    }
}


text:
layout: data_model
title: GenericRelationshipListType
this_version: 1.0.1
---

  Heads up! These docs are for STIX 1.0.1, which is not the latest version (1.2). View the latest!

GenericRelationshipListTypeSTIX Common Schema

Allows the expression of a list of relationships between STIX components. It's extended throughout STIX and should not be used directly.

      <form id="nav-version">
        <select>

            <option value="1.2" >STIX 1.2</option>

            <option value="1.1.1" >STIX 1.1.1</option>

            <option value="1.1" >STIX 1.1</option>

            <option value="1.0.1" selected="selected">STIX 1.0.1</option>

            <option value="1.0" >STIX 1.0</option>

        </select>
      </form>

Fields

      Field Name
      Type
      Description

      @scopeoptional

          RelationshipScopeEnum

Indicates how multiple related items should be interpreted in this relationship. If "inclusive" is specified, then a single conceptual relationship is being defined between the subject and the collection of objects indicated by the related items (i.e. the relationship is not necessarily relevant for any one particular object being referenced, but for the aggregated collection of objects referenced). If "exclusive" is specified, then multiple relationships are being defined between the specific subject and each object individually.


text:
package com.kodelabs.boilerplate.network.okhttp;

import android.text.TextUtils;

import com.kodelabs.boilerplate.network.listener.DownloadListener;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okio.BufferedSink;
import okio.Okio;

/**
 * OkHttp工具类,封装下载进度监听
 * <br>
 * create on 2017/1/4
 */
public class UpdateHttpUtils {
    private volatile static UpdateHttpUtils mInstance;
    private OkHttpClient mOkHttpClient;

    private UpdateHttpUtils() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        if (UpdateConfig.isDebug()) {
            builder.addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    String outBefore = String.format("发送请求:%s %n [body]:%s %n [headers]:%s", request.url(), request.body(), request.headers());
                    Log.d("OkHttpUtils", outBefore);

                    Response response = chain.proceed(request);
                    String outAfter = String.format("接收返回: %s %n [headers]:%s %n [body]:%s", response.request().url(), response.headers(), response.body());
                    Log.d("OkHttpUtils", outAfter);
                    return response;
                }
            });
        }

        mOkHttpClient = builder.retryOnConnectionFailure(true).build();
    }

    public static UpdateHttpUtils getInstance() {
        if (mInstance == null) {
            synchronized (UpdateHttpUtils.class) {
                if (mInstance == null) {
                    mInstance = new UpdateHttpUtils();
                }
            }
        }
        return mInstance;
    }

    public OkHttpClient getOkHttpClient() {
        return mOkHttpClient;
    }

    public void getRequest(String url, ResponseCallback callback) {
        Request request = new Request.Builder().get().url(url).tag(url).build();
        mOkHttpClient.newCall(request).enqueue(callback);
    }

    public void downloadApp(String url, String filePath, final DownloadListener listener) {
        if (TextUtils.isEmpty(filePath) || TextUtils.isEmpty(url)) {
            if (listener != null) {
                listener.onFail(-1, "下载失败");
            }
            return;
        }
        final File file = new File(filePath);
        if (file.exists()) {
                //String fileMd5 = MD5.getFileMD5(file);
                //if (FileSizeUtil.getFileOrFilesSize(filePath, SIZETYPE_B) == updateBean.getData().getSize() &&
                //        (!TextUtils.isEmpty(fileMd5) && fileMd5.equalsIgnoreCase(updateBean.getData().getMd5()))) {
                //    if (listener != null) {
                //        listener.onSuccess(file);
                //    }
                    //已下载过
                //    return;
                //}
        }
        OkHttpClient client = mOkHttpClient.newBuilder().addInterceptor(new ResponseInterceptor(listener)).build();
        Request request = new Request.Builder().get().url(url).tag(url).build();
        client.newCall(request).enqueue(new ResponseCallback() {
            @Override
            protected void onFail(final int errorCode, final String errorMsg) {
                if (listener != null) {
                    listener.onFail(errorCode, errorMsg);
                }
            }

            @Override
            protected void onSuccess(Response response) throws IOException {
                try {
                    BufferedSink bufferedSink = Okio.buffer(Okio.sink(file));
                    bufferedSink.writeAll(response.body().source());
                    bufferedSink.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (listener != null) {
                    listener.onSuccess(file);
                }
            }
        });
    }

    public void canceRequest(String tag) {
        for (Call call : mOkHttpClient.dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : mOkHttpClient.dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }
}


text:
from keystone import utils
from keystone.common import wsgi
from keystone.logic.types import auth
from keystone.logic.types import fault
import keystone.config as config
from . import get_marker_limit_and_url

class AuthController(wsgi.Controller):
    """Controller for token related operations"""

    def __init__(self, options):
        self.options = options

    @utils.wrap_error
    def authenticate(self, req):
        try:
            auth_with_credentials = utils.get_normalized_request_content(
                auth.AuthWithPasswordCredentials, req)
            result = config.SERVICE.authenticate(auth_with_credentials)
        except fault.BadRequestFault as e1:
            try:
                unscoped = utils.get_normalized_request_content(
                    auth.AuthWithUnscopedToken, req)
                result = config.SERVICE.authenticate_with_unscoped_token(
                    unscoped)
            except fault.BadRequestFault as e2:
                if e1.msg == e2.msg:
                    raise e1
                else:
                    raise fault.BadRequestFault(e1.msg + ' or ' + e2.msg)

        return utils.send_result(200, req, result)

    @utils.wrap_error
    def authenticate_ec2(self, req):
        creds = utils.get_normalized_request_content(auth.Ec2Credentials, req)
        return utils.send_result(200, req,
            config.SERVICE.authenticate_ec2(creds))

    def _validate_token(self, req, token_id):
        """Validates the token, and that it belongs to the specified tenant"""
        belongs_to = req.GET.get('belongsTo')
        return config.SERVICE.validate_token(
            utils.get_auth_token(req), token_id, belongs_to)

    @utils.wrap_error
    def validate_token(self, req, token_id):
        result = self._validate_token(req, token_id)
        return utils.send_result(200, req, result)

    @utils.wrap_error
    def check_token(self, req, token_id):
        """Validates the token, but only returns a status code (HEAD)"""
        self._validate_token(req, token_id)
        return utils.send_result(200, req)

    @utils.wrap_error
    def delete_token(self, req, token_id):
        return utils.send_result(204, req,
            config.SERVICE.revoke_token(utils.get_auth_token(req), token_id))

    @utils.wrap_error
    def endpoints(self, req, token_id):
        marker, limit, url = get_marker_limit_and_url(req)
        return utils.send_result(200, req,
            config.SERVICE.get_endpoints_for_token(
                utils.get_auth_token(req),
                token_id, marker, limit, url))


text:
module VagrantPlugins
  module Docker
    VERSION = "0.0.1.dev"
  end
end


text:
package com.glevel.dungeonhero.models.skills;

import com.glevel.dungeonhero.game.GameConstants;
import com.glevel.dungeonhero.models.Levelable;
import com.glevel.dungeonhero.models.StorableResource;
import com.glevel.dungeonhero.models.effects.Effect;

/**
 * Created by guillaume ON 10/6/14.
 */
public abstract class Skill extends StorableResource implements Levelable {

    private static final long serialVersionUID = -5459063916950986709L;

    private int level;
    private final Effect effect;

    public Skill(String identifier, Effect effect, int level) {
        super(identifier);
        this.level = level;
        this.effect = effect;
    }

    @Override
    public int getLevel() {
        return level;
    }

    public boolean canBeImproved() {
        return level <= GameConstants.SKILL_MAX_LEVEL;
    }

    public Skill improve() {
        level++;
        effect.improve();
        if (effect.getSpecial() != null) {
            effect.getSpecial().improve();
        }
        return this;
    }

    public Effect getEffect() {
        return effect;
    }

    public int getColor() {
        return GameConstants.getLevelColor(level);
    }

}


text:
.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px;}
/* .divider{width:100px;height:0;margin:10px 0;border-bottom:1px solid #eee;} */
/* header */
.header{background:#CC3333;padding:1em;}
.header a{color:#fff;}
.header .divider{color:#fff;margin:0 0.5em;font-size:12px;opacity:0.5;}
/* body */
.container{width:1170px;}
.main{margin:60px auto 0;}
/* body{background:#eee;} */
/* banner */
.banner .hero-unit{background:#fff;padding:60px 0;}
/* .banner .hero-unit .copyright{margin-left:60px;} */
.banner .hero-unit .media-heading{color:#666;}
.banner li{line-height:20px;list-style:none;}
.banner a{color:#3f79d0;font-size:12px;}
.banner a:hover{color:#d80000;text-decoration:none;}
.banner .notice-date,.banner .author{color:#999;font-size:12px;font-style:normal;}
.body{margin:100px auto 10px auto;height:800px;min-height:800px;}
.body .form-register{margin-left:180px;}
.body .form-register .pwd-level{width:56px;}
.body .form-register .file{opacity: 0;filter: alpha(opacity=0);display: block;position: absolute;left: 220px;top: 0;z-index: 200;height: 30px;width: 50px;overflow: hidden;font-size: 8px;}
.body .file_area{position:relative;}
.container .img_logo{width:45px;}

/* pic-show */
.pic-show{margin:10px 0 0 0;}
.pic-show .breadcrumb{background:#f8f8f8;margin:0;}
.pic-show .breadcrumb b{color:#666;}
.pic-show .pics{border: 1px solid #e5e5e5;border-top: 0;}
.pic-show .pic-content{position: relative;margin: 0 35px;width: 1100px;overflow: hidden;}
.pic-show .pic-content .pic-content-all{width:10000px;}
.pic-show .pic-content .pic-content-all .pic-item{float: left;width: 150px;margin-right: 28px;color: #666;}
.pic-item .img{width:150px;height:150px;text-align:center;background:#eee;}
.pic-item .img img{width:auto;height:150px;}
.pic-item p{margin:0;color:#666;text-indent:1em;font-size:12px;}
.pic-scroll{position: relative;padding: 31px 0 35px;}
.pic-scroll .mover-pre {position: absolute;left: 0;top: 50%;margin-top: -35px;}
.pic-scroll .mover-next {position: absolute;right: 0;top: 50%;margin-top: -35px;}
.pic-show .pic-scroll .mover-pre .mover-pre-ico{display: block;width: 30px;height: 71px;background: url(http://p1.qhimg.com/t01427e358904fd399e.png) no-repeat;}
.pic-show .pic-scroll .mover-pre .mover-pre-ico:hover {background-position: -58px 0}
.pic-show .pic-scroll .mover-next .mover-next-ico{display: block;width: 30px;height: 71px;background: url(http://p1.qhimg.com/t01427e358904fd399e.png) no-repeat 0 -81px;}
.pic-show .pic-scroll .mover-next .mover-next-ico:hover {background-position: -58px -81px}

/* footer */
.well.footer{text-align:center;font-size:12px;color:#99999;margin:8px 0;padding:8px;}
.well.footer .breadcrumb{margin-bottom:0;}
.well.footer .breadcrumb a{color:#999;}
.well.footer p{margin-bottom:2px;}
/* login */
.form-horizontal .control-group{margin-bottom:5px;height:50px;}
.tab-pane .ms-tishi {font-size: 0.8em; color: #c5c1c1;}
.container .row .login-out,#login-modal .login-out{width: 390px;background: #fff;border: 1px #afaaaa solid;padding: 0 0 20px; border-radius: 5px;}
.tab-pane .ms-username {width: 50px;font-size: .8em;vertical-align: middle;}
.tab-pane .ms-control {margin-left: 60px;}
.tabbable .ms-personal {width: 95%;margin: 0 auto;}
.tab-pane .ms-forget {float:right;font-size: .8em;}
.tab-pane .ms-forget a:first-child {color: #bababa;}
.login-out .ms-loginwrap {padding-top: 30px;}
.login-out .ms-login-colse {padding: 5px 10px 0 0;font-size: 2em;}
.login-out .tit-color {width: 100%;height: 30px;background: #CC3333; border-radius: 5px 5px 0 0;color: #fff;line-height: 30px;text-indent: 1em;font-weight: bolder;}
.tab-pane .ms-denglu {background: #CC3333;color: #fff;}
.tab-pane .ms-checkbox {margin: 0px 0 0 60px;font-size: .8em;}
.tab-pane .controls .ms-forget {float: none;color: #3F79D0;line-height: 30px;}
.tab-pane .ms-form-action {background: transparent;border: none;padding: 0 0 0 60px;margin: 10px 0 0 0;}
.tab-pane .ms-zhuce {margin-left: 20px;font-size: .8em;}

#login-modal{width:300px;margin:-120px 0 0 -150px;}
#login-modal .login-out{margin-left:0;}
#login-modal .ms-denglu{margin-left:0;}

/* special */
.top{padding:10px 0 15px 0;overflow:hidden;_zoom:1;margin:0 auto}
.top .logo{float:left;position:relative;width:190px;height:72px}
.top .logo .cs_num{position:absolute;right:20px;top:20px;color:#fff;font-size:14px;font-family:Arial,Helvetica,sans-serif}
.picBigTitle{float:left;margin:0 0 0 21px;padding:12px 0 0 21px;border-left:1px solid #ddd;height:60px;font-size:22px;font-family:\5FAE\8F6F\96C5\9ED1;text-align:left}
.picBigTitle span.date{display:inline-block;float:left;font-size:12px;margin:5px 0 0 0;color:#888;background:url(http://img1.cache.netease.com/f2e/ent/comicStrip/images/btns_v2.png) 0 -221px no-repeat;padding:0 0 0 21px;height:16px}
.picBigTitle .titleInfo{font-size:12px;padding:5px 0 0 0;line-height:16px;}
.actions{padding:20px 0 0 0}
.titleInfo .vieworigin:hover{background-position:-147px 3px}
.titleInfo .comment:hover{background-position:-147px -74px}
.actions a{color:#333}
.actions a:hover{color:#000;text-decoration:none}
.titleInfo .vieworigin{background-position:13px 3px}
.titleInfo .comment{background-position:13px -74px}
.actions .share{background-position:13px -155px;padding-right:2px;cursor:pointer}
.titleInfo .vieworigin,.titleInfo .comment,.actions .share,.actions .replay,.actions .photocenter{display:inline-block;float:left;height:25px;line-height:25px;padding:0 10px 0 37px;background-image:url(http://img1.cache.netease.com/f2e/ent/comicStrip/images/btns_v2.png);background-repeat:no-repeat;color:#252525}
.titleInfo .comment span,.titleInfo .comment b{line-height:1}
.titleInfo .comment span,.titleInfo .share span{color:#878787;font-family:Arial,sans-serif;font-weight:bold;font-style:italic;font-size:14px;margin:0}
.titleInfo .comment b,.actions .share b{color:#b92635;font-size:16px;font-style:italic;font-weight:normal;font-family:Georgia,Arial,sans-serif}
.actions .parting-line{float:left;height:22px;width:1px;font-size:0;background:#dadada}

.slider_back{margin-bottom:2em}


text:
from __future__ import unicode_literals

from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
from lugar.models import *
from sorl.thumbnail import ImageField
from smart_selects.db_fields import ChainedForeignKey
from multiselectfield import MultiSelectField

# Create your models here.
STATUS_CHOICES = (
	(1,'ONG'),
	(2,'Cooperativa'),
	(3,'Asociación'),
	(4,'Proyectos'),
	)

class Organizacion(models.Model):
	nombre = models.CharField(max_length=200,verbose_name='Nombre de la Organización')
	siglas = models.CharField(max_length=200)
	fundacion = models.DateField(verbose_name='Año de fundación',null=True,blank=True)
	gerente = models.CharField(max_length=200,verbose_name='Presidente/Administrador',null=True,blank=True)
	status = models.IntegerField(verbose_name='Estatus Legal',choices=STATUS_CHOICES)
	direccion = models.CharField(max_length=300,null=True,blank=True,verbose_name='Dirección fisica de la Organización')
	departamento = models.ForeignKey(Departamento)
	municipio = ChainedForeignKey(
                                Municipio,
                                chained_field="departamento",
                                chained_model_field="departamento",
                                show_all=False, auto_choose=True)
	telefono = models.IntegerField(verbose_name='Número telefónico',null=True,blank=True)
	email = models.EmailField(null=True,blank=True)
	web = models.URLField(verbose_name='Sitio web',null=True,blank=True)
	contacto = models.CharField(max_length=200,verbose_name='Persona de contacto #1',null=True,blank=True)
	contacto_1 = models.CharField(max_length=200,verbose_name='Persona de contacto #2',null=True,blank=True)
	logo = ImageField(upload_to='logo/',null=True,blank=True)
	slug = models.SlugField(editable=False, max_length=450)

	def __unicode__(self):
		return self.siglas

	def save(self, *args, **kwargs):
		if not self.id:
			self.slug = slugify(self.siglas)
		super(Organizacion, self).save(*args, **kwargs)

	class Meta:
		verbose_name = "Organización"
		verbose_name_plural = "Organizaciones"

class EscuelaCampo(models.Model):
	nombre = models.CharField(max_length=200)
	organizacion = models.ForeignKey(Organizacion)

	def __unicode__(self):
		return self.nombre

	class Meta:
		verbose_name = "Escuela de campo"
		verbose_name_plural = "Escuelas de campo"

class EncuestaOrganicacion(models.Model):
		fecha = models.DateField()
		organizacion = models.ForeignKey(Organizacion,related_name='Organizacion')
		anno = models.IntegerField(editable=False)
		usuario = models.ForeignKey(User,related_name='User',editable=False)

		def __unicode__(self):
			return self.organizacion.siglas

		def save(self, *args, **kwargs):
			self.anno = self.fecha.year
			super(EncuestaOrganicacion, self).save(*args, **kwargs)

		class Meta:
			verbose_name = "Encuesta"
			verbose_name_plural = "Encuestas"

SI_NO_CHOICES = (
	(1,'Si'),
	(2,'No'),
	)

TRAMITE_CHOICES = (
	(1,'Si'),
	(2,'No'),
	(3,'Trámite'),
)

class AspectosJuridicos(models.Model):
	tiene_p_juridica = models.IntegerField(choices=TRAMITE_CHOICES,verbose_name='Personería jurídica')
	solvencia_tributaria = models.IntegerField(choices=SI_NO_CHOICES,verbose_name='Cuenta con Registro Tributario Nacional Numérico')
	junta_directiva = models.IntegerField(choices=SI_NO_CHOICES,verbose_name='Junta Directiva certificada')
	mujeres = models.IntegerField(verbose_name='Miembros mujeres JD')
	hombres = models.IntegerField(verbose_name='Miembros hombres JD')
	lista_socios = models.IntegerField(choices=SI_NO_CHOICES,verbose_name='Lista socias/os esta actualizada y certificada')
	numero_registro = models.CharField(max_length=50,verbose_name='Número de Registro de las Cooperativas en CONSUCOOP',null=True,blank=True)
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "II. Aspectos jurídicos"

class ListaMiembros(models.Model):
	nombre = models.CharField(max_length=100,verbose_name='Nombre y apellido')
	cargo = models.CharField(max_length=100)
	telefonos = models.CharField(max_length=100)
	email = models.CharField(max_length=100,blank=True,null=True)
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "Lista de miembros de la junta directiva"

DOCUMENTOS_CHOICES = (
	(1,'Poseen estatutos'),
	(2,'Poseen libro de Actas'),
	(3,'Cuenta con un Reglamento Interno'),
	(4,'Cuenta con un Plan Estratégico'),
	(5,'Cuenta con un Plan Opeativo Anual'),
	(6,'Cuenta con un Plan de Negocios'),
	(7,'Cuentan con Plan de Acopio'),
	)

class Documentacion(models.Model):
	documentos = models.IntegerField(choices=DOCUMENTOS_CHOICES)
	si_no = models.IntegerField(choices=SI_NO_CHOICES,verbose_name='Si/No')
	tramite = models.BooleanField(default=False)
	fecha = models.DateField(verbose_name='Fecha de elaboración o actualización')
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "III. Información sobre documentación"

CUMPLIMIENTO_CHOICES = (
	(1,'10-30%'),
	(2,'31-60%'),
	(3,'61-100%')
)

class NivelCumplimiento(models.Model):
	documentos = models.IntegerField(choices=DOCUMENTOS_CHOICES)
	cumplimiento = models.IntegerField(choices=CUMPLIMIENTO_CHOICES)
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "Nivel de cumplimiento"

DATOS_PROD_CHOICES = (
	(1,'Número de productoras y productores con cacao'),
	(2,'Área total Establecida (Mz)'),
	(3,'Área certificadas (Mz)'),
	(4,'Área convencional (Mz)'),
)

ESTADO_PROD_CHOICES = (
	(1,'Baba'),
	(2,'Seco')
)

TIPO_CACAO_CHOICES = (
	(1,'Convencional'),
	(2,'T1'),
	(3,'T2'),
	(4,'T3'),
	(5,'Ecológico'),
)

CALIDAD_CHOICES = (
	(1,'A'),
	(2,'B'),
	(3,'C'),
)

DESTINO_CHOICES = (
	(1,'Intermediario local'),
	(2,'APROCACAHO'),
	(3,'Chocolats Halba'),
	(4,'Otros'),
)

class ProduccionComercializacion(models.Model):
	fecha = models.DateField()
	cantidad = models.FloatField(verbose_name='Cantidad (lbs)')
	estado = models.IntegerField(choices=ESTADO_PROD_CHOICES)
	tipo_cacao = models.IntegerField(choices=TIPO_CACAO_CHOICES)
	calidad = models.IntegerField(choices=CALIDAD_CHOICES)
	precio = models.FloatField(blank=True,null=True,verbose_name='Precio (Lps)')
	mercado = models.IntegerField(choices=DESTINO_CHOICES)
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "Producción y comercialización cacao"

# class DatosProductivos(models.Model):
# 	pregunta = models.IntegerField(choices=DATOS_PROD_CHOICES)
# 	productores_socios = models.IntegerField()
# 	productoras_socias = models.IntegerField()
# 	productores_no_socios = models.IntegerField()
# 	productoras_no_socias = models.IntegerField()
# 	encuesta = models.ForeignKey(EncuestaOrganicacion)
#
# 	class Meta:
# 		verbose_name_plural = 'IV- Información sobre datos productivos'
#
# DATOS_CHOICES = (
# 	(1,'Rendimiento promedio de cacao en baba por Mz'),
# 	(2,'Rendimiento promedio de cacao seco por Mz'),
# )
#
# class DatosProductivosTabla(models.Model):
# 	pregunta = models.IntegerField(choices=DATOS_CHOICES)
# 	productores_socios = models.FloatField()
# 	productores_no_socios = models.FloatField()
# 	encuesta = models.ForeignKey(EncuestaOrganicacion)
	#
	# class Meta:
	# 	verbose_name_plural = 'IV- Información sobre datos productivos'

INFRAESTRUCTURA_CHOICES = (
	(1,'Centro de Acopio central'),
	(2,'Centro de acopio comunitario'),
	(3,'Secadoras artificiales'),
	# (4,'Planta de procesamiento'),
	(4,'Bodegas'),
	# (6,'Cuartos fríos'),
	(5,'Oficina'),
	# (8,'Medios de Transporte'),
	(6,'Área de fermentado'),
	(7,'Secadoras solares'),
	# (11,'Viveros'),
	)

ESTADO_CHOICES = (
	(1,'Bueno'),
	(2,'Malo'),
	(3,'Regular'),
	)

class Infraestructura(models.Model):
	tipo = models.IntegerField(choices=INFRAESTRUCTURA_CHOICES,verbose_name='Tipo de Infraestructura')
	# cantidad = models.IntegerField()
	capacidad = models.FloatField(verbose_name='Capacidad (qq)')
	anno_construccion = models.DateField(verbose_name='Año de construcción')
	estado = models.IntegerField(choices=ESTADO_CHOICES,verbose_name='Estado de infraestructura')
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "V. Información sobre instalaciones y equipos"

class Transporte(models.Model):
	medio_transporte = models.IntegerField(choices=SI_NO_CHOICES,verbose_name='Cuenta con medios de transporte propio')
	estado = models.IntegerField(choices=ESTADO_CHOICES,verbose_name='Estado mecánico de los medios',null=True,blank=True)
	encuesta = models.ForeignKey(EncuestaOrganicacion)

COMERCIO_CHOICES = (
	(1,'No. de socios que entregaron cacao al acopio'),
	(2,'No. de No socios que entregaron cacao al acopio'),
	(3,'Cantidad de cacao en baba acopiado por la organización'),
)

# class Comercializacion(models.Model):
# 	seleccion = models.IntegerField(choices=COMERCIO_CHOICES)
# 	socias_corriente = models.FloatField(verbose_name="Mujeres (Corriente)")
# 	socios_corriente = models.FloatField(verbose_name="Hombres (Corriente)")
# 	no_socias_corriente = models.FloatField(verbose_name="Mujeres (Fermentado)")
# 	no_socios_corriente = models.FloatField(verbose_name="Hombres (Fermentado)")
# 	encuesta = models.ForeignKey(EncuestaOrganicacion)
#
# 	class Meta:
# 		verbose_name_plural = "VI. Información sobre la Comercialización"
#
# class CacaoComercializado(models.Model):
# 	corriente = models.FloatField()
# 	fermentado = models.FloatField()
# 	encuesta = models.ForeignKey(EncuestaOrganicacion)
#
# 	class Meta:
# 		verbose_name_plural = "Cacao seco comercializado"

CERTIFICACION_CHOICES = (
	(1,'Orgánico'),
	(2,'Comercio Justo'),
	(3,'UTZ'),
)

class CertificacionOrg(models.Model):
	corriente = MultiSelectField(choices=CERTIFICACION_CHOICES)
	fermentado = MultiSelectField(choices=CERTIFICACION_CHOICES)
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "Tipo de certificación"

class DestinoProdCorriente(models.Model):
	destino = models.IntegerField(choices=DESTINO_CHOICES)
	entrega = models.FloatField(verbose_name='% de entrega')
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "Destino de la producción Cacao corriente"

class DestinoProdFermentado(models.Model):
	destino = models.IntegerField(choices=DESTINO_CHOICES)
	entrega = models.FloatField(verbose_name='% de entrega')
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "Destino de la producción Cacao fermentado"

class Financiamiento(models.Model):
	financiamiento = models.IntegerField(choices=SI_NO_CHOICES,verbose_name='Brinda financiamiento a productores de cacao')
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "VII. Información sobre financiamiento"

TIPO_FINANCIAM_CHOICES = (
	(1,'Infraestructura'),
	(2,'Post cosecha'),
	(3,'Riego'),
	(4,'Vivero'),
	(5,'Capital trabajo'),
)

class FinanciamientoProductores(models.Model):
	tipo = models.IntegerField(choices=TIPO_FINANCIAM_CHOICES,verbose_name='Tipo de financiamiento')
	monto = models.FloatField(verbose_name='Monto de financiamiento (Lp) total')
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "Tipo de Financiamiento"

FINANACIA_CHOICES = (
	(1,'La propia organización'),
	(2,'Cooperación Internacional'),
	(3,'Crédito bancario'),
	(4,'Financiamiento del comprador'),
)

class InfoFinanciamiento(models.Model):
	seleccion = models.IntegerField(choices=FINANACIA_CHOICES,verbose_name='¿Quién financia la organización?')
	monto = models.FloatField()
	porcentaje = models.FloatField()
	encuesta = models.ForeignKey(EncuestaOrganicacion)

	class Meta:
		verbose_name_plural = "VIII- Información sobre financiamiento de la organización"


text:
package pt.notificationhubssample;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.microsoft.windowsazure.notifications.NotificationsHandler;

import java.util.Date;

/**
 * Created by Carlos Martins NB20466 on 25/02/2015.
 */
public class PushNotificationHandler extends NotificationsHandler {

    private MainActivity baseActivity;

    public PushNotificationHandler() {
        super();
    }

    @Override
    public void onRegistered(Context context, String gcmRegistrationId) {
        super.onRegistered(context, gcmRegistrationId);
        baseActivity = (MainActivity) context;
        baseActivity.registerForPush(gcmRegistrationId);
    }

    @Override
    public void onReceive(Context context, Bundle bundle) {
        String receivedMessage = bundle.getString("message");
        Log.i("receivedmsg", receivedMessage);

        NotificationManager mNotificationManager = (NotificationManager) baseActivity.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent activityIntent = new Intent(baseActivity, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(baseActivity, 0, activityIntent, PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(baseActivity)
                .setSmallIcon(R.drawable.ic_launcher)
                .setAutoCancel(true)
                .setContentTitle("Notification Hubs Sample")
                .setStyle(new NotificationCompat.BigTextStyle()
                        .bigText(receivedMessage))
                .setContentText(receivedMessage);

        mBuilder.setContentIntent(contentIntent);

        // Generates an unique id for android to display multiple notifications
        int notificationId = (int) (new Date().getTime()/1000);
        mNotificationManager.notify(notificationId, mBuilder.build());
    }
}


text:
#include <cudaCompress/global.h>

namespace cudaCompress {

void convertRGBToYCoCgCPU(byte* pTarget, const byte* pData, int pixelCount);
void convertYCoCgToRGBCPU(byte* pTarget, const byte* pData, int pixelCount);

}

#endif


text:
//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_PhotoelectricPhotoatomicReaction_def.hpp
//! \author Alex Robinson
//! \brief  The photoelectric photoatomic reaction class definition
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_PHOTOELECTRIC_PHOTOATOMIC_REACTION_DEF_HPP
#define MONTE_CARLO_PHOTOELECTRIC_PHOTOATOMIC_REACTION_DEF_HPP

// FRENSIE Includes
#include "Utility_ContractException.hpp"

namespace MonteCarlo{

// Basic constructor
template<typename InterpPolicy, bool processed_cross_section>
PhotoelectricPhotoatomicReaction<InterpPolicy,processed_cross_section>::PhotoelectricPhotoatomicReaction(
		   const Teuchos::ArrayRCP<const double>& incoming_energy_grid,
		   const Teuchos::ArrayRCP<const double>& cross_section,
		   const unsigned threshold_energy_index )
  : StandardPhotoatomicReaction<InterpPolicy,processed_cross_section>(
						       incoming_energy_grid,
						       cross_section,
						       threshold_energy_index )
{
  // Make sure the incoming energy grid is valid
  testPrecondition( incoming_energy_grid.size() > 0 );
  testPrecondition( Utility::Sort::isSortedAscending(
						incoming_energy_grid.begin(),
						incoming_energy_grid.end() ) );
  // Make sure the cross section is valid
  testPrecondition( cross_section.size() > 0 );
  testPrecondition( cross_section.size() ==
		    incoming_energy_grid.size() - threshold_energy_index );
  // Make sure the threshold energy is valid
  testPrecondition( threshold_energy_index < incoming_energy_grid.size() );
}

// Constructor
template<typename InterpPolicy, bool processed_cross_section>
PhotoelectricPhotoatomicReaction<InterpPolicy,processed_cross_section>::PhotoelectricPhotoatomicReaction(
      const Teuchos::ArrayRCP<const double>& incoming_energy_grid,
      const Teuchos::ArrayRCP<const double>& cross_section,
      const unsigned threshold_energy_index,
      const Teuchos::RCP<const Utility::HashBasedGridSearcher>& grid_searcher )
  : StandardPhotoatomicReaction<InterpPolicy,processed_cross_section>(
						       incoming_energy_grid,
						       cross_section,
						       threshold_energy_index,
						       grid_searcher )
{
  // Make sure the incoming energy grid is valid
  testPrecondition( incoming_energy_grid.size() > 0 );
  testPrecondition( Utility::Sort::isSortedAscending(
						incoming_energy_grid.begin(),
						incoming_energy_grid.end() ) );
  // Make sure the cross section is valid
  testPrecondition( cross_section.size() > 0 );
  testPrecondition( cross_section.size() ==
		    incoming_energy_grid.size() - threshold_energy_index );
  // Make sure the threshold energy is valid
  testPrecondition( threshold_energy_index < incoming_energy_grid.size() );
  // Make sure the grid searcher is valid
  testPrecondition( !grid_searcher.is_null() );
}

// Return the number of photons emitted from the rxn at the given energy
/*! \details This does not include photons from atomic relaxation.
 */
template<typename InterpPolicy, bool processed_cross_section>
unsigned PhotoelectricPhotoatomicReaction<InterpPolicy,processed_cross_section>::getNumberOfEmittedPhotons( const double energy ) const
{
  return 0u;
}

// Return the reaction type
template<typename InterpPolicy, bool processed_cross_section>
PhotoatomicReactionType PhotoelectricPhotoatomicReaction<InterpPolicy,processed_cross_section>::getReactionType() const
{
  return TOTAL_PHOTOELECTRIC_PHOTOATOMIC_REACTION;
}

// Simulate the reaction
template<typename InterpPolicy, bool processed_cross_section>
void
PhotoelectricPhotoatomicReaction<InterpPolicy,processed_cross_section>::react(
				     PhotonState& photon,
				     ParticleBank& bank,
				     SubshellType& shell_of_interaction ) const
{
  // End the photon history
  photon.setAsGone();

  // The interaction subshell is not taken into account in this reaction
  shell_of_interaction = UNKNOWN_SUBSHELL;
}

} // end MonteCarlo namespace

#endif // end MONTE_CARLO_PHOTOELECTRIC_PHOTOATOMIC_REACTION_DEF_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_PhotoelectricPhotoatomicReaction_def.hpp
//---------------------------------------------------------------------------//


text:
label: FieldNumericStepper
id: FieldNumericStepper
categorySlug: widget
categoryLabel: Widgety
categoryRank: 1
documentRank: 1

# FieldNumericStepper element

```jade

+FieldNumericStepper()

```


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Editor.CSharp.Completion.FileSystem;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Roslyn.Test.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion
{
    public class LoadDirectiveCompletionProviderTests : AbstractCSharpCompletionProviderTests
    {
        public LoadDirectiveCompletionProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
        {
        }

        internal override CompletionListProvider CreateCompletionProvider()
        {
            return new LoadDirectiveCompletionProvider();
        }

        protected override bool CompareItems(string actualItem, string expectedItem)
        {
            return actualItem.Equals(expectedItem, StringComparison.OrdinalIgnoreCase);
        }

        protected override void VerifyWorker(string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, bool experimental, int? glyph)
        {
            BaseVerifyWorker(code,
                position,
                expectedItemOrNull,
                expectedDescriptionOrNull,
                sourceCodeKind,
                usePreviousCharAsTrigger,
                checkForAbsence,
                glyph);
        }

        private void VerifyItemExistsInScript(string markup, string expected)
        {
            VerifyItemExists(markup, expected, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: false);
        }

        private void VerifyItemIsAbsentInInteractive(string markup, string expected)
        {
            VerifyItemIsAbsent(markup, expected, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: false);
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
        public void NetworkPath()
        {
            VerifyItemExistsInScript(
                @"#load ""$$",
                @"\\");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
        public void NetworkPathAfterInitialBackslash()
        {
            VerifyItemExistsInScript(
                @"#load ""\$$",
                @"\\");
        }

        [WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
        public void UpOneDirectoryNotShownAtRoot()
        {
            // after so many ".." we should be at the root drive an should no longer suggest the parent.  we can determine
            // our current directory depth by counting the number of backslashes present in the current working directory
            // and after that many references to "..", we are at the root.
            int depth = Directory.GetCurrentDirectory().Count(c => c == Path.DirectorySeparatorChar);
            var pathToRoot = string.Concat(Enumerable.Repeat(@"..\", depth));

            VerifyItemExistsInScript(
                @"#load ""$$",
                "..");
            VerifyItemIsAbsentInInteractive(
                @"#load """ + pathToRoot + "$$",
                "..");
        }
    }
}


text:
<?php

namespace Symfony\Component\Cache\Adapter;

use Psr\SimpleCache\CacheInterface;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Component\Cache\ResettableInterface;
use Symfony\Component\Cache\Traits\ProxyTrait;

/**
 * @author Nicolas Grekas <p@tchwork.com>
 */
class SimpleCacheAdapter extends AbstractAdapter implements PruneableInterface, ResettableInterface
{
    use ProxyTrait;

    private $miss;

    public function __construct(CacheInterface $pool, string $namespace = '', int $defaultLifetime = 0)
    {
        parent::__construct($namespace, $defaultLifetime);

        $this->pool = $pool;
        $this->miss = new \stdClass();
    }

    /**
     * {@inheritdoc}
     */
    protected function doFetch(array $ids)
    {
        foreach ($this->pool->getMultiple($ids, $this->miss) as $key => $value) {
            if ($this->miss !== $value) {
                yield $key => $value;
            }
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function doHave($id)
    {
        return $this->pool->has($id);
    }

    /**
     * {@inheritdoc}
     */
    protected function doClear($namespace)
    {
        return $this->pool->clear();
    }

    /**
     * {@inheritdoc}
     */
    protected function doDelete(array $ids)
    {
        return $this->pool->deleteMultiple($ids);
    }

    /**
     * {@inheritdoc}
     */
    protected function doSave(array $values, $lifetime)
    {
        return $this->pool->setMultiple($values, 0 === $lifetime ? null : $lifetime);
    }
}


text:
import PropTypes from "prop-types";
import { Component } from "react";
import { connect } from "react-redux";

import { nav } from "../../../../data/store";
import { reset } from "../../../../deprecated/methods/accounts/browser";

import { Error as Err, Loading } from "../../../../components/@primitives/UI/states";
import Success from "../Success";
import Layout from "./Layout";

class ChangePasswordWithoutData extends Component {

  static propTypes = {
    dispatch: PropTypes.func.isRequired,
  }

  state = {
    current: null,
    newP: null,
    newPDup: null,
    state: "default",
  }

  componentWillMount() {
    this.props.dispatch(nav.setLevel("BASIC_CONTENT"));
  }

  componentWillUnmount() {
    this.props.dispatch(nav.setLevel("TOP"));
  }

  submit = e => {
    e.preventDefault();
    this.setState({ state: "loading" });

    reset(this.state.current, this.state.newP, err => {
      if (err) {
        this.setState({ state: "error", err });
        setTimeout(() => {
          this.setState({ state: "default" });
        }, 5000);
        return;
      }

      this.setState({ state: "success" });

      setTimeout(() => {
        this.setState({ state: "default" });
      }, 5000);
    });
  }

  save = (value, input) => {
    const { id } = input;

    if (id === "newPDup" && this.state.newP && this.state.newP !== value) {
      return false;
    }

    if (id === "newP" && this.state.newPDup && this.state.newPDup !== value) {
      return false;
    }

    this.setState({ [id]: value });

    return true;
  }

  render() {
    const { state, err } = this.state;

    switch (state) {
      case "error":
        return (

            <Err error={err} msg="Looks like there was a problem" />;

        );
      case "loading":
        return (

            <Loading msg="Updating your password..." />;

        );
      case "success":
        return <Success msg="Your password has been updated!" />;
      default:
        return (
          <Layout
            submit={this.submit}
            save={this.save}
            state={this.state}
          />
        );
    }
  }
}

export default connect()(ChangePasswordWithoutData);

export {
  ChangePasswordWithoutData,
};


text:
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Proto;
using Proto.Remote;
using Proto.Cluster;
using Proto.Schedulers.SimpleScheduler;
using DomsProtoUtils;

sealed class Heartbeat : IActor
{
	public static readonly string TypeName = MethodBase.GetCurrentMethod().DeclaringType.Name;
	SimpleScheduler _scheduler = new SimpleScheduler();
	CancellationTokenSource _cancelScheduler;
	PID _channel;

	public Task ReceiveAsync(IContext context)
	{
		PID sender = context.Sender;
		switch (context.Message)
		{
			case Started _:
				System.Console.WriteLine("Hearbeat started, my PID: " + context.Self.ToString());
				// Won't spawn IntChannel with context as it does spawn it as child. But childs are not visible in a cluster, only root nodes
				break;
			case Messages.TargetPID targetMsg:
				_channel = targetMsg.Target;
				System.Console.WriteLine("Hearbeat got target channel PID: " + _channel.ToString());
				Messages.IntValue msg = new Messages.IntValue() { Number = 1 };
				this._scheduler.ScheduleTellRepeatedly(TimeSpan.FromSeconds(1), TimeSpan.FromMilliseconds(250), _channel, msg, out _cancelScheduler);
				break;
		}
		return Actor.Done;
	}
}


text:
This is a command line client Jira API, useful to create new issues.

## Getting Started

*  Install with npm: `npm install -g jira-cl`
*  Run it with `jira [command] [arguments]`

### Initial Setup
When running the first time (or if you didn't create a config file), it will ask you for your Jira host, username, password and if you use 'https' protocol and a new config file will be created in `~/.jira-cli.json` with this data. You can create or modify this file manually.

## Usage

There is only one main command `create` if no command is provided help is shown:

```
  Usage:  [options] [command]

  Commands:

    create [options] [options]     Create a new issue
    open|o [options]               Open issues in browser
    config [options] [command]     Configuration file options
    issue|i [options] [command]    Issue commands
    project|p [options] [command]  Project commands
    version|v <project>            Get project versions

  Options:

    -h, --help     output usage information
    -V, --version  output the version number

```

## License

Copyright (c) 2016 Behuti
Licensed under the MIT license.


text:
package org.droidparts.net.image;

import android.graphics.Bitmap;
import android.util.Pair;

public abstract class AbstractImageReshaper implements ImageReshaper {

	// slow, supports transparency
	public static final Pair<Bitmap.CompressFormat, Integer> PNG = Pair.create(Bitmap.CompressFormat.PNG, 100);
	// fast
	public static final Pair<Bitmap.CompressFormat, Integer> JPEG = Pair.create(Bitmap.CompressFormat.JPEG, 80);

	@Override
	public Pair<Bitmap.CompressFormat, Integer> getCacheFormat(String mimeType) {
		if ("image/png".equals(mimeType)) {
			return PNG;
		} else {
			return JPEG;
		}
	}

	@Override
	public Bitmap.Config getBitmapConfig() {
		return Bitmap.Config.ARGB_8888;
	}

}


text:
from django.contrib.auth.models import User
from django.test.utils import override_settings

from funfactory.urlresolvers import reverse
from mock import patch
from nose.tools import eq_, nottest
from product_details import product_details
from pyquery import PyQuery as pq

from common import browserid_mock
from common.tests import ESTestCase, user
from groups.models import Group

from ..helpers import validate_username
from ..models import UserProfile, UsernameBlacklist

Group.objects.get_or_create(name='staff', system=True)
COUNTRIES = product_details.get_regions('en-US')

class RegistrationTest(ESTestCase):
    """Tests registration."""
    # Assertion doesn't matter since we monkey patched it for testing
    fake_assertion = 'mrfusionsomereallylongstring'

    def test_validate_username(self):
        """Test validate_username helper."""
        valid_usernames = ['giorgos', 'aakash',
                           'nikos', 'bat-man']

        invalid_usernames = ['administrator', 'test',
                             'no-reply', 'noreply', 'spam']

        for name in valid_usernames:
            self.assertTrue(validate_username(name),
                            'Username: %s did not pass test' % name)

        for name in invalid_usernames:
            self.assertFalse(validate_username(name),
                            'Username: %s did not pass test' % name)

    def test_mozillacom_registration(self):
        """Verify @mozilla.com users are auto-vouched and marked "staff"."""

        d = dict(assertion=self.fake_assertion)
        with browserid_mock.mock_browserid('mrfusion@mozilla.com'):
            self.client.post(reverse('browserid_verify'), d, follow=True)

        d = dict(username='ad',
                 email='mrfusion@mozilla.com',
                 full_name='Akaaaaaaash Desaaaaaaai',
                 optin=True)
        with browserid_mock.mock_browserid('mrfusion@mozilla.com'):
            r = self.client.post(reverse('register'), d, follow=True)

        doc = pq(r.content)

        assert r.context['user'].get_profile().is_vouched, (
                "Moz.com should be auto-vouched")

        assert not doc('#pending-approval'), (
                'Moz.com profile page should not having pending vouch div.')

        assert r.context['user'].get_profile().groups.filter(name='staff'), (
                'Moz.com should belong to the "staff" group.')

    def test_plus_signs(self):
        email = 'mrfusion+dotcom@mozilla.com'
        d = dict(assertion=self.fake_assertion)
        with browserid_mock.mock_browserid(email):
            self.client.post(reverse('browserid_verify'), d, follow=True)

        d = dict(username='ad',
                 email=email,
                 full_name='Akaaaaaaash Desaaaaaaai',
                 optin=True)
        with browserid_mock.mock_browserid(email):
            self.client.post(reverse('register'), d, follow=True)

        assert User.objects.filter(email=d['email'])

    def test_username(self):
        """Test that we can submit a perfectly cromulent username.

        We verify that /:username then works as well.

        """
        email = 'mrfusion+dotcom@mozilla.com'
        d = dict(assertion=self.fake_assertion)
        with browserid_mock.mock_browserid(email):
            self.client.post(reverse('browserid_verify'), d, follow=True)
        d = dict(email=email,
                 username='mrfusion',
                 full_name='Akaaaaaaash Desaaaaaaai',
                 optin=True)
        with browserid_mock.mock_browserid(email):
            r = self.client.post(reverse('register'), d)
        eq_(r.status_code, 302, "Problems if we didn't redirect...")
        u = User.objects.filter(email=d['email'])[0]
        eq_(u.username, 'mrfusion', "Username didn't get set.")

        r = self.mozillian_client.get(reverse('profile', args=['mrfusion']),
                                              follow=True)
        eq_(r.status_code, 200)
        eq_(r.context['profile'].user_id, u.id)

    def test_username_characters(self):
        """Verify usernames can have digits/symbols, but nothing too
        insane.

        """
        email = 'mrfusion+dotcom@mozilla.com'
        username = 'mr.fu+s_i-on@246'
        d = dict(assertion=self.fake_assertion)
        with browserid_mock.mock_browserid(email):
            self.client.post(reverse('browserid_verify'), d, follow=True)

        d = dict(email=email,
                 username=username,
                 full_name='Akaaaaaaash Desaaaaaaai',
                 optin=True)
        with browserid_mock.mock_browserid(email):
            r = self.client.post(reverse('register'), d)
        eq_(r.status_code, 302, (
                'Registration flow should finish with a redirect.'))
        u = User.objects.get(email=d['email'])
        eq_(u.username, username, 'Username should be set to "%s".' % username)

        r = self.mozillian_client.get(reverse('profile', args=[username]),
                                              follow=True)
        eq_(r.status_code, 200)
        eq_(r.context['profile'].user_id, u.id)

        # Now test a username with even weirder characters that we don't allow.
        bad_user_email = 'mrfusion+coolbeans@mozilla.com'
        bad_username = 'mr.we*rd'
        d = dict(assertion=self.fake_assertion)
        with browserid_mock.mock_browserid(email):
            self.client.post(reverse('browserid_verify'), d, follow=True)

        d = dict(email=bad_user_email,
                 username=bad_username,
                 full_name='Akaaaaaaash Desaaaaaaai',
                 optin=True)
        with browserid_mock.mock_browserid(email):
            r = self.client.post(reverse('register'), d)
        eq_(r.status_code, 302, (
                'Registration flow should fail; username is bad.'))
        assert not User.objects.filter(email=d['email']), (
                "User shouldn't exist; username was bad.")

    def test_bad_username(self):
        """'about' is a terrible username, as are its silly friends.

        Let's make some stop words *and* analyze the routing system,
        whenever someone sets their username and verify that they can't
        be 'about' or 'help' or anything that is in use.
        """
        email = 'mrfusion+dotcom@mozilla.com'
        badnames = UsernameBlacklist.objects.all().values_list('value',
                                                               flat=True)
        # BrowserID needs an assertion not to be whiney
        d = dict(assertion=self.fake_assertion)
        with browserid_mock.mock_browserid(email):
            self.client.post(reverse('browserid_verify'), d, follow=True)

        for name in badnames:
            d = dict(email=email,
                     username=name,
                     full_name='Akaaaaaaash Desaaaaaaai',
                     optin=True)
            with browserid_mock.mock_browserid(email):
                r = self.client.post(reverse('register'), d)

            eq_(r.status_code, 200,
                'This form should fail for "%s", and say so.' % name)
            assert r.context['user_form'].errors, (
                "Didn't raise errors for %s" % name)

    def test_nickname_changes_before_vouch(self):
        """Notify pre-vouched users of URL change from nickname
        changes.

        See: https://bugzilla.mozilla.org/show_bug.cgi?id=736556

        """
        d = dict(assertion=self.fake_assertion)
        email = 'soy@latte.net'
        with browserid_mock.mock_browserid(email):
            self.client.post(reverse('browserid_verify'), d, follow=True)

        # Note: No username supplied.
        d = dict(email=email,
                 full_name='Tofu Matt',
                 optin=True)
        with browserid_mock.mock_browserid(email):
            r = self.client.post(reverse('register'), d, follow=True)

        assert r.context['user'].id, 'User should be created'
        assert not r.context['user'].get_profile().is_vouched, (
                'User should not be vouched')

        d['username'] = 'foobar'
        r = self.client.post(reverse('profile.edit'), d, follow=True)
        assert 'You changed your username;' in r.content, (
                'User should know that changing their username changes '
                'their URL.')

    def test_repeat_username(self):
        """Verify one cannot repeat email adresses."""
        register = dict(username='repeatedun',
                        full_name='Akaaaaaaash Desaaaaaaai',
                        optin=True)

        # Create first user
        email1 = 'mRfUsIoN@mozilla.com'
        register.update(email=email1)
        d = dict(assertion=self.fake_assertion)
        with browserid_mock.mock_browserid(email1):
            self.client.post(reverse('browserid_verify'), d, follow=True)

        with browserid_mock.mock_browserid(email1):
            self.client.post(reverse('register'), register, follow=True)

        self.client.logout()
        # Create a different user
        email2 = 'coldfusion@gmail.com'
        register.update(email=email2)
        with browserid_mock.mock_browserid(email2):
            self.client.post(reverse('browserid_verify'), d, follow=True)

        with browserid_mock.mock_browserid(email2):
            r = self.client.post(reverse('register'), register, follow=True)

        # Make sure we can't use the same username twice
        assert r.context['user_form'].errors, "Form should throw errors."

class TestThingsForPeople(ESTestCase):
    """Verify that the wrong users don't see things."""

    def test_searchbox(self):
        url = reverse('home')
        r = self.client.get(url)
        doc = pq(r.content)
        assert not doc('input[type=text]')
        r = self.pending_client.get(url)
        doc = pq(r.content)
        assert not doc('input[type=text]')
        r = self.mozillian_client.get(url)
        doc = pq(r.content)
        assert doc('input[type=text]')

    def test_invitelink(self):
        url = reverse('home')
        r = self.client.get(url)
        doc = pq(r.content)
        assert not doc('a#invite')
        r = self.pending_client.get(url)
        doc = pq(r.content)
        assert not doc('a#invite'), "Unvouched can't invite."
        r = self.mozillian_client.get(url)
        doc = pq(r.content)
        assert doc('a#invite')

    def test_register_redirects_for_authenticated_users(self):
        """Ensure only anonymous users can register an account."""
        r = self.client.get(reverse('home'))
        self.assertTrue(200 == r.status_code,
                        'Anonymous users can access the homepage to '
                        'begin registration flow')

        r = self.mozillian_client.get(reverse('register'))
        eq_(302, r.status_code,
            'Authenticated users are redirected from registration.')

    def test_vouchlink(self):
        """No vouch link when PENDING looks at PENDING."""
        url = reverse('profile', args=['pending'])
        r = self.mozillian_client.get(url)
        doc = pq(r.content)
        assert doc('#vouch-form button')
        r = self.pending_client.get(url)
        doc = pq(r.content)
        errmsg = 'Self vouching... silliness.'
        assert not doc('#vouch-form button'), errmsg
        assert 'Vouch for me' not in r.content, errmsg

    @patch('users.admin.index_all_profiles')
    def test_es_index_admin_view(self, mock_obj):
        """Test that admin:user_index_profiles work fires a re-index."""
        self.mozillian.is_superuser = True
        self.mozillian.is_staff = True
        self.mozillian.save()
        url = reverse('admin:users_index_profiles')
        self.client.login(email=self.mozillian.email)
        self.client.get(url)
        mock_obj.assert_any_call()

class VouchTest(ESTestCase):

    # TODO
    # Mark this as nottest until we decide the policy in search
    # page. Then fix accordingly.
    @nottest
    def test_vouch_method(self):
        """Test UserProfile.vouch()

        Assert that a previously unvouched user shows up as unvouched
        in the database.

        Assert that when vouched they are listed as vouched.
        """
        vouchee = self.mozillian.get_profile()
        profile = self.pending.get_profile()
        assert not profile.is_vouched, 'User should not yet be vouched.'
        r = self.mozillian_client.get(reverse('search'),
                                      {'q': self.pending.email})
        assert 'Non-Vouched' in r.content, (
                'User should not appear as a Mozillian in search.')

        profile.vouch(vouchee)
        profile = UserProfile.objects.get(pk=profile.pk)
        assert profile.is_vouched, 'User should be marked as vouched.'

        r = self.mozillian_client.get(reverse('profile', args=['pending']))
        eq_(r.status_code, 200)
        doc = pq(r.content)
        assert 'Mozillian Profile' in r.content, (
                'User should appear as having a vouched profile.')
        assert not 'Pending Profile' in r.content, (
                'User should not appear as having a pending profile.')
        assert not doc('#pending-approval'), (
                'Pending profile div should not be in DOM.')

        # Make sure the user appears vouched in search results
        r = self.mozillian_client.get(reverse('search'),
                                      {'q': self.pending.email})
        assert 'Mozillian' in r.content, (
                'User should appear as a Mozillian in search.')

class TestUser(ESTestCase):
    """Test User functionality."""

    def test_userprofile(self):
        u = user()

        UserProfile.objects.all().delete()

        # Somehow the User lacks a UserProfile
        # Note that u.get_profile() caches in memory.
        self.assertRaises(UserProfile.DoesNotExist,
                          lambda: u.userprofile)

        # Sign in
        with browserid_mock.mock_browserid(u.email):
            d = dict(assertion='qwer')
            self.client.post(reverse('browserid_verify'), d, follow=True)

        # Good to go
        assert u.get_profile()

    def test_blank_ircname(self):
        username = 'thisisatest'
        email = 'test@example.com'
        register = dict(username=username,
                        full_name='David Teststhings',
                        optin=True)
        d = {'assertion': 'rarrr'}

        with browserid_mock.mock_browserid(email):
            self.client.post(reverse('browserid_verify'), d, follow=True)
            self.client.post(reverse('register'), register, follow=True)

        u = User.objects.filter(email=email)[0]
        p = u.get_profile()
        p.ircname = ''
        eq_(p.ircname, '', 'We need to allow IRCname to be blank')

class TestMigrateRegistration(ESTestCase):
        """Test funky behavior of flee ldap."""
        email = 'robot1337@domain.com'

        def test_login(self):
            """Given an invite_url go to it and redeem an invite."""
            # Lettuce make sure we have a clean slate

            info = dict(full_name='Akaaaaaaash Desaaaaaaai', optin=True)
            self.client.logout()
            u = User.objects.create(username='robot1337', email=self.email)
            p = u.get_profile()

            p.full_name = info['full_name']
            u.save()
            p.save()

            # BrowserID needs an assertion not to be whiney
            d = dict(assertion='tofu')
            with browserid_mock.mock_browserid(self.email):
                r = self.client.post(reverse('browserid_verify'),
                                     d, follow=True)

            eq_(r.status_code, 200)

            # Now let's register
            with browserid_mock.mock_browserid(self.email):
                r = self.client.post(reverse('register'), info, follow=True)

            eq_(r.status_code, 200)

@override_settings(AUTO_VOUCH_DOMAINS=['mozilla.com'])
class AutoVouchTests(ESTestCase):

    def test_only_autovouch_in_staff(self):
        """Restrict the staff group to emails in AUTO_VOUCH_DOMAINS."""
        staff = Group.objects.get_or_create(name='staff', system=True)[0]
        staff_user = user(email='abcd@mozilla.com')
        staff_profile = staff_user.get_profile()
        staff_profile.save()
        assert staff in staff_profile.groups.all(), (
            'Auto-vouched email in staff group by default.')

        staff_profile.groups.remove(staff)
        staff_profile.save()
        assert staff in staff_profile.groups.all(), (
            'Auto-vouched email cannot be removed from staff group.')

        community_user = user()
        community_profile = community_user.get_profile()
        community_profile.save()
        assert staff not in community_profile.groups.all(), (
            'Non-auto-vouched email not automatically in staff group.')

        community_profile.groups.add(staff)
        community_profile.save()
        assert staff not in community_profile.groups.all(), (
            'Non-auto-vouched email cannot be added to staff group.')

    def test_autovouch_email(self):
        """Users with emails in AUTO_VOUCH_DOMAINS should be vouched."""
        auto_user = user(email='abcd@mozilla.com')
        auto_profile = auto_user.get_profile()
        auto_profile.save()
        assert auto_profile.is_vouched, 'Profile should be vouched.'
        assert auto_profile.vouched_by is None, (
            'Profile should not have a voucher.')

        non_auto_user = user()
        non_auto_profile = non_auto_user.get_profile()
        non_auto_profile.save()
        assert not non_auto_profile.is_vouched, (
            'Profile should not be vouched.')

@override_settings(
    AUTHENTICATION_BACKENDS=['django.contrib.auth.backends.ModelBackend'])
class UsernameRedirectionMiddlewareTests(ESTestCase):
    # Assertion doesn't matter since we monkey patched it for testing
    def test_username_redirection_middleware(self):
        """Test the username redirection middleware."""

        auto_user = user(username='lalala')
        self.client.login(username=auto_user.username, password='testpass')
        response = self.client.get('/%s' % auto_user.username, follow=True)
        self.assertTemplateUsed(response, 'phonebook/profile.html')

        response = self.client.get('/%s' % 'invaliduser', follow=True)
        self.assertTemplateUsed(response, '404.html')

class SearchTests(ESTestCase):

    def setUp(self):
        self.data = {'country': 'us',
                     'region': 'California',
                     'city': 'Mountain View',
                     'ircname': 'hax0r',
                     'bio': 'I love ice cream. I code. I tweet.',
                     'website': 'http://www.example.com',
                     'full_name': 'Nikos Koukos'}
        self.auto_user = user()
        self.up = self.auto_user.userprofile
        for key, value in self.data.iteritems():
            setattr(self.up, key, value)
        self.up.save()

    def test_search_generic(self):
        for key, value in self.data.iteritems():
            if key == 'country':
                value = COUNTRIES[value]
            results = UserProfile.search(value)
            self.assertEqual(len(results), 1)

        results = UserProfile.search(self.up.full_name)
        self.assertEqual(len(results), 1)

        results = UserProfile.search('mountain')
        self.assertEqual(len(results), 0)

        results = UserProfile.search(self.up.full_name[:2])
        self.assertEqual(len(results), 1)

        results = UserProfile.search(
            self.up.bio.split(' ')[3])
        self.assertEqual(len(results), 1)


text:
print "Get me some text"
user_input = gets.chomp
user_input.downcase!

user_input.gsub! /s/, "th"


text:
package nl.knaw.dans.common.wicket.components.upload;

/**
 * @author lobo
 * This class contains the information concerning the upload process. It is being held
 * by an UploadProcess class.
 */
public class UploadStatus
{
    private Integer percentComplete = 0;

    private boolean error = false;

    private boolean finished = false;

    private String message;

    public UploadStatus(String message)
    {
        this.message = message;
        percentComplete = 0;
    }

    public boolean isError()
    {
        return error;
    }

    public void setError(boolean error)
    {
        this.error = error;
    }

    public void setError(String errorMessage)
    {
        this.error = true;
        this.message = errorMessage;
    }

    public String getMessage()
    {
        return message;
    }

    public void setMessage(String message)
    {
        this.message = message;
    }

    public Integer getPercentComplete()
    {
        return percentComplete;
    }

    public void setPercentComplete(Integer percentComplete)
    {
        this.percentComplete = percentComplete;
    }

    public boolean isFinished()
    {
        return finished;
    }

    public void setFinished(boolean finished)
    {
        this.finished = finished;
    }
}


text:
class openweather:
    '''
    Uma classe simples que utiliza a api do openweathermap
    para fazer requisições de tempo
    https://openweathermap.org/api
    '''
    def __init__(self, chave, cidade):
        self.cidade = cidade
        self.chave = chave
        self.site = 'http://api.openweathermap.org/data/2.5/weather?id='
        self.update()

    def update(self):
        url = self.site + self.cidade + '&appid=' + self.chave
        resposta = urllib2.urlopen(url)
        dados_resposta = resposta.read()
        dados = json.loads(dados_resposta)
        self.dados = dados

    def temperatura(self):
        return self.dados['main']['temp'] - 273.1

    def pressao(self):
        return self.dados['main']['pressure']


text:
<?php
    require_once 'lib/headers.php';
    require_once 'lib/session.php';
    session_destroy();
    setcookie("authSecret", "", 1, "/", "", false, true);
?>
<!DOCTYPE html>

        <title>PDNS Manager</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="include/bootstrap/css/bootstrap.min.css" rel="stylesheet">
        <link href="include/bootstrap/css/bootstrap-theme.min.css" rel="stylesheet">
        <link href="include/custom.css" rel="stylesheet">

                PDNS Manager

You have been logged out successfully!

                    Login again


text:
namespace DLaB.Xrm.Entities
{

	[System.Runtime.Serialization.DataContractAttribute()]
	[System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.0.0.9154")]
	public enum NavigationSetting_SettingType
	{

		[System.Runtime.Serialization.EnumMemberAttribute()]
		AdvancedSetup = 0,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		AdvancedSetupSummary = 2,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		BasicSetup = 1,

		[System.Runtime.Serialization.EnumMemberAttribute()]
		BasicSetupSummary = 3,
	}
}


text:
j2 /templates/nginx-default.conf.j2 > /etc/nginx/conf.d/default.conf
j2 /templates/supervisord.conf.j2 > /etc/supervisor/conf.d/supervisord.conf
j2 /templates/msmtprc.j2 > /etc/msmtprc

umask 002

chown -R www-data:www-data /var/www
chmod -R g=u /var/www

exec "$@"


text:
import pump from 'pump';
import gutil from 'gulp-util';
import babel from 'gulp-babel';
import sourcemaps from 'gulp-sourcemaps';
import uglify from 'gulp-uglify';
import less from 'gulp-less';
import postcss from 'gulp-postcss';
import autoprefixer from 'autoprefixer';
import cleanCSS from 'gulp-clean-css';
import rename from 'gulp-rename';

import { JS_FILES, CSS_FILES, LESS_FILES, IMAGE_FILES, FONT_FILES } from './constant';

export default (gulp, options) => {
  let { distDir } = options;

  gulp.task('build:dist', [
    'build:dist:js', 'build:dist:style', 'build:dist:resource'
  ]).desc('build project as distribution');

  gulp.task('build:dist:js', (cb) => {
    pump([
      gulp.src(JS_FILES),
      sourcemaps.init(),
      babel(options.babel),
      gulp.dest(distDir),
      uglify(),
      rename({ suffix: '.min' }),
      sourcemaps.write('.'),
      gulp.dest(distDir),
    ], cb);
  });

  gulp.task('build:dist:style', [
    'build:dist:css', 'build:dist:less'
  ]);

  gulp.task('build:dist:css', (cb) => {
    pump([
      gulp.src(CSS_FILES),
      postcss([autoprefixer()]),
      gulp.dest(distDir),
      cleanCSS({compatibility: 'ie8'}),
      rename({ suffix: '.min' }),
      gulp.dest(distDir),
    ], cb);
  });

  gulp.task('build:dist:less', (cb) => {
    pump([
      gulp.src(LESS_FILES),
      less(),
      postcss([autoprefixer()]),
      gulp.dest(distDir),
      cleanCSS({compatibility: 'ie8'}),
      rename({ suffix: '.min' }),
      gulp.dest(distDir),
    ], cb);
  });

  gulp.task('build:dist:resource', [
    'build:dist:image', 'build:dist:font'
  ]);

  gulp.task('build:dist:image', (cb) => {
    try {
      let imagemin = require('gulp-imagemin');
      pump([
        gulp.src(IMAGE_FILES),
        imagemin(),
        gulp.dest(distDir),
      ], cb);
    } catch (e) {
      pump([
        gulp.src(IMAGE_FILES),
        gulp.dest(distDir),
      ], cb);
    }
  });

  gulp.task('build:dist:font', (cb) => {
    pump([
      gulp.src(FONT_FILES),
      gulp.dest(distDir),
    ], cb);
  });
}


text:
package com.netflix.spinnaker.clouddriver.kubernetes.provider;

import com.netflix.spinnaker.clouddriver.model.HealthState;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
public class KubernetesModelUtil {
  public static long translateTime(String time) {
    try {
      return StringUtils.isNotEmpty(time) ? (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX").parse(time)).getTime() : 0;
    } catch (ParseException e) {
      log.error("Failed to parse kubernetes timestamp", e);
      return 0;
    }
  }

  public static HealthState getHealthState(List<Map<String, String>> health) {
    return someUpRemainingUnknown(health) ? HealthState.Up :
        someSucceededRemainingUnknown(health) ? HealthState.Succeeded :
            anyStarting(health) ? HealthState.Starting :
                anyDown(health) ? HealthState.Down :
                    anyFailed(health) ? HealthState.Failed :
                        anyOutOfService(health) ? HealthState.OutOfService :
                            HealthState.Unknown;
  }

  private static boolean stateEquals(Map<String, String> health, HealthState state) {
    String healthState = health.get("state");
    return healthState != null && healthState.equals(state.name());
  }

  private static boolean someUpRemainingUnknown(List<Map<String, String>> healthsList) {
    List<Map<String, String>> knownHealthList = healthsList.stream()
        .filter(h -> !stateEquals(h, HealthState.Unknown))
        .collect(Collectors.toList());

    return !knownHealthList.isEmpty() && knownHealthList.stream().allMatch(h -> stateEquals(h, HealthState.Up));
  }

  private static boolean someSucceededRemainingUnknown(List<Map<String, String>> healthsList) {
    List<Map<String, String>> knownHealthList = healthsList.stream()
        .filter(h -> !stateEquals(h, HealthState.Unknown))
        .collect(Collectors.toList());

    return !knownHealthList.isEmpty() && knownHealthList.stream().allMatch(h -> stateEquals(h, HealthState.Succeeded));
  }

  private static boolean anyDown(List<Map<String, String>> healthsList) {
    return healthsList.stream().anyMatch(h -> stateEquals(h, HealthState.Down));
  }

  private static boolean anyStarting(List<Map<String, String>> healthsList) {
    return healthsList.stream().anyMatch(h -> stateEquals(h, HealthState.Starting));
  }

  private static boolean anyFailed(List<Map<String, String>> healthsList) {
    return healthsList.stream().anyMatch(h -> stateEquals(h, HealthState.Failed));
  }

  private static boolean anyOutOfService(List<Map<String, String>> healthsList) {
    return healthsList.stream().anyMatch(h -> stateEquals(h, HealthState.OutOfService));
  }
}


text:
package org.deeplearning4j.util;

import java.io.DataInputStream;
import java.io.IOException;

public class ByteUtil {
	private ByteUtil() {
	}

	/**
	 *
	 *
	 * @param dis
	 * @return
	 * @throws IOException
	 */
	public static String readString(DataInputStream dis,int maxSize) throws IOException {
		byte[] bytes = new byte[maxSize];
		byte b = dis.readByte();
		int i = -1;
		StringBuilder sb = new StringBuilder();
		while (b != 32 && b != 10) {
			i++;
			bytes[i] = b;
			b = dis.readByte();
			if (i == 49) {
				sb.append(new String(bytes));
				i = -1;
				bytes = new byte[maxSize];
			}
		}
		sb.append(new String(bytes, 0, i + 1));
		return sb.toString();
	}

}