text:
<?php

namespace WindowsAzure\Common\Internal;
use WindowsAzure\Common\Internal\Resources;

/**
 * Represents the settings used to sign and access a request against the service
 * management. For more information about service management connection strings check
 * this page: http://msdn.microsoft.com/en-us/library/windowsazure/gg466228.aspx
 *
 * @category  Microsoft
 * @package   WindowsAzure\Common\Internal
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.0_2014-01
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
class MediaServicesSettings extends ServiceSettings
{
    /**
     * @var string
     */
    private $_accountName;

    /**
     * @var string
     */
    private $_accessKey;

    /**
     * @var string
     */
    private $_endpointUri;

    /**
     * @var string
     */
    private $_oauthEndpointUri;

    /**
     * Validator for the MediaServicesAccountName setting. It has to be provided.
     *
     * @var array
     */
    private static $_accountNameSetting;

    /**
     * Validator for the MediaServicesAccessKey setting. It has to be provided.
     *
     * @var array
     */
    private static $_accessKeySetting;

    /**
     * Validator for the MediaServicesEndpoint setting. Must be a valid Uri.
     *
     * @var array
     */
    private static $_endpointUriSetting;

    /**
     * Validator for the MediaServicesOAuthEndpoint setting. Must be a valid Uri.
     *
     * @var array
     */
    private static $_oauthEndpointUriSetting;

    /**
     * @var boolean
     */
    protected static $isInitialized = false;

    /**
     * Holds the expected setting keys.
     *
     * @var array
     */
    protected static $validSettingKeys = array();

    /**
     * Initializes static members of the class.
     *
     * @return none
     */
    protected static function init()
    {
        self::$_endpointUriSetting = self::settingWithFunc(
            Resources::MEDIA_SERVICES_ENDPOINT_URI_NAME,
            Validate::getIsValidUri()
        );

        self::$_oauthEndpointUriSetting = self::settingWithFunc(
            Resources::MEDIA_SERVICES_OAUTH_ENDPOINT_URI_NAME,
            Validate::getIsValidUri()
        );

        self::$_accountNameSetting = self::setting(
            Resources::MEDIA_SERVICES_ACCOUNT_NAME
        );

        self::$_accessKeySetting = self::setting(
            Resources::MEDIA_SERVICES_ACCESS_KEY
        );

        self::$validSettingKeys[] = Resources::MEDIA_SERVICES_ENDPOINT_URI_NAME;
        self::$validSettingKeys[] = Resources::MEDIA_SERVICES_OAUTH_ENDPOINT_URI_NAME;
        self::$validSettingKeys[] = Resources::MEDIA_SERVICES_ACCOUNT_NAME;
        self::$validSettingKeys[] = Resources::MEDIA_SERVICES_ACCESS_KEY;
    }

    /**
     * Creates new media services settings instance.
     *
     * @param string $accountName      The user provided account name.
     * @param string $accessKey        The user provided primary access key
     * @param string $endpointUri      The service management endpoint uri.
     * @param string $oauthEndpointUri The OAuth service endpoint uri.
     */
    public function __construct(
        $accountName,
        $accessKey,
        $endpointUri = null,
        $oauthEndpointUri = null)
    {
        Validate::notNullOrEmpty($accountName, 'accountName');
        Validate::notNullOrEmpty($accessKey, 'accountKey');
        Validate::isString($accountName, 'accountName');
        Validate::isString($accessKey, 'accountKey');

        if ($endpointUri != null) {
            Validate::isValidUri($endpointUri);
        } else {
            $endpointUri = Resources::MEDIA_SERVICES_URL;
        }

        if ($oauthEndpointUri != null) {
            Validate::isValidUri($oauthEndpointUri);
        } else {
            $oauthEndpointUri = Resources::MEDIA_SERVICES_OAUTH_URL;
        }

        $this->_accountName      = $accountName;
        $this->_accessKey        = $accessKey;
        $this->_endpointUri      = $endpointUri;
        $this->_oauthEndpointUri = $oauthEndpointUri;
    }

    /**
     * Creates a MediaServicesSettings object from the given connection string.
     *
     * @param string $connectionString The media services settings connection string.
     *
     * @return MediaServicesSettings
     */
    public static function createFromConnectionString($connectionString)
    {
        $tokenizedSettings = self::parseAndValidateKeys($connectionString);

        $matchedSpecs = self::matchedSpecification(
            $tokenizedSettings,
            self::allRequired(
                self::$_accountNameSetting,
                self::$_accessKeySetting
            ),
            self::optional(
                self::$_endpointUriSetting,
                self::$_oauthEndpointUriSetting
            )
        );
        if ($matchedSpecs) {
            $endpointUri = Utilities::tryGetValueInsensitive(
                Resources::MEDIA_SERVICES_ENDPOINT_URI_NAME,
                $tokenizedSettings,
                Resources::MEDIA_SERVICES_URL
            );

            $oauthEndpointUri = Utilities::tryGetValueInsensitive(
                Resources::MEDIA_SERVICES_OAUTH_ENDPOINT_URI_NAME,
                $tokenizedSettings,
                Resources::MEDIA_SERVICES_OAUTH_URL
            );

            $accountName = Utilities::tryGetValueInsensitive(
                Resources::MEDIA_SERVICES_ACCOUNT_NAME,
                $tokenizedSettings
            );

            $accessKey = Utilities::tryGetValueInsensitive(
                Resources::MEDIA_SERVICES_ACCESS_KEY,
                $tokenizedSettings
            );

            return new MediaServicesSettings(
                $accountName,
                $accessKey,
                $endpointUri,
                $oauthEndpointUri
            );
        }

        self::noMatch($connectionString);
    }

    /**
     * Gets media services account name.
     *
     * @return string
     */
    public function getAccountName()
    {
        return $this->_accountName;
    }

    /**
     * Gets media services access key.
     *
     * @return string
     */
    public function getAccessKey()
    {
        return $this->_accessKey;
    }

    /**
     * Gets media services endpoint uri.
     *
     * @return string
     */
    public function getEndpointUri()
    {
        return $this->_endpointUri;
    }

    /**
     * Gets media services OAuth endpoint uri.
     *
     * @return string
     */
    public function getOAuthEndpointUri()
    {
        return $this->_oauthEndpointUri;
    }
}


text:
namespace ShaderUtils
{
/// Get the keywords list for a DX9 assembly shader
/// \param[out] keyWords The keywords list.
/// \param[in] pdwShader Pointer to the shader.
/// \return True if successful, otherwise false.
bool GetDX9AsmKeyWords(ShaderUtils::KeyWordsList& keyWords, const DWORD* pdwShader);

/// Get the keywords list for DX9 assembly shaders
/// \param[out] keyWords The keywords list.
/// \param[in] shaderType The type shader.
/// \param[in] wShaderModelMajor The shader model major version number.
/// \param[in] wShaderModelMinor The shader model minor version number.
/// \return True if successful, otherwise false.
bool GetDX9AsmKeyWords(ShaderUtils::KeyWordsList& keyWords, D3D9ShaderUtils::DX9ShaderType shaderType, WORD wShaderModelMajor, WORD wShaderModelMinor);

/// Get the keywords list for DX9 HLSL shaders
/// \param[out] keyWords The keywords list.
/// \param[in] shaderType The type shader.
/// \param[in] wShaderModelMajor The shader model major version number.
/// \param[in] wShaderModelMinor The shader model minor version number.
/// \return True if successful, otherwise false.
bool GetDX9HLSLKeyWords(ShaderUtils::KeyWordsList& keyWords, D3D9ShaderUtils::DX9ShaderType shaderType, WORD wShaderModelMajor, WORD wShaderModelMinor);
}; // ShaderUtils

#endif // DX9KEYWORDS_H

redpajama_set_name: RedPajamaGithub


text:
package trunk.coref.engine.exec.operator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import trunk.coref.config.CorefConfig;
import trunk.coref.engine.exec.WorkerPool;
import trunk.coref.engine.exec.tasks.BoundQueryTask;
import trunk.description.RemoteService;

import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.sparql.core.Var;
import com.hp.hpl.jena.sparql.engine.binding.Binding;

public class BoundQueryExecutor extends QueryExecutor {

	List<Binding> intermediate = new ArrayList<Binding>();

	public BoundQueryExecutor(Triple tp, Collection<RemoteService> sources, Collection<Binding> bindings) {
		super(tp,sources);
		intermediate.addAll(bindings);
	}

	@Override
	void setTaskCounter() {
		taskcounter = (int) (sources.size()*(Math.ceil((double)intermediate.size()/CorefConfig.bindJoinInterval)));
	}

	@Override
	void execTasks() {
		int begin = 0;

		do {
			int end = begin + CorefConfig.bindJoinInterval;
			end = Math.min(end, intermediate.size());
			List<Binding> sublist = intermediate.subList(begin, end);
			for(RemoteService rs:sources) {
				WorkerPool pool = WorkerPool.getWorkerPool(rs);
				pool.submit(new BoundQueryTask(this,tp,rs,sublist));
			}
			begin = end;
		}while(begin < intermediate.size());
	}
}


text:
A volte è necessario trasformare un numero in una stringa.

In quei casi, userai il metodo `.toString()`. Ecco un esempio:

```js
var n = 256;
n = n.toString();
```

## La sfida:

Crea un file dal nome `number-to-string.js`.

In questo file definisci una variabile chiamata `n` che referenzia il numero `128`;

Invoca il metodo `.toString()` sulla variabile `n`.

Usa `console.log()` per stampare i risultati del metodo `.toString()` sul terminale.

Verifica che il tuo programma sia corretto eseguendo questo comando:

```bash
javascripting verify number-to-string.js
```


text:
function fix_gawker_embeds_apply(button){

	document.querySelector('#fix_gawker_embeds_indicator').style.visibility = 'visible';
	button.setAttribute('disabled', 'disabled');

	var query = 'op=pluginhandler&plugin=fix_gawker_embeds&method=fix_gawker_embeds_apply';

	new Ajax.Request('backend.php', {
		parameters: query,
		onSuccess: function(response){
			alert('All fixes applied successfully.');
		},
		onFailure: function(response){
			alert('There was a problem while sending the query.\nServer says: '+ response.status +': '+ response.statusText );
		},
		onComplete: function(response){
			document.querySelector('#fix_gawker_embeds_indicator').style.visibility = 'hidden';
			button.removeAttribute('disabled');
		}
	});

	return false;
}


text: This is an example of how to easily implement JSON-RPC call on Hapi framework


text:
package agent

import (
	"github.com/hashicorp/consul/consul/structs"
	"net/http"
	"strings"
)

func (s *HTTPServer) HealthChecksInState(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Set default DC
	args := structs.ChecksInStateRequest{}
	s.parseSource(req, &args.Source)
	if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the service name
	args.State = strings.TrimPrefix(req.URL.Path, "/v1/health/state/")
	if args.State == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing check state"))
		return nil, nil
	}

	// Make the RPC request
	var out structs.IndexedHealthChecks
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("Health.ChecksInState", &args, &out); err != nil {
		return nil, err
	}

	// Use empty list instead of nil
	if out.HealthChecks == nil {
		out.HealthChecks = make(structs.HealthChecks, 0)
	}
	return out.HealthChecks, nil
}

func (s *HTTPServer) HealthNodeChecks(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Set default DC
	args := structs.NodeSpecificRequest{}
	if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the service name
	args.Node = strings.TrimPrefix(req.URL.Path, "/v1/health/node/")
	if args.Node == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing node name"))
		return nil, nil
	}

	// Make the RPC request
	var out structs.IndexedHealthChecks
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("Health.NodeChecks", &args, &out); err != nil {
		return nil, err
	}

	// Use empty list instead of nil
	if out.HealthChecks == nil {
		out.HealthChecks = make(structs.HealthChecks, 0)
	}
	return out.HealthChecks, nil
}

