text:
var test = require('tape');
var stream = require('stream');
var _ = require('underscore');
var fs = require('fs');
var path = require('path');
var url = require('url');
var assert = require('assert');
var tm = require('../lib/tm');
var style = require('../lib/style');
var defpath = tm.join(path.dirname(require.resolve('mapbox-studio-default-style')));
var mockOauth = require('../lib/mapbox-mock')(require('express')());
var Vector = require('tilelive-vector');
var tilelive = require('tilelive');
var testutil = require('./util');
var UPDATE = !!process.env.UPDATE;
var tmp = tm.join(require('os').tmpdir(), 'mapbox-studio');
var creds = {
    account: 'test',
    accesstoken: 'testaccesstoken'
};

var server;
var localstyle = 'tmstyle://' + tm.join(__dirname, 'fixtures-local style');
var fontstyle = 'tmstyle://' + tm.join(__dirname, 'fixtures-font style');
var tmppath = tm.join(tmp, 'Style ШЖФ -' + (+new Date));

test('setup: config ' + __filename, function(t) {
    tm.config({
        log: false,
        db: path.join(tmppath, 'app.db'),
        fonts: path.join(tmppath, 'fonts'),
        cache: path.join(tmppath, 'cache')
    }, t.end);
});

test('setup: mockserver', function(t) {
    tm.db.set('oauth', creds);
    tm.db.set('MapboxAPIAuth', 'http://localhost:3001');
    tm.db.set('MapboxAPITile', 'http://localhost:3001');
    server = mockOauth.listen(3001, t.end);
});

test('loads default style from disk', function(t) {
    style('tmstyle://' + defpath, function(err, proj) {
        t.ifError(err);
        t.ok('style.mss' in proj.data.styles, 'style load expands stylesheets');
        t.equal(proj.data.background, 'rgba(255,255,255,1.00)', 'style load determines map BG color');
        t.end();
    });
});

test('loads local style via tilelive', function(assert) {
    style.clear(localstyle);
    assert.equal(style.cache[localstyle] === undefined, true, 'uncached');
    tilelive.load(localstyle, function(err, proj) {
        assert.ifError(err);
        assert.equal(proj.data.id, localstyle);
        assert.deepEqual(style.cache[localstyle] === proj, true, 'cached');
        assert.end();
    });
});

test('refresh style in memory', function(t) {
    testutil.createTmpProject('style-save', localstyle, function(err, tmpid, data) {
    t.ifError(err);

    style.refresh(_({id:style.tmpid()}).defaults(data), function(err, source) {
        t.ifError(err);
        t.ok(source);
        t.end();
    });

    });
});

test('refresh style (invalid)', function(t) {
    testutil.createTmpProject('style-save', localstyle, function(err, tmpid, data) {
        t.ifError(err);
        style.refresh(_({id:style.tmpid(),minzoom:-1}).defaults(data), function(err, source) {
            t.equal(err.toString(), 'Error: minzoom must be an integer between 0 and 30', 'style.refresh() errors on invalid style');
            t.end();
        });
    });
});

test('refresh style (invalid bookmarks)', function(t) {
    testutil.createTmpProject('style-save', localstyle, function(err, tmpid, data) {
        t.ifError(err);
        style.refresh(_({id:style.tmpid(),_bookmarks:'asdf'}).defaults(data), function(err, source) {
            t.equal(err.toString(), 'Error: bookmarks must be an array', 'style.refresh() errors on invalid style');
            t.end();
        });
    });
});

test('save temporary', function(t) {
    testutil.createTmpProject('style-save', localstyle, function(err, tmpid, data) {
        t.ifError(err);
        style.save(_({id:style.tmpid()}).defaults(data), function(err) {
            t.equal(/^Error: Cannot save temporary style/.test(err.toString()), true, 'style.save() errors on temporary style');
            t.end();
        });
    });
});

test('saves style to disk', function(t) {
    testutil.createTmpProject('style-save', localstyle, function(err, tmpid, data) {
    t.ifError(err);

    style.save(_({id:tmpid}).defaults(data), function(err, source) {
        t.ifError(err);
        t.ok(source);

        var expect = {};
        expect['style-save-project.yml'] = path.join(__dirname,'expected','style-save-project.yml');
        expect['style-save-project.xml'] = path.join(__dirname,'expected','style-save-project.xml');
        expect['style-save-a.mss'] = path.join(__dirname,'expected','style-save-a.mss');
        expect['style-save-b.mss'] = path.join(__dirname,'expected','style-save-b.mss');

        var output = {};
        var tmpdir = tm.parse(tmpid).dirname;
        output['project.yml'] = path.join(tmpdir,'project.yml');
        output['project.xml'] = path.join(tmpdir,'project.xml');
        output['a.mss'] = path.join(tmpdir,'a.mss');
        output['b.mss'] = path.join(tmpdir,'b.mss');

        if (UPDATE) {
            fs.writeFileSync(expect['style-save-project.yml'], fs.readFileSync(output['project.yml']));
            fs.writeFileSync(expect['style-save-project.xml'], fs.readFileSync(output['project.xml']));
            fs.writeFileSync(expect['style-save-a.mss'], fs.readFileSync(output['a.mss']));
            fs.writeFileSync(expect['style-save-b.mss'], fs.readFileSync(output['b.mss']));
        }

        t.equal(fs.readFileSync(output['project.yml'],'utf8'), fs.readFileSync(expect['style-save-project.yml'],'utf8'));
        t.equal(fs.readFileSync(output['project.xml'],'utf8'), fs.readFileSync(expect['style-save-project.xml'],'utf8'));
        t.equal(fs.readFileSync(output['a.mss'],'utf8'), fs.readFileSync(expect['style-save-a.mss'],'utf8'));
        t.equal(fs.readFileSync(output['b.mss'],'utf8'), fs.readFileSync(expect['style-save-b.mss'],'utf8'));

        t.end();

        // @TODO commented out as this would require true access to the mapbox API.
        // This setTimeout is here because thumbnail generation on save
        // is an optimistic operation (e.g. callback does not wait for it
        // to complete).
        // setTimeout(function() {
        //     t.ok(fs.existsSync(path.join(tmpdir,'.thumb.png')), 'saves thumb');
        //     t.end();
        // }, 500);
    });

    });
});

test('save to disk with fonts ', function(t) {
    // Uses an example style with assets to test pre-save dir copy.
    style.info(fontstyle, function(err, data) {
        t.ifError(err);
        var tmpid = fontstyle;
        var permid = path.join(tmp, 'style-saveas-' + Math.random().toString(36).split('.').pop());
        style.save(_({_tmp:tmpid, id:permid}).defaults(data), function(err, source) {

            t.ifError(err);
            t.ok(source);
            t.equal(source.data._tmp, false);
            var tmpdir = tm.parse(permid).dirname;
            t.deepEqual(source.data.fonts, ['Comic Neue Angular Bold Oblique', 'Comic Neue Oblique'], ' returns correct fonts');

            // Remove one of the fonts
            fs.unlink(tm.join(tmpdir,'ComicNeue-Regular-Oblique.ttf'), function(err) {
                t.ifError(err);
                style.refresh(_({_tmp:tmpid, id:permid}).defaults(data), function(err, source) {
                    t.ifError(err);
                    t.deepEqual(source.data.fonts, ['Comic Neue Angular Bold Oblique'], ' returns correct fonts');
                    t.end();
                });
            });
        });
    });
});

test('save as tmp => perm', function(t) {
    // Uses an example style with assets to test pre-save dir copy.
    style.info(style.examples['mapbox-studio-comic'], function(err, data) {
        t.ifError(err);
        var tmpid = style.examples['mapbox-studio-comic'];
        var permid = path.join(tmp, 'style-saveas-' + Math.random().toString(36).split('.').pop());
        style.save(_({_tmp:tmpid, id:permid}).defaults(data), function(err, source) {
            t.ifError(err);
            t.ok(source);
            t.equal(source.data._tmp, false);
            var tmpdir = tm.parse(permid).dirname;
            t.ok(fs.existsSync(tm.join(tmpdir,'img')));
            t.ok(fs.existsSync(tm.join(tmpdir,'project.yml')));
            t.ok(fs.existsSync(tm.join(tmpdir,'project.xml')));
            t.ok(!fs.existsSync(tm.join(tmpdir,'_gfx')));
            t.end();
        });
    });
});

test('save as tmp => perm', function(t) {
    // Uses an example style with assets to test pre-save dir copy.

    style.info(style.examples['mapbox-studio-comic'], function(err, data) {
        t.ifError(err);
        var tmpid = style.examples['mapbox-studio-comic'];
        var permid = path.join(tmp, 'style-saveas-' + Math.random().toString(36).split('.').pop());
        style.save(_({_tmp:tmpid, id:permid}).defaults(data), function(err, source) {
            t.ifError(err);
            t.ok(source);
            t.equal(source.data._tmp, false);
            var tmpdir = tm.parse(permid).dirname;
            t.ok(fs.existsSync(tm.join(tmpdir,'img')));
            t.ok(fs.existsSync(tm.join(tmpdir,'project.yml')));
            t.ok(fs.existsSync(tm.join(tmpdir,'project.xml')));
            t.ok(!fs.existsSync(tm.join(tmpdir,'_gfx')));
            t.end();
        });
    });
});

test('saves style with space', function(t) {
    testutil.createTmpProject('style-save space', localstyle, function(err, tmpid, data) {
        t.ifError(err);
        t.end();
    });
});

test('packages style to tm2z', function(t) {
    testutil.createTmpProject('style-save', localstyle, function(err, tmpid, data) {
    t.ifError(err);

    var tmptm2z = tm.parse(tmpid).dirname + '.tm2z';
    style.toPackage(tmpid, tmptm2z, function(err) {
        t.ifError(err);
        var stat = fs.statSync(tmptm2z);
        t.ok(fs.existsSync(tmptm2z));
        t.ok(stat.isFile(), 'writes file');
        t.ok(846, stat.size, 'with correct size');
        Vector.tm2z(url.parse('tm2z://' + tmptm2z), function(err, source) {
            t.ifError(err, 'tilelive-vector succeeds in reading tm2z');
            t.ok(source);
            t.end();
        });
    });

    });
});

test('fails to package tmp style', function(t) {
    testutil.createTmpProject('style-save', localstyle, function(err, tmpid, data) {
    t.ifError(err);

    var tmptm2z = tm.parse(tmpid).dirname + '.tm2z';
    style.toPackage(style.tmpid(), tmptm2z, function(err) {
        t.ok(err);
        t.equal('Error: temporary style must be saved first', err.toString());
        t.end();
    });

    });
});

