text:
(function(global) {

    var ApiDoc = global.ApiDoc = new Backbone.Marionette.Application();

    ApiDoc.addRegions({
        sidebar: '.sidebar',
        tabs: '.tabs',
        tabsContainer: '.tabs-container',
        modalSettings: '.modal-settings'
    });

    ApiDoc.cookies = {
        get: function(cookieName, defaultValue) {
            var cookieData = $.cookie(cookieName), data;
            if(!cookieData) {
                this.set(cookieName, defaultValue);
                data = defaultValue;
            } else {
                data = JSON.parse(cookieData);
            }

            return data;
        },

        set: function(cookieName, value) {
            $.cookie(cookieName, JSON.stringify(value));

            return this;
        }
    };

    ApiDoc.on('before:start', function(options) {
        var sections = [], section, resources, resource, methods = [], method;

        if(!_.isUndefined(options)) {

            if(_.isObject(options.sections)) {

                _.each(options.sections, function(resourceList, sectionName) {
                    resources = [];
                    _.each(resourceList, function(methodsList, resourceName) {

                        resource = {
                            type: 'resource',
                            id: _.uniqueId('resource_'),
                            name: resourceName,
                            children: []
                        };

                        _.each(methodsList, function(methodData) {
                            methodData['sandbox'] = {};
                            method = new ApiDoc.entities.Method(methodData);
                            resource.children.push(method);
                            methods.push(method);
                        });

                        if(sectionName == '_others') {
                            sections.push(resource);
                        } else {
                            resources.push(resource);
                        }
                    });

                    section = {
                        type: 'section',
                        id: _.uniqueId('section_'),
                        name: sectionName,
                        children: resources
                    };

                    if(sectionName != '_others') {
                        sections.push(section);
                    }
                });
                delete options.sections;
            }
        }

        options.sections = sections;
        options.methods = methods;

        ApiDoc.options = options;
    });

    ApiDoc.addInitializer(function(options) {
        var auth, settings = {
            apiEndpoint: options.endpoint,
            requestFormatMethod: options.requestFormatMethod
        };

        if(options.acceptType) {
            settings.acceptType = options.acceptType;
        }

        if(options.authentication) {
            auth = options.authentication;
            if(auth.delivery == 'http_basic') {
                settings.authDelivery = auth.delivery;
            } else if(auth.delivery == 'query') {
                settings.authDelivery = auth.delivery;
                settings.apiKeyParameter = auth.name;
                var search = window.location.search;
                var apiKeyStart = search.indexOf(auth.name) + auth.name.length + 1;
                if(apiKeyStart > 0) {
                    var apiKeyEnd = search.indexOf('&', apiKeyStart);
                    settings.apiKey = -1 == apiKeyEnd ? search.substr(apiKeyStart) : search.substring(apiKeyStart, apiKeyEnd);
                }
            } else if(auth.delivery == 'header') {
                settings.authDelivery = auth.delivery;
                settings.apiKeyParameter = auth.name;
            }
        }

        ApiDoc.settings = new ApiDoc.entities.Settings(settings);

        var storedSettings = ApiDoc.cookies.get('settings', {});
        ApiDoc.settings.set(storedSettings);
    });

    ApiDoc.addInitializer(function(options) {
        ApiDoc.sections = new ApiDoc.entities.Sections(options.sections);
    });

    ApiDoc.addInitializer(function(options) {
        ApiDoc.methods = new ApiDoc.entities.Methods(options.methods);
    });

    ApiDoc.addInitializer(function() {
        var previousMethods = ApiDoc.cookies.get('active_methods', {});
        var activeMethods = [];
        _.each(previousMethods, function(data, id) {
            var model = ApiDoc.methods.get(id);
            if(model) {
                if(data.active) {
                    model.set('isActive', true);
                }
                if(data.sandbox) {
                    model.get('sandbox').set(data.sandbox);
                }
                activeMethods.push(model);
            }
        });

        ApiDoc.activeMethods = new ApiDoc.entities.ActiveMethods();
        ApiDoc.listenTo(ApiDoc.activeMethods, 'add', function(model) {
            var activeMethods = ApiDoc.cookies.get('active_methods', {});
            var activeMethod = {active: model.get('isActive'), sandbox: model.get('sandbox').toJSON()};
            delete activeMethod.sandbox.id;
            activeMethods[model.id] = activeMethod;
            ApiDoc.cookies.set('active_methods', activeMethods);
        });

        ApiDoc.listenTo(ApiDoc.activeMethods, 'remove', function(model) {
            var activeMethods = ApiDoc.cookies.get('active_methods', {});
            delete activeMethods[model.id];
            ApiDoc.cookies.set('active_methods', activeMethods);
        });

        ApiDoc.listenTo(ApiDoc.activeMethods, 'change:isActive update', function(model) {
            var activeMethods = ApiDoc.cookies.get('active_methods', {});
            var activeMethod = {active: model.get('isActive'), sandbox: model.get('sandbox').toJSON()};
            delete activeMethod.sandbox.id;
            activeMethods[model.id] = activeMethod;
            ApiDoc.cookies.set('active_methods', activeMethods);
        });

        ApiDoc.activeMethods.set(activeMethods);
    });
})(window);