func (s *HTTPServer) HealthServiceChecks(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Set default DC
	args := structs.ServiceSpecificRequest{}
	s.parseSource(req, &args.Source)
	if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
		return nil, nil
	}

	// Pull out the service name
	args.ServiceName = strings.TrimPrefix(req.URL.Path, "/v1/health/checks/")
	if args.ServiceName == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing service name"))
		return nil, nil
	}

	// Make the RPC request
	var out structs.IndexedHealthChecks
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("Health.ServiceChecks", &args, &out); err != nil {
		return nil, err
	}

	// Use empty list instead of nil
	if out.HealthChecks == nil {
		out.HealthChecks = make(structs.HealthChecks, 0)
	}
	return out.HealthChecks, nil
}

func (s *HTTPServer) HealthServiceNodes(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	// Set default DC
	args := structs.ServiceSpecificRequest{}
	s.parseSource(req, &args.Source)
	if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
		return nil, nil
	}

	// Check for a tag
	params := req.URL.Query()
	if _, ok := params["tag"]; ok {
		args.ServiceTag = params.Get("tag")
		args.TagFilter = true
	}

	// Pull out the service name
	args.ServiceName = strings.TrimPrefix(req.URL.Path, "/v1/health/service/")
	if args.ServiceName == "" {
		resp.WriteHeader(400)
		resp.Write([]byte("Missing service name"))
		return nil, nil
	}

	// Make the RPC request
	var out structs.IndexedCheckServiceNodes
	defer setMeta(resp, &out.QueryMeta)
	if err := s.agent.RPC("Health.ServiceNodes", &args, &out); err != nil {
		return nil, err
	}

	// Filter to only passing if specified
	if _, ok := params["passing"]; ok {
		out.Nodes = filterNonPassing(out.Nodes)
	}

	// Use empty list instead of nil
	for i, _ := range out.Nodes {
		// TODO (slackpad) It's lame that this isn't a slice of pointers
		// but it's not a well-scoped change to fix this. We should
		// change this at the next opportunity.
		if out.Nodes[i].Checks == nil {
			out.Nodes[i].Checks = make(structs.HealthChecks, 0)
		}
	}
	if out.Nodes == nil {
		out.Nodes = make(structs.CheckServiceNodes, 0)
	}
	return out.Nodes, nil
}

// filterNonPassing is used to filter out any nodes that have check that are not passing
func filterNonPassing(nodes structs.CheckServiceNodes) structs.CheckServiceNodes {
	n := len(nodes)
OUTER:
	for i := 0; i < n; i++ {
		node := nodes[i]
		for _, check := range node.Checks {
			if check.Status != structs.HealthPassing {
				nodes[i], nodes[n-1] = nodes[n-1], structs.CheckServiceNode{}
				n--
				i--
				continue OUTER
			}
		}
	}
	return nodes[:n]
}


text:
package org.zstack.test.cascade;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;
import org.zstack.appliancevm.ApplianceVmVO;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.componentloader.ComponentLoader;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.header.vm.VmInstanceState;
import org.zstack.header.vm.VmInstanceVO;
import org.zstack.test.Api;
import org.zstack.test.ApiSenderException;
import org.zstack.test.DBUtil;
import org.zstack.test.WebBeanConstructor;
import org.zstack.test.deployer.Deployer;

/**
 * 1. create a vm with virtual router
 * 2. delete host
 * <p>
 * confirm vr is migrated
 */
public class TestCascadeDeletion20 {
    Deployer deployer;
    Api api;
    ComponentLoader loader;
    CloudBus bus;
    DatabaseFacade dbf;

    @Before
    public void setUp() throws Exception {
        DBUtil.reDeployDB();
        WebBeanConstructor con = new WebBeanConstructor();
        deployer = new Deployer("deployerXml/virtualRouter/virtualRouterSNAT2.xml", con);
        deployer.addSpringConfig("KVMRelated.xml");
        deployer.addSpringConfig("VirtualRouter.xml");
        deployer.addSpringConfig("VirtualRouterSimulator.xml");
        deployer.build();
        api = deployer.getApi();
        loader = deployer.getComponentLoader();
        bus = loader.getComponent(CloudBus.class);
        dbf = loader.getComponent(DatabaseFacade.class);
    }

    @Test
    public void test() throws ApiSenderException, InterruptedException {
        api.setTimeout(100000);
        ApplianceVmVO vr = dbf.listAll(ApplianceVmVO.class).get(0);
        String lastHostUuid = vr.getHostUuid();
        api.deleteHost(lastHostUuid);
        vr = dbf.listAll(ApplianceVmVO.class).get(0);
        Assert.assertEquals(VmInstanceState.Running, vr.getState());
        Assert.assertFalse(lastHostUuid.equals(vr.getHostUuid()));

        long count = dbf.count(VmInstanceVO.class);
        Assert.assertEquals(2, count);
    }
}


text:
package fr.paris.lutece.portal.business.user;

/**
 * Should the password be updated or ignored
 *
 * @since 6.0.0
 */
public enum PasswordUpdateMode
{
    UPDATE,
    IGNORE,
}


text:
package org.apache.camel.web.model;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

import org.apache.camel.CamelContext;