test('style.info: fails on bad path', function(t) {
    style.info('tmstyle:///path/does/not/exist', function(err, info) {
        t.ok(err);
        t.equal('ENOENT', err.code);
        t.end();
    });
});

test('style.info: reads style YML', function(t) {
    var tmpid = 'tmstyle://' + defpath;
    style.info(tmpid, function(err, info) {
        t.ifError(err);
        t.equal(info.id, tmpid, 'style.info adds id key');
        t.equal(info._tmp, false, 'style info adds _tmp=false');

        var basepath = tm.parse(tmpid).dirname;
        info.id = info.id.replace(basepath, '[BASEPATH]');

        var filepath = path.join(__dirname,'expected','style-info-default.json');
        if (UPDATE) {
            fs.writeFileSync(filepath, JSON.stringify(info, null, 2));
        }
        t.deepEqual(info, require(filepath));
        t.end();
    });
});

test('style.info: reads style YML (tmp)', function(t) {
    var tmpid = 'tmpstyle://' + defpath;
    style.info(tmpid, function(err, info) {
        t.ifError(err);
        t.equal(info.id, tmpid, 'style.info adds id key');
        t.equal(info._tmp, tmpid, 'style info adds _tmp=id');

        var basepath = tm.parse(tmpid).dirname;
        info.id = info.id.replace(basepath, '[BASEPATH]');
        info._tmp = info._tmp.replace(basepath, '[BASEPATH]');

        var filepath = path.join(__dirname,'expected','style-info-default-tmp.json');
        if (UPDATE) {
            fs.writeFileSync(filepath, JSON.stringify(info, null, 2));
        }
        t.deepEqual(info, require(filepath));
        t.end();
    });
});

test('style.info: reads style YML (bookmarks)', function(t) {
    style.info(localstyle, function(err, info) {
        t.ifError(err);
        t.equal(info.id, localstyle, 'style.info adds id key');
        t.equal(info._tmp, false, 'style info adds _tmp=false');

        var basepath = tm.parse(localstyle).dirname;
        info.id = info.id.replace(basepath, '[BASEPATH]');

        var filepath = path.join(__dirname,'expected','style-info-bookmarks.json');
        if (UPDATE) {
            fs.writeFileSync(filepath, JSON.stringify(info, null, 2));
        }
        t.deepEqual(info, require(filepath));
        t.end();
    });
});

test('style.info: invalid yaml (non-object)', function(t) {
    style.info('tmstyle://' + path.join(__dirname,'fixtures-invalid nonobj'), function(err, source) {
        t.ok(err);
        t.ok(/^Error: Invalid YAML/.test(err.toString()));
        t.end();
    });
});

test('style.info: invalid bookmarks', function(t) {
    style.info('tmstyle://' + path.join(__dirname,'fixtures-invalid badbookmarks'), function(err, source) {
        t.ok(err);
        t.ok(/^JS-YAML: end of the stream or a document separator is expected/.test(err.toString()));
        t.end();
    });
});

test('style.info: invalid yaml', function(t) {
    style.info('tmstyle://' + path.join(__dirname,'fixtures-invalid yaml'), function(err, source) {
        t.ok(err);
        t.ok(/^JS-YAML/.test(err.toString()));
        t.end();
    });
});

test('style.toXML: fails on invalid source', function(t) {
    style.toXML({
        id:'tmstyle:///tmp-1234',
        source:'tmsource:///foobar'
    }, function(err, xml) {
        t.ok(err);
        t.equal('ENOENT', err.code);
        t.end();
    });
});

test('style.toXML: compiles', function(t) {
    style.toXML({
        id:'tmstyle:///tmp-1234',
        source:'mapbox:///mapbox.mapbox-streets-v2',
        styles:{'style.mss': '#water { polygon-fill:#fff }'},
        _properties:{bridge:{'group-by':'layer'}}
    }, function(err, xml) {
        t.ifError(err);
        t.ok(/<Map srs/.test(xml), 'looks like Mapnik XML');
        t.ok(/<Layer name="water"/.test(xml), 'includes layer');
        t.ok(/group-by="layer"/.test(xml), 'includes layer properties');
        t.ok(/<PolygonSymbolizer fill="#ffffff"/.test(xml), 'includes rule');
        t.ok(xml.indexOf('<Layer name="road"') < xml.indexOf('<Layer name="bridge"'));
        t.end();
    });
});

test('style.toXML: compiles layer order + classed layers', function(t) {
    style.toXML({
        id:'tmstyle:///tmp-1234',
        source:'mapbox:///mapbox.mapbox-streets-v2',
        styles:{'style.mss': '#water { polygon-fill:#fff } #road.line::line { line-width:0.5 } #road.label::label { line-width:1 }'},
        layers:[ 'water', 'bridge', 'poi_label', 'road.line', 'tunnel', 'road.label' ],
        _properties:{bridge:{'group-by':'layer'}}
    }, function(err, xml) {
        t.ifError(err);
        t.ok(/<Map srs/.test(xml), 'looks like Mapnik XML');
        t.ok(/<Layer name="water"/.test(xml), 'includes layer');
        t.ok(/group-by="layer"/.test(xml), 'includes layer properties');
        t.ok(/<PolygonSymbolizer fill="#ffffff"/.test(xml), 'includes rule');
        // Moves specified layers last, in order.
        t.ok(xml.indexOf('<Layer name="road"') > xml.indexOf('<Layer name="poi_label"'));
        t.ok(xml.indexOf('<Layer name="road"') > xml.indexOf('<Layer name="road_label"'));
        t.ok(xml.indexOf('<Layer name="tunnel"') > xml.indexOf('<Layer name="road"'));
        t.ok(xml.indexOf('<StyleName>road-label</StyleName>') > xml.indexOf('<StyleName>road-line</StyleName>'));
        t.end();
    });
});

