text:
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>ai.cookie</groupId>
        <artifactId>flink-tensorflow-parent</artifactId>
		<version>0.1-SNAPSHOT</version>
		<relativePath>..</relativePath>
	</parent>

	<artifactId>flink-tensorflow_2.11</artifactId>
	<name>flink-tensorflow</name>
	<packaging>jar</packaging>

	<dependencies>

		<!-- ARM -->
		<dependency>
			<groupId>com.jsuereth</groupId>
			<artifactId>scala-arm_2.11</artifactId>
			<version>${arm.version}</version>
		</dependency>

		<!-- Twitter Bijection -->
		<dependency>
			<groupId>com.twitter</groupId>
			<artifactId>bijection-core_2.11</artifactId>
			<version>${bijection.version}</version>
		</dependency>
		<dependency>
			<groupId>com.twitter</groupId>
			<artifactId>bijection-protobuf_2.11</artifactId>
			<version>${bijection.version}</version>
		</dependency>

		<!-- Apache Flink dependencies -->
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-scala_2.11</artifactId>
			<version>${flink.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-streaming-scala_2.11</artifactId>
			<version>${flink.version}</version>
			<scope>provided</scope>
		</dependency>
		<!--<dependency>-->
			<!--<groupId>org.ow2.asm</groupId>-->
			<!--<artifactId>asm</artifactId>-->
			<!--<version>${asm.version}</version>-->
		<!--</dependency>-->
		<!--<dependency>-->
			<!--<groupId>org.apache.flink</groupId>-->
			<!--<artifactId>flink-clients_2.11</artifactId>-->
			<!--<version>${flink.version}</version>-->
		<!--</dependency>-->
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-ml_2.11</artifactId>
			<version>${flink.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.flink</groupId>
			<artifactId>flink-test-utils_2.11</artifactId>
			<version>${flink.version}</version>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.apache.hadoop</groupId>
					<artifactId>hadoop-minikdc</artifactId>
				</exclusion>
			</exclusions>
		</dependency>

		<!-- TensorFlow dependencies -->
		<dependency>
			<groupId>org.tensorflow</groupId>
			<artifactId>tensorflow</artifactId>
			<version>${tf.version}</version>
		</dependency>
		<dependency>
			<groupId>org.tensorflow</groupId>
			<artifactId>proto</artifactId>
			<version>${tf.version}</version>
		</dependency>
		<dependency>
			<groupId>com.google.protobuf</groupId>
			<artifactId>protobuf-java</artifactId>
			<version>${protobuf.version}</version>
		</dependency>
		<dependency>
			<groupId>com.twitter</groupId>
			<artifactId>chill-protobuf</artifactId>
			<version>${chill.version}</version>
		</dependency>

		<!-- Logging dependencies -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>

		<!-- Test depencencies -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.scalatest</groupId>
			<artifactId>scalatest_${scala.binary.version}</artifactId>
			<version>${scalatest.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>${mockito.version}</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4</artifactId>
			<version>${powermock.version}</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-mockito</artifactId>
			<version>${powermock.version}</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hamcrest</groupId>
			<artifactId>hamcrest-all</artifactId>
			<version>${hamcrest.version}</version>
			<type>jar</type>
			<scope>test</scope>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>

			<plugin>
				<groupId>net.alchim31.maven</groupId>
				<artifactId>scala-maven-plugin</artifactId>
				<version>3.1.4</version>
				<executions>
					<execution>
						<goals>
							<goal>compile</goal>
							<goal>testCompile</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<!-- Adding scala source directories to build path -->
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>build-helper-maven-plugin</artifactId>
				<version>1.7</version>
				<executions>
					<!-- Add src/main/scala to eclipse build path -->
					<execution>
						<id>add-source</id>
						<phase>generate-sources</phase>
						<goals>
							<goal>add-source</goal>
						</goals>
						<configuration>
							<sources>
								<source>src/main/scala</source>
							</sources>
						</configuration>
					</execution>
					<!-- Add src/test/scala to eclipse build path -->
					<execution>
						<id>add-test-source</id>
						<phase>generate-test-sources</phase>
						<goals>
							<goal>add-test-source</goal>
						</goals>
						<configuration>
							<sources>
								<source>src/test/scala</source>
							</sources>
						</configuration>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.19.1</version>
				<configuration>
					<forkMode>once</forkMode>
					<!--<argLine>-Djava.library.path=${env.TF_HOME}/bazel-bin/tensorflow/java/</argLine>-->
				</configuration>
				<executions>
					<execution>
						<id>default-test</id>
						<phase>test</phase>
						<goals>
							<goal>test</goal>
						</goals>
						<configuration>
							<includes>
								<include>**/*ITCase.*</include>
							</includes>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>


text:
using static QuantConnect.StringExtensions;

namespace QuantConnect.Orders
{
    /// <summary>
    /// Represents a response to an <see cref="OrderRequest"/>. See <see cref="OrderRequest.Response"/> property for
    /// a specific request's response value
    /// </summary>
    public class OrderResponse
    {
        /// <summary>
        /// Gets the order id
        /// </summary>
        public int OrderId
        {
            get; private set;
        }

        /// <summary>
        /// Gets the error message if the <see cref="ErrorCode"/> does not equal <see cref="OrderResponseErrorCode.None"/>, otherwise
        /// gets <see cref="string.Empty"/>
        /// </summary>
        public string ErrorMessage
        {
            get; private set;
        }

        /// <summary>
        /// Gets the error code for this response.
        /// </summary>
        public OrderResponseErrorCode ErrorCode
        {
            get; private set;
        }

        /// <summary>
        /// Gets true if this response represents a successful request, false otherwise
        /// If this is an unprocessed response, IsSuccess will return false.
        /// </summary>
        public bool IsSuccess
        {
            get { return IsProcessed && !IsError; }
        }

        /// <summary>
        /// Gets true if this response represents an error, false otherwise
        /// </summary>
        public bool IsError
        {
            get { return IsProcessed && ErrorCode != OrderResponseErrorCode.None; }
        }

        /// <summary>
        /// Gets true if this response has been processed, false otherwise
        /// </summary>
        public bool IsProcessed
        {
            get { return this != Unprocessed; }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="OrderResponse"/> class
        /// </summary>
        /// <param name="orderId">The order id</param>
        /// <param name="errorCode">The error code of the response, specify <see cref="OrderResponseErrorCode.None"/> for no error</param>
        /// <param name="errorMessage">The error message, applies only if the <paramref name="errorCode"/> does not equal <see cref="OrderResponseErrorCode.None"/></param>
        private OrderResponse(int orderId, OrderResponseErrorCode errorCode, string errorMessage)
        {
            OrderId = orderId;
            ErrorCode = errorCode;
            if (errorCode != OrderResponseErrorCode.None)
            {
                ErrorMessage = errorMessage ?? "An unexpected error occurred.";
            }
        }

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>
        /// A string that represents the current object.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        public override string ToString()
        {
            if (this == Unprocessed)
            {
                return "Unprocessed";
            }

            if (IsError)
            {
                return Invariant($"Error: {ErrorCode} - {ErrorMessage}");
            }

            return "Success";
        }

        #region Statics - implicit(int), Unprocessed constant, reponse factory methods

        /// <summary>
        /// Gets an <see cref="OrderResponse"/> for a request that has not yet been processed
        /// </summary>
        public static readonly OrderResponse Unprocessed = new OrderResponse(int.MinValue, OrderResponseErrorCode.None, "The request has not yet been processed.");

        /// <summary>
        /// Helper method to create a successful response from a request
        /// </summary>
        public static OrderResponse Success(OrderRequest request)
        {
            return new OrderResponse(request.OrderId, OrderResponseErrorCode.None, null);
        }

        /// <summary>
        /// Helper method to create an error response from a request
        /// </summary>
        public static OrderResponse Error(OrderRequest request, OrderResponseErrorCode errorCode, string errorMessage)
        {
            return new OrderResponse(request.OrderId, errorCode, errorMessage);
        }

        /// <summary>
        /// Helper method to create an error response due to an invalid order status
        /// </summary>
        public static OrderResponse InvalidStatus(OrderRequest request, Order order)
        {
            return Error(request, OrderResponseErrorCode.InvalidOrderStatus,
                Invariant($"Unable to update order with id {request.OrderId} because it already has {order.Status} status.")
            );
        }

        /// <summary>
        /// Helper method to create an error response due to the "New" order status
        /// </summary>
        public static OrderResponse InvalidNewStatus(OrderRequest request, Order order)
        {
            return Error(request, OrderResponseErrorCode.InvalidNewOrderStatus,
                Invariant($"Unable to update or cancel order with id {request.OrderId} and status {order.Status} because the submit confirmation has not been received yet.")
            );
        }

        /// <summary>
        /// Helper method to create an error response due to a bad order id
        /// </summary>
        public static OrderResponse UnableToFindOrder(OrderRequest request)
        {
            return Error(request, OrderResponseErrorCode.UnableToFindOrder,
                Invariant($"Unable to locate order with id {request.OrderId}.")
            );
        }

        /// <summary>
        /// Helper method to create an error response due to a zero order quantity
        /// </summary>
        public static OrderResponse ZeroQuantity(OrderRequest request)
        {
            return Error(request, OrderResponseErrorCode.OrderQuantityZero,
                Invariant($"Unable to {request.OrderRequestType.ToLower()} order with id {request.OrderId} that has zero quantity.")
            );
        }

        /// <summary>
        /// Helper method to create an error response due to algorithm still in warmup mode
        /// </summary>
        public static OrderResponse WarmingUp(OrderRequest request)
        {
            return Error(request, OrderResponseErrorCode.AlgorithmWarmingUp,
                Invariant($"This operation is not allowed in Initialize or during warm up: OrderRequest.{request.OrderRequestType}. ") +
                "Please move this code to the OnWarmupFinished() method."
            );
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'rubygems'
require 'uri'
require 'net/http'
require 'httpclient'

# we need to be able to build an HTTPResponse object,
# and apparently, there's no way to do that outside of the HTTPResponse class
# WTF?
module HTTP
  class Message
    def body=(value)
      @body = value
    end
  end
end

# SPORE
class Spore

  attr_accessor :name, :author
  attr_accessor :base_url, :format, :version
  attr_accessor :methods
  attr_accessor :middlewares
  attr_reader :specs, :config

  class RequiredParameterExptected < Exception
  end

  class UnexpectedResponse < Exception
  end

  class UnsupportedSpec < Exception
  end

  class InvalidHeaders < Exception
  end

  ##
  # Initialize a Spore instance with a specification file

  # Optionally a file to require the parser from and the custom bound Parser class
  #
  # :call-seq:
  #   new(file_path, options = {} )
  #
  #   Spore.new('/tmp/github.json')
  #
  # or
  #
  #   Spore.new('/tmp/spec.dot', :require => 'my_custom_lib', :parser => 'DotParser')
  #
  # DotParser must implement a class method load_file
  #
  #   class DotParser
  #     def self.load_file(f)
  #       str = ""
  #       File.open(f) do |f|
  #         str = ...
  #         # Do what you have to here
  #       end
  #     end
  #   end
  #
  def initialize(spec,options = {})
    # Don't load gems that are not needed
    # Only When it requires json, then json is loaded
    parser = self.class.load_parser(spec, options)
    @config = options[:client_config] || {:ssl_verify_mode =>  OpenSSL::SSL::VERIFY_PEER | OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT }

    specs = parser.load_file(spec)

    inititliaze_api_attrs(specs)
    construct_client_class(self.methods)
    self.middlewares = []
  end

  ##
  # :call-seq:
  #   spore.enable(Spore::Middleware::SomeThing, :optionX => 42)
  #
  # This method takes a middleware class as its first argument.
  # Options to pass to the middleware can be given as a second
  # argument.
  # Once this method is called, the Spore client will pass the request
  # and the response objects to the middleware whenever appropriate.
  # The order in which middlewares are enabled is respected by Spore.
  # (same order for processing the request before it's sent, reverse
  # order for processing response, as described in the Spore
  # specification).
  #

  def enable(middleware, args={})
    m = middleware.new(args)
    self.middlewares.push({
      :condition => Proc.new { true },
      :middleware => m
    })
  end

  ##
  # :call-seq:
  #   spore.enable_if(Spore::Middleware::SomeThing, :optionX => 42) do |env| {
  #     # return true or false, depending on env to say if the
  #     # middleware should be enabled or not for this request
  # }
  #
  # Same as the enable method, but is enabled dynamically, depending
  # of the current request env.
  # A block is given and is passed the env stack, it should return a
  # boolean value to tell if the middleware should be enabled or not.
  #
  def enable_if(middleware, args={}, &block)
    m = middleware.new(args)
    self.middlewares.push({
      :condition => block,
      :middleware => m
    })
  end

  ##
  # :call-seq:
  #   load_parser(spec_file, options = {})
  #
  # This method takes two arguments spec_file and options

  # If spec is a yml or json file options is skipped

  # Else options is used for requiring and loading the correct parser

  # options is a Hash with :require and :parser keys.
  # *  :require is a file to require
  # *   :parser is a String to pass in Object.const_get
  #

  def self.load_parser(spec, options = {})
    case spec
    when /\.ya?ml/
      require('spore/spec_parser/yaml')
      Spore::SpecParser::Yaml
    when /\.json/
      require 'spore/spec_parser/json'
      Spore::SpecParser::Json
    else
      if options.has_key?(:require)
        require options[:require]
        if options.has_key?(:parser)
          Object.const_get(options[:parser])
        else
          Object.const_get(options[:require].to_s.capitalize)
        end
      else
        raise UnsupportedSpec, "don't know how to parse '#{spec}'"
      end
    end
  end

  private

  def inititliaze_api_attrs(spec)
    self.name = spec['name']
    self.author = spec['author']
    self.base_url = spec['base_url'].gsub(/\/$/, '')
    self.format = spec['format']
    self.version = spec['version']
    self.methods = spec['methods']
  end

  # FIXME : collapse methods
  # Hmmm I think it is not good
  # If we use Github API and Facebook API in the same project, methods may be overriden

  def construct_client_class(methods)
    methods.keys.each do |m|
      define_method(m, methods[m])
    end
  end

  def define_method(name, m)
    method = m['method'].downcase
    path = m['path']
    params = m['params']
    required = m['required_params'] || m['required']
    expected = m['expected']
    desc = m['description']

    mod = Module.new
    mod.send(:define_method, name) do |args|

      # make sure all mandatory params are sent
      required.each do |mandatory|
        if not args.has_key?(mandatory.to_sym)
          raise RequiredParameterExptected, "parameter `#{mandatory}' expected"
        end
      end

      # build the real path (expand named tokens)
      real_path = path
      while m = real_path.match(/:([^:\/\.]+)/)
        if not args.has_key?(m[1].to_sym)
          raise RequiredParameterExptected, "named token `#{m[1]}' expected"
        end
        real_path = real_path.gsub(/:#{m[1]}/, args[m[1].to_sym].to_s)
          args.delete(m[1].to_sym)
      end
      full_path = "#{self.base_url}#{real_path}"

      # build the ENV hash
      env = {}
      env['spore.request_method'] = method
      env['spore.request_path'] = full_path
      env['spore.request_params'] = args
      env['spore.request_headers'] = []

      response = nil

      # call all middlewares
      self.middlewares.each do |m|
        if m[:condition].call(env)
          response = m[:middleware].process_request(env)
          break if response
        end
      end

      # transoform the SPORE response to a valid HTTPResponse object
      if response
        response = to_http(response)
      end

      if not response

        res = send_http_request(
          env['spore.request_method'],
          env['spore.request_path'],
          env['spore.request_params'],
          env['spore.request_headers'])

          # parse the response and make sure we have expected result
          if expected && (not expected.include?(res.code.to_i))
            raise UnexpectedResponse, "response status: '#{res.code}' expected is: #{expected.to_json}"
          end

          response = res
      end

      # process response with middlewares in reverse orders
      self.middlewares.reverse.each do |m|
        if m[:condition].call(env)
          response = m[:middleware].process_response(response, env)
        end
      end

      response
    end
    self.extend(mod)
  end

  def send_http_request(method_name, path, params, headers)

    # our HttpClient object
    client = HTTPClient.new
    client.ssl_config.verify_mode = @config[:ssl_verify_mode]

    # normalize our headers for HttpClient
    h = headers.map{|header| header.values_at(:name,:value)}

    # the response object we expect to have
    resp = client.send(method_name,path, params, h) if method_name =~ %r{get|post|put|delete}

    return resp
  end

  def to_http(spore_resp)
    return nil if spore_resp.nil?
    return spore_resp if spore_resp.class != Array

    code    = spore_resp[0]
    headers = spore_resp[1]
    body    = spore_resp[2][0]

    if headers.size % 2 != 0
      raise InvalidHeaders, "Odd number of elements in SPORE headers"
    end

    r = Net::HTTPResponse.new('1.1', code, '')
    i = 0
    while i < headers.size
      header = headers[i]
      value  = headers[i+1]
      r.add_field(header, value)
      i += 2
    end

    r.body = body if body
    return r
  end
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Rhodophyllus platyspermus f. platyspermus Romagn. & Gilles

### Remarks
null


text:
/* global THREE */

window.createViewports = (() => {
  'use strict';

  const zero = new THREE.Vector3();

  return function viewports( element, {
    width = 128,
    height = 128,
    distance = 2,
  } = {} ) {
    return [ 'x', 'y', 'z' ].reduce( ( views, axis ) => {
      const renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setPixelRatio( window.devicePixelRatio );
      renderer.setSize( width, height );
      element.appendChild( renderer.domElement );

      const size = 1;
      const camera = new THREE.OrthographicCamera( -size, size, size, -size );
      camera.position[ axis ] = distance;
      camera.lookAt( zero );

      views[ axis ] = {
        renderer,
        camera,
      };

      return views;
    }, {} );
  };
})();


text:
<?php
namespace Chamilo\Core\Admin\Announcement\Integration\Chamilo\Core\Repository\Package;

use Chamilo\Configuration\Package\NotAllowed;

class Remover extends \Chamilo\Configuration\Package\Action\Remover implements NotAllowed
{
}


text:
package org.chaston.oakfunds.data;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
import com.google.inject.multibindings.Multibinder;
import org.chaston.oakfunds.account.AccountCode;
import org.chaston.oakfunds.account.AccountCodeManager;
import org.chaston.oakfunds.bootstrap.BootstrapTask;
import org.chaston.oakfunds.bootstrap.TransactionalBootstrapTask;
import org.chaston.oakfunds.ledger.Account;
import org.chaston.oakfunds.ledger.BankAccount;
import org.chaston.oakfunds.ledger.BankAccountType;
import org.chaston.oakfunds.ledger.ExpenseAccount;
import org.chaston.oakfunds.ledger.LedgerManager;
import org.chaston.oakfunds.ledger.RevenueAccount;
import org.chaston.oakfunds.storage.Record;
import org.chaston.oakfunds.storage.StorageException;
import org.chaston.oakfunds.storage.Store;
import org.chaston.oakfunds.system.SystemBootstrapModule;
import org.chaston.oakfunds.util.BigDecimalUtil;
import org.joda.time.DateTime;

/**
 * TODO(mchaston): write JavaDocs
 */
public class DataBootstrapModule extends AbstractModule {

  public static final int BOOTSTRAP_TASK_PRIORITY =
      SystemBootstrapModule.BOOTSTRAP_TASK_PRIORITY + 10;

  @Override
  protected void configure() {
    requireBinding(AccountCodeManager.class);
    requireBinding(LedgerManager.class);
    requireBinding(Store.class);

    Multibinder<BootstrapTask> bootstrapTaskBinder =
        Multibinder.newSetBinder(binder(), BootstrapTask.class);
    bootstrapTaskBinder.addBinding().to(DataBootstrapTask.class);
  }

  private static class DataBootstrapTask extends TransactionalBootstrapTask {
    private final AccountCodeManager accountCodeManager;
    private final LedgerManager ledgerManager;

    @Inject
    DataBootstrapTask(
        Store store,
        AccountCodeManager accountCodeManager,
        LedgerManager ledgerManager) {
      super(store);
      this.accountCodeManager = accountCodeManager;
      this.ledgerManager = ledgerManager;
    }

    @Override
    public String getName() {
      return "data";
    }

    @Override
    protected void bootstrapDuringTransaction() throws Exception {
      ImmutableMap<Integer, AccountCode> accountCodes = bootstrapAccountCodes();
      ImmutableMap<Integer, BankAccount> bankAccounts = bootstrapBankAccounts(accountCodes);
      addTransactions(bankAccounts.values());
      ImmutableMap<Integer, RevenueAccount> revenueAccounts =
          bootstrapRevenueAccounts(accountCodes, bankAccounts);
      addTransactions(revenueAccounts.values());
      ImmutableMap<Integer, ExpenseAccount> expenseAccounts =
          bootstrapExpenseAccounts(accountCodes, bankAccounts);
      addTransactions(expenseAccounts.values());
    }

    private ImmutableMap<Integer, AccountCode> bootstrapAccountCodes() throws StorageException{
      RecordMapBuilder<AccountCode> accountCodes = new RecordMapBuilder<>();
      accountCodes.add(accountCodeManager.createAccountCode(100, "First account code"));
      accountCodes.add(accountCodeManager.createAccountCode(200, "Second account code"));
      accountCodes.add(accountCodeManager.createAccountCode(300, "Third account code"));
      return accountCodes.build();
    }

    private ImmutableMap<Integer, BankAccount> bootstrapBankAccounts(
        ImmutableMap<Integer, AccountCode> accountCodes)
        throws StorageException {
      RecordMapBuilder<BankAccount> bankAccounts = new RecordMapBuilder<>();
      bankAccounts.add(ledgerManager.createBankAccount(accountCodes.get(100),
          "Current Account", BankAccountType.OPERATING));
      bankAccounts.add(ledgerManager.createBankAccount(accountCodes.get(100),
          "Reserve", BankAccountType.RESERVE));
      bankAccounts.add(ledgerManager.createBankAccount(accountCodes.get(100),
          "CD 1", BankAccountType.RESERVE));
      return bankAccounts.build();
    }

    private ImmutableMap<Integer, RevenueAccount> bootstrapRevenueAccounts(
        ImmutableMap<Integer, AccountCode> accountCodes,
        ImmutableMap<Integer, BankAccount> bankAccounts)
        throws StorageException {
      RecordMapBuilder<RevenueAccount> revenueAccounts = new RecordMapBuilder<>();
      revenueAccounts.add(ledgerManager.createRevenueAccount(accountCodes.get(200),
          "HOA Dues",
          Iterables.find(bankAccounts.values(),
              new Predicate<BankAccount>() {
                @Override
                public boolean apply(BankAccount bankAccount) {
                  return bankAccount.getTitle().equals("Current Account");
                }
              })));
      return revenueAccounts.build();
    }

    private ImmutableMap<Integer, ExpenseAccount> bootstrapExpenseAccounts(
        ImmutableMap<Integer, AccountCode> accountCodes,
        ImmutableMap<Integer, BankAccount> bankAccounts)
        throws StorageException {
      RecordMapBuilder<ExpenseAccount> expenseAccounts = new RecordMapBuilder<>();
      expenseAccounts.add(ledgerManager.createExpenseAccount(accountCodes.get(300),
          "Trash and Recycling",
          Iterables.find(bankAccounts.values(),
              new Predicate<BankAccount>() {
                @Override
                public boolean apply(BankAccount bankAccount) {
                  return bankAccount.getTitle().equals("Current Account");
                }
              })));
      return expenseAccounts.build();
    }

    private void addTransactions(ImmutableCollection<? extends Account> accounts)
        throws StorageException {
      int day = 3;
      long value = 1;
      for (Account account : accounts) {
        ledgerManager.recordTransaction(account,
            DateTime.parse("2014-12-" + day++).toInstant(),
            BigDecimalUtil.valueOf(value++ * 1000),
            "bootstrapped");
      }
    }

    @Override
    public int getPriority() {
      return BOOTSTRAP_TASK_PRIORITY;
    }
  }

  private static class RecordMapBuilder<T extends Record<T>> {
    private final ImmutableMap.Builder<Integer, T> records = ImmutableMap.builder();

    void add(T record) {
      records.put(record.getId(), record);
    }

    ImmutableMap<Integer, T> build() {
      return records.build();
    }
  }
}


text:
<!DOCTYPE html>

		<title>Common Validation Rule</title>
		<link rel="stylesheet" href="../../../codebase/webix.css" type="text/css" charset="utf-8">

		<link rel="stylesheet" type="text/css" href="../common/samples.css">

Cell validation

There must not be empty cells

		<input type="button" value="Add row" onclick="grid.add({ rank:-1, year:'', title:'', votes:'' })">


text:
using System.Collections.Generic;

namespace Nonagon.Modular.DynamicForm.FieldAttributes
{
	public class ChoicesFieldAttribute : IFieldAttribute
	{
		/// <summary>
		/// Gets the type of the field.
		/// </summary>
		/// <value>The type of the field.</value>
		public FieldType SupportedFieldType {
			get { return FieldType.Choices; }
		}

		/// <summary>
		/// Gets or sets the selectable items.
		/// </summary>
		/// <value>The selectable items.</value>
		public IEnumerable<SelectableItem> SelectableItems { get; set; }
	}
}


text:
//using System.Collections.Generic;
//using System.Linq;
//using Newtonsoft.Json;
//using Skybrud.Social.Gmail.Scopes;
//using Skybrud.Social.Google.Analytics.Scopes;
//using Skybrud.Social.Google.Scopes;
//using Skybrud.Social.GoogleCalendar.Scopes;
//using Skybrud.Social.GoogleDrive.Scopes;
//using Skybrud.Social.YouTube.Scopes;

//namespace Skybrud.Social.Umbraco.Models.Google {

//    public class GoogleScopeGroup {

//        [JsonProperty("name")]
//        public string Name { get; set; }

//        [JsonProperty("scopes")]
//        public GoogleScopeItem[] Scopes { get; set; }

//        public GoogleScopeGroup(string name, params GoogleScope[] scope) {
//            Name = name;
//            Scopes = scope.Select(x => new GoogleScopeItem(x)).ToArray();
//        }

//        public static GoogleScopeGroup[] GetAll() {

//            List<GoogleScopeGroup> groups = new List<GoogleScopeGroup>();

//            groups.Add(new GoogleScopeGroup("Basic", GoogleScopes.All));
//            groups.Add(new GoogleScopeGroup("Analytics", AnalyticsScopes.All));
//            groups.Add(new GoogleScopeGroup("Calendar", CalendarScopes.All));
//            groups.Add(new GoogleScopeGroup("Drive", DriveScopes.All));
//            groups.Add(new GoogleScopeGroup("Gmail", GmailScopes.All));
//            groups.Add(new GoogleScopeGroup("YouTube", YouTubeScopes.All));

//            return groups.ToArray();

//        }

//    }

//    public class GoogleScopeItem {

//        [JsonProperty("alias")]
//        public string Alias { get; set; }

//        [JsonProperty("name")]
//        public string Name { get; set; }

//        [JsonProperty("description")]
//        public string Description { get; set; }

//        public GoogleScopeItem(GoogleScope scope) {
//            Alias = scope.Alias;
//            Name = scope.Name;
//            Description = scope.Description;
//        }

//    }

//}


text:
{% extends "base.html" %}
{% load i18n %}
{% load url from future %}

{% block title %}团体列表{% endblock %}
{% block css %}
    <link rel="stylesheet" href="http://akbquiz.qiniudn.com/css/48g-colors.min.css">
    <link rel="stylesheet" href="{{STATIC_URL}}css/database.css">
{% endblock %}

{% block content %}

        {% for group in groups %}

{{group.groupname}}
 进入页面

组建时间:{{ group.founded|date:"Y年n月j日" }}

{{group.description}}

            队伍列表
            团体成员

        {% endfor %}

{% endblock %}


text:
require "rails_helper"

RSpec.describe MaintenancesController, type: :routing do
  describe "routing" do

    it "routes to #index" do
      expect(:get => "/maintenances").to route_to("maintenances#index")
    end

    it "routes to #new" do
      expect(:get => "/maintenances/new").to route_to("maintenances#new")
    end

    it "routes to #show" do
      expect(:get => "/maintenances/1").to route_to("maintenances#show", :id => "1")
    end

    it "routes to #edit" do
      expect(:get => "/maintenances/1/edit").to route_to("maintenances#edit", :id => "1")
    end

    it "routes to #create" do
      expect(:post => "/maintenances").to route_to("maintenances#create")
    end

    it "routes to #update" do
      expect(:put => "/maintenances/1").to route_to("maintenances#update", :id => "1")
    end

    it "routes to #destroy" do
      expect(:delete => "/maintenances/1").to route_to("maintenances#destroy", :id => "1")
    end

  end
end


text:
namespace {

const char kStringOne[] = "Once Upon A Time, ";
const char kStringTwo[] = "There was a std::string benchmark";

// We want to include negative numbers in the benchmark, so this function
// is used to count 0, 1, -1, 2, -2, 3, -3, ...
inline int IncrementAlternatingSign(int i) {
  return i > 0 ? -i : 1 - i;
}

void BM_Sum_By_StrCat(benchmark::State& state) {
  int i = 0;
  char foo[100];
  for (auto _ : state) {
    // NOLINTNEXTLINE(runtime/printf)
    strcpy(foo, absl::StrCat(kStringOne, i, kStringTwo, i * 65536ULL).c_str());
    int sum = 0;
    for (char* f = &foo[0]; *f != 0; ++f) {
      sum += *f;
    }
    benchmark::DoNotOptimize(sum);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_Sum_By_StrCat);

void BM_StrCat_By_snprintf(benchmark::State& state) {
  int i = 0;
  char on_stack[1000];
  for (auto _ : state) {
    snprintf(on_stack, sizeof(on_stack), "%s %s:%d", kStringOne, kStringTwo, i);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_StrCat_By_snprintf);

void BM_StrCat_By_Strings(benchmark::State& state) {
  int i = 0;
  for (auto _ : state) {
    std::string result =
        std::string(kStringOne) + " " + kStringTwo + ":" + absl::StrCat(i);
    benchmark::DoNotOptimize(result);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_StrCat_By_Strings);

void BM_StrCat_By_StringOpPlus(benchmark::State& state) {
  int i = 0;
  for (auto _ : state) {
    std::string result = kStringOne;
    result += " ";
    result += kStringTwo;
    result += ":";
    result += absl::StrCat(i);
    benchmark::DoNotOptimize(result);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_StrCat_By_StringOpPlus);

void BM_StrCat_By_StrCat(benchmark::State& state) {
  int i = 0;
  for (auto _ : state) {
    std::string result = absl::StrCat(kStringOne, " ", kStringTwo, ":", i);
    benchmark::DoNotOptimize(result);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_StrCat_By_StrCat);

void BM_HexCat_By_StrCat(benchmark::State& state) {
  int i = 0;
  for (auto _ : state) {
    std::string result =
        absl::StrCat(kStringOne, " ", absl::Hex(int64_t{i} + 0x10000000));
    benchmark::DoNotOptimize(result);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_HexCat_By_StrCat);

void BM_HexCat_By_Substitute(benchmark::State& state) {
  int i = 0;
  for (auto _ : state) {
    std::string result = absl::Substitute(
        "$0 $1", kStringOne, reinterpret_cast<void*>(int64_t{i} + 0x10000000));
    benchmark::DoNotOptimize(result);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_HexCat_By_Substitute);

void BM_FloatToString_By_StrCat(benchmark::State& state) {
  int i = 0;
  float foo = 0.0f;
  for (auto _ : state) {
    std::string result = absl::StrCat(foo += 1.001f, " != ", int64_t{i});
    benchmark::DoNotOptimize(result);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_FloatToString_By_StrCat);

void BM_DoubleToString_By_SixDigits(benchmark::State& state) {
  int i = 0;
  double foo = 0.0;
  for (auto _ : state) {
    std::string result =
        absl::StrCat(absl::SixDigits(foo += 1.001), " != ", int64_t{i});
    benchmark::DoNotOptimize(result);
    i = IncrementAlternatingSign(i);
  }
}
BENCHMARK(BM_DoubleToString_By_SixDigits);

}  // namespace


text:
import {
    COMPONENT_ADD,
    COMPONENTS_FETCH,
    COMPONENTS_FETCH_DONE,
    COMPONENTS_FETCH_FAILED,
    UPDATE_COMPONENT,
    DELETE_COMPONENT
} from '../constants';

export default function components (state: any = {
    all: [],
    userComponents: [],
    current: null,
    fetching: false
}, action: any) {
  switch (action.type) {
    case COMPONENT_ADD:
      return [
        ...state,
        action.data
      ]
    case DELETE_COMPONENT:

    case COMPONENTS_FETCH:
        return Object.assign({}, state, {
            fetching: true
        })
    case COMPONENTS_FETCH_DONE:
        return Object.assign({}, state, {
                all: action.data,
                fetching: false
        })
    case COMPONENTS_FETCH_FAILED:
        return Object.assign({}, state, {
            fetching: false
        })
    case UPDATE_COMPONENT:

    default:
      return state;
  }
};


text:
#ifndef BOARD_H__
#define BOARD_H__
#include <rtthread.h>
#include <SWM320.h>
#define SRAM_BASE 0x20000000
#define SRAM_SIZE 0x20000

#ifdef BSP_USING_EXT_SRAM
    #define EXT_SRAM_BASE SRAMM_BASE
    #define EXT_SRAM_SIZE BSP_EXT_SRAM_SIZE
    #define EXT_SRAM_BEGIN EXT_SRAM_BASE
    #define EXT_SRAM_END (EXT_SRAM_BASE + EXT_SRAM_SIZE)
#endif

#define SRAM_END (SRAM_BASE + SRAM_SIZE)
#if defined(__CC_ARM) || defined(__CLANG_ARM)
    extern int Image$$RW_IRAM1$$ZI$$Limit;
    #define HEAP_BEGIN ((void *)&Image$$RW_IRAM1$$ZI$$Limit)
#elif __ICCARM__
    #pragma section = "HEAP"
    #define HEAP_BEGIN (__segment_end("HEAP"))
#else
    extern int __bss_end;
    #define HEAP_BEGIN ((void *)&__bss_end)
#endif
#define HEAP_END SRAM_END
#define HEAP_SIZE (HEAP_END - (rt_uint32_t)HEAP_BEGIN)
extern void rt_hw_board_init(void);
#endif


text:
package hydrograph.ui.propertywindow.widgets.customwidgets;

import org.apache.commons.lang.StringUtils;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Cursor;
import org.slf4j.Logger;

import hydrograph.ui.common.property.util.Utils;
import hydrograph.ui.logging.factory.LogFactory;
import hydrograph.ui.propertywindow.property.ComponentConfigrationProperty;
import hydrograph.ui.propertywindow.property.ComponentMiscellaneousProperties;
import hydrograph.ui.propertywindow.propertydialog.PropertyDialogButtonBar;
import hydrograph.ui.propertywindow.widgets.gridwidgets.container.AbstractELTContainerWidget;

/**
 * Widget for Port_No in DB Components
 * @author Bitwise
 *
 */
public class PortWidget extends TextBoxWithLabelWidget{

	private PropertyDialogButtonBar propDialogButtonBar;
	private Cursor cursor;
	private AbstractELTContainerWidget container;
	private static final Logger logger = LogFactory.INSTANCE.getLogger(PortWidget.class);

	public PortWidget(ComponentConfigrationProperty componentConfigProp,
			ComponentMiscellaneousProperties componentMiscProps, PropertyDialogButtonBar propDialogButtonBar) {
		super(componentConfigProp, componentMiscProps, propDialogButtonBar);
		this.propDialogButtonBar = propDialogButtonBar;
	}

	@Override
	public void attachToPropertySubGroup(AbstractELTContainerWidget container) {
		this.container=container;
		super.attachToPropertySubGroup(container);

	}

	@Override
	protected void populateWidget() {
		Utils.INSTANCE.loadProperties();
		cursor = container.getContainerControl().getDisplay().getSystemCursor(SWT.CURSOR_HAND);

		logger.trace("Populating {} textbox", textBoxConfig.getName());
		String property = propertyValue;
		if(StringUtils.isNotBlank(property) ){
			textBox.setText(property);
			Utils.INSTANCE.addMouseMoveListener(textBox, cursor);
		}
		else{
			textBox.setText("");
			txtDecorator.show();
		}
	}
}


text:
package practicaltest01var04.eim.systems.cs.pub.ro.practicaltest01var04;

import android.app.SearchManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class PracticalTest01Var03ChooseNumber extends ActionBarActivity implements View.OnClickListener{
    private final static int SECONDARY_ACTIVITY_REQUEST_CODE = 2016;
    private EditText numberField ;
    private Button playButton;

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.playButton:

                try{

                    Intent intent = new Intent(getApplicationContext(), PracticalTest01Var02PlayActivity.class);
                    int enteredNumber = Integer.parseInt(numberField.getText().toString());
                    intent.putExtra("enteredNumber", enteredNumber);
                    startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);
                }catch(NumberFormatException e){

                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_practical_test01_var03_choose_number);

        numberField = (EditText)findViewById(R.id.numberField);
        playButton = (Button)findViewById(R.id.playButton);
        playButton.setOnClickListener(this);

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
"""
Fortify SSC API python wrapper.
"""

__title__ = "PyFortify"
__version__ = "0.1"
__author__ = "space"
__copyright__ = "camp"
__licence__ = "MIT"

import os
from .fortify import Connect


text:
<?php

namespace Cocorico\ReviewBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CocoricoReviewBundle extends Bundle
{
}


text:
.sales-example span {
    font-weight: bold;
}


text:
package com.siyeh.ipp.opassign.assignment;

class AssignmentAssign {
  void x(int i) {
    i <caret>+= i = 3;
  }
}


text:
<!DOCTYPE html>

    <title ng-bind="pageTitle"></title>
    <% styles.forEach( function ( file ) { %>
    <link rel="stylesheet" type="text/css" href="<%= file %>" /><% }); %>

    <% scripts.forEach( function ( file ) { %>
    <% }); %>

        Tasks

          Shuffle

          Backup

          License


text:
class CreateComments < ActiveRecord::Migration[5.0]
  def change
    create_table :comments do |t|
      t.text :body
      t.belongs_to :user
      t.belongs_to :commentable, polymorphic: true, index: true
      t.timestamps
    end
  end
end


text:
require 'spec_helper'

describe Api::V1::TasksHelper do
end


text:
import datetime
import functools
import operator
import random
import unittest

import genetic

def obtener_aptitud(genes):
    sumaDelGrupo1 = sum(genes[0:5])
    productoDelGrupo2 = functools.reduce(operator.mul, genes[5:10])
    duplicados = (len(genes) - len(set(genes)))
    return Aptitud(sumaDelGrupo1, productoDelGrupo2, duplicados)

def mostrar(candidato, horaInicio):
    diferencia = (datetime.datetime.now() - horaInicio).total_seconds()
    print("{} - {}\t{}\t{}".format(
        ', '.join(map(str, candidato.Genes[0:5])),
        ', '.join(map(str, candidato.Genes[5:10])),
        candidato.Aptitud,
        diferencia))

def mutar(genes, geneSet):
    if len(genes) == len(set(genes)):
        cuenta = random.randint(1, 4)
        while cuenta > 0:
            cuenta -= 1
            índiceA, índiceB = random.sample(range(len(genes)), 2)
            genes[índiceA], genes[índiceB] = genes[índiceB], genes[índiceA]
    else:
        índiceA = random.randrange(0, len(genes))
        índiceB = random.randrange(0, len(geneSet))
        genes[índiceA] = geneSet[índiceB]

class PruebasDeCartas(unittest.TestCase):
    def test(self):
        geneSet = [i + 1 for i in range(10)]
        horaInicio = datetime.datetime.now()

        def fnMostrar(candidato):
            mostrar(candidato, horaInicio)

        def fnObtenerAptitud(genes):
            return obtener_aptitud(genes)

        def fnMutar(genes):
            mutar(genes, geneSet)

        aptitudÓptima = Aptitud(36, 360, 0)
        mejor = genetic.obtener_mejor(fnObtenerAptitud, 10, aptitudÓptima,
                                      geneSet, fnMostrar,
                                      mutación_personalizada=fnMutar)
        self.assertTrue(not aptitudÓptima > mejor.Aptitud)

    def test_comparativa(self):
        genetic.Comparar.ejecutar(lambda: self.test())

class Aptitud:
    def __init__(self, sumaDelGrupo1, productoDelGrupo2, duplicados):
        self.SumaDelGrupo1 = sumaDelGrupo1
        self.ProductoDelGrupo2 = productoDelGrupo2
        diferenciaSuma = abs(36 - sumaDelGrupo1)
        diferenciaProducto = abs(360 - productoDelGrupo2)
        self.DiferenciaTotal = diferenciaSuma + diferenciaProducto
        self.Duplicados = duplicados

    def __gt__(self, otro):
        if self.Duplicados != otro.Duplicados:
            return self.Duplicados < otro.Duplicados
        return self.DiferenciaTotal < otro.DiferenciaTotal

    def __str__(self):
        return "sum: {} prod: {} dups: {}".format(
            self.SumaDelGrupo1,
            self.ProductoDelGrupo2,
            self.Duplicados)

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


text:
package com.github.terma.gigaspaceroutine.tasks;

import com.gigaspaces.async.AsyncResult;
import org.openspaces.core.executor.DistributedTask;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public abstract class SafeDistributedTask<R extends Serializable, T> implements DistributedTask<R, T> {

    @Override
    public T reduce(List<AsyncResult<R>> list) throws Exception {
        List<R> r = new ArrayList<>();
        for (AsyncResult<R> portion : list) {
            if (portion.getException() != null) throw new RuntimeException(portion.getException());
            r.add(portion.getResult());
        }
        return safeReduce(r);
    }

    protected abstract T safeReduce(List<R> list) throws Exception;

}


text:
import requests

from flask import request
from bson.objectid import ObjectId, InvalidId

from app import app
from app.config import *
from app.util import MongoUtil

def get_auth_info():
    """
    Get user's identity

    Verify the interity of token from the OAuth provider,
    then look up the database check if user exist or not.
    If the user does not exist, create a new user instead.

    :return: user instance
    """
    if 'Access-Token' not in request.headers:
        return None

    access_token = request.headers['Access-Token']
    if access_token is not None:
        # For development purpose only
        if access_token in app.config['TEST_TOKEN'].keys():
            user = MongoUtil.find_user(app.config['TEST_TOKEN'][access_token])
        else:
            # Check that the Access Token is valid.
            url = ('https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=%s'
                   % access_token)
            result = requests.get(url).json()
            if result.get('error_description') is not None:
                app.logger.debug('User {} failed to access the server'.format(access_token))
                return None
            user = MongoUtil.find_user(result['email'])

    if user is None:
        # if user does not exist, create a new user instead
        app.logger.info('Create User: {}'.format(user))
        first_name, last_name = get_user_profile(access_token)
        user = MongoUtil.create_user(result['email'], first_name, last_name)

    return user

def get_user_profile(access_token):
    url = 'https://www.googleapis.com/plus/v1/people/me?access_token={}'.format(access_token)
    result = requests.get(url).json()
    if result.get('error') is not None:
        return None
    return result['name']['givenName'], result['name']['familyName']

def validate_id(objectid):
    """
    Validate the incoming objectid of item
    :param objectid: The id in string
    :return: True/False
    """
    try:
        ObjectId(objectid)
    except InvalidId:
        return False

    return True

def check_group_read_permission(user):
    # Parse request
    req = get_request()

    if req is None:
        return None

    group_id = req.get('group_id', None)

    if group_id is None:
        return None

    if MongoUtil.check_user_in_group(user, group_id) is None:
        return None

    return user

def get_request():
    """
    Parse request, convert empty string or 'null' into None type in python
    :return:
    """
    if request.get_json() is not None:
        return {k: v if v != '' and v != 'null' else None for k, v in request.get_json().items()}


text:
package org.jbox2d.dynamics;

// updated to rev 100
/** This holds contact filtering data.
 *
 * @author daniel */
public class Filter {
	/** The collision category bits. Normally you would just set one bit. */
	public int categoryBits;

	/** The collision mask bits. This states the categories that this shape would accept for collision. */
	public int maskBits;

	/** Collision groups allow a certain group of objects to never collide (negative) or always collide (positive). Zero means no
	 * collision group. Non-zero group filtering always wins against the mask bits. */
	public int groupIndex;

	public Filter () {
		categoryBits = 0x0001;
		maskBits = 0xFFFF;
		groupIndex = 0;
	}

	public void set (Filter argOther) {
		categoryBits = argOther.categoryBits;
		maskBits = argOther.maskBits;
		groupIndex = argOther.groupIndex;
	}
}


text:
namespace views {
class ImageView;
class Label;
class MdTextButton;
class ImageButton;
class ProgressBar;
class FlexLayoutView;
class InkDropContainerView;
}  // namespace views

class DownloadShelfContextMenuView;
class DownloadBubbleUIController;

class DownloadBubbleRowView : public views::View,
                              public views::ContextMenuController,
                              public DownloadUIModel::Delegate,
                              public views::FocusChangeListener {
 public:
  METADATA_HEADER(DownloadBubbleRowView);

  explicit DownloadBubbleRowView(
      DownloadUIModel::DownloadUIModelPtr model,
      DownloadBubbleRowListView* row_list_view,
      DownloadBubbleUIController* bubble_controller,
      DownloadBubbleNavigationHandler* navigation_handler,
      Browser* browser);
  DownloadBubbleRowView(const DownloadBubbleRowView&) = delete;
  DownloadBubbleRowView& operator=(const DownloadBubbleRowView&) = delete;
  ~DownloadBubbleRowView() override;

  // Overrides views::View:
  void AddedToWidget() override;
  void RemovedFromWidget() override;
  void OnThemeChanged() override;
  void Layout() override;
  Views GetChildrenInZOrder() override;
  bool OnMouseDragged(const ui::MouseEvent& event) override;
  void OnMouseCaptureLost() override;
  void OnMouseEntered(const ui::MouseEvent& event) override;
  void OnMouseExited(const ui::MouseEvent& event) override;
  gfx::Size CalculatePreferredSize() const override;
  void AddLayerBeneathView(ui::Layer* layer) override;
  void RemoveLayerBeneathView(ui::Layer* layer) override;

  // Overrides views::FocusChangeListener
  void OnWillChangeFocus(views::View* before, views::View* now) override;
  void OnDidChangeFocus(views::View* before, views::View* now) override {}

  // Update the row and its elements for hover and focus events.
  void UpdateRowForHover(bool hovered);
  void UpdateRowForFocus(bool visible, bool request_focus_on_last_quick_action);

  // Overrides DownloadUIModel::Delegate:
  void OnDownloadOpened() override;
  void OnDownloadUpdated() override;
  void OnDownloadDestroyed(const ContentId& id) override;

  // Overrides views::ContextMenuController:
  void ShowContextMenuForViewImpl(View* source,
                                  const gfx::Point& point,
                                  ui::MenuSourceType source_type) override;

  DownloadUIModel* model() { return model_.get(); }

  DownloadUIModel::BubbleUIInfo& ui_info() { return ui_info_; }
  void SetUIInfoForTesting(DownloadUIModel::BubbleUIInfo ui_info) {
    ui_info_ = ui_info;
  }

 protected:
  // Overrides ui::LayerDelegate:
  void OnDeviceScaleFactorChanged(float old_device_scale_factor,
                                  float new_device_scale_factor) override;

 private:
  views::MdTextButton* AddMainPageButton(DownloadCommands::Command command,
                                         const std::u16string& button_string);
  views::ImageButton* AddQuickAction(DownloadCommands::Command command);
  views::ImageButton* GetActionButtonForCommand(
      DownloadCommands::Command command);

  // If there is any change in state, update UI info.
  // Returns whether the ui info was changed.
  bool UpdateBubbleUIInfo(bool initial_setup);

  // Update the DownloadBubbleRowView's members.
  void UpdateRow(bool initial_setup);

  void UpdateButtons();
  void UpdateProgressBar();
  void UpdateLabels();
  void RecordMetricsOnUpdate();
  void RecordDownloadDisplayed();

  // Load the icon, from the cache or from IconManager::LoadIcon.
  void LoadIcon();

  // Called when icon has been loaded by IconManager::LoadIcon.
  // |use_over_last_override| controls whether icon should be set if
  // the current icon is an override_icon.
  void SetIconFromImage(bool use_over_last_override, gfx::Image icon);
  void SetIconFromImageModel(bool use_over_last_override, ui::ImageModel icon);

  void OnCancelButtonPressed();
  void OnDiscardButtonPressed();
  void OnMainButtonPressed();

  // The icon for the file. We get platform-specific icons from IconLoader.
  raw_ptr<views::ImageView> icon_ = nullptr;
  raw_ptr<views::ImageView> subpage_icon_ = nullptr;
  raw_ptr<views::FlexLayoutView> subpage_icon_holder_ = nullptr;

  // The primary label.
  raw_ptr<views::Label> primary_label_ = nullptr;

  // The secondary label.
  raw_ptr<views::Label> secondary_label_ = nullptr;

  // Buttons on the main page.
  raw_ptr<views::MdTextButton> cancel_button_ = nullptr;
  raw_ptr<views::MdTextButton> discard_button_ = nullptr;
  raw_ptr<views::MdTextButton> keep_button_ = nullptr;
  raw_ptr<views::MdTextButton> scan_button_ = nullptr;
  raw_ptr<views::MdTextButton> open_now_button_ = nullptr;
  raw_ptr<views::MdTextButton> resume_button_ = nullptr;
  raw_ptr<views::MdTextButton> review_button_ = nullptr;
  raw_ptr<views::MdTextButton> retry_button_ = nullptr;

  // Quick Actions on the main page.
  raw_ptr<views::ImageButton> resume_action_ = nullptr;
  raw_ptr<views::ImageButton> pause_action_ = nullptr;
  raw_ptr<views::ImageButton> show_in_folder_action_ = nullptr;
  raw_ptr<views::ImageButton> cancel_action_ = nullptr;
  raw_ptr<views::ImageButton> open_when_complete_action_ = nullptr;

  // Holder for the main button.
  raw_ptr<views::FlexLayoutView> main_button_holder_ = nullptr;
  // Holder for the quick actions.
  raw_ptr<views::FlexLayoutView> quick_action_holder_ = nullptr;

  // The progress bar for in-progress downloads.
  raw_ptr<views::ProgressBar> progress_bar_ = nullptr;
  raw_ptr<views::FlexLayoutView> progress_bar_holder_ = nullptr;

  // Device scale factor, used to load icons.
  float current_scale_ = 1.0f;

  // Tracks tasks requesting file icons.
  base::CancelableTaskTracker cancelable_task_tracker_;

  // The model controlling this object's state.
  DownloadUIModel::DownloadUIModelPtr model_;

  // Reuse the download shelf context menu in the bubble.
  std::unique_ptr<DownloadShelfContextMenuView> context_menu_;

  // Parent row list view.
  raw_ptr<DownloadBubbleRowListView> row_list_view_ = nullptr;

  // Controller for keeping track of downloads.
  raw_ptr<DownloadBubbleUIController> bubble_controller_ = nullptr;

  raw_ptr<DownloadBubbleNavigationHandler> navigation_handler_ = nullptr;

  raw_ptr<Browser> browser_ = nullptr;

  download::DownloadItemMode mode_;
  download::DownloadItem::DownloadState state_;
  DownloadUIModel::BubbleUIInfo ui_info_;
  bool is_paused_;

  raw_ptr<const gfx::VectorIcon> last_overriden_icon_ = nullptr;
  bool already_set_default_icon_ = false;

  // Button for transparent button click, inkdrop animations and drag and drop
  // events.
  raw_ptr<views::Button> transparent_button_ = nullptr;

  raw_ptr<views::InkDropContainerView> inkdrop_container_;

  // Drag and drop:
  // Whether we are dragging the download bubble row.
  bool dragging_ = false;
  // Position that a possible drag started at.
  absl::optional<gfx::Point> drag_start_point_;

  // Whether the download's completion has already been logged. This is used to
  // avoid inaccurate repeated logging.
  bool has_download_completion_been_logged_ = false;

  base::WeakPtrFactory<DownloadBubbleRowView> weak_factory_{this};
};

#endif  // CHROME_BROWSER_UI_VIEWS_DOWNLOAD_BUBBLE_DOWNLOAD_BUBBLE_ROW_VIEW_H_


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

<TITLE>
com.numericalmethod.suanshu.matrix.doubles.operation (SuanShu 1.3.1 API Documentation)
</TITLE>

<META NAME="date" CONTENT="2011-04-26">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Tree
      Index
      Help

                SuanShu, a Java numerical and statistical library

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package com.numericalmethod.suanshu.matrix.doubles.operation

Class Summary

CreateMatrix
This class collects the utility functions to create a new matrix/vector from existing ones.

ElementaryOperation
There are three elementary row operations which are equivalent to left multiplying an elementary matrix.

Householder
A Householder transformation in the 3-dimensional space is the reflection of a vector in a plane.

Householder.Context
Context information about a <tt>Householder</tt> transformation.

ImmutableKroneckerProduct
This immutable version of KroneckerProduct is fast and efficient for
 construction and read-only operations.

Inverse
For a square matrix A,
 A-1,
 if the inverse exists.

KroneckerProduct
Given an m-by-n matrix A and a p-by-q matrix B,
 their Kronecker product C, also called their matrix direct product, is
 an (mp)-by-(nq) matrix with elements defined by

 cst = aij bkl

 where

 s = p(i - 1) + k

 t = q(j - 1) + l

MatrixUtils
This class collects a set of utility functions to operate on matrices.

Measure
A measure, μ, of a matrix, A, is a map from the DenseMatrix space to the real line.

Pow
This computes a square DenseMatrix A to the power of integer n, An.

PseudoInverse
The Moore–Penrose pseudoinverse of an m x n matrix A is A+.

SubMatrixRef
This class creates a 'reference' to a sub-part of a large matrix without copying it.

      Overview
    Package
      Class
      Tree
      Index
      Help

                SuanShu, a Java numerical and statistical library

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

                Copyright © 2011 Numerical Method Inc. Ltd. All Rights Reserved.


text:
<?php
namespace Ssg\Model;

use \Ssg\Core\DatabaseFactory;
use Ssg\Core\Model;
use Ssg\Core\Config;
use Ssg\Core\Text;
use Ssg\Core\Session;

/**
 * UserModel
 * Handles all the PUBLIC profile stuff. This is not for getting data of the logged in user, it's more for handling
 * data of all the other users. Useful for display profile information, creating user lists etc.
 */
class UserModel
{
    /**
     * Gets an array that contains all the users in the database. The array's keys are the user ids.
     * Each array element is an object, containing a specific user's data.
     * The avatar line is built using Ternary Operators, have a look here for more:
     * @see http://davidwalsh.name/php-shorthand-if-else-ternary-operators
     *
     * @return array The profiles of all users
     */
    public static function getPublicProfilesOfAllUsers()
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT user_id, user_name, user_email, user_active, user_has_avatar FROM tbl_users";
        $query = $database->prepare($sql);
        $query->execute();

        $all_users_profiles = array();

        foreach ($query->fetchAll() as $user) {
            $all_users_profiles[$user->user_id] = new stdClass();
            $all_users_profiles[$user->user_id]->user_id = $user->user_id;
            $all_users_profiles[$user->user_id]->user_name = $user->user_name;
            $all_users_profiles[$user->user_id]->user_email = $user->user_email;
            $all_users_profiles[$user->user_id]->user_active = $user->user_active;
            $all_users_profiles[$user->user_id]->user_avatar_link = (Config::get('USE_GRAVATAR') ? AvatarModel::getGravatarLinkByEmail($user->user_email) : AvatarModel::getPublicAvatarFilePathOfUser($user->user_has_avatar, $user->user_id));
        }

        return $all_users_profiles;
    }

    /**
     * Gets a user's profile data, according to the given $user_id
     * @param int $user_id The user's id
     * @return mixed The selected user's profile
     */
    public static function getPublicProfileOfUser($user_id)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT user_id, user_name, user_email, user_active, user_has_avatar
                FROM tbl_users WHERE user_id = :user_id LIMIT 1";
        $query = $database->prepare($sql);
        $query->execute(array(':user_id' => $user_id));

        $user = $query->fetch();

        if ($query->rowCount() == 1) {
            if (Config::get('USE_GRAVATAR')) {
                $user->user_avatar_link = AvatarModel::getGravatarLinkByEmail($user->user_email);
            } else {
                $user->user_avatar_link = AvatarModel::getPublicAvatarFilePathOfUser($user->user_has_avatar, $user->user_id);
            }
        } else {
            Session::add('feedback_negative', Text::get('FEEDBACK_USER_DOES_NOT_EXIST'));
        }

        return $user;
    }

    /**
     * @param $user_name_or_email
     *
     * @return mixed
     */
    public static function getUserDataByUserNameOrEmail($user_name_or_email)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $query = $database->prepare("SELECT user_id, user_name, user_email FROM tbl_users
                                     WHERE (user_name = :user_name_or_email OR user_email = :user_name_or_email)
                                           AND user_provider_type = :provider_type LIMIT 1");
        $query->execute(array(':user_name_or_email' => $user_name_or_email, ':provider_type' => 'DEFAULT'));

        return $query->fetch();
    }

    /**
     * Checks if a username is already taken
     *
     * @param $user_name string username
     *
     * @return bool
     */
    public static function doesUsernameAlreadyExist($user_name)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $query = $database->prepare("SELECT user_id FROM tbl_users WHERE user_name = :user_name LIMIT 1");
        $query->execute(array(':user_name' => $user_name));
        if ($query->rowCount() == 0) {
            return false;
        }
        return true;
    }

    /**
     * Checks if a email is already used
     *
     * @param $user_email string email
     *
     * @return bool
     */
    public static function doesEmailAlreadyExist($user_email)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $query = $database->prepare("SELECT user_id FROM tbl_users WHERE user_email = :user_email LIMIT 1");
        $query->execute(array(':user_email' => $user_email));
        if ($query->rowCount() == 0) {
            return false;
        }
        return true;
    }

    /**
     * Writes new username to database
     *
     * @param $user_id int user id
     * @param $new_user_name string new username
     *
     * @return bool
     */
    public static function saveNewUserName($user_id, $new_user_name)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $query = $database->prepare("UPDATE users SET user_name = :user_name WHERE user_id = :user_id LIMIT 1");
        $query->execute(array(':user_name' => $new_user_name, ':user_id' => $user_id));
        if ($query->rowCount() == 1) {
            return true;
        }
        return false;
    }

    /**
     * Writes new email address to database
     *
     * @param $user_id int user id
     * @param $new_user_email string new email address
     *
     * @return bool
     */
    public static function saveNewEmailAddress($user_id, $new_user_email)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $query = $database->prepare("UPDATE users SET user_email = :user_email WHERE user_id = :user_id LIMIT 1");
        $query->execute(array(':user_email' => $new_user_email, ':user_id' => $user_id));
        $count =  $query->rowCount();
        if ($count == 1) {
            return true;
        }
        return false;
    }

    /**
     * Edit the user's name, provided in the editing form
     *
     * @param $new_user_name string The new username
     *
     * @return bool success status
     */
    public static function editUserName($new_user_name)
    {
        // new username same as old one ?
        if ($new_user_name == Session::get('user_name')) {
            Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_SAME_AS_OLD_ONE'));
            return false;
        }

        // username cannot be empty and must be azAZ09 and 2-64 characters
        if (!preg_match("/^[a-zA-Z0-9]{2,64}$/", $new_user_name)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_DOES_NOT_FIT_PATTERN'));
            return false;
        }

        // clean the input, strip usernames longer than 64 chars (maybe fix this ?)
        $new_user_name = substr(strip_tags($new_user_name), 0, 64);

        // check if new username already exists
        if (UserModel::doesUsernameAlreadyExist($new_user_name)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_USERNAME_ALREADY_TAKEN'));
            return false;
        }

        $status_of_action = UserModel::saveNewUserName(Session::get('user_id'), $new_user_name);
        if ($status_of_action) {
            Session::set('user_name', $new_user_name);
            Session::add('feedback_positive', Text::get('FEEDBACK_USERNAME_CHANGE_SUCCESSFUL'));
            return true;
        } else {
            Session::add('feedback_negative', Text::get('FEEDBACK_UNKNOWN_ERROR'));
            return false;
        }
    }

    /**
     * Edit the user's email
     *
     * @param $new_user_email
     *
     * @return bool success status
     */
    public static function editUserEmail($new_user_email)
    {
        // email provided ?
        if (empty($new_user_email)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_FIELD_EMPTY'));
            return false;
        }

        // check if new email is same like the old one
        if ($new_user_email == Session::get('user_email')) {
            Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_SAME_AS_OLD_ONE'));
            return false;
        }

        // user's email must be in valid email format, also checks the length
        // @see http://stackoverflow.com/questions/21631366/php-filter-validate-email-max-length
        // @see http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address
        if (!filter_var($new_user_email, FILTER_VALIDATE_EMAIL)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_EMAIL_DOES_NOT_FIT_PATTERN'));
            return false;
        }

        // strip tags, just to be sure
        $new_user_email = substr(strip_tags($new_user_email), 0, 254);

        // check if user's email already exists
        if (UserModel::doesEmailAlreadyExist($new_user_email)) {
            Session::add('feedback_negative', Text::get('FEEDBACK_USER_EMAIL_ALREADY_TAKEN'));
            return false;
        }

        // write to database, if successful ...
        // ... then write new email to session, Gravatar too (as this relies to the user's email address)
        if (UserModel::saveNewEmailAddress(Session::get('user_id'), $new_user_email)) {
            Session::set('user_email', $new_user_email);
            Session::set('user_gravatar_image_url', AvatarModel::getGravatarLinkByEmail($new_user_email));
            Session::add('feedback_positive', Text::get('FEEDBACK_EMAIL_CHANGE_SUCCESSFUL'));
            return true;
        }

        Session::add('feedback_negative', Text::get('FEEDBACK_UNKNOWN_ERROR'));
        return false;
    }

    /**
     * Gets the user's id
     *
     * @param $user_name
     *
     * @return mixed
     */
    public static function getUserIdByUsername($user_name)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT user_id FROM tbl_users WHERE user_name = :user_name AND user_provider_type = :provider_type LIMIT 1";
        $query = $database->prepare($sql);

        // DEFAULT is the marker for "normal" accounts (that have a password etc.)
        // There are other types of accounts that don't have passwords etc. (FACEBOOK)
        $query->execute(array(':user_name' => $user_name, ':provider_type' => 'DEFAULT'));

        // return one row (we only have one result or nothing)
        return $query->fetch()->user_id;
    }

    /**
     * Gets the user's data
     *
     * @param $user_name string User's name
     *
     * @return mixed Returns false if user does not exist, returns object with user's data when user exists
     */
    public static function getUserDataByUsername($user_name)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        $sql = "SELECT user_id, user_name, user_email, user_password_hash, user_active, user_account_type,
                       user_failed_logins, user_last_failed_login
                  FROM tbl_users
                 WHERE (user_name = :user_name OR user_email = :user_name)
                       AND user_provider_type = :provider_type
                 LIMIT 1";
        $query = $database->prepare($sql);

        // DEFAULT is the marker for "normal" accounts (that have a password etc.)
        // There are other types of accounts that don't have passwords etc. (FACEBOOK)
        $query->execute(array(':user_name' => $user_name, ':provider_type' => 'DEFAULT'));

        // return one row (we only have one result or nothing)
        return $query->fetch();
    }

    /**
     * Gets the user's data by user's id and a token (used by login-via-cookie process)
     *
     * @param $user_id
     * @param $token
     *
     * @return mixed Returns false if user does not exist, returns object with user's data when user exists
     */
    public static function getUserDataByUserIdAndToken($user_id, $token)
    {
        $database = DatabaseFactory::getFactory()->getConnection();

        // get real token from database (and all other data)
        $query = $database->prepare("SELECT user_id, user_name, user_email, user_password_hash, user_active,
                                          user_account_type,  user_has_avatar, user_failed_logins, user_last_failed_login
                                     FROM tbl_users
                                     WHERE user_id = :user_id
                                       AND user_remember_me_token = :user_remember_me_token
                                       AND user_remember_me_token IS NOT NULL
                                       AND user_provider_type = :provider_type LIMIT 1");
        $query->execute(array(':user_id' => $user_id, ':user_remember_me_token' => $token, ':provider_type' => 'DEFAULT'));

        // return one row (we only have one result or nothing)
        return $query->fetch();
    }
}


text:
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.naming.NamingException;
import javax.swing.*;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;

/**
 * User interface of main window
 * @author User
 */
public class MainUI extends JFrame {

	private static final long serialVersionUID = -7524564950227284713L;
	private static ArrayList<PlayerInfo> currentPlayers = new ArrayList<PlayerInfo>();
	private JButton userProfileButton;
    private JButton playGameButton;
    private JButton leaderBoardButton;
    private JButton logoutButton;
    private JPanel MenuPanel;
    private JPanel mainPanel;
    private JPanel ContentPanel;
    private String username;
    private GameUserOp gameUserOp;
    private JMSHelper jmshelper;
	private MessageProducer queueSender;
	private MessageConsumer topicReceiver;
    private int status;
    //private String host;

    /**
     * Constructor of main window specifying the interface of functions fetched by RMI, the login name and host of server
     * @param loginName Login name
     * @param guo Interface of functions fetched by RMI
     * @param host Host of server for connection
     */
    public MainUI (String loginName, GameUserOp guo, String host) {
        username = loginName;
        gameUserOp = guo;
        try {
			jmshelper = new JMSHelper(host);
			queueSender = jmshelper.createQueueSender();
			topicReceiver = jmshelper.createTopicReader();
		} catch (NamingException | JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        //this.host = host;
        setTitle("JPoker 24-Game");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(800,600));
        setResizable(false);
        mainPanel = new MainPanel();
        setContentPane(mainPanel);
        userProfileButton.addActionListener(new UserProfileButtonListener());
        playGameButton.addActionListener(new PlayGameButtonListener());
        leaderBoardButton.addActionListener(new LeaderBoardButtonListener());
        logoutButton.addActionListener(new LogoutButtonListener());
        addWindowListener(new myWindowListener());
        setLocation(100,50);
        pack();
        setVisible(true);
    }

    /**
     * Main panel combining menu buttons and content interface
     * @author User
     *
     */
    private class MainPanel extends JPanel {

		private static final long serialVersionUID = 6204775178240754183L;

		/**
		 * Constructor of main panel
		 */
		private MainPanel(){
			MenuPanel = new MyMenuPanel();
			add(MenuPanel, BorderLayout.PAGE_START);
			ContentPanel = new UserProfilePanel(gameUserOp, username);
			add(ContentPanel, BorderLayout.CENTER);
			pack();
    	}
    }

    /**
     * Menu buttons layout
     * @author User
     *
     */
    private class MyMenuPanel extends JPanel {

		private static final long serialVersionUID = -3733711632285893549L;

		/**
		 * Constructor for menu buttons layout
		 */
		private MyMenuPanel(){
    		setLayout(new GridLayout(0,4));
    		setPreferredSize(new Dimension(800,40));
    		userProfileButton = new JButton("User Profile");
			add(userProfileButton);
			playGameButton = new JButton("Play Game");
			add(playGameButton);
			leaderBoardButton = new JButton("Leader Board");
			add(leaderBoardButton);
			logoutButton = new JButton("Logout");
			add(logoutButton);
			pack();
    	}
    }

    /**
     * Logout when window is closed
     * @author User
     *
     */
    private class myWindowListener extends WindowAdapter {

		/**
		 * Trigger logout action when window is closed
		 */
    	@Override
		public void windowClosing(WindowEvent e) {
			// TODO Auto-generated method stub
			logoutButton.doClick();
		}

    }

    /**
     * User profile button listener to open user profile in content interface
     * @author User
     *
     */
    private class UserProfileButtonListener implements ActionListener {

		/**
		 * Open user profile in content interface
		 */
    	@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			remove(ContentPanel);
			repaint();
			ContentPanel = new UserProfilePanel(gameUserOp, username);
			add(ContentPanel, BorderLayout.CENTER);
			invalidate();
			validate();
		}

    }

    /**
     * Play game button listener to open play game in content interface
     * @author User
     *
     */
    private class PlayGameButtonListener implements ActionListener {

		/**
		 * Open play game in content interface
		 */
    	@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			remove(ContentPanel);
			repaint();
			ContentPanel = new PlayGamePanel(gameUserOp, username, jmshelper, queueSender, topicReceiver);
			add(ContentPanel, BorderLayout.CENTER);
			invalidate();
			validate();
		}

    }

    /**
     * Leader board button listener to open leader board in content interface
     * @author User
     *
     */
    private class LeaderBoardButtonListener implements ActionListener {

		/**
		 * Open leader board in content interface
		 */
    	@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			remove(ContentPanel);
			repaint();
			ContentPanel = new LeaderBoardPanel(gameUserOp, username);
			add(ContentPanel, BorderLayout.CENTER);
			invalidate();
			validate();
		}

    }

    /**
     * Logout button listener to trigger RMI logout
     * @author User
     *
     */
    private class LogoutButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            new LogoutUpdater().execute();
        }
    }

    /**
     * Trigger RMI logout and output result
     * @author User
     *
     */
    private class LogoutUpdater extends SwingWorker<Void, Void> {
        @Override
        protected Void doInBackground() throws Exception {
            updateStatus();
            return null;
        }
        @Override
        protected void done(){
            if (status >= 0) {
            	setVisible(false);
            	System.exit(0);
                //SwingUtilities.invokeLater(new PostFix(host));
            }
        }
    }

    /**
     * Module responsible for RMI logout
     */
    private void updateStatus() {
        if (gameUserOp != null){
            try {
                status = gameUserOp.logout(username, currentPlayers);
            } catch (Exception e){
                JOptionPane.showMessageDialog(null, "Logout error",
                        "Error", JOptionPane.ERROR_MESSAGE);
                System.err.println("Register: "+e);
                System.exit(1);
            }
        }
    }

	public static ArrayList<PlayerInfo> getCurrentPlayers() {
		return currentPlayers;
	}

	public static void setCurrentPlayers(ArrayList<PlayerInfo> currentPlayers) {
		MainUI.currentPlayers = currentPlayers;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="fr_FR">
<context>
    <name>iotik::ruc::IotikRuCEnglishGeneratorPlugin</name>
    <message>
        <location filename="../../../../plugins/robots/generators/iotik/iotikRuCEnglishGenerator/iotikRuCEnglishGeneratorPlugin.cpp" line="29"/>
        <source>Generation (RuC) (English)</source>
        <translation>Génération (RuC) (Anglais)</translation>
    </message>
</context>
</TS>


text:
\section{Example data and Index computation process}

Our data model consists of a list of observations which can be raw observations
obtained from an external source or computed observations derived from other
observations. An example observation can be:

\begin{lstlisting}[style=SPARQL]
obs:obsM23 a qb:Observation ;
 cex:computation [ a cex:Z-Score ;
      cex:observation obs:obsA23 ; cex:slice slice:sliceA09 ; ] ;
 cex:value 0.56 ;
 cex:md5-checksum "2917835203..." ;
 cex:indicator indicator:A ;
 cex:concept country:ESP ;
 qb:dataSet dataset:A-Normalized ;
 # ... other declarations omitted for brevity
\end{lstlisting}

Where we declare that \lstinline|obs:obsM23| is an observation
 whose value is \lstinline|0.56| that has been obtained as the Z-Score
 of the observation \lstinline|obs:A23| using the slice
 \lstinline|slice:sliceA09|. The observations refers to indicator
 \lstinline|indicator:A|, to the concept \lstinline|country:ESP| and to the
 dataset \lstinline|dataset:A-Normalized|.

For each observation, we also add a value for
\lstinline|cex:md5-checksum| which is obtained as a combination of the
different values of the observation and allows a user to verify the
values asserted to that observation.

\section{Computex vocabulary}

The \emph{Computex} vocabulary is available
at~\url{http://purl.org/weso/computex}. It defines terms related to the
computation of statistical index data and is compatible with RDF Data Cube
vocabulary. Some terms defined in the vocabulary are:

\begin{itemize}
\item\textbf{\lstinline|cex:Concept|} represents the entities that we are
indexing.
In the case of the Web Index project, the concepts are the different countries.
In other applications it could be Universities, journals, services, etc.

\item\textbf{\lstinline|cex:Indicator|}. A dimension whose values add
information to the Index.
Indicators can be simple dimensions, for example: the mobile phone
suscriptions per 100 population, or can be composed from other
indicators.

\item\textbf{\lstinline|qb:Observation|}. This is the same term as in the
RDF Data Cube vocabulary. It contains values for the
properties: \lstinline|cex:value|, \lstinline|cex:indicator|
and \lstinline|cex:concept|, etc.
The value of a \lstinline|qb:Observation| can be a Raw value
   obtained from an external source or a computed value obtained from other
   observations.

\item\textbf{\lstinline|cex:Computation|}. We have declared the main computation
types that we needed for the WebIndex project, which have been summarized in
Table~\ref{table:computations}. That list of computation types is non-exhaustive
and can be further extended in the future.

\item\textbf{\lstinline|cex:WeightSchema|} a weight schema for a list of
indicators. It consists of a weight associated for each indicator which can be
used to compute an aggregated observation.

\end{itemize}

\begin{table*}[t]
\label{table:computations}
\begin{center}
\begin{tabular}{ p{0.2\textwidth} p{0.5\textwidth} p{0.3\textwidth}}
\toprule
Computation & Description & Properties \\
\hline
Raw			& No computation. Raw value obtained from external source.
			&  \\
Mean	    & Mean of a set of observations
			& \lstinline|cex:observation| \newline
			  \lstinline|cex:slice| \\
Increment	& Increment an observation by a given amount
			& \lstinline|cex:observation| \newline
			  \lstinline|cex:amount|  \\
Copy		& A copy of another observation
			& \lstinline|cex:observation| \\
Z-score		& A normalization of an observation using the values from a Slice.
			& \lstinline|cex:observation| \newline
			  \lstinline|cex:slice| \\
Ranking		& Position in the ranking of a slice of observations.
			& \lstinline|cex:observation| \newline
			  \lstinline|cex:slice| \\
AverageGrowth & Expected average growth of N observations
			  & \lstinline|cex:observations| \\
WeightedMean & Weighted mean of an observation
			& \lstinline|cex:observation| \newline
			  \lstinline|cex:slice|       \newline
			  \lstinline|cex:weightSchema| \\
\bottomrule\\
\end{tabular}
\caption{Some types of statistical computations}
\end{center}
\end{table*}

\section{Validation approach}

The validation approach employed in the 2012 WebIndex project was based on
 resource templates similar to the OSLC resource
 shapes\footnoteUrl{http://www.w3.org/2012/12/rdf-val/SOTA} and
 the MD5 checksum field.
 Apart from that, we did not verify that the precomputed values imported from
 the Excel sheets really match the value that could be obtained by
 following the declared computation process.

The new validation approach proposed in the paper goes a step forward.
The goal is not only to check that a resource contains
 a given set of fields and values, but also that those values really match
 the values that can be obtained by following the declared computations.

The proposed approach has been inspired by the integrity
constraint specification proposed by the RDF Data Cube vocabulary
which employs a set of SPARQL
 \lstinline|ASK| queries to check the integrity of RDF Data Cube data.
 Although \lstinline|ASK| queries provide a good means to check integrity, in
 practice their boolean nature does not offer too much help when a
 dataset does not accomplish with the data model.

 We decided to use \lstinline|CONSTRUCT| queries which, in case of error,
  contain an error message and a list of error parameters that can help to spot
  the problematic data.

 We transformed the \lstinline|ASK| queries defined in the RDF Data Cube
 specification to \lstinline|CONSTRUCT| queries. For example, the
 query to validate the RDF Data Cube integrity constraint 4 (IC-4) is:

\begin{lstlisting}[style=SPARQL]
CONSTRUCT {
 [ a cex:Error ; cex:errorParam [cex:name "dim"; cex:value ?dim ] ;
   cex:msg "Every Dimension must have a declared range" . ]
} WHERE { ?dim a qb:DimensionProperty .
  FILTER NOT EXISTS { ?dim rdfs:range [] }
}
\end{lstlisting}

In order to make our error messages compatible with EARL~\cite{EARL}, we have
 defined \lstinline|cex:Error| as a subclass of \lstinline|earl:TestResult| and
 declared it to have the value \lstinline|earl:failed| for the property
 \lstinline|earl:outcome|.

We have also created our own set of SPARQL \lstinline|CONSTRUCT| queries to
validate the \emph{Computex} vocabulary terms, specially the computation of index data.
For example, the following query validates that every observation
  has at most one value.

\begin{lstlisting}[style=SPARQL]
CONSTRUCT {
 [ a cex:Error ; cex:errorParam  # ... omitted
    cex:msg "Observation has two different values" . ]
} WHERE { ?obs a qb:Observation .
 ?obs cex:value ?value1 . ?obs cex:value ?value2 .
 FILTER ( ?value1 != ?value2  )
}
\end{lstlisting}

Using this approach, it is possible to define more expressive validations.
For example, we are able to validate that an observation has been obtained as
the mean of other observations.

\begin{lstlisting}[style=SPARQL]
CONSTRUCT {
 [ a cex:Error ; cex:errorParam # ...omitted
   cex:msg "Mean value does not match" ] .
} WHERE {
    ?obs a qb:Observation ;
         cex:computation ?comp ;
         cex:value ?val .
  ?comp a cex:Mean .
  { SELECT (AVG(?value) as ?mean) ?comp WHERE {
     ?comp cex:observation ?obs1 .
	 ?obs1 cex:value ?value ;
  } GROUP BY ?comp }
 FILTER( abs(?mean - ?val) > 0.0001)
}
\end{lstlisting}

\section{Expressivity limits of SPARQL queries}

Validating statistical computations using SPARQL queries offered
 a good exercise to check SPARQL expressivity. Although we were able
 to express most of the computation types, some of them had to employ functions
 that are not part of SPARQL 1.1 or had to be defined in a limited way.
 In this section we review some of the challenges that we found.

\begin{itemize}

\item The Z-score of a value $x_i$ is defined as $\frac{x - \bar{x}}{\sigma}$
where $\bar{x}$ is the mean and $\sigma=\sqrt{\frac{\sum_{i=1}^{N}(\bar{x}-x_i)^2}{N -
1}}$ is the standard deviation. To validate that computation using SPARQL
queries, it is necessary to employ the \lstinline|sqrt| function.
This function is not available in SPARQL 1.1 although some implementations
 like Jena
 ARQ\footnoteUrl{http://jena.apache.org/documentation/query/library-function.html}
 provide it.

\item In order to validate the ranking of an observation (in which position it
appears in a list of observations), we have found two approaches. One is to
check all the observations that are below the value of that observation.
This approach requires checking the value of each observation against all the
other values. The other approach is to use a subquery that groups all the
observations ordered by their value using the \lstinline|GROUP_CONCAT|.
However, SPARQL does not offer a function to calculate the position
of a substring in a string\footnote{This function is called \lstinline|strpos| in PHP or \lstinline|indexOf| in Java},
so we divided the length of the substring before the concept's
name by the length of the concept's name.
This approach is more efficient but only works when all the names have
the same length.

\item Given a list of values $x_1,x_2\ldots{}x_n$ the expected value
$x_{n+1}$ can be extrapolated using the forward average growth formula:
$x_n\times{\frac{\frac{x_{n}}{x_{n-1}}+\ldots{}+\frac{x_{2}}{x_1}}{n-1}}$.
Accessing RDF collections in SPARQL 1.1 requires property paths
and offers limited expressivity. In this particular case
the query can be expressed
as\footnote{This query was suggested by Joshua Taylor.}:

\begin{lstlisting}[style=SPARQL]
CONSTRUCT {
  # ... omitted for brevity
} WHERE {
  ?obs cex:computation [a cex:AverageGrowth; cex:observations ?ls] ;
  cex:value ?val .
  ?ls rdf:first [cex:value ?v1 ] .
  { SELECT ( SUM(?v_n / ?v_n1)/COUNT(*) as ?meanGrowth) WHERE {
      ?ls rdf:rest* [ rdf:first [ cex:value ?v_n ] ;
                      rdf:rest  [ rdf:first [ cex:value ?v_n1 ]]] .
  }}
 FILTER (abs(?meanGrowth * ?v1 - ?val) > 0.001) }
\end{lstlisting}

\end{itemize}


text:
<?xml version="1.0" encoding="UTF-8"?>
<flowconnector:FlowConnectorDefinition xmi:version="2.0" xmlns:xmi="http://www.omg.org/XMI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:flowconnector="http://www.founderfix.com/flowconnector" id="AutoSendMail" name="自动发送" note="自动发送邮件给当前处理人" categoryId="8cd83844-8779-4781-bff2-3f0c5b236117" icon="AutoSendMail.jpg">
  <input id="mailTitle" type="java.lang.String" mandatory="是" defaultValue=""/>
  <input id="mailContent" type="java.lang.String" mandatory="是" defaultValue=""/>
  <page id="page1" name="邮件参数" note="标题和内容不填写则使用默认标题和内容">
    <widget xsi:type="flowconnector:Text" id="Widget_0" name="邮件标题" inputId="mailTitle">
      <widgetExpression expressionValue=""/>
    </widget>
    <widget xsi:type="flowconnector:Text" id="Widget_1" name="邮件内容" inputId="mailContent">
      <widgetExpression expressionValue=""/>
    </widget>
  </page>
  <definitionImpl className="AutoSendMail" packageName="com.founder.fix.fixflow.expand.flowconnector.AutoSendMail"/>
</flowconnector:FlowConnectorDefinition>


text:
layout: leafletmap
title:  "Geosearch + marker in realtime"
date:   2017-05-10 20:12:00 -0300
categories: leaflet map openstreemap geosearch
---


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
Copyright 2020 The Chromium Authors
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<org.chromium.components.browser_ui.widget.MaterialCardViewNoShadow
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    style="@style/MaterialCardStyle">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="@dimen/no_content_padding">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="@dimen/no_content_text_padding"
            android:textAppearance="@style/TextAppearance.TextLarge.Primary"
            android:text="@string/discover_cant_refresh" />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="@style/TextAppearance.TextMedium.Secondary"
            android:text="@string/discover_cant_refresh_instructions" />
    </LinearLayout>
</org.chromium.components.browser_ui.widget.MaterialCardViewNoShadow>


text:
#ifndef DEMO_PANDORA_GUI_WAYPOINT_LABELER_H
#define DEMO_PANDORA_GUI_WAYPOINT_LABELER_H

#include <memory>
#include <vector>
#include <dpengine/scene/SceneNode.h>
#include "../RRTUpdateListener.h"

namespace DreadedPE
{
	class Material;
	class SceneManager;
	class SceneLeafModel;
	class Texture;
};

class RRT;
class TextBanner;

class WaypointLabeler : public DreadedPE::SceneNode, RRTUpdateListener
{
public:
	WaypointLabeler(DreadedPE::SceneManager& scene_manager, RRT& rrt, DreadedPE::SceneNode& parent);

	/**
	 * When the RRT is invalidated we remove all the scene leafs.
	 */
	void rrtInvalidated();

	/**
	 * When a new RRT is created we add all the new scene leafs.
	 */
	void rrtUpdated();

private:
	const RRT* rrt_;
	std::shared_ptr<DreadedPE::Material> material_;
	std::vector<DreadedPE::SceneLeafModel*> models_;
	DreadedPE::Texture* font_texture_;
};

#endif