text:
package linprogMPC.components;

import akka.basicMessages.AnswerContent;
import linprogMPC.components.prototypes.Producer;
import linprogMPC.helper.SolarRadiation;
import linprogMPC.messages.extension.NetworkType;
import linprogMPC.messages.planning.VolatileProducerMessage;

/**
 * Achtung SolarTheric ist ein Clon von PV, mit dem Unterschied, dass die geschickte message, den NetworkType Heat hat.
 * @author bytschkow
 *
 */
public class SolarThermic extends Producer {

	static double efficiency = 1.0;
	VolatileProducerMessage volatileProducerMessage;

	public SolarThermic(double installedPower, int port) {
		super(installedPower, efficiency, port); //qdot_max not used here
		volatileProducerMessage = new VolatileProducerMessage();
	}

	@Override
	public void makeDecision() {
		int cts = this.actor.getCurrentTimeStep();
		volatileProducerMessage.name = this.actorName;
		volatileProducerMessage.id = this.fullActorPath;
		volatileProducerMessage.operationalCostEUR = 0.00001;
		volatileProducerMessage.operationalCostCO2 = 0.0;
		volatileProducerMessage.efficiency = efficiency;
		volatileProducerMessage.maxPower = maxPower;
		volatileProducerMessage.networkType = NetworkType.HEAT;
		volatileProducerMessage.forecast = new double[nStepsMPC];

		SolarRadiation solarRadiation = new SolarRadiation();

		for (int i = 0; i < nStepsMPC; i++) {
			volatileProducerMessage.forecast[i] = solarRadiation.getSolarProductionPerKWp(cts+i)*maxPower;
		}
		super.updateDisplay(volatileProducerMessage);
	}

	@Override
	public AnswerContent returnAnswerContentToSend() {
		return volatileProducerMessage;
	}
}


text:
Pluggable Provisioning Mechanism
================================

Sahara can be integrated with 3rd party management tools like Apache Ambari
and Cloudera Management Console. The integration is achieved using the plugin
mechanism.

In short, responsibilities are divided between the Sahara core and a plugin as
follows. Sahara interacts with the user and uses Heat to provision OpenStack
resources (VMs, baremetal servers, security groups, etc.) The plugin installs
and configures a Hadoop cluster on the provisioned instances. Optionally,
a plugin can deploy management and monitoring tools for the cluster. Sahara
provides plugins with utility methods to work with provisioned instances.

A plugin must extend the `sahara.plugins.provisioning:ProvisioningPluginBase`
class and implement all the required methods. Read :doc:`plugin.spi` for
details.

The `instance` objects provided by Sahara have a `remote` property which
can be used to interact with instances. The `remote` is a context manager so
you can use it in `with instance.remote:` statements. The list of available
commands can be found in `sahara.utils.remote.InstanceInteropHelper`.
See the source code of the Vanilla plugin for usage examples.

redpajama_set_name: RedPajamaGithub


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

<mujoco>
  <!--
  the force sensor on body1 should register 2N (for the weight of both bodies).
  body2 is welded to body1 at an offset of 1m, so the torque sensor should register 1Nm.
  -->
  <option gravity="0 0 -1"/>

  <default>
    <!-- A cube of size 0.1^3 with density of 1000 has mass of 1. -->
    <geom size="0.05 0.05 0.05" type="box"/>
  </default>

  <worldbody>
    <body name="body1" euler="0 45 0">
      <geom/>
      <site name="sensor" euler="0 0 90"/>
    </body>
    <body name="body2" pos="0 1 0" euler="30 30 30">
      <joint type="free"/>
      <geom/>
    </body>
  </worldbody>

  <equality>
    <weld body1="body1" body2="body2"/>
  </equality>

  <sensor>
    <force site="sensor" user="0 1.41421356237 1.41421356237"/>
    <torque site="sensor" user="0 -0.70710678118 0.70710678118"/>
  </sensor>
</mujoco>


text:
using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {

	public bool player; // True = player 1, false = player 2, set via inspector

	Player1 player_1;
	Player2 player_2;

	// Use this for initialization
	void Start () {
		if(player == true){
			gameObject.AddComponent<Player1>();
			player_1 = gameObject.GetComponent<Player1>();
		}else if(player == false){
			gameObject.AddComponent<Player2>();
			player_2 = gameObject.GetComponent<Player2>();
		}
	}

	// Update is called once per frame
	void Update () {

	}
}


text:
from google.cloud import appengine_admin_v1

def sample_list_ingress_rules():
    # Create a client
    client = appengine_admin_v1.FirewallClient()

    # Initialize request argument(s)
    request = appengine_admin_v1.ListIngressRulesRequest(
    )

    # Make the request
    page_result = client.list_ingress_rules(request=request)

    # Handle the response
    for response in page_result:
        print(response)

# [END appengine_v1_generated_Firewall_ListIngressRules_sync]


text:
'''
Created on 2012-3-5

@author: zepheir
'''
import sys
sys.path.append('/app/srv/src')

from binascii import b2a_hex

try:
    from twisted.internet import epollreactor
    epollreactor.install()
except:
    pass

from twisted.internet import reactor
from twisted.python import log
from twisted.application import service

from zhyDB import ZhyDB

import Zoro
from ussop import temp_meter as TM
import time

import config
from config import *

# ECHO = True
# DEBUG = True

# 常量
zhy = ZhyDB()

# ElecMeterDict = zhy.listElecMeters(allSDS=None, allMods=True)
TempMeterDict = zhy.listTempMeters()
# factoryDict = {}
# modules = {}

class SampleServer(object):
    """docstring for SampleServer"""
    def __init__(self, *sds):
        super(SampleServer, self).__init__()
        self.sds = sds
        self.host,self.port = self.sds[0], int(self.sds[1])
        self.nowtype=''

        self.pointer = 0

        self.modules = 0
        self.mod = TM.Repeater(addr='000000000108')
        self.factory = Zoro.SetupTempRepeaterConnect(self.host, self.port, self.ReceiveData, reConnectMode=False)
        self.factory.spendtime = 10

        self.setup()

    def setup(self):
        # self.modules += ElecMeterDict[self.sds]
        self.sampletimer = ElectroMeterTimer
        if ECHO: print "*********** Time pass from start: %s"%(time.ctime()), self.factory.connection.getDestination(),self.factory.getState()

        self.pointer = zhy.readTempRepeaterPointer()

    def ReceiveData(self, *data):
        # if DEBUG: print ' ===> Received Data:', data
        # # global zhy
        _result = self.mod.realdata(data[2])
        if type(_result) == type({}):
            if 'pointer' in _result.keys():
                _pointer = int(_result['pointer'])
                print ' ===> Received Data:', data, _pointer
                # print '----------result---------',_result
                print data[0],data[1],zhy.updateTempRepeaterResult(
                        ip=data[1][0],
                        port=data[1][1],
                        addr=data[0],
                        value=_pointer
                    )
                self.modules = _pointer - self.pointer
            else:
                print ' ===> Received Data:', _result
                print data[0],data[1],zhy.updateTempMeterResults(
                    ip=data[1][0],
                    port=str(data[1][1]),
                    addr=_result['addr'],
                    value=_result['value']
                    )
        else:
            print ' ===> Received Data:', b2a_hex(data[2])

    def update(self):
        if DEBUG: print "[",self.sds,"] starting in the SampleServer Class!"

        if self.modules>0:
            print 'modules:',self.modules

            _cmd = self.mod.readRecordData(self.pointer)
            reactor.callLater(0.1, self.factory.protocol.SendCmd, _cmd)
            print b2a_hex(_cmd )

            self.modules = 0

        else:
            _cmd = self.mod.readRecordMount()
            zhy.setTempRepeaterState(
                ip=self.host,
                port=str(self.port),
                addr='000000000108',
                type='repeater',
                state='reading'
                )
            if DEBUG: print "===> Output command:",b2a_hex(_cmd)
            reactor.callLater(0.1, self.factory.protocol.SendCmd, _cmd)

        if SERVERRECONNECT:
            reactor.callLater(3, self.factory.connection.disconnect)
            reactor.callLater(8,self.factory.connection.connect)
        reactor.callLater(9,self.setup)
        reactor.callLater(10, self.update)
        # reactor.callLater(SdsConnectTimer+self.factory.spendtime, self.update)

servs ={}

def main():
    # for sds in ElecMeterDict:
    #     servs[sds]=SampleServer(sds[0],sds[1])
    #     servs[sds].update()
        # time.sleep(0.2)

    servs1=SampleServer('130.139.200.49','10003')
    # servs1.update()

if __name__ == '__main__':
    import sys

    main()

    reactor.run()
    print 'reactor stopped!'

    sys.exit(1)
elif __name__ =="__builtin__":
    import sys

    main()
    application = service.Application("TEMP1")