text:
[![Greenkeeper badge](https://badges.greenkeeper.io/MetaMask/eth-sig-util.svg)](https://greenkeeper.io/)

A small collection of ethereum signing functions.

You can find usage examples [here](https://github.com/flyswatter/js-eth-personal-sign-examples)

[Available on NPM](https://www.npmjs.com/package/eth-sig-util)

## Supported Signing Methods

Currently there is only one supported signing protocol. More will be added as standardized.

- Personal Sign (`personal_sign`) [geth thread](https://github.com/ethereum/go-ethereum/pull/2940)

## Installation

```
npm install eth-sig-util --save
```

## Methods

### concatSig(v, r, s)

All three arguments should be provided as buffers.

Returns a continuous, hex-prefixed hex value for the signature, suitable for inclusion in a JSON transaction's data field.

### normalize(address)

Takes an address of either upper or lower case, with or without a hex prefix, and returns an all-lowercase, hex-prefixed address, suitable for submitting to an ethereum provider.

### personalSign (privateKeyBuffer, msgParams)

msgParams should have a `data` key that is hex-encoded data to sign.

Returns the prefixed signature expected for calls to `eth.personalSign`.

### recoverPersonalSignature (msgParams)

msgParams should have a `data` key that is hex-encoded data unsigned, and a `sig` key that is hex-encoded and already signed.

Returns a hex-encoded sender address.

### signTypedData (privateKeyBuffer, msgParams)

Signs typed data as per [EIP712](https://github.com/ethereum/EIPs/pull/712).

Data should be under `data` key of `msgParams`. The method returns prefixed signature.

### recoverTypedSignature ({data, sig})

Return address of a signer that did `signTypedData`.

Expects the same data that were used for signing. `sig` is a prefixed signature.

### typedSignatureHash (typedData)

Return hex-encoded hash of typed data params according to [EIP712](https://github.com/ethereum/EIPs/pull/712) schema.

### extractPublicKey (msgParams)

msgParams should have a `data` key that is hex-encoded data unsigned, and a `sig` key that is hex-encoded and already signed.

Returns a hex-encoded public key.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Froiden\RestAPI\Exceptions;

class RelatedResourceNotFoundException extends ApiException
{
    protected $statusCode = 422;

    protected $code = ErrorCodes::VALIDATION_EXCEPTION;

    protected $innercode = ErrorCodes::INNER_RELATED_RESOURCE_NOT_EXISTS;

    protected $message = "Related resource not found";
}


text:
package main

import (
	"context"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net"
	"strings"
	"sync"

	"github.com/sirupsen/logrus"
	"github.com/stampzilla/stampzilla-go/v2/nodes/stampzilla-spc/edp"
	"github.com/stampzilla/stampzilla-go/v2/pkg/node"
)

func main() {
	wg, node, _ := start()
	if node == nil {
		return
	}
	node.Wait()
	wg.Wait()
}

func start() (*sync.WaitGroup, *node.Node, chan string) {
	node := node.New("spc")
	connectToPort := make(chan string)
	node.OnConfig(updatedConfig(connectToPort))
	if err := node.Connect(); err != nil {
		logrus.Error(err)
		return nil, nil, nil
	}

	ctx, cancel := context.WithCancel(context.Background())
	data := make(chan []byte, 100)
	wg := &sync.WaitGroup{}
	syncWorker(ctx, wg, data, node)
	startListen(ctx, wg, connectToPort, data)

	node.OnShutdown(func() {
		cancel()
	})

	return wg, node, connectToPort
}

func syncWorker(ctx context.Context, wg *sync.WaitGroup, data chan []byte, node *node.Node) {
	wg.Add(1)
	go func() {
		defer wg.Done()
		for {
			select {
			case <-ctx.Done():
				return
			case d := <-data:
				err := decodeAndSync(d, node)
				if err != nil {
					logrus.Error(err)
				}
			}
		}
	}()
}

func decodeAndSync(buf []byte, node *node.Node) error {
	logrus.Debug("string", string(buf))
	if logrus.GetLevel() >= logrus.DebugLevel {
		fmt.Println(hex.Dump(buf)) // nolint
	}
	pkg, err := edp.Decode(buf)
	if err != nil {
		return fmt.Errorf("error decoding pkg: %w", err)
	}

	dev := node.GetDevice(pkg.ID)
	newDev, areaDev := edp.GenerateDevice(pkg)

	if dev == nil && newDev != nil {
		node.AddOrUpdate(newDev)
		return nil
	}

	if newDev == nil {
		logrus.Warnf("unsupported packet class %s data: %s", pkg.Class, string(buf[23:]))
		return nil
	}

	if areaDev != nil {
		node.UpdateState(areaDev.ID.ID, areaDev.State)
	}
	node.UpdateState(newDev.ID.ID, newDev.State)
	return nil
}

func startListen(ctx context.Context, wg *sync.WaitGroup, connectToPort chan string, data chan []byte) {
	listen := func(port string) net.PacketConn {
		logrus.Infof("started udp4 server on %s", port)
		l, err := net.ListenPacket("udp4", ":"+port)
		if err != nil {
			logrus.Error(err)
			return nil
		}
		if c, ok := l.(*net.UDPConn); ok {
			rb := 1024 * 1024
			logrus.Infof("setting ReadBuffer on udp conn to: %d", rb)
			err := c.SetReadBuffer(rb)
			if err != nil {
				logrus.Error(err)
			}
		}
		wg.Add(1)
		go func() {
			defer wg.Done()
			for {
				buf := make([]byte, 1440)
				n, _, err := l.ReadFrom(buf)
				if err != nil {
					if strings.Contains(err.Error(), "use of closed network connection") {
						return
					}
					logrus.Error(err)
					continue
				}
				data <- buf[0:n]
			}
		}()
		return l
	}

	wg.Add(1)
	go func() {
		defer wg.Done()
		var l net.PacketConn
		defer func() {
			if l != nil {
				l.Close()
			}
		}()
		for {
			select {
			case port := <-connectToPort:
				if l != nil {
					l.Close()
				}
				l = listen(port)
			case <-ctx.Done():
				return
			}
		}
	}()
}

var config = &Config{}

func updatedConfig(connectToPort chan string) node.OnFunc {
	return func(data json.RawMessage) error {
		logrus.Info("Received config from server:", string(data))

		newConf := &Config{}
		err := json.Unmarshal(data, newConf)
		if err != nil {
			return fmt.Errorf("error decoding json config: %w", err)
		}

		if newConf.EDPPort != config.EDPPort {
			logrus.Infof("got new EDPPort from config %s", newConf.EDPPort)
			connectToPort <- newConf.EDPPort
		}
		config = newConf
		return nil
	}
}

type Config struct {
	EDPPort string
}

/*
Config to put into gui:
{
	EDPPort: "1234"
}

*/


text:
define(["dijit","dojo","dojox"],function(_1,_2,_3){
_2.provide("dojox.drawing.manager.Stencil");
(function(){
var _4,_5;
_3.drawing.manager.Stencil=_3.drawing.util.oo.declare(function(_6){
_4=_6.surface;
this.canvas=_6.canvas;
this.defaults=_3.drawing.defaults.copy();
this.undo=_6.undo;
this.mouse=_6.mouse;
this.keys=_6.keys;
this.anchors=_6.anchors;
this.stencils={};
this.selectedStencils={};
this._mouseHandle=this.mouse.register(this);
_2.connect(this.keys,"onArrow",this,"onArrow");
_2.connect(this.keys,"onEsc",this,"deselect");
_2.connect(this.keys,"onDelete",this,"onDelete");
},{_dragBegun:false,_wasDragged:false,_secondClick:false,_isBusy:false,setRecentStencil:function(_7){
this.recent=_7;
},getRecentStencil:function(){
return this.recent;
},register:function(_8){
if(_8.isText&&!_8.editMode&&_8.deleteEmptyCreate&&!_8.getText()){
console.warn("EMPTY CREATE DELETE",_8);
_8.destroy();
return false;
}
this.stencils[_8.id]=_8;
this.setRecentStencil(_8);
if(_8.execText){
if(_8._text&&!_8.editMode){
this.selectItem(_8);
}
_8.connect("execText",this,function(){
if(_8.isText&&_8.deleteEmptyModify&&!_8.getText()){
console.warn("EMPTY MOD DELETE",_8);
this.deleteItem(_8);
}else{
if(_8.selectOnExec){
this.selectItem(_8);
}
}
});
}
_8.connect("deselect",this,function(){
if(!this._isBusy&&this.isSelected(_8)){
this.deselectItem(_8);
}
});
_8.connect("select",this,function(){
if(!this._isBusy&&!this.isSelected(_8)){
this.selectItem(_8);
}
});
return _8;
},unregister:function(_9){
if(_9){
_9.selected&&this.onDeselect(_9);
delete this.stencils[_9.id];
}
},onArrow:function(_a){
if(this.hasSelected()){
this.saveThrottledState();
this.group.applyTransform({dx:_a.x,dy:_a.y});
}
},_throttleVrl:null,_throttle:false,throttleTime:400,_lastmxx:-1,_lastmxy:-1,saveMoveState:function(){
var mx=this.group.getTransform();
if(mx.dx==this._lastmxx&&mx.dy==this._lastmxy){
return;
}
this._lastmxx=mx.dx;
this._lastmxy=mx.dy;
this.undo.add({before:_2.hitch(this.group,"setTransform",mx)});
},saveThrottledState:function(){
clearTimeout(this._throttleVrl);
clearInterval(this._throttleVrl);
this._throttleVrl=setTimeout(_2.hitch(this,function(){
this._throttle=false;
this.saveMoveState();
}),this.throttleTime);
if(this._throttle){
return;
}
this._throttle=true;
this.saveMoveState();
},unDelete:function(_b){
for(var s in _b){
_b[s].render();
this.onSelect(_b[s]);
}
},onDelete:function(_c){
if(_c!==true){
this.undo.add({before:_2.hitch(this,"unDelete",this.selectedStencils),after:_2.hitch(this,"onDelete",true)});
}
this.withSelected(function(m){
this.anchors.remove(m);
var id=m.id;
m.destroy();
delete this.stencils[id];
});
this.selectedStencils={};
},deleteItem:function(_d){
if(this.hasSelected()){
var _e=[];
for(var m in this.selectedStencils){
if(this.selectedStencils.id==_d.id){
if(this.hasSelected()==1){
this.onDelete();
return;
}
}else{
_e.push(this.selectedStencils.id);
}
}
this.deselect();
this.selectItem(_d);
this.onDelete();
_2.forEach(_e,function(id){
this.selectItem(id);
},this);
}else{
this.selectItem(_d);
this.onDelete();
}
},removeAll:function(){
this.selectAll();
this._isBusy=true;
this.onDelete();
this.stencils={};
this._isBusy=false;
},setSelectionGroup:function(){
this.withSelected(function(m){
this.onDeselect(m,true);
});
if(this.group){
_4.remove(this.group);
this.group.removeShape();
}
this.group=_4.createGroup();
this.group.setTransform({dx:0,dy:0});
this.withSelected(function(m){
this.group.add(m.container);
m.select();
});
},setConstraint:function(){
var t=Infinity,l=Infinity;
this.withSelected(function(m){
var o=m.getBounds();
t=Math.min(o.y1,t);
l=Math.min(o.x1,l);
});
this.constrain={l:-l,t:-t};
},onDeselect:function(_f,_10){
if(!_10){
delete this.selectedStencils[_f.id];
}
this.anchors.remove(_f);
_4.add(_f.container);
_f.selected&&_f.deselect();
_f.applyTransform(this.group.getTransform());
},deselectItem:function(_11){
this.onDeselect(_11);
},deselect:function(){
this.withSelected(function(m){
this.onDeselect(m);
});
this._dragBegun=false;
this._wasDragged=false;
},onSelect:function(_12){
if(!_12){
console.error("null stencil is not selected:",this.stencils);
}
if(this.selectedStencils[_12.id]){
return;
}
this.selectedStencils[_12.id]=_12;
this.group.add(_12.container);
_12.select();
if(this.hasSelected()==1){
this.anchors.add(_12,this.group);
}
},selectAll:function(){
this._isBusy=true;
for(var m in this.stencils){
this.selectItem(m);
}
this._isBusy=false;
},selectItem:function(_13){
var id=typeof (_13)=="string"?_13:_13.id;
var _14=this.stencils[id];
this.setSelectionGroup();
this.onSelect(_14);
this.group.moveToFront();
this.setConstraint();
},onLabelDoubleClick:function(obj){
if(this.selectedStencils[obj.id]){
this.deselect();
}
},onStencilDoubleClick:function(obj){
if(this.selectedStencils[obj.id]){
if(this.selectedStencils[obj.id].edit){
var m=this.selectedStencils[obj.id];
m.editMode=true;
this.deselect();
m.edit();
}
}
},onAnchorUp:function(){
this.setConstraint();
},onStencilDown:function(obj,evt){
if(!this.stencils[obj.id]){
return;
}
this.setRecentStencil(this.stencils[obj.id]);
this._isBusy=true;
if(this.selectedStencils[obj.id]&&this.keys.meta){
if(_2.isMac&&this.keys.cmmd){
}
this.onDeselect(this.selectedStencils[obj.id]);
if(this.hasSelected()==1){
this.withSelected(function(m){
this.anchors.add(m,this.group);
});
}
this.group.moveToFront();
this.setConstraint();
return;
}else{
if(this.selectedStencils[obj.id]){
var mx=this.group.getTransform();
this._offx=obj.x-mx.dx;
this._offy=obj.y-mx.dy;
return;
}else{
if(!this.keys.meta){
this.deselect();
}else{
}
}
}
this.selectItem(obj.id);
mx=this.group.getTransform();
this._offx=obj.x-mx.dx;
this._offy=obj.y-mx.dx;
this.orgx=obj.x;
this.orgy=obj.y;
this._isBusy=false;
this.undo.add({before:function(){
},after:function(){
}});
},onLabelDown:function(obj,evt){
this.onStencilDown(obj,evt);
},onStencilUp:function(obj){
},onLabelUp:function(obj){
this.onStencilUp(obj);
},onStencilDrag:function(obj){
if(!this._dragBegun){
this.onBeginDrag(obj);
this._dragBegun=true;
}else{
this.saveThrottledState();
var x=obj.x-obj.last.x,y=obj.y-obj.last.y,c=this.constrain,mz=this.defaults.anchors.marginZero;
x=obj.x-this._offx;
y=obj.y-this._offy;
if(x<c.l+mz){
x=c.l+mz;
}
if(y<c.t+mz){
y=c.t+mz;
}
this.group.setTransform({dx:x,dy:y});
}
},onLabelDrag:function(obj){
this.onStencilDrag(obj);
},onDragEnd:function(obj){
this._dragBegun=false;
},onBeginDrag:function(obj){
this._wasDragged=true;
},onDown:function(obj){
this.deselect();
},onStencilOver:function(obj){
_2.style(obj.id,"cursor","move");
},onStencilOut:function(obj){
_2.style(obj.id,"cursor","crosshair");
},exporter:function(){
var _15=[];
for(var m in this.stencils){
this.stencils[m].enabled&&_15.push(this.stencils[m].exporter());
}
return _15;
},listStencils:function(){
return this.stencils;
},toSelected:function(_16){
var _17=Array.prototype.slice.call(arguments).splice(1);
for(var m in this.selectedStencils){
var _18=this.selectedStencils[m];
_18[_16].apply(_18,_17);
}
},withSelected:function(_19){
var f=_2.hitch(this,_19);
for(var m in this.selectedStencils){
f(this.selectedStencils[m]);
}
},withUnselected:function(_1a){
var f=_2.hitch(this,_1a);
for(var m in this.stencils){
!this.stencils[m].selected&&f(this.stencils[m]);
}
},withStencils:function(_1b){
var f=_2.hitch(this,_1b);
for(var m in this.stencils){
f(this.stencils[m]);
}
},hasSelected:function(){
var ln=0;
for(var m in this.selectedStencils){
ln++;
}
return ln;
},isSelected:function(_1c){
return !!this.selectedStencils[_1c.id];
}});
})();
});


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

namespace Ploeh.Samples.DI.AntiPatterns.DirectControl.Factory.AbstractFactory
{
    public abstract class ProductRepositoryFactory
    {
        public abstract ProductRepository Create();
    }
}


text:
import os

from samples.snippets import process_document_specialized_sample

location = "us"
project_id = os.environ["GOOGLE_CLOUD_PROJECT"]
processor_id = "feacd98c28866ede"
file_path = "resources/us_driver_license.pdf"
mime_type = "application/pdf"

def test_process_documents(capsys):
    process_document_specialized_sample.process_document_specialized_sample(
        project_id=project_id,
        location=location,
        processor_id=processor_id,
        file_path=file_path,
        mime_type=mime_type,
    )
    out, _ = capsys.readouterr()

    expected_strings = [
        "Document Id",
        "97551579",
    ]
    for expected_string in expected_strings:
        assert expected_string in out


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@mipmap/icon_checked" android:state_checked="true" />
    <item android:drawable="@mipmap/icon_checked" android:state_selected="true"></item>
    <item android:drawable="@mipmap/icon_checked_no" android:state_checked="false" />

</selector>


text:
package org.drools.guvnor.client.rpc;

import com.google.gwt.user.client.rpc.IsSerializable;

/**
 * A single row of a paged data
 */
public abstract class AbstractPageRow
    implements
    IsSerializable,
    Comparable<AbstractPageRow> {

    public int compareTo(AbstractPageRow o) {
        return 0;
    }

}


text:
package org.fusesource.fabric.dosgi.api;

import org.fusesource.fabric.dosgi.tcp.InvocationStrategy;
import org.fusesource.fabric.dosgi.tcp.ResponseFuture;
import org.fusesource.fabric.dosgi.util.ClassLoaderObjectInputStream;
import org.fusesource.hawtbuf.DataByteArrayInputStream;
import org.fusesource.hawtbuf.DataByteArrayOutputStream;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.rmi.RemoteException;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 *

 *

 *
 * @author Hiram Chirino
 */
public class ObjectSerializationStrategy implements SerializationStrategy {
    public static final ObjectSerializationStrategy INSTANCE = new ObjectSerializationStrategy();

    public String name() {
        return "object";
    }

    public void encodeRequest(ClassLoader loader, Class<?>[] types, Object[] args, DataByteArrayOutputStream target) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(target);
        oos.writeObject(args);
        oos.flush();
    }

    public void decodeResponse(ClassLoader loader, Class<?> type, DataByteArrayInputStream source, AsyncCallback result) throws IOException, ClassNotFoundException {
        ClassLoaderObjectInputStream ois = new ClassLoaderObjectInputStream(source);
        ois.setClassLoader(loader);
        Throwable error = (Throwable) ois.readObject();
        Object value = ois.readObject();
        if (error != null) {
            result.onFailure(error);
        } else {
            result.onSuccess(value);
        }
    }

    public void decodeRequest(ClassLoader loader, Class<?>[] types, DataByteArrayInputStream source, Object[] target) throws IOException, ClassNotFoundException {
        final ClassLoaderObjectInputStream ois = new ClassLoaderObjectInputStream(source);
        ois.setClassLoader(loader);
        final Object[] args = (Object[]) ois.readObject();
        if( args!=null ) {
            System.arraycopy(args, 0, target, 0, args.length);
        }
    }

    public void encodeResponse(ClassLoader loader, Class<?> type, Object value, Throwable error, DataByteArrayOutputStream target) throws IOException, ClassNotFoundException {
        ObjectOutputStream oos = new ObjectOutputStream(target);
        oos.writeObject(error);
        oos.writeObject(value);
        oos.flush();
    }

}


text:
"""Operations for working with string Tensors."""

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

import numpy as np

from tensorflow.python.compat import compat
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_parsing_ops
from tensorflow.python.ops import gen_string_ops
from tensorflow.python.ops import math_ops

# go/tf-wildcard-import
# pylint: disable=wildcard-import
# pylint: disable=g-bad-import-order
from tensorflow.python.ops.gen_string_ops import *
from tensorflow.python.util import compat as util_compat
from tensorflow.python.util import deprecation
from tensorflow.python.util import dispatch
from tensorflow.python.util.tf_export import tf_export
# pylint: enable=g-bad-import-order
# pylint: enable=wildcard-import

# pylint: disable=redefined-builtin
@tf_export("strings.regex_full_match")
@dispatch.add_dispatch_support
def regex_full_match(input, pattern, name=None):
  r"""Match elements of `input` with regex `pattern`.

  Args:
    input: string `Tensor`, the source strings to process.
    pattern: string or scalar string `Tensor`, regular expression to use,
      see more details at https://github.com/google/re2/wiki/Syntax
    name: Name of the op.

  Returns:
    bool `Tensor` of the same shape as `input` with match results.
  """
  # TODO(b/112455102): Remove compat.forward_compatible once past the horizon.
  if not compat.forward_compatible(2018, 11, 10):
    return gen_string_ops.regex_full_match(
        input=input, pattern=pattern, name=name)
  if isinstance(pattern, util_compat.bytes_or_text_types):
    # When `pattern` is static through the life of the op we can
    # use a version which performs the expensive regex compilation once at
    # creation time.
    return gen_string_ops.static_regex_full_match(
        input=input, pattern=pattern, name=name)
  return gen_string_ops.regex_full_match(
      input=input, pattern=pattern, name=name)

regex_full_match.__doc__ = gen_string_ops.regex_full_match.__doc__

@tf_export(
    "strings.regex_replace", v1=["strings.regex_replace", "regex_replace"])
@deprecation.deprecated_endpoints("regex_replace")
@dispatch.add_dispatch_support
def regex_replace(input, pattern, rewrite, replace_global=True, name=None):
  r"""Replace elements of `input` matching regex `pattern` with `rewrite`.

  Args:
    input: string `Tensor`, the source strings to process.
    pattern: string or scalar string `Tensor`, regular expression to use,
      see more details at https://github.com/google/re2/wiki/Syntax
    rewrite: string or scalar string `Tensor`, value to use in match
      replacement, supports backslash-escaped digits (\1 to \9) can be to insert
      text matching corresponding parenthesized group.
    replace_global: `bool`, if `True` replace all non-overlapping matches,
      else replace only the first match.
    name: A name for the operation (optional).

  Returns:
    string `Tensor` of the same shape as `input` with specified replacements.
  """
  if (isinstance(pattern, util_compat.bytes_or_text_types) and
      isinstance(rewrite, util_compat.bytes_or_text_types)):
    # When `pattern` and `rewrite` are static through the life of the op we can
    # use a version which performs the expensive regex compilation once at
    # creation time.
    return gen_string_ops.static_regex_replace(
        input=input, pattern=pattern,
        rewrite=rewrite, replace_global=replace_global,
        name=name)
  return gen_string_ops.regex_replace(
      input=input, pattern=pattern,
      rewrite=rewrite, replace_global=replace_global,
      name=name)

@tf_export("strings.format")
def string_format(template, inputs, placeholder="{}", summarize=3, name=None):
  r"""Formats a string template using a list of tensors.

  Formats a string template using a list of tensors, abbreviating tensors by
  only printing the first and last `summarize` elements of each dimension
  (recursively). If formatting only one tensor into a template, the tensor does
  not have to be wrapped in a list.

  Example:
    Formatting a single-tensor template:
    ```python
    sess = tf.compat.v1.Session()
    with sess.as_default():
        tensor = tf.range(10)
        formatted = tf.strings.format("tensor: {}, suffix", tensor)
        out = sess.run(formatted)
        expected = "tensor: [0 1 2 ... 7 8 9], suffix"

        assert(out.decode() == expected)
    ```

    Formatting a multi-tensor template:
    ```python
    sess = tf.compat.v1.Session()
    with sess.as_default():
        tensor_one = tf.reshape(tf.range(100), [10, 10])
        tensor_two = tf.range(10)
        formatted = tf.strings.format("first: {}, second: {}, suffix",
          (tensor_one, tensor_two))

        out = sess.run(formatted)
        expected = ("first: [[0 1 2 ... 7 8 9]\n"
              " [10 11 12 ... 17 18 19]\n"
              " [20 21 22 ... 27 28 29]\n"
              " ...\n"
              " [70 71 72 ... 77 78 79]\n"
              " [80 81 82 ... 87 88 89]\n"
              " [90 91 92 ... 97 98 99]], second: [0 1 2 ... 7 8 9], suffix")

        assert(out.decode() == expected)
    ```

  Args:
    template: A string template to format tensor values into.
    inputs: A list of `Tensor` objects, or a single Tensor.
      The list of tensors to format into the template string. If a solitary
      tensor is passed in, the input tensor will automatically be wrapped as a
      list.
    placeholder: An optional `string`. Defaults to `{}`.
      At each placeholder occurring in the template, a subsequent tensor
      will be inserted.
    summarize: An optional `int`. Defaults to `3`.
      When formatting the tensors, show the first and last `summarize`
      entries of each tensor dimension (recursively). If set to -1, all
      elements of the tensor will be shown.
    name: A name for the operation (optional).

  Returns:
    A scalar `Tensor` of type `string`.

  Raises:
    ValueError: if the number of placeholders does not match the number of
      inputs.
  """
  # If there is only one tensor to format, we will automatically wrap it in a
  # list to simplify the user experience
  if tensor_util.is_tensor(inputs):
    inputs = [inputs]
  if template.count(placeholder) != len(inputs):
    raise ValueError("%s placeholder(s) in template does not match %s tensor(s)"
                     " provided as input" % (template.count(placeholder),
                                             len(inputs)))

  return gen_string_ops.string_format(inputs,
                                      template=template,
                                      placeholder=placeholder,
                                      summarize=summarize,
                                      name=name)

# Note: tf.strings.split is exported in ragged/ragged_string_ops.py, which
# defines a wrapper for this function.
def string_split(source, sep=None, skip_empty=True, delimiter=None):  # pylint: disable=invalid-name
  """Split elements of `source` based on `delimiter` into a `SparseTensor`.

  Let N be the size of source (typically N will be the batch size). Split each
  element of `source` based on `delimiter` and return a `SparseTensor`
  containing the split tokens. Empty tokens are ignored.

  If `sep` is an empty string, each element of the `source` is split
  into individual strings, each containing one byte. (This includes splitting
  multibyte sequences of UTF-8.) If delimiter contains multiple bytes, it is
  treated as a set of delimiters with each considered a potential split point.

  For example:
  N = 2, source[0] is 'hello world' and source[1] is 'a b c', then the output
  will be

  st.indices = [0, 0;
                0, 1;
                1, 0;
                1, 1;
                1, 2]
  st.shape = [2, 3]
  st.values = ['hello', 'world', 'a', 'b', 'c']

  Args:
    source: `1-D` string `Tensor`, the strings to split.
    sep: `0-D` string `Tensor`, the delimiter character, the string should
      be length 0 or 1. Default is ' '.
    skip_empty: A `bool`. If `True`, skip the empty strings from the result.
    delimiter: deprecated alias for `sep`.

  Raises:
    ValueError: If delimiter is not a string.

  Returns:
    A `SparseTensor` of rank `2`, the strings split according to the delimiter.
    The first column of the indices corresponds to the row in `source` and the
    second column corresponds to the index of the split component in this row.
  """
  delimiter = deprecation.deprecated_argument_lookup(
      "sep", sep, "delimiter", delimiter)

  if delimiter is None:
    delimiter = " "
  delimiter = ops.convert_to_tensor(delimiter, dtype=dtypes.string)
  source = ops.convert_to_tensor(source, dtype=dtypes.string)

  indices, values, shape = gen_string_ops.string_split(
      source, delimiter=delimiter, skip_empty=skip_empty)
  indices.set_shape([None, 2])
  values.set_shape([None])
  shape.set_shape([2])
  return sparse_tensor.SparseTensor(indices, values, shape)

# Note: tf.strings.split is exported in ragged/ragged_string_ops.py, which
# defines a wrapper for this function.
def string_split_v2(source, sep=None, maxsplit=-1):
  """Split elements of `source` based on `sep` into a `SparseTensor`.

  Let N be the size of source (typically N will be the batch size). Split each
  element of `source` based on `sep` and return a `SparseTensor`
  containing the split tokens. Empty tokens are ignored.

  For example, N = 2, source[0] is 'hello world' and source[1] is 'a b c',
  then the output will be

  st.indices = [0, 0;
                0, 1;
                1, 0;
                1, 1;
                1, 2]
  st.shape = [2, 3]
  st.values = ['hello', 'world', 'a', 'b', 'c']

  If `sep` is given, consecutive delimiters are not grouped together and are
  deemed to delimit empty strings. For example, source of `"1<>2<><>3"` and
  sep of `"<>"` returns `["1", "2", "", "3"]`. If `sep` is None or an empty
  string, consecutive whitespace are regarded as a single separator, and the
  result will contain no empty strings at the start or end if the string has
  leading or trailing whitespace.

  Note that the above mentioned behavior matches python's str.split.

  Args:
    source: `1-D` string `Tensor`, the strings to split.
    sep: `0-D` string `Tensor`, the delimiter character.
    maxsplit: An `int`. If `maxsplit > 0`, limit of the split of the result.

  Raises:
    ValueError: If sep is not a string.

  Returns:
    A `SparseTensor` of rank `2`, the strings split according to the delimiter.
    The first column of the indices corresponds to the row in `source` and the
    second column corresponds to the index of the split component in this row.
  """
  if sep is None:
    sep = ""
  sep = ops.convert_to_tensor(sep, dtype=dtypes.string)
  source = ops.convert_to_tensor(source, dtype=dtypes.string)

  indices, values, shape = gen_string_ops.string_split_v2(
      source, sep=sep, maxsplit=maxsplit)
  indices.set_shape([None, 2])
  values.set_shape([None])
  shape.set_shape([2])
  return sparse_tensor.SparseTensor(indices, values, shape)

def _reduce_join_reduction_dims(x, axis):
  """Returns range(rank(x) - 1, 0, -1) if axis is None; or axis otherwise."""
  if axis is not None:
    return axis
  else:
    # Fast path: avoid creating Rank and Range ops if ndims is known.
    if x.get_shape().ndims is not None:
      return constant_op.constant(
          np.arange(x.get_shape().ndims - 1, -1, -1), dtype=dtypes.int32)

    # Otherwise, we rely on Range and Rank to do the right thing at run-time.
    return math_ops.range(array_ops.rank(x) - 1, -1, -1)

@tf_export(v1=["strings.reduce_join", "reduce_join"])
@deprecation.deprecated_args(None,
                             "keep_dims is deprecated, use keepdims instead",
                             "keep_dims")
@deprecation.deprecated_endpoints("reduce_join")
def reduce_join(inputs, axis=None,  # pylint: disable=missing-docstring
                keep_dims=None,
                separator="",
                name=None,
                reduction_indices=None,
                keepdims=None):
  keepdims = deprecation.deprecated_argument_lookup("keepdims", keepdims,
                                                    "keep_dims", keep_dims)
  if keep_dims is None:
    keep_dims = False
  axis = deprecation.deprecated_argument_lookup("axis", axis,
                                                "reduction_indices",
                                                reduction_indices)
  return reduce_join_v2(
      inputs=inputs,
      axis=axis,
      keepdims=keepdims,
      separator=separator,
      name=name)

@tf_export("strings.reduce_join", v1=[])
@dispatch.add_dispatch_support
def reduce_join_v2(  # pylint: disable=missing-docstring
    inputs,
    axis=None,
    keepdims=False,
    separator="",
    name=None):
  with ops.name_scope(None, "ReduceJoin", [inputs, axis]):
    inputs_t = ops.convert_to_tensor(inputs)
    axis = _reduce_join_reduction_dims(inputs_t, axis)
    return gen_string_ops.reduce_join(
        inputs=inputs_t,
        reduction_indices=axis,
        keep_dims=keepdims,
        separator=separator,
        name=name)

reduce_join.__doc__ = deprecation.rewrite_argument_docstring(
    gen_string_ops.reduce_join.__doc__, "reduction_indices", "axis")
reduce_join.__doc__ = reduce_join.__doc__.replace("tf.reduce_join(",
                                                  "tf.strings.reduce_join(")

# This wrapper provides backwards compatibility for code that predates the
# unit argument and that passed 'name' as a positional argument.
@tf_export(v1=["strings.length"])
@dispatch.add_dispatch_support
def string_length(input, name=None, unit="BYTE"):
  return gen_string_ops.string_length(input, unit=unit, name=name)

@tf_export("strings.length", v1=[])
@dispatch.add_dispatch_support
def string_length_v2(input, unit="BYTE", name=None):
  return string_length(input, name, unit)

string_length.__doc__ = gen_string_ops.string_length.__doc__

@tf_export(v1=["substr"])
@deprecation.deprecated(None, "Use `tf.strings.substr` instead of `tf.substr`.")
def substr_deprecated(input, pos, len, name=None, unit="BYTE"):
  return substr(input, pos, len, name=name, unit=unit)

substr_deprecated.__doc__ = gen_string_ops.substr.__doc__

@tf_export(v1=["strings.substr"])
@dispatch.add_dispatch_support
def substr(input, pos, len, name=None, unit="BYTE"):
  return gen_string_ops.substr(input, pos, len, unit=unit, name=name)

substr.__doc__ = gen_string_ops.substr.__doc__

@tf_export("strings.substr", v1=[])
@dispatch.add_dispatch_support
def substr_v2(input, pos, len, unit="BYTE", name=None):
  return gen_string_ops.substr(input, pos, len, unit=unit, name=name)

substr_v2.__doc__ = gen_string_ops.substr.__doc__

ops.NotDifferentiable("RegexReplace")
ops.NotDifferentiable("StringToHashBucket")
ops.NotDifferentiable("StringToHashBucketFast")
ops.NotDifferentiable("StringToHashBucketStrong")
ops.NotDifferentiable("ReduceJoin")
ops.NotDifferentiable("StringJoin")
ops.NotDifferentiable("StringSplit")
ops.NotDifferentiable("AsString")
ops.NotDifferentiable("EncodeBase64")
ops.NotDifferentiable("DecodeBase64")

@tf_export("strings.to_number", v1=[])
@dispatch.add_dispatch_support
def string_to_number(input, out_type=dtypes.float32, name=None):
  r"""Converts each string in the input Tensor to the specified numeric type.

  (Note that int32 overflow results in an error while float overflow
  results in a rounded value.)

  Args:
    input: A `Tensor` of type `string`.
    out_type: An optional `tf.DType` from: `tf.float32, tf.float64, tf.int32,
      tf.int64`. Defaults to `tf.float32`.
      The numeric type to interpret each string in `string_tensor` as.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` of type `out_type`.
  """
  return gen_parsing_ops.string_to_number(input, out_type, name)

@tf_export(v1=["strings.to_number", "string_to_number"])
def string_to_number_v1(
    string_tensor=None,
    out_type=dtypes.float32,
    name=None,
    input=None):
  string_tensor = deprecation.deprecated_argument_lookup(
      "input", input, "string_tensor", string_tensor)
  return gen_parsing_ops.string_to_number(string_tensor, out_type, name)

string_to_number_v1.__doc__ = gen_parsing_ops.string_to_number.__doc__

@tf_export("strings.to_hash_bucket", v1=[])
@dispatch.add_dispatch_support
def string_to_hash_bucket(input, num_buckets, name=None):
  # pylint: disable=line-too-long
  r"""Converts each string in the input Tensor to its hash mod by a number of buckets.

  The hash function is deterministic on the content of the string within the
  process.

  Note that the hash function may change from time to time.
  This functionality will be deprecated and it's recommended to use
  `tf.strings.to_hash_bucket_fast()` or `tf.strings.to_hash_bucket_strong()`.

  Args:
    input: A `Tensor` of type `string`.
    num_buckets: An `int` that is `>= 1`. The number of buckets.
    name: A name for the operation (optional).

  Returns:
    A `Tensor` of type `int64`.
  """
  # pylint: enable=line-too-long
  return gen_string_ops.string_to_hash_bucket(input, num_buckets, name)

@tf_export(v1=["strings.to_hash_bucket", "string_to_hash_bucket"])
def string_to_hash_bucket_v1(
    string_tensor=None,
    num_buckets=None,
    name=None,
    input=None):
  string_tensor = deprecation.deprecated_argument_lookup(
      "input", input, "string_tensor", string_tensor)
  return gen_string_ops.string_to_hash_bucket(string_tensor, num_buckets, name)

string_to_hash_bucket_v1.__doc__ = gen_string_ops.string_to_hash_bucket.__doc__


text:
date: 2022-01-07T08:00:00Z
title: Function RECURSIVE-LOCK-P
weight: 4
---

#### Syntax:

**recursive-lock-p** datum => generalized-boolean

#### Arguments and values:

*datum* -> an object.\
*generalized-boolean* -> a [generalized
boolean](http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_g.htm#generalized_boolean).

#### Description:

Returns
[true](http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_t.htm#true)
if `datum` is a recursive lock, otherwise
[false](http://www.lispworks.com/documentation/HyperSpec/Body/26_glo_f.htm#false).

#### Exceptional situations:

None.

#### See also:

[**recursive-lock**](../recursive-lock)

#### Notes:

None.


text:
package org.apache.tester;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Test to insure that an included servlet can set request attributes that are
 * visible to the calling servlet after the include() returns.
 * The spec is silent on this topic, but it seems consistent with the overall
 * intent to behave in this manner.
 *
 * The test includes either a servlet ("/Include03a") or a JSP page
 * ("/Include03b.jsp") depending on the value specified for the "path"
 * parameter.  The default is the servlet.
 *
 * @author Craig R. McClanahan
 * @version $Revision: 1.2 $ $Date: 2001/05/03 18:41:37 $
 */

public class Include03 extends HttpServlet {

    private static final String specials[] =
    { "javax.servlet.include.request_uri",
      "javax.servlet.include.context_path",
      "javax.servlet.include.servlet_path",
      "javax.servlet.include.path_info",
      "javax.servlet.include.query_string" };

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

        // Prepare this response
        StringBuffer sb = new StringBuffer();
        response.setContentType("text/plain");
	PrintWriter writer = response.getWriter();

        // Acquire the path to which we will issue an include
        String path = request.getParameter("path");
        if (path == null)
            path = "/Include03a";

        // Create a request dispatcher and call include() on it
        RequestDispatcher rd =
            getServletContext().getRequestDispatcher(path);
        if (rd == null) {
            sb.append(" No RequestDispatcher returned/");
        } else {
            rd.include(request, response);
        }
        response.resetBuffer();

        // We MUST be able to see the attribute created by the includee
        String value = null;
        try {
            value = (String)
                request.getAttribute(path.substring(1));
        } catch (ClassCastException e) {
            sb.append(" Returned attribute not of type String/");
        }
        if ((sb.length() < 1) && (value == null)) {
            sb.append(" No includee-created attribute was returned/");
        }

        // We MUST NOT see the special attributes created by the container
        for (int i = 0; i < specials.length; i++) {
            if (request.getAttribute(specials[i]) != null) {
                sb.append(" Returned attribute ");
                sb.append(specials[i]);
                sb.append("/");
            }
        }

        // Write our response
        if (sb.length() < 1)
            writer.println("Include03 PASSED");
        else {
            writer.print("Include03 FAILED -");
            writer.println(sb.toString());
        }

        while (true) {
            String message = StaticLogger.read();
            if (message == null)
                break;
            writer.println(message);
        }
        StaticLogger.reset();

    }

}


text:
from unittest.mock import patch

from airflow.providers.amazon.aws.hooks.lambda_function import AwsLambdaHook

try:
    from moto import mock_lambda
except ImportError:
    mock_lambda = None

class TestAwsLambdaHook:
    @mock_lambda
    def test_get_conn_returns_a_boto3_connection(self):
        hook = AwsLambdaHook(
            aws_conn_id='aws_default', function_name="test_function", region_name="us-east-1"
        )
        assert hook.conn is not None

    @mock_lambda
    def test_invoke_lambda_function(self):

        hook = AwsLambdaHook(
            aws_conn_id='aws_default', function_name="test_function", region_name="us-east-1"
        )

        with patch.object(hook.conn, 'invoke') as mock_invoke:
            payload = '{"hello": "airflow"}'
            hook.invoke_lambda(payload=payload)

        mock_invoke.asset_called_once_with(
            FunctionName="test_functin",
            InvocationType="RequestResponse",
            LogType="None",
            Payload=payload,
            Qualifier="$LATEST",
        )


text:
<?php
namespace MangoPay;

/**
 * Class to management MangoPay API for wallets
 */
class ApiWallets extends Libraries\ApiBase
{
    /**
     * Create new wallet
     * @param Wallet $wallet
     * @return \MangoPay\Wallet Wallet object returned from API
     */
    public function Create($wallet, $idempotencyKey = null)
    {
        return $this->CreateObject('wallets_create', $wallet, '\MangoPay\Wallet', null, null, $idempotencyKey);
    }

    /**
     * Get wallet
     * @param int $walletId Wallet identifier
     * @return \MangoPay\Wallet Wallet object returned from API
     */
    public function Get($walletId)
    {
        return $this->GetObject('wallets_get', $walletId, '\MangoPay\Wallet');
    }

    /**
     * Save wallet
     * @param Wallet $wallet Wallet object to save
     * @return \MangoPay\Wallet Wallet object returned from API
     */
    public function Update($wallet)
    {
        return $this->SaveObject('wallets_save', $wallet, '\MangoPay\Wallet');
    }

    /**
     * Get transactions for the wallet
     * @param type $walletId Wallet identifier
     * @param \MangoPay\Pagination $pagination Pagination object
     * @param \MangoPay\FilterTransactions $filter Object to filter data
     * @param \MangoPay\Sorting $sorting Object to sorting data
     * @return \MangoPay\Transaction[] Transactions for wallet returned from API
     */
    public function GetTransactions($walletId, & $pagination = null, $filter = null, $sorting = null)
    {
        return $this->GetList('wallets_alltransactions', $pagination, '\MangoPay\Transaction', $walletId, $filter, $sorting);
    }
}


text:
"""Models for ${app_name} application."""

MODELS = ()


text:
package org.apache.logging.log4j.layout.template.json.util;

import org.apache.logging.log4j.util.Strings;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Callable;

public final class StringParameterParser {

    private StringParameterParser() {}

    public static final class Values {

        private Values() {}

        static NullValue nullValue() {
            return NullValue.INSTANCE;
        }

        static StringValue stringValue(final String string) {
            return new StringValue(string);
        }

        static DoubleQuotedStringValue doubleQuotedStringValue(
                final String doubleQuotedString) {
            return new DoubleQuotedStringValue(doubleQuotedString);
        }

    }

    public interface Value {}

    public static final class NullValue implements Value {

        private static final NullValue INSTANCE = new NullValue();

        private NullValue() {}

        @Override
        public String toString() {
            return "null";
        }

    }

    public static final class StringValue implements Value {

        private final String string;

        private StringValue(String string) {
            this.string = string;
        }

        public String getString() {
            return string;
        }

        @Override
        public boolean equals(Object object) {
            if (this == object) {
                return true;
            }
            if (object == null || getClass() != object.getClass()) {
                return false;
            }
            StringValue that = (StringValue) object;
            return string.equals(that.string);
        }

        @Override
        public int hashCode() {
            return 31 + Objects.hashCode(string);
        }

        @Override
        public String toString() {
            return string;
        }

    }

    public static final class DoubleQuotedStringValue implements Value {

        private final String doubleQuotedString;

        private DoubleQuotedStringValue(String doubleQuotedString) {
            this.doubleQuotedString = doubleQuotedString;
        }

        public String getDoubleQuotedString() {
            return doubleQuotedString;
        }

        @Override
        public boolean equals(Object object) {
            if (this == object) {
                return true;
            }
            if (object == null || getClass() != object.getClass()) {
                return false;
            }
            DoubleQuotedStringValue that = (DoubleQuotedStringValue) object;
            return doubleQuotedString.equals(that.doubleQuotedString);
        }

        @Override
        public int hashCode() {
            return 31 + Objects.hashCode(doubleQuotedString);
        }

        @Override
        public String toString() {
            return doubleQuotedString.replaceAll("\\\\\"", "\"");
        }

    }

    private enum State { READING_KEY, READING_VALUE }

    private static final class Parser implements Callable<Map<String, Value>> {

        private final String input;

        private final Map<String, Value> map;

        private State state;

        private int i;

        private String key;

        private Parser(final String input) {
            this.input = Objects.requireNonNull(input, "input");
            this.map = new LinkedHashMap<>();
            this.state = State.READING_KEY;
            this.i = 0;
            this.key = null;
        }

        @Override
        public Map<String, Value> call() {
            while (true) {
                skipWhitespace();
                if (i >= input.length()) {
                    break;
                }
                switch (state) {
                    case READING_KEY:
                        readKey();
                        break;
                    case READING_VALUE:
                        readValue();
                        break;
                    default:
                        throw new IllegalStateException("unknown state: " + state);
                }
            }
            if (state == State.READING_VALUE) {
                map.put(key, Values.nullValue());
            }
            return map;
        }

        private void readKey() {
            final int eq = input.indexOf('=', i);
            final int co = input.indexOf(',', i);
            final int j;
            final int nextI;
            if (eq < 0 && co < 0) {
                // Neither '=', nor ',' was found.
                j = nextI = input.length();
            } else if (eq < 0) {
                // Found ','.
                j = nextI = co;
            } else if (co < 0) {
                // Found '='.
                j = eq;
                nextI = eq + 1;
            } else if (eq < co) {
                // Found '=...,'.
                j = eq;
                nextI = eq + 1;
            } else {
                // Found ',...='.
                j = co;
                nextI = co;
            }
            key = input.substring(i, j).trim();
            if (Strings.isEmpty(key)) {
                final String message = String.format(
                        "failed to locate key at index %d: %s",
                        i, input);
                throw new IllegalArgumentException(message);
            }
            if (map.containsKey(key)) {
                final String message = String.format(
                        "conflicting key at index %d: %s",
                        i, input);
                throw new IllegalArgumentException(message);
            }
            state = State.READING_VALUE;
            i = nextI;
        }

        private void readValue() {
            final boolean doubleQuoted = input.charAt(i) == '"';
            if (doubleQuoted) {
                readDoubleQuotedStringValue();
            } else {
                readStringValue();
            }
            key = null;
            state = State.READING_KEY;
        }

        private void readDoubleQuotedStringValue() {
            int j = i + 1;
            while (j < input.length()) {
                if (input.charAt(j) == '"' && input.charAt(j - 1) != '\\') {
                    break;
                } else {
                    j++;
                }
            }
            if (j >= input.length()) {
                final String message = String.format(
                        "failed to locate the end of double-quoted content starting at index %d: %s",
                        i, input);
                throw new IllegalArgumentException(message);
            }
            final String content = input
                    .substring(i + 1, j)
                    .replaceAll("\\\\\"", "\"");
            final Value value = Values.doubleQuotedStringValue(content);
            map.put(key, value);
            i = j + 1;
            skipWhitespace();
            if (i < input.length()) {
                if (input.charAt(i) != ',') {
                    final String message = String.format(
                            "was expecting comma at index %d: %s",
                            i, input);
                    throw new IllegalArgumentException(message);
                }
                i++;
            }
        }

        private void skipWhitespace() {
            while (i < input.length()) {
                final char c = input.charAt(i);
                if (!Character.isWhitespace(c)) {
                    break;
                } else {
                    i++;
                }
            }
        }

        private void readStringValue() {
            int j = input.indexOf(',', i/* + 1*/);
            if (j < 0) {
                j = input.length();
            }
            final String content = input.substring(i, j);
            final String trimmedContent = content.trim();
            final Value value = trimmedContent.isEmpty()
                    ? Values.nullValue()
                    : Values.stringValue(trimmedContent);
            map.put(key, value);
            i += content.length() + 1;
        }

    }

    public static Map<String, Value> parse(final String input) {
        return parse(input, null);
    }

    public static Map<String, Value> parse(
            final String input,
            final Set<String> allowedKeys) {
        if (Strings.isBlank(input)) {
            return Collections.emptyMap();
        }
        final Map<String, Value> map = new Parser(input).call();
        final Set<String> actualKeys = map.keySet();
        for (final String actualKey : actualKeys) {
            final boolean allowed = allowedKeys == null || allowedKeys.contains(actualKey);
            if (!allowed) {
                final String message = String.format(
                        "unknown key \"%s\" is found in input: %s",
                        actualKey, input);
                throw new IllegalArgumentException(message);
            }
        }
        return map;
    }

}


text:
"""Generates sequence of binary patterns or kv pairs to test associative memory.

Pattern task: Given N patterns, retrieve the right pattern via its degraded
version, where some of the bits are set to 0.

Symbolic key-value task: Given a string of concatenated key-value pairs,
retrieve the right value given the key.

See [Miconi et al. 2018] Differentiable Plasticity
(https://arxiv.org/abs/1804.02464) and [Ba et al. 2016] Using Fast Weights to
to Attend to the Recent Past (https://arxiv.org/abs/1610.06258v1) for details
of task design.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import random
import string

import numpy as np
import tensorflow.compat.v1 as tf

def generate_pattern_data(num_patterns, pattern_size):
  """Generates a sequence of patterns followed by a degraded query pattern.

  Args:
    num_patterns (int): Number of unique patterns in the sequence
    pattern_size (int): Dimensionality of each pattern

  Returns:
    seq: Numpy array, the sequence of patterns to be presented
      shape [num_patterns + 1, pattern_size]
    target: Numpy array, the pattern we expect to retrieve for the degraded
      query pattern
      shape [pattern_size,]
    target_idx (int): The index into the list of unique patterns for the target
    patterns: List of np arrays, all unique patterns
  """
  patterns = []
  for _ in range(num_patterns):
    pattern = np.random.choice([-1, 1], size=(pattern_size,), p=[.5, .5])
    patterns.append(pattern)

  # Choose one pattern to degrade
  target_idx = random.choice(range(num_patterns))
  target = patterns[target_idx]
  degraded = target.copy()
  degraded_idxs = np.random.choice(
      pattern_size, pattern_size // 2, replace=False)
  degraded[degraded_idxs] = 0
  patterns.append(degraded)

  seq = np.array(patterns)

  return seq, target, target_idx, patterns

def generate_pattern_data_selective(num_patterns, num_patterns_store,
                                    pattern_size):
  """Generates a sequence of patterns followed by a degraded query pattern.

  Args:
    num_patterns (int): Number of unique patterns in the sequence
    num_patterns_store (int): Number of patterns we actually have to store
    pattern_size (int): Dimensionality of each pattern

  Returns:
    seq: Numpy array, the sequence of patterns to be presented.
      shape [num_patterns + 1, pattern_size]
    target: Numpy array, the pattern we expect to retrieve for the degraded
      query pattern.
      shape [pattern_size,]
    target_idx (int): The index into the list of unique patterns for the target.
    patterns: List of np arrays, all unique patterns.
      Patterns we need to remember (that may be queried) have their last bit set
      to 1, otherwise 0.
  """
  patterns = []
  for _ in range(num_patterns):
    pattern = np.random.choice([-1, 1], size=(pattern_size,), p=[.5, .5])
    patterns.append(pattern)

  # Choose patterns that are important to remember
  remember_idxs = np.random.choice(
      range(num_patterns), size=num_patterns_store, replace=False)
  patterns = [
      np.append(p, [1]) if i in remember_idxs else np.append(p, [0])
      for i, p in enumerate(patterns)
  ]

  # Choose one pattern to degrade
  target_idx = random.choice(range(num_patterns))
  target = patterns[target_idx]
  degraded = target.copy()
  degraded_idxs = np.random.choice(
      pattern_size, pattern_size // 2, replace=False)
  degraded[degraded_idxs] = 0
  patterns.append(degraded)

  seq = np.array(patterns)

  return seq, target, target_idx, patterns

def generate_symbolic_data(num_pairs):
  """Generates a sequence of key-value pairs followed by a query key.

  Args:
    num_pairs (int): Number of pairs

  Returns:
    seq_text (str): Sequence of kv pairs, followed by a ?,
      followed by the query key.
    seq_encoded (numpy arr): Sequence of kv pairs, encoded into vocab indices.
    target_val (str): Digit, the value we expect to retrieve for the key.
    target_val_encoded (int): Encoded target_val
    target_idx (int): The index into the list of pairs for the target
  """
  pairs = zip(
      np.random.choice(list(string.ascii_lowercase), num_pairs, replace=False),
      np.random.choice(list("0123456789"), num_pairs)
  )

  vocab = get_symbolic_vocab()

  # Choose a query key
  target_idx = random.choice(range(num_pairs))
  target_key, target_val_text = pairs[target_idx]
  target_val_encoded = vocab.index(target_val_text)

  seq_text = "".join([k + v for k, v in pairs]) + "?" + target_key
  seq_encoded = [vocab.index(char) for char in seq_text]

  return seq_text, seq_encoded, target_val_text, target_val_encoded, target_idx

def get_pattern_dataset(n=100000,
                        num_patterns=3,
                        pattern_size=50,
                        selective=False,
                        num_patterns_store=None):
  """Generates a dataset of sequences of patterns and retrieval targets.

  Args:
    n: Number of examples
    num_patterns: Number of unique patterns in the sequence
    pattern_size: Dimensionality of each pattern
    selective (bool): True if only a subset of patterns needs to be stored.
    num_patterns_store: Number of patterns to store if selective=True.

  Returns:
    A tf.data.Dataset created from a dict with property "seqs,"
    containing the sequences of randomly generated binary patterns, and
    "targets," containing the ground-truth pattern to retrieve for the last
    degraded query pattern in the sequence.
  """
  seqs = []
  targets = []

  for _ in range(n):
    if selective:
      if num_patterns_store is None:
        num_patterns_store = num_patterns // 10
      seq, target, _, _ = generate_pattern_data_selective(
          num_patterns, num_patterns_store, pattern_size)
    else:
      seq, target, _, _ = generate_pattern_data(num_patterns, pattern_size)

    seqs.append(seq)
    targets.append(target)

  return tf.data.Dataset.from_tensor_slices({
      "seqs": np.array(seqs, dtype=np.float32),
      "targets": np.array(targets, dtype=np.int32)
  })

def get_symbolic_dataset(_, n=100000, num_pairs=5):
  """Generates a dataset of sequences of key-value pairs and retrieval targets.

  Args:
    n: Number of examples
    num_pairs: Number of pairs in each sequence

  Returns:
    A tf.data.Dataset created from a dict with property "seqs,"
    containing the sequences of randomly generated key-value pairs, and
    "targets," containing the ground-truth value to retrieve for the query key.
  """

  seqs = []
  targets = []

  for _ in range(n):
    _, seq_encoded, _, target_encoded, _ = generate_symbolic_data(num_pairs)
    seqs.append(seq_encoded)
    targets.append(target_encoded)

  return tf.data.Dataset.from_tensor_slices({
      "seqs": np.array(seqs, dtype=np.int32),
      "targets": np.array(targets, dtype=np.int32)
  })

def get_symbolic_vocab():
  """Gets the vocabulary for the symbolic task.

  Returns:
    A list with a-z, 0-9, and ?.
  """
  return list(string.ascii_lowercase) + list(string.digits + "?")


text:
package org.omg.PortableServer;

/**
 * Allows dynamic handling of object invocations.  POA-based DSI
 * servants inherit from the
 * standard DynamicImplementation class, this class inherits
 * from the Servant class. Based on IDL to Java spec.
 * CORBA V 2.3.1 ptc/00-01-08.pdf.
 */
abstract public class DynamicImplementation extends Servant {

/**
 * Receives requests issued to any CORBA object
 * incarnated by the DSI servant and performs the processing
 * necessary to execute the request.
 * @param request the request issued to the CORBA object.
 */
    abstract public void invoke(org.omg.CORBA.ServerRequest request);
}


text:
<?php

declare(strict_types=1);

namespace OAuth2Framework\ServerBundle\Component\Endpoint\Authorization\Compiler;

use OAuth2Framework\Component\AuthorizationEndpoint\User\UserAuthenticationCheckerManager;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class UserAuthenticationCheckerCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container): void
    {
        if (!$container->hasDefinition(UserAuthenticationCheckerManager::class)) {
            return;
        }

        $definition = $container->getDefinition(UserAuthenticationCheckerManager::class);

        $taggedServices = $container->findTaggedServiceIds('oauth2_server_user_authentication_checker');
        foreach ($taggedServices as $id => $attributes) {
            $definition->addMethodCall('add', [new Reference($id)]);
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>1. About — SmallK 1.6.2 documentation</title>

    <link rel="stylesheet" href="_static/css/my_theme.css" type="text/css" />

        <link rel="index" title="Index"
              href="genindex.html"/>
        <link rel="search" title="Search" href="search.html"/>
    <link rel="top" title="SmallK 1.6.2 documentation" href="index.html"/>
        <link rel="next" title="2. Introduction" href="pages_introduction.html"/>
        <link rel="prev" title="SmallK" href="index.html"/>

             SmallK

  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

SmallK

1. About

1.1. Distributed Versions

1.2. Ground truth data for graph clustering and community detection

1.3. Acknowledgements

1.4. Contact Info

2. Introduction

2.1. Background

2.2. Constrained low rank approximations and NMF

2.3. SmallK Overview

2.4. Prerequisites

3. Quickstart - Installation

3.1. Vagrant Virtual Machine

3.2. Docker Instructions

4. Quickstart - Smallk API

4.1. Introduction

4.2. C++ Project Setup

4.3. Load a Matrix

4.4. Perform NMF on the Loaded Matrix

4.4.1. NMF-BPP

4.4.2. NMF-HALS

4.4.3. NMF Initialization

4.5. Hierarchical Clustering

4.6. Flat Clustering

4.7. Disclaimer

4.8. Contact Info

5. Installation Instructions

5.1. Prerequisites

5.1.1. Elemental

5.1.1.1. How to Install Elemental on MacOSX

5.1.1.1.1. OSX:Install the latest GNU compilers

5.1.1.1.2. OSX:Install MPI Tools

5.1.1.1.3. OSX:Install libFlame

5.1.1.1.4. OSX:Install Elemental

5.1.1.1.4.1. HybridRelease Build

5.1.1.1.4.2. PureRelease Build

5.1.1.2. How to Install Elemental on Linux

5.1.1.2.1. Linux:Install the latest GNU compilers

5.1.1.2.2. Linux:Install MPI Tools

5.1.1.2.3. Linux:Install libFlame

5.1.1.2.4. Linux:Install an accelerated BLAS library

5.1.1.2.5. Linux:Install Elemental

5.1.1.2.5.1. HybridRelease build

5.1.1.2.5.2. PureRelease build

5.1.2. Installation of Python libraries

5.1.2.1. OSX:Install Python libraries

5.1.2.1.1. Install Python scientific packages

5.1.2.1.2. Install Cython: a Python interface to C/C++

5.1.2.2. Linux:Install Python libraries

5.2. Build and Installation of SmallK

5.2.1. Obtain the Source Code

5.2.2. Build the SmallK library

5.2.3. Install the SmallK library

5.2.4. Check the build and installation

5.3. Build and Installation of pysmallk shared library

5.4. Matrix file formats

5.5. Disclaimer

5.6. Contact Info

6. Command Line Tools

6.1. Introduction

6.2. Preprocessor

6.2.1. Overview

6.2.2. Input Files

6.2.3. Command Line Options

6.2.4. Sample Runs

6.3. Matrixgen

6.3.1. Overview

6.3.2. Command Line Options

6.3.3. Sample Runs

6.4. Nonnegative Matrix Factorization (NMF)

6.4.1. Overview

6.4.2. Command Line Options

6.4.3. Sample Runs

6.5. Hierclust

6.5.1. Overview

6.5.2. Command Line Options

6.5.3. Sample Runs

6.6. Flatclust

6.6.1. Overview

6.6.2. Command Line Options

6.6.3. Sample Runs

7. Smallk API (C++)

7.1. Examples of API Usage

7.2. SmallK API

7.2.1. Enumerations

7.2.2. API functions

7.2.2.1. Initialization and cleanup

7.2.2.2. Versioning

7.2.2.3. Common functions

7.2.2.4. NMF functions

8. Pysmallk API (Python)

8.1. Introduction

8.2. Examples of Pysmallk Usage

8.3. Pysmallk Functions

8.3.1. Preprocessor

8.3.2. Matrixgen

8.3.3. SmallkAPI

8.3.4. Flatclust

8.3.5. Hierclust

9. Tests

9.1. SmallK Test Results

10. Benchmarks and Results

11. Publications

12. Software Repo

12.1. Getting the code and instructions

12.2. Contact Info

          SmallK

Docs »

1. About

             View page source

1. About¶

SmallK is a high performance software package for constrained low rank matrix approximation via the nonnegative matrix factorization (NMF). Algorithms for NMF compute the low rank factors of a matrix producing two nonnegative matrices whose product approximates the original matrix. The role of NMF in data analytics has been as significant as the singular value decomposition (SVD). However, due to nonnegativity constraints, NMF has far superior interpretability of its results for many practical problems such as image processing, chemometrics, bioinformatics, topic modeling for text analytics and many more. Our approach to solving the NMF nonconvex optimization problem has proven convergence properties and is one of the most efficient methods developed to date.

1.1. Distributed Versions¶

Recently open sourced: MPI-FAUN! Both MPI and OPENMP implementations for MU, HALS and ANLS/BPP based NMF algorithms are now available. The implementations can run off the shelf or can be easily integrated into other source code. These are very highly tuned NMF algorithms to work on super computers. We have tested this software in NERSC as well OLCF cluster. The openmp implementation is tested on many different linux variants with intel processors. The library works well for both sparse and dense matrices.

Please visit MPI-FAUN text for more information and source code.

1.2. Ground truth data for graph clustering and community detection¶

Community discovery is an important task for revealing structures in large networks. The massive size of contemporary social networks poses a tremendous challenge to the scalability of traditional graph clustering algorithms and the evaluation of discovered communities.

Please visit dblp ground truth data to obtain the data.

For U.S. Patent data go test hybrid clustering of content and connection structure using joint NMF go to patent data to view the readme.

1.3. Acknowledgements¶

This work was funded in part by the DARPA XDATA program under contract FA8750-12-2-0309. Our DARPA program manager is Mr. Wade Shen and our XDATA Principal Investigator is Prof. Haesun Park of the Georgia Institute of Technology. We would like to thank Rundong Du for the dblp ground truth data set and Dr. Ramakrishnan Kannan of ORNL for the MPI-FAUN! distributed code.  Also, special thanks to Dr. Richard Boyd, Dr. Da Kuang, and Ashley Scripka-Beavers for their contributions to previous versions of this documentation and significant technical contributions. A final special thanks to Ethan Trewhitt, who created the Docker install and advised on how to use Sphinx and RTD for documentation.

1.4. Contact Info¶

For comments, questions, bug reports, suggestions, etc., contact:

Barry Drake

Research Scientist

Information and Communications Laboratory (ICL)

Information and Cyber Sciences Directorate (ICSD)

Georgia Tech Research Institute (GTRI)

75 5TH St. NW STE 900

ATLANTA, GA 30308-1018

barry.drake@gtri.gatech.edu

Stephen Lee-Urban

Research Scientist

Information and Communications Laboratory (ICL)

Information and Cyber Sciences Directorate (ICSD)

Georgia Tech Research Institute (GTRI)

75 5TH St. NW STE 900

ATLANTA, GA 30308-1018

stephen.lee-urban@gtri.gatech.edu

        Next

         Previous

        © Copyright 2017, Georgia Institute of Technology.

  Built with Sphinx using a theme provided by Read the Docs.


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="QuantityHelperTests.cs" company="Hukano">
// Copyright (c) Hukano. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Sundew.Quantities.UnitTests.Core;

using System.Linq;
using FluentAssertions;
using Sundew.Quantities.Core;
using Sundew.Quantities.Representations.Expressions;
using Sundew.Quantities.Representations.Units;
using Xunit;

public class QuantityHelperTests
{
    [Theory]
    [InlineData(5, "km", 5000, "m", true)]
    [InlineData(3, "m", 4, "m", false)]
    [InlineData(5, "m", 5, "m", true)]
    [InlineData(5, "m", 5, "s", false)]
    public void AreEqual_Then_ResultShouldBeExpected(
        double lhs,
        string lhsUnit,
        double rhs,
        string rhsUnit,
        bool expected)
    {
        var testee1 = new Quantity(lhs, GetUnit(lhsUnit));
        var testee2 = new Quantity(rhs, GetUnit(rhsUnit));

        var result = QuantityHelper.AreEqual(testee1, testee2);

        result.Should().Be(expected);
    }

    [Theory]
    [InlineData(3, 3, false)]
    [InlineData(5, 18, true)]
    public void AreEqual_When_ComparingTwoCompatibleUnits_Then_ResultShouldBeExpected(
        double lhs,
        double rhs,
        bool expected)
    {
        var testee1 = new Quantity(lhs, UnitDefinitions.Velocity);
        var testee2 = new Quantity(
            rhs,
            new DerivedUnit(string.Empty, new UnitExpression(UnitDefinitions.Meter.GetPrefixedUnit(Prefixes.Kilo)) / UnitDefinitions.Hour.GetExpression()));

        var result = QuantityHelper.AreEqual(testee1, testee2);

        result.Should().Be(expected);
    }

    private static IUnit GetUnit(string lhsUnit)
    {
        var unit = new Unit(lhsUnit.Cast<char>().Last().ToString());
        if (lhsUnit.Length == 2)
        {
            var notation = lhsUnit[0].ToString();
            return unit.GetPrefixedUnit(new FactoredPrefix(notation, 1000, notation));
        }

        return unit;
    }
}


text:
#include "core/svg/SVGAnimateMotionElement.h"

#include "core/SVGNames.h"
#include "core/dom/ElementTraversal.h"
#include "core/layout/LayoutObject.h"
#include "core/svg/SVGMPathElement.h"
#include "core/svg/SVGParserUtilities.h"
#include "core/svg/SVGPathElement.h"
#include "core/svg/SVGPathUtilities.h"
#include "platform/transforms/AffineTransform.h"
#include "wtf/MathExtras.h"
#include "wtf/StdLibExtras.h"

namespace blink {

using namespace SVGNames;

inline SVGAnimateMotionElement::SVGAnimateMotionElement(Document& document)
    : SVGAnimationElement(animateMotionTag, document)
    , m_hasToPointAtEndOfDuration(false)
{
    setCalcMode(CalcModePaced);
}

DEFINE_NODE_FACTORY(SVGAnimateMotionElement)

SVGAnimateMotionElement::~SVGAnimateMotionElement()
{
}

bool SVGAnimateMotionElement::hasValidAttributeType()
{
    SVGElement* targetElement = this->targetElement();
    if (!targetElement)
        return false;

    // We don't have a special attribute name to verify the animation type. Check the element name instead.
    if (!targetElement->isSVGGraphicsElement())
        return false;
    // Spec: SVG 1.1 section 19.2.15
    // FIXME: svgTag is missing. Needs to be checked, if transforming <svg> could cause problems.
    return (isSVGGElement(*targetElement)
        || isSVGDefsElement(*targetElement)
        || isSVGUseElement(*targetElement)
        || isSVGImageElement(*targetElement)
        || isSVGSwitchElement(*targetElement)
        || isSVGPathElement(*targetElement)
        || isSVGRectElement(*targetElement)
        || isSVGCircleElement(*targetElement)
        || isSVGEllipseElement(*targetElement)
        || isSVGLineElement(*targetElement)
        || isSVGPolylineElement(*targetElement)
        || isSVGPolygonElement(*targetElement)
        || isSVGTextElement(*targetElement)
        || isSVGClipPathElement(*targetElement)
        || isSVGMaskElement(*targetElement)
        || isSVGAElement(*targetElement)
        || isSVGForeignObjectElement(*targetElement)
        );
}

bool SVGAnimateMotionElement::hasValidAttributeName()
{
    // AnimateMotion does not use attributeName so it is always valid.
    return true;
}

void SVGAnimateMotionElement::parseAttribute(const QualifiedName& name, const AtomicString& oldValue, const AtomicString& value)
{
    if (name == SVGNames::pathAttr) {
        m_path = Path();
        buildPathFromString(value, m_path);
        updateAnimationPath();
        return;
    }

    SVGAnimationElement::parseAttribute(name, oldValue, value);
}

SVGAnimateMotionElement::RotateMode SVGAnimateMotionElement::getRotateMode() const
{
    DEFINE_STATIC_LOCAL(const AtomicString, autoVal, ("auto", AtomicString::ConstructFromLiteral));
    DEFINE_STATIC_LOCAL(const AtomicString, autoReverse, ("auto-reverse", AtomicString::ConstructFromLiteral));
    const AtomicString& rotate = getAttribute(SVGNames::rotateAttr);
    if (rotate == autoVal)
        return RotateAuto;
    if (rotate == autoReverse)
        return RotateAutoReverse;
    return RotateAngle;
}

void SVGAnimateMotionElement::updateAnimationPath()
{
    m_animationPath = Path();
    bool foundMPath = false;

    for (SVGMPathElement* mpath = Traversal<SVGMPathElement>::firstChild(*this); mpath; mpath = Traversal<SVGMPathElement>::nextSibling(*mpath)) {
        if (SVGPathElement* pathElement = mpath->pathElement()) {
            m_animationPath = pathElement->asPath();
            foundMPath = true;
            break;
        }
    }

    if (!foundMPath && fastHasAttribute(SVGNames::pathAttr))
        m_animationPath = m_path;

    updateAnimationMode();
}

template<typename CharType>
static bool parsePointInternal(const String& string, FloatPoint& point)
{
    const CharType* ptr = string.getCharacters<CharType>();
    const CharType* end = ptr + string.length();

    if (!skipOptionalSVGSpaces(ptr, end))
        return false;

    float x = 0;
    if (!parseNumber(ptr, end, x))
        return false;

    float y = 0;
    if (!parseNumber(ptr, end, y))
        return false;

    point = FloatPoint(x, y);

    // disallow anything except spaces at the end
    return !skipOptionalSVGSpaces(ptr, end);
}

static bool parsePoint(const String& string, FloatPoint& point)
{
    if (string.isEmpty())
        return false;
    if (string.is8Bit())
        return parsePointInternal<LChar>(string, point);
    return parsePointInternal<UChar>(string, point);
}

void SVGAnimateMotionElement::resetAnimatedType()
{
    if (!hasValidAttributeType())
        return;
    SVGElement* targetElement = this->targetElement();
    if (!targetElement)
        return;
    if (AffineTransform* transform = targetElement->animateMotionTransform())
        transform->makeIdentity();
}

void SVGAnimateMotionElement::clearAnimatedType()
{
    SVGElement* targetElement = this->targetElement();
    if (!targetElement)
        return;

    AffineTransform* transform = targetElement->animateMotionTransform();
    if (!transform)
        return;

    transform->makeIdentity();

    if (LayoutObject* targetLayoutObject = targetElement->layoutObject()) {
        targetLayoutObject->setNeedsTransformUpdate();
        markForLayoutAndParentResourceInvalidation(targetLayoutObject);
    }
}

bool SVGAnimateMotionElement::calculateToAtEndOfDurationValue(const String& toAtEndOfDurationString)
{
    parsePoint(toAtEndOfDurationString, m_toPointAtEndOfDuration);
    m_hasToPointAtEndOfDuration = true;
    return true;
}

bool SVGAnimateMotionElement::calculateFromAndToValues(const String& fromString, const String& toString)
{
    m_hasToPointAtEndOfDuration = false;
    parsePoint(fromString, m_fromPoint);
    parsePoint(toString, m_toPoint);
    return true;
}

bool SVGAnimateMotionElement::calculateFromAndByValues(const String& fromString, const String& byString)
{
    m_hasToPointAtEndOfDuration = false;
    if (getAnimationMode() == ByAnimation && !isAdditive())
        return false;
    parsePoint(fromString, m_fromPoint);
    FloatPoint byPoint;
    parsePoint(byString, byPoint);
    m_toPoint = FloatPoint(m_fromPoint.x() + byPoint.x(), m_fromPoint.y() + byPoint.y());
    return true;
}

void SVGAnimateMotionElement::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGSMILElement*)
{
    SVGElement* targetElement = this->targetElement();
    if (!targetElement)
        return;
    AffineTransform* transform = targetElement->animateMotionTransform();
    if (!transform)
        return;

    if (LayoutObject* targetLayoutObject = targetElement->layoutObject())
        targetLayoutObject->setNeedsTransformUpdate();

    if (!isAdditive())
        transform->makeIdentity();

    if (getAnimationMode() != PathAnimation) {
        FloatPoint toPointAtEndOfDuration = m_toPoint;
        if (isAccumulated() && repeatCount && m_hasToPointAtEndOfDuration)
            toPointAtEndOfDuration = m_toPointAtEndOfDuration;

        float animatedX = 0;
        animateAdditiveNumber(percentage, repeatCount, m_fromPoint.x(), m_toPoint.x(), toPointAtEndOfDuration.x(), animatedX);

        float animatedY = 0;
        animateAdditiveNumber(percentage, repeatCount, m_fromPoint.y(), m_toPoint.y(), toPointAtEndOfDuration.y(), animatedY);

        transform->translate(animatedX, animatedY);
        return;
    }

    ASSERT(!m_animationPath.isEmpty());

    float positionOnPath = m_animationPath.length() * percentage;
    FloatPoint position;
    float angle;
    m_animationPath.pointAndNormalAtLength(positionOnPath, position, angle);

    // Handle accumulate="sum".
    if (isAccumulated() && repeatCount) {
        FloatPoint positionAtEndOfDuration = m_animationPath.pointAtLength(m_animationPath.length());
        position.move(positionAtEndOfDuration.x() * repeatCount, positionAtEndOfDuration.y() * repeatCount);
    }

    transform->translate(position.x(), position.y());
    RotateMode rotateMode = this->getRotateMode();
    if (rotateMode != RotateAuto && rotateMode != RotateAutoReverse)
        return;
    if (rotateMode == RotateAutoReverse)
        angle += 180;
    transform->rotate(angle);
}

void SVGAnimateMotionElement::applyResultsToTarget()
{
    // We accumulate to the target element transform list so there is not much to do here.
    SVGElement* targetElement = this->targetElement();
    if (!targetElement)
        return;

    if (LayoutObject* layoutObject = targetElement->layoutObject())
        markForLayoutAndParentResourceInvalidation(layoutObject);

    AffineTransform* t = targetElement->animateMotionTransform();
    if (!t)
        return;

    // ...except in case where we have additional instances in <use> trees.
    const WillBeHeapHashSet<RawPtrWillBeWeakMember<SVGElement>>& instances = targetElement->instancesForElement();
    for (SVGElement* shadowTreeElement : instances) {
        ASSERT(shadowTreeElement);
        AffineTransform* transform = shadowTreeElement->animateMotionTransform();
        if (!transform)
            continue;
        transform->setMatrix(t->a(), t->b(), t->c(), t->d(), t->e(), t->f());
        if (LayoutObject* layoutObject = shadowTreeElement->layoutObject()) {
            layoutObject->setNeedsTransformUpdate();
            markForLayoutAndParentResourceInvalidation(layoutObject);
        }
    }
}

float SVGAnimateMotionElement::calculateDistance(const String& fromString, const String& toString)
{
    FloatPoint from;
    FloatPoint to;
    if (!parsePoint(fromString, from))
        return -1;
    if (!parsePoint(toString, to))
        return -1;
    FloatSize diff = to - from;
    return sqrtf(diff.width() * diff.width() + diff.height() * diff.height());
}

void SVGAnimateMotionElement::updateAnimationMode()
{
    if (!m_animationPath.isEmpty())
        setAnimationMode(PathAnimation);
    else
        SVGAnimationElement::updateAnimationMode();
}

} // namespace blink


text:
export interface IEquals {
    equals(other: any): boolean;
}

export class Equals {
    equals(other: any) {
        return other == null ? false : this.constructor === other.constructor;
    }
}


text:
package kafka.server

import kafka.api.KAFKA_0_10_2_IV0
import kafka.log.LogConfig
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.protocol.Errors
import org.apache.kafka.common.requests.{FetchRequest, FetchResponse}
import org.junit.jupiter.api.Assertions.{assertEquals, assertTrue}
import org.junit.jupiter.api.Test

import java.util.Properties

import scala.annotation.nowarn
import scala.collection.Seq
import scala.jdk.CollectionConverters._

class FetchRequestWithLegacyMessageFormatTest extends BaseFetchRequestTest {

  override def brokerPropertyOverrides(properties: Properties): Unit = {
    super.brokerPropertyOverrides(properties)
    // legacy message formats are only supported with IBP < 3.0
    properties.put(KafkaConfig.InterBrokerProtocolVersionProp, "2.8")
  }

  /**
   * Fetch request v2 (pre KIP-74) respected `maxPartitionBytes` even if no message could be returned
   * due to a message that was larger than `maxPartitionBytes`.
   */
  @nowarn("cat=deprecation")
  @Test
  def testFetchRequestV2WithOversizedMessage(): Unit = {
    initProducer()
    val maxPartitionBytes = 200
    // Fetch v2 down-converts if the message format is >= 0.11 and we want to avoid
    // that as it affects the size of the returned buffer
    val topicConfig = Map(LogConfig.MessageFormatVersionProp -> KAFKA_0_10_2_IV0.version)
    val (topicPartition, leaderId) = createTopics(numTopics = 1, numPartitions = 1, topicConfig).head
    val topicIds = getTopicIds().asJava
    val topicNames = topicIds.asScala.map(_.swap).asJava
    producer.send(new ProducerRecord(topicPartition.topic, topicPartition.partition,
      "key", new String(new Array[Byte](maxPartitionBytes + 1)))).get
    val fetchVersion: Short = 2
    val fetchRequest = FetchRequest.Builder.forConsumer(fetchVersion, Int.MaxValue, 0,
      createPartitionMap(maxPartitionBytes, Seq(topicPartition))).build(fetchVersion)
    val fetchResponse = sendFetchRequest(leaderId, fetchRequest)
    val partitionData = fetchResponse.responseData(topicNames, fetchVersion).get(topicPartition)
    assertEquals(Errors.NONE.code, partitionData.errorCode)

    assertTrue(partitionData.highWatermark > 0)
    assertEquals(maxPartitionBytes, FetchResponse.recordsSize(partitionData))
    assertEquals(0, records(partitionData).map(_.sizeInBytes).sum)
  }

}


text:
{% extends "_layout" %}
{% set title = entry.title %}

{% block pagestyles %}
{% endblock %}

  {% block content %}

  {% set image = entry.heroImage.first() %}
  {% if image %}

{{ entry.title }}

{{ entry.ert }} min read

          {% if entry.author.photoUrl %}

          {% endif %}
          by: {{ entry.author }} {{ entry.postDate.format('M jS, Y') }}

    {% else %}

{{ entry.title }}

{{ entry.ert }} min read

          {% if entry.author.photoUrl %}

          {% endif %}
          by: {{ entry.author }} {{ entry.postDate.format('M jS, Y') }}

  {% endif %}

        blog list

        {% for block in entry.blogLayout %}

        {% if block.type == "mainTitle" %}

            {{ block.mainTitle }}

        {% elseif block.type == "secondaryTitle" %}

            {{ block.secondaryTitle }}

        {% elseif block.type == "textBlock" %}
          {{ block.textBlock }}

        {% elseif block.type == "photoBlock" %}
          {% set image = block.image.first() %}
          {% if image %}

              {{ block.caption }}

          {% endif %}

          {% elseif block.type == "quoteBlock" %}

              {{ block.quote }}
              - {{ block.cite }}

          {% endif %}

        {% endfor %}

Related Articles

    {% for tag in craft.tags.slug(q).limit(2) %}
      {% set blogEntries = craft.entries.section('blog').relatedTo(tag).sort('postDate').limit(1) %}

      {% for entry in blogEntries %}

          {% set image = entry.thumbnail.first() %}
            {% if image %}

            {% else %}

            {% set image = entry.heroImage.first() %}
            {% if image %}

            {% endif%}
          {% endif %}

{{ entry.title }}

{{ entry.postDate.format('F d, Y') }}

          Read More

        {% endfor %}

      {% endfor %}

{% endblock %}

{% block pagescripts %}
{% endblock %}


text:
package org.petuum.jbosen.server;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class NameNode {

    private static NameNodeThread nameNodeThread;

    public static void init() {
        CyclicBarrier initBarrier = new CyclicBarrier(2);
        nameNodeThread = new NameNodeThread(initBarrier);
        nameNodeThread.start();
        try {
            initBarrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            e.printStackTrace();
        }
    }

    public static void shutdown() {
        nameNodeThread.shutdown();
    }

}


text:
// Adds any extra JS functions/helpers we want to the PathKit Library.
// Wrapped in a function to avoid leaking global variables.
(function(PathKit){

  // Caching the Float32Arrays can save having to reallocate them
  // over and over again.
  var Float32ArrayCache = {};

  // Takes a 2D array of commands and puts them into the WASM heap
  // as a 1D array. This allows them to referenced from the C++ code.
  // Returns a 2 element array, with the first item being essentially a
  // pointer to the array and the second item being the length of
  // the new 1D array.
  //
  // Example usage:
  // let cmds = [
  //   [PathKit.MOVE_VERB, 0, 10],
  //   [PathKit.LINE_VERB, 30, 40],
  //   [PathKit.QUAD_VERB, 20, 50, 45, 60],
  // ];
  //
  // // The following uses ES6 syntactic sugar "Array Destructuring".
  // // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring
  // let [ptr, len] = PathKit.loadCmdsTypedArray(cmds);
  // let path = PathKit.FromCmds(ptr, len);
  //
  // If arguments at index 1... in each cmd row are strings, they will be
  // parsed as hex, and then converted to floats using SkBits2FloatUnsigned
  PathKit.loadCmdsTypedArray = function(arr) {
    var len = 0;
    for (var r = 0; r < arr.length; r++) {
      len += arr[r].length;
    }

    var ta;
    if (Float32ArrayCache[len]) {
      ta = Float32ArrayCache[len];
    } else {
      ta = new Float32Array(len);
      Float32ArrayCache[len] = ta;
    }
    // Flatten into a 1d array
    var i = 0;
    for (var r = 0; r < arr.length; r++) {
      for (var c = 0; c < arr[r].length; c++) {
        var item = arr[r][c];
        if (typeof item === 'string') {
          // Converts hex to an int, which can be passed to SkBits2FloatUnsigned
          item = PathKit.SkBits2FloatUnsigned(parseInt(item));
        }
        ta[i] = item;
        i++;
      }
    }

    var ptr = PathKit._malloc(ta.length * ta.BYTES_PER_ELEMENT);
    PathKit.HEAPF32.set(ta, ptr / ta.BYTES_PER_ELEMENT);
    return [ptr, len];
  }

  // Experimentation has shown that using TypedArrays to pass arrays from
  // JS to C++ is faster than passing the JS Arrays across.
  // See above for example of cmds.
  PathKit.FromCmds = function(cmds) {
    var ptrLen = PathKit.loadCmdsTypedArray(cmds);
    var path = PathKit._FromCmds(ptrLen[0], ptrLen[1]);
    // TODO(kjlubick): cache this memory blob somehow.
    PathKit._free(ptrLen[0]);
    return path;
  }

  /**
   * A common pattern is to call this function in sequence with the same
   * params. We can just remember the last one to speed things up.
   * Caching in this way is about a 10-15x speed up.
   * See externs.js for this definition
   * @type {CubicMap}
   */
  var cachedMap;
  var _cpx1, _cpy1, _cpx2, _cpy2;

  PathKit.cubicYFromX = function(cpx1, cpy1, cpx2, cpy2, X) {
    if (!cachedMap || _cpx1 !== cpx1 || _cpy1 !== cpy1 ||
       _cpx2 !== cpx2 || _cpy2 !== cpy2) {
      if (cachedMap) {
        // Delete previous cached map to avoid memory leaks.
        cachedMap.delete()
      }
      cachedMap = new PathKit._SkCubicMap([cpx1, cpy1], [cpx2, cpy2]);
      _cpx1 = cpx1, _cpy1 = cpy1, _cpx2 = cpx2, _cpy2 = cpy2;
    }
    return cachedMap.computeYFromX(X);
  }

  PathKit.cubicPtFromT = function(cpx1, cpy1, cpx2, cpy2, T) {
    if (!cachedMap || _cpx1 !== cpx1 || _cpy1 !== cpy1 ||
       _cpx2 !== cpx2 || _cpy2 !== cpy2) {
      if (cachedMap) {
        // Delete previous cached map to avoid memory leaks.
        cachedMap.delete()
      }
      cachedMap = new PathKit._SkCubicMap([cpx1, cpy1], [cpx2, cpy2]);
      _cpx1 = cpx1, _cpy1 = cpy1, _cpx2 = cpx2, _cpy2 = cpy2;
    }
    return cachedMap.computePtFromT(T);
  }
}(Module)); // When this file is loaded in, the high level object is "Module";


text:
(function (factory) {
  if (typeof module === 'object' && module.exports) {
    // Node/CommonJS
    module.exports = function( root, jQuery ) {
      if ( jQuery === undefined ) {
        // require('jQuery') returns a factory that requires window to
        // build a jQuery instance, we normalize how we use modules
        // that require this pattern but the window provided is a noop
        // if it's defined (how jquery works)
        if ( typeof window !== 'undefined' ) {
          jQuery = require('./jquery.js');
        }
        else {
          jQuery = require('./jquery.js')(root);
        }
      }
      factory(jQuery);
      return jQuery;
    };
  } if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['./jquery.js'], factory);
  } else {
    // Browser globals
    factory(jQuery);
  }
})(function ($) {
    /* like button */
    // keep "like" button on the same line as "share on"
    var previousDistance_dsShare_dsThread = "0px", class_dsMeta_previousWidth = 0;
    var dsElementsReady = false;
    var $pseudoDsMeta = null, $dsShare = null, $dsThread = null, $dsMeta = null;
    $(document).ready(function() {
      $pseudoDsMeta = $('.pseudo-ds-meta');
      $dsShare = $('.ds-share'),
      $dsThread = $('.ds-thread');
      $dsMeta = $('.ds-meta');
      modifyShareOn();
    });
    $('body').on('resize', function() {
      // raise "like" button
      var currentDistance_dsShare_dsThread = $dsShare[0].offsetTop - $dsThread[0].offsetTop - 5 + "px";
      if (previousDistance_dsShare_dsThread != currentDistance_dsShare_dsThread) {
        previousDistance_dsShare_dsThread = $dsMeta[0].style.top = currentDistance_dsShare_dsThread;
      }

      // change the offset of "share on" as the width of "like" button changes
      var class_dsMeta_currentWidth = class_dsMeta[0].clientWidth;
      if (class_dsMeta_previousWidth != class_dsMeta_currentWidth) {
        $pseudoDsMeta[0].style.width = (class_dsMeta_currentWidth > 0) ? (class_dsMeta_currentWidth + 20 + "px") : "0";
        class_dsMeta_previousWidth = class_dsMeta_currentWidth;
      }
    });

    /* share on */
    function modifyShareOn() {
      // fix "undefined" problem
      $('ul.ds-share-icons-16').on('mouseover', function() {
        $('.ds-douban').text('Douban')
        $('.ds-youdao').text('Youdao CloudNote');
        $('ul.ds-share-icons-16').off('mouseover');
      });
    }

    /* back to top button */
    var $backToTop = $('#backtotop');
    $backToTop.on('click', function () {
        var documentBody = document.body;
        var distanceFromTop = documentBody.scrollTop;
        var time = distanceFromTop / 30;
        if (time > 1500) time = 1500;
        else if (time < 200) time = 200;
        $('body').animate({
          scrollTop: 0
        }, time, 'swing');
        // window.requestAnimationFrame((function() {
        //   var calculatedScrollTop = parseInt(documentBody.scrollTop) - pace;
        //   documentBody.scrollTop = ((calculatedScrollTop < 0) ? 0 : calculatedScrollTop);
        //   if (parseInt(documentBody.scrollTop) > 0) window.requestAnimationFrame(arguments.callee);
        // }));
      // }, false);
    });

    /* gif view again */
    $('.view-again').on('click', function() {
      var img = this.parentNode.nextElementSibling.firstChild;
      var imgSrc = img.src;
      img.src = "https://www.baidu.com/img/bd_logo1.png";
      img.src = imgSrc;
    });
});


text:
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
@import GoogleMaps;
@interface LocationGenerator : NSObject
+ (NSArray<GMSMarker *> *) generateMarkersNear:(CLLocationCoordinate2D)location count:(int)count;
@end


text:
class AddDisconnectedToUsers < ActiveRecord::Migration
  def change
    add_column :users, :disconnected, :boolean, default: false
  end
end


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
// ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable UnusedMember.Global

namespace Sumo.Nop.MediaTools.Models {
    [Table("Setting")]
    public partial class Setting {
        [Key]
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Value { get; set; }

        [Required]
        public int StoreId { get; set; }
    }
}