/**
 *
 */
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Camel {
    @XmlAttribute
    private String name;
    @XmlAttribute
    private String version;

    public Camel() {
    }

    public Camel(CamelContext camelContext) {
        setName(camelContext.getName());
    }

    public Camel(CamelContext camelContext, String version) {
        setName(camelContext.getName());
        setVersion(version);
    }

    @Override
    public String toString() {
        return "CamelContext: " + getName();

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Quantler.Tests.Bootstrap.Clusters
{
    class NonClusteredTests
    {
    }
}


text:
require 'rubygems'
require 'bundler/setup'

require 'sinatra'
require 'haml'
require 'sqlite3'

db = SQLite3::Database.new "data/comics.db"
db.results_as_hash = true  # Make my life easier later if things are added to the schema

allpubs = 'select * from publishers order by name ASC'
titleselect = 'select * from comics where title is ?'
titles_by_publisher = 'select distinct comics.title from comics inner join publishers on comics.publisher=publishers.id where publishers.name is ? order by comics.title ASC'

get '/' do
  haml :index
end

# Display the publishers in the database
get '/publishers' do
  @publishers = db.execute(allpubs)
  haml :publishers
end

# Display all the titles in the database by the given publisher
get '/publisher/:name' do |name|
  @titles = db.execute(titles_by_publisher, name)
  haml :publisher_name
end

# Display all the titles in the database
get '/titles' do
  # Show a clickable list of all titles that are in the database
  @titles = db.execute('select distinct title from comics order by title ASC')
  haml :titles
end

# Display all the issues in the database of a given title
get '/title/:name' do |name|
  rows = db.execute(titleselect, name)
  @titles = rows.sort { |x,y| x[0].to_i <=> y[0].to_i }

  haml :title_name
end

# Display specific infomation about a given title and issue number
get '/title/:name/:issuenumber' do |name, issuenumber|
  @issue = db.execute('select * from comics where title is ? and issue is ?', name, issuenumber)
  haml :title_name_issuenumber
end

# Display the form for adding a publisher
get '/addPublisher' do
  haml :addpublisher
end

# Form action for adding a publisher
post '/addPublisher' do
  # Check to make sure it doesn't already exist
  rows = db.execute('select id from publishers where name is ?', params[:name])

  if (rows.empty?)
    # No rows were returned, so the publisher doesn't already exist
    db.execute('insert into publishers (name) values (?)', params[:name])
    redirect to('/publishers')
  else
    haml "%h2 A publisher named #{params[:name]} already exists"
  end
end

# Display the form for adding an issue
get '/addIssue' do
  @publishers = db.execute(allpubs)
  haml :addissue
end

get '/addIssue/:name' do |name|
  @publishers = db.execute(allpubs)
  haml :addissue
end

# Form action for adding an issue
post '/addIssue' do
  db.execute(
    'insert into comics (title,issue,publisher,notes) values (?,?,?,?)',
    params[:name], params[:issuenumber], params[:publisherid], params[:notes]
  )
  # Call the /title/:name/:issuenumber on success?  Or just display a message and have a redirect in x seconds to the addIssue page
  redirect to("/title/#{URI.escape(params[:name])}/#{URI.escape(params[:issuenumber])}")
end

# Display form for modifying an issue
get '/modifyIssue/:id' do |id|
  @publishers = db.execute(allpubs)
  @issue = db.execute('select id,title,issue,publisher,notes from comics where id = ?', id)[0]
  haml :modifyissue, :locals => {:issue => @issue[0]}
end

# Form action for modifying an existing issue
post '/modifyIssue' do
  db.execute(
    'update comics set title=?, issue=?, publisher=?, notes=? where id=?',
    params[:title], params[:issuenumber],
    params[:publisherid], params[:notes],
    params[:issueid])
  redirect to("/title/#{URI.escape(params[:title])}/#{URI.escape(params[:issuenumber])}")
end

# Delete the issue identified by id
get '/deleteIssue/:id' do |id|
  db.execute('delete from comics where id=?', id)
  redirect to("/titles")
end


text:
<?php

namespace Koala\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class SecuredController extends Controller
{
    public function indexAction()
    {
		//this page requires the user to be logged in
        return $this->render('KoalaUserBundle:Secured:index.html.twig');
    }

}


text:
package org.krysalis.barcode4j.impl.datamatrix.encoder;

/**
 *
 * @author mk
 */
class Base256Encoder implements Encoder {

    @Override
    public Encodation getEncodingMode() {
        return Encodation.BASE256_ENCODATION;
    }

    @Override
    public void encode(EncoderContext context) {
        final StringBuilder buffer = new StringBuilder();
        buffer.append('\0'); //Initialize length field
        while (context.hasMoreCharacters()) {
            final char c = context.getCurrentChar();
            buffer.append(c);

            context.incPos();

            final Encodation newMode = LookAhead.lookAheadTest(context.getMessage(), context.getPos(), getEncodingMode());
            if (newMode != getEncodingMode()) {
                context.signalEncoderChange(newMode);
                break;
            }
        }
        final int dataCount = buffer.length() - 1;
        final int lengthFieldSize = 1;
        final int currentSize = context.getCodewordCount() + dataCount + lengthFieldSize;
        context.updateSymbolInfo(currentSize);
        final boolean mustPad = (context.getSymbolInfo().getDataCapacity() - currentSize) > 0;
        if (context.hasMoreCharacters() || mustPad) {
            if (dataCount <= 249) {
                buffer.setCharAt(0, (char) dataCount);
            } else if (dataCount > 249 && dataCount <= 1555) {
                buffer.setCharAt(0, (char) ((dataCount / 250) + 249));
                buffer.insert(1, (char) (dataCount % 250));
            } else {
                throw new IllegalStateException(
                        "Message length not in valid ranges: " + dataCount);
            }
        }
        for (int i = 0; i < buffer.length(); i++) {
            context.writeCodeword(randomize255State(
                    buffer.charAt(i), context.getCodewordCount() + 1));
        }
    }

    private static char randomize255State(char ch, int codewordPosition) {
        final int pseudoRandom = ((149 * codewordPosition) % 255) + 1;
        final int tempVariable = ch + pseudoRandom;
        if (tempVariable <= 255) {
            return (char) tempVariable;
        } else {
            return (char) (tempVariable - 256);
        }
    }
}


text:
package org.netbeans.cubeon.jira.repository;

import com.dolby.jira.net.soap.jira.RemoteComment;
import com.dolby.jira.net.soap.jira.RemoteFieldValue;
import com.dolby.jira.net.soap.jira.RemoteIssue;
import java.awt.Image;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.netbeans.cubeon.jira.query.JiraQuerySupport;
import org.netbeans.cubeon.jira.remote.JiraException;
import org.netbeans.cubeon.jira.remote.JiraSession;
import org.netbeans.cubeon.jira.repository.attributes.JiraProject;
import org.netbeans.cubeon.jira.tasks.JiraRemoteTask;
import org.netbeans.cubeon.jira.tasks.JiraTask;
import org.netbeans.cubeon.tasks.core.api.TaskEditorFactory;
import org.netbeans.cubeon.tasks.spi.repository.TaskRepository;
import org.netbeans.cubeon.tasks.spi.task.TaskElement;
import org.openide.filesystems.FileObject;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.ImageUtilities;
import org.openide.util.lookup.Lookups;

/**
 *
 * @author Anuradha
 */
public class JiraTaskRepository implements TaskRepository {

    private final JiraTaskRepositoryProvider provider;
    private final TaskEditorFactory factory = Lookup.getDefault().lookup(TaskEditorFactory.class);
    private final String id;
    private String name;
    private String description;
    /**
     * Url of the Repository
     * Ex:http://jira.repository
     */
    private String url;
    /**this is key of the project if repository for singel project
     * ex(CN is key for http://jira.repository/browse/CN)
     * if null it will download all projects
     */
    private String projectKey;
    //----------------------------
    private String userName;
    private String password;
    private boolean ignoreSSL;
    //----------------------------
    private final JiraRepositoryExtension extension;
    private final JiraTaskPriorityProvider jtpp = new JiraTaskPriorityProvider();
    private final JiraTaskTypeProvider jttp = new JiraTaskTypeProvider();
    private final JiraTaskStatusProvider jtsp = new JiraTaskStatusProvider();
    private final JiraTaskResolutionProvider jtrp = new JiraTaskResolutionProvider();
    private final JiraOfflineTaskSupport offlineTaskSupport;
    private final JiraRepositoryAttributes repositoryAttributes;
    private final JiraQuerySupport querySupport;
    private final TaskPersistenceHandler handler;
    private final TaskPersistenceHandler cache;
    private Map<String, JiraTask> map = new HashMap<String, JiraTask>();
    private FileObject baseDir;
    private State state = State.INACTIVE;
    private volatile JiraSession session;
    //locks
    private final Object SYNCHRONIZE_LOCK = new Object();
    public final Object SYNCHRONIZE_QUERY_LOCK = new Object();
    private final Object FILTER_UPDATE_LOCK = new Object();
    private final Lookup lookup;
    //----

    public JiraTaskRepository(JiraTaskRepositoryProvider provider,
            String id, String name, String description) {
        this.provider = provider;
        this.id = id;
        this.name = name;
        this.description = description;
        extension = new JiraRepositoryExtension(this);
        baseDir = provider.getBaseDir().getFileObject(id);
        if (baseDir == null) {
            try {
                baseDir = provider.getBaseDir().createFolder(id);
            } catch (IOException ex) {
                Exceptions.printStackTrace(ex);
            }
        }

        repositoryAttributes = new JiraRepositoryAttributes(this);
        handler = new TaskPersistenceHandler(this, baseDir, "tasks");//NOI18N
        cache = new TaskPersistenceHandler(this, baseDir, "cache");//NOI18N
        querySupport = new JiraQuerySupport(this, extension);
        offlineTaskSupport = new JiraOfflineTaskSupport(this);
        lookup = Lookups.fixed(this,
                provider, extension, jtpp, jtrp, jtsp, jttp, querySupport, offlineTaskSupport);
    }

    public FileObject getBaseDir() {
        return baseDir;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Lookup getLookup() {
        return lookup;
    }

    public Image getImage() {
        return ImageUtilities.loadImage("org/netbeans/cubeon/jira/repository/jira-repository.png");
    }

    public List<String> getTaskIds() {
        return handler.getTaskIds();
    }

    public void synchronize() {
        RequestProcessor.getDefault().post(new Runnable() {

            public void run() {
                synchronized (SYNCHRONIZE_LOCK) {
                    List<String> taskIds = handler.getTaskIds();
                    if (taskIds.isEmpty()) {
                        return;
                    }
                    ProgressHandle handle = ProgressHandleFactory.createHandle(
                            NbBundle.getMessage(JiraTaskRepository.class,
                            "LBL_Synchronizing_Tasks", getName()));
                    handle.start(taskIds.size());

                    try {
                        JiraSession session = getSession();
                        if (session != null) {
                            for (String id : taskIds) {
                                JiraTask jiraTask = getTaskElementById(id);
                                if (jiraTask != null && !jiraTask.isLocal()) {
                                    handle.progress(jiraTask.getId() + " : " + jiraTask.getName(), taskIds.indexOf(id));
                                    update(session, jiraTask);
                                }
                            }
                        }
                    } catch (JiraException ex) {
                        Logger.getLogger(JiraTaskRepository.class.getName()).warning(ex.getMessage());
                    } finally {
                        handle.finish();
                    }

                }
            }
        });
    }

    public TaskElement createTaskElement(String summery, String description) {

        JiraTask jiraTask = new JiraTask(handler.nextTaskId(),
                summery, description, this);
        jiraTask.setLocal(true);
        jiraTask.setProject(getPrefredProject());
        jiraTask.setType(getJiraTaskTypeProvider().getPrefedTaskType());
        jiraTask.setPriority(jtpp.getPrefredPriority());
        return jiraTask;
    }

    public synchronized JiraTask getTaskElementById(String id) {
        JiraTask get = map.get(id);
        if (get == null) {

            get = handler.getTaskElementById(id);
            if (get != null) {
                map.put(id, get);
            }
        }
        return get;
    }

    public void persist(TaskElement element) {
        JiraTask jiraTask = element.getLookup().lookup(JiraTask.class);
        assert jiraTask != null;
        handler.persist(jiraTask);
        //notify to outgoing query about modified state
        if (jiraTask.isModifiedFlag()) {
            querySupport.getOutgoingQuery().addTaskId(element.getId());
        } else {
            querySupport.getOutgoingQuery().removeTaskId(element.getId());
        }
    }

    public void revert(JiraTask task) {
        synchronized (task) {
            task.setAction(null);
            task.setNewComment(null);
            JiraUtils.remoteToTask(this, getJiraRemoteTaskCache(task.getId()), task);
            task.setModifiedFlag(false);
            persist(task);
            task.getExtension().fireStateChenged();
        }
    }

    public void remove(JiraTask jiraTask) {
        handler.removeTaskElement(jiraTask);
        //issue-26 check if loacl as local task not on cache
        if (!jiraTask.isLocal()) {
            cache.removeTaskElement(jiraTask);
        }
        extension.fireTaskRemoved(jiraTask);
        //make sure to remove from outgoing resultset
        querySupport.getOutgoingQuery().removeTaskId(jiraTask.getId());
    }

    public void cache(JiraRemoteTask remoteTask) {

        cache.persist(remoteTask);
    }

    public String getPassword() {
        return password;
    }

    public JiraRemoteTask getJiraRemoteTaskCache(String id) {
        return cache.getJiraRemoteTaskById(id);
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getURL() {
        return url;
    }

    public void setURL(String url) {
        this.url = url;
    }

    public String getProjectKey() {
        return projectKey;
    }

    public void setProjectKey(String projectKey) {
        this.projectKey = projectKey;
    }

    public JiraTaskRepositoryProvider getProvider() {
        return provider;
    }

    public JiraRepositoryExtension getNotifier() {
        return extension;
    }

    public void updateAttributes() {

        try {
            setState(State.SYNCHRONIZING);
            ProgressHandle handle = ProgressHandleFactory.createHandle(
                    NbBundle.getMessage(JiraTaskRepository.class,
                    "LBL_Updating_Attributes", getName()));
            repositoryAttributes.refresh(handle);
            loadAttributes();
            handle.finish();
        } catch (JiraException ex) {
            Logger.getLogger(JiraAttributesPersistence.class.getName()).
                    log(Level.WARNING, ex.getMessage());
            setState(State.ACTIVE);
        }

    }

    public void updateFilters() {
        ProgressHandle handle = ProgressHandleFactory.createHandle(
                NbBundle.getMessage(JiraTaskRepository.class,
                "LBL_Updating_Filters", getName()));
        handle.start();
        handle.switchToIndeterminate();
        try {

            synchronized (FILTER_UPDATE_LOCK) {
                repositoryAttributes.refreshFilters(handle);
                loadFilters();
            }

        } catch (JiraException ex) {
            Logger.getLogger(JiraAttributesPersistence.class.getName()).
                    log(Level.WARNING, ex.getMessage());

        } finally {
            handle.finish();
        }
    }

    public synchronized void loadAttributes() {
        repositoryAttributes.loadAttributes();
        setState(State.ACTIVE);
    }

    public synchronized void loadFilters() {
        repositoryAttributes.loadFilters();
        querySupport.refresh();

    }

    public JiraTaskPriorityProvider getJiraTaskPriorityProvider() {
        return jtpp;
    }

    public JiraTaskResolutionProvider getJiraTaskResolutionProvider() {
        return jtrp;
    }

    public JiraTaskStatusProvider getJiraTaskStatusProvider() {
        return jtsp;
    }

    public JiraTaskTypeProvider getJiraTaskTypeProvider() {
        return jttp;
    }

    public JiraRepositoryAttributes getRepositoryAttributes() {
        return repositoryAttributes;
    }

    public State getState() {
        return state;//default
    }

    public void setState(State state) {
        this.state = state;
        extension.fireStateChanged(state);
    }

    public JiraProject getPrefredProject() {
        List<JiraProject> projects = repositoryAttributes.getProjects();
        if (projects.size() > 0) {
            return projects.get(0);//TODO Extenalize this
        }
        return null;
    }

    public void update(JiraTask task) throws JiraException {
        synchronized (task) {

            JiraSession js = getSession();

            update(js, task);
        }

    }

    private void update(JiraSession js, JiraTask task) throws JiraException {
        RemoteIssue issue = js.getIssue(task.getId());
        update(issue, task);
    }

    public void update(RemoteIssue issue, JiraTask task) throws JiraException {
        synchronized (task) {
            if (!task.isLocal()) {
                JiraRemoteTask jiraRemoteTask = getJiraRemoteTaskCache(task.getId());
                if (jiraRemoteTask != null && jiraRemoteTask.getUpdated().getTime() == issue.getUpdated().getTime().getTime()) {
                    Logger.getLogger(getClass().getName()).info("Up to date : " + issue.getKey());//NOI18N

                } else {
                    //issue - 85 we need to save any changes before task marege
                    factory.save(task);

                    JiraUtils.maregeToTask(this, issue, jiraRemoteTask, task);
                    persist(task);

                    //make cache up to date
                    cache(JiraUtils.issueToTask(this, issue));

                    factory.refresh(task);

                    task.getExtension().fireStateChenged();
                }
            }
        }

    }

    public void submit(JiraTask task) throws JiraException {
        synchronized (task) {

            if (task.isLocal()) {
                JiraUtils.createTaskElement(this, task);
            } else {

                JiraSession js = getSession();
                if (task.getAction() != null) {

                    js.progressWorkflowAction(task.getId(),
                            task.getAction().getId(),
                            JiraUtils.changedFieldValuesForAction(task.getAction(),
                            getJiraRemoteTaskCache(task.getId()), task));

                    task.setAction(null);
                    JiraUtils.readWorkFlow(this, task);

                }
                RemoteFieldValue[] fieldValues = JiraUtils.changedFieldValues(getJiraRemoteTaskCache(task.getId()), task);

                if (fieldValues.length > 0) {
                    if (task.getNewComment() != null && task.getNewComment().trim().length() > 0) {
                        RemoteComment comment = new RemoteComment();
                        comment.setAuthor(getUserName());
                        comment.setBody(task.getNewComment());
                        js.addComment(task.getId(), comment);
                        task.setNewComment(null);
                    }

                    RemoteIssue remoteIssue = js.updateTask(task.getId(), fieldValues);
                    JiraRemoteTask remoteTask = JiraUtils.issueToTask(this, remoteIssue);
                    JiraUtils.remoteToTask(this, remoteTask, task);

                    //make cache up to date
                    cache(remoteTask);
                }

                if (task.getNewComment() != null && task.getNewComment().trim().length() > 0) {
                    RemoteComment comment = new RemoteComment();
                    comment.setAuthor(getUserName());
                    comment.setBody(task.getNewComment());
                    js.addComment(task.getId(), comment);
                    task.setNewComment(null);
                    RemoteIssue remoteIssue = js.getIssue(task.getId());

                    JiraRemoteTask remoteTask = JiraUtils.issueToTask(this, remoteIssue);
                    JiraUtils.remoteToTask(this, remoteTask, task);

                    //make cache up to date
                    cache(remoteTask);
                }
                task.setModifiedFlag(false);
                persist(task);
            }

            task.getExtension().fireStateChenged();
        }
    }

    public synchronized JiraSession getSession() throws JiraException {
        if (session == null) {
            reconnect();
        }
        return session;
    }

    TaskPersistenceHandler getTaskPersistenceHandler() {
        return handler;
    }

    public JiraQuerySupport getQuerySupport() {
        return querySupport;
    }

    public synchronized void reconnect() throws JiraException {
        ProgressHandle handle = ProgressHandleFactory.createHandle(
                NbBundle.getMessage(JiraTaskRepository.class, "LBL_Connecting", getName()));
        handle.start();
        handle.switchToIndeterminate();
        try {
            session = null;
            //try to reconnect
            session = new JiraSession(url, getUserName(), password,isIgnoreSSL());
        } finally {
            handle.finish();
        }
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final JiraTaskRepository other = (JiraTaskRepository) obj;
        if (this.provider != other.provider && (this.provider == null || !this.provider.equals(other.provider))) {
            return false;
        }
        if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 97 * hash + (this.provider != null ? this.provider.hashCode() : 0);
        hash = 97 * hash + (this.id != null ? this.id.hashCode() : 0);
        return hash;
    }

    public boolean isIgnoreSSL() {
        return ignoreSSL;
    }

    public void setIgnoreSSL(boolean ignoreSSL) {
        this.ignoreSSL = ignoreSSL;
    }
}


text:
package org.apache.qpid.proton.codec.security;

import java.util.AbstractList;
import java.util.List;
import org.apache.qpid.proton.amqp.Binary;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedLong;
import org.apache.qpid.proton.amqp.security.SaslInit;
import org.apache.qpid.proton.codec.AbstractDescribedType;
import org.apache.qpid.proton.codec.DecodeException;
import org.apache.qpid.proton.codec.Decoder;
import org.apache.qpid.proton.codec.DescribedTypeConstructor;
import org.apache.qpid.proton.codec.EncoderImpl;

public class SaslInitType extends AbstractDescribedType<SaslInit,List> implements DescribedTypeConstructor<SaslInit>
{
    private static final Object[] DESCRIPTORS =
    {
        UnsignedLong.valueOf(0x0000000000000041L), Symbol.valueOf("amqp:sasl-init:list"),
    };

    private static final UnsignedLong DESCRIPTOR = UnsignedLong.valueOf(0x0000000000000041L);

    private SaslInitType(EncoderImpl encoder)
    {
        super(encoder);
    }

    public UnsignedLong getDescriptor()
    {
        return DESCRIPTOR;
    }

    @Override
    protected List wrap(SaslInit val)
    {
        return new SaslInitWrapper(val);
    }

    public static class SaslInitWrapper extends AbstractList
    {

        private SaslInit _saslInit;

        public SaslInitWrapper(SaslInit saslInit)
        {
            _saslInit = saslInit;
        }

        public Object get(final int index)
        {

            switch(index)
            {
                case 0:
                    return _saslInit.getMechanism();
                case 1:
                    return _saslInit.getInitialResponse();
                case 2:
                    return _saslInit.getHostname();
            }

            throw new IllegalStateException("Unknown index " + index);

        }

        public int size()
        {
            return _saslInit.getHostname() != null
                      ? 3
                      : _saslInit.getInitialResponse() != null
                      ? 2
                      : 1;

        }
    }

    public SaslInit newInstance(Object described)
    {
        List l = (List) described;

        SaslInit o = new SaslInit();

        if(l.size() <= 0)
        {
            throw new DecodeException("The mechanism field cannot be omitted");
        }

        switch(3 - l.size())
        {

            case 0:
                o.setHostname( (String) l.get( 2 ) );
            case 1:
                o.setInitialResponse( (Binary) l.get( 1 ) );
            case 2:
                o.setMechanism( (Symbol) l.get( 0 ) );
        }

        return o;
    }

    public Class<SaslInit> getTypeClass()
    {
        return SaslInit.class;
    }

    public static void register(Decoder decoder, EncoderImpl encoder)
    {
        SaslInitType type = new SaslInitType(encoder);
        for(Object descriptor : DESCRIPTORS)
        {
            decoder.register(descriptor, type);
        }
        encoder.register(type);
    }
}


text:
{% extends "base.html" %}
{% load humanize wagtailimages_tags digi_tags wagtailcore_tags people_tags %}

{% block content %}

{{ page.type }}

{{ page.title }}

            {% phases_indicator page.phase %}

                {% image page.image width-800 as page_image %}

                    {% for block in page.body %}
                    {{ block }}
                    {% endfor %}

            {% if page.projects.exists %}

Teeman projektit

                    {% for project in page.projects %}

                                {% image project.image fill-400x400 as project_image %}

{{ project.title }}

{{ project.short_description }}

                    {% endfor %}

            {% endif %}

            {% include "includes/sidebar_links_and_roles.html" %}
            {% include "includes/sidebar_twitter_feed.html" %}

{% endblock %}


text:
import { zeros, add } from 'dsp-array'
import { rectangular } from 'dsp-spectrum'
import { ifftshift } from 'dsp-fftshift'

/**
 * Synthesize a signal from a collection of frames
 * @private
 * @param {Array<Object>} frames - an array of frames (`{ magnitudes, phases }`)
 * @param {Object} options - All required: size, hop, sampeRate, factor
 * @param {Array} output - (Optional) the output array
 */
export default function synthesis (frames, { ft, size, hop, sampleRate, factor }, output) {
  if (!frames || !frames.length) throw Error('"frames" parameter is required in synthesis')

  var len = frames.length
  var hopS = hop * factor
  console.log('SYNTHESIS', hop, hopS, len, len * hopS, output)
  if (!output) output = zeros(len * hopS + size)
  var position = 0

  // create some intermediate buffers (and reuse it for performance)
  var rectFD = { real: zeros(size), imag: zeros(size) }
  var timeDomain = { real: zeros(size), imag: zeros(size) }
  for (var i = 0; i < len; i++) {
    // 1. Convert freq-domain from polar to rectangular
    rectangular(frames[i], rectFD)
    // 2. Convert from freq-domain in rectangular to time-domain
    var signal = ft.inverse(rectFD, timeDomain).real
    // 3. Unshift the previous cycling shift
    ifftshift(signal)
    // 4. Overlap add
    var write = output.subarray(position, position + hopS)
    add(hopS, signal, write, write)
    position += hopS
  }
  return output
}


text:
class Howcast::Client
  class Playlist
    extend WatchAttrAccessors
    include XmlMethods

    attr_accessor :id, :title, :description, :playlist_thumbnail_url, :videos

    # Creates a new Playlist object which is used to encapsulate all the attributes available
    # from the Howcast playlist API.
    #
    # === Inputs
    #
    # * <tt>attributes</tt> -- A hash to set the various attributes of the playlist object
    #
    # === Examples
    #
    # Initialize a playlist with title "My Playlist"
    #   Playlist.new :title => "My Playlist"
    def initialize(attributes={})
      attributes.each do |k, v|
        if k == :title
          self.send("#{k}=", v.gsub(/^Howcast - /, '')) if self.respond_to?(k)
        else
          self.send("#{k}=", v) if self.respond_to?(k)
        end
      end
    end
  end

  # Provides access to the Howcast playlist API.
  #
  # === Inputs
  #
  # * <tt>id</tt> -- The id of the playlist to lookup
  #
  # === Outputs
  #
  # Playlist object if the id exists or nil if the id doesn't exist or is malformed
  #
  # === Exceptions
  #
  # * <tt>Howcast::ApiNotFound</tt>
  #
  # === Examples
  #
  # Get the Howcast playlist with id 12345
  #   Howcast::Client.new.playlist(12345)
  def playlist(id, options = {})
    response = establish_connection("playlists/#{id}.xml")
    parse_single_xml(response, Playlist)
  end
end


text:
Puppet ``iptables`` Management Like it should be
================================================

This is how puppet ``iptables`` management should be:

Idempotent
    Running puppet again and again, with the same iptable configuration should
    not modify anything.

Transactional
    When ``iptables`` rules changed, it should not remove or add rules one by
    one. There should not be intermediate states.

This does not intend to be compatible with platforms other than Linux.
This is just a proof of concept for now. It only works on Debian.

Examples
--------

.. code-block:: puppet

    # Define the default policies for each node

    node base {
      class {"iptables":
        policies => {
          'INPUT'   => "DROP",
          'OUTPUT'  => "ACCEPT",
          'FORWARD' => "DROP",
        },
      }

      iptables::entry {"accept ssh":
        dport => 22,
        jump  => "ACCEPT",
      }

    }

    class dns_server {
      package {"bind9":
        ensure => pesent;
      }

      iptables::entry {"accept dns traffic":
        proto => "udp",
        dport => "domain", # Equivalent to 53
      }
    }

    node dns1.example.com inherits base {
      include dns_server

      iptables::entry {"accept replication from dns2.example.com":
        proto  => "tcp", # Default value
        source => "dns2.example.com",
        dport  => "domain",
        jump   => "ACCEPT",
      }

      iptables::entry {"block kumar":
        rule => "-A INPUT -m country --country-block kumar -j REJECT",
      }

    }

Known bugs
----------

For now, this is a proof of concept:

 * It only supports IPv4
 * It only work on Debian
 * It only supports the filter table


text:
require 'test_helper'

class BaseAuthenticatorTest < ActiveSupport::TestCase

  test "verify is not implemented" do
    assert_raise NotImplementedError do
      RailsCasServer::Authenticators::Base.new.verify
    end
  end
end


text:
const AWS = require('aws-sdk');
const Service = AWS.Service;

AWS.apiLoader.services.zenko = {};
const ZenkoClient = Service.defineService(
    'zenko', ['2018-07-08-json', '2018-07-11-xml']);

/*
 * Note: a version is identified by the first 10 chars if it is not a valid
 * date format. As such, ZenkoClient version suffixes will only serve to
 * help differentiate between JSON and XML apis, and is not used to determine
 * the api version.
 * Ex. 2018-07-08-json and 2018-07-08-xml are both evaluated as version
 * 2018-07-08
 */

Object.assign(ZenkoClient.prototype, {
    validateService() {
        if (!this.config.region) {
            this.config.region = 'us-east-1';
        }
    },
});

// default to use XML when apiVersion is not specified by the user
Object.defineProperty(AWS.apiLoader.services.zenko, 'latest', {
    get: function get() {
        const model = require('./zenko-2018-07-11-xml.api.json');
        return model;
    },
    enumerable: true,
    configurable: true,
});

// Backbeat api specific client methods, handles JSON responses
Object.defineProperty(AWS.apiLoader.services.zenko, '2018-07-08-json', {
    get: function get() {
        const model = require('./zenko-2018-07-08-json.api.json');
        return model;
    },
    enumerable: true,
    configurable: true,
});

// Search specific client, regular s3 cilent, handles XML responses
Object.defineProperty(AWS.apiLoader.services.zenko, '2018-07-11-xml', {
    get: function get() {
        const model = require('./zenko-2018-07-11-xml.api.json');
        return model;
    },
    enumerable: true,
    configurable: true,
});

module.exports = ZenkoClient;


text:
"""Definition of Abstract Class State to represent Base State
"""
from abc import ABC, abstractclassmethod
import logging

class State(ABC):
    """State is an abstract class to represent a state. It defines the abstract method for behavior of state and
    transition method to facilitate transition between states.
    """

    def __init__(self, components):
        self.components = components
        self.allowedStateTransitions = {}

    @abstractclassmethod
    def on_enter(self, payload=None):
        """This method is executed on entry to a state. Perform the action designated for the state in this method.
        :param payload: an object to transfer information to the state. Default: None
        :return: None
        """
        pass

    @abstractclassmethod
    def on_exit(self):
        """This method is executed on exit from a state. Free up required resources or perform other important actions
        in this method
        :return: None
        """
        pass

    def transition(self, state, payload=None):
        """Execute this method to transition from one state to other valid state. Transition is only performed if valid.
        :param state: The state to which transition is to be performed.
        :param payload: any object that is needed to be transferred to next state.
        :return: None
        """
        if not self.__can_transition(state):
            print(self.allowedStateTransitions)
            logging.warning("Invalid transition to State: {0}".format(state))
            return

        self.on_exit()
        state.on_enter(payload)

    def __can_transition(self, state):
        return state in self.allowedStateTransitions.values()


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

<title>ShadowVelocityTracker</title>
<meta name="date" content="2017-03-02">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.robolectric.shadows

Class ShadowVelocityTracker

java.lang.Object

org.robolectric.shadows.ShadowVelocityTracker

@Implements(value=android.view.VelocityTracker.class)
public class ShadowVelocityTracker
extends java.lang.Object

Shadow for VelocityTracker.

Constructor Summary

Constructors

Constructor and Description

ShadowVelocityTracker()

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

void
addMovement(android.view.MotionEvent event)

void
clear()

void
computeCurrentVelocity(int units)

void
computeCurrentVelocity(int units,
                      float maxVelocity)

float
getXVelocity()

float
getXVelocity(int id)

float
getYVelocity()

float
getYVelocity(int id)

Methods inherited from class java.lang.Object

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

Constructor Detail

ShadowVelocityTracker

public ShadowVelocityTracker()

Method Detail

clear

@Implementation
public void clear()

addMovement

@Implementation
public void addMovement(android.view.MotionEvent event)

computeCurrentVelocity

@Implementation
public void computeCurrentVelocity(int units)

computeCurrentVelocity

@Implementation
public void computeCurrentVelocity(int units,
                                                   float maxVelocity)

getXVelocity

@Implementation
public float getXVelocity()

getYVelocity

@Implementation
public float getYVelocity()

getXVelocity

@Implementation
public float getXVelocity(int id)

getYVelocity

@Implementation
public float getYVelocity(int id)

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
@echo off
cls
del *.exe
del *.obj
del err.txt
del logfile.txt
c:\lcc\bin\lcc -A -errout=err.txt -DNDEBUG test.c
c:\lcc\bin\lcclnk -s -subsystem windows test.obj eml.lib kernel32.lib wsock32.lib iphlpapi.lib


text:
<hazelcast xsi:schemaLocation="http://www.hazelcast.com/schema/config
    http://www.hazelcast.com/schema/config/hazelcast-config-3.6.xsd"
    xmlns="http://www.hazelcast.com/schema/config" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <properties>
        <property name="hazelcast.logging.type">jdk</property>
        <property name="hazelcast.version.check.enabled">false</property>
    </properties>

    <network>
        <port auto-increment="true">5701</port>
        <outbound-ports>
            <ports>33000-35000</ports>
        </outbound-ports>
        <join>
            <multicast enabled="false" />
            <tcp-ip enabled="true">
                <member>10.66.21.2-4</member>
            </tcp-ip>
        </join>
        <interfaces enabled="true">
            <interface>10.66.21.*</interface>
        </interfaces>
    </network>
</hazelcast>


text:
import * as Bluebird from "bluebird";
import { Context } from "../interfaces/api/context";
import * as io from "../interfaces/io";
export declare function declineContactRequest(io: io.HttpIo, apiContext: Context, contactUsername: string): Bluebird<any>;
export default declineContactRequest;


text:
package com.jaamsim.EntityProviders;

import com.jaamsim.basicsim.Entity;

public class EntityProvConstant<T extends Entity> implements EntityProvider<T> {

	private final T ent;

	public EntityProvConstant(T ent) {
		this.ent = ent;
	}

	public Entity getEntity() {
		return ent;
	}

	@Override
	public T getNextEntity(double simTime) {
		return ent;
	}

	@Override
	public String toString() {
		return ent.getName();
	}

}


text:
package org.apache.uima.fit.util;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import org.apache.uima.fit.testing.util.DisableLogging;
import org.junit.jupiter.api.Test;

public class DisableLoggingTest {

  @Test
  public void test() {
    // get the top logger and remove all handlers
    Logger topLogger = Logger.getLogger("");
    Handler[] handlers = topLogger.getHandlers();
    for (Handler handler : handlers) {
      topLogger.removeHandler(handler);
    }

    // add a single hander that writes to a string buffer
    final StringBuffer buffer = new StringBuffer();
    Handler bufferhandler = new Handler() {
      @Override
      public void close() throws SecurityException {/* do nothing */
      }

      @Override
      public void flush() {/* do nothing */
      }

      @Override
      public void publish(LogRecord record) {
        buffer.append(record.getMessage());
      }
    };
    topLogger.addHandler(bufferhandler);

    // log to the buffer
    Logger.getLogger("foo").info("Hello!");
    assertThat(buffer.toString()).isEqualTo("Hello!");

    // disable logging, and make sure nothing is written to the buffer
    buffer.setLength(0);
    Level level = DisableLogging.disableLogging();
    Logger.getLogger("bar").info("Hello!");
    assertThat(buffer).isEmpty();

    // enable logging, and make sure things are written to the buffer
    DisableLogging.enableLogging(level);
    Logger.getLogger("baz").info("Hello!");
    assertThat(buffer.toString()).isEqualTo("Hello!");

    // try disabling logging with a logger that has its own handler
    buffer.setLength(0);
    Logger logger = Logger.getLogger("foo.bar.baz");
    logger.addHandler(new Handler() {
      @Override
      public void close() throws SecurityException {/* do nothing */
      }

      @Override
      public void flush() { /* do nothing */
      }

      @Override
      public void publish(LogRecord record) {
        buffer.append("Not disabled!");
      }
    });
    level = DisableLogging.disableLogging();
    logger.info("Hello!");
    assertThat(buffer).isEmpty();
    DisableLogging.enableLogging(level);

    // restore the original handlers
    topLogger.removeHandler(bufferhandler);
    for (Handler handler : handlers) {
      topLogger.addHandler(handler);
    }
  }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var ts = require("typescript");
var perform_compile_1 = require("./perform_compile");
var compiler_host_1 = require("./transformers/compiler_host");
var program_1 = require("./transformers/program");
var EmitFlags;
(function (EmitFlags) {
    EmitFlags[EmitFlags["DTS"] = 1] = "DTS";
    EmitFlags[EmitFlags["JS"] = 2] = "JS";
    EmitFlags[EmitFlags["Metadata"] = 4] = "Metadata";
    EmitFlags[EmitFlags["I18nBundle"] = 8] = "I18nBundle";
    EmitFlags[EmitFlags["Codegen"] = 16] = "Codegen";
    EmitFlags[EmitFlags["Default"] = 19] = "Default";
    EmitFlags[EmitFlags["All"] = 31] = "All";
})(EmitFlags = exports.EmitFlags || (exports.EmitFlags = {}));
// Wrapper for createProgram.
function createProgram(_a) {
    var rootNames = _a.rootNames, options = _a.options, host = _a.host, oldProgram = _a.oldProgram;
    return program_1.createProgram({ rootNames: rootNames, options: options, host: host, oldProgram: oldProgram });
}
exports.createProgram = createProgram;
// Wrapper for createCompilerHost.
function createCompilerHost(_a) {
    var options = _a.options, _b = _a.tsHost, tsHost = _b === void 0 ? ts.createCompilerHost(options, true) : _b;
    return compiler_host_1.createCompilerHost({ options: options, tsHost: tsHost });
}
exports.createCompilerHost = createCompilerHost;
function formatDiagnostics(diags) {
    return perform_compile_1.formatDiagnostics(diags);
}
exports.formatDiagnostics = formatDiagnostics;
//# sourceMappingURL=ngtools_api2.js.map


text:
[YQBoots Framework](http://www.yqboots.com/projects/framework) is a production-ready framework for building modern applications. It is built on [Spring IO Platform](http://spring.io/platform/), and simplifying the initialization of a Spring-powered, production-grade applications and services with minimal effort by using [Spring Boot](https://spring.io/spring-boot).

It also contains a fully responsive user interface, built by [Bootstrap](http://getbootstrap.com/), providing an optimal viewing and interaction experience -- easy reading and navigation with a minimum of resizing, panning, and scrolling-across a wide range of devices (from desktop to mobile phones).

# Prerequisites
[JDK 8 update 20 or later](http://www.oracle.com/technetwork/java/javase/downloads)

# Features
## Modern User Interface
A fully responsive, HTML5 + CSS3 user interface, no need to build different user interface for different devices.

Thanks to the HTML5 nature, it supports almost all modern browsers, such as Internet Explorer 10+, Microsoft Edge, Google Chrome, Mozilla Firefox, etc.

## Rapid Prototyping
It is powered by [Thymeleaf](http://www.thymeleaf.org/), a modern server-side Java template engine, which can bring elegant nature templates to your development flow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

## Quick Start
It is powered by [Spring Boot](https://spring.io/spring-boot), its spring-based and convention-over-configuration feature rapidly decreases the initialization of your project.

You can launch the application with ```http://localhost``` after you run the command.
```
java -jar yqboots-web-site-[version].jar --server.port=80 --spring.profiles.active=prd
```

## Security
It provides the RBAC (Role-Based Access Control) model to protected your web sites, which has an ACL (Access Control List) strategy to protected your URL, methods, and even domains.

For the audit requirement, it can log any actions you take to the specified domains.

## Modularization and Internationalization
It divides the functionality of your application into independent, interchangeable modules, so that each contains everything necessary to execute only one aspect of the desired functionality.

It also supports multiple languages, and switch between them.

# License
The [YQBoots Framework](http://www.yqboots.com/projects/framework) is released under version 2.0 of [the Apache License](http://www.apache.org/licenses/LICENSE-2.0).


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="?textColorSecondaryInverse" android:alpha="?disabledAlpha" />
    <item android:color="?textColorPrimaryInverse" android:state_activated="true" />
    <item android:color="?textColorSecondaryInverse" />
</selector>


text:
/* Mode support
 *
 * (C) 2008-2011 Adam <Adam@anope.org>
 * (C) 2008-2016 Anope Team <team@anope.org>
 *
 * Please read COPYING and README for further details.
 */

#ifndef MODES_H
#define MODES_H

#include "anope.h"
#include "base.h"

/** The different types of modes
*/
enum ModeType
{
	/* Regular mode */
	MODE_REGULAR,
	/* b/e/I */
	MODE_LIST,
	/* k/l etc */
	MODE_PARAM,
	/* v/h/o/a/q */
	MODE_STATUS
};

/* Classes of modes, Channel modes and User modes
 */
enum ModeClass
{
	MC_CHANNEL,
	MC_USER
};

/** This class is the basis of all modes in Anope
 */
class CoreExport Mode : public Base
{
 public:
 	/* Mode name */
 	Anope::string name;
	/* Class of mode this is (user/channel) */
	ModeClass mclass;
	/* Mode char for this, eg 'b' */
	char mchar;
	/* Type of mode this is, eg MODE_LIST */
	ModeType type;

	/** constructor
	 * @param mname The mode name
	 * @param mclass The type of mode this is
	 * @param mc The mode char
	 * @param type The mode type
	 */
	Mode(const Anope::string &mname, ModeClass mclass, char mc, ModeType type);
	virtual ~Mode();

	/** Can a user set this mode, used for mlock
	 * @param u The user
	 */
	virtual bool CanSet(User *u) const;
};

/** This class is a user mode, all user modes use this/inherit from this
 */
class CoreExport UserMode : public Mode
{
 public:
	/** constructor
	 * @param name The mode name
	 * @param mc The mode char
	 */
	UserMode(const Anope::string &name, char mc);
};

class CoreExport UserModeParam : public UserMode
{
 public:
 	/** constructor
	 * @param name The mode name
	 * @param mc The mode char
	 */
	UserModeParam(const Anope::string &name, char mc);

	/** Check if the param is valid
	 * @param value The param
	 * @return true or false
	 */
	virtual bool IsValid(Anope::string &value) const { return true; }
};

/** This class is a channel mode, all channel modes use this/inherit from this
 */
class CoreExport ChannelMode : public Mode
{
 public:
	/* channel modes that can posssibly unwrap this mode */
	std::vector<ChannelMode *> listeners;

	/** constructor
	 * @param name The mode name
	 * @param mc The mode char
	 */
	ChannelMode(const Anope::string &name, char mc);

	bool CanSet(User *u) const anope_override;

	virtual void Check() { }

	/** 'wrap' this channel mode and param to the underlying mode and param
	 */
	virtual ChannelMode *Wrap(Anope::string &param);

	/** 'unwrap' this mode to our internal representation
	 */
	ChannelMode *Unwrap(Anope::string &param);

	/** called when a mode is being unwrapped, and is asking us if we can unwrap it
	 */
	virtual ChannelMode *Unwrap(ChannelMode *, Anope::string &param);
};

/** This is a mode for lists, eg b/e/I. These modes should inherit from this
 */
class CoreExport ChannelModeList : public ChannelMode
{
 public:
	/** constructor
	 * @param name The mode name
	 * @param mc The mode char
	 */
	ChannelModeList(const Anope::string &name, char mc);

	/** Is the mask valid
	 * @param mask The mask
	 * @return true for yes, false for no
	 */
	virtual bool IsValid(Anope::string &mask) const;

	/** Checks if mask affects user
	 * Should only be used for extbans or other weird ircd-specific things.
	 * @param u The user
	 * @param e The entry to match against
	 * @return true on match
	 */
	virtual bool Matches(User *u, const Entry *e) { return false; }

	/** Called when a mask is added to a channel
	 * @param chan The channel
	 * @param mask The mask
	 */
	virtual void OnAdd(Channel *chan, const Anope::string &mask) { }

	/** Called when a mask is removed from a channel
	 * @param chan The channel
	 * @param mask The mask
	 */
	virtual void OnDel(Channel *chan, const Anope::string &mask) { }
};

/** This is a mode with a paramater, eg +k/l. These modes should use/inherit from this
*/
class CoreExport ChannelModeParam : public ChannelMode
{
 public:
	/** constructor
	 * @param name The mode name
	 * @param mc The mode char
	 * @param minus_no_arg true if this mode sends no arg when unsetting
	 */
	ChannelModeParam(const Anope::string &name, char mc, bool minus_no_arg = false);

	/* Should we send an arg when unsetting this mode? */
	bool minus_no_arg;

	/** Is the param valid
	 * @param value The param
	 * @return true for yes, false for no
	 */
	virtual bool IsValid(Anope::string &value) const { return true; }
};

/** This is a mode that is a channel status, eg +v/h/o/a/q.
*/
class CoreExport ChannelModeStatus : public ChannelMode
{
 public:
	/* The symbol, eg @ % + */
	char symbol;
	/* The "level" of the mode, used to compare with other modes.
	 * Used so we know op > halfop > voice etc.
	 */
	short level;

	/** constructor
	 * @param name The mode name
	 * @param mc The mode char
	 * @param msymbol The symbol for the mode, eg @ %
	 * @param mlevel A level for the mode, which is usually determined by the PREFIX capab
	 */
	ChannelModeStatus(const Anope::string &name, char mc, char msymbol, short mlevel);
};

/** A virtual mode. This mode doesn't natively exist on the IRCd (like extbans),
 * but we still have a representation for it.
 */
template<typename T>
class CoreExport ChannelModeVirtual : public T
{
	Anope::string base;
	ChannelMode *basech;

 public:
	ChannelModeVirtual(const Anope::string &mname, const Anope::string &basename);

	~ChannelModeVirtual();

	void Check() anope_override;

	ChannelMode *Wrap(Anope::string &param) anope_override;

	ChannelMode *Unwrap(ChannelMode *cm, Anope::string &param) = 0;
};

/* The status a user has on a channel (+v, +h, +o) etc */
class CoreExport ChannelStatus
{
	Anope::string modes;
 public:
 	ChannelStatus();
 	ChannelStatus(const Anope::string &modes);
 	void AddMode(char c);
	void DelMode(char c);
	bool HasMode(char c) const;
	bool Empty() const;
	void Clear();
	const Anope::string &Modes() const;
	Anope::string BuildModePrefixList() const;
};

class CoreExport UserModeOperOnly : public UserMode
{
 public:
	UserModeOperOnly(const Anope::string &mname, char um) : UserMode(mname, um) { }

	bool CanSet(User *u) const anope_override;
};

class CoreExport UserModeNoone : public UserMode
{
 public:
	UserModeNoone(const Anope::string &mname, char um) : UserMode(mname, um) { }

	bool CanSet(User *u) const anope_override;
};

/** Channel mode +k (key)
 */
class CoreExport ChannelModeKey : public ChannelModeParam
{
 public:
	ChannelModeKey(char mc) : ChannelModeParam("KEY", mc) { }

	bool IsValid(Anope::string &value) const anope_override;
};

/** This class is used for oper only channel modes
 */
class CoreExport ChannelModeOperOnly : public ChannelMode
{
 public:
	ChannelModeOperOnly(const Anope::string &mname, char mc) : ChannelMode(mname, mc) { }

	/* Opers only */
	bool CanSet(User *u) const anope_override;
};

/** This class is used for channel modes only servers may set
 */
class CoreExport ChannelModeNoone : public ChannelMode
{
 public:
	ChannelModeNoone(const Anope::string &mname, char mc) : ChannelMode(mname, mc) { }

	bool CanSet(User *u) const anope_override;
};

/** This is the mode manager
 * It contains functions for adding modes to Anope so Anope can track them
 * and do things such as MLOCK.
 * This also contains a mode stacker that will combine multiple modes and set
 * them on a channel or user at once
 */
class CoreExport ModeManager
{
 public:

	/* Number of generic channel and user modes we are tracking */
	static unsigned GenericChannelModes;
	static unsigned GenericUserModes;

	/** Add a user mode to Anope
	 * @param um A UserMode or UserMode derived class
	 * @return true on success, false on error
	 */
	static bool AddUserMode(UserMode *um);

	/** Add a channel mode to Anope
	 * @param cm A ChannelMode or ChannelMode derived class
	 * @return true on success, false on error
	 */
	static bool AddChannelMode(ChannelMode *cm);

	/** Remove a user mode from Anope
	 * @param um A UserMode to remove
	 */
	static void RemoveUserMode(UserMode *um);

	/** Remove a channel mode from Anope
	 * @param um A ChanneMode to remove
	 */
	static void RemoveChannelMode(ChannelMode *cm);

	/** Find a channel mode
	 * @param mode The mode
	 * @return The mode class
	 */
	static ChannelMode *FindChannelModeByChar(char mode);

	/** Find a user mode
	 * @param mode The mode
	 * @return The mode class
	 */
	static UserMode *FindUserModeByChar(char mode);

	/** Find a channel mode
	 * @param name The modename
	 * @return The mode class
	 */
	static ChannelMode *FindChannelModeByName(const Anope::string &name);

	/** Find a user mode
	 * @param name The modename
	 * @return The mode class
	 */
	static UserMode *FindUserModeByName(const Anope::string &name);

	/** Gets the channel mode char for a symbol (eg + returns v)
	 * @param symbol The symbol
	 * @return The char
	 */
	static char GetStatusChar(char symbol);

	static const std::vector<ChannelMode *> &GetChannelModes();
	static const std::vector<UserMode *> &GetUserModes();
	static const std::vector<ChannelModeStatus *> &GetStatusChannelModesByRank();
	static void RebuildStatusModes();

	/** Add a mode to the stacker to be set on a channel
	 * @param bi The client to set the modes from
	 * @param c The channel
	 * @param cm The channel mode
	 * @param set true for setting, false for removing
	 * @param param The param, if there is one
	 */
	static void StackerAdd(BotInfo *bi, Channel *c, ChannelMode *cm, bool set, const Anope::string &param = "");

	/** Add a mode to the stacker to be set on a user
	 * @param bi The client to set the modes from
	 * @param u The user
	 * @param um The user mode
	 * @param set true for setting, false for removing
	 * @param param The param, if there is one
	 */
	static void StackerAdd(BotInfo *bi, User *u, UserMode *um, bool set, const Anope::string &param = "");

	/** Process all of the modes in the stacker and send them to the IRCd to be set on channels/users
	 */
	static void ProcessModes();

	/** Delete a user, channel, or mode from the stacker
	 */
	static void StackerDel(User *u);
	static void StackerDel(Channel *c);
	static void StackerDel(Mode *m);
};

/** Represents a mask set on a channel (b/e/I)
 */
class CoreExport Entry
{
	Anope::string name;
	Anope::string mask;
 public:
	unsigned short cidr_len;
	Anope::string nick, user, host, real;

	/** Constructor
 	 * @param mode What mode this host is for, can be empty for unknown/no mode
	 * @param host A full or poartial nick!ident@host/cidr#real name mask
	 */
	Entry(const Anope::string &mode, const Anope::string &host);

	/** Get the banned mask for this entry
	 * @return The mask
	 */
	const Anope::string GetMask() const;

	const Anope::string GetNUHMask() const;

	/** Check if this entry matches a user
	 * @param u The user
	 * @param full True to match against a users real host and IP
	 * @return true on match
	 */
	bool Matches(User *u, bool full = false) const;
};

#endif // MODES_H


text:
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import StoryList from '../components/StoryList'
import Header from '../components/Header'
import Footer from '../components/Footer'
import { fetchStoriesIfNeeded} from '../actions/storyActions'

class App extends Component {
  constructor(props) {
    super(props)
  }

  render() {
    const {items} = this.props;
    return (

React Blog

The testing react blog application with Bootstrap

            { this.props.children }

    )
  }
}

export default App;


text:
namespace em = enterprise_management;

namespace chromeos {

namespace {

void WaitForShutdownButtonVisibility(bool visible) {
  int ui_update_count = ash::LoginScreenTestApi::GetUiUpdateCount();
  while (ash::LoginScreenTestApi::IsShutdownButtonShown() != visible) {
    ash::LoginScreenTestApi::WaitForUiUpdate(ui_update_count);
    ui_update_count = ash::LoginScreenTestApi::GetUiUpdateCount();
  }
}

}  // namespace

class ShutdownPolicyBaseTest
    : public policy::DevicePolicyCrosBrowserTest,
      public DeviceSettingsService::Observer {
 protected:
  ShutdownPolicyBaseTest() {}
  ~ShutdownPolicyBaseTest() override {}

  // DeviceSettingsService::Observer:
  void DeviceSettingsUpdated() override {
    if (run_loop_)
      run_loop_->Quit();
  }

  // policy::DevicePolicyCrosBrowserTest:
  void SetUpOnMainThread() override {
    policy::DevicePolicyCrosBrowserTest::SetUpOnMainThread();
    tray_test_api_ = ash::SystemTrayTestApi::Create();
  }

  // Updates the device shutdown policy and sets it to |reboot_on_shutdown|.
  void UpdateRebootOnShutdownPolicy(bool reboot_on_shutdown) {
    policy::DevicePolicyBuilder* builder = device_policy();
    ASSERT_TRUE(builder);
    em::ChromeDeviceSettingsProto& proto(builder->payload());
    proto.mutable_reboot_on_shutdown()->set_reboot_on_shutdown(
        reboot_on_shutdown);
  }

  // Refreshes device policy and waits for it to be applied.
  void SyncRefreshDevicePolicy() {
    run_loop_.reset(new base::RunLoop());
    DeviceSettingsService::Get()->AddObserver(this);
    RefreshDevicePolicy();
    run_loop_->Run();
    DeviceSettingsService::Get()->RemoveObserver(this);
    run_loop_.reset();
  }

  // Blocks until the OobeUI indicates that the javascript side has been
  // initialized.
  void WaitUntilOobeUIIsReady(OobeUI* oobe_ui) {
    ASSERT_TRUE(oobe_ui);
    base::RunLoop run_loop;
    const bool oobe_ui_ready = oobe_ui->IsJSReady(run_loop.QuitClosure());
    if (!oobe_ui_ready)
      run_loop.Run();
  }

  bool result_;
  std::unique_ptr<base::RunLoop> run_loop_;
  std::unique_ptr<ash::SystemTrayTestApi> tray_test_api_;
};

class ShutdownPolicyInSessionTest
    : public ShutdownPolicyBaseTest {
 protected:
  ShutdownPolicyInSessionTest() {}
  ~ShutdownPolicyInSessionTest() override {}

  // Opens the system tray menu. This creates the tray views.
  void OpenSystemTrayMenu() { tray_test_api_->ShowBubble(); }

  // Closes the system tray menu. This deletes the tray views.
  void CloseSystemTrayMenu() { tray_test_api_->CloseBubble(); }

  // Returns true if the shutdown button's tooltip matches |tooltip|.
  bool HasShutdownButtonTooltip(const std::string& tooltip) {
    base::string16 actual_tooltip =
        tray_test_api_->GetBubbleViewTooltip(ash::VIEW_ID_POWER_BUTTON);
    return base::UTF8ToUTF16(tooltip) == actual_tooltip;
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ShutdownPolicyInSessionTest);
};

// Tests that by default the shutdown button tooltip is "Shut down".
IN_PROC_BROWSER_TEST_F(ShutdownPolicyInSessionTest, TestBasic) {
  OpenSystemTrayMenu();
  EXPECT_TRUE(HasShutdownButtonTooltip("Shut down"));
  CloseSystemTrayMenu();
}

// Tests that enabling the reboot-on-shutdown policy changes the shutdown button
// tooltip to "restart". Note that the tooltip doesn't change dynamically if the
// menu is open during the policy change -- that's a rare condition and
// supporting it would add complexity.
//
// TODO(crbug.com/851208): Disabled test due to flakiness.
IN_PROC_BROWSER_TEST_F(ShutdownPolicyInSessionTest, DISABLED_PolicyChange) {
  // Change the policy to reboot and let it propagate over mojo to ash.
  UpdateRebootOnShutdownPolicy(true);
  SyncRefreshDevicePolicy();
  content::RunAllPendingInMessageLoop();

  OpenSystemTrayMenu();
  EXPECT_TRUE(HasShutdownButtonTooltip("Restart"));
  CloseSystemTrayMenu();

  // Change the policy to shutdown and let it propagate over mojo to ash.
  UpdateRebootOnShutdownPolicy(false);
  SyncRefreshDevicePolicy();
  content::RunAllPendingInMessageLoop();

  OpenSystemTrayMenu();
  EXPECT_TRUE(HasShutdownButtonTooltip("Shut down"));
  CloseSystemTrayMenu();
}

class ShutdownPolicyLockerTest : public ShutdownPolicyBaseTest {
 protected:
  ShutdownPolicyLockerTest() = default;
  ~ShutdownPolicyLockerTest() override = default;

  void SetUpInProcessBrowserTestFixture() override {
    ShutdownPolicyBaseTest::SetUpInProcessBrowserTestFixture();
    zero_duration_mode_.reset(new ui::ScopedAnimationDurationScaleMode(
        ui::ScopedAnimationDurationScaleMode::ZERO_DURATION));
  }

  void SetUpOnMainThread() override {
    ShutdownPolicyBaseTest::SetUpOnMainThread();

    // Bring up the locker screen.
    chromeos::ScreenLockerTester().Lock();
  }

  void TearDownOnMainThread() override {
    ScreenLocker::Hide();
    ShutdownPolicyBaseTest::TearDownOnMainThread();
  }

 private:
  std::unique_ptr<ui::ScopedAnimationDurationScaleMode> zero_duration_mode_;

  DISALLOW_COPY_AND_ASSIGN(ShutdownPolicyLockerTest);
};

IN_PROC_BROWSER_TEST_F(ShutdownPolicyLockerTest, TestBasic) {
  ScreenLockerTester tester;
  EXPECT_FALSE(tester.IsLockRestartButtonShown());
  EXPECT_TRUE(tester.IsLockShutdownButtonShown());
}

IN_PROC_BROWSER_TEST_F(ShutdownPolicyLockerTest, PolicyChange) {
  ScreenLockerTester tester;
  UpdateRebootOnShutdownPolicy(true);
  RefreshDevicePolicy();
  WaitForShutdownButtonVisibility(false);
  EXPECT_TRUE(tester.IsLockRestartButtonShown());

  UpdateRebootOnShutdownPolicy(false);
  RefreshDevicePolicy();
  WaitForShutdownButtonVisibility(true);
  EXPECT_FALSE(tester.IsLockRestartButtonShown());
}

class ShutdownPolicyLoginTest : public ShutdownPolicyBaseTest {
 protected:
  ShutdownPolicyLoginTest() = default;
  ~ShutdownPolicyLoginTest() override = default;

  // ShutdownPolicyBaseTest:
  void SetUpCommandLine(base::CommandLine* command_line) override {
    command_line->AppendSwitch(switches::kLoginManager);
    command_line->AppendSwitch(switches::kForceLoginManagerInTests);
  }

  void SetUpOnMainThread() override {
    ShutdownPolicyBaseTest::SetUpOnMainThread();

    content::WindowedNotificationObserver(
        chrome::NOTIFICATION_LOGIN_OR_LOCK_WEBUI_VISIBLE,
        content::NotificationService::AllSources()).Wait();
    LoginDisplayHost* host = LoginDisplayHost::default_host();
    ASSERT_TRUE(host);
    ASSERT_TRUE(host->GetOobeWebContents());

    // Wait for the login UI to be ready.
    WaitUntilOobeUIIsReady(host->GetOobeUI());
  }

  void TearDownOnMainThread() override {
    // If the login display is still showing, exit gracefully.
    if (LoginDisplayHost::default_host()) {
      base::ThreadTaskRunnerHandle::Get()->PostTask(
          FROM_HERE, base::BindOnce(&chrome::AttemptExit));
      RunUntilBrowserProcessQuits();
    }
  }

 private:
  DISALLOW_COPY_AND_ASSIGN(ShutdownPolicyLoginTest);
};

IN_PROC_BROWSER_TEST_F(ShutdownPolicyLoginTest, PolicyNotSet) {
  EXPECT_FALSE(ash::LoginScreenTestApi::IsRestartButtonShown());
  EXPECT_TRUE(ash::LoginScreenTestApi::IsShutdownButtonShown());
}

IN_PROC_BROWSER_TEST_F(ShutdownPolicyLoginTest, PolicyChange) {
  UpdateRebootOnShutdownPolicy(true);
  RefreshDevicePolicy();
  WaitForShutdownButtonVisibility(false);
  EXPECT_TRUE(ash::LoginScreenTestApi::IsRestartButtonShown());

  UpdateRebootOnShutdownPolicy(false);
  RefreshDevicePolicy();
  WaitForShutdownButtonVisibility(true);
  EXPECT_FALSE(ash::LoginScreenTestApi::IsRestartButtonShown());
}

}  // namespace chromeos


text:
[![pipeline status](https://gitlab.com/jsass/jsass/badges/master/pipeline.svg)](https://gitlab.com/jsass/jsass/commits/master)
[![Build Status](https://img.shields.io/travis/bit3/jsass/master.svg?style=flat&logo=travis)](https://travis-ci.org/bit3/jsass)
[![Build Status](https://cloud.drone.io/api/badges/bit3/jsass/status.svg)](https://cloud.drone.io/bit3/jsass)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/bit3/jsass/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/bit3/jsass/?branch=master)
[![Code Coverage](https://scrutinizer-ci.com/g/bit3/jsass/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/bit3/jsass/?branch=master)
[![Known Vulnerabilities](https://snyk.io/test/github/bit3/jsass/badge.svg)](https://snyk.io/test/github/bit3/jsass)
[![Documentation Status](https://readthedocs.org/projects/jsass/badge/?version=latest)](http://jsass.readthedocs.io/en/latest/)
[![Javadoc Status](https://javadocio-badges.herokuapp.com/io.bit3/jsass/badge.svg)](http://javadoc.io/doc/io.bit3/jsass/)

ATTENTION: ONLY MAINTENANCE, NO FURTHER DEVELOPMENT
===================================================

libsass has been [declared deprecated][libsass-deprecated] and there will be no further development!
This also ends the further development of jsass. It is not yet clear whether there will ever be an implementation based
on the [Sass embedded protocol][sass-embedded-protocol]. I recommend switching to [Webpack][webpack] or similar technologies!
This project will continue to be maintained for the time being and compatibility with newer Java versions will be ensured.
But please do not expect any further development on my part.

[libsass-deprecated]: https://sass-lang.com/blog/libsass-is-deprecated
[sass-embedded-protocol]: https://github.com/sass/embedded-protocol
[webpack]: https://webpack.js.org/

Java sass compiler
==================

Feature complete java sass compiler using [libsass][libsass] version 3.6.4.

The most advantage of jsass is to hide the libsass complexity from the developer and provide a more java like way.

For complete documentation, see [jsass.rtfd.org][jsass-docs].

[libsass]: https://github.com/sass/libsass
[jsass-docs]: http://jsass.rtfd.org/

Example
-------

There is a [webapp example](example/webapp) containing a servlet sample implementation, to illustrate the way you
may integrate jsass into your webapp.

Changelog
---------

You can find the changelog in our documentation at [jsass.rtfd.org/en/latest/changelog.html][changelog]

[changelog]: http://jsass.readthedocs.org/en/latest/changelog.html

Third party projects
--------------------

Third party projects using JSASS.

- [libsass-maven-plugin](https://gitlab.com/haynes/libsass-maven-plugin)
- [JSass Gradle Plugin](https://plugins.gradle.org/plugin/io.freefair.jsass-java)
- [lein-jsass (Clojure)](https://clojars.org/lein-jsass)
- [Deraen/sass4clj (Clojure)](https://github.com/Deraen/sass4clj)
- [oVirt](https://www.ovirt.org/)

Merge requests for further projects are welcome :-)

Compatibility Overview
----------------------

| Compatibility                              |                                                                      |
| -------------------------------------------|----------------------------------------------------------------------|
| ![Java 7][java7]                           | not supported, jsass uses Java 8 features like streams and lambdas!  |
| ![Java 8][java8]                           | fully supported                                                      |
| ![Java 11][java11]                         | fully supported and [tested][gitlab-ci] (gitlab ci)                  |
| **Linux**                                  |                                                                      |
| ![CentOS 6 (i686)][centos6_32]             | not supported (since jsass 5.7.4 the 32bit support was been removed) |
| ![CentOS 6 (x86_64)][centos6]              | fully supported and [tested][gitlab-ci] (gitlab ci)                  |
| ![CentOS 7 (x86_64)][centos7]              | fully supported and [tested][gitlab-ci] (gitlab ci)                  |
| ![ubuntu 16.04 (x86_64)][ubuntu16.04]      | fully supported and [tested][gitlab-ci] (gitlab ci)                  |
| ![ubuntu 18.04 (x86_64)][ubuntu18.04]      | fully supported and [tested][gitlab-ci] (gitlab ci)                  |
| ![Debian Stretch (x86_64)][debian-stretch] | fully supported and [tested][gitlab-ci] (gitlab ci)                  |
| ![Debian Buster (x86_64)][debian-buster]   | fully supported and [tested][gitlab-ci] (gitlab ci)                  |
| ![Debian Stretch (armhf32)][armhf32]       | experimental, [tests][drone-io] are failing (drone.io)               |
| ![Debian Stretch (aarch64)][aarch64]       | fully supported and [tested][drone-io] (drone.io)                    |
| **Windows**                                |                                                                      |
| ![Windows 32bit][windows32]                | not supported                                                        |
| ![Windows 64bit][windows64]                | fully supported and [tested][travis-ci] (travis ci)                  |
| **macOS**                                  |                                                                      |
| ![macOS][macos]                            | fully supported and [tested][travis-ci] (travis ci)                  |
| **Others**                                 |                                                                      |
| ![Solaris][solaris]                        | not supported                                                        |
| ![FreeBSD][freebsd]                        | not supported                                                        |

[java7]: https://img.shields.io/badge/Java-7-red.svg?style=flat
[java8]: https://img.shields.io/badge/Java-8-green.svg?style=flat
[java11]: https://img.shields.io/badge/Java-11-green.svg?style=flat

[centos6_32]: https://img.shields.io/badge/CentOS_6-x86-red.svg?style=flat
[centos6]: https://img.shields.io/badge/CentOS_6-x86__64-green.svg?style=flat
[centos7]: https://img.shields.io/badge/CentOS_7-x86__64-green.svg?style=flat

[ubuntu16.04]: https://img.shields.io/badge/ubuntu_16.04-x86__64-green.svg?style=flat
[ubuntu18.04]: https://img.shields.io/badge/ubuntu_18.04-x86__64-green.svg?style=flat

[debian-stretch]: https://img.shields.io/badge/Debian_Stretch-x86__64-green.svg?style=flat
[debian-buster]: https://img.shields.io/badge/Debian_Buster-x86__64-green.svg?style=flat

[armhf32]: https://img.shields.io/badge/Debian_Stretch-arm_(armhf32)-yellow.svg?style=flat
[aarch64]: https://img.shields.io/badge/Debian_Stretch-arm64_(aarch64)-green.svg?style=flat

[windows32]: https://img.shields.io/badge/Windows-32bit-red.svg?style=flat
[windows64]: https://img.shields.io/badge/Windows-64bit-green.svg?style=flat

[macos]: https://img.shields.io/badge/macOS-10+-green.svg?style=flat

[gitlab-ci]: https://gitlab.com/jsass/jsass/pipelines
[travis-ci]: https://travis-ci.org/bit3/jsass
[drone-io]: https://cloud.drone.io/bit3/jsass

[solaris]: https://img.shields.io/badge/Solaris-red.svg?style=flat
[freebsd]: https://img.shields.io/badge/FreeBSD-red.svg?style=flat

Testing Matrix
--------------

A matrix of all CI systems and jobs, used for testing.

|                                            | OpenJDK 8                                                                           | OpenJDK 11                                                                           | OpenJDK 13                                                                           |
|--------------------------------------------|-------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
| ![CentOS 6 (x86_64)][centos6]              | ![Gitlab CI / test-centos6-openjdk8][gitlab-ci-test-centos6-openjdk8]               | ![Gitlab CI / test-centos6-openjdk8][gitlab-ci-test-centos6-openjdk11]               | ![Gitlab CI / test-centos6-openjdk8][gitlab-ci-test-centos6-openjdk13]               |
| ![CentOS 7 (x86_64)][centos7]              | ![Gitlab CI / test-centos7-openjdk8][gitlab-ci-test-centos7-openjdk8]               | ![Gitlab CI / test-centos7-openjdk8][gitlab-ci-test-centos7-openjdk11]               | ![Gitlab CI / test-centos7-openjdk8][gitlab-ci-test-centos7-openjdk13]               |
| ![ubuntu 16.04 (x86_64)][ubuntu16.04]      | ![Gitlab CI / test-ubuntu16.04-openjdk8][gitlab-ci-test-ubuntu16.04-openjdk8]       | ![Gitlab CI / test-ubuntu16.04-openjdk8][gitlab-ci-test-ubuntu16.04-openjdk11]       | ![Gitlab CI / test-ubuntu16.04-openjdk8][gitlab-ci-test-ubuntu16.04-openjdk13]       |
| ![ubuntu 18.04 (x86_64)][ubuntu18.04]      | ![Gitlab CI / test-ubuntu18.04-openjdk8][gitlab-ci-test-ubuntu18.04-openjdk8]       | ![Gitlab CI / test-ubuntu18.04-openjdk8][gitlab-ci-test-ubuntu18.04-openjdk11]       | ![Gitlab CI / test-ubuntu18.04-openjdk8][gitlab-ci-test-ubuntu18.04-openjdk13]       |
| ![Debian Stretch (x86_64)][debian-stretch] | ![Gitlab CI / test-debian-stretch-openjdk8][gitlab-ci-test-debian-stretch-openjdk8] | ![Gitlab CI / test-debian-stretch-openjdk8][gitlab-ci-test-debian-stretch-openjdk11] | ![Gitlab CI / test-debian-stretch-openjdk8][gitlab-ci-test-debian-stretch-openjdk13] |
| ![Debian Buster (x86_64)][debian-buster]   | ![Gitlab CI / test-debian-buster-openjdk8][gitlab-ci-test-debian-buster-openjdk8]   | ![Gitlab CI / test-debian-buster-openjdk8][gitlab-ci-test-debian-buster-openjdk11]   | ![Gitlab CI / test-debian-buster-openjdk8][gitlab-ci-test-debian-buster-openjdk13]   |
| ![ARM (armhf32)][armhf32]                  | ![Drone.io / test-arm-openjdk8][drone.io-test-arm-openjdk8]                         | ![Drone.io / test-arm-openjdk8][drone.io-test-arm-openjdk11]                         |                                                                                |
| ![ubuntu 16.04 (aarch64)][aarch64]         | ![Drone.io / test-arm64-openjdk8][drone.io-test-arm64-openjdk8]                     | ![Drone.io / test-arm64-openjdk8][drone.io-test-arm64-openjdk11]                     |                                                                                |
| ![Windows 64bit][windows64]                |                                                                                | ![Travis CI / OS: Windows][travis-ci-os-windows]                                     |                                                                                |
| ![macOS][macos]                            |                                                                                | ![Travis CI / OS: macOS][travis-ci-os-macos]                                         |                                                                                |

[gitlab-ci-test-centos6-openjdk8]: https://img.shields.io/badge/Gitlab_CI-test--centos6--openjdk8-blue.svg?style=flat
[gitlab-ci-test-centos6-openjdk11]: https://img.shields.io/badge/Gitlab_CI-test--centos6--openjdk11-blue.svg?style=flat
[gitlab-ci-test-centos6-openjdk13]: https://img.shields.io/badge/Gitlab_CI-test--centos6--openjdk13-blue.svg?style=flat

[gitlab-ci-test-centos7-openjdk8]: https://img.shields.io/badge/Gitlab_CI-test--centos7--openjdk8-blue.svg?style=flat
[gitlab-ci-test-centos7-openjdk11]: https://img.shields.io/badge/Gitlab_CI-test--centos7--openjdk11-blue.svg?style=flat
[gitlab-ci-test-centos7-openjdk13]: https://img.shields.io/badge/Gitlab_CI-test--centos7--openjdk13-blue.svg?style=flat

[gitlab-ci-test-ubuntu16.04-openjdk8]: https://img.shields.io/badge/Gitlab_CI-test--ubuntu16.04--openjdk8-blue.svg?style=flat
[gitlab-ci-test-ubuntu16.04-openjdk11]: https://img.shields.io/badge/Gitlab_CI-test--ubuntu16.04--openjdk11-blue.svg?style=flat
[gitlab-ci-test-ubuntu16.04-openjdk13]: https://img.shields.io/badge/Gitlab_CI-test--ubuntu16.04--openjdk13-blue.svg?style=flat

[gitlab-ci-test-ubuntu18.04-openjdk8]: https://img.shields.io/badge/Gitlab_CI-test--ubuntu18.04--openjdk8-blue.svg?style=flat
[gitlab-ci-test-ubuntu18.04-openjdk11]: https://img.shields.io/badge/Gitlab_CI-test--ubuntu18.04--openjdk11-blue.svg?style=flat
[gitlab-ci-test-ubuntu18.04-openjdk13]: https://img.shields.io/badge/Gitlab_CI-test--ubuntu18.04--openjdk13-blue.svg?style=flat

[gitlab-ci-test-debian-stretch-openjdk8]: https://img.shields.io/badge/Gitlab_CI-test--debian--stretch--openjdk8-blue.svg?style=flat
[gitlab-ci-test-debian-stretch-openjdk11]: https://img.shields.io/badge/Gitlab_CI-test--debian--stretch--openjdk11-blue.svg?style=flat
[gitlab-ci-test-debian-stretch-openjdk13]: https://img.shields.io/badge/Gitlab_CI-test--debian--stretch--openjdk13-blue.svg?style=flat

[gitlab-ci-test-debian-buster-openjdk8]: https://img.shields.io/badge/Gitlab_CI-test--debian--buster--openjdk8-blue.svg?style=flat
[gitlab-ci-test-debian-buster-openjdk11]: https://img.shields.io/badge/Gitlab_CI-test--debian--buster--openjdk11-blue.svg?style=flat
[gitlab-ci-test-debian-buster-openjdk13]: https://img.shields.io/badge/Gitlab_CI-test--debian--buster--openjdk13-blue.svg?style=flat

[drone.io-test-arm-openjdk8]: https://img.shields.io/badge/Drone.io-test--arm--openjdk8-blue.svg?style=flat
[drone.io-test-arm-openjdk11]: https://img.shields.io/badge/Drone.io-test--arm--openjdk11-blue.svg?style=flat
[drone.io-test-arm-openjdk13]: https://img.shields.io/badge/Drone.io-test--arm--openjdk13-blue.svg?style=flat

[drone.io-test-arm64-openjdk8]: https://img.shields.io/badge/Drone.io-test--arm64--openjdk8-blue.svg?style=flat
[drone.io-test-arm64-openjdk11]: https://img.shields.io/badge/Drone.io-test--arm64--openjdk11-blue.svg?style=flat
[drone.io-test-arm64-openjdk13]: https://img.shields.io/badge/Drone.io-test--arm64--openjdk13-blue.svg?style=flat

[travis-ci-os-windows]: https://img.shields.io/badge/Travis_CI-OS:_Windows-blue.svg?style=flat
[travis-ci-os-macos]: https://img.shields.io/badge/Travis_CI-OS:_macOS-blue.svg?style=flat

Gradle tasks you should know
----------------------------

`gradle check` runs checkstyle, pmd, junit locally.

`gradle runDockerTests` runs junit tests on all docker containers.

`gradle buildNativeLibs` build the native libs, using our build docker container.

How to make a release
---------------------

```bash
$ ./gradlew clean release
$ git checkout $(git describe --abbrev=0)
$ ./gradlew clean uploadArchives
```

Dont forget to release the artifact from [staging repository](https://oss.sonatype.org/#stagingRepositories)!

License
-------

MIT-License