test('style.toXML: compiles data params', function(t) {
    style.toXML({
        id:'tmstyle:///tmp-1234',
        source:'mapbox:///mapbox.mapbox-streets-v2',
        name:'test',
        description:'test style',
        attribution:'test',
        bounds:[-180,-85,180,85],
        center:[0,0,3],
        minzoom:0,
        maxzoom:22,
        customproperty:'foobar'
    }, function(err, xml) {
        t.ifError(err);
        t.ok(/<Map srs/.test(xml));
        t.ok(/<Parameter name="name"/.test(xml));
        t.ok(/<Parameter name="description"/.test(xml));
        t.ok(/<Parameter name="attribution"/.test(xml));
        t.ok(/<Parameter name="bounds">-180,-85,180,85/.test(xml));
        t.ok(/<Parameter name="center">0,0,3/.test(xml));
        t.ok(/<Parameter name="minzoom">0/.test(xml));
        t.ok(/<Parameter name="maxzoom">22/.test(xml));
        t.ok(/<Parameter name="source"><\!\[CDATA\[mapbox:\/\/\/mapbox.mapbox-streets-v2\]\]>/.test(xml));
        t.ok(!/<Parameter name="custom/.test(xml));
        t.end();
    });
});

test('style.toXML: compiles raster', function(t) {
    style.toXML({
        id:'tmstyle:///tmp-1234',
        source:'mapbox:///mapbox.satellite',
        styles:{'style.mss': '#_image { raster-opacity:1; }'}
    }, function(err, xml) {
        t.ifError(err);
        t.ok(/<Map srs/.test(xml));
        t.ok(/<Layer name="_image"/.test(xml), 'includes _image layer');
        t.ok(/<Style name="_image"/.test(xml), 'includes style for _image layer');
        t.ok(/<RasterSymbolizer opacity="1"/.test(xml), 'includes raster opacity');
        t.ok(/<Parameter name="source"><\!\[CDATA\[mapbox:\/\/\/mapbox.satellite\]\]>/.test(xml));
        t.end();
    });
});

test('style.layervalidate: fails if layers is not an array', function(t) {
    var err = style.layervalidate('foo');
    t.equal(err.toString(), 'Error: Layers must be an array')
    t.end();
});

test('style.layervalidate: fails on invalid characters', function(t) {
    var err = style.layervalidate(['foo','foo.bar','foo/bar']);
    t.equal(err.toString(), 'Error: Invalid characters in layer foo/bar')
    t.end();
});

test('style.layervalidate: saves with valid layer names', function(t) {
    var err = style.layervalidate(['foo','foo.bar', 'foo.bar-bar']);
    t.ifError(err);
    t.end();
});

test('style.upload: uploads stylesheet', function(t) {
    var id = 'tmstyle://' + __dirname + '/fixtures-upload';
    var cache = path.join(tmppath, 'cache');
    style.upload(id, function(err, info){
        t.ifError(err);
        t.assert(!fs.existsSync(path.join(cache, 'package-' + info._prefs.mapid + '.tm2z')), 'file unlinked');
        t.assert(/test\..{8}/.test(info._prefs.mapid), 'mapid correctly generated');
        t.assert(true, 'uploads stylesheet');
        t.end();
    });
});

test('style.upload: errors on unsaved id', function(t) {
    style.upload(style.tmpid(), function(err, info){
        t.equal(err.message, 'Style must be saved first');
        t.end();
    });
});

test('cleanup ' + __filename, function(t) {
    server.close(function() { t.end(); });
});


text:
package com.dw.log4j_1_12;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class DocumentBuilderFactoryTest {
	public static void main(String argv[])
	{
		try {
			//clazz.getResource("/org/apache/log4j/xml/log4j.dtd").getPath();
			//String path = DocumentBuilderFactoryTest.class.getResource("/org/apache/log4j/xml/log4j.dtd").getPath();

			File fXmlFile = new File("/Users/ewu/dev/Java/JavaMain/src/com/dw/log4j_1_12/log4j.xml");
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

			Document doc = dBuilder.parse(fXmlFile);

			doc.getDocumentElement().normalize();

			System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

			NodeList nList = doc.getElementsByTagName("staff");

			System.out.println("----------------------------");

			for (int temp = 0; temp < nList.getLength(); temp++) {

				Node nNode = nList.item(temp);

				System.out.println("\nCurrent Element :" + nNode.getNodeName());

				if (nNode.getNodeType() == Node.ELEMENT_NODE) {

					Element eElement = (Element) nNode;

					System.out.println("Staff id : " + eElement.getAttribute("id"));
					System.out.println(
							"First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
					System.out.println(
							"Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
					System.out.println(
							"Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
					System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());

				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.ftfl.googlemap.Map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.model.LatLng;

public class DirectionsJSONParser {

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public List<List<HashMap<String,String>>> parse(JSONObject jObject){

        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<HashMap<String, String>>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = "";
                        polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for(int l=0;l<list.size();l++){
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                            hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                            path.add(hm);
                        }
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }catch (Exception e){
        }

        return routes;
    }

    /**
     * Method to decode polyline points
     * Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
     * */
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
org.sword.wechat4j.token 类分层结构
</TITLE>

<META NAME="date" CONTENT="2015-02-03">

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

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

 上一个
 下一个

  框架
 无框架

  所有类

软件包 org.sword.wechat4j.token 的分层结构

软件包分层结构:
所有软件包

类分层结构

java.lang.Object

org.sword.wechat4j.token.Token

org.sword.wechat4j.token.AccessToken
org.sword.wechat4j.token.Ticket

org.sword.wechat4j.token.TokenListener (implements javax.servlet.ServletContextListener)

org.sword.wechat4j.token.TokenProxy

枚举分层结构

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

org.sword.wechat4j.token.TicketType

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

 上一个
 下一个

  框架
 无框架

  所有类


text:
package etcd

import (
	"fmt"
	"os"
	"testing"
	"time"

	"github.com/hashicorp/vault/helper/logformat"
	"github.com/hashicorp/vault/physical"
	log "github.com/mgutz/logxi/v1"
)

func TestEtcd3Backend(t *testing.T) {
	addr := os.Getenv("ETCD_ADDR")
	if addr == "" {
		t.Skipf("Skipped. No etcd3 server found")
	}

	logger := logformat.NewVaultLogger(log.LevelTrace)

	b, err := NewEtcdBackend(map[string]string{
		"path":     fmt.Sprintf("/vault-%d", time.Now().Unix()),
		"etcd_api": "3",
	}, logger)
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	physical.ExerciseBackend(t, b)
	physical.ExerciseBackend_ListPrefix(t, b)

	ha, ok := b.(physical.HABackend)
	if !ok {
		t.Fatalf("etcd3 does not implement HABackend")
	}
	physical.ExerciseHABackend(t, ha, ha)
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import abc
import six

class NetModifier(six.with_metaclass(abc.ABCMeta, object)):
    """
    An abstraction class for supporting modifying a generated net.
    Inherited classes should implement the modify_net method where
    related operators are added to the net.

    Example usage:
        modifier = SomeNetModifier(opts)
        modifier(net)
    """

    def __init__(self):
        pass

    @abc.abstractmethod
    def modify_net(self, net, init_net=None, grad_map=None, blob_to_device=None):
        pass

    def __call__(self, net, init_net=None, grad_map=None, blob_to_device=None):
        self.modify_net(
            net,
            init_net=init_net,
            grad_map=grad_map,
            blob_to_device=blob_to_device)


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="IFileVerifier.cs" company="Appccelerate">
//   Copyright (c) 2008-2015
//
//   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.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Appccelerate.CheckHintPathTask
{
    public interface IFileVerifier
    {
        bool DoesFileExist(string path);
    }
}


text:
package alluxio.master.file.options;

import alluxio.CommonTestUtils;
import alluxio.thrift.ListStatusTOptions;
import alluxio.thrift.LoadMetadataTType;
import alluxio.wire.LoadMetadataType;

import org.junit.Assert;
import org.junit.Test;

/**
 * Tests for the {@link ListStatusOptions} class.
 */
public class ListStatusOptionsTest {
  @Test
  public void defaults() {
    ListStatusOptions options = ListStatusOptions.defaults();
    Assert.assertEquals(LoadMetadataType.Once, options.getLoadMetadataType());
  }

  @Test
  public void fields() {
    ListStatusOptions options = ListStatusOptions.defaults();
    Assert.assertEquals(LoadMetadataType.Once, options.getLoadMetadataType());
    options.setLoadMetadataType(LoadMetadataType.Always);
    Assert.assertEquals(LoadMetadataType.Always, options.getLoadMetadataType());
  }

  @Test
  public void fromThrift() {
    ListStatusTOptions listStatusTOptions = new ListStatusTOptions();
    listStatusTOptions.setLoadMetadataType(LoadMetadataTType.Always);
    ListStatusOptions options = new ListStatusOptions(listStatusTOptions);
    Assert.assertEquals(LoadMetadataType.Always, options.getLoadMetadataType());
  }

  @Test
  public void equalsTest() throws Exception {
    CommonTestUtils.testEquals(ListStatusOptions.class);
  }
}


text:
// ******************************************************************
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE CODE OR THE USE OR OTHER DEALINGS IN THE CODE.
// ******************************************************************

using System;

namespace Microsoft.Toolkit.Uwp.Notifications
{
    /// <summary>
    /// A class that represents the progress bar's value.
    /// </summary>
    public sealed class AdaptiveProgressBarValue
    {
        /// <summary>
        /// Gets or sets the value (0-1) representing the percent complete.
        /// </summary>
        public double Value { get; set; }

        /// <summary>
        /// Gets or sets whether the progress bar is indeterminate.
        /// </summary>
        public bool IsIndeterminate { get; set; }

        /// <summary>
        /// Private constructor
        /// </summary>
        private AdaptiveProgressBarValue()
        {
        }

        internal string ToXmlString()
        {
            if (IsIndeterminate)
            {
                return "indeterminate";
            }

            return Value.ToString();
        }

        /// <summary>
        /// Returns an indeterminate progress bar value.
        /// </summary>
        public static AdaptiveProgressBarValue Indeterminate
        {
            get
            {
                return new AdaptiveProgressBarValue()
                {
                    IsIndeterminate = true
                };
            }
        }

        /// <summary>
        /// Returns a progress bar value using the specified value (0-1) representing the percent complete.
        /// </summary>
        /// <param name="d">The value, 0-1, inclusive.</param>
        /// <returns>A progress bar value.</returns>
        public static AdaptiveProgressBarValue FromValue(double d)
        {
            if (d < 0 || d > 1)
            {
                throw new ArgumentOutOfRangeException("d", "Value must be between 0 and 1, inclusive.");
            }

            return new AdaptiveProgressBarValue()
            {
                Value = d
            };
        }
    }
}


text:
using System;

namespace Comsys.Core
{
    using System.Diagnostics;

    using GraphSharp;
    using QuickGraph;

    [DebuggerDisplay("L{Source.id}->{Target.id}")]
    public class GraphLink : WeightedEdge<GraphNode>
    {
        public GraphLink(GraphNode source, GraphNode target)
            : base(source, target)
        {
        }

        public GraphLink(GraphNode source, GraphNode target, double weight)
            : base(source, target, weight)
        {
        }

    }
}


text:
> :warning: **DEPRECATION NOTICE**: The libo3d3xx libary has been
> superceded by [ifm3d](https://github.com/ifm/ifm3d). Similarly,
> this package has been deprecated in favor of
> [ifm3d-ros](https://github.com/ifm/ifm3d-ros) which is also available
> in the ROS distribution (starting with ROS Kinetic)

o3d3xx-ros
==========
o3d3xx-ros is a wrapper around
[libo3d3xx](https://github.com/lovepark/libo3d3xx) enabling the usage of IFM
Efector O3D3xx ToF cameras from within [ROS](http://ros.org) software
systems.

Software Compatibility Matrix
-----------------------------

             o3d3xx-ros version
             libo3d3xx version
             ROS distribution(s)

             0.1.3
             0.1.9
             Indigo

             0.1.4
             0.1.9
             Indigo

             0.1.5
             0.1.11
             Indigo

             0.1.6
             0.1.11
             Indigo

             0.1.7
             0.2.0
             Indigo

             0.1.8
             0.2.0
             Indigo

             0.2.0
             0.3.0
             Indigo

             0.2.1
             0.4.0
             Indigo

             0.2.2
             0.4.0, 0.4.1, 0.4.2
             Indigo

             0.2.3
             0.4.3
             Indigo, Kinetic

             0.2.4
             0.4.4
             Indigo, Kinetic

             0.2.5
             0.4.5, 0.4.6, 0.4.8, 0.4.9, 0.5.0, 0.6.0, 0.7.0
             Indigo, Kinetic

Prerequisites
-------------

1. [Ubuntu 14.04 or 16.04](http://www.ubuntu.com)
2. [ROS Indigo or Kinetic](http://www.ros.org/install)
3. [libo3d3xx](https://github.com/lovepark/libo3d3xx)

Additionally, your compiler must support C++11. This package has been validated
with:

* g++ 4.8.2 on Ubuntu 14.04 LTS, ROS Indigo
* g++ 5.3.x on Ubuntu 16.04 LTS, ROS Kinetic

Building and Installing the Software
------------------------------------

__NOTE__: Since we are talking about ROS here, we assume you are on Ubuntu
Linux.

You should first ensure that you have installed ROS by following
[these](http://wiki.ros.org/ROS/Installation) instructions. The
`desktop-full` installation is highly recommended.

Next, you should be sure to install
[libo3d3xx](https://github.com/lovepark/libo3d3xx). This ROS package assumes
you have installed libo3d3xx via the supported debian installer. Step-by-step
instructions for that process are located
[here](https://github.com/lovepark/libo3d3xx#full-instructions). If you already
have `libo3d3xx` installed you can skip this step. However, it is important to
point out that the table above denotes a software compatibility matrix and you
should be sure to link `o3d3xx-ros` against a compatible version of
`libo3d3xx`.

We now move on to building o3d3xx-ros.

Building and installing o3d3xx-ros is accomplished by utilizing the ROS
[catkin](http://wiki.ros.org/catkin) tool. There are many tutorials and other
pieces of advice available on-line advising how to most effectively utilize
catkin. However, the basic idea is to provide a clean separation between your
source code repository and your build and runtime environments. The
instructions that now follow represent how we choose to use catkin to build and
_permanently install_ a ROS package from source.

First, we need to decide where we want our software to ultimately be
installed. For purposes of this document, we will assume that we will install
our ROS packages at `~/ros`. For convenience, we add the following to our
`~/.bash_profile`:

    if [ -f /opt/ros/indigo/setup.bash ]; then
        source /opt/ros/indigo/setup.bash
    fi

    cd ${HOME}

    export LPR_ROS=${HOME}/ros

    if [ -d ${LPR_ROS} ]; then
        for i in $(ls ${LPR_ROS}); do
            if [ -d ${LPR_ROS}/${i} ]; then
                if [ -f ${LPR_ROS}/${i}/setup.bash ]; then
                    source ${LPR_ROS}/${i}/setup.bash --extend
                fi
            fi
        done
    fi

Next, we need to get the code from github. We assume we keep all of our git
repositories in `~/dev`.

    $ cd ~/dev
    $ git clone https://github.com/lovepark/o3d3xx-ros.git

We now have the code in `~/dev/o3d3xx-ros`. Next, we want to create a _catkin
workspace_ that we can use to build and install that code from. It is the
catkin philosophy that we do not do this directly in the source directory.

    $ cd ~/dev
    $ mkdir o3d3xx-catkin
    $ cd o3d3xx-catkin
    $ mkdir src
    $ cd src
    $ catkin_init_workspace
    $ ln -s ~/dev/o3d3xx-ros o3d3xx

So, you should have a catkin workspace set up to build the o3d3xx-ros code that
looks basically like:

    [ ~/dev/o3d3xx-catkin/src ]
    tpanzarella@jelly: $ pwd
    /home/tpanzarella/dev/o3d3xx-catkin/src

    [ ~/dev/o3d3xx-catkin/src ]
    tpanzarella@jelly: $ ls -l
    total 0
    lrwxrwxrwx 1 tpanzarella tpanzarella 49 Dec  2 15:26 CMakeLists.txt -> /opt/ros/indigo/share/catkin/cmake/toplevel.cmake
    lrwxrwxrwx 1 tpanzarella tpanzarella 32 Dec  2 15:24 o3d3xx -> /home/tpanzarella/dev/o3d3xx-ros

Now we are ready to build the code.

    $ cd ~/dev/o3d3xx-catkin
    $ catkin_make -DCATKIN_ENABLE_TESTING=ON
    $ catkin_make run_tests
    $ catkin_make -DCMAKE_INSTALL_PREFIX=${LPR_ROS}/o3d3xx install

The ROS package should now be installed in `~/ros/o3d3xx`. To test everything
out you should open a fresh bash shell, and start up a ROS core:

    $ roscore

Open another shell and start the primary camera node:

    $ roslaunch o3d3xx camera.launch ip:=192.168.10.69

__NOTE__: The IP address of your camera may differ. If you are using the
factory default (192.168.0.69), you do not need to specify it on the above
`roslaunch` line.

Open another shell and start the rviz node to visualize the data coming from
the camera:

    $ roslaunch o3d3xx rviz.launch

At this point, you should see an rviz window that looks something like:

![rviz1](doc/figures/rviz1.png)

Congratulations! You can now utilize o3d3xx-ros.

Nodes
-----

### /o3d3xx/camera

This node provides a real-time feed to the camera data. This node is started
from the primary `camera.launch` file:

    $ roslaunch o3d3xx camera.launch

The naming of the camera can be customized via the `ns` (namespace) and `nn`
(node name) command line arguments passed to the `camera.launch` file. For
example, if you specify your roslaunch command as:

    $ roslaunch o3d3xx camera.launch ns:=robot nn:=front_camera

The node will have the name `/robot/front_camera` in the ROS computation
graph.

#### Published Topics

             Topic
             Message
             Description

             /o3d3xx/camera/amplitude
             sensor_msgs/Image
             16-bit gray scale encoding of the sensor Amplitude image
             normalized wrt exposure time.

             /o3d3xx/camera/raw_amplitude
             sensor_msgs/Image
             16-bit gray scale encoding of the sensor Amplitude image
             non-normalized.

             /o3d3xx/camera/cloud
             sensor_msgs/PointCloud2

             A 3D PCL point cloud of point type `XYZI`. In this encoding the
             intensity channel is represented by the corresponding pixel's
             amplitude data. The units of this point cloud are in meters.

             /o3d3xx/camera/confidence
             sensor_msgs/Image

             An 8-bit mono image encoding of the confidence image. The meaning
             of each bit of each pixel value is discussed in the official IFM
             documentation for the camera.

             /o3d3xx/camera/depth
             sensor_msgs/Image

             A 16-bit mono image encoding of the radial depth map from the
             camera. The depth units are in millimeters.

             /o3d3xx/camera/depth_viz
             sensor_msgs/Image

             A rendering of the depth image utilizing a colormap more
             human-friendly for visualization purposes. For performance
             reasons, messages are only published to this topic when the
             `publish_viz_images` parameter is set to true at launch time.

             /o3d3xx/camera/good_bad_pixels
             sensor_msgs/Image

             A binary image showing good vs. bad pixels on the pixel array. Bad
             pixels can be caused by numerous reasons (e.g., motion blur over
             an integration/exposure timestep). Visualizing this data is useful
             for when you are tuning your imager parameters. For performance
             reasons, messages are only published to this topic when the
             `publish_viz_images` parameter is set to true at launch time.

             /o3d3xx/camera/xyz_image
             sensor_msgs/Image

             An OpenCV image encoding (CV_16SC3) of the same point cloud that
             is published to `/o3d3xx/camera/cloud` where the three image planes
             are 0 = x, 1 = y, 2 = z. Units are in millimeters yet the coord
             frame is consistent with the point cloud.

             /o3d3xx/camera/unit_vectors
             sensor_msgs/Image

             An OpenCV image encoding (CV_32FC3) of the rotated unit vectors
             that can be used together with the translation vector from the
             camera extrinsics and the radial distance image to compute the
             cartesian coordinates for each pixel in the imager array off-board
             the camera. This topic is latched.

             /o3d3xx/camera/extrinsics
             Extrinsics.msg

             Extrinsics as reported by the camera. The translation vector here
             is used together with the unit vectors and the radial distance
             image to compute the Cartesian coordinates for each pixel in the
             imager array. It should be noted that for this message, the
             translational units are in mm and the rotational units are in
             degrees. This is to be consistent with the camera eventhough it is
             not necessarily consistent with ROS conventions. Usage of this
             message is really for very specialized use-cases.

#### Advertised Services

        Service Name
        Service Definition
        Description

        /o3d3xx/camera/Config
        Config.srv

        Mutates camera settings based upon an input JSON file. NOTE: Due
        to what appears to be limitations in the YAML parsing of the stock ROS
        `rosservice` command line tool (i.e., it does not handle JSON as string
        payload well) you will have to use the
        /o3d3xx/camera/config_node to configure the camera. This is
        explained in further detail below.

        /o3d3xx/camera/Dump
        Dump.srv

        Dumps the current configuration of the camera to a JSON string. The
        output of this dump is suitable for editing and passing to the `Config`
        service for configuring the camera.

        /o3d3xx/camera/GetVersion
        GetVersion.srv

        Returns the current version of the underlying
        libo3d3xx library
        that this ROS node is linked to.

        /o3d3xx/camera/Rm
        Rm.srv
        Removes an application from the camera. This service will restrict
        removing the current active application.

        /o3d3xx/camera/Trigger
        Trigger.srv

        Sends a software trigger signal to the camera.

#### Parameters

Name	Data Type	Description

        ip
        string
        IP address of the camera

        xmlrpc_port
        int
        TCP port the camera's XMLRPC server is listening on

        password
        string
        Password to use to connect to the camera

        schema_mask
        uint16_t
        Mask controlling which image types to stream back from the
           camera. This is useful for numerous reasons. It allows for
           conserving bandwidth between the host computer and the camera or
           lessens the CPU cycles required by the camera to compute image data
           which may result in an increased frame rate. See the o3d3xx-schema
           command line tool for generating custom masks.

        timeout_millis
        int
        Time, in milliseconds, to block when waiting for a frame from the
        camera before timing out.

        timeout_tolerance_secs
        double
        Time, in seconds, to wait before trying to restart the underlying
        framegrabber if it is currently experiencing timeouts while trying to
        capture image data.

        publish_viz_images
        bool

        In general, for a runtime system, the core data a system will want from
        this camera include the `cloud`, `depth`, `amplitude`, and `confidence`
        images. This node will always publish those data. However, if you set
        this parameter to `true` a few additional images are published. These
        are `depth_viz` and `good_bad_pixels` (they are described
        above in the `Topics` section). These viz images are intended
        for human analysis and visualization in `rviz`.

        assume_sw_trigger
        bool

        If your application intends to use software triggering (as opposed to a
        free-running framegrabber), this parameter does four things. First, it
        will not print out framegrabber timeout messages to the
        rosconsole. Second, it will set, a-priori, the `timeout_millis`
        parameter to 500 milliseconds (this is so that the node will release
        the framegrabber mutex in the main publishing loop). Third, this will
        set the `timeout_tolerance_secs` to 600 seconds so that the
        framegrabber is not constantly getting recycled unnecessarily. Fourth,
        it sets the `GLOG_minloglevel` environment variable to 3 (ERROR). This
        is so the underlying `libo3d3xx` library does not fill your log files
        with timeout messages which it emits at the WARNING level.

        frame_id_base
        string
        tf frame prefix

### /o3d3xx/camera_tf

This node is of type `tf/static_transform_publisher`. It establishes a frame_id
for the camera in the global tf tree. This node is launched from the primary
`camera.launch` file:

    $ roslaunch o3d3xx camera.launch

When run as above, the tf publishing node would be named `/o3d3xx/camera_tf`
and the camera coordinate frame would be `o3d3xx/camera_link` in the tf tree.

You can customize this naming via the `frame_id_base` arg or implicitly through
the `ns` (namespace) and `nn` (node name) command line arguments passed to the
`camera.launch` file. For example, if you specify your roslaunch command as:

    $ roslaunch o3d3xx camera.launch ns:=robot nn:=front_camera

The node name will be `/robot/front_camera_tf` and the camera frame will
be `robot/front_camera_link` in the tf tree.

### /o3d3xx/camera/config_node

This node is used as a proxy to simplify calling the `/o3d3xx/camera/Config`
service offered by the `/o3d3xx/camera` node. It was noted above that there
appears to be a limitation in the YAML parser of the ROS `rosservice` command
line tool. Specifically, it seems that it is not capable of assigning a JSON
string to a variable. This is the reason for this node. This is not a
long-running node but rather works like a typical command-line tool would: you
invoke it, it runs, and exits. The following command line will launch this
node:

    $ roslaunch o3d3xx config.launch

#### Parameters

Name	Data Type	Description

        infile
        string

        By default, this node will read `stdin` for a JSON string to use to
        pass to the `/o3d3xx/camera/Config` service. However, if this parameter
        is specified it will read the JSON from this file.

### /rviz

This package offers a launch script that wraps the execution of `rviz` so that
the display will be conveniently configured for visualizing the
`/o3d3xx/camera` data. To launch this node:

    $ roslaunch o3d3xx rviz.launch

Running the command as above will color the point cloud with the
data from the normalized amplitude image (i.e., the intensity).

The rviz window should look something like (assuming you are coloring the point
cloud with the intensity data):

![rviz1](doc/figures/rviz1.png)

### /o3d3xx/camera/XXX_throttler

This package offers a launch script that wraps the
[topic_tools/throttler](http://wiki.ros.org/topic_tools/throttle) node
so that it can throttle the core topics from the camera. Specifically, it will
throttle `/o3d3xx/camera/cloud` to `/o3d3xx/camera/cloud_throttle`,
`/o3d3xx/camera/amplitude` to `/o3d3xx/camera/amplitude_throttle`,
`/o3d3xx/camera/raw_amplitude_throttle`,
`/o3d3xx/camera/depth` to `/o3d3xx/camera/depth_throttle`,
`/o3d3xx/camera/confidence` to `/o3d3xx/camera/confidence_throttle`. To launch
this node:

    $ roslaunch o3d3xx throttled.launch

By default, it will throttle the above named topics to 1 Hz. You can change the
frequency with the `hz` command line argument. For example, to send data at 2
Hz:

    $ roslaunch o3d3xx throttled.launch hz:=2.0

Using this launch file to launch this set of nodes is strictly optional. We
have found use for it in two ways. First, to slow down the publishing frequency
of the topics when used in conjunction with the `/o3d3xx/camera/file_writer`
node for collecting data (i.e., in those instances when we really do not need
all the data but rather some subsampling of it). Second, if we are running the
camera on a drone (for example) that has a slower radio link down to a ground
control station running `rviz` where we want to see what the camera sees while
the drone is in flight. Clearly there are other uses for this, YMMV.

Configuring Camera Settings
---------------------------

Configuring the camera is accomplished by passing a JSON string to the
`/o3d3xx/camera/config_node` which will call the `/o3d3xx/camera/Config`
service to mutate the camera settings. Using a JSON string to configure the
camera has the following primary benefits:

0. Configuration is declarative. The camera configuration will reflect that
   which is described by the JSON file.
1. The JSON data is human-consumable and easily edited in a text editor. This
   makes it very convenient for headless embedded systems.
2. The JSON data is machine parsable, so configuring the camera on the fly via
   programmable logic is also possible.

There are also a few downfalls to using JSON. Most notably the lack of comments
and an enforceable schema. One could argue that the latter keeps things
flexible. None-the-less, JSON is the format used by `libo3d3xx` and, by
extension, this ROS package.

An exemplary JSON file is shown [here](json/ex_camera.json) (this is the result
of calling the `/o3d3xx/camera/Dump` service on a development system). When
passing a JSON string (like the previously linked to file) to the
`/o3d3xx/camera/Config` service (or to the `/o3d3xx/camera/config_node`) the
following rules are used to configure the camera:

0. The `Device` section is processed and saved on the camera.
1. The `Apps` section is processed. For each app:
  0. If the `Index` key is present, a current app at that `Index` is looked
     up. If present, it is edited to reflect the data in the JSON file. If an
     app at that `Index` is not present, a new app is created with the
     parameters from the JSON file. It is not guaranteed that the new app will
     have the specified `Index`.
  1. If the `Index` key is not present, a new app is created with the
     parameters as specified in the JSON file.
2. The active application is set by consulting the desired index of the
   `ActiveApplication` from the `Device` section of the JSON. If the specified
   `Index` does not exist, the active application is not set.
3. The `Net` section is processed. A reboot of the camera may be necessary
   after changing the camera's network parameters. Additionally, you will
   likely need to restart the `/o3d3xx/camera` node pointing it to the new IP
   address (if that is what you changed).

It should also be noted that any portion of the JSON tree can be specfied to
configure only that part of the camera. The only rule to follow is that all
keys should be fully qualified. For example, to simply set the active
application, you can use a JSON snippet like this:

    {
        "o3d3xx":
        {
            "Device":
            {
                "ActiveApplication": "2"
            }
        }
    }

The above snippet is provided as an example [here](json/ex_set_active.json). To
apply this to your camera, you can:

    $ roslaunch o3d3xx config.launch infile:=/path/to/ex_set_active.json

It was also noted above that the `/o3d3xx/camera/config_node` will read `stdin`
by default, so you could also:

    $ echo '{"o3d3xx":{"Device":{"ActiveApplication":"2"}}}' | roslaunch o3d3xx config.launch

[Here](json/ex_add_app.json) is another example JSON file. This one will add a
new application to the camera, using the default values for the high-dynamic
range imager. We note that this application is _added_ to the camera because no
`Index` is specified for the application. If an `Index` were specfied, the
application at the specified `Index`, if present, would be edited to reflect
this configuration.

In general, a simple way to configure camera settings without having to
memorize the JSON syntax would be to simply dump the current camera settings to
a file:

    $ rosservice call /o3d3xx/camera/Dump > /tmp/camera.json

Then, open `/tmp/camera.json` with a text editor to create a declarative JSON
configuration for your camera. You should be sure to delete the variable names
from the `rosservice` output if you are following this example
_word-for-word_. Additionally, you can delete any unnecessary keys if you would
like, however it is not strictly necessary as the `/o3d3xx/camera/Config`
service will leave unedited values unchanged on the camera. Once you have a
configuration that you like, you can:

    $ roslaunch o3d3xx config.launch infile:=/tmp/camera.json

You can check that your configuration is active by calling the
`/o3d3xx/camera/Dump` service again.

TODO
----

Please see the [Github Issues](https://github.com/lovepark/o3d3xx-ros/issues).

LICENSE
-------

Please see the file called LICENSE.

AUTHORS
-------

Tom Panzarella <tom@loveparkrobotics.com>


text:
package com.sany.sap.connection;

/**
 * <p> SAPConf.java</p>
 * <p> Description: </p>
 * <p> bboss workgroup </p>
 * <p> Copyright (c) 2009 </p>
 *
 * @Date 2012-9-24 下午5:53:26
 * @author biaoping.yin
 * @version 1.0
 */
public class SAPConf {

	/**
	 * 10.0.13.11

01

150

esb_rfc

ESB@1qaz
	 */
	private String client = "150";
	private String user = "esb_rfc";
	private String passward = "ESB@1qaz";
	private String host = "10.0.13.11";
	private String sysnr = "01";
	private String lang = "ZH";
	private int jco_pool_capacity;
	private int jco_peak_limit;

	public static final String rfcName_BAPI_ACC_DOCUMENT_POST = "BAPI_ACC_DOCUMENT_POST";
	public static final String rfcName_commit = "BAPI_TRANSACTION_COMMIT";
	public static final String rfcName_rollback = "BAPI_TRANSACTION_ROLLBACK";
	public String getClient() {
		return client;
	}
	public void setClient(String client) {
		this.client = client;
	}
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public String getPassward() {
		return passward;
	}
	public void setPassward(String passward) {
		this.passward = passward;
	}
	public String getHost() {
		return host;
	}
	public void setHost(String host) {
		this.host = host;
	}
	public String getSysnr() {
		return sysnr;
	}
	public void setSysnr(String sysnr) {
		this.sysnr = sysnr;
	}
	public String getLang() {
		return lang;
	}
	public void setLang(String lang) {
		this.lang = lang;
	}
	public int getJco_pool_capacity() {
		return jco_pool_capacity;
	}
	public void setJco_pool_capacity(int jco_pool_capacity) {
		this.jco_pool_capacity = jco_pool_capacity;
	}
	public int getJco_peak_limit() {
		return jco_peak_limit;
	}
	public void setJco_peak_limit(int jco_peak_limit) {
		this.jco_peak_limit = jco_peak_limit;
	}

}


text:
export default class TextHelpers {
    // Public
    static getTextStyle(fontSize = 12, fontFamily = 'Verdana', fill = 0xffffff) {
        return {
            fontSize: fontSize,
            fontFamily: fontFamily,
            fill: fill
        }
    }
}


text:
Here are some related projects you might be interested in from the [Assemble](http://assemble.io) core team.

<!-- toc -->

### [grunt-convert](https://github.com/assemble/grunt-convert) [![NPM version](https://badge.fury.io/js/grunt-convert.png)](http://badge.fury.io/js/grunt-convert)
> Grunt task to convert to or from JSON, YAML, XML, PLIST or CSV.

### [grunt-firebase](https://github.com/assemble/grunt-firebase) [![NPM version](https://badge.fury.io/js/grunt-firebase.png)](http://badge.fury.io/js/grunt-firebase)
> Grunt task for updating firebase data.

### [grunt-github-api](https://github.com/assemble/grunt-github-api) [![NPM version](https://badge.fury.io/js/grunt-github-api.png)](http://badge.fury.io/js/grunt-github-api)
> Grunt plugin used to query the Github API and save the returned JSON files locally.

### [grunt-matter](https://github.com/assemble/grunt-matter) [![NPM version](https://badge.fury.io/js/grunt-matter.png)](http://badge.fury.io/js/grunt-matter)
> Add, extend, sort, and strip YAML front matter. Also has options for populating randomized mock data.

### [grunt-repos](https://github.com/assemble/grunt-repos) [![NPM version](https://badge.fury.io/js/grunt-repos.png)](http://badge.fury.io/js/grunt-repos)
> Use Grunt to pull down a list of repos from GitHub.

### [grunt-toc](https://github.com/assemble/grunt-toc) [![NPM version](https://badge.fury.io/js/grunt-toc.png)](http://badge.fury.io/js/grunt-toc)
> Grunt plugin for generating a markdown Table of Contents (TOC).

Visit [assemble.io/plugins](http:/assemble.io/plugins/) for more information about [Assemble](http:/assemble.io/) plugins.


text:
<?php

declare(strict_types=1);

namespace Doctrine\ORM\Mapping;

use ArrayIterator;
use ReflectionClass;
use ReflectionException;
use ReflectionProperty;

/**
 * A <tt>ComponentMetadata</tt> instance holds object-relational property mapping.
 */
abstract class ComponentMetadata
{
    /** @var string */
    protected $className;

    /** @var ComponentMetadata|null */
    protected $parent;

    /**
     * The ReflectionClass instance of the component class.
     *
     * @var ReflectionClass|null
     */
    protected $reflectionClass;

    /** @var CacheMetadata|null */
    protected $cache;

    /** @var Property[] */
    protected $declaredProperties = [];

    public function __construct(string $className, ClassMetadataBuildingContext $metadataBuildingContext)
    {
        $reflectionService = $metadataBuildingContext->getReflectionService();

        $this->reflectionClass = $reflectionService->getClass($className);
        $this->className       = $this->reflectionClass ? $this->reflectionClass->getName() : $className;
    }

    public function getClassName() : string
    {
        return $this->className;
    }

    public function setParent(ComponentMetadata $parent) : void
    {
        $this->parent = $parent;
    }

    public function getParent() : ?ComponentMetadata
    {
        return $this->parent;
    }

    public function getReflectionClass() : ?ReflectionClass
    {
        return $this->reflectionClass;
    }

    public function setCache(?CacheMetadata $cache = null) : void
    {
        $this->cache = $cache;
    }

    public function getCache() : ?CacheMetadata
    {
        return $this->cache;
    }

    /**
     * @return iterable|Property[]
     */
    public function getDeclaredPropertiesIterator() : iterable
    {
        foreach ($this->declaredProperties as $name => $property) {
            yield $name => $property;
        }
    }

    /**
     * @throws ReflectionException
     * @throws MappingException
     */
    public function addDeclaredProperty(Property $property) : void
    {
        $className    = $this->getClassName();
        $propertyName = $property->getName();

        // @todo guilhermeblanco Switch to hasProperty once inherited properties are not being mapped on child classes
        if ($this->hasDeclaredProperty($propertyName)) {
            throw MappingException::duplicateProperty($className, $this->getProperty($propertyName));
        }

        $property->setDeclaringClass($this);

        if ($this->reflectionClass) {
            $reflectionProperty = new ReflectionProperty($className, $propertyName);

            $reflectionProperty->setAccessible(true);

            $property->setReflectionProperty($reflectionProperty);
        }

        $this->declaredProperties[$propertyName] = $property;
    }

    public function hasDeclaredProperty(string $propertyName) : bool
    {
        return isset($this->declaredProperties[$propertyName]);
    }

    /**
     * @return iterable|Property[]
     */
    public function getPropertiesIterator() : iterable
    {
        if ($this->parent) {
            yield from $this->parent->getPropertiesIterator();
        }

        yield from $this->getDeclaredPropertiesIterator();
    }

    public function getProperty(string $propertyName) : ?Property
    {
        if (isset($this->declaredProperties[$propertyName])) {
            return $this->declaredProperties[$propertyName];
        }

        if ($this->parent) {
            return $this->parent->getProperty($propertyName);
        }

        return null;
    }

    public function hasProperty(string $propertyName) : bool
    {
        if (isset($this->declaredProperties[$propertyName])) {
            return true;
        }

        return $this->parent && $this->parent->hasProperty($propertyName);
    }

    /**
     * @return ArrayIterator|ColumnMetadata[]
     */
    public function getColumnsIterator() : ArrayIterator
    {
        $iterator = new ArrayIterator();

        // @todo guilhermeblanco Must be switched to getPropertiesIterator once class only has its declared properties
        foreach ($this->getDeclaredPropertiesIterator() as $property) {
            switch (true) {
                case $property instanceof FieldMetadata:
                    $iterator->offsetSet($property->getColumnName(), $property);
                    break;

                case $property instanceof ToOneAssociationMetadata && $property->isOwningSide():
                    foreach ($property->getJoinColumns() as $joinColumn) {
                        /** @var JoinColumnMetadata $joinColumn */
                        $iterator->offsetSet($joinColumn->getColumnName(), $joinColumn);
                    }

                    break;
            }
        }

        return $iterator;
    }
}


text:
import logging
from datetime import datetime

from dateutil.relativedelta import relativedelta
from google.appengine.ext import deferred, ndb
from typing import Iterable

from rogerthat.bizz.news.influx import get_influxdb_client, get_age_field_key
from rogerthat.consts import NEWS_STATS_QUEUE
from rogerthat.models.news import NewsItemStatisticsExporter, NewsItemActionStatistics
from rogerthat.utils.cloud_tasks import create_task, schedule_tasks

@ndb.transactional()
def run():
    key = NewsItemStatisticsExporter.create_key('influx')
    settings = key.get()
    if not settings:
        logging.info('NewsItemStatisticsExporter not set for type "influx"')
        return

    start = settings.exported_until
    end_ = datetime.utcnow()
    minute = end_.minute
    # Always round down minute to nearest 5 minutes
    while minute % 5 != 0:
        minute -= 1

    end = datetime(year=end_.year, month=end_.month, day=end_.day, hour=end_.hour, minute=minute)
    settings.exported_until = end
    settings.put()
    deferred.defer(_run_scheduler, start, end, _transactional=True, _queue=NEWS_STATS_QUEUE)

def _run_scheduler(start, end):
    tasks = []
    while True:
        end_tmp = start + relativedelta(minutes=5)
        if end_tmp < end:
            tasks.append(create_task(_run, start, end_tmp, _countdown=5))
            start = end_tmp
        else:
            tasks.append(create_task(_run, start, end, _countdown=5))
            break

    schedule_tasks(tasks, NEWS_STATS_QUEUE)

def _get_gender_field_key(gender):
    if gender == 'unknown':
        return 'gender-unknown'
    return gender

def _create_item_stats_key(s):
    # type: (NewsItemActionStatistics) -> str
    return '%s_%d_%s' % (s.get_app_id(), s.news_id, s.action)

def _create_global_stats_key(s):
    # type: (NewsItemActionStatistics) -> str
    return '%s_%s' % (s.get_app_id(), s.action)

def fill_fields_for_stats(all_stats, stats_key, statistic):
    # type: (dict, str, NewsItemActionStatistics) -> None
    if stats_key not in all_stats:
        all_stats[stats_key] = {
            'app_id': statistic.get_app_id(),
            'news_id': statistic.news_id,
            'action': statistic.action,
            'fields': {
                'total': 0,
            }
        }
    fields = all_stats[stats_key]['fields']

    if statistic.age:
        age_key = get_age_field_key(statistic.age)
        if age_key not in fields:
            fields[age_key] = 1
        else:
            fields[age_key] += 1
    if statistic.gender:
        gender_key = _get_gender_field_key(statistic.gender)
        if gender_key not in fields:
            fields[gender_key] = 1
        else:
            fields[gender_key] += 1
    fields['total'] += 1

def _run(start, end, params=None):
    time_diff = (end - start)
    if time_diff.total_seconds() != 300.0:
        raise Exception('Start & end where more or less then 5 minutes apart')

    item_stats = {}
    global_stats = {}

    qry = NewsItemActionStatistics.list_between(start, end)  # type: Iterable[NewsItemActionStatistics]
    for statistic in qry:
        fill_fields_for_stats(item_stats, _create_item_stats_key(statistic), statistic)
        fill_fields_for_stats(global_stats, _create_global_stats_key(statistic), statistic)

    time_str = end.isoformat() + 'Z'
    entries = [{
        'measurement': 'item.%s' % statistic['news_id'],
        'time': time_str,
        'tags': {
            'app': statistic['app_id'],
            'action': statistic['action']
        },
        'fields': statistic['fields'],
    } for statistic in item_stats.itervalues()]
    for statistic in global_stats.itervalues():
        entries.append({
            'measurement': 'global',
            'time': time_str,
            'tags': {
                'app': statistic['app_id'],
                'action': statistic['action']
            },
            'fields': statistic['fields'],
        })

    if entries:
        logging.info('Writing %d entries to influxdb', len(entries))
        client = get_influxdb_client(params=params)
        success = client.write_points(entries, 'u')
        if not success:
            raise Exception('Failed to save to influx db')


text:
/*	$NetBSD: eisadevs.h,v 1.17 1998/07/01 21:59:20 kleink Exp $	*/

/*
 * THIS FILE AUTOMATICALLY GENERATED.  DO NOT EDIT.
 *
 * generated from:
 *	NetBSD: eisadevs,v 1.15 1998/07/01 21:57:32 kleink Exp
 */

/*
 * Copyright (c) 1995, 1996 Christopher G. Demetriou
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *      This product includes software developed by Christopher G. Demetriou
 *	for the NetBSD Project.
 * 4. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * List of known products, grouped by vendor.
 */

/* Adaptec products */
#define	EISA_PRODUCT_ADP0000	"Adaptec AHA-1740 SCSI"
#define	EISA_PRODUCT_ADP0001	"Adaptec AHA-1740A SCSI"
#define	EISA_PRODUCT_ADP0002	"Adaptec AHA-1742A SCSI"
#define	EISA_PRODUCT_ADP0400	"Adaptec AHA-1744 SCSI"
#define	EISA_PRODUCT_ADP7770	"Adaptec AIC-7770 SCSI (on motherboard)"
#define	EISA_PRODUCT_ADP7771	"Adaptec AHA-274x SCSI"
#define	EISA_PRODUCT_ADP7756	"Adaptec AHA-284x SCSI (BIOS enabled)"
#define	EISA_PRODUCT_ADP7757	"Adaptec AHA-284x SCSI (BIOS disabled)"

/* AMI products */
#define	EISA_PRODUCT_AMI4801	"AMI Series 48 SCSI"

/* BusLogic products */
#define	EISA_PRODUCT_BUS4201	"BusLogic Bt74xB SCSI"
#define	EISA_PRODUCT_BUS4202	"BusLogic Bt74xC SCSI"

/* Digital Equipment products */
#define	EISA_PRODUCT_DEC4250	"Digital Equipment DE425 Ethernet"
#define	EISA_PRODUCT_DEC3001	"Digital Equipment DEFEA FDDI Controller"
#define	EISA_PRODUCT_DEC3002	"Digital Equipment DEFEA FDDI Controller"
#define	EISA_PRODUCT_DEC3003	"Digital Equipment DEFEA FDDI Controller"
#define	EISA_PRODUCT_DEC3004	"Digital Equipment DEFEA FDDI Controller"

/* FORE Systems products */
#define	EISA_PRODUCT_FSI2001	"FORE Systems ESA-200 ATM"
#define	EISA_PRODUCT_FSI2002	"FORE Systems ESA-200A ATM"
#define	EISA_PRODUCT_FSI2003	"FORE Systems ESA-200E ATM"

/* Interphase products */
#define	EISA_PRODUCT_INP25D0	"Interphase Seahawk 4811 FDDI Controller"

/* Intel products */
#define	EISA_PRODUCT_INT1010	"Intel EtherExpress 32 Flash Ethernet"

/* ETI products */
#define	EISA_PRODUCT_ETI1001	"Microdyne NE3300 Ethernet Rev. C & D"

/* 3Com products */
#define	EISA_PRODUCT_TCM5091	"3Com 3C509 Ethernet"
#define	EISA_PRODUCT_TCM5092	"3Com 3C579-TP Ethernet"
#define	EISA_PRODUCT_TCM5093	"3Com 3C579 Ethernet"
#define	EISA_PRODUCT_TCM5920	"3Com 3C592 Etherlink III"
#define	EISA_PRODUCT_TCM5970	"3Com 3C597 Fast Etherlink TX"
#define	EISA_PRODUCT_TCM5971	"3Com 3C597 Fast Etherlink T4"
#define	EISA_PRODUCT_TCM5972	"3Com 3C597 Fast Etherlink MII"

/* Standard Microsystems (SMC) */
#define	EISA_PRODUCT_SMC8010	"Standard Microsystems Corp. Ethercard Elite32C Ultra"
#define	EISA_PRODUCT_SMC0110	"Standard Microsystems Corp. Elite32 Ethernet"

/* UltraStor products */
#define	EISA_PRODUCT_USC0240	"UltraStor 24f SCSI"


text:
using System.IO;
using FluentAssertions;
using Unicorn.Roles.Formatting;
using Unicorn.Roles.Model;
using Xunit;

namespace Unicorn.Roles.Tests.Formatting
{
	public class YamlRoleSerializationFormatterTests
	{
		[Fact]
		public void ShouldFormatSingleRole_AsExpected()
		{
			var sut = new YamlRoleSerializationFormatter();

			using (var ms = new MemoryStream())
			{
				sut.WriteSerializedRole(new SerializedRoleData("Test", new string[0], "Foo"), ms);

				ms.Seek(0, SeekOrigin.Begin);

				using (var reader = new StreamReader(ms))
				{
					var yml = reader.ReadToEnd();

					yml.Should().Be(@"---
Role: Test
");
				}
			}
		}

		[Fact]
		public void ShouldFormatRoleWithParents_AsExpected()
		{
			var sut = new YamlRoleSerializationFormatter();

			using (var ms = new MemoryStream())
			{
				sut.WriteSerializedRole(new SerializedRoleData("Test", new [] { "Foo", "Foo-Bar" }, "Foo"), ms);

				ms.Seek(0, SeekOrigin.Begin);

				using (var reader = new StreamReader(ms))
				{
					var yml = reader.ReadToEnd();

					yml.Should().Be(@"---
Role: Test
MemberOf:
  Role: Foo
  Role: ""Foo-Bar""
");
				}
			}
		}
	}
}


text:
package com.colobu.kafka;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Collections;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消费者例子.
 *
 */
public class ConsumerExample {
	private final KafkaConsumer<String,String> consumer;
	private final String topic;
	private ExecutorService executor;
	private long delay;

	public ConsumerExample(Properties props, String topic) {
		consumer = new KafkaConsumer<>(props);
		this.topic = topic;
	}

	public void shutdown() {
		if (consumer != null)
			consumer.close();
		if (executor != null)
			executor.shutdown();
	}

	public void run() {
		consumer.subscribe(Collections.singletonList(this.topic));

		Executors.newSingleThreadExecutor().execute(() -> {
			while(true) {
				try {
					ConsumerRecords<String, String> records = consumer.poll(1000);
					for (ConsumerRecord<String, String> record : records) {
						System.out.println("Received message: (" + record.key() + ", " + record.value() + ") at offset " + record.offset());
					}
				}catch(Exception ex) {
					ex.printStackTrace();
				}
			}
		});

	}

	/**
	 * consumer 配置.
	 *
	 * @param brokers brokers
	 * @param groupId 组名
	 * @return
	 */
	private static Properties createConsumerConfig(String brokers, String groupId) {
		Properties props = new Properties();
		props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
		props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
		props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "true");
		props.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
		props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "30000");
		props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
		props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");

		//props.put("auto.commit.enable", "false");

		return props;
	}

	public static void main(String[] args) throws InterruptedException {
		String brokers = args[0];
		String groupId = args[1];
		String topic = args[2];
		Properties props = createConsumerConfig(brokers, groupId);
		ConsumerExample example = new ConsumerExample(props, topic);
		example.run();

		Thread.sleep(24*60*60*1000);

		example.shutdown();
	}
}


text:
package net.sf.jacclog.service.importer.internal.queue;

import java.util.ArrayDeque;
import java.util.Collection;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import net.sf.jacclog.api.domain.ReadonlyLogEntry;
import net.sf.jacclog.service.importer.api.service.LogEntryImportService;
import net.sf.jacclog.util.observer.BlockingQueueObserver;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogEntryQueuePersisterObserver implements BlockingQueueObserver<ReadonlyLogEntry> {

	public static class LogEntryPersisterTask implements Runnable {

		private static final int MAX_ATTEMPTS = 3;

		private final BlockingQueue<ReadonlyLogEntry> queue;

		private final LogEntryImportService<ReadonlyLogEntry> service;

		public LogEntryPersisterTask(final LogEntryImportService<ReadonlyLogEntry> service,
				final BlockingQueue<ReadonlyLogEntry> queue) {
			if (queue == null) {
				throw new IllegalArgumentException("Argument 'queue' can not be null.");
			}

			if (service == null) {
				throw new IllegalArgumentException("Argument 'service' can not be null.");
			}

			this.queue = queue;
			this.service = service;
		}

		private boolean persist(final Collection<ReadonlyLogEntry> entries) {
			boolean result = false;
			try {
				service.create(entries);
				result = true;
			} catch (final Exception e) {
				// no problem with an exception here, we try it multiple times
				LOG.info("Persisting failed: " + e.getLocalizedMessage());
			}
			return result;
		}

		private boolean persistWithMultipleAttempts(final Collection<ReadonlyLogEntry> entries) {
			boolean isPersisted = false;
			if (!entries.isEmpty()) {
				for (int i = 0; i < MAX_ATTEMPTS; i++) {
					isPersisted = persist(entries);
					if (isPersisted) {
						break;
					}
				}
			}
			return isPersisted;
		}

		@Override
		public void run() {
			if (!queue.isEmpty()) {

				// pause for a while so that more entries can be persist
				try {
					Thread.sleep(100l);
				} catch (final InterruptedException e1) {
					LOG.warn(e1.getLocalizedMessage(), e1);
				}

				// take all available entries from the queue
				final Collection<ReadonlyLogEntry> entries = new ArrayDeque<ReadonlyLogEntry>();
				ReadonlyLogEntry entry = null;
				int count = 0;
				do {
					entry = queue.poll();
					if (entry != null) {
						entries.add(entry);
						count++;
					}
				} while (entry != null && count < BATCH_SIZE);

				if (!entries.isEmpty()) {
					if (!persistWithMultipleAttempts(entries)) {
						LOG.warn(entries.size() + " entries were not stored in the repository.");
					}
				}
			}
		}

	}

	public static class UncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {

		private static final Logger LOG = LoggerFactory.getLogger(UncaughtExceptionHandler.class);

		@Override
		public void uncaughtException(final Thread thread, final Throwable throwable) {
			LOG.warn("An unexpected error has occurred in Thread '" + thread.getName() + "'.", throwable);
		}

	}

	private static final Logger LOG = LoggerFactory.getLogger(LogEntryQueuePersisterObserver.class);

	private final ExecutorService executor;

	private final LogEntryImportService<ReadonlyLogEntry> service;

	private final AtomicInteger counter = new AtomicInteger();

	private static final int BATCH_SIZE = 1000;

	public LogEntryQueuePersisterObserver(final LogEntryImportService<ReadonlyLogEntry> service) {
		if (service == null) {
			throw new IllegalArgumentException("Argument 'service' can not be null.");
		}

		this.service = service;

		final BasicThreadFactory factory = new BasicThreadFactory.Builder()
				// attributes
				.namingPattern("persister-%d").daemon(true).priority(Thread.MAX_PRIORITY)
				.uncaughtExceptionHandler(new UncaughtExceptionHandler()).build();
		executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), factory);
	}

	@Override
	public void added(final BlockingQueue<ReadonlyLogEntry> queue, final ReadonlyLogEntry element) {
		LOG.debug("Added entry '" + element.hashCode() + "' to queue.");

		if (counter.decrementAndGet() <= 0) {
			counter.set(BATCH_SIZE);
			executor.execute(new LogEntryPersisterTask(service, queue));
		}
	}

	@Override
	public void empty(final BlockingQueue<ReadonlyLogEntry> queue) {
		LOG.debug("Log entry queue is empty. (size: " + queue.size() + ")");

		// cleaning task
		executor.execute(new LogEntryPersisterTask(service, queue));
	}

	@Override
	public void removed(final BlockingQueue<ReadonlyLogEntry> queue, final ReadonlyLogEntry entry) {
		LOG.debug("Removed entry '" + entry.hashCode() + "' from queue.");
	}

}


text:
package org.ovirt.engine.api.restapi.resource;

import org.ovirt.engine.api.model.VnicProfile;
import org.ovirt.engine.api.resource.AssignedPermissionsResource;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.queries.GetPermissionsForObjectParameters;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;

public abstract class AbstractBackendVnicProfileResource
        extends AbstractBackendSubResource<VnicProfile, org.ovirt.engine.core.common.businessentities.network.VnicProfile> {

    protected AbstractBackendVnicProfileResource(String id) {
        super(id, VnicProfile.class,
                org.ovirt.engine.core.common.businessentities.network.VnicProfile.class,
                AbstractBackendVnicProfilesResource.SUB_COLLECTIONS);
    }

    protected VnicProfile get() {
        return performGet(VdcQueryType.GetVnicProfileById, new IdQueryParameters(guid));
    }

    protected AssignedPermissionsResource getPermissionsResource() {
        return inject(new BackendAssignedPermissionsResource(guid,
                VdcQueryType.GetPermissionsForObject,
                new GetPermissionsForObjectParameters(guid),
                VnicProfile.class,
                VdcObjectType.VnicProfile));
    }

    @Override
    protected VnicProfile doPopulate(VnicProfile model,
            org.ovirt.engine.core.common.businessentities.network.VnicProfile entity) {
        return model;
    }
}


text:
go-ristretto
============

Many cryptographic schemes need a group of prime order.  Popular and
efficient elliptic curves like (Edwards25519 of `ed25519` fame) are
rarely of prime order.  There is, however, a convenient method
to construct a prime order group from such curves,
called [Ristretto](https://ristretto.group) proposed by
[Mike Hamburg](https://www.shiftleft.org).

This is a pure Go implementation of the group operations on the
Ristretto prime-order group built from Edwards25519.
Documentation is on [godoc](https://godoc.org/github.com/bwesterb/go-ristretto).

Example: El'Gamal encryption
----------------------------

```go
// Generate an El'Gamal keypair
var secretKey ristretto.Scalar
var publicKey ristretto.Point

secretKey.Rand() // generate a new secret key
publicKey.ScalarMultBase(&secretKey) // compute public key

// El'Gamal encrypt a random curve point p into a ciphertext-pair (c1,c2)
var p ristretto.Point
var r ristretto.Scalar
var c1 ristretto.Point
var c2 ristretto.Point
p.Rand()
r.Rand()
c2.ScalarMultBase(&r)
c1.PublicScalarMult(&publicKey, &r)
c1.Add(&c1, &p)

// Decrypt (c1,c2) back to p
var blinding, p2 ristretto.Point
blinding.ScalarMult(&c2, &secretKey)
p2.Sub(&c1, &blinding)

fmt.Printf("%v", bytes.Equal(p.Bytes(), p2.Bytes()))
// Output:
// true
```

Compatibility with `ristretto255` RFC draft
-------------------------------------------

An [RFC has been proposed](https://datatracker.ietf.org/doc/draft-hdevalence-cfrg-ristretto/)
to standardise Ristretto over Ed25519.  This RFC is compatible with `go-ristretto`.  There
is one caveat: one should use `Point.DeriveDalek` instead of `Point.Derive` to derive a point
from a string.

References
----------

The curve and Ristretto implementation is based on the unpublished
[PandA](https://link.springer.com/chapter/10.1007/978-3-319-04873-4_14)
library by
[Chuengsatiansup](https://perso.ens-lyon.fr/chitchanok.chuengsatiansup/),
[Ribarski](http://panceribarski.com) and
[Schwabe](https://cryptojedi.org/peter/index.shtml),
see [cref/cref.c](cref/cref.c).  The old generic radix 25.5 field operations borrow
from [Adam Langley](https://www.imperialviolet.org)'s
[ed25519](http://github.com/agl/ed25519).
The amd64 optimized field arithmetic are from George Tankersley's
[ed25519 patch](https://go-review.googlesource.com/c/crypto/+/71950),
which in turn is based on SUPERCOP's
[`amd64-51-30k`](https://github.com/floodyberry/supercop/tree/master/crypto_sign/ed25519/amd64-51-30k)
by Bernstein, Duif, Lange, Schwabe and Yang.
The new generic radix 51 field operations are also based on `amd64-51-30k`.
The variable-time scalar multiplication code is based on that
of [curve25519-dalek](https://github.com/dalek-cryptography/curve25519-dalek).
The Lizard encoding was proposed by [Bram Westerbaan](https://bram.westerbaan.name/).
The quick RistrettoElligator inversion for it is joint work
with [Bram Westerbaan](https://bram.westerbaan.name/)
and [Mike Hamburg](https://www.shiftleft.org).

### other platforms
* [Rust](https://github.com/dalek-cryptography/curve25519-dalek)
* [Javascript](https://github.com/jedisct1/wasm-crypto)
* [C (part of `libsodium`)](https://libsodium.gitbook.io/doc/advanced/point-arithmetic/ristretto)

Changes
-------

### 1.2.1 (08-11-2021)
- Add Scalar.SetUint64().

### 1.2.0 (17-02-2021)

- Add Point.Double().  See issue #21.
- To align more closely with the RFC, Point.SetBytes()
  and Point.UnmarshalBinary() will now reject points with non-canonical
  encodings.  See #20.

### 1.1.1 (24-09-2019)

- Only use bits.Add64 from Go 1.13 onwards to make sure we're constant-time
  on non-amd64 platforms.  Thanks @Yawning; see issue #17.

### 1.1.0 (13-05-2019)

- Add support for the Lizard 16-bytes-to-point-injection.
  See  `ristretto.Point.`{`SetLizard()`, `Lizard()`,`LizardInto()`}.
- Add `Scalar.DeriveShort()` to derive a half-length scalar.
  (Warning: half-length scalars are unsafe in almost every application.)

- (internal) Add `ExtendedPoint.RistrettoElligator2Inverse()` to compute
  all preimages of a given point up-to Ristretto equivalence
  of `CompletedPoint.SetRistrettoElligator2()`.


text:
/*
 * Test that a basic collector works. Here we will do a basic reduction, keeping
 * the last value received
 *
 */
#include <unistd.h>
#include "../tests.h"
#include "area51/hashmap.h"
#include <area51/cache.h>

static void sleep_quarter_second() {
    struct timespec ts;
    ts.tv_nsec = 250000000;
    ts.tv_sec = 0;
    nanosleep(&ts, NULL);
}

static void put(Test *t, Cache *cache, int s, int e) {
    logconsole("Insert %d..%d", s, e - 1);
    for (int i = s; i < e; i++) {
        // The key
        void *key = malloc(32);
        assertNonNull(t, key);
        snprintf(key, 9, "k%d", i);

        // Value
        char *val = malloc(32);
        assertNonNull(t, val);
        snprintf(val, 9, "v%d", i);

        cachePut(cache, key, val, free);

        sleep_quarter_second();
    }
}

void test_cache_single(Test *t) {

    startTest(t);

    // Max size 10
    int maxSize = 10;

    // Max age 5s
    time_t maxAge = 5;

    // Create the cache. We want to expire when full the least used entries
    Cache *cache = cacheCreate(maxSize,
            maxAge,
            hashmapStringHash, hashmapStringEquals, free,
            CACHE_EXPIRE_LEAST_USED,
            // No lookup
            NULL, NULL, NULL
            );

    assertNonNull(t, cache);

    // Fill the cache
    put(t, cache, 0, maxSize);

    // Should be maxSize
    assertTrue(t, cacheSize(cache) == maxSize);

    // Add one more, should remove oldest so still maxSize
    put(t, cache, maxSize, maxSize + 1);

    // Should still be maxSize
    assertTrue(t, cacheSize(cache) == maxSize);

    // Should remove some entries
    sleep_quarter_second(maxAge - 1);

    // Should have some expired now, give some allowance on the result
    assertTrue(t, cacheSize(cache) >= 5 || cacheSize(cache) <= 7);

    // Add another lot. The first one should also replace an existing entry
    put(t, cache, maxSize, maxSize * 2);

    // Should now be full, i.e. maxSize
    assertTrue(t, cacheSize(cache) == maxSize);

    cacheFree(cache);

    pass(t);
}


text:
package com.javarush.task.task32.task3208;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Animal extends Remote {
    void say() throws RemoteException;

    void printName() throws RemoteException;
}


text:
<?xml version="1.0" encoding="WINDOWS-1252"?>
<safe_pregnancy xmlns="http://www.commcare.org/MVP/safe_motherhood/close_v0.1">
<Meta>
<formName>safe_pregnancy_close_0.0.1</formName>
<formVersion>GORKZSCKN</formVersion>
<DeviceID>FNCBMNHFXWQPDURDC</DeviceID>
<TimeStart>2009-09-07T01:00:00.000</TimeStart>
<TimeEnd>2009-06-12T01:00:00.000</TimeEnd>
<username>gayo</username>
<userid>gayo</userid>
</Meta>
<what_happened>ZURNPPOPB</what_happened>
<other_what_happened>OBNLEHYMBAKVU</other_what_happened>
<mother_survived>YEWYT</mother_survived>
<infants_delivered>4</infants_delivered>
<infants_survived>2</infants_survived>
<birth_location>DYOMDJOCTTVQH</birth_location>
<other_location>MQIBGERUWQUAAYKCZECJRCZIFV</other_location>
<birth_attendant>VODXLFHDVVJOLTUGHGBXGL</birth_attendant>
<other_attendant>FKMK</other_attendant>
<termination_location>SSMINTPOJCOTSRXZL</termination_location>
<other_termination_location>UZU</other_termination_location>
<termination_attendant>ZTUJCIVNJVAJMVDNKDYFDBHLBRRBE</termination_attendant>
<other_termination_attendant>RGTMOGICPULOLJYXWPH</other_termination_attendant>
<death_case_mother>ATNEPXXRVTANTLGAPUTLULKWY</death_case_mother>
<death_case_infant>U</death_case_infant>
<newborn_case>FIEPPJE</newborn_case>
</safe_pregnancy>


text:
package com.crashinvaders.common.scene2d;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.scenes.scene2d.utils.Layout;

/**
 * Container that can scale its child while works correct in layout.
 * This group overrides scale related methods and use internal scale values that are used to compute child's size (to layouts and other native Scene2D mechanics scale of this actor always will be 1.0f).
 * The child will receive different size values depending on the scale value and should layout properly.
 */
public class ScalarScalableWrapper<T extends Actor> extends WidgetGroup {

    private T actor;
    private float origWidth = 0f;
    private float origHeight = 0f;
    private float scaleX = 1f;
    private float scaleY = 1f;

    public ScalarScalableWrapper() {
        super.setTransform(false);
    }

    public ScalarScalableWrapper(T actor) {
        this();
        setActor(actor);
    }

    @Override
    public void layout() {
        super.layout();

        if (actor != null) {
            actor.setPosition(0f, 0f);
            actor.setSize(getWidth(), getHeight());
        }
    }

    @Override
    public float getPrefWidth() {
        if (actor == null) return 0f;

        if (actor instanceof Layout) {
            Layout layout = (Layout) actor;
            return layout.getPrefWidth() * scaleX;
        } else {
            return origWidth * scaleX;
        }
    }

    @Override
    public float getPrefHeight() {
        if (actor == null) return 0f;

        if (actor instanceof Layout) {
            Layout layout = (Layout) actor;
            return layout.getPrefHeight() * scaleY;
        } else {
            return origHeight * scaleY;
        }
    }

    public void setActor(T actor) {
        if (this.actor == actor) return;

        if (this.actor != null) {
            super.removeActor(this.actor, true);
        }

        if (actor != null) {
            this.actor = actor;
            origWidth = actor.getWidth();
            origHeight = actor.getHeight();
            super.addActor(actor);
        }
    }

    public T getActor() {
        return actor;
    }

    @Override
    public float getScaleX() {
        return scaleX;
    }

    @Override
    public float getScaleY() {
        return scaleY;
    }

    @Override
    public void setScaleX(float scaleX) {
        this.scaleX = scaleX;
        invalidateHierarchy();
    }

    @Override
    public void setScaleY(float scaleY) {
        this.scaleY = scaleY;
        invalidateHierarchy();
    }

    @Override
    public void setScale(float scaleXY) {
        this.setScale(scaleXY, scaleXY);
    }

    @Override
    public void setScale(float scaleX, float scaleY) {
        this.scaleX = scaleX;
        this.scaleY = scaleY;
        invalidateHierarchy();
    }

    @Override
    public void scaleBy(float scale) {
        this.scaleBy(scale, scaleY);
    }

    @Override
    public void scaleBy(float scaleX, float scaleY) {
        this.scaleX += scaleX;
        this.scaleY += scaleY;
        invalidateHierarchy();
    }

    @Deprecated
    @Override
    public void setTransform(boolean transform) {
        throw new UnsupportedOperationException();
    }

    //region Omitted child related methods
    @Deprecated
    @Override
    public void addActor(Actor actor) {
        throw new UnsupportedOperationException();
    }

    @Deprecated
    @Override
    public void addActorAt(int index, Actor actor) {
        throw new UnsupportedOperationException();
    }

    @Deprecated
    @Override
    public void addActorBefore(Actor actorBefore, Actor actor) {
        throw new UnsupportedOperationException();
    }

    @Deprecated
    @Override
    public void addActorAfter(Actor actorAfter, Actor actor) {
        throw new UnsupportedOperationException();
    }

    @Deprecated
    @Override
    public boolean removeActor(Actor actor) {
        throw new UnsupportedOperationException();
    }

    @Deprecated
    @Override
    public boolean removeActor(Actor actor, boolean unfocus) {
        throw new UnsupportedOperationException();
    }
    //endregion
}