text:
[![Build Status](https://github.com/paulgoetze/weka-jruby/workflows/JRuby%20CI/badge.svg)](https://github.com/paulgoetze/weka-jruby/workflows/JRuby%20CI/badge.svg)
[![Gem Version](https://badge.fury.io/rb/weka.svg)](http://badge.fury.io/rb/weka)

Machine Learning & Data Mining with JRuby based on the
[Weka](http://www.cs.waikato.ac.nz/~ml/weka/index.html) Java library.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'weka'
```

And then execute:

    $ bundle install

Or install it yourself as:

    $ gem install weka

## Usage

Use Weka's Machine Learning and Data Mining algorithms by requiring the gem:

```ruby
require 'weka'
```

The weka gem tries to carry over the namespaces defined in Weka and enhances
some interfaces in order to allow a more Ruby-ish programming style when using
the Weka library.

The idea behind keeping the namespaces is, that you can also use the
[Weka documentation](http://weka.sourceforge.net/doc.dev/) for looking up
functionality and classes.

Please refer to [the gem's Wiki](https://github.com/paulgoetze/weka-jruby/wiki)
for detailed information about how to use weka with JRuby and some examplary
code snippets.

## Development

1. Check out the repo with `git clone git@github.com:paulgoetze/weka-jruby.git`.
2. Set a local environment variable `export JARS_VENDOR=false`. This will
   prevent compiling the jars into your repo's /lib directory and will load them
   from your local maven repository instead. See the
   [jar-dependencies README](https://github.com/mkristian/jar-dependencies#for-development-you-do-not-need-to-vendor-the-jars-at-all)
   for more information.
3. Run `bin/setup` or `bundle install` to install the dependencies.

Then, run `rake spec` to run the tests. You can also run `bin/console` or
`rake irb` for an interactive prompt that will allow you to experiment.

## Contributing

Bug reports and pull requests are welcome on GitHub at
https://github.com/paulgoetze/weka-jruby. This project is intended to be a safe,
welcoming space for collaboration, and contributors are expected to adhere to
the
[Contributor Covenant Code of Conduct](https://github.com/paulgoetze/weka-jruby/blob/main/CODE_OF_CONDUCT.md).

For development we use the
[git branching model](http://nvie.com/posts/a-successful-git-branching-model/)
described by [nvie](https://github.com/nvie).

Here's how to contribute:

1. Fork it (https://github.com/paulgoetze/weka-jruby/fork)
2. Create your feature branch (`git checkout -b feature/my-new-feature develop`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin feature/my-new-feature`)
5. Create a new Pull Request

Please try to add RSpec tests along with your new feature. This will ensure that
your code does not break existing functionality and that your feature is working
as expected.

We use [Rubocop](https://github.com/bbatsov/rubocop) for code style
recommendations. Please make sure your contributions comply with the project's
Rubocop config.

## Acknowledgement

The original ideas for wrapping Weka in JRuby come from
[@arrigonialberto86](https://github.com/arrigonialberto86) and his
[ruby-band](https://github.com/arrigonialberto86/ruby-band) gem. Great thanks!

## License

The gem is available as open source under the terms of the
[MIT License](https://github.com/paulgoetze/weka-jruby/blob/main/MIT-LICENSE.txt).


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Module: Selenium::WebDriver::Zipper

    — Documentation by YARD 0.8.3

</title>

  <link rel="stylesheet" href="../../css/style.css" type="text/css" media="screen" charset="utf-8" />

  <link rel="stylesheet" href="../../css/common.css" type="text/css" media="screen" charset="utf-8" />

    Index (Z) »
    Selenium » WebDriver
     »
    Zipper

(no frames)

      Class List

      Method List

      File List

Module: Selenium::WebDriver::Zipper

  Private

Defined in:

rb/lib/selenium/webdriver/common/zipper.rb

  This module is part of a private API.
  You should avoid using this module if possible, as it may be removed or be changed in the future.

Constant Summary

EXTENSIONS =

  This constant is part of a private API.
  You should avoid using this constant if possible, as it may be removed or be changed in the future.

%w[.zip .xpi]

      Class Method Summary
      (collapse)

      + (Object) unzip(path)

  private

      + (Object) zip(path)

  private

      + (Object) zip_file(path)

  private

Class Method Details

    + (<tt>Object</tt>) unzip(path)

  This method is part of a private API.
  You should avoid using this method if possible, as it may be removed or be changed in the future.

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# File 'rb/lib/selenium/webdriver/common/zipper.rb', line 17

def unzip(path)
  destination = Dir.mktmpdir("webdriver-unzip")
  FileReaper << destination

  Zip::ZipFile.open(path) do |zip|
    zip.each do |entry|
      to      = File.join(destination, entry.name)
      dirname = File.dirname(to)

      FileUtils.mkdir_p dirname unless File.exist? dirname
      zip.extract(entry, to)
    end
  end

  destination
end

    + (<tt>Object</tt>) zip(path)

  This method is part of a private API.
  You should avoid using this method if possible, as it may be removed or be changed in the future.

34
35
36
37
38
39
40
41
42
43
44
45

# File 'rb/lib/selenium/webdriver/common/zipper.rb', line 34

def zip(path)
  with_tmp_zip do |zip|
    ::Find.find(path) do |file|
      unless File.directory?(file)
        add_zip_entry zip, file, file.sub("#{path}/", '')
      end
    end

    zip.commit
    File.open(zip.name, "rb") { |io| Base64.strict_encode64 io.read }
  end
end

    + (<tt>Object</tt>) zip_file(path)

  This method is part of a private API.
  You should avoid using this method if possible, as it may be removed or be changed in the future.

47
48
49
50
51
52
53
54

# File 'rb/lib/selenium/webdriver/common/zipper.rb', line 47

def zip_file(path)
  with_tmp_zip do |zip|
    add_zip_entry zip, path, File.basename(path)

    zip.commit
    File.open(zip.name, "rb") { |io| Base64.strict_encode64 io.read }
  end
end

  Generated on Mon Jan 21 19:22:43 2013 by
  yard
  0.8.3 (ruby-1.9.3).


text:
import sys
import os
import numpy as np
import shutil
from common import PostProcess, update_metrics_in_report_json
from common import read_limits, check_limits_and_add_to_report_json
from common import VirtualVehicleMakeMetrics as VVM

def main():
    mat_file_name = sys.argv[1]
    if not os.path.exists(mat_file_name):
        raise IOError('Given result file does not exist: {0}'.format(sys.argv[1]))
    else:
        dstpath = os.path.join(os.getcwd(), 'matfiles')
        if not os.path.isdir(dstpath):
            os.makedirs(dstpath)
        numFiles = len(os.listdir(dstpath))
        dstname = '_' + str(numFiles) + mat_file_name
        shutil.copyfile(mat_file_name, os.path.join(dstpath, dstname))

    ## First limit part
    limit_dict, filter = read_limits()
    ## End of first limit part

    ## Post processing part
    #--------accelerations-----------------------------------------------
    pos_uri = 'DriveTrain.r'
    filter.append(pos_uri)
    currentDistance_uri = 'DriveTrain.ACC.currentDistance'
    filter.append(currentDistance_uri)
    targetDistance_uri = 'DriveTrain.ACC.TargetDistance.y'
    filter.append(targetDistance_uri)

    vel_uri = 'DriveTrain.vel'
    filter.append(vel_uri)
    #desired_uri = 'DriveTrain.ACC.differenceTargetAndCurrentSpeed.u2' #This is the general setpoint. It takes velocity or a distance that has been converted to a velocity
    v_desired_uri = 'DriveTrain.targetSpeed'
    filter.append(v_desired_uri)
    #LeaderTargetVelocity_uri = 'LeaderTargetVelocity'
    LeaderTargetVelocity_uri = 'vehicleAhead.Velocity'
    filter.append(LeaderTargetVelocity_uri)

    a_uri = 'DriveTrain.a'
    filter.append(a_uri)

    jerk_uri = 'DriveTrain.j'
    filter.append(jerk_uri)

    gear_uri = "DriveTrain.current_gear"
    filter.append(gear_uri)

    followTime_uri = 'DriveTrain.followTime'
    filter.append(followTime_uri)
    FCC_uri = 'FOLLOWER_CRUISE_CONTROL'
    filter.append(FCC_uri)

    #--- Force, torque and rolling radius for front and rear tires. The two front wheels are the same so we only pull one of them
    # To find the vehicle weight the value needs to multiplied by two.
    wheelF_Force_uri = 'DriveTrain.wheelF_Force'
    wheelR_Force_uri = 'DriveTrain.wheelR_Force'
    wheelF_Torque_uri = 'DriveTrain.wheelF_Torque'
    wheelR_Torque_uri = 'DriveTrain.wheelR_Torque'
    wheelF_RollRadius_uri = 'DriveTrain.wheelF_RollRadius'
    wheelR_RollRadius_uri = 'DriveTrain.wheelR_RollRadius'
    filter.extend((wheelF_Force_uri, wheelR_Force_uri, wheelF_RollRadius_uri, wheelR_RollRadius_uri))
    #chassis_type_uri = 'DriveTrain.chassisType'
    #---------------------------------------------------------------------------------
    #                  Processing
    #---------------------------------------------------------------------------------
    # loads results with the filtered out variables (and 'time' which is default)
    pp = VVM(mat_file_name, filter)
    #---------------------------------------------------------------------------------
    #                  SETUP
    #---------------------------------------------------------------------------------
    start_time = 5 #time from which we start averaging
    endTime = pp.time[-1] #last time in data sequence
    startIndex = pp.get_index_from_time(start_time) #ignore data while system falls into place.
    time_inc = .1 #step size for rolling average
    a_bar = 0
    jerk_bar = 0
    tolerance = 0.01 # controls when set point detection occurs
    rise_tol = .1 # rise time set at 100*(1- rise_tol) of set point
    settle_tol = 0.1 # settle time within 100*(1- settle_tol) of set point.

    #---------------------------------------------------------------------------------
    #                  vehicleMass
    #---------------------------------------------------------------------------------
    wheelF_Force = pp.get_data_by_index(wheelF_Force_uri, -1)
    print "Front wheel load: %d" %wheelF_Force
    wheelR_Force = pp.get_data_by_index(wheelR_Force_uri, -1)
    print "Rear wheel load: %d" %wheelR_Force
    vehicleMass = 2*( wheelF_Force + wheelR_Force)/9.81
    #---------------------------------------------------------------------------------
    #                 Distance traveled
    #---------------------------------------------------------------------------------
    distanceTraveled = pp.get_data_by_index(pos_uri, -1)
    print "Distance traveled: %d" %distanceTraveled
    #---------------------------------------------------------------------------------
    #                  minumum following distance
    #---------------------------------------------------------------------------------
    minDistance = pp.get_local_min(currentDistance_uri, startIndex, -1)
    print "minDistance is : %f" %minDistance
    minDistanceIndex = pp.get_local_min_index(currentDistance_uri, startIndex, -1)
    #print "minDistanceIndex is: %d" %minDistanceIndex
    minDistanceVelocity = pp.get_data_by_index(vel_uri, minDistanceIndex)
    #---------------------------------------------------------------------------------
    #                 initial and final velocity
    #---------------------------------------------------------------------------------
    V0 = pp.get_data_by_index(vel_uri, 0)
    print "initial velocity: %f" %V0
    Vf = pp.get_data_by_index(vel_uri, -1)
    print "final velocity: %f" %Vf
    #---------------------------------------------------------------------------------
    #                  requiredTorque
    #---------------------------------------------------------------------------------
    forceExerted = vehicleMass*(Vf**2-V0**2)/(2*distanceTraveled) # Fd = (1/2)m(V^2) Work formula solve for force
    print "forece Exerted if uniform: %d" %forceExerted
    requiredTorque = forceExerted*(.5*(pp.get_data_by_index(wheelF_RollRadius_uri, -1) + pp.get_data_by_index(wheelR_RollRadius_uri, -1)))
    print "requiredTorque if uniform: %d" %requiredTorque
    #---------------------------------------------------------------------------------
    #                  Rise time, Overshoot, Settling time, RMS Error
    #                  Setpoint Crossings for REGULAR CRUISE CONTROL
    #---------------------------------------------------------------------------------
    SETPOINT = ''
    CURRENT =''
    #print type(desired_uri)
    if (pp.get_data_by_index(FCC_uri, -1) == 1 and pp.get_data_by_index(currentDistance_uri, -1)<=150):
        #print "HERE"
        #SETPOINT = targetDistance_uri #this data set varies if there is a vehicle ahead based on primary vehicles speed
        #CURRENT = currentDistance_uri
        SETPOINT = LeaderTargetVelocity_uri
        CURRENT = vel_uri
        #print SETPOINT
    else:
        SETPOINT = v_desired_uri # this data is constant
        CURRENT = vel_uri

    print SETPOINT
    #--the negative 1 gets the last/only value in the array.--
    riseTime =pp.calculate_rise_time(CURRENT, SETPOINT, start_time, tolerance, rise_tol)[-1]
    #calculate_rise_time(self, actual_name, setpoint_name, start_time = 0, tolerance = 0.01, rise_tol = 0.05, changes_allowed = 100, num_index = 1)
    print "rise time: %d" %riseTime
    #--the zero gets the first value in the array.--
    Overshoot = (100*pp.calculate_overshoot(CURRENT, SETPOINT, start_time)[-1])
    print "Percent Overshoot: %f" %Overshoot
    SettlingTime = pp.calculate_settling_time(CURRENT, SETPOINT, start_time, tolerance, settle_tol)[-1]
    #calculate_settling_time(self, actual_name, setpoint_name, start_time = 0, tolerance = 0.01, settle_tol = 0.05, changes_allowed = 100, num_index = 2):
    print "SettlingTime: %f" %SettlingTime
    RMS_error = pp.calculate_rmse(CURRENT, SETPOINT,startIndex)
    print "RMS_error: %d" %RMS_error
    #numSetPointCrossings = pp.calculate_settling_crossing(CURRENT, SETPOINT, start_time)[-1]
    #print "numSetPointCrossings: %d" %numSetPointCrossings
    # don't know what this function was doing but it wasn't what i was after.

    #--------------SETPOINT CROSSINGS--------------------------
    TargetArray = pp.short_array(SETPOINT, startIndex, -1)
    #print TargetArray
    #print TargetArray[0]
    #print TargetArray[-1]
    CurrentArray = pp.short_array(CURRENT, startIndex, -1)
    numSetPointCrossings = 0
    sign = 1
    index = 0
    if CurrentArray[0] < TargetArray[0]:
        sign = -1

    for i in xrange(len(CurrentArray)):
        diff = CurrentArray[i] -TargetArray[i]

        if(TargetArray[i] != TargetArray[i-1]):
            #print "Set point change, adjust sign."
            #print "sign: %d" %sign
            if CurrentArray[i] < TargetArray[i]:
                sign = -1
            else: sign = 1
            #print "sign: %d" %sign

        if (diff * sign < 0):
            sign = -sign
            #print "sign"
            #print i
            #print TargetArray[i]
            #print CurrentArray[i]
            numSetPointCrossings += 1

    print "numSetPointCrossings: %d" %numSetPointCrossings
    #distance_desired = pp.short_array(distance_targetDistance_uri, start_time, -1)
    #---------------------------------------------------------------------------------
    #                  Rolling average Acceleration and Jerk
    #---------------------------------------------------------------------------------
    a_roll_int = 2
    j_roll = 1
    #print 'endTime:{0}'.format(endTime)

    #shiftIndex=[]
    #k = 0
    #shift_skip = 0.3
    #Gear = pp.get_data_by_index(gear_uri, initIndex)
    #print "Gear is %d" %Gear
    #Gear_Array = pp.short_array(gear_uri, initIndex, -1)
    #Gear = Gear_Array[0]
    #print "Gear is now: %d" %Gear
    #Gear_Array = Gear_Array[Gear:-1]
    #print len(Gear_Array)
    #print type(Gear_Array) #check to make sure I actually have a numpy array.
#    it = np.nditer(Gear_Array, flags=['f_index'])
#    for i in it:
#            shiftIndex.append(it.index)
#            Gear = i
#    print shiftIndex
    #-------------SETUP----------------------------------
    print 'Measure Acceleration'
    time_array = pp.time_array()
    #print type(time_array)
    #print "time is: %d " %time_array[100]
    time_iter = np.nditer(time_array, flags=['f_index'])

    accel_array = pp.data_array(a_uri)
    clean_accel_array = []
    sumAccel = 0
    #print type(accel_array)
    jerk_array = pp.data_array(jerk_uri)
    clean_jerk_array = []
    sumJerk = 0
    #print type(jerk_array)
    avg_Accel = []
    avg_Jerk = []

    #-------------Iterate----------------------------------
    next_time = start_time
    past_time = 0
    accelStep = int(a_roll_int/time_inc)
    #print accelStep
    for i in time_iter:
        if i > next_time:
            next_time = i + time_inc
            clean_accel_array.append(accel_array[time_iter.index])
            clean_jerk_array.append(jerk_array[time_iter.index])

    #print "clean: %d" %len(clean_accel_array)
    for i in xrange(len(clean_accel_array)):
        sumAccel = sumAccel + clean_accel_array[i]
        sumJerk = sumJerk + clean_jerk_array[i]
        if i > a_roll_int/time_inc:
            sumAccel = sumAccel - clean_accel_array[i - int(a_roll_int/time_inc)]
            avg_Accel.append(sumAccel/int(a_roll_int/time_inc))
        if i > j_roll/time_inc:
            sumJerk = sumJerk - clean_jerk_array[i-int(j_roll/time_inc)]
            avg_Jerk.append(sumJerk/int(j_roll/time_inc))

    maxAccel = np.amax(avg_Accel)
    maxJerk = np.amax(avg_Jerk)
    #print type(maxAccel) # added this because I had the wrong type for the print statement.
    print "Max average acceleration: %f" %maxAccel
    print "Max average Jerk: %f" %maxJerk

            #print "next time is: %d" %next_time
#    time = start_time
#    while time < (endTime-a_roll_int):
#        #print 'time:{0}'.format(t)
#        start = pp.get_index_from_time(time)
#        end = pp.get_index_from_time(time+a_roll_int)
#        if k<len(shiftIndex) and pp.time[shiftIndex[k]]<pp.time[start]+a_roll_int:
#            print 'here'
#            start = pp.get_index_from_time(pp.time[shiftIndex[k]]+shift_skip)
#            end = pp.get_index_from_time(pp.time[shiftIndex[k]]+shift_skip+a_roll_int)
#            time = pp.time[start]
#            k = k+1
#        print 'time:{0}'.format(pp.time[start])
#        a = pp.short_array(a_uri, start, end)
#        #print abs(numpy.mean(a))
#        if(numpy.mean(a) > a_bar):
#                a_bar = numpy.mean(a)
#                print a_bar
#                #print 'time:{0}'.format(t)
#        time = time + time_inc
#
#    time = start_time # restart
#    k = 0
#    print 'Measure Jerk'
#    while time < (endTime-j_roll):
#        #print 'time:{0}'.format(t)
#        start = pp.get_index_from_time(time)
#        end = pp.get_index_from_time(time+j_roll)
#        if k<len(shiftIndex) and pp.time[shiftIndex[k]]<pp.time[start]+j_roll:
#            print 'here'
#            start = pp.get_index_from_time(pp.time[shiftIndex[k]]+shift_skip)
#            end = pp.get_index_from_time(pp.time[shiftIndex[k]]+shift_skip+j_roll)
#            time = pp.time[start]
#            k = k+1
#        jerk = pp.short_array(jerk_uri, start, end)
#        print 'time:{0}'.format(pp.time[start])
#        absjerk = []
#        #print absjerk
#        for i in jerk:
#            absjerk.append(abs(i))
#        if(numpy.mean(absjerk) > jerk_bar):
#                jerk_bar = numpy.mean(absjerk)
#                print jerk_bar
#                #print 'time:{0}'.format(t)
#        time = time + time_inc
#        #print "done"
    #---------------------------------------------------------------------------------
    #                  Potential_Design
    #---------------------------------------------------------------------------------
    Potential_Design = 0
    followTime = pp.get_data_by_index(followTime_uri, -1)
    if (SettlingTime == -1 or riseTime == -1 or minDistance < .1*minDistanceVelocity*followTime):
        Potential_Design = -1
    else: Potential_Design = 1

    print "Potential_Design: %d" %Potential_Design

    #---------------------------------------------------------------------------------
    #                  Metrics
    #---------------------------------------------------------------------------------
    metrics = {}
    metrics.update({'vehicleMass':{'value': vehicleMass, 'unit':'kg'},
                    'distanceTraveled':{'value': distanceTraveled, 'unit': 'm'},
                    'minDistance': {'value': minDistance, 'unit': 'm'},
                    'finalVelocity':{'value': Vf, 'unit': 'm/s'},
                    'requiredTorque':{'value': requiredTorque, 'unit':'N-m'},
                    'riseTime':{'value': np.amax(riseTime), 'unit' :''},
                    'Overshoot':{'value': np.amax(Overshoot), 'unit' :''},
                    'settlingTime':{'value': np.amax(SettlingTime), 'unit' :''},
                    'rms_error':{'value': RMS_error, 'unit' : ''},
                    'numSetpointCrossings':{'value':numSetPointCrossings, 'unit': ''},
                    'averageA': {'value': maxAccel, 'unit': 'm/s2'},
                    'averageJ': {'value': maxJerk, 'unit': 'm/s3'},
                    'Potential_Design': {'value': Potential_Design, 'unit': ''},

                    #'chassisType':{'value': chassisType, 'unit' :''},
                    })
    print metrics
    cwd = os.getcwd()
    os.chdir('..')
    # print 'Plot saved to : {0}'.format(pp.save_as_svg(vehicle_speed,
                                                      # pp.global_abs_max(vehicle_speed),
                                                      # 'VehicleSpeed',
                                                      # 'max(FTP_Driver.driver_bus.vehicle_speed)',
                                                      # 'kph'))

    numSamples = int(endTime/time_inc)
    print numSamples
    #pp.store_data_to_csv(jerk_uri, '{0}.csv'.format(jerk_uri), 0, time_inc, numSamples)
    #pp.store_data_to_csv(a_uri, '{0}.csv'.format(a_uri), 0, time_inc, numSamples)
    #pp.store_data_to_csv(pp.time_array, '{0}.csv'.format(pp.time_array), 0, time_inc, numSamples)
    #pp.store_data_to_csv(boomCylLength_uri, '{0}.csv'.format(boomCylLength_uri), 0, time_inc, numSamples)
    #pp.store_data_to_csv(armCylLength_uri, '{0}.csv'.format(armCylLength_uri), 0, time_inc, numSamples)
    #pp.store_data_to_csv(bucketCylLength_uri, '{0}.csv'.format(bucketCylLength_uri), 0, time_inc, numSamples)
    #pp.store_data_to_csv(boomCylRPressure_uri, '{0}.csv'.format(boomCylRPressure_uri), 0, 0.1, dur)
    #pp.store_data_to_csv(arm_ang_vel_uri, '{0}.csv'.format(arm_ang_vel_uri), 0, 0.1, dur)
    #pp.store_data_to_csv(max_Y_uri, '{0}.csv'.format(max_Y_uri), 0, 0.1, dur)
    #pp.store_data_to_csv(max_reach_uri, '{0}.csv'.format(max_reach_uri), 0, 0.1, dur)
    #pp.store_data_to_csv(State_uri, '{0}.csv'.format(State_uri), 0, 0.1, dur)
    ## end of postprocessing part

    ## Second limit part
    check_limits_and_add_to_report_json(pp, limit_dict)
    update_metrics_in_report_json(metrics)
    ## end of Second limit part
    os.chdir(cwd)

if __name__ == '__main__':
    root_dir = os.getcwd()
    try:
        main()
    except:
        os.chdir(root_dir)
        import traceback
        trace = traceback.format_exc()
        # Generate this file on failed executions, https://github.com/scipy/scipy/issues/1840
        with open(os.path.join('..', '_POST_PROCESSING_FAILED.txt'), 'wb') as f_out:
            f_out.write(trace)


text:
<?xml version="1.0"?>
<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/maven-v4_0_0.xsd">
    <parent>
        <groupId>com.twelvemonkeys</groupId>
        <artifactId>twelvemonkeys</artifactId>
        <version>3.10.0-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.twelvemonkeys.servlet</groupId>
    <artifactId>servlet</artifactId>
    <name>TwelveMonkeys :: Servlet</name>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.4</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>4.1.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-source-plugin</artifactId>
            </plugin>

            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <configuration>
                  <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <archive>
                        <manifestEntries>
                            <Implementation-Title>${project.name}</Implementation-Title>
                            <Implementation-Vendor>TwelveMonkeys</Implementation-Vendor>
                            <Implementation-Version>${project.version}</Implementation-Version>
                            <Implementation-URL>http://github.com/haraldk/TwelveMonkeys</Implementation-URL>
                        </manifestEntries>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>3.2.2</version>
                <executions>
                    <execution>
                        <id>jakarta</id>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <shadedArtifactAttached>true</shadedArtifactAttached>
                            <shadedClassifierName>jakarta</shadedClassifierName>
                            <createDependencyReducedPom>false</createDependencyReducedPom>
                            <artifactSet>
                                <includes>
                                    <include>${project.groupId}:${project.artifactId}</include>
                                </includes>
                            </artifactSet>
                            <relocations>
                                <relocation>
                                    <pattern>javax.servlet</pattern>
                                    <shadedPattern>jakarta.servlet</shadedPattern>
                                </relocation>
                            </relocations>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
<?php

declare(strict_types=1);

namespace Sonata\AdminBundle\Form\Type\Filter;

use Sonata\AdminBundle\Form\Type\Operator\ContainsOperatorType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType as FormChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Translation\TranslatorInterface;

/**
 * @final since sonata-project/admin-bundle 3.52
 *
 * @author Thomas Rabaix <thomas.rabaix@sonata-project.org>
 */
class ChoiceType extends AbstractType
{
    /**
     * @deprecated since sonata-project/admin-bundle 3.57, to be removed with 4.0: Use ContainsOperatorType::TYPE_CONTAINS instead
     */
    public const TYPE_CONTAINS = 1;

    /**
     * @deprecated since sonata-project/admin-bundle 3.57, to be removed with 4.0: Use ContainsOperatorType::TYPE_NOT_CONTAINS instead
     */
    public const TYPE_NOT_CONTAINS = 2;

    /**
     * @deprecated since sonata-project/admin-bundle 3.57, to be removed with 4.0: Use ContainsOperatorType::TYPE_EQUAL instead
     */
    public const TYPE_EQUAL = 3;

    /**
     * NEXT_MAJOR: remove this property.
     *
     * @deprecated since sonata-project/admin-bundle 3.5, to be removed with 4.0
     *
     * @var TranslatorInterface
     */
    protected $translator;

    public function __construct(TranslatorInterface $translator)
    {
        $this->translator = $translator;
    }

    /**
     * NEXT_MAJOR: Remove when dropping Symfony <2.8 support.
     *
     * @return string
     */
    public function getName()
    {
        return $this->getBlockPrefix();
    }

    public function getBlockPrefix()
    {
        return 'sonata_type_filter_choice';
    }

    /**
     * @param array<string, mixed> $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('type', $options['operator_type'], array_merge(['required' => false], $options['operator_options']))
            ->add('value', $options['field_type'], array_merge(['required' => false], $options['field_options']))
        ;
    }

    /**
     * @return void
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'field_type' => FormChoiceType::class,
            'field_options' => [],
            'operator_type' => ContainsOperatorType::class,
            'operator_options' => [],
        ]);
    }
}


text:
#include <string>

#ifndef PATHUTIL_H_
#define PATHUTIL_H_

class PathUtil {
public:
	PathUtil();

	static std::string getFileNameFromPath(const std::string& path);

	static std::string getFileNameFromPath(const char *path);

	static std::string combinePathAndFileName(const std::string& path,
			const std::string& fileName);

	static std::string combinePathFileNameAndExt(const std::string& path,
			const std::string& fileName, const std::string& extension);

private:
#ifdef WIN32
	const static char DIRECTORY_SEPARATOR = '\\';
#else
	const static char DIRECTORY_SEPARATOR = '/';
#endif
};

#endif /* PATHUTIL_H_ */


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org" />

  <title>RMagick 2.13.2: RVG Tutorial</title>
  <meta name="GENERATOR" content="Quanta Plus" />
  <link rel="stylesheet" type="text/css" href="css/doc.css" />

RMagick 2.13.2 User's Guide and Reference

    « Prev | Contents | Next »

Drawing with RVG

A tutorial

Introduction

RVG (Ruby Vector Graphics) is a facade for RMagick's
      Draw class that supplies a drawing
      API based on the Scalable Vector
      Graphics W3C recommendation.

RVG is a scalable vector drawing
      library. Scalable means that drawings are not fixed
      to a single size in pixels. The same drawing can be rendered
      for a screen display or for printing. Vector images
      are drawn using geometric objects like lines and circles.
      Unlike raster images, vector images don't get "pixelated"
      when you make them bigger.
As an introduction to the RVG
      library, let's see how to draw this little duck on the left.
      Here is the complete program.

 1  require 'rvg/rvg'
 2  include Magick
 3
 4  RVG::dpi = 72
 5
 6  rvg = RVG.new(2.5.in, 2.5.in).viewbox(0,0,250,250) do |canvas|
 7      canvas.background_fill = 'white'
 8
 9      canvas.g.translate(100, 150).rotate(-30) do |body|
10          body.styles(:fill=>'yellow', :stroke=>'black', :stroke_width=>2)
11          body.ellipse(50, 30)
12          body.rect(45, 20, -20, -10).skewX(-35)
13      end
14
15      canvas.g.translate(130, 83) do |head|
16          head.styles(:stroke=>'black', :stroke_width=>2)
17          head.circle(30).styles(:fill=>'yellow')
18          head.circle(5, 10, -5).styles(:fill=>'black')
19          head.polygon(30,0, 70,5, 30,10, 62,25, 23,20).styles(:fill=>'orange')
20      end
21
22      foot = RVG::Group.new do |_foot|
23          _foot.path('m0,0 v30 l30,10 l5,-10, l-5,-10 l-30,10z').
24                styles(:stroke_width=>2, :fill=>'orange', :stroke=>'black')
25      end
26      canvas.use(foot).translate(75, 188).rotate(15)
27      canvas.use(foot).translate(100, 185).rotate(-15)
28
29      canvas.text(125, 30) do |title|
30          title.tspan("duck|").styles(:text_anchor=>'end', :font_size=>20,
31                         :font_family=>'helvetica', :fill=>'black')
32          title.tspan("type").styles(:font_size=>22,
33                 :font_family=>'times', :font_style=>'italic', :fill=>'red')
34      end
35      canvas.rect(249,249).styles(:stroke=>'blue', :fill=>'none')
36  end
37
38  rvg.draw.write('duck.gif')

Summary

All drawings follow the same 3 steps:

Create an RVG object. Specify the width and height of the
    final image. The RVG.new method yields to a
    block.

Within the block, call methods on the RVG object to specify
    a background, add shapes, text, or raster images, or add groups
    of shapes, text, or raster images.

Call the draw method to draw the shapes, text,
    or raster images onto the background.

I'll step through the example line-by-line.

Lines 1-3

 1   require 'rvg/rvg'
 2   include Magick

These are just the usual Ruby code to load the RVG extension.
  To save some typing, I've included the Magick module into
  Object's namespace.

Lines 4-6

 4   RVG::dpi = 72
 5
 6   rvg = RVG.new(2.5.in, 2.5.in).viewbox(0,0,250,250) do |canvas|

RVG::dpi enables the use of unit methods
  in RVG. When you set RVG::dpi to a non-nil value,
  RVG adds a number of conversion methods to the Fixnum and Float
  classes . These methods allow you to specify measurements in
  units such as inches, millimeters, and centimeters. DPI
  stands for "dots per inch," the image resolution. Here I set
  RVG::dpi to 72, a common value for displays.

The RVG.new method accepts 2 parameters. These
  parameters specify the width and height of the final image in
  pixels. Since I've defined RVG::dpi, I can specify
  these values in inches using the in conversion
  method. At 72dpi, the final image will be 2.5*72=180 pixels on a
  side.

By default, RVG uses pixels as its unit of measurement, but
  since I'm drawing a scalable picture I don't want to confine
  myself to pixels. The viewbox method defines a
  coordinate system with a logical unit. Viewbox takes
  4 parameters, min_x, min_y,
  width, and height. On line 6 I define
  my coordinate system to have its origin at (0,0) and a width and
  height of 250 units. By using my own coordinate system, I can
  later change the size of the image to 5 inches square or 1 inch
  square just by changing the arguments to new.

The default coordinate system

By default, the RVG coordinate system has its origin in
      the upper-left corner. The x-axis proceeds to the right. The
      y-axis proceeds downwards. The image on the left shows the
      axes of this coordinate system. I've added a light-blue
      "graph-paper" background to the example images to help
      associate the coordinate arguments to the actual locations in
      the image. Just remember that the axes and graph-paper
      background are not actually part of the image I'm
      producing.

The RVG class is one of the container classes defined
  by RVG. Container objects can contain graphic objects such as
  circles and lines, text, raster images, and other container
  objects. The outermost container is always an RVG object. I will
  add all the graphic objects that form the duck to this
  container.

Container constructors normally yield to a block. However,
  here I've chained viewbox to new, so
  viewbox takes responsibility for yielding and passes
  the new instance of RVG to the canvas argument.

Line 7

 7       canvas.background_fill = 'white'

By default, RVG graphics are drawn on a transparent
  background. This is convenient when you want to display your
  image over another image. You can override the default background
  color by assigning a color to the background_fill=
  attribute. Here I set the background color to "white."

Lines 9-13

 9      canvas.g.translate(100, 150).rotate(-30) do |body|
10          body.styles(:fill=>'yellow', :stroke=>'black', :stroke_width=>2)
11          body.ellipse(50, 30)
12          body.rect(45, 20, -20, -10).skewX(-35)
13      end

There's a lot going on in these few lines - seven method calls
  - so let's take it one method at a time.

Groups

Group is the second container class in RVG. The
  purpose of a group is to associate a set of coordinate system
  transformations and a set of styles with the graphic objects
  within the group. To create a Group object within another
  container, call the g method on the container. The
  g method yields if a block is present. In this
  example, there is no block associated with g, so
  g returns the new group. The g method
  adds the group to the content of its container. In this example,
  the group's container is the canvas object created in line 6. The
  graphic objects in the group are drawn as part of drawing the
  container. The translate and rotate
  chained to g modify the group by adding
  coordinate system transforms.

(Okay, there is a block, but there are 2 method calls
  between g and the block. I'll explain more
  later.)

Transforms

I'm going to use this group to contain the ellipse that forms
  the duck's body and the rectangle that forms the wing. I could
  just specify x- and y-coordinates to position these shapes
  relative to the origin, but it's easier to move the origin to
  where I want to draw the shapes. This is the purpose of the
  translate method. This method moves the origin to
  the (x,y) position specified by its arguments. I call
  translate on the group object, and since the content
  of the group gets the coordinate system transformations specified
  for the group, the ellipse and the rectangle will be drawn on a
  coordinate system with the origin at (100, 150) relative to the
  old coordinate system.

Also, I want the duck's body to slant upward, so I use the
  rotate method to rotate the axes. The argument to
  rotate is the number of degrees of rotation. A
  negative number indicates counter-clockwise rotation.

After translating and rotating the coordinate system, the axes
  look like this:

The transform methods

There are six transform methods. In addition to
      translate and rotate, there's
      scale, skewX, skewY,
      and matrix. When groups are nested, any
      transforms defined on the inner group(s) are added to the
      outer transforms.

Styles

Recall that the styles method modifies the
  default group styles. The styles method takes a hash
  as an argument. The hash keys are style names, and the hash
  values are, well, style values. In this example there are three
  style names. The :fill style sets the fill color to 'yellow'. The
  :stroke style sets the outline color to 'black'. The
  :stroke_width style sets the width of the outline to 2. I want
  the styles to apply to all objects within the group so in line 10
  I call styles on the new group object.

The styles method is a real workhorse. It's
  defined in almost every class in RVG and there are many other
  style names in addition to these three..

Basic shapes

The group contains two basic shapes, an ellipse and a
  rectangle. I add the ellipse to the group with the
  ellipse method. Ellipse has four
  parameters. The first two, the radius on the x-axis and the
  radius on the y-axis, are required. The last two are the (x,y)
  coordinate of the center. When these are omitted, as here, they
  default to (0,0). I add the rectangle with the rect
  method, which also has four parameters. The first two are the
  width and height of the rectangle. The last two are the (x,y)
  coordinate of the upper-left corner. Both of these methods return
  self, so you can chain other methods to them.

Here's what the group looks like when rendered. The ellipse is
  centered on the origin. The upper-left corner of the rectangle is
  slightly up and to the left of the origin.

The shape methods

There are 7 shape methods. In addition to
      ellipse and rect, there's
      circle, line, path,
      polygon, and polyline. You can also
      think of text as a shape. Shapes are stroked and filled, and
      can be modified by the transform methods and the
      styles method.

SkewX

Everybody knows that a wing doesn't look like a rectangle! A
  wing looks like a slanted parallelogram. (Well, it does in this
  example!) Fortunately, I can use the transform methods on shapes
  as well as containers. The skewX method makes it
  easy for us to give the rectangle a slant. The skewX
  method is another transform. It takes a single argument, the
  number of degrees to skew the x-axis. Since all the shape
  constructors, including rect, return
  self, I can chain skewX directly to
  rect and limit the effect of the transform to just
  the rectangle. The result looks like this. (I've drawn in the
  axes for the wing coordinate system.)

That's it for the body. Let's tie up one loose end before
  moving on. I said earlier that container constructors (such as
  g) yield to a block if present. In this case,
  though, the translate and rotate
  methods intervene between g and the block. All the
  transform methods yield when there is an associated block, so I
  can easily chain them to a container constructor and still use a
  block argument to define the graphic objects in the group. Method
  chaining is a common RVG idiom. You'll see it a lot in the
  examples.

The next group draws the head.

Lines 15-20

15      canvas.g.translate(130, 83) do |head|
16          head.styles(:stroke=>'black', :stroke_width=>2)
17          head.circle(30).styles(:fill=>'yellow')
18          head.circle(5, 10, -5).styles(:fill=>'black')
19          head.polygon(30,0, 70,5, 30,10, 62,25, 23,20).styles(:fill=>'orange')
20      end

This section is very similar to the previous one. I'm defining
  a group to contain the graphic objects that draw the duck's head,
  eye, and beak. First I use the translate method to move the
  origin to (130,83):

In line 16 I define the stroke and
  stroke_width styles on the group. Styles defined on
  the group propagate to shapes within the group unless you
  override them. To do that, call styles on the
  shapes. In this group each shape has its own fill color. The
  yellow circle forms the head. The circle method
  takes 3 parameters. The first parameter is the radius of the
  circle. The other two parameters are the (x,y) coordinate of the
  center. If omitted, as here, they default to (0,0). I use a small
  black circle for the eye.

Last, I use the polygon method to draw the beak.
  This method draws a polygon from a series of (x,y) coordinates.
  If the last coordinate is not the same as the first,
  polygon implicitly adds it to close the polygon.
  Again, I use styles to set the fill color to
  orange.

Lines 22-25

22      foot = RVG::Group.new do |_foot|
23          _foot.path('m0,0 v30 l30,10 l5,-10, l-5,-10 l-30,10z').
24                styles(:stroke_width=>2, :fill=>'orange', :stroke=>'black')
25      end

Here I create a group by directly calling new
  instead of calling the g method on a container. This
  creates a group object that is not contained within the canvas.
  You might think of the foot as not being attached to anything,
  like this:

Lines 26-27

26       canvas.use(foot).translate(75, 188).rotate(15)
27       canvas.use(foot).translate(100, 185).rotate(-15)

To add the group to the canvas I use the use
  method. The use method can accept any container or graphic object
  as an argument. Optionally you can specify an (x,y) coordinate
  that specifies where to position the objects. In this example,
  however, I let those arguments default to (0,0) and use
  translate to position the feet. Here's how the left
  foot attaches to the duck:

Of course, the duck is walking, so I have to give the foot a
  little slant with rotate:

Attaching the right foot is easy. Call use again
  but give different arguments to translate and
  rotate:

Lines 29-34

29      canvas.text(125, 30) do |title|
30          title.tspan("duck|").styles(:text_anchor=>'end', :font_size=>20,
31                         :font_family=>'helvetica', :fill=>'black')
32          title.tspan("type").styles(:font_size=>22,
33                 :font_family=>'times', :font_style=>'italic', :fill=>'red')
34      end

All I need now is a title for the picture. Text in RVG is a
  job for the text method. Like the shape methods,
  text can be used with any container object.
  Text itself is a container, except that it can only
  contain text-related objects. The text method takes
  2 or 3 arguments, an (x,y) pair and optionally a string. The
  (x,y) pair define a current text position at which
  rendering starts. If there is a string argument, it will be
  rendered starting at the current text position. Rendering text
  changes the current text position to the end of the text.

In the example, text is used as a container. Text objects can
  contain Tspan objects. Each tspan can specify its own styles. By
  default each tspan is rendered starting at the current text
  position.

As usual, I can change the appearance of the text with
  styles. Here I choose a font, a font style (the
  default is "normal"), its size in points, and the color.

Line 35

35       canvas.rect(249,249).styles(:stroke=>'blue', :fill=>'none')

I'm almost done. All I need to do it add a blue border. (I'm
  going to remove the graph paper background because we don't need
  it any more.)

Line 38

38   rvg.draw.write('duck.gif')

The draw method call doesn't occupy a lot of
  space - just 4 letters - but does a lot of work. The
  draw method goes through all the graphics objects
  that I've added to the outermost RVG container and draws them on
  the background. When the drawing is complete, draw
  returns the drawing in the form of an RMagick Image object. You
  can use any Image class methods on the drawing. Here I simply
  write the image to a GIF file.

Scalable graphics

Are RVG images really scalable? Let's try. Change the RVG.new
  call to make an image that's 4 times as big. That's 5 inches on a
  side:

 6   rvg = RVG.new(5.in, 5.in).viewbox(0,0,250,250) do |canvas|

Change nothing else. Run the program again and see what you
  get.

    « Prev | Contents | Next »


text:
package tccpazs

import (
	"github.com/giantswarm/microerror"
	"k8s.io/apimachinery/pkg/api/errors"
)

var invalidConfigError = &microerror.Error{
	Kind: "invalid config",
}

// IsInvalidConfig asserts invalidConfigError.
func IsInvalidConfig(err error) bool {
	return microerror.Cause(err) == invalidConfigError
}

var notFoundError = &microerror.Error{
	Kind: "notFoundError",
}

// IsNotFound asserts notFoundError.
func IsNotFound(err error) bool {
	c := microerror.Cause(err)
	return c == notFoundError || errors.IsNotFound(c)
}

var tooManyCRsError = &microerror.Error{
	Kind: "tooManyCRsError",
	Desc: "There is only a single G8sControlPlane CR allowed with the current implementation.",
}

// IsTooManyCRsError asserts tooManyCRsError.
func IsTooManyCRsError(err error) bool {
	return microerror.Cause(err) == tooManyCRsError
}


text:
<!-- Import Polymer -->
<link rel="import" href="../bower_components/polymer/polymer.html">

<!-- Define your custom element -->
<% if (polymerVersion == '0.5.1') { %><polymer-element name="<%= elementName %>"><% } %><% if (polymerVersion == '1.4.0') { %><dom-module id="<%= elementName %>"><% } %>
    <template></template>
    <script>
        Polymer(<% if (polymerVersion == '0.5.1') { %>'<%= elementName %>', <% } %>{<% if (lifecycle) { %><% if (polymerVersion == '1.4.0') { %>
            is:'<%= elementName %>',<% } %>
            // Fires when an instance of the element is created
            created: function() {},
            <% if (polymerVersion == '0.5.1') { %>
            // Fires when the element's initial set of children and siblings are guaranteed to exist
            domReady: function() {},
            <% } %>
            // Fires when the "<polymer-element>" has been fully prepared
            ready: function() {},

            // Fires when the element was inserted into the document
            attached: function() {},

            // Fires when the element was removed from the document
            detached: function() {},

            // Fires when an attribute was added, removed, or updated
            attributeChanged: function(attr, oldVal, newVal) {}<% } %>
        });
    </script>
<% if (polymerVersion == '0.5.1') { %></polymer-element><% } %><% if (polymerVersion == '1.4.0') { %></dom-module><% } %>


text:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Assertions;
using System.Linq;
using System.Collections;
using System.Collections.Generic;

using Newtonsoft.Json;

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class World
{
    [JsonObject(IsReference = false)]
    public class Info
    {
        public Test.Version version;
        public string name;
        [JsonIgnore]
        public string root;
        public System.DateTime lastPlayed;
    }

    public class Avatar
    {
        public int id;
        public Vector2 destination, source;
        public Sprite graphic;
        public string name;

        public float u;
    }

    public Texture2D tileset;
    public Sprite[] tiles;

    [JsonProperty]
    public byte[] tilemap;
    [JsonProperty]
    public HashSet<byte> walls = new HashSet<byte>();
    [JsonProperty]
    public Color[] palette;

    public List<Avatar> avatars = new List<Avatar>();

    public World()
    {
        tileset = new Texture2D(512, 512);
        tileset.filterMode = FilterMode.Point;

        tiles = new Sprite[256];
        tilemap = new byte[1024];
        palette = new Color[16];

        for (int i = 0; i < 256; ++i)
        {
            int x = i % 16;
            int y = i / 16;

            tiles[i] = Sprite.Create(tileset,
                                     new Rect(x * 32, y * 32, 32, 32),
                                     Vector2.zero,
                                     1,
                                     0U,
                                     SpriteMeshType.FullRect);
        }
    }

    public void StaticiseTileset()
    {
        Color32[] colors = new Color32[512 * 512];
        Color32[] colors2 =
        {
            Color.black,
            Color.white,
        };

        for (int i = 0; i < colors.Length; ++i)
        {
            colors[i] = colors2[Random.Range(0, 2)];
        }

        tileset.SetPixels32(colors);
        tileset.Apply();
    }

    // TODO: just generate 3 curves (HSL) then evaluate n palette colours w them
    public void RandomisePalette()
    {
        float phase = Random.value;
        var borders = Enumerable.Range(0, 4)
                                .Select(i => (i / 3f + Random.value * 0.1f + phase) % 1)
                                .OrderBy(i => i)
                                .ToArray();

        float[] ranges = new float[borders.Length];

        ranges[borders.Length - 1] = 1 - borders[borders.Length - 1] + borders[0];

        for (int i = 0; i < borders.Length - 1; ++i)
        {
            ranges[i] = borders[i + 1] - borders[i];
        }

        var hues = new AnimationCurve[borders.Length];
        var ligs = new AnimationCurve[borders.Length];

        for (int i = 0; i < borders.Length; ++i)
        {
            float offset = ranges[i] * 0.125f * Random.value;
            float min = borders[i] + offset;
            float max = min + ranges[i] - offset;

            hues[i] = AnimationCurve.Linear(0, min, 1, max);
            ligs[i] = AnimationCurve.Linear(0, 0.1f + 0.3f * Random.value, 1, 0.9f - 0.3f * Random.value);
        }

        for (int r = 0; r < 4; ++r)
        {
            bool fliph = Random.value > 0.5f;
            bool flipl = Random.value > 0.5f;

            for (int i = 0; i < 4; ++i)
            {
                float up = i / 3f;
                float down = 1 - up;

                float hue = hues[r].Evaluate(up) % 1;
                float sat = 0.75f + Random.value * 0.25f;
                float lig = ligs[r].Evaluate(flipl ? up : down) % 1;

                IList<double> RGB = HUSL.HUSLToRGB(new double[] { hue * 360, sat * 100, lig * 100 });
                Color color = new Color((float) RGB[0], (float) RGB[1], (float) RGB[2], 1);

                palette[r * 4 + i] = color;
            }
        }

        palette[0] = Color.clear;

        /*
        for (int i = 0; i < 16; ++i)
        {
            Color color;

            do
            {
                color = new Color(Random.value, Random.value, Random.value, 1);
            }
            while (palette.Take(i).Any(other => Test.ColorDistance(other, color) < 16f));

            palette[i] = color;
        }
        */
    }

    public byte ColorToPalette(Color color, bool clearzero = false)
    {
        return (byte) palette.ColorToPalette(color, clearzero);
    }

    private Color IndexToMask(byte index)
    {
        return index == 0 ? Color.clear : new Color(index / 15f, 0, 0, 1f);
    }

    public void PalettiseTexture(Texture2D texture, bool clearzero = false)
    {
        var colors = texture.GetPixels()
                            .Select(color => ColorToPalette(color, clearzero))
                            .Select(index => IndexToMask(index))
                            .ToArray();

        texture.SetPixels(colors);
        texture.Apply();
    }

    public void Convert()
    {
        palette[0] = Color.clear;

        PalettiseTexture(tileset);
    }
}


text:
package everstore.java.serialization.jackson;

public class ComplexEvent {
    public final SimpleEvent inner;
    public final int value;

    protected ComplexEvent() {
        inner = new SimpleEvent("");
        value = 54321; // Default value
    }

    public ComplexEvent(SimpleEvent inner, int value) {
        this.inner = inner;
        this.value = value;
    }

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

        ComplexEvent that = (ComplexEvent) o;

        if (value != that.value) return false;
        return inner.equals(that.inner);

    }

    @Override
    public int hashCode() {
        int result = inner.hashCode();
        result = 31 * result + value;
        return result;
    }
}


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

using System;
using System.Net;
using HttpWebAdapters.Adapters;

namespace HttpWebAdapters {
	public class HttpWebRequestFactory : IHttpWebRequestFactory {
		public IHttpWebRequest Create(string url) {
			return new HttpWebRequestAdapter((HttpWebRequest) WebRequest.Create(url));
		}

		public IHttpWebRequest Create(Uri url) {
			return new HttpWebRequestAdapter((HttpWebRequest) WebRequest.Create(url));
		}
	}
}


text:
All URIs are relative to *http://api.swindle.net/archetypes/v1/parties*

Method | HTTP request | Description
------------- | ------------- | -------------
[**getParties**](PartiesApi.md#getParties) | **GET** / | Retrieve all Parties.
[**getPartyByPartyIdentifier**](PartiesApi.md#getPartyByPartyIdentifier) | **GET** /{party-identifier} | Retrieve a specific Party entity.

# **getParties**
> [InlineResponse200] getParties()

Retrieve all Parties.

Retrieve all Parties.

### Example
```javascript
var Party = require('party');

var apiInstance = new Party.PartiesApi();

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.getParties(callback);
```

### Parameters
This endpoint does not need any parameter.

### Return type

[**[InlineResponse200]**](InlineResponse200.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json, application/xml

# **getPartyByPartyIdentifier**
> InlineResponse200 getPartyByPartyIdentifier(partyIdentifier)

Retrieve a specific Party entity.

Retrieve a Party by its unique identifier.

### Example
```javascript
var Party = require('party');

var apiInstance = new Party.PartiesApi();

var partyIdentifier = "partyIdentifier_example"; // String | The unique identifier of the Party.

var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.getPartyByPartyIdentifier(partyIdentifier, callback);
```

### Parameters

Name | Type | Description  | Notes
------------- | ------------- | ------------- | -------------
 **partyIdentifier** | **String**| The unique identifier of the Party. |

### Return type

[**InlineResponse200**](InlineResponse200.md)

### Authorization

No authorization required

### HTTP request headers

 - **Content-Type**: Not defined
 - **Accept**: application/json, application/xml


text:
#import <iWorkImport/TSUPair.h>

// Not exported
@interface TSUMutablePair : TSUPair
{
}

- (void)setSecond:(id)arg1;
- (void)setFirst:(id)arg1;

@end


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

<title>org.myrobotlab.memory</title>
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.myrobotlab.memory

Interfaces

Cache

ManagedCache

MemoryChangeListener

Classes

BaseCache

CacheFactory

CacheManager

Generalizer

LocalCache

Memory

Node

Node.NodeContext

NodeDeprecate


text:
import hashing.*;
import ordinations.QuickSort;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class Menu {
    public void printMenu() {
        Scanner sc = new Scanner(System.in);
        ArrayList<ArrayList<Long>> arrayTweets, array1, array2, array3, array4, array5;
        QuickSort quick = new QuickSort();
        Generator generator = new Generator();
        Comparations compare = new Comparations();

        System.out.println("Trabalho de Estrutura de Dados 2");
        System.out.println();
        System.out.println("Aguarde enquanto é criado o vetor de Tweets!");
        System.out.println();

        // Criar vetor de tweets
        arrayTweets = generator.createFileReading("valores.txt", "tweets.txt");

        int option = 9;
        while (option != 0) {
            System.out.println("Escolha uma opção abaixo: ");
            System.out.println();
            System.out.println("1 - Ordenar atráves de QuickSort");
            System.out.println("2 - Ordenar através de variações do QuickSort");
            System.out.println("3 - Ordenar através de diferentes algoritmos");
            System.out.println("4 - Tratamento de Colisões");
            System.out.println("0 - Sair");
            System.out.print("Digite a opção: ");
            option = sc.nextInt();

            if (option == 1) {
                array1 = arrayTweets;
                try {
                    PrintWriter writer = new PrintWriter("estatisticas/estatisticas-quicksort.txt", "UTF-8");
                    for (int i = 0; i < arrayTweets.size(); i++) {
                        writer.println("##### Tweets ID para leitura de " + arrayTweets.get(i).size() + " valores #####");
                        writer.println();
                        writer.println("Tempo de Processamento: " + compare.timeQuickSort(array1.get(i)));
                        writer.println("Numero de comparações: " + quick.getNumeroComparacoes());
                        writer.println("-------------------------------------------------------------------------------------------------------------------------");
                        writer.println();
                    }

                    writer.close();
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }
                System.out.println();
                System.out.println("Arquivo estatisticas-quicksort.txt criado com sucesso!");
                System.out.println();
            } else if (option == 2) {
                array1 = arrayTweets;
                array2 = arrayTweets;
                array3 = arrayTweets;
                array4 = arrayTweets;
                array5 = arrayTweets;

                try {
                    PrintWriter writer = new PrintWriter("estatisticas/estatisticas-variacoes-quicksort.txt", "UTF-8");
                    for (int i = 0; i < arrayTweets.size(); i++) {
                        writer.println("##### Tweets ID para leitura de " + arrayTweets.get(i).size() + " valores #####");
                        writer.println();
                        writer.println("Tempo de Processamento:");
                        writer.println("QuickSort Recursivo= " + compare.timeQuickSort(array1.get(i)));
                        //writer.println("QuickSort Median(k = 3) = " + compare.timeQuickSortMedian(array2.get(i), 3));
                        //writer.println("QuickSort Median(k = 5) = " + compare.timeQuickSortMedian(array3.get(i), 5));
                        writer.println("QuickSort Insertion(m = 30) = " + compare.timeQuickSortInsertion(array4.get(i), 30));
                        writer.println("QuickSort Insertion(m = 100) = " + compare.timeQuickSortInsertion(array5.get(i), 100));
                        writer.println();
                        writer.println("Numero de comparações: ");
                        writer.println("QuickSort Recursivo = " + compare.getnumCompQuickSort());
                        //writer.println("QuickSort Median(k = 3) = " + compare.numCompQuicMedia());
                        //writer.println("QuickSort Median(k = 5) = " + compare.numCompQuicMedia());
                        writer.println("QuickSort Insertion(m = 30) = " + compare.numCompQuicSortInsert());
                        writer.println("QuickSort Insertion(m = 100) = " + compare.numCompQuicSortInsert());
                        writer.println("-------------------------------------------------------------------------------------------------------------------------");
                        writer.println();
                    }
                    writer.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.print(e.getMessage());
                }
                System.out.println();
                System.out.println("Arquivo estatisticas-variacoes-quicksort.txt criado com sucesso!");
                System.out.println();
            } else if (option == 3) {
                array1 = arrayTweets;
                array2 = arrayTweets;
                array3 = arrayTweets;
                array4 = arrayTweets;
                array5 = arrayTweets;
                try {
                    PrintWriter writer = new PrintWriter("estatisticas/estatisticas-diferentes-algoritmos.txt", "UTF-8");
                    for (int i = 0; i < arrayTweets.size(); i++) {
                        writer.println("##### Tweets ID para leitura de " + arrayTweets.get(i).size() + " valores #####");
                        writer.println();
                        writer.println("Tempo de Processamento:");
                        writer.println("QuickSort Recursivo = " + compare.timeQuickSort(array1.get(i)));
                        writer.println("InsertionSort = " + compare.timeInsertionSort(array2.get(i)));
                        writer.println("MergeSort = " + compare.timeMergeSort(array3.get(i)));
                        writer.println("HeapSort = " + compare.timeHeapSort(array4.get(i)));
                        writer.println("BubbleSort = " + compare.timeBubbleSort(array5.get(i)));
                        writer.println();
                        writer.println("Numero de comparações: ");
                        writer.println("QuickSort Recursivo = " + compare.getnumCompQuickSort());
                        writer.println("InsertionSort = " + compare.numCompInsertionSort());
                        writer.println("MergeSort = " + compare.numCompMerge());
                        writer.println("HeapSort = " + compare.getnumCompHeapSort());
                        writer.println("BubbleSort = " + compare.numCompBubble());
                        writer.println("-------------------------------------------------------------------------------------------------------------------------");
                        writer.println();
                    }
                    writer.close();
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }
                System.out.println();
                System.out.println("Arquivo estatisticas-diferentes-algoritmos.txt criado com sucesso!");
                System.out.println();
            } else if (option == 4) {
                Runtime rt = Runtime.getRuntime();
                HashingLinear linear = new HashingLinear();
                HashingQuadratic quadratic = new HashingQuadratic();
                DoubleHashing dh = new DoubleHashing();
                SeparateChaining separate = new SeparateChaining();
                CoalescedChaining coalesced = new CoalescedChaining(0, 0);
                ArrayList<Long> array;
                System.out.print("Escolha a quantidade de valores: ");
                int n = sc.nextInt();
                array = generator.arrayTweetsId(n);

                try {
                    PrintWriter writer = new PrintWriter("estatisticas/estatisticas-hashing.txt", "UTF-8");
                    writer.println("Tratamento de Colisões: Endereçamento x Encadeamento");
                    writer.println();
                    writer.println("Número de Colisões:");
                    linear.hashingLinear(array);
                    writer.println("Hashing Linear = " + linear.getCollisions());
                    quadratic.hashingQuadratic(array);
                    writer.println("Hashing Quadrático = " + quadratic.getCollisions());
                    dh.doubleHashing(array);
                    writer.println("Duplo Hashing = " + dh.getCollisions());
                    separate.separateChaining(array);
                    writer.println("Encadeamento Separado = " + separate.getCollisions());
                    coalesced.coalescedChaining(array);
                    writer.println("Encadeamento Coalescido = " + coalesced.getCollisions());
                    writer.println("Memória: ");
                    writer.println("Memória livre " + rt.freeMemory());
                    writer.println("Máximo memória: " + rt.maxMemory());
                    writer.println("Número de processadores: " + rt.availableProcessors());
                    writer.println("-------------------------------------------------------------------------------------------------------------------------");
                    writer.println();
                    writer.close();
                } catch (Exception e) {
                    System.out.print(e.getMessage());
                }
                System.out.println();
                System.out.println("Arquivo estatisticas-hashing.txt criado com sucesso!");
                System.out.println();
            }
        }
    }
}


text:
package com.myunihome.myxapp.paas.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class CertUtil
{
  private static final transient Log log = LogFactory.getLog(CertUtil.class);
  private static final String PKCS12 = "PKCS12";
  private static final String X509 = "X.509";
  private static final String SHA1withRSA = "SHA1withRSA";
  private static final String MD5 = "MD5";
  private static final String SHA1 = "SHA-1";
  private static final String CHARSET = "UTF-8";

  private static PrivateKey loadPrivateKey(String pfxFile, String pfxPwd, String privateKeyPwd)
  {
    try
    {
      InputStream bis = new FileInputStream(pfxFile);
      KeyStore store = KeyStore.getInstance(PKCS12);
      store.load(bis, pfxPwd.toCharArray());
      String alias = (String)store.aliases().nextElement();
      return (PrivateKey)store.getKey(alias, privateKeyPwd.toCharArray());
    }
    catch (Exception e) {
      log.error("load private key failed.", e);
    }return null;
  }

  private static PublicKey loadPublicKey(String cerFile)
  {
    try {
      InputStream bis = new FileInputStream(cerFile);
      CertificateFactory cf = CertificateFactory.getInstance(X509);
      Certificate cert = cf.generateCertificate(bis);
      return cert.getPublicKey();
    } catch (Exception e) {
      log.error("load public key failed.", e);
    }return null;
  }

  public static String sign(String plainText, String charset, String pfxFile, String pfxPwd, String privateKeyPwd)
  {
    try
    {
      Signature signature = Signature.getInstance(SHA1withRSA);
      signature.initSign(loadPrivateKey(pfxFile, pfxPwd, privateKeyPwd));
      if ((charset != null) && (charset.length() > 0))
        signature.update(plainText.getBytes(charset));
      else {
        signature.update(plainText.getBytes());
      }
      byte[] sign = signature.sign();
      return new String(AsciiUtil.hex2Ascii(sign));
    } catch (Exception e) {
      log.error("", e);
    }
    return null;
  }

  public static String sign(String plainText, String pfxFile, String pfxPwd, String privateKeyPwd)
  {
    return sign(plainText, null, pfxFile, pfxPwd, privateKeyPwd);
  }

  public boolean verifySignature(String sign, String plainText, String cerFile) {
    try {
      PublicKey key = loadPublicKey(cerFile);
      byte[] signArray = AsciiUtil.ascii2Hex(sign.getBytes());
      Signature signature = Signature.getInstance(SHA1withRSA);
      signature.initVerify(key);
      signature.update(plainText.getBytes());
      return signature.verify(signArray);
    } catch (Exception e) {
      log.error("", e);
    }
    return false;
  }

  public static boolean verifySignatureWithCharset(String sign, String plainText, String cerFile, String charset)
  {
    try {
      PublicKey key = loadPublicKey(cerFile);
      byte[] signArray = AsciiUtil.ascii2Hex(sign.getBytes());
      Signature signature = Signature.getInstance(SHA1withRSA);
      signature.initVerify(key);
      signature.update(plainText.getBytes(charset));
      return signature.verify(signArray);
    } catch (Exception e) {
      log.error("", e);
    }
    return false;
  }

  public static MessageDigest getMessageDigest(String algorithm)
  {
    MessageDigest digest = null;
    try {
      digest = MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    }
    return digest;
  }

  public static String MD5(String input)
  {
    MessageDigest digest = null;
    byte[] resBytes = null;
    try {
      digest = getMessageDigest(MD5);
      digest.update(input.getBytes(CHARSET));
      resBytes = digest.digest();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return new String(Base64Util.encode(resBytes));
  }

  public static String SHA1(String input)
  {
    MessageDigest digest = null;
    byte[] resBytes = null;
    try {
      digest = getMessageDigest(SHA1);
      digest.update(input.getBytes(CHARSET));
      resBytes = digest.digest();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return new String(Base64Util.encode(resBytes));
  }

  public static void main(String[] args) {
    String strSendData = "test date";
    String sign = sign(strSendData, "GBK", "/Volumes/HD/Downloads/weg_private_key.pfx", "aipay123456", "aipay654321");

    System.out.println(sign);
    boolean ret = verifySignatureWithCharset(sign, strSendData, "/Volumes/HD/Downloads/weg_public_key.cer", "GBK");

    System.out.println(ret);
    System.out.println("lc,MD5加密后的结果:" + MD5("lc"));
    System.out.println("lc,SHA-1加密后的结果:" + SHA1("woego.cn"));
  }
}


text:
/**
 *
 */
package kanatotranselation.popup.actions;

import kanatotranselation.popup.service.UraKanjiToHepburnCapitalTranslation;

import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;

/**
 * @author syany
 *
 */
public class KanjiToHepburnCapital extends KanjiToHepburn {

	/**
	 *
	 */
	public KanjiToHepburnCapital() {
	}

	/* (非 Javadoc)
	 * @see kanatotranselation.popup.actions.KanaToHepburn#run(org.eclipse.jface.action.IAction)
	 */
	@Override
	public void run(IAction action) {
		UraKanjiToHepburnCapitalTranslation.getInstance().translate(targetEditor);

		MessageDialog.openInformation(
			shell,
			"KanaToTranselation",
			"Kanji to Hepburn was executed.");
	}

}


text:
function TextPanel() {

    return {
        restrict: 'E',
        templateUrl: 'directives/text-panel.html',
        scope: {
            info: '='
        }
    }
}

export default {
    name: 'textPanel',
    fn: TextPanel
};


text:
"""Environment that can be used with OpenAI Baselines."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import collections
import cv2
from gfootball.env import football_action_set
from gfootball.env import observation_preprocessing
import gym
import numpy as np

class GetStateWrapper(gym.Wrapper):
  """A wrapper that only dumps traces/videos periodically."""

  def __init__(self, env):
    gym.Wrapper.__init__(self, env)
    self._wrappers_with_support = {
        'CheckpointRewardWrapper', 'FrameStack', 'GetStateWrapper',
        'SingleAgentRewardWrapper', 'SingleAgentObservationWrapper',
        'SMMWrapper', 'PeriodicDumpWriter', 'Simple115StateWrapper',
        'PixelsStateWrapper'
    }

  def _check_state_supported(self):
    o = self
    while True:
      name = o.__class__.__name__
      if o.__class__.__name__ == 'FootballEnv':
        break
      assert name in self._wrappers_with_support, (
          'get/set state not supported'
          ' by {} wrapper').format(name)
      o = o.env

  def get_state(self):
    self._check_state_supported()
    to_pickle = {}
    return self.env.get_state(to_pickle)

  def set_state(self, state):
    self._check_state_supported()
    self.env.set_state(state)

class PeriodicDumpWriter(gym.Wrapper):
  """A wrapper that only dumps traces/videos periodically."""

  def __init__(self, env, dump_frequency, render=False):
    gym.Wrapper.__init__(self, env)
    self._dump_frequency = dump_frequency
    self._render = render
    self._original_dump_config = {
        'write_video': env._config['write_video'],
        'dump_full_episodes': env._config['dump_full_episodes'],
        'dump_scores': env._config['dump_scores'],
    }
    self._current_episode_number = 0

  def step(self, action):
    return self.env.step(action)

  def reset(self):
    if (self._dump_frequency > 0 and
        (self._current_episode_number % self._dump_frequency == 0)):
      self.env._config.update(self._original_dump_config)
      if self._render:
        self.env.render()
    else:
      self.env._config.update({'write_video': False,
                               'dump_full_episodes': False,
                               'dump_scores': False})
      if self._render:
        self.env.disable_render()
    self._current_episode_number += 1
    return self.env.reset()

class Simple115StateWrapper(gym.ObservationWrapper):
  """A wrapper that converts an observation to 115-features state."""

  def __init__(self, env, fixed_positions=False):
    """Initializes the wrapper.

    Args:
      env: an envorinment to wrap
      fixed_positions: whether to fix observation indexes corresponding to teams
    Note: simple115v2 enables fixed_positions option.
    """
    gym.ObservationWrapper.__init__(self, env)
    action_shape = np.shape(self.env.action_space)
    shape = (action_shape[0] if len(action_shape) else 1, 115)
    self.observation_space = gym.spaces.Box(
        low=-np.inf, high=np.inf, shape=shape, dtype=np.float32)
    self._fixed_positions = fixed_positions

  def observation(self, observation):
    """Converts an observation into simple115 (or simple115v2) format."""
    return Simple115StateWrapper.convert_observation(observation, self._fixed_positions)

  @staticmethod
  def convert_observation(observation, fixed_positions):
    """Converts an observation into simple115 (or simple115v2) format.

    Args:
      observation: observation that the environment returns
      fixed_positions: Players and positions are always occupying 88 fields
                       (even if the game is played 1v1).
                       If True, the position of the player will be the same - no
                       matter how many players are on the field:
                       (so first 11 pairs will belong to the first team, even
                       if it has less players).
                       If False, then the position of players from team2
                       will depend on number of players in team1).

    Returns:
      (N, 115) shaped representation, where N stands for the number of players
      being controlled.
    """

    def do_flatten(obj):
      """Run flatten on either python list or numpy array."""
      if type(obj) == list:
        return np.array(obj).flatten()
      return obj.flatten()

    final_obs = []
    for obs in observation:
      o = []
      if fixed_positions:
        for i, name in enumerate(['left_team', 'left_team_direction',
                                  'right_team', 'right_team_direction']):
          o.extend(do_flatten(obs[name]))
          # If there were less than 11vs11 players we backfill missing values
          # with -1.
          if len(o) < (i + 1) * 22:
            o.extend([-1] * ((i + 1) * 22 - len(o)))
      else:
        o.extend(do_flatten(obs['left_team']))
        o.extend(do_flatten(obs['left_team_direction']))
        o.extend(do_flatten(obs['right_team']))
        o.extend(do_flatten(obs['right_team_direction']))

      # If there were less than 11vs11 players we backfill missing values with
      # -1.
      # 88 = 11 (players) * 2 (teams) * 2 (positions & directions) * 2 (x & y)
      if len(o) < 88:
        o.extend([-1] * (88 - len(o)))

      # ball position
      o.extend(obs['ball'])
      # ball direction
      o.extend(obs['ball_direction'])
      # one hot encoding of which team owns the ball
      if obs['ball_owned_team'] == -1:
        o.extend([1, 0, 0])
      if obs['ball_owned_team'] == 0:
        o.extend([0, 1, 0])
      if obs['ball_owned_team'] == 1:
        o.extend([0, 0, 1])

      active = [0] * 11
      if obs['active'] != -1:
        active[obs['active']] = 1
      o.extend(active)

      game_mode = [0] * 7
      game_mode[obs['game_mode']] = 1
      o.extend(game_mode)
      final_obs.append(o)
    return np.array(final_obs, dtype=np.float32)

class PixelsStateWrapper(gym.ObservationWrapper):
  """A wrapper that extracts pixel representation."""

  def __init__(self, env, grayscale=True,
               channel_dimensions=(observation_preprocessing.SMM_WIDTH,
                                   observation_preprocessing.SMM_HEIGHT)):
    gym.ObservationWrapper.__init__(self, env)
    self._grayscale = grayscale
    self._channel_dimensions = channel_dimensions
    action_shape = np.shape(self.env.action_space)
    self.observation_space = gym.spaces.Box(
        low=0,
        high=255,
        shape=(action_shape[0] if len(action_shape) else 1,
               channel_dimensions[1], channel_dimensions[0],
               1 if grayscale else 3),
        dtype=np.uint8)

  def observation(self, obs):
    o = []
    for observation in obs:
      assert 'frame' in observation, ("Missing 'frame' in observations. Pixel "
                                      "representation requires rendering and is"
                                      " supported only for players on the left "
                                      "team.")
      frame = observation['frame']
      if self._grayscale:
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
      frame = cv2.resize(frame, (self._channel_dimensions[0],
                                 self._channel_dimensions[1]),
                         interpolation=cv2.INTER_AREA)
      if self._grayscale:
        frame = np.expand_dims(frame, -1)
      o.append(frame)
    return np.array(o, dtype=np.uint8)

class SMMWrapper(gym.ObservationWrapper):
  """A wrapper that convers observations into a minimap format."""

  def __init__(self, env,
               channel_dimensions=(observation_preprocessing.SMM_WIDTH,
                                   observation_preprocessing.SMM_HEIGHT)):
    gym.ObservationWrapper.__init__(self, env)
    self._channel_dimensions = channel_dimensions
    action_shape = np.shape(self.env.action_space)
    shape = (action_shape[0] if len(action_shape) else 1, channel_dimensions[1],
             channel_dimensions[0],
             len(
                 observation_preprocessing.get_smm_layers(
                     self.env.unwrapped._config)))
    self.observation_space = gym.spaces.Box(
        low=0, high=255, shape=shape, dtype=np.uint8)

  def observation(self, obs):
    return observation_preprocessing.generate_smm(
        obs, channel_dimensions=self._channel_dimensions,
        config=self.env.unwrapped._config)

class SingleAgentObservationWrapper(gym.ObservationWrapper):
  """A wrapper that returns an observation only for the first agent."""

  def __init__(self, env):
    gym.ObservationWrapper.__init__(self, env)
    self.observation_space = gym.spaces.Box(
        low=env.observation_space.low[0],
        high=env.observation_space.high[0],
        dtype=env.observation_space.dtype)

  def observation(self, obs):
    return obs[0]

class SingleAgentRewardWrapper(gym.RewardWrapper):
  """A wrapper that converts an observation to a minimap."""

  def __init__(self, env):
    gym.RewardWrapper.__init__(self, env)

  def reward(self, reward):
    return reward[0]

class CheckpointRewardWrapper(gym.RewardWrapper):
  """A wrapper that adds a dense checkpoint reward."""

  def __init__(self, env):
    gym.RewardWrapper.__init__(self, env)
    self._collected_checkpoints = {}
    self._num_checkpoints = 10
    self._checkpoint_reward = 0.1

  def reset(self):
    self._collected_checkpoints = {}
    return self.env.reset()

  def get_state(self, to_pickle):
    to_pickle['CheckpointRewardWrapper'] = self._collected_checkpoints
    return self.env.get_state(to_pickle)

  def set_state(self, state):
    from_pickle = self.env.set_state(state)
    self._collected_checkpoints = from_pickle['CheckpointRewardWrapper']
    return from_pickle

  def reward(self, reward):
    observation = self.env.unwrapped.observation()
    if observation is None:
      return reward

    assert len(reward) == len(observation)

    for rew_index in range(len(reward)):
      o = observation[rew_index]
      if reward[rew_index] == 1:
        reward[rew_index] += self._checkpoint_reward * (
            self._num_checkpoints -
            self._collected_checkpoints.get(rew_index, 0))
        self._collected_checkpoints[rew_index] = self._num_checkpoints
        continue

      # Check if the active player has the ball.
      if ('ball_owned_team' not in o or
          o['ball_owned_team'] != 0 or
          'ball_owned_player' not in o or
          o['ball_owned_player'] != o['active']):
        continue

      d = ((o['ball'][0] - 1) ** 2 + o['ball'][1] ** 2) ** 0.5

      # Collect the checkpoints.
      # We give reward for distance 1 to 0.2.
      while (self._collected_checkpoints.get(rew_index, 0) <
             self._num_checkpoints):
        if self._num_checkpoints == 1:
          threshold = 0.99 - 0.8
        else:
          threshold = (0.99 - 0.8 / (self._num_checkpoints - 1) *
                       self._collected_checkpoints.get(rew_index, 0))
        if d > threshold:
          break
        reward[rew_index] += self._checkpoint_reward
        self._collected_checkpoints[rew_index] = (
            self._collected_checkpoints.get(rew_index, 0) + 1)
    return reward

class FrameStack(gym.Wrapper):
  """Stack k last observations."""

  def __init__(self, env, k):
    gym.Wrapper.__init__(self, env)
    self.obs = collections.deque([], maxlen=k)
    low = env.observation_space.low
    high = env.observation_space.high
    low = np.concatenate([low] * k, axis=-1)
    high = np.concatenate([high] * k, axis=-1)
    self.observation_space = gym.spaces.Box(
        low=low, high=high, dtype=env.observation_space.dtype)

  def reset(self):
    observation = self.env.reset()
    self.obs.extend([observation] * self.obs.maxlen)
    return self._get_observation()

  def get_state(self, to_pickle):
    to_pickle['FrameStack'] = self.obs
    return self.env.get_state(to_pickle)

  def set_state(self, state):
    from_pickle = self.env.set_state(state)
    self.obs = from_pickle['FrameStack']
    return from_pickle

  def step(self, action):
    observation, reward, done, info = self.env.step(action)
    self.obs.append(observation)
    return self._get_observation(), reward, done, info

  def _get_observation(self):
    return np.concatenate(list(self.obs), axis=-1)

class MultiAgentToSingleAgent(gym.Wrapper):
  """Converts raw multi-agent observations to single-agent observation.

  It returns observations of the designated player on the team, so that
  using this wrapper in multi-agent setup is equivalent to controlling a single
  player. This wrapper is used for scenarios with control_all_players set when
  agent controls only one player on the team. It can also be used
  in a standalone manner:

  env = gfootball.env.create_environment(env_name='tests/multiagent_wrapper',
      number_of_left_players_agent_controls=11)
  observations = env.reset()
  single_observation = MultiAgentToSingleAgent.get_observation(observations)
  single_action = agent.run(single_observation)
  actions = MultiAgentToSingleAgent.get_action(single_action, observations)
  env.step(actions)
  """

  def __init__(self, env, left_players, right_players):
    assert left_players < 2
    assert right_players < 2
    players = left_players + right_players
    gym.Wrapper.__init__(self, env)
    self._observation = None
    if players > 1:
      self.action_space = gym.spaces.MultiDiscrete([env._num_actions] * players)
    else:
      self.action_space = gym.spaces.Discrete(env._num_actions)

  def reset(self):
    self._observation = self.env.reset()
    return self._get_observation()

  def step(self, action):
    assert self._observation, 'Reset must be called before step'
    action = MultiAgentToSingleAgent.get_action(action, self._observation)
    self._observation, reward, done, info = self.env.step(action)
    return self._get_observation(), reward, done, info

  def _get_observation(self):
    return MultiAgentToSingleAgent.get_observation(self._observation)

  @staticmethod
  def get_observation(observation):
    assert 'designated' in observation[
        0], 'Only raw observations can be converted'
    result = []
    for obs in observation:
      if obs['designated'] == obs['active']:
        result.append(obs)
    return result

  @staticmethod
  def get_action(actions, orginal_observation):
    assert 'designated' in orginal_observation[
        0], 'Only raw observations can be converted'
    result = [football_action_set.action_builtin_ai] * len(orginal_observation)
    action_idx = 0
    for idx, obs in enumerate(orginal_observation):
      if obs['designated'] == obs['active']:
        assert action_idx < len(actions)
        result[idx] = actions[action_idx]
        action_idx += 1
